forked from zhiphe/Potatso-iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPacketTunnelProvider.m
280 lines (255 loc) · 11 KB
/
PacketTunnelProvider.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
//
// PacketTunnelProvider.m
// PacketTunnel
//
// Created by LEI on 12/13/15.
// Copyright © 2015 TouchingApp. All rights reserved.
//
#import "PacketTunnelProvider.h"
#import "ProxyManager.h"
#import "TunnelInterface.h"
#import "dns.h"
#import <MMWormhole/MMWormhole.h>
#import "PotatsoBase.h"
#import <sys/syslog.h>
#import <ShadowPath/ShadowPath.h>
#import <sys/socket.h>
#import <arpa/inet.h>
#import <CocoaAsyncSocket/GCDAsyncSocket.h>
@interface PacketTunnelProvider () <GCDAsyncSocketDelegate>
@property (nonatomic) MMWormhole *wormhole;
@property (nonatomic) GCDAsyncSocket *statusSocket;
@property (nonatomic) GCDAsyncSocket *statusClientSocket;
@property (nonatomic) BOOL didSetupHockeyApp;
@property (nonatomic) NWPath *lastPath;
@property (strong) void (^pendingStartCompletion)(NSError *);
@property (strong) void (^pendingStopCompletion)(void);
@end
@implementation PacketTunnelProvider
- (void)startTunnelWithOptions:(NSDictionary *)options completionHandler:(void (^)(NSError *))completionHandler {
[self openLog];
NSLog(@"starting potatso tunnel...");
NSError *error = [TunnelInterface setupWithPacketTunnelFlow:self.packetFlow];
if (error) {
completionHandler(error);
exit(1);
return;
}
self.pendingStartCompletion = completionHandler;
[self startProxies];
[self startPacketForwarders];
[self setupWormhole];
}
- (void)setupWormhole {
self.wormhole = [[MMWormhole alloc] initWithApplicationGroupIdentifier:@"group.com.touchingapp.potatso" optionalDirectory:@"wormhole"];
__weak typeof(self) weakSelf = self;
[self.wormhole listenForMessageWithIdentifier:@"getTunnelStatus" listener:^(id _Nullable messageObject) {
[weakSelf.wormhole passMessageObject:@"ok" identifier:@"tunnelStatus"];
}];
[self.wormhole listenForMessageWithIdentifier:@"stopTunnel" listener:^(id _Nullable messageObject) {
[weakSelf stop];
}];
[self.wormhole listenForMessageWithIdentifier:@"getTunnelConnectionRecords" listener:^(id _Nullable messageObject) {
NSMutableArray *records = [NSMutableArray array];
struct log_client_states *p = log_clients;
while (p) {
struct client_state *client = p->csp;
NSMutableDictionary *d = [NSMutableDictionary dictionary];
char *url = client->http->url;
if (url == NULL) {
p = p->next;
continue;
}
d[@"url"] = [NSString stringWithCString:url encoding:NSUTF8StringEncoding];
d[@"method"] = @(client->http->gpc);
for (int i=0; i < STATUS_COUNT; i++) {
d[[NSString stringWithFormat:@"time%d", i]] = @(client->timestamp[i]);
}
d[@"version"] = @(client->http->ver);
// if (p->headers) {
// d[@"headers"] = [NSString stringWithCString:p->headers->string encoding:NSUTF8StringEncoding];
// }
// if (p->rule) {
// d[@"ruleType"] = @(p->rule->type),
// d[@"ruleAction"] = @(p->rule->action),
// d[@"ruleValue"] = [NSString stringWithCString:p->rule->value encoding:NSUTF8StringEncoding];
// }
d[@"responseCode"] = @(client->http->status);
[records addObject:d];
p = p->next;
}
NSString *result = [records jsonString];
[weakSelf.wormhole passMessageObject:result identifier:@"tunnelConnectionRecords"];
}];
[self setupStatusSocket];
}
- (void)setupStatusSocket {
NSError *error;
self.statusSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)];
[self.statusSocket acceptOnInterface:@"127.0.0.1" port:0 error:&error];
[self.statusSocket performBlock:^{
int port = sock_port(self.statusSocket.socket4FD);
[[Potatso sharedUserDefaults] setObject:@(port) forKey:@"tunnelStatusPort"];
[[Potatso sharedUserDefaults] synchronize];
}];
}
- (void)startProxies {
__block NSError *proxyError;
dispatch_group_t g = dispatch_group_create();
dispatch_group_enter(g);
[[ProxyManager sharedManager] startShadowsocks:^(int port, NSError *error) {
proxyError = error;
dispatch_group_leave(g);
}];
dispatch_group_wait(g, DISPATCH_TIME_FOREVER);
if (proxyError) {
exit(1);
return;
}
dispatch_group_enter(g);
[[ProxyManager sharedManager] startHttpProxy:^(int port, NSError *error) {
proxyError = error;
dispatch_group_leave(g);
}];
dispatch_group_wait(g, DISPATCH_TIME_FOREVER);
if (proxyError) {
exit(1);
return;
}
dispatch_group_enter(g);
[[ProxyManager sharedManager] startSocksProxy:^(int port, NSError *error) {
proxyError = error;
dispatch_group_leave(g);
}];
dispatch_group_wait(g, DISPATCH_TIME_FOREVER);
if (proxyError) {
exit(1);
return;
}
}
- (void)startPacketForwarders {
__weak typeof(self) weakSelf = self;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTun2SocksFinished) name:kTun2SocksStoppedNotification object:nil];
[self startVPNWithOptions:nil completionHandler:^(NSError *error) {
if (error == nil) {
[weakSelf addObserver:weakSelf forKeyPath:@"defaultPath" options:NSKeyValueObservingOptionInitial context:nil];
[TunnelInterface startTun2Socks:[ProxyManager sharedManager].socksProxyPort];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[TunnelInterface processPackets];
});
}
if (weakSelf.pendingStartCompletion) {
weakSelf.pendingStartCompletion(error);
weakSelf.pendingStartCompletion = nil;
}
}];
}
- (void)startVPNWithOptions:(NSDictionary *)options completionHandler:(void (^)(NSError *error))completionHandler {
NSString *generalConfContent = [NSString stringWithContentsOfURL:[Potatso sharedGeneralConfUrl] encoding:NSUTF8StringEncoding error:nil];
NSDictionary *generalConf = [generalConfContent jsonDictionary];
NSString *dns = generalConf[@"dns"];
NEIPv4Settings *ipv4Settings = [[NEIPv4Settings alloc] initWithAddresses:@[@"192.0.2.1"] subnetMasks:@[@"255.255.255.0"]];
NSArray *dnsServers;
if (dns.length) {
dnsServers = [dns componentsSeparatedByString:@","];
NSLog(@"custom dns servers: %@", dnsServers);
}else {
dnsServers = [DNSConfig getSystemDnsServers];
NSLog(@"system dns servers: %@", dnsServers);
}
NSMutableArray *excludedRoutes = [NSMutableArray array];
for (NSString *server in dnsServers) {
[excludedRoutes addObject:[[NEIPv4Route alloc] initWithDestinationAddress:[server stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] subnetMask:@"255.255.255.255"]];
}
[excludedRoutes addObject:[[NEIPv4Route alloc] initWithDestinationAddress:@"192.168.0.0" subnetMask:@"255.255.0.0"]];
[excludedRoutes addObject:[[NEIPv4Route alloc] initWithDestinationAddress:@"10.0.0.0" subnetMask:@"255.0.0.0"]];
[excludedRoutes addObject:[[NEIPv4Route alloc] initWithDestinationAddress:@"172.16.0.0" subnetMask:@"255.240.0.0"]];
ipv4Settings.includedRoutes = @[[NEIPv4Route defaultRoute]];
ipv4Settings.excludedRoutes = excludedRoutes;
NEPacketTunnelNetworkSettings *settings = [[NEPacketTunnelNetworkSettings alloc] initWithTunnelRemoteAddress:@"192.0.2.2"];
settings.IPv4Settings = ipv4Settings;
settings.MTU = @(TunnelMTU);
NEProxySettings* proxySettings = [[NEProxySettings alloc] init];
NSInteger proxyServerPort = [ProxyManager sharedManager].httpProxyPort;
NSString *proxyServerName = @"localhost";
proxySettings.HTTPEnabled = YES;
proxySettings.HTTPServer = [[NEProxyServer alloc] initWithAddress:proxyServerName port:proxyServerPort];
proxySettings.HTTPSEnabled = YES;
proxySettings.HTTPSServer = [[NEProxyServer alloc] initWithAddress:proxyServerName port:proxyServerPort];
proxySettings.excludeSimpleHostnames = YES;
settings.proxySettings = proxySettings;
settings.DNSSettings = [[NEDNSSettings alloc] initWithServers:dnsServers];
[self setTunnelNetworkSettings:settings completionHandler:^(NSError * _Nullable error) {
if (error) {
if (completionHandler) {
completionHandler(error);
}
}else{
if (completionHandler) {
completionHandler(nil);
}
}
}];
}
- (void)openLog {
NSString *logFilePath = [Potatso sharedLogUrl].path;
[[NSFileManager defaultManager] createFileAtPath:logFilePath contents:nil attributes:nil];
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "w+", stdout);
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "w+", stderr);
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"defaultPath"]) {
if (self.defaultPath.status == NWPathStatusSatisfied && ![self.defaultPath isEqualToPath:self.lastPath]) {
if (!self.lastPath) {
self.lastPath = self.defaultPath;
}else {
NSLog(@"received network change notifcation");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self startVPNWithOptions:nil completionHandler:nil];
});
}
}else {
self.lastPath = self.defaultPath;
}
}
}
- (void)stopTunnelWithReason:(NEProviderStopReason)reason completionHandler:(void (^)(void))completionHandler
{
// Add code here to start the process of stopping the tunnel
self.pendingStopCompletion = completionHandler;
[self stop];
}
- (void)stop {
NSLog(@"stoping potatso tunnel...");
[[Potatso sharedUserDefaults] setObject:@(0) forKey:@"tunnelStatusPort"];
[[Potatso sharedUserDefaults] synchronize];
[[ProxyManager sharedManager] stopHttpProxy];
[[ProxyManager sharedManager] stopSocksProxy];
[TunnelInterface stop];
}
- (void)onTun2SocksFinished {
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (self.pendingStopCompletion) {
self.pendingStopCompletion();
self.pendingStopCompletion = nil;
}
[self cancelTunnelWithError:nil];
exit(EXIT_SUCCESS);
}
- (void)handleAppMessage:(NSData *)messageData completionHandler:(void (^)(NSData *))completionHandler {
if (completionHandler != nil) {
completionHandler(nil);
}
}
- (void)sleepWithCompletionHandler:(void (^)(void))completionHandler {
NSLog(@"sleeping potatso tunnel...");
completionHandler();
}
- (void)wake {
NSLog(@"waking potatso tunnel...");
}
#pragma mark - GCDAsyncSocket Delegate
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket {
self.statusClientSocket = newSocket;
}
@end