-
Notifications
You must be signed in to change notification settings - Fork 0
/
HTTPServer.m
792 lines (606 loc) · 19.6 KB
/
HTTPServer.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
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
#import "HTTPServer.h"
#import "GCDAsyncSocket.h"
#import "HTTPConnection.h"
#import "WebSocket.h"
#import "HTTPLogging.h"
// Log levels: off, error, warn, info, verbose
// Other flags: trace
static const int httpLogLevel = HTTP_LOG_LEVEL_INFO; // | HTTP_LOG_FLAG_TRACE;
@interface HTTPServer (PrivateAPI)
- (void)unpublishBonjour;
- (void)publishBonjour;
+ (void)startBonjourThreadIfNeeded;
+ (void)performBonjourBlock:(dispatch_block_t)block waitUntilDone:(BOOL)waitUntilDone;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation HTTPServer
@synthesize connectionDelegate;
/**
* Standard Constructor.
* Instantiates an HTTP server, but does not start it.
**/
- (id)init
{
if ((self = [super init]))
{
HTTPLogTrace();
// Initialize underlying dispatch queue and GCD based tcp socket
serverQueue = dispatch_queue_create("HTTPServer", NULL);
asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:serverQueue];
// Use default connection class of HTTPConnection
connectionQueue = dispatch_queue_create("HTTPConnection", NULL);
connectionClass = [HTTPConnection self];
// By default bind on all available interfaces, en1, wifi etc
interface = nil;
// Use a default port of 0
// This will allow the kernel to automatically pick an open port for us
port = 0;
// Configure default values for bonjour service
// Bonjour domain. Use the local domain by default
domain = @"local.";
// If using an empty string ("") for the service name when registering,
// the system will automatically use the "Computer Name".
// Passing in an empty string will also handle name conflicts
// by automatically appending a digit to the end of the name.
name = @"";
// Initialize arrays to hold all the HTTP and webSocket connections
connections = [[NSMutableArray alloc] init];
webSockets = [[NSMutableArray alloc] init];
connectionsLock = [[NSLock alloc] init];
webSocketsLock = [[NSLock alloc] init];
// Register for notifications of closed connections
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(connectionDidDie:)
name:HTTPConnectionDidDieNotification
object:nil];
// Register for notifications of closed websocket connections
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(webSocketDidDie:)
name:WebSocketDidDieNotification
object:nil];
isRunning = NO;
}
return self;
}
/**
* Standard Deconstructor.
* Stops the server, and clients, and releases any resources connected with this instance.
**/
- (void)dealloc
{
HTTPLogTrace();
// Remove notification observer
[[NSNotificationCenter defaultCenter] removeObserver:self];
// Stop the server if it's running
[self stop];
// Release all instance variables
dispatch_release(serverQueue);
dispatch_release(connectionQueue);
[asyncSocket setDelegate:nil delegateQueue:NULL];
[asyncSocket release];
[documentRoot release];
[interface release];
[netService release];
[domain release];
[name release];
[type release];
[txtRecordDictionary release];
[connections release];
[webSockets release];
[connectionsLock release];
[webSocketsLock release];
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Server Configuration
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The document root is filesystem root for the webserver.
* Thus requests for /index.html will be referencing the index.html file within the document root directory.
* All file requests are relative to this document root.
**/
- (NSString *)documentRoot
{
__block NSString *result;
dispatch_sync(serverQueue, ^{
result = [documentRoot retain];
});
return [result autorelease];
}
- (void)setDocumentRoot:(NSString *)value
{
HTTPLogTrace();
// Document root used to be of type NSURL.
// Add type checking for early warning to developers upgrading from older versions.
if (value && ![value isKindOfClass:[NSString class]])
{
HTTPLogWarn(@"%@: %@ - Expecting NSString parameter, received %@ parameter",
THIS_FILE, THIS_METHOD, NSStringFromClass([value class]));
return;
}
NSString *valueCopy = [value copy];
dispatch_async(serverQueue, ^{
[documentRoot release];
documentRoot = [valueCopy retain];
});
[valueCopy release];
}
/**
* The connection class is the class that will be used to handle connections.
* That is, when a new connection is created, an instance of this class will be intialized.
* The default connection class is HTTPConnection.
* If you use a different connection class, it is assumed that the class extends HTTPConnection
**/
- (Class)connectionClass
{
__block Class result;
dispatch_sync(serverQueue, ^{
result = connectionClass;
});
return result;
}
- (void)setConnectionClass:(Class)value
{
HTTPLogTrace();
dispatch_async(serverQueue, ^{
connectionClass = value;
});
}
/**
* What interface to bind the listening socket to.
**/
- (NSString *)interface
{
__block NSString *result;
dispatch_sync(serverQueue, ^{
result = [interface retain];
});
return [result autorelease];
}
- (void)setInterface:(NSString *)value
{
NSString *valueCopy = [value copy];
dispatch_async(serverQueue, ^{
[interface release];
interface = [valueCopy retain];
});
[valueCopy release];
}
/**
* The port to listen for connections on.
* By default this port is initially set to zero, which allows the kernel to pick an available port for us.
* After the HTTP server has started, the port being used may be obtained by this method.
**/
- (UInt16)port
{
__block UInt16 result;
dispatch_sync(serverQueue, ^{
result = port;
});
return result;
}
- (UInt16)listeningPort
{
__block UInt16 result;
dispatch_sync(serverQueue, ^{
if (isRunning)
result = [asyncSocket localPort];
else
result = 0;
});
return result;
}
- (void)setPort:(UInt16)value
{
HTTPLogTrace();
dispatch_async(serverQueue, ^{
port = value;
});
}
/**
* Domain on which to broadcast this service via Bonjour.
* The default domain is @"local".
**/
- (NSString *)domain
{
__block NSString *result;
dispatch_sync(serverQueue, ^{
result = [domain retain];
});
return [domain autorelease];
}
- (void)setDomain:(NSString *)value
{
HTTPLogTrace();
NSString *valueCopy = [value copy];
dispatch_async(serverQueue, ^{
[domain release];
domain = [valueCopy retain];
});
[valueCopy release];
}
/**
* The name to use for this service via Bonjour.
* The default name is an empty string,
* which should result in the published name being the host name of the computer.
**/
- (NSString *)name
{
__block NSString *result;
dispatch_sync(serverQueue, ^{
result = [name retain];
});
return [name autorelease];
}
- (NSString *)publishedName
{
__block NSString *result;
dispatch_sync(serverQueue, ^{
if (netService == nil)
{
result = nil;
}
else
{
dispatch_block_t bonjourBlock = ^{
result = [[netService name] copy];
};
[[self class] performBonjourBlock:bonjourBlock waitUntilDone:YES];
}
});
return [result autorelease];
}
- (void)setName:(NSString *)value
{
NSString *valueCopy = [value copy];
dispatch_async(serverQueue, ^{
[name release];
name = [valueCopy retain];
});
[valueCopy release];
}
/**
* The type of service to publish via Bonjour.
* No type is set by default, and one must be set in order for the service to be published.
**/
- (NSString *)type
{
__block NSString *result;
dispatch_sync(serverQueue, ^{
result = [type retain];
});
return [result autorelease];
}
- (void)setType:(NSString *)value
{
NSString *valueCopy = [value copy];
dispatch_async(serverQueue, ^{
[type release];
type = [valueCopy retain];
});
[valueCopy release];
}
/**
* The extra data to use for this service via Bonjour.
**/
- (NSDictionary *)TXTRecordDictionary
{
__block NSDictionary *result;
dispatch_sync(serverQueue, ^{
result = [txtRecordDictionary retain];
});
return [result autorelease];
}
- (void)setTXTRecordDictionary:(NSDictionary *)value
{
HTTPLogTrace();
NSDictionary *valueCopy = [value copy];
dispatch_async(serverQueue, ^{
[txtRecordDictionary release];
txtRecordDictionary = [valueCopy retain];
// Update the txtRecord of the netService if it has already been published
if (netService)
{
NSNetService *theNetService = netService;
NSData *txtRecordData = nil;
if (txtRecordDictionary)
txtRecordData = [NSNetService dataFromTXTRecordDictionary:txtRecordDictionary];
dispatch_block_t bonjourBlock = ^{
[theNetService setTXTRecordData:txtRecordData];
};
[[self class] performBonjourBlock:bonjourBlock waitUntilDone:NO];
}
});
[valueCopy release];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Server Control
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)start:(NSError **)errPtr
{
HTTPLogTrace();
__block BOOL success = YES;
__block NSError *err = nil;
dispatch_sync(serverQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
success = [asyncSocket acceptOnInterface:interface port:port error:&err];
if (success)
{
HTTPLogInfo(@"%@: Started HTTP server on port %hu", THIS_FILE, [asyncSocket localPort]);
isRunning = YES;
[self publishBonjour];
}
else
{
HTTPLogError(@"%@: Failed to start HTTP Server: %@", THIS_FILE, err);
[err retain];
}
[pool release];
});
if (errPtr)
*errPtr = [err autorelease];
else
[err release];
return success;
}
- (BOOL)stop
{
HTTPLogTrace();
dispatch_sync(serverQueue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// First stop publishing the service via bonjour
[self unpublishBonjour];
// Stop listening / accepting incoming connections
[asyncSocket disconnect];
isRunning = NO;
// Now stop all HTTP connections the server owns
[connectionsLock lock];
for (HTTPConnection *connection in connections)
{
[connection stop];
}
[connections removeAllObjects];
[connectionsLock unlock];
// Now stop all WebSocket connections the server owns
[webSocketsLock lock];
for (WebSocket *webSocket in webSockets)
{
[webSocket stop];
}
[webSockets removeAllObjects];
[webSocketsLock unlock];
[pool release];
});
return YES;
}
- (BOOL)isRunning
{
__block BOOL result;
dispatch_sync(serverQueue, ^{
result = isRunning;
});
return result;
}
- (void)addWebSocket:(WebSocket *)ws
{
[webSocketsLock lock];
HTTPLogTrace();
[webSockets addObject:ws];
[webSocketsLock unlock];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Server Status
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Returns the number of http client connections that are currently connected to the server.
**/
- (NSUInteger)numberOfHTTPConnections
{
NSUInteger result = 0;
[connectionsLock lock];
result = [connections count];
[connectionsLock unlock];
return result;
}
/**
* Returns the number of websocket client connections that are currently connected to the server.
**/
- (NSUInteger)numberOfWebSocketConnections
{
NSUInteger result = 0;
[webSocketsLock lock];
result = [webSockets count];
[webSocketsLock unlock];
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Incoming Connections
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (HTTPConfig *)config
{
// Override me if you want to provide a custom config to the new connection.
//
// Generally this involves overriding the HTTPConfig class to include any custom settings,
// and then having this method return an instance of 'MyHTTPConfig'.
// Note: Think you can make the server faster by putting each connection on its own queue?
// Then benchmark it before and after and discover for yourself the shocking truth!
//
// Try the apache benchmark tool (already installed on your Mac):
// $ ab -n 1000 -c 1 http://localhost:<port>/some_path.html
return [[[HTTPConfig alloc] initWithServer:self documentRoot:documentRoot queue:connectionQueue] autorelease];
}
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
HTTPConnection *newConnection = (HTTPConnection *)[[connectionClass alloc] initWithAsyncSocket:newSocket
configuration:[self config]];
if(connectionDelegate != nil)
newConnection.delegate = connectionDelegate;
[connectionsLock lock];
[connections addObject:newConnection];
[connectionsLock unlock];
[newConnection start];
[newConnection release];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Bonjour
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)publishBonjour
{
HTTPLogTrace();
NSAssert(dispatch_get_current_queue() == serverQueue, @"Invalid queue");
if (type)
{
netService = [[NSNetService alloc] initWithDomain:domain type:type name:name port:[asyncSocket localPort]];
[netService setDelegate:self];
NSNetService *theNetService = netService;
NSData *txtRecordData = nil;
if (txtRecordDictionary)
txtRecordData = [NSNetService dataFromTXTRecordDictionary:txtRecordDictionary];
dispatch_block_t bonjourBlock = ^{
[theNetService removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
[theNetService scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[theNetService publish];
// Do not set the txtRecordDictionary prior to publishing!!!
// This will cause the OS to crash!!!
if (txtRecordData)
{
[theNetService setTXTRecordData:txtRecordData];
}
};
[[self class] startBonjourThreadIfNeeded];
[[self class] performBonjourBlock:bonjourBlock waitUntilDone:NO];
}
}
- (void)unpublishBonjour
{
HTTPLogTrace();
NSAssert(dispatch_get_current_queue() == serverQueue, @"Invalid queue");
if (netService)
{
NSNetService *theNetService = netService;
dispatch_block_t bonjourBlock = ^{
[theNetService stop];
[theNetService release];
};
[[self class] performBonjourBlock:bonjourBlock waitUntilDone:NO];
netService = nil;
}
}
/**
* Republishes the service via bonjour if the server is running.
* If the service was not previously published, this method will publish it (if the server is running).
**/
- (void)republishBonjour
{
HTTPLogTrace();
dispatch_async(serverQueue, ^{
[self unpublishBonjour];
[self publishBonjour];
});
}
/**
* Called when our bonjour service has been successfully published.
* This method does nothing but output a log message telling us about the published service.
**/
- (void)netServiceDidPublish:(NSNetService *)ns
{
// Override me to do something here...
//
// Note: This method is invoked on our bonjour thread.
HTTPLogInfo(@"Bonjour Service Published: domain(%@) type(%@) name(%@)", [ns domain], [ns type], [ns name]);
}
/**
* Called if our bonjour service failed to publish itself.
* This method does nothing but output a log message telling us about the published service.
**/
- (void)netService:(NSNetService *)ns didNotPublish:(NSDictionary *)errorDict
{
// Override me to do something here...
//
// Note: This method in invoked on our bonjour thread.
HTTPLogWarn(@"Failed to Publish Service: domain(%@) type(%@) name(%@) - %@",
[ns domain], [ns type], [ns name], errorDict);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Notifications
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* This method is automatically called when a notification of type HTTPConnectionDidDieNotification is posted.
* It allows us to remove the connection from our array.
**/
- (void)connectionDidDie:(NSNotification *)notification
{
// Note: This method is called on the connection queue that posted the notification
[connectionsLock lock];
HTTPLogTrace();
[connections removeObject:[notification object]];
[connectionsLock unlock];
}
/**
* This method is automatically called when a notification of type WebSocketDidDieNotification is posted.
* It allows us to remove the websocket from our array.
**/
- (void)webSocketDidDie:(NSNotification *)notification
{
// Note: This method is called on the connection queue that posted the notification
[webSocketsLock lock];
HTTPLogTrace();
[webSockets removeObject:[notification object]];
[webSocketsLock unlock];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Bonjour Thread
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* NSNetService is runloop based, so it requires a thread with a runloop.
* This gives us two options:
*
* - Use the main thread
* - Setup our own dedicated thread
*
* Since we have various blocks of code that need to synchronously access the netservice objects,
* using the main thread becomes troublesome and a potential for deadlock.
**/
static NSThread *bonjourThread;
+ (void)startBonjourThreadIfNeeded
{
HTTPLogTrace();
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
HTTPLogVerbose(@"%@: Starting bonjour thread...", THIS_FILE);
bonjourThread = [[NSThread alloc] initWithTarget:self
selector:@selector(bonjourThread)
object:nil];
[bonjourThread start];
});
}
+ (void)bonjourThread
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
HTTPLogVerbose(@"%@: BonjourThread: Started", THIS_FILE);
// We can't run the run loop unless it has an associated input source or a timer.
// So we'll just create a timer that will never fire - unless the server runs for 10,000 years.
[NSTimer scheduledTimerWithTimeInterval:DBL_MAX target:self selector:@selector(ignore:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] run];
HTTPLogVerbose(@"%@: BonjourThread: Aborted", THIS_FILE);
[pool release];
}
+ (void)performBonjourBlock:(dispatch_block_t)block
{
HTTPLogTrace();
NSAssert([NSThread currentThread] == bonjourThread, @"Executed on incorrect thread");
block();
}
+ (void)performBonjourBlock:(dispatch_block_t)block waitUntilDone:(BOOL)waitUntilDone
{
HTTPLogTrace();
dispatch_block_t bonjourBlock = Block_copy(block);
[self performSelector:@selector(performBonjourBlock:)
onThread:bonjourThread
withObject:bonjourBlock
waitUntilDone:waitUntilDone];
Block_release(bonjourBlock);
}
@end