Added fastlane scripts, old ids cleaned up
This commit is contained in:
parent
39e348948c
commit
56754d616b
34 changed files with 1361 additions and 153 deletions
65
client/platforms/ios/Shadowsocks.h
Normal file
65
client/platforms/ios/Shadowsocks.h
Normal file
|
@ -0,0 +1,65 @@
|
|||
// Copyright 2018 The Outline Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef Shadowsocks_h
|
||||
#define Shadowsocks_h
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
/**
|
||||
* Manages the lifecycle and configuration of ss-local, the Shadowsocks client library.
|
||||
*/
|
||||
@interface Shadowsocks : NSObject
|
||||
|
||||
extern const int kShadowsocksLocalPort;
|
||||
|
||||
typedef NS_ENUM(NSInteger, ErrorCode) {
|
||||
noError = 0,
|
||||
undefinedError = 1,
|
||||
vpnPermissionNotGranted = 2,
|
||||
invalidServerCredentials = 3,
|
||||
udpRelayNotEnabled = 4,
|
||||
serverUnreachable = 5,
|
||||
vpnStartFailure = 6,
|
||||
illegalServerConfiguration = 7,
|
||||
shadowsocksStartFailure = 8,
|
||||
configureSystemProxyFailure = 9,
|
||||
noAdminPermissions = 10,
|
||||
unsupportedRoutingTable = 11,
|
||||
systemMisconfigured = 12
|
||||
};
|
||||
|
||||
@property (nonatomic) NSDictionary *config;
|
||||
|
||||
/**
|
||||
* Initializes the object with a Shadowsocks server configuration, |config|.
|
||||
*/
|
||||
- (id)init:(NSDictionary *)config;
|
||||
|
||||
/**
|
||||
* Starts ss-local on a separate thread with the configuration supplied in the constructor.
|
||||
* If |checkConnectivity| is true, verifies that the server credentials are valid and that
|
||||
* the remote supports UDP forwarding, calling |completion| with the result.
|
||||
*/
|
||||
- (void)startWithConnectivityChecks:(bool)checkConnectivity
|
||||
completion:(void (^)(ErrorCode))completion;
|
||||
|
||||
/**
|
||||
* Stops the thread running ss-local. Calls |completion| with the success of the operation.
|
||||
*/
|
||||
- (void)stop:(void (^)(ErrorCode))completion;
|
||||
|
||||
@end
|
||||
|
||||
#endif /* Shadowsocks_h */
|
202
client/platforms/ios/Shadowsocks.m
Normal file
202
client/platforms/ios/Shadowsocks.m
Normal file
|
@ -0,0 +1,202 @@
|
|||
// Copyright 2018 The Outline Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#import "Shadowsocks.h"
|
||||
#include <limits.h>
|
||||
#include <pthread.h>
|
||||
#import "ShadowsocksConnectivity.h"
|
||||
#import <Shadowsocks/shadowsocks.h>
|
||||
|
||||
const int kShadowsocksLocalPort = 9999;
|
||||
static const int kShadowsocksTimeoutSecs = INT_MAX;
|
||||
static const int kShadowsocksTcpAndUdpMode =
|
||||
1; // See https://github.com/shadowsocks/shadowsocks-libev/blob/4ea517/src/jconf.h#L44
|
||||
static char *const kShadowsocksLocalAddress = "127.0.0.1";
|
||||
|
||||
@interface Shadowsocks ()
|
||||
@property (nonatomic) pthread_t ssLocalThreadId;
|
||||
@property (nonatomic, copy) void (^startCompletion)(ErrorCode);
|
||||
@property (nonatomic, copy) void (^stopCompletion)(ErrorCode);
|
||||
@property (nonatomic) dispatch_queue_t dispatchQueue;
|
||||
@property (nonatomic) dispatch_group_t dispatchGroup;
|
||||
@property(nonatomic) bool checkConnectivity;
|
||||
@property(nonatomic) ShadowsocksConnectivity *ssConnectivity;
|
||||
@end
|
||||
|
||||
@implementation Shadowsocks
|
||||
|
||||
- (id) init:(NSDictionary *)config {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_config = config;
|
||||
_dispatchQueue = dispatch_queue_create("Shadowsocks", DISPATCH_QUEUE_SERIAL);
|
||||
_dispatchGroup = dispatch_group_create();
|
||||
_ssConnectivity = [[ShadowsocksConnectivity alloc] initWithPort:kShadowsocksLocalPort];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)startWithConnectivityChecks:(bool)checkConnectivity
|
||||
completion:(void (^)(ErrorCode))completion {
|
||||
if (self.ssLocalThreadId != 0) {
|
||||
return completion(shadowsocksStartFailure);
|
||||
}
|
||||
self.checkConnectivity = checkConnectivity;
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
// Start ss-local from the main application thread.
|
||||
self.startCompletion = completion;
|
||||
[self startShadowsocksThread];
|
||||
});
|
||||
}
|
||||
|
||||
-(void)stop:(void (^)(ErrorCode))completion {
|
||||
if (self.ssLocalThreadId == 0) {
|
||||
return;
|
||||
}
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
// The ev_loop in the ss-local thread will not break unless it is signaled to stop from the main
|
||||
// application thread.
|
||||
self.stopCompletion = completion;
|
||||
pthread_kill(self.ssLocalThreadId, SIGUSR1);
|
||||
self.ssLocalThreadId = 0;
|
||||
});
|
||||
}
|
||||
|
||||
#pragma mark - Lifecycle
|
||||
|
||||
void shadowsocksCallback(int socks_fd, int udp_fd, void *udata) {
|
||||
if (socks_fd <= 0 || udp_fd <= 0) {
|
||||
return;
|
||||
}
|
||||
Shadowsocks* ss = (__bridge Shadowsocks *)udata;
|
||||
[ss checkServerConnectivity];
|
||||
}
|
||||
|
||||
- (void)startShadowsocks {
|
||||
if (self.config == nil) {
|
||||
self.startCompletion(illegalServerConfiguration);
|
||||
return;
|
||||
}
|
||||
int port = [self.config[@"port"] intValue];
|
||||
char *host = (char *)[self.config[@"host"] UTF8String];
|
||||
char *password = (char *)[self.config[@"password"] UTF8String];
|
||||
char *method = (char *)[self.config[@"method"] UTF8String];
|
||||
const profile_t profile = {.remote_host = host,
|
||||
.local_addr = kShadowsocksLocalAddress,
|
||||
.method = method,
|
||||
.password = password,
|
||||
.remote_port = port,
|
||||
.local_port = kShadowsocksLocalPort,
|
||||
.timeout = kShadowsocksTimeoutSecs,
|
||||
.acl = NULL,
|
||||
.log = NULL,
|
||||
.fast_open = 0,
|
||||
.mode = kShadowsocksTcpAndUdpMode,
|
||||
.verbose = 0};
|
||||
int success = start_ss_local_server_with_callback(profile, shadowsocksCallback,
|
||||
(__bridge void *)self);
|
||||
if (success < 0) {
|
||||
self.startCompletion(shadowsocksStartFailure);
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.stopCompletion) {
|
||||
self.stopCompletion(noError);
|
||||
self.stopCompletion = nil;
|
||||
}
|
||||
}
|
||||
|
||||
// Entry point for the Shadowsocks POSIX thread.
|
||||
void *startShadowsocks(void *udata) {
|
||||
Shadowsocks* ss = (__bridge Shadowsocks *)udata;
|
||||
[ss startShadowsocks];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Starts a POSIX thread that runs ss-local.
|
||||
- (void)startShadowsocksThread {
|
||||
pthread_attr_t attr;
|
||||
int err = pthread_attr_init(&attr);
|
||||
if (err) {
|
||||
self.startCompletion(shadowsocksStartFailure);
|
||||
return;
|
||||
}
|
||||
err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
|
||||
if (err) {
|
||||
self.startCompletion(shadowsocksStartFailure);
|
||||
return;
|
||||
}
|
||||
err = pthread_create(&_ssLocalThreadId, &attr, &startShadowsocks, (__bridge void *)self);
|
||||
if (err) {
|
||||
self.startCompletion(shadowsocksStartFailure);
|
||||
}
|
||||
err = pthread_attr_destroy(&attr);
|
||||
if (err) {
|
||||
self.startCompletion(shadowsocksStartFailure);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - Connectivity
|
||||
|
||||
/**
|
||||
* Checks that the remote server is reachable, allows UDP forwarding, and the credentials are valid.
|
||||
* Synchronizes and parallelizes the execution of the connectivity checks and calls
|
||||
* |startCompletion| with the combined outcome.
|
||||
* Only performs the tests if |checkConnectivity| is true; otherwise calls |startCompletion|
|
||||
* with success.
|
||||
*/
|
||||
- (void) checkServerConnectivity {
|
||||
if (!self.checkConnectivity) {
|
||||
self.startCompletion(noError);
|
||||
return;
|
||||
}
|
||||
__block BOOL isRemoteUdpForwardingEnabled = false;
|
||||
__block BOOL serverCredentialsAreValid = false;
|
||||
__block BOOL isServerReachable = false;
|
||||
|
||||
// Enter the group once for each check
|
||||
dispatch_group_enter(self.dispatchGroup);
|
||||
dispatch_group_enter(self.dispatchGroup);
|
||||
dispatch_group_enter(self.dispatchGroup);
|
||||
|
||||
[self.ssConnectivity isUdpForwardingEnabled:^(BOOL enabled) {
|
||||
isRemoteUdpForwardingEnabled = enabled;
|
||||
dispatch_group_leave(self.dispatchGroup);
|
||||
}];
|
||||
[self.ssConnectivity isReachable:self.config[@"host"]
|
||||
port:[self.config[@"port"] intValue]
|
||||
completion:^(BOOL isReachable) {
|
||||
isServerReachable = isReachable;
|
||||
dispatch_group_leave(self.dispatchGroup);
|
||||
}];
|
||||
[self.ssConnectivity checkServerCredentials:^(BOOL valid) {
|
||||
serverCredentialsAreValid = valid;
|
||||
dispatch_group_leave(self.dispatchGroup);
|
||||
}];
|
||||
|
||||
dispatch_group_notify(self.dispatchGroup, self.dispatchQueue, ^{
|
||||
if (isRemoteUdpForwardingEnabled) {
|
||||
self.startCompletion(noError);
|
||||
} else if (serverCredentialsAreValid) {
|
||||
self.startCompletion(udpRelayNotEnabled);
|
||||
} else if (isServerReachable) {
|
||||
self.startCompletion(invalidServerCredentials);
|
||||
} else {
|
||||
self.startCompletion(serverUnreachable);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@end
|
50
client/platforms/ios/ShadowsocksConnectivity.h
Normal file
50
client/platforms/ios/ShadowsocksConnectivity.h
Normal file
|
@ -0,0 +1,50 @@
|
|||
// Copyright 2018 The Outline Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef ShadowsocksConnectivity_h
|
||||
#define ShadowsocksConnectivity_h
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
/**
|
||||
* Non-thread-safe class to perform Shadowsocks connectivity checks.
|
||||
*/
|
||||
@interface ShadowsocksConnectivity : NSObject
|
||||
|
||||
/**
|
||||
* Initializes the object with a local Shadowsocks port, |shadowsocksPort|.
|
||||
*/
|
||||
- (id)initWithPort:(uint16_t)shadowsocksPort;
|
||||
|
||||
/**
|
||||
* Verifies that the server has enabled UDP forwarding. Performs an end-to-end test by sending
|
||||
* a DNS request through the proxy. This method is a superset of |checkServerCredentials|, as its
|
||||
* success implies that the server credentials are valid.
|
||||
*/
|
||||
- (void)isUdpForwardingEnabled:(void (^)(BOOL))completion;
|
||||
|
||||
/**
|
||||
* Verifies that the server credentials are valid. Performs an end-to-end authentication test
|
||||
* by issuing an HTTP HEAD request to a target domain through the proxy.
|
||||
*/
|
||||
- (void)checkServerCredentials:(void (^)(BOOL))completion;
|
||||
|
||||
/**
|
||||
* Checks that the server is reachable on |host| and |port|.
|
||||
*/
|
||||
- (void)isReachable:(NSString *)host port:(uint16_t)port completion:(void (^)(BOOL))completion;
|
||||
|
||||
@end
|
||||
|
||||
#endif /* ShadowsocksConnectivity_h */
|
333
client/platforms/ios/ShadowsocksConnectivity.m
Normal file
333
client/platforms/ios/ShadowsocksConnectivity.m
Normal file
|
@ -0,0 +1,333 @@
|
|||
// Copyright 2018 The Outline Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#import "ShadowsocksConnectivity.h"
|
||||
#include <arpa/inet.h>
|
||||
#import <ShadowSocks/shadowsocks.h>
|
||||
#import <CocoaAsyncSocket/CocoaAsyncSocket.h>
|
||||
|
||||
//@import CocoaAsyncSocket;
|
||||
|
||||
static char *const kShadowsocksLocalAddress = "127.0.0.1";
|
||||
|
||||
static char *const kDnsResolverAddress = "208.67.222.222"; // OpenDNS
|
||||
static const uint16_t kDnsResolverPort = 53;
|
||||
static const size_t kDnsRequestNumBytes = 28;
|
||||
|
||||
static const size_t kSocksHeaderNumBytes = 10;
|
||||
static const uint8_t kSocksMethodsResponseNumBytes = 2;
|
||||
static const size_t kSocksConnectResponseNumBytes = 10;
|
||||
static const uint8_t kSocksVersion = 0x5;
|
||||
static const uint8_t kSocksMethodNoAuth = 0x0;
|
||||
static const uint8_t kSocksCmdConnect = 0x1;
|
||||
static const uint8_t kSocksAtypIpv4 = 0x1;
|
||||
static const uint8_t kSocksAtypDomainname = 0x3;
|
||||
|
||||
static const NSTimeInterval kTcpSocketTimeoutSecs = 10.0;
|
||||
static const NSTimeInterval kUdpSocketTimeoutSecs = 1.0;
|
||||
static const long kSocketTagHttpRequest = 100;
|
||||
static const int kUdpForwardingMaxChecks = 5;
|
||||
static const uint16_t kHttpPort = 80;
|
||||
|
||||
@interface ShadowsocksConnectivity ()<GCDAsyncSocketDelegate, GCDAsyncUdpSocketDelegate>
|
||||
|
||||
@property(nonatomic) uint16_t shadowsocksPort;
|
||||
|
||||
@property(nonatomic, copy) void (^udpForwardingCompletion)(BOOL);
|
||||
@property(nonatomic, copy) void (^reachabilityCompletion)(BOOL);
|
||||
@property(nonatomic, copy) void (^credentialsCompletion)(BOOL);
|
||||
|
||||
@property(nonatomic) dispatch_queue_t dispatchQueue;
|
||||
@property(nonatomic) GCDAsyncUdpSocket *udpSocket;
|
||||
@property(nonatomic) GCDAsyncSocket *credentialsSocket;
|
||||
@property(nonatomic) GCDAsyncSocket *reachabilitySocket;
|
||||
|
||||
@property(nonatomic) bool isRemoteUdpForwardingEnabled;
|
||||
@property(nonatomic) bool areServerCredentialsValid;
|
||||
@property(nonatomic) bool isServerReachable;
|
||||
@property(nonatomic) int udpForwardingNumChecks;
|
||||
@end
|
||||
|
||||
@implementation ShadowsocksConnectivity
|
||||
|
||||
- (id)initWithPort:(uint16_t)shadowsocksPort {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_shadowsocksPort = shadowsocksPort;
|
||||
_dispatchQueue = dispatch_queue_create("ShadowsocksConnectivity", DISPATCH_QUEUE_SERIAL);
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark - UDP Forwarding
|
||||
|
||||
struct socks_udp_header {
|
||||
uint16_t rsv;
|
||||
uint8_t frag;
|
||||
uint8_t atyp;
|
||||
uint32_t addr;
|
||||
uint16_t port;
|
||||
};
|
||||
|
||||
- (void)isUdpForwardingEnabled:(void (^)(BOOL))completion {
|
||||
self.isRemoteUdpForwardingEnabled = false;
|
||||
self.udpForwardingNumChecks = 0;
|
||||
self.udpForwardingCompletion = completion;
|
||||
self.udpSocket =
|
||||
[[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:self.dispatchQueue];
|
||||
struct in_addr dnsResolverAddress;
|
||||
if (!inet_aton(kDnsResolverAddress, &dnsResolverAddress)) {
|
||||
[self udpForwardingCheckDone:false];
|
||||
return;
|
||||
}
|
||||
struct socks_udp_header socksHeader = {
|
||||
.atyp = kSocksAtypIpv4,
|
||||
.addr = dnsResolverAddress.s_addr, // Already in network order
|
||||
.port = htons(kDnsResolverPort)};
|
||||
uint8_t *dnsRequest = [self getDnsRequest];
|
||||
size_t packetNumBytes = kSocksHeaderNumBytes + kDnsRequestNumBytes;
|
||||
uint8_t socksPacket[packetNumBytes];
|
||||
memset(socksPacket, 0, packetNumBytes);
|
||||
memcpy(socksPacket, &socksHeader, kSocksHeaderNumBytes);
|
||||
memcpy(socksPacket + kSocksHeaderNumBytes, dnsRequest, kDnsRequestNumBytes);
|
||||
|
||||
NSData *packetData = [[NSData alloc] initWithBytes:socksPacket length:packetNumBytes];
|
||||
|
||||
dispatch_source_t timer =
|
||||
dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.dispatchQueue);
|
||||
if (!timer) {
|
||||
[self udpForwardingCheckDone:false];
|
||||
return;
|
||||
}
|
||||
dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, 0),
|
||||
kUdpSocketTimeoutSecs * NSEC_PER_SEC, 0);
|
||||
__weak ShadowsocksConnectivity *weakSelf = self;
|
||||
dispatch_source_set_event_handler(timer, ^{
|
||||
if (++weakSelf.udpForwardingNumChecks > kUdpForwardingMaxChecks ||
|
||||
weakSelf.isRemoteUdpForwardingEnabled) {
|
||||
dispatch_source_cancel(timer);
|
||||
if (!weakSelf.isRemoteUdpForwardingEnabled) {
|
||||
[weakSelf udpForwardingCheckDone:false];
|
||||
}
|
||||
[weakSelf.udpSocket close];
|
||||
return;
|
||||
}
|
||||
[weakSelf.udpSocket sendData:packetData
|
||||
toHost:[[NSString alloc] initWithUTF8String:kShadowsocksLocalAddress]
|
||||
port:self.shadowsocksPort
|
||||
withTimeout:kUdpSocketTimeoutSecs
|
||||
tag:0];
|
||||
if (![weakSelf.udpSocket receiveOnce:nil]) {
|
||||
}
|
||||
});
|
||||
dispatch_resume(timer);
|
||||
}
|
||||
|
||||
// Returns a byte representation of a DNS request for "google.com".
|
||||
- (uint8_t *)getDnsRequest {
|
||||
static uint8_t kDnsRequest[] = {
|
||||
0, 0, // [0-1] query ID
|
||||
1, 0, // [2-3] flags; byte[2] = 1 for recursion desired (RD).
|
||||
0, 1, // [4-5] QDCOUNT (number of queries)
|
||||
0, 0, // [6-7] ANCOUNT (number of answers)
|
||||
0, 0, // [8-9] NSCOUNT (number of name server records)
|
||||
0, 0, // [10-11] ARCOUNT (number of additional records)
|
||||
6, 'g', 'o', 'o', 'g', 'l', 'e', 3, 'c', 'o', 'm',
|
||||
0, // null terminator of FQDN (root TLD)
|
||||
0, 1, // QTYPE, set to A
|
||||
0, 1 // QCLASS, set to 1 = IN (Internet)
|
||||
};
|
||||
return kDnsRequest;
|
||||
}
|
||||
|
||||
#pragma mark - GCDAsyncUdpSocketDelegate
|
||||
|
||||
- (void)udpSocket:(GCDAsyncUdpSocket *)sock
|
||||
didNotSendDataWithTag:(long)tag
|
||||
dueToError:(NSError *)error {
|
||||
}
|
||||
|
||||
- (void)udpSocket:(GCDAsyncUdpSocket *)sock
|
||||
didReceiveData:(NSData *)data
|
||||
fromAddress:(NSData *)address
|
||||
withFilterContext:(id)filterContext {
|
||||
if (!self.isRemoteUdpForwardingEnabled) {
|
||||
// Only report success if it hasn't been done so already.
|
||||
[self udpForwardingCheckDone:true];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)udpForwardingCheckDone:(BOOL)enabled {
|
||||
self.isRemoteUdpForwardingEnabled = enabled;
|
||||
if (self.udpForwardingCompletion != NULL) {
|
||||
self.udpForwardingCompletion(self.isRemoteUdpForwardingEnabled);
|
||||
self.udpForwardingCompletion = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - Credentials
|
||||
|
||||
struct socks_methods_request {
|
||||
uint8_t ver;
|
||||
uint8_t nmethods;
|
||||
uint8_t method;
|
||||
};
|
||||
|
||||
struct socks_request_header {
|
||||
uint8_t ver;
|
||||
uint8_t cmd;
|
||||
uint8_t rsv;
|
||||
uint8_t atyp;
|
||||
};
|
||||
|
||||
- (void)checkServerCredentials:(void (^)(BOOL))completion {
|
||||
self.areServerCredentialsValid = false;
|
||||
self.credentialsCompletion = completion;
|
||||
self.credentialsSocket =
|
||||
[[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:self.dispatchQueue];
|
||||
NSError *error;
|
||||
[self.credentialsSocket
|
||||
connectToHost:[[NSString alloc] initWithUTF8String:kShadowsocksLocalAddress]
|
||||
onPort:self.shadowsocksPort
|
||||
withTimeout:kTcpSocketTimeoutSecs
|
||||
error:&error];
|
||||
if (error) {
|
||||
[self serverCredentialsCheckDone];
|
||||
return;
|
||||
}
|
||||
|
||||
struct socks_methods_request methodsRequest = {
|
||||
.ver = kSocksVersion, .nmethods = 0x1, .method = kSocksMethodNoAuth};
|
||||
NSData *methodsRequestData =
|
||||
[[NSData alloc] initWithBytes:&methodsRequest length:sizeof(struct socks_methods_request)];
|
||||
[self.credentialsSocket writeData:methodsRequestData withTimeout:kTcpSocketTimeoutSecs tag:0];
|
||||
[self.credentialsSocket readDataToLength:kSocksMethodsResponseNumBytes
|
||||
withTimeout:kTcpSocketTimeoutSecs
|
||||
tag:0];
|
||||
|
||||
size_t socksRequestHeaderNumBytes = sizeof(struct socks_request_header);
|
||||
NSString *domain = [self chooseRandomDomain];
|
||||
uint8_t domainNameNumBytes = domain.length;
|
||||
size_t socksRequestNumBytes = socksRequestHeaderNumBytes + domainNameNumBytes +
|
||||
sizeof(uint16_t) /* port */ +
|
||||
sizeof(uint8_t) /* domain name length */;
|
||||
|
||||
struct socks_request_header socksRequestHeader = {
|
||||
.ver = kSocksVersion, .cmd = kSocksCmdConnect, .atyp = kSocksAtypDomainname};
|
||||
uint8_t socksRequest[socksRequestNumBytes];
|
||||
memset(socksRequest, 0x0, socksRequestNumBytes);
|
||||
memcpy(socksRequest, &socksRequestHeader, socksRequestHeaderNumBytes);
|
||||
socksRequest[socksRequestHeaderNumBytes] = domainNameNumBytes;
|
||||
memcpy(socksRequest + socksRequestHeaderNumBytes + sizeof(uint8_t), [domain UTF8String],
|
||||
domainNameNumBytes);
|
||||
uint16_t httpPort = htons(kHttpPort);
|
||||
memcpy(socksRequest + socksRequestHeaderNumBytes + sizeof(uint8_t) + domainNameNumBytes,
|
||||
&httpPort, sizeof(uint16_t));
|
||||
|
||||
NSData *socksRequestData =
|
||||
[[NSData alloc] initWithBytes:socksRequest length:socksRequestNumBytes];
|
||||
[self.credentialsSocket writeData:socksRequestData withTimeout:kTcpSocketTimeoutSecs tag:0];
|
||||
[self.credentialsSocket readDataToLength:kSocksConnectResponseNumBytes
|
||||
withTimeout:kTcpSocketTimeoutSecs
|
||||
tag:0];
|
||||
|
||||
NSString *httpRequest =
|
||||
[[NSString alloc] initWithFormat:@"HEAD / HTTP/1.1\r\nHost: %@\r\n\r\n", domain];
|
||||
[self.credentialsSocket
|
||||
writeData:[NSData dataWithBytes:[httpRequest UTF8String] length:httpRequest.length]
|
||||
withTimeout:kTcpSocketTimeoutSecs
|
||||
tag:kSocketTagHttpRequest];
|
||||
[self.credentialsSocket readDataWithTimeout:kTcpSocketTimeoutSecs tag:kSocketTagHttpRequest];
|
||||
[self.credentialsSocket disconnectAfterReading];
|
||||
}
|
||||
|
||||
// Returns a statically defined array containing domain names for validating server credentials.
|
||||
+ (const NSArray *)getCredentialsValidationDomains {
|
||||
static const NSArray *kCredentialsValidationDomains;
|
||||
static dispatch_once_t kDispatchOnceToken;
|
||||
dispatch_once(&kDispatchOnceToken, ^{
|
||||
// We have chosen these domains due to their neutrality.
|
||||
kCredentialsValidationDomains =
|
||||
@[ @"eff.org", @"ietf.org", @"w3.org", @"wikipedia.org", @"example.com" ];
|
||||
});
|
||||
return kCredentialsValidationDomains;
|
||||
}
|
||||
|
||||
// Returns a random domain from |kCredentialsValidationDomains|.
|
||||
- (NSString *)chooseRandomDomain {
|
||||
const NSArray *domains = [ShadowsocksConnectivity getCredentialsValidationDomains];
|
||||
int index = arc4random_uniform((uint32_t)domains.count);
|
||||
return domains[index];
|
||||
}
|
||||
|
||||
// Calls |credentialsCompletion| once with |areServerCredentialsValid|.
|
||||
- (void)serverCredentialsCheckDone {
|
||||
if (self.credentialsCompletion != NULL) {
|
||||
self.credentialsCompletion(self.areServerCredentialsValid);
|
||||
self.credentialsCompletion = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - Reachability
|
||||
|
||||
- (void)isReachable:(NSString *)host port:(uint16_t)port completion:(void (^)(BOOL))completion {
|
||||
self.isServerReachable = false;
|
||||
self.reachabilityCompletion = completion;
|
||||
self.reachabilitySocket =
|
||||
[[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:self.dispatchQueue];
|
||||
NSError *error;
|
||||
[self.reachabilitySocket connectToHost:host
|
||||
onPort:port
|
||||
withTimeout:kTcpSocketTimeoutSecs
|
||||
error:&error];
|
||||
if (error) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Calls |reachabilityCompletion| once with |isServerReachable|.
|
||||
- (void)reachabilityCheckDone {
|
||||
if (self.reachabilityCompletion != NULL) {
|
||||
self.reachabilityCompletion(self.isServerReachable);
|
||||
self.reachabilityCompletion = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - GCDAsyncSocketDelegate
|
||||
|
||||
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
|
||||
// We don't need to inspect any of the data, as the SOCKS responses are hardcoded in ss-local and
|
||||
// the fact that we have read the HTTP response indicates that the server credentials are valid.
|
||||
if (tag == kSocketTagHttpRequest && data != nil) {
|
||||
NSString *httpResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
|
||||
self.areServerCredentialsValid = httpResponse != nil && [httpResponse hasPrefix:@"HTTP/1.1"];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
|
||||
if ([self.reachabilitySocket isEqual:sock]) {
|
||||
self.isServerReachable = true;
|
||||
[self.reachabilitySocket disconnect];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)error {
|
||||
if ([self.reachabilitySocket isEqual:sock]) {
|
||||
[self reachabilityCheckDone];
|
||||
} else {
|
||||
[self serverCredentialsCheckDone];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
86
client/platforms/ios/Subnet.swift
Normal file
86
client/platforms/ios/Subnet.swift
Normal file
|
@ -0,0 +1,86 @@
|
|||
// Copyright 2018 The Outline Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
import Foundation
|
||||
|
||||
// Represents an IP subnetwork.
|
||||
@objcMembers
|
||||
class Subnet: NSObject {
|
||||
static let kReservedSubnets = [
|
||||
"10.0.0.0/8",
|
||||
"100.64.0.0/10",
|
||||
"169.254.0.0/16",
|
||||
"172.16.0.0/12",
|
||||
"192.0.0.0/24",
|
||||
"192.0.2.0/24",
|
||||
"192.31.196.0/24",
|
||||
"192.52.193.0/24",
|
||||
"192.88.99.0/24",
|
||||
"192.168.0.0/16",
|
||||
"192.175.48.0/24",
|
||||
"198.18.0.0/15",
|
||||
"198.51.100.0/24",
|
||||
"203.0.113.0/24",
|
||||
"240.0.0.0/4"
|
||||
]
|
||||
|
||||
// Parses a CIDR subnet into a Subnet object. Returns nil on failure.
|
||||
static func parse(_ cidrSubnet: String) -> Subnet? {
|
||||
let components = cidrSubnet.components(separatedBy: "/")
|
||||
guard components.count == 2 else {
|
||||
NSLog("Malformed CIDR subnet")
|
||||
return nil
|
||||
}
|
||||
guard let prefix = UInt16(components[1]) else {
|
||||
NSLog("Invalid subnet prefix")
|
||||
return nil
|
||||
}
|
||||
return Subnet(address: components[0], prefix: prefix)
|
||||
}
|
||||
|
||||
// Returns a list of reserved Subnets.
|
||||
static func getReservedSubnets() -> [Subnet] {
|
||||
var subnets: [Subnet] = []
|
||||
for cidrSubnet in kReservedSubnets {
|
||||
if let subnet = self.parse(cidrSubnet) {
|
||||
subnets.append(subnet)
|
||||
}
|
||||
}
|
||||
return subnets
|
||||
}
|
||||
|
||||
public var address: String
|
||||
public var prefix: UInt16
|
||||
public var mask: String
|
||||
|
||||
init(address: String, prefix: UInt16) {
|
||||
self.address = address
|
||||
self.prefix = prefix
|
||||
let mask = (0xffffffff as UInt32) << (32 - prefix);
|
||||
self.mask = mask.IPv4String()
|
||||
}
|
||||
}
|
||||
|
||||
extension UInt32 {
|
||||
// Returns string representation of the integer as an IP address.
|
||||
public func IPv4String() -> String {
|
||||
let ip = self
|
||||
let a = UInt8((ip>>24) & 0xff)
|
||||
let b = UInt8((ip>>16) & 0xff)
|
||||
let c = UInt8((ip>>8) & 0xff)
|
||||
let d = UInt8(ip & 0xff)
|
||||
return "\(a).\(b).\(c).\(d)"
|
||||
}
|
||||
}
|
||||
|
|
@ -5,8 +5,8 @@ import Foundation
|
|||
import NetworkExtension
|
||||
import os
|
||||
import OpenVPNAdapter
|
||||
import ShadowSocks
|
||||
//import Tun2Socks
|
||||
//import ShadowSocks
|
||||
//import Tun2socks
|
||||
|
||||
enum TunnelProtoType: String {
|
||||
case wireguard, openvpn, shadowsocks, none
|
||||
|
@ -28,11 +28,12 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
|
|||
return adapter
|
||||
}()
|
||||
|
||||
private var shadowSocksPort: Int32 = 0
|
||||
private var isShadowsocksRunning: Bool = false
|
||||
var ssCompletion: ShadowsocksProxyCompletion = nil
|
||||
private let ssQueue = DispatchQueue(label: "org.amnezia.shadowsocks")
|
||||
private var shadowSocksConfig: Data? = nil
|
||||
var ssCompletion: ShadowsocksProxyCompletion = nil
|
||||
|
||||
// private var shadowSocksPort: Int32 = 0
|
||||
// private var isShadowsocksRunning: Bool = false
|
||||
// private let ssQueue = DispatchQueue(label: "org.amnezia.shadowsocks")
|
||||
|
||||
// private var tun2socksWriter: AmneziaTun2SocksWriter? = nil
|
||||
// private var tun2socksTunnel: Tun2socksOutlineTunnelProtocol? = nil
|
||||
|
@ -67,9 +68,7 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
|
|||
case .openvpn:
|
||||
startOpenVPN(completionHandler: completionHandler)
|
||||
case .shadowsocks:
|
||||
startShadowSocks { error in
|
||||
|
||||
}
|
||||
startShadowSocks(completionHandler: completionHandler)
|
||||
case .none:
|
||||
break
|
||||
}
|
||||
|
@ -207,8 +206,8 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
|
|||
wg_log(.error, message: "Cannot start startShadowSocks()")
|
||||
return
|
||||
}
|
||||
// self.shadowSocksConfig = ssConfiguration
|
||||
//
|
||||
self.shadowSocksConfig = ssConfiguration
|
||||
|
||||
// guard let config = self.shadowSocksConfig else { return }
|
||||
// guard let ssConfig = try? JSONSerialization.jsonObject(with: config, options: []) as? [String: Any] else {
|
||||
// self.ssCompletion?(0, NSError(domain: Bundle.main.bundleIdentifier ?? "unknown",
|
||||
|
@ -216,36 +215,50 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
|
|||
// userInfo: [NSLocalizedDescriptionKey: "Cannot parse json for ss in tunnel"]))
|
||||
// return
|
||||
// }
|
||||
|
||||
// let sshost = ssConfig["local_addr"] as? String
|
||||
// let ssport = ssConfig["local_port"] as? Int ?? Int(self.shadowSocksPort)
|
||||
//
|
||||
// let sshost = ssConfig["local_addr"] as? String
|
||||
// let ssport = ssConfig["local_port"] as? Int ?? 8585
|
||||
// let method = ssConfig["method"] as? String
|
||||
// let password = ssConfig["password"] as? String
|
||||
//
|
||||
// var errorCode: Int = 0
|
||||
// ShadowsocksCheckConnectivity(sshost, ssport, password, method, &errorCode, nil)
|
||||
// if (errorCode != 0) {
|
||||
// self.ssCompletion?(0, NSError(domain: Bundle.main.bundleIdentifier ?? "unknown",
|
||||
// code: 100,
|
||||
// userInfo: [NSLocalizedDescriptionKey: "Error checking ss connectivity: \(errorCode)"]))
|
||||
// return
|
||||
// }
|
||||
|
||||
|
||||
// Thread.detachNewThread { [weak self] in
|
||||
setupAndLaunchShadowSocksProxy(withConfig: ssConfiguration, ssHandler: { [weak self] port, error in
|
||||
wg_log(.info,
|
||||
message: "Prepare to start openvpn, self is \(self == nil ? "null" : "not null")")
|
||||
self.setupAndlaunchOpenVPN(withConfig: ovpnConfiguration) { error in
|
||||
guard error == nil else {
|
||||
wg_log(.error, message: "Stopping tunnel: \(error?.localizedDescription ?? "none")")
|
||||
wg_log(.error, message: "Start OpenVPN tunnel error : \(error?.localizedDescription ?? "none")")
|
||||
completionHandler(error!)
|
||||
return
|
||||
}
|
||||
|
||||
self?.setupAndlaunchOpenVPN(withConfig: ovpnConfiguration) { error in
|
||||
guard error == nil else {
|
||||
wg_log(.error, message: "Start OpenVPN tunnel error : \(error?.localizedDescription ?? "none")")
|
||||
completionHandler(error!)
|
||||
return
|
||||
}
|
||||
wg_log(.error, message: "OpenVPN tunnel connected.")
|
||||
}
|
||||
|
||||
// self?.startTun2Socks(host: sshost, port: ssport, password: password, cipher: method, isUDPEnabled: false, error: nil)
|
||||
})
|
||||
// }
|
||||
wg_log(.error, message: "OpenVPN tunnel connected.")
|
||||
// self.startTun2Socks(host: sshost, port: ssport, password: password, cipher: method, isUDPEnabled: false, error: nil)
|
||||
}
|
||||
//// Thread.detachNewThread { [weak self] in
|
||||
//// setupAndLaunchShadowSocksProxy(withConfig: ssConfiguration, ssHandler: { [weak self] port, error in
|
||||
//// wg_log(.info,
|
||||
//// message: "Prepare to start openvpn, self is \(self == nil ? "null" : "not null")")
|
||||
//// guard error == nil else {
|
||||
//// wg_log(.error, message: "Stopping tunnel: \(error?.localizedDescription ?? "none")")
|
||||
//// completionHandler(error!)
|
||||
//// return
|
||||
//// }
|
||||
////
|
||||
//// self?.setupAndlaunchOpenVPN(withConfig: ovpnConfiguration) { error in
|
||||
//// guard error == nil else {
|
||||
//// wg_log(.error, message: "Start OpenVPN tunnel error : \(error?.localizedDescription ?? "none")")
|
||||
//// completionHandler(error!)
|
||||
//// return
|
||||
//// }
|
||||
//// wg_log(.error, message: "OpenVPN tunnel connected.")
|
||||
//// }
|
||||
//// })
|
||||
//// }
|
||||
}
|
||||
|
||||
private func stopWireguard(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
|
||||
|
@ -294,7 +307,7 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
|
|||
// self.processQueue.sync { self.processPackets() }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
|
||||
// private func processPackets() {
|
||||
// wg_log(.info, message: "Inside startTun2SocksPacketForwarder")
|
||||
// packetFlow.readPacketObjects { [weak self] packets in
|
||||
|
@ -341,100 +354,100 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
|
|||
ovpnAdapter.connect(using: packetFlow)
|
||||
}
|
||||
|
||||
private func setupAndLaunchShadowSocksProxy(withConfig config: Data, ssHandler: ShadowsocksProxyCompletion) {
|
||||
let str = String(decoding: config, as: UTF8.self)
|
||||
wg_log(.info, message: "config: \(str)")
|
||||
ssCompletion = ssHandler
|
||||
guard let ssConfig = try? JSONSerialization.jsonObject(with: config, options: []) as? [String: Any] else {
|
||||
ssHandler?(0, NSError(domain: Bundle.main.bundleIdentifier ?? "unknown",
|
||||
code: 100,
|
||||
userInfo: [NSLocalizedDescriptionKey: "Cannot parse json for ss in tunnel"]))
|
||||
return
|
||||
}
|
||||
|
||||
wg_log(.info, message: "SS Config: \(ssConfig)")
|
||||
|
||||
guard let remoteHost = ssConfig["server"] as? String, // UnsafeMutablePointer<CChar>,
|
||||
let remotePort = ssConfig["server_port"] as? Int32,
|
||||
let localAddress = ssConfig["local_addr"] as? String, //UnsafeMutablePointer<CChar>,
|
||||
let localPort = ssConfig["local_port"] as? Int32,
|
||||
let method = ssConfig["method"] as? String, //UnsafeMutablePointer<CChar>,
|
||||
let password = ssConfig["password"] as? String,//UnsafeMutablePointer<CChar>,
|
||||
let timeout = ssConfig["timeout"] as? Int32
|
||||
else {
|
||||
ssHandler?(0, NSError(domain: Bundle.main.bundleIdentifier ?? "unknown",
|
||||
code: 100,
|
||||
userInfo: [NSLocalizedDescriptionKey: "Cannot assing profile params for ss in tunnel"]))
|
||||
return
|
||||
}
|
||||
|
||||
/* An example profile
|
||||
*
|
||||
* const profile_t EXAMPLE_PROFILE = {
|
||||
* .remote_host = "example.com",
|
||||
* .local_addr = "127.0.0.1",
|
||||
* .method = "bf-cfb",
|
||||
* .password = "barfoo!",
|
||||
* .remote_port = 8338,
|
||||
* .local_port = 1080,
|
||||
* .timeout = 600;
|
||||
* .acl = NULL,
|
||||
* .log = NULL,
|
||||
* .fast_open = 0,
|
||||
* .mode = 0,
|
||||
* .verbose = 0
|
||||
* };
|
||||
*/
|
||||
|
||||
var profile: profile_t = .init()
|
||||
memset(&profile, 0, MemoryLayout<profile_t>.size)
|
||||
profile.remote_host = strdup(remoteHost)
|
||||
profile.remote_port = remotePort
|
||||
profile.local_addr = strdup(localAddress)
|
||||
profile.local_port = localPort
|
||||
profile.method = strdup(method)
|
||||
profile.password = strdup(password)
|
||||
profile.timeout = timeout
|
||||
profile.acl = nil
|
||||
profile.log = nil
|
||||
profile.mtu = 1600
|
||||
profile.fast_open = 1
|
||||
profile.mode = 0
|
||||
profile.verbose = 1
|
||||
|
||||
wg_log(.debug, message: "Prepare to start shadowsocks proxy server...")
|
||||
let observer = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
|
||||
ssQueue.sync { [weak self] in
|
||||
let success = start_ss_local_server_with_callback(profile, { socks_fd, udp_fd, data in
|
||||
wg_log(.debug, message: "Inside cb callback")
|
||||
wg_log(.debug, message: "Params: socks_fd -> \(socks_fd), udp_fd -> \(udp_fd)")
|
||||
if let obs = data {
|
||||
wg_log(.debug, message: "Prepare to call onShadowsocksCallback() with socks port \(socks_fd) and udp port \(udp_fd)")
|
||||
let mySelf = Unmanaged<PacketTunnelProvider>.fromOpaque(obs).takeUnretainedValue()
|
||||
mySelf.onShadowsocksCallback(fd: socks_fd)
|
||||
}
|
||||
}, observer)
|
||||
if success != -1 {
|
||||
wg_log(.error, message: "ss proxy started on port \(localPort)")
|
||||
self?.shadowSocksPort = localPort
|
||||
self?.isShadowsocksRunning = true
|
||||
} else {
|
||||
wg_log(.error, message: "Failed to start ss proxy")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func onShadowsocksCallback(fd: Int32) {
|
||||
wg_log(.debug, message: "Inside onShadowsocksCallback() with port \(fd)")
|
||||
var error: NSError? = nil
|
||||
if fd > 0 {
|
||||
// shadowSocksPort = getSockPort(for: fd)
|
||||
isShadowsocksRunning = true
|
||||
} else {
|
||||
error = NSError(domain: Bundle.main.bundleIdentifier ?? "unknown", code: 100, userInfo: [NSLocalizedDescriptionKey : "Failed to start shadowsocks proxy"])
|
||||
}
|
||||
ssCompletion?(shadowSocksPort, error)
|
||||
}
|
||||
// private func setupAndLaunchShadowSocksProxy(withConfig config: Data, ssHandler: ShadowsocksProxyCompletion) {
|
||||
// let str = String(decoding: config, as: UTF8.self)
|
||||
// wg_log(.info, message: "config: \(str)")
|
||||
// ssCompletion = ssHandler
|
||||
// guard let ssConfig = try? JSONSerialization.jsonObject(with: config, options: []) as? [String: Any] else {
|
||||
// ssHandler?(0, NSError(domain: Bundle.main.bundleIdentifier ?? "unknown",
|
||||
// code: 100,
|
||||
// userInfo: [NSLocalizedDescriptionKey: "Cannot parse json for ss in tunnel"]))
|
||||
// return
|
||||
// }
|
||||
//
|
||||
// wg_log(.info, message: "SS Config: \(ssConfig)")
|
||||
//
|
||||
// guard let remoteHost = ssConfig["server"] as? String, // UnsafeMutablePointer<CChar>,
|
||||
// let remotePort = ssConfig["server_port"] as? Int32,
|
||||
// let localAddress = ssConfig["local_addr"] as? String, //UnsafeMutablePointer<CChar>,
|
||||
// let localPort = ssConfig["local_port"] as? Int32,
|
||||
// let method = ssConfig["method"] as? String, //UnsafeMutablePointer<CChar>,
|
||||
// let password = ssConfig["password"] as? String,//UnsafeMutablePointer<CChar>,
|
||||
// let timeout = ssConfig["timeout"] as? Int32
|
||||
// else {
|
||||
// ssHandler?(0, NSError(domain: Bundle.main.bundleIdentifier ?? "unknown",
|
||||
// code: 100,
|
||||
// userInfo: [NSLocalizedDescriptionKey: "Cannot assing profile params for ss in tunnel"]))
|
||||
// return
|
||||
// }
|
||||
//
|
||||
// /* An example profile
|
||||
// *
|
||||
// * const profile_t EXAMPLE_PROFILE = {
|
||||
// * .remote_host = "example.com",
|
||||
// * .local_addr = "127.0.0.1",
|
||||
// * .method = "bf-cfb",
|
||||
// * .password = "barfoo!",
|
||||
// * .remote_port = 8338,
|
||||
// * .local_port = 1080,
|
||||
// * .timeout = 600;
|
||||
// * .acl = NULL,
|
||||
// * .log = NULL,
|
||||
// * .fast_open = 0,
|
||||
// * .mode = 0,
|
||||
// * .verbose = 0
|
||||
// * };
|
||||
// */
|
||||
//
|
||||
// var profile: profile_t = .init()
|
||||
// memset(&profile, 0, MemoryLayout<profile_t>.size)
|
||||
// profile.remote_host = strdup(remoteHost)
|
||||
// profile.remote_port = remotePort
|
||||
// profile.local_addr = strdup(localAddress)
|
||||
// profile.local_port = localPort
|
||||
// profile.method = strdup(method)
|
||||
// profile.password = strdup(password)
|
||||
// profile.timeout = timeout
|
||||
// profile.acl = nil
|
||||
// profile.log = nil
|
||||
// profile.mtu = 1600
|
||||
// profile.fast_open = 1
|
||||
// profile.mode = 0
|
||||
// profile.verbose = 1
|
||||
//
|
||||
// wg_log(.debug, message: "Prepare to start shadowsocks proxy server...")
|
||||
// let observer = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
|
||||
// ssQueue.sync { [weak self] in
|
||||
// let success = start_ss_local_server_with_callback(profile, { socks_fd, udp_fd, data in
|
||||
// wg_log(.debug, message: "Inside cb callback")
|
||||
// wg_log(.debug, message: "Params: socks_fd -> \(socks_fd), udp_fd -> \(udp_fd)")
|
||||
// if let obs = data {
|
||||
// wg_log(.debug, message: "Prepare to call onShadowsocksCallback() with socks port \(socks_fd) and udp port \(udp_fd)")
|
||||
// let mySelf = Unmanaged<PacketTunnelProvider>.fromOpaque(obs).takeUnretainedValue()
|
||||
// mySelf.onShadowsocksCallback(fd: socks_fd)
|
||||
// }
|
||||
// }, observer)
|
||||
// if success != -1 {
|
||||
// wg_log(.error, message: "ss proxy started on port \(localPort)")
|
||||
// self?.shadowSocksPort = localPort
|
||||
// self?.isShadowsocksRunning = true
|
||||
// } else {
|
||||
// wg_log(.error, message: "Failed to start ss proxy")
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private func onShadowsocksCallback(fd: Int32) {
|
||||
// wg_log(.debug, message: "Inside onShadowsocksCallback() with port \(fd)")
|
||||
// var error: NSError? = nil
|
||||
// if fd > 0 {
|
||||
//// shadowSocksPort = getSockPort(for: fd)
|
||||
// isShadowsocksRunning = true
|
||||
// } else {
|
||||
// error = NSError(domain: Bundle.main.bundleIdentifier ?? "unknown", code: 100, userInfo: [NSLocalizedDescriptionKey : "Failed to start shadowsocks proxy"])
|
||||
// }
|
||||
// ssCompletion?(shadowSocksPort, error)
|
||||
// }
|
||||
|
||||
private func getSockPort(for fd: Int32) -> Int32 {
|
||||
var addr_in = sockaddr_in();
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue