forked from rickyzhang82/tethering
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SocksProxyController.mm
582 lines (443 loc) · 16.4 KB
/
SocksProxyController.mm
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//
// SOCKS - SOCKS Proxy for iPhone
// Copyright (C) 2009 Ehud Ben-Reuven
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation version 2.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,USA.
//
// Enhanced by Daniel Sachse on 10/30/10.
// Copyright 2010 coffeecoding. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
#import "SocksProxyController.h"
#import "SocksProxyController_TableView.h"
#import "AppDelegate.h"
#import "UIDevice_Extended.h"
#import "MOGlassButton.h"
#include <CFNetwork/CFNetwork.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
@interface SocksProxyController ()
// Properties that don't need to be seen by the outside world.
@property (nonatomic, readonly) BOOL isStarted;
@property (nonatomic, strong) NSNetService * netService;
@property (nonatomic, assign) CFSocketRef listeningSocket;
@property (nonatomic, assign) NSInteger nConnections;
@property (nonatomic, strong) NSMutableArray* sendreceiveStream;
@property (nonatomic, strong) AVPlayer* bgPlayer;
// Forward declarations
- (void)_stopServer:(NSString *)reason;
@end
@implementation SocksProxyController
@synthesize nConnections = _nConnections;
// Because sendreceiveStream is declared as an array, you have to use a custom getter.
// A synthesised getter doesn't compile.
@synthesize bgPlayer;
- (NSMutableArray*)sendreceiveStream
{
if(_sendreceiveStream == nil)
_sendreceiveStream = [[NSMutableArray alloc]init];
return _sendreceiveStream;
}
#pragma mark * Status management
// These methods are used by the core transfer code to update the UI.
- (void)_serverDidStartOnPort:(int)port
{
assert( (port > 0) && (port < 65536) );
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
// Disable device sleep mode
[UIApplication sharedApplication].idleTimerDisabled = YES;
// Enable proximity sensor (public as of 3.0)
[UIDevice currentDevice].proximityMonitoringEnabled = YES;
// Enable backgrounding
// Set AVAudioSession
NSError *sessionError = nil;
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 60000
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&sessionError];
#else
NSLog(@"Warning: iOS 6 is required for background audio hiding.");
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
#endif
AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"silence" withExtension:@"mp3"]];
[self setBgPlayer:[[AVPlayer alloc] initWithPlayerItem:item]];
[[self bgPlayer] setActionAtItemEnd:AVPlayerActionAtItemEndNone];
[[self bgPlayer] play];
self.currentAddress = [UIDevice localWiFiIPAddress];
self.currentPort = port;
self.currentStatusText = NSLocalizedString(@"Started", nil);
[self.startOrStopButton setTitle:NSLocalizedString(@"Stop", nil)
forState:UIControlStateNormal];
[self.startOrStopButton setupAsRedButton];
[self refreshProxyTable];
LOG_NETWORK_SOCKS(NSLOGGER_LEVEL_INFO, @"Server Started");
}
- (void)_serverDidStopWithReason:(NSString *)reason
{
if (reason == nil) {
reason = NSLocalizedString(@"Stopped", nil);
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
// Enable device sleep mode
[UIApplication sharedApplication].idleTimerDisabled = NO;
// Disable proximity sensor (public as of 3.0)
[UIDevice currentDevice].proximityMonitoringEnabled = NO;
// Disable backgrounding
[self setBgPlayer:nil];
self.currentAddress = @"";
self.currentPort = 0;
self.currentStatusText = reason;
[self.startOrStopButton setTitle:NSLocalizedString(@"Start" , nil)
forState:UIControlStateNormal];
[self.startOrStopButton setupAsGreenButton];
[self refreshProxyTable];
LOG_NETWORK_SOCKS(NSLOGGER_LEVEL_INFO, @"Server Stopped: %@", reason);
}
- (NSInteger)countOpen
{
int countOpen = 0;
for(SocksProxy* asocksProxy in self.sendreceiveStream)
{
if ( ! [asocksProxy isSendingReceiving])
++countOpen;
}
return countOpen;
}
- (void)_sendreceiveDidStart
{
self.currentStatusText = NSLocalizedString(@"Receiving", nil);
NSInteger countOpen = [self countOpen];
self.currentOpenConnections = countOpen;
if (!countOpen) {
[[AppDelegate sharedAppDelegate] didStartNetworking];
}
[self refreshProxyTable];
}
- (void)_updateStatus:(NSString *)statusString
{
assert(statusString != nil);
self.currentStatusText = statusString;
LOG_NETWORK_SOCKS(NSLOGGER_LEVEL_DEBUG, @"Status: %@", statusString);
}
- (void)_sendreceiveDidStopWithStatus:(NSString *)statusString
{
if (statusString == nil) {
statusString = NSLocalizedString(@"Receive succeeded", nil);
}
self.currentStatusText = statusString;
NSInteger countOpen = [self countOpen];
self.currentOpenConnections = countOpen;
if (!countOpen) {
[[AppDelegate sharedAppDelegate] didStopNetworking];
}
[self refreshProxyTable];
LOG_NETWORK_SOCKS(NSLOGGER_LEVEL_INFO, @"Connection ended %ld %ld: %@", (long)countOpen, (long)self.nConnections, statusString);
}
- (void)_downloadData:(NSInteger)bytes
{
self.downloadData += bytes/1024;
[self refreshProxyTable];
}
- (void)_uploadData:(NSInteger)bytes
{
self.uploadData += bytes/1024;
[self refreshProxyTable];
}
#pragma mark * Core transfer code
// This is the code that actually does the networking.
@synthesize netService = _netService;
@synthesize listeningSocket = _listeningSocket;
- (BOOL)isStarted
{
return (self.netService != nil);
}
// Have to write our own setter for listeningSocket because CF gets grumpy
// if you message NULL.
- (void)setListeningSocket:(CFSocketRef)newValue
{
if (newValue != self->_listeningSocket) {
if (self->_listeningSocket != NULL) {
CFRelease(self->_listeningSocket);
}
self->_listeningSocket = newValue;
if (self->_listeningSocket != NULL) {
CFRetain(self->_listeningSocket);
}
}
}
- (void)_acceptConnection:(int)fd
{
SocksProxy *proxy = nil;
BOOL isFoundFreeProxy = NO;
int totalNumProxy = 0;
for(proxy in self.sendreceiveStream)
{
if(![proxy isSendingReceiving])
{
isFoundFreeProxy = YES;
break;
}
totalNumProxy++;
}
if(!isFoundFreeProxy) {
if(totalNumProxy>MAX_CONNECTIONS) {
LOG_NETWORK_SOCKS(NSLOGGER_LEVEL_WARNNING, @"Reach maximum number of concurrent SOCKS connectionss.");
close(fd);
return;
}
proxy = [SocksProxy new];
proxy.delegate = self;
[self.sendreceiveStream addObject:proxy];
++self.nConnections;
self.currentConnectionCount = self.nConnections;
}
//recount open connection
int countOpen = 0;
for (SocksProxy* asocksProxy in self.sendreceiveStream)
{
if (![asocksProxy isSendingReceiving])
++countOpen;
}
LOG_NETWORK_SOCKS(NSLOGGER_LEVEL_INFO, @"Accept connection %d %ld", countOpen, (long)self.nConnections);
if (![proxy startSendReceive:fd])
close(fd);
[self refreshProxyTable];
}
static void AcceptCallback(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *info)
// Called by CFSocket when someone connects to our listening socket.
// This implementation just bounces the request up to Objective-C.
{
SocksProxyController * obj;
#pragma unused(type)
assert(type == kCFSocketAcceptCallBack);
#pragma unused(address)
// assert(address == NULL);
assert(data != NULL);
obj = (__bridge SocksProxyController *) info;
assert(obj != nil);
#pragma unused(s)
assert(s == obj->_listeningSocket);
[obj _acceptConnection:*(int *)data];
}
- (void)netService:(NSNetService *)sender didNotPublish:(NSDictionary *)errorDict
// A NSNetService delegate callback that's called if our Bonjour registration
// fails. We respond by shutting down the server.
//
// This is another of the big simplifying assumptions in this sample.
// A real server would use the real name of the device for registrations,
// and handle automatically renaming the service on conflicts. A real
// client would allow the user to browse for services. To simplify things
// we just hard-wire the service name in the client and, in the server, fail
// if there's a service name conflict.
{
#pragma unused(sender)
assert(sender == self.netService);
#pragma unused(errorDict)
[self _stopServer:@"Registration failed"];
}
- (void)_startServer
{
BOOL success;
int err;
int fd;
int junk;
struct sockaddr_in addr;
int port;
const int on = 1;
self.nConnections = 0;
// Create a listening socket and use CFSocket to integrate it into our
// runloop. We bind to port 0, which causes the kernel to give us
// any free port, then use getsockname to find out what port number we
// actually got.
port = 0;
fd = socket(AF_INET, SOCK_STREAM, 0);
success = (fd != -1);
if (success) {
// set scoket to reuse port and ignore TIME_WAIT state
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
memset(&addr, 0, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
int iport;
int ports[] = {1080,3128,-1};
for (iport = 0 ; ports[iport] >= 0 ; ++iport) {
port=ports[iport];
addr.sin_port = htons(port);
err = bind(fd, (const struct sockaddr *) &addr, sizeof(addr));
success = (err == 0);
if (success)
break;
else{
LOG_NETWORK_SOCKS(NSLOGGER_LEVEL_ERROR, @"Socks Server failed to bind port (%d), errono (%d)", port, errno);
}
}
}
if (success) {
err = listen(fd, 5);
success = (err == 0);
}else{
LOG_NETWORK_SOCKS(NSLOGGER_LEVEL_ERROR, @"Socks Server failed to bind to address, errno(%d)", errno);
}
if (success) {
socklen_t addrLen;
addrLen = sizeof(addr);
err = getsockname(fd, (struct sockaddr *) &addr, &addrLen);
success = (err == 0);
if (success) {
assert(addrLen == sizeof(addr));
port = ntohs(addr.sin_port);
}
}else{
LOG_NETWORK_SOCKS(NSLOGGER_LEVEL_ERROR, @"Socks Server failed to listen, errno(%d)", errno);
}
if (success) {
CFSocketContext context = { 0, (__bridge void*)self, NULL, NULL, NULL };
self.listeningSocket = CFSocketCreateWithNative(
NULL,
fd,
kCFSocketAcceptCallBack,
AcceptCallback,
&context
);
success = (self.listeningSocket != NULL);
if (success) {
CFRunLoopSourceRef rls;
CFRelease(self.listeningSocket); // to balance the create
fd = -1; // listeningSocket is now responsible for closing fd
rls = CFSocketCreateRunLoopSource(NULL, self.listeningSocket, 0);
assert(rls != NULL);
CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
CFRelease(rls);
}
}
// Now register our service with Bonjour. See the comments in -netService:didNotPublish:
// for more info about this simplifying assumption.
if (success) {
self.netService = [[NSNetService alloc] initWithDomain:@""
type:@"_socks5._tcp."
name:@"iPhone"
port:port];
success = (self.netService != nil);
}
if (success) {
self.netService.delegate = self;
[self.netService publishWithOptions:NSNetServiceNoAutoRename];
// continues in -netServiceDidPublish: or -netService:didNotPublish: ...
}
// Clean up after failure.
if ( success ) {
assert(port != 0);
[self _serverDidStartOnPort:port];
} else {
[self _stopServer:@"Start failed"];
if (fd != -1) {
junk = close(fd);
assert(junk == 0);
}
}
}
- (void)_stopServer:(NSString *)reason
{
for (SocksProxy* asocksProxy in self.sendreceiveStream)
{
if ([asocksProxy isSendingReceiving])
[asocksProxy stopSendReceiveWithStatus:@"Cancelled"];
}
[self.sendreceiveStream removeAllObjects];
if (self.netService != nil) {
[self.netService stop];
self.netService = nil;
}
if (self.listeningSocket != NULL) {
CFSocketInvalidate(self.listeningSocket);
self.listeningSocket = NULL;
}
[self _serverDidStopWithReason:reason];
}
#pragma mark * Actions
- (IBAction)startOrStopAction:(id)sender
{
#pragma unused(sender)
if (self.isStarted) {
[self _stopServer:nil];
_DNSServer = DNSServer::getInstance();
_DNSServer->stopDNSServer();
_HTTPServer = [HTTPServer sharedHTTPServerWithSocksProxyPort:currentPort];
[_HTTPServer stop];
} else {
if(self.currentAddress == nil)
self.currentAddress = [UIDevice localWiFiIPAddress];
if(currentAddress != nil){
//start socks proxy server
[self _startServer];
//start DNS server
_DNSServer = DNSServer::getInstance();
const char * ipv4Addr = [currentAddress cStringUsingEncoding:NSASCIIStringEncoding];
_DNSServer->startDNSServer(0, ipv4Addr);
//start HTTP server that advertise socks.pac
_HTTPServer = [HTTPServer sharedHTTPServerWithSocksProxyPort:currentPort];
HTTPServerState currentHTTPServerState = [_HTTPServer state] ;
if (currentHTTPServerState == SERVER_STATE_IDLE ||
currentHTTPServerState == SERVER_STATE_STOPPING)
[_HTTPServer start];
}else{
[self _updateStatus:@"Please connect to wifi."];
LOG_NETWORK_SOCKS(NSLOGGER_LEVEL_WARNNING, @"No local IP can be retrieved. iPhone may not connect to wifi network\n");
}
}
[self refreshProxyTable];
}
#pragma mark * View controller boilerplate
@synthesize currentPort;
@synthesize currentAddress;
@synthesize currentOpenConnections;
@synthesize currentConnectionCount;
@synthesize downloadData, uploadData;
@synthesize currentStatusText;// = _statusLabel;
@synthesize startOrStopButton = _startOrStopButton;
- (void)refreshProxyTable
{
[proxyTableView reloadData];
}
- (void)applicationDidEnterForeground:(NSNotification *)n
{
LOG_NETWORK_SOCKS(NSLOGGER_LEVEL_DEBUG, @"refreshing ip address");
// refresh the IP address, just in case
self.currentAddress = [UIDevice localWiFiIPAddress];
[self refreshProxyTable];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidEnterForeground:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
assert(self.startOrStopButton != nil);
self.currentStatusText = NSLocalizedString(@"Tap Start to start the server", nil);
[self.startOrStopButton setupAsGreenButton];
self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.startOrStopButton = nil;
}
- (void)dealloc
{
[self _stopServer:nil];
}
@end