GCDWebServer.m 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. /*
  2. Copyright (c) 2012-2014, Pierre-Olivier Latour
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. * Redistributions of source code must retain the above copyright
  7. notice, this list of conditions and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. * The name of Pierre-Olivier Latour may not be used to endorse
  12. or promote products derived from this software without specific
  13. prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  15. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  16. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17. DISCLAIMED. IN NO EVENT SHALL PIERRE-OLIVIER LATOUR BE LIABLE FOR ANY
  18. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  19. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  20. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  21. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  22. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  23. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. #import <TargetConditionals.h>
  26. #if TARGET_OS_IPHONE
  27. #import <MobileCoreServices/MobileCoreServices.h>
  28. #else
  29. #import <SystemConfiguration/SystemConfiguration.h>
  30. #endif
  31. #import <netinet/in.h>
  32. #import <ifaddrs.h>
  33. #import <net/if.h>
  34. #import <netdb.h>
  35. #import "GCDWebServerPrivate.h"
  36. #if TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR
  37. #define kDefaultPort 80
  38. #else
  39. #define kDefaultPort 8080
  40. #endif
  41. #define kMaxPendingConnections 16
  42. @interface GCDWebServer () {
  43. @private
  44. NSMutableArray* _handlers;
  45. NSUInteger _port;
  46. dispatch_source_t _source;
  47. CFNetServiceRef _service;
  48. #if !TARGET_OS_IPHONE
  49. BOOL _recording;
  50. #endif
  51. }
  52. @end
  53. @interface GCDWebServerHandler () {
  54. @private
  55. GCDWebServerMatchBlock _matchBlock;
  56. GCDWebServerProcessBlock _processBlock;
  57. }
  58. @end
  59. #ifndef __GCDWEBSERVER_LOGGING_HEADER__
  60. #ifdef NDEBUG
  61. GCDWebServerLogLevel GCDLogLevel = kGCDWebServerLogLevel_Info;
  62. #else
  63. GCDWebServerLogLevel GCDLogLevel = kGCDWebServerLogLevel_Debug;
  64. #endif
  65. #endif
  66. static NSDateFormatter* _dateFormatterRFC822 = nil;
  67. static NSDateFormatter* _dateFormatterISO8601 = nil;
  68. static dispatch_queue_t _dateFormatterQueue = NULL;
  69. #if !TARGET_OS_IPHONE
  70. static BOOL _run;
  71. #endif
  72. #ifndef __GCDWEBSERVER_LOGGING_HEADER__
  73. void GCDLogMessage(GCDWebServerLogLevel level, NSString* format, ...) {
  74. static const char* levelNames[] = {"DEBUG", "VERBOSE", "INFO", "WARNING", "ERROR", "EXCEPTION"};
  75. va_list arguments;
  76. va_start(arguments, format);
  77. NSString* message = [[NSString alloc] initWithFormat:format arguments:arguments];
  78. va_end(arguments);
  79. fprintf(stderr, "[%s] %s\n", levelNames[level], [message UTF8String]);
  80. ARC_RELEASE(message);
  81. }
  82. #endif
  83. NSString* GCDWebServerNormalizeHeaderValue(NSString* value) {
  84. if (value) {
  85. NSRange range = [value rangeOfString:@";"]; // Assume part before ";" separator is case-insensitive
  86. if (range.location != NSNotFound) {
  87. value = [[[value substringToIndex:range.location] lowercaseString] stringByAppendingString:[value substringFromIndex:range.location]];
  88. } else {
  89. value = [value lowercaseString];
  90. }
  91. }
  92. return value;
  93. }
  94. NSString* GCDWebServerTruncateHeaderValue(NSString* value) {
  95. DCHECK([value isEqualToString:GCDWebServerNormalizeHeaderValue(value)]);
  96. NSRange range = [value rangeOfString:@";"];
  97. return range.location != NSNotFound ? [value substringToIndex:range.location] : value;
  98. }
  99. NSString* GCDWebServerExtractHeaderValueParameter(NSString* value, NSString* name) {
  100. DCHECK([value isEqualToString:GCDWebServerNormalizeHeaderValue(value)]);
  101. NSString* parameter = nil;
  102. NSScanner* scanner = [[NSScanner alloc] initWithString:value];
  103. [scanner setCaseSensitive:NO]; // Assume parameter names are case-insensitive
  104. NSString* string = [NSString stringWithFormat:@"%@=", name];
  105. if ([scanner scanUpToString:string intoString:NULL]) {
  106. [scanner scanString:string intoString:NULL];
  107. if ([scanner scanString:@"\"" intoString:NULL]) {
  108. [scanner scanUpToString:@"\"" intoString:&parameter];
  109. } else {
  110. [scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString:&parameter];
  111. }
  112. }
  113. ARC_RELEASE(scanner);
  114. return parameter;
  115. }
  116. // http://www.w3schools.com/tags/ref_charactersets.asp
  117. NSStringEncoding GCDWebServerStringEncodingFromCharset(NSString* charset) {
  118. NSStringEncoding encoding = kCFStringEncodingInvalidId;
  119. if (charset) {
  120. encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)charset));
  121. }
  122. return (encoding != kCFStringEncodingInvalidId ? encoding : NSUTF8StringEncoding);
  123. }
  124. NSString* GCDWebServerFormatRFC822(NSDate* date) {
  125. __block NSString* string;
  126. dispatch_sync(_dateFormatterQueue, ^{
  127. string = [_dateFormatterRFC822 stringFromDate:date];
  128. });
  129. return string;
  130. }
  131. NSDate* GCDWebServerParseRFC822(NSString* string) {
  132. __block NSDate* date;
  133. dispatch_sync(_dateFormatterQueue, ^{
  134. date = [_dateFormatterRFC822 dateFromString:string];
  135. });
  136. return date;
  137. }
  138. NSString* GCDWebServerFormatISO8601(NSDate* date) {
  139. __block NSString* string;
  140. dispatch_sync(_dateFormatterQueue, ^{
  141. string = [_dateFormatterISO8601 stringFromDate:date];
  142. });
  143. return string;
  144. }
  145. NSDate* GCDWebServerParseISO8601(NSString* string) {
  146. __block NSDate* date;
  147. dispatch_sync(_dateFormatterQueue, ^{
  148. date = [_dateFormatterISO8601 dateFromString:string];
  149. });
  150. return date;
  151. }
  152. static inline BOOL _IsTextContentType(NSString* type) {
  153. return ([type hasPrefix:@"text/"] || [type hasPrefix:@"application/json"] || [type hasPrefix:@"application/xml"]);
  154. }
  155. NSString* GCDWebServerDescribeData(NSData* data, NSString* type) {
  156. if (_IsTextContentType(type)) {
  157. NSString* charset = GCDWebServerExtractHeaderValueParameter(type, @"charset");
  158. NSString* string = [[NSString alloc] initWithData:data encoding:GCDWebServerStringEncodingFromCharset(charset)];
  159. if (string) {
  160. return ARC_AUTORELEASE(string);
  161. }
  162. }
  163. return [NSString stringWithFormat:@"<%lu bytes>", (unsigned long)data.length];
  164. }
  165. NSString* GCDWebServerGetMimeTypeForExtension(NSString* extension) {
  166. static NSDictionary* _overrides = nil;
  167. if (_overrides == nil) {
  168. _overrides = [[NSDictionary alloc] initWithObjectsAndKeys:
  169. @"text/css", @"css",
  170. nil];
  171. }
  172. NSString* mimeType = nil;
  173. extension = [extension lowercaseString];
  174. if (extension.length) {
  175. mimeType = [_overrides objectForKey:extension];
  176. if (mimeType == nil) {
  177. CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (ARC_BRIDGE CFStringRef)extension, NULL);
  178. if (uti) {
  179. mimeType = ARC_BRIDGE_RELEASE(UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType));
  180. CFRelease(uti);
  181. }
  182. }
  183. }
  184. return mimeType ? mimeType : kGCDWebServerDefaultMimeType;
  185. }
  186. NSString* GCDWebServerEscapeURLString(NSString* string) {
  187. return ARC_BRIDGE_RELEASE(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(":@/?&=+"), kCFStringEncodingUTF8));
  188. }
  189. NSString* GCDWebServerUnescapeURLString(NSString* string) {
  190. return ARC_BRIDGE_RELEASE(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)string, CFSTR(""), kCFStringEncodingUTF8));
  191. }
  192. // http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
  193. NSDictionary* GCDWebServerParseURLEncodedForm(NSString* form) {
  194. NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
  195. NSScanner* scanner = [[NSScanner alloc] initWithString:form];
  196. [scanner setCharactersToBeSkipped:nil];
  197. while (1) {
  198. NSString* key = nil;
  199. if (![scanner scanUpToString:@"=" intoString:&key] || [scanner isAtEnd]) {
  200. break;
  201. }
  202. [scanner setScanLocation:([scanner scanLocation] + 1)];
  203. NSString* value = nil;
  204. if (![scanner scanUpToString:@"&" intoString:&value]) {
  205. break;
  206. }
  207. key = [key stringByReplacingOccurrencesOfString:@"+" withString:@" "];
  208. value = [value stringByReplacingOccurrencesOfString:@"+" withString:@" "];
  209. if (key && value) {
  210. [parameters setObject:GCDWebServerUnescapeURLString(value) forKey:GCDWebServerUnescapeURLString(key)];
  211. } else {
  212. DNOT_REACHED();
  213. }
  214. if ([scanner isAtEnd]) {
  215. break;
  216. }
  217. [scanner setScanLocation:([scanner scanLocation] + 1)];
  218. }
  219. ARC_RELEASE(scanner);
  220. return parameters;
  221. }
  222. NSString* GCDWebServerGetPrimaryIPv4Address() {
  223. NSString* address = nil;
  224. #if TARGET_OS_IPHONE
  225. #if !TARGET_IPHONE_SIMULATOR
  226. const char* primaryInterface = "en0"; // WiFi interface on iOS
  227. #endif
  228. #else
  229. const char* primaryInterface = NULL;
  230. SCDynamicStoreRef store = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("GCDWebServer"), NULL, NULL);
  231. if (store) {
  232. CFPropertyListRef info = SCDynamicStoreCopyValue(store, CFSTR("State:/Network/Global/IPv4"));
  233. if (info) {
  234. primaryInterface = [[NSString stringWithString:[(ARC_BRIDGE NSDictionary*)info objectForKey:@"PrimaryInterface"]] UTF8String];
  235. CFRelease(info);
  236. }
  237. CFRelease(store);
  238. }
  239. if (primaryInterface == NULL) {
  240. primaryInterface = "lo0";
  241. }
  242. #endif
  243. struct ifaddrs* list;
  244. if (getifaddrs(&list) >= 0) {
  245. for (struct ifaddrs* ifap = list; ifap; ifap = ifap->ifa_next) {
  246. #if TARGET_IPHONE_SIMULATOR
  247. if (strcmp(ifap->ifa_name, "en0") && strcmp(ifap->ifa_name, "en1")) // Assume en0 is Ethernet and en1 is WiFi since there is no way to use SystemConfiguration framework in iOS Simulator
  248. #else
  249. if (strcmp(ifap->ifa_name, primaryInterface))
  250. #endif
  251. {
  252. continue;
  253. }
  254. if ((ifap->ifa_flags & IFF_UP) && (ifap->ifa_addr->sa_family == AF_INET)) {
  255. char buffer[NI_MAXHOST];
  256. if (getnameinfo(ifap->ifa_addr, ifap->ifa_addr->sa_len, buffer, sizeof(buffer), NULL, 0, NI_NUMERICHOST | NI_NOFQDN) >= 0) {
  257. address = [NSString stringWithUTF8String:buffer];
  258. }
  259. break;
  260. }
  261. }
  262. freeifaddrs(list);
  263. }
  264. return address;
  265. }
  266. #if !TARGET_OS_IPHONE
  267. static void _SignalHandler(int signal) {
  268. _run = NO;
  269. printf("\n");
  270. }
  271. #endif
  272. @implementation GCDWebServerHandler
  273. @synthesize matchBlock=_matchBlock, processBlock=_processBlock;
  274. - (id)initWithMatchBlock:(GCDWebServerMatchBlock)matchBlock processBlock:(GCDWebServerProcessBlock)processBlock {
  275. if ((self = [super init])) {
  276. _matchBlock = [matchBlock copy];
  277. _processBlock = [processBlock copy];
  278. }
  279. return self;
  280. }
  281. - (void)dealloc {
  282. ARC_RELEASE(_matchBlock);
  283. ARC_RELEASE(_processBlock);
  284. ARC_DEALLOC(super);
  285. }
  286. @end
  287. @implementation GCDWebServer
  288. @synthesize handlers=_handlers, port=_port;
  289. #ifndef __GCDWEBSERVER_LOGGING_HEADER__
  290. + (void)load {
  291. const char* logLevel = getenv("logLevel");
  292. if (logLevel) {
  293. GCDLogLevel = atoi(logLevel);
  294. }
  295. }
  296. #endif
  297. // HTTP/1.1 server must use RFC822
  298. // TODO: Handle RFC 850 and ANSI C's asctime() format (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3)
  299. + (void)initialize {
  300. if (_dateFormatterRFC822 == nil) {
  301. DCHECK([NSThread isMainThread]); // NSDateFormatter should be initialized on main thread
  302. _dateFormatterRFC822 = [[NSDateFormatter alloc] init];
  303. _dateFormatterRFC822.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
  304. _dateFormatterRFC822.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'";
  305. _dateFormatterRFC822.locale = ARC_AUTORELEASE([[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]);
  306. DCHECK(_dateFormatterRFC822);
  307. }
  308. if (_dateFormatterISO8601 == nil) {
  309. DCHECK([NSThread isMainThread]); // NSDateFormatter should be initialized on main thread
  310. _dateFormatterISO8601 = [[NSDateFormatter alloc] init];
  311. _dateFormatterISO8601.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
  312. _dateFormatterISO8601.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss'+00:00'";
  313. _dateFormatterISO8601.locale = ARC_AUTORELEASE([[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]);
  314. DCHECK(_dateFormatterISO8601);
  315. }
  316. if (_dateFormatterQueue == NULL) {
  317. _dateFormatterQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL);
  318. DCHECK(_dateFormatterQueue);
  319. }
  320. }
  321. - (instancetype)init {
  322. if ((self = [super init])) {
  323. _handlers = [[NSMutableArray alloc] init];
  324. }
  325. return self;
  326. }
  327. - (void)dealloc {
  328. if (_source) {
  329. [self stop];
  330. }
  331. ARC_RELEASE(_handlers);
  332. ARC_DEALLOC(super);
  333. }
  334. - (NSString*)bonjourName {
  335. CFStringRef name = _service ? CFNetServiceGetName(_service) : NULL;
  336. return name && CFStringGetLength(name) ? ARC_BRIDGE_RELEASE(CFStringCreateCopy(kCFAllocatorDefault, name)) : nil;
  337. }
  338. - (void)addHandlerWithMatchBlock:(GCDWebServerMatchBlock)matchBlock processBlock:(GCDWebServerProcessBlock)handlerBlock {
  339. DCHECK(_source == NULL);
  340. GCDWebServerHandler* handler = [[GCDWebServerHandler alloc] initWithMatchBlock:matchBlock processBlock:handlerBlock];
  341. [_handlers insertObject:handler atIndex:0];
  342. ARC_RELEASE(handler);
  343. }
  344. - (void)removeAllHandlers {
  345. DCHECK(_source == NULL);
  346. [_handlers removeAllObjects];
  347. }
  348. - (BOOL)start {
  349. return [self startWithPort:kDefaultPort bonjourName:@""];
  350. }
  351. static void _NetServiceClientCallBack(CFNetServiceRef service, CFStreamError* error, void* info) {
  352. @autoreleasepool {
  353. if (error->error) {
  354. LOG_ERROR(@"Bonjour error %i (domain %i)", (int)error->error, (int)error->domain);
  355. } else {
  356. GCDWebServer* server = (ARC_BRIDGE GCDWebServer*)info;
  357. LOG_INFO(@"%@ now reachable at %@", [server class], server.bonjourServerURL);
  358. }
  359. }
  360. }
  361. - (BOOL)startWithPort:(NSUInteger)port bonjourName:(NSString*)name {
  362. DCHECK(_source == NULL);
  363. int listeningSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  364. if (listeningSocket > 0) {
  365. int yes = 1;
  366. setsockopt(listeningSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  367. struct sockaddr_in addr4;
  368. bzero(&addr4, sizeof(addr4));
  369. addr4.sin_len = sizeof(addr4);
  370. addr4.sin_family = AF_INET;
  371. addr4.sin_port = htons(port);
  372. addr4.sin_addr.s_addr = htonl(INADDR_ANY);
  373. if (bind(listeningSocket, (void*)&addr4, sizeof(addr4)) == 0) {
  374. if (listen(listeningSocket, kMaxPendingConnections) == 0) {
  375. _source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, listeningSocket, 0, kGCDWebServerGCDQueue);
  376. dispatch_source_set_cancel_handler(_source, ^{
  377. @autoreleasepool {
  378. int result = close(listeningSocket);
  379. if (result != 0) {
  380. LOG_ERROR(@"Failed closing socket (%i): %s", errno, strerror(errno));
  381. } else {
  382. LOG_DEBUG(@"Closed listening socket");
  383. }
  384. }
  385. });
  386. dispatch_source_set_event_handler(_source, ^{
  387. @autoreleasepool {
  388. struct sockaddr remoteSockAddr;
  389. socklen_t remoteAddrLen = sizeof(remoteSockAddr);
  390. int socket = accept(listeningSocket, &remoteSockAddr, &remoteAddrLen);
  391. if (socket > 0) {
  392. NSData* remoteAddress = [NSData dataWithBytes:&remoteSockAddr length:remoteAddrLen];
  393. struct sockaddr localSockAddr;
  394. socklen_t localAddrLen = sizeof(localSockAddr);
  395. NSData* localAddress = nil;
  396. if (getsockname(socket, &localSockAddr, &localAddrLen) == 0) {
  397. localAddress = [NSData dataWithBytes:&localSockAddr length:localAddrLen];
  398. } else {
  399. DNOT_REACHED();
  400. }
  401. int noSigPipe = 1;
  402. setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, sizeof(noSigPipe)); // Make sure this socket cannot generate SIG_PIPE
  403. Class connectionClass = [[self class] connectionClass];
  404. GCDWebServerConnection* connection = [[connectionClass alloc] initWithServer:self localAddress:localAddress remoteAddress:remoteAddress socket:socket]; // Connection will automatically retain itself while opened
  405. #if __has_feature(objc_arc)
  406. [connection self]; // Prevent compiler from complaining about unused variable / useless statement
  407. #else
  408. [connection release];
  409. #endif
  410. } else {
  411. LOG_ERROR(@"Failed accepting socket (%i): %s", errno, strerror(errno));
  412. }
  413. }
  414. });
  415. if (port == 0) { // Determine the actual port we are listening on
  416. struct sockaddr addr;
  417. socklen_t addrlen = sizeof(addr);
  418. if (getsockname(listeningSocket, &addr, &addrlen) == 0) {
  419. struct sockaddr_in* sockaddr = (struct sockaddr_in*)&addr;
  420. _port = ntohs(sockaddr->sin_port);
  421. } else {
  422. LOG_ERROR(@"Failed retrieving socket address (%i): %s", errno, strerror(errno));
  423. }
  424. } else {
  425. _port = port;
  426. }
  427. if (name) {
  428. _service = CFNetServiceCreate(kCFAllocatorDefault, CFSTR("local."), CFSTR("_http._tcp"), (ARC_BRIDGE CFStringRef)name, (SInt32)_port);
  429. if (_service) {
  430. CFNetServiceClientContext context = {0, (ARC_BRIDGE void*)self, NULL, NULL, NULL};
  431. CFNetServiceSetClient(_service, _NetServiceClientCallBack, &context);
  432. CFNetServiceScheduleWithRunLoop(_service, CFRunLoopGetMain(), kCFRunLoopCommonModes);
  433. CFStreamError error = {0};
  434. CFNetServiceRegisterWithOptions(_service, 0, &error);
  435. } else {
  436. LOG_ERROR(@"Failed creating CFNetService");
  437. }
  438. }
  439. dispatch_resume(_source);
  440. LOG_INFO(@"%@ started on port %i and reachable at %@", [self class], (int)_port, self.serverURL);
  441. } else {
  442. LOG_ERROR(@"Failed listening on socket (%i): %s", errno, strerror(errno));
  443. close(listeningSocket);
  444. }
  445. } else {
  446. LOG_ERROR(@"Failed binding socket (%i): %s", errno, strerror(errno));
  447. close(listeningSocket);
  448. }
  449. } else {
  450. LOG_ERROR(@"Failed creating socket (%i): %s", errno, strerror(errno));
  451. }
  452. return (_source ? YES : NO);
  453. }
  454. - (BOOL)isRunning {
  455. return (_source ? YES : NO);
  456. }
  457. - (void)stop {
  458. DCHECK(_source != NULL);
  459. if (_source) {
  460. if (_service) {
  461. CFNetServiceUnscheduleFromRunLoop(_service, CFRunLoopGetMain(), kCFRunLoopCommonModes);
  462. CFNetServiceSetClient(_service, NULL, NULL);
  463. CFRelease(_service);
  464. _service = NULL;
  465. }
  466. dispatch_source_cancel(_source); // This will close the socket
  467. ARC_DISPATCH_RELEASE(_source);
  468. _source = NULL;
  469. LOG_INFO(@"%@ stopped", [self class]);
  470. }
  471. _port = 0;
  472. }
  473. @end
  474. @implementation GCDWebServer (Subclassing)
  475. + (Class)connectionClass {
  476. return [GCDWebServerConnection class];
  477. }
  478. + (NSString*)serverName {
  479. return NSStringFromClass(self);
  480. }
  481. + (BOOL)shouldAutomaticallyMapHEADToGET {
  482. return YES;
  483. }
  484. @end
  485. @implementation GCDWebServer (Extensions)
  486. #if !TARGET_OS_IPHONE
  487. - (void)setRecordingEnabled:(BOOL)flag {
  488. _recording = flag;
  489. }
  490. - (BOOL)isRecordingEnabled {
  491. return _recording;
  492. }
  493. #endif
  494. - (NSURL*)serverURL {
  495. if (_source) {
  496. NSString* ipAddress = GCDWebServerGetPrimaryIPv4Address();
  497. if (ipAddress) {
  498. if (_port != 80) {
  499. return [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%i/", ipAddress, (int)_port]];
  500. } else {
  501. return [NSURL URLWithString:[NSString stringWithFormat:@"http://%@/", ipAddress]];
  502. }
  503. }
  504. }
  505. return nil;
  506. }
  507. - (NSURL*)bonjourServerURL {
  508. if (_source && _service) {
  509. CFStringRef name = CFNetServiceGetName(_service);
  510. if (name && CFStringGetLength(name)) {
  511. if (_port != 80) {
  512. return [NSURL URLWithString:[NSString stringWithFormat:@"http://%@.local:%i/", name, (int)_port]];
  513. } else {
  514. return [NSURL URLWithString:[NSString stringWithFormat:@"http://%@.local/", name]];
  515. }
  516. }
  517. }
  518. return nil;
  519. }
  520. #if !TARGET_OS_IPHONE
  521. - (BOOL)runWithPort:(NSUInteger)port {
  522. BOOL success = NO;
  523. _run = YES;
  524. void (*handler)(int) = signal(SIGINT, _SignalHandler);
  525. if (handler != SIG_ERR) {
  526. if ([self startWithPort:port bonjourName:@""]) {
  527. while (_run) {
  528. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0, true);
  529. }
  530. [self stop];
  531. success = YES;
  532. }
  533. signal(SIGINT, handler);
  534. }
  535. return success;
  536. }
  537. static CFHTTPMessageRef _CreateHTTPMessageFromFileDump(NSString* path, BOOL isRequest) {
  538. NSData* data = [NSData dataWithContentsOfFile:path];
  539. if (data) {
  540. CFHTTPMessageRef message = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, isRequest);
  541. if (CFHTTPMessageAppendBytes(message, data.bytes, data.length)) {
  542. return message;
  543. }
  544. CFRelease(message);
  545. }
  546. return NULL;
  547. }
  548. static CFHTTPMessageRef _CreateHTTPMessageFromHTTPRequestResponse(CFHTTPMessageRef request) {
  549. CFHTTPMessageRef response = NULL;
  550. CFReadStreamRef stream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request);
  551. if (CFReadStreamOpen(stream)) {
  552. CFMutableDataRef data = CFDataCreateMutable(kCFAllocatorDefault, 0);
  553. CFDataSetLength(data, 256 * 1024);
  554. CFIndex length = 0;
  555. while (1) {
  556. CFIndex result = CFReadStreamRead(stream, CFDataGetMutableBytePtr(data) + length, CFDataGetLength(data) - length);
  557. if (result <= 0) {
  558. break;
  559. }
  560. length += result;
  561. if (length >= CFDataGetLength(data)) {
  562. CFDataSetLength(data, 2 * CFDataGetLength(data));
  563. }
  564. }
  565. if (CFReadStreamGetStatus(stream) == kCFStreamStatusAtEnd) {
  566. response = (CFHTTPMessageRef)CFReadStreamCopyProperty(stream, kCFStreamPropertyHTTPResponseHeader);
  567. if (response) {
  568. CFDataSetLength(data, length);
  569. CFHTTPMessageSetBody(response, data);
  570. }
  571. }
  572. CFRelease(data);
  573. CFReadStreamClose(stream);
  574. CFRelease(stream);
  575. }
  576. return response;
  577. }
  578. static void _LogResult(NSString* format, ...) {
  579. va_list arguments;
  580. va_start(arguments, format);
  581. NSString* message = [[NSString alloc] initWithFormat:format arguments:arguments];
  582. va_end(arguments);
  583. fprintf(stdout, "%s\n", [message UTF8String]);
  584. ARC_RELEASE(message);
  585. }
  586. - (NSInteger)runTestsInDirectory:(NSString*)path withPort:(NSUInteger)port {
  587. NSInteger result = -1;
  588. if ([self startWithPort:port bonjourName:nil]) {
  589. result = 0;
  590. NSArray* files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
  591. for (NSString* requestFile in files) {
  592. if (![requestFile hasSuffix:@".request"]) {
  593. continue;
  594. }
  595. @autoreleasepool {
  596. NSString* index = [[requestFile componentsSeparatedByString:@"-"] firstObject];
  597. BOOL success = NO;
  598. CFHTTPMessageRef request = _CreateHTTPMessageFromFileDump([path stringByAppendingPathComponent:requestFile], YES);
  599. if (request) {
  600. _LogResult(@"[%i] %@ %@", (int)[index integerValue], ARC_BRIDGE_RELEASE(CFHTTPMessageCopyRequestMethod(request)), [ARC_BRIDGE_RELEASE(CFHTTPMessageCopyRequestURL(request)) path]);
  601. NSString* prefix = [index stringByAppendingString:@"-"];
  602. for (NSString* responseFile in files) {
  603. if ([responseFile hasPrefix:prefix] && [responseFile hasSuffix:@".response"]) {
  604. CFHTTPMessageRef expectedResponse = _CreateHTTPMessageFromFileDump([path stringByAppendingPathComponent:responseFile], NO);
  605. if (expectedResponse) {
  606. CFHTTPMessageRef actualResponse = _CreateHTTPMessageFromHTTPRequestResponse(request);
  607. if (actualResponse) {
  608. success = YES;
  609. CFIndex expectedStatusCode = CFHTTPMessageGetResponseStatusCode(expectedResponse);
  610. CFIndex actualStatusCode = CFHTTPMessageGetResponseStatusCode(actualResponse);
  611. if (actualStatusCode != expectedStatusCode) {
  612. _LogResult(@" Status code not matching:\n Expected: %i\n Actual: %i", (int)expectedStatusCode, (int)actualStatusCode);
  613. success = NO;
  614. }
  615. NSDictionary* expectedHeaders = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyAllHeaderFields(expectedResponse));
  616. NSDictionary* actualHeaders = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyAllHeaderFields(actualResponse));
  617. for (NSString* expectedHeader in expectedHeaders) {
  618. if ([expectedHeader isEqualToString:@"Date"]) {
  619. continue;
  620. }
  621. NSString* expectedValue = [expectedHeaders objectForKey:expectedHeader];
  622. NSString* actualValue = [actualHeaders objectForKey:expectedHeader];
  623. if (![actualValue isEqualToString:expectedValue]) {
  624. _LogResult(@" Header '%@' not matching:\n Expected: \"%@\"\n Actual: \"%@\"", expectedHeader, expectedValue, actualValue);
  625. success = NO;
  626. }
  627. }
  628. for (NSString* actualHeader in actualHeaders) {
  629. if (![expectedHeaders objectForKey:actualHeader]) {
  630. _LogResult(@" Header '%@' not matching:\n Expected: \"%@\"\n Actual: \"%@\"", actualHeader, nil, [actualHeaders objectForKey:actualHeader]);
  631. success = NO;
  632. }
  633. }
  634. NSData* expectedBody = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyBody(expectedResponse));
  635. NSData* actualBody = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyBody(actualResponse));
  636. if (![actualBody isEqualToData:expectedBody]) {
  637. _LogResult(@" Bodies not matching:\n Expected: %lu bytes\n Actual: %lu bytes", (unsigned long)expectedBody.length, (unsigned long)actualBody.length);
  638. success = NO;
  639. if (_IsTextContentType([expectedHeaders objectForKey:@"Content-Type"])) {
  640. NSString* expectedPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[[NSProcessInfo processInfo] globallyUniqueString] stringByAppendingPathExtension:@"txt"]];
  641. NSString* actualPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[[NSProcessInfo processInfo] globallyUniqueString] stringByAppendingPathExtension:@"txt"]];
  642. if ([expectedBody writeToFile:expectedPath atomically:YES] && [actualBody writeToFile:actualPath atomically:YES]) {
  643. NSTask* task = [[NSTask alloc] init];
  644. [task setLaunchPath:@"/usr/bin/opendiff"];
  645. [task setArguments:@[expectedPath, actualPath]];
  646. [task launch];
  647. ARC_RELEASE(task);
  648. }
  649. }
  650. }
  651. CFRelease(actualResponse);
  652. }
  653. CFRelease(expectedResponse);
  654. }
  655. break;
  656. }
  657. }
  658. CFRelease(request);
  659. }
  660. _LogResult(@"");
  661. if (!success) {
  662. ++result;
  663. }
  664. }
  665. }
  666. [self stop];
  667. }
  668. return result;
  669. }
  670. #endif
  671. @end
  672. @implementation GCDWebServer (Handlers)
  673. - (void)addDefaultHandlerForMethod:(NSString*)method requestClass:(Class)aClass processBlock:(GCDWebServerProcessBlock)block {
  674. [self addHandlerWithMatchBlock:^GCDWebServerRequest *(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) {
  675. if (![requestMethod isEqualToString:method]) {
  676. return nil;
  677. }
  678. return ARC_AUTORELEASE([[aClass alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery]);
  679. } processBlock:block];
  680. }
  681. - (void)addHandlerForMethod:(NSString*)method path:(NSString*)path requestClass:(Class)aClass processBlock:(GCDWebServerProcessBlock)block {
  682. if ([path hasPrefix:@"/"] && [aClass isSubclassOfClass:[GCDWebServerRequest class]]) {
  683. [self addHandlerWithMatchBlock:^GCDWebServerRequest *(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) {
  684. if (![requestMethod isEqualToString:method]) {
  685. return nil;
  686. }
  687. if ([urlPath caseInsensitiveCompare:path] != NSOrderedSame) {
  688. return nil;
  689. }
  690. return ARC_AUTORELEASE([[aClass alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery]);
  691. } processBlock:block];
  692. } else {
  693. DNOT_REACHED();
  694. }
  695. }
  696. - (void)addHandlerForMethod:(NSString*)method pathRegex:(NSString*)regex requestClass:(Class)aClass processBlock:(GCDWebServerProcessBlock)block {
  697. NSRegularExpression* expression = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:NULL];
  698. if (expression && [aClass isSubclassOfClass:[GCDWebServerRequest class]]) {
  699. [self addHandlerWithMatchBlock:^GCDWebServerRequest *(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) {
  700. if (![requestMethod isEqualToString:method]) {
  701. return nil;
  702. }
  703. if ([expression firstMatchInString:urlPath options:0 range:NSMakeRange(0, urlPath.length)] == nil) {
  704. return nil;
  705. }
  706. return ARC_AUTORELEASE([[aClass alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery]);
  707. } processBlock:block];
  708. } else {
  709. DNOT_REACHED();
  710. }
  711. }
  712. @end
  713. @implementation GCDWebServer (GETHandlers)
  714. - (void)addGETHandlerForPath:(NSString*)path staticData:(NSData*)staticData contentType:(NSString*)contentType cacheAge:(NSUInteger)cacheAge {
  715. GCDWebServerResponse* response = [GCDWebServerDataResponse responseWithData:staticData contentType:contentType];
  716. response.cacheControlMaxAge = cacheAge;
  717. [self addHandlerForMethod:@"GET" path:path requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
  718. return response;
  719. }];
  720. }
  721. - (void)addGETHandlerForPath:(NSString*)path filePath:(NSString*)filePath isAttachment:(BOOL)isAttachment cacheAge:(NSUInteger)cacheAge allowRangeRequests:(BOOL)allowRangeRequests {
  722. [self addHandlerForMethod:@"GET" path:path requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
  723. GCDWebServerResponse* response = nil;
  724. if (allowRangeRequests) {
  725. response = [GCDWebServerFileResponse responseWithFile:filePath byteRange:request.byteRange isAttachment:isAttachment];
  726. [response setValue:@"bytes" forAdditionalHeader:@"Accept-Ranges"];
  727. } else {
  728. response = [GCDWebServerFileResponse responseWithFile:filePath isAttachment:isAttachment];
  729. }
  730. response.cacheControlMaxAge = cacheAge;
  731. return response;
  732. }];
  733. }
  734. - (GCDWebServerResponse*)_responseWithContentsOfDirectory:(NSString*)path {
  735. NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:path];
  736. if (enumerator == nil) {
  737. return nil;
  738. }
  739. NSMutableString* html = [NSMutableString string];
  740. [html appendString:@"<!DOCTYPE html>\n"];
  741. [html appendString:@"<html><head><meta charset=\"utf-8\"></head><body>\n"];
  742. [html appendString:@"<ul>\n"];
  743. for (NSString* file in enumerator) {
  744. if (![file hasPrefix:@"."]) {
  745. NSString* type = [[enumerator fileAttributes] objectForKey:NSFileType];
  746. NSString* escapedFile = [file stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  747. DCHECK(escapedFile);
  748. if ([type isEqualToString:NSFileTypeRegular]) {
  749. [html appendFormat:@"<li><a href=\"%@\">%@</a></li>\n", escapedFile, file];
  750. } else if ([type isEqualToString:NSFileTypeDirectory]) {
  751. [html appendFormat:@"<li><a href=\"%@/\">%@/</a></li>\n", escapedFile, file];
  752. }
  753. }
  754. [enumerator skipDescendents];
  755. }
  756. [html appendString:@"</ul>\n"];
  757. [html appendString:@"</body></html>\n"];
  758. return [GCDWebServerDataResponse responseWithHTML:html];
  759. }
  760. - (void)addGETHandlerForBasePath:(NSString*)basePath directoryPath:(NSString*)directoryPath indexFilename:(NSString*)indexFilename cacheAge:(NSUInteger)cacheAge allowRangeRequests:(BOOL)allowRangeRequests {
  761. if ([basePath hasPrefix:@"/"] && [basePath hasSuffix:@"/"]) {
  762. #if __has_feature(objc_arc)
  763. GCDWebServer* __unsafe_unretained server = self;
  764. #else
  765. __block GCDWebServer* server = self;
  766. #endif
  767. [self addHandlerWithMatchBlock:^GCDWebServerRequest *(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) {
  768. if (![requestMethod isEqualToString:@"GET"]) {
  769. return nil;
  770. }
  771. if (![urlPath hasPrefix:basePath]) {
  772. return nil;
  773. }
  774. return ARC_AUTORELEASE([[GCDWebServerRequest alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery]);
  775. } processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
  776. GCDWebServerResponse* response = nil;
  777. NSString* filePath = [directoryPath stringByAppendingPathComponent:[request.path substringFromIndex:basePath.length]];
  778. BOOL isDirectory;
  779. if ([[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory]) {
  780. if (isDirectory) {
  781. if (indexFilename) {
  782. NSString* indexPath = [filePath stringByAppendingPathComponent:indexFilename];
  783. if ([[NSFileManager defaultManager] fileExistsAtPath:indexPath isDirectory:&isDirectory] && !isDirectory) {
  784. return [GCDWebServerFileResponse responseWithFile:indexPath];
  785. }
  786. }
  787. response = [server _responseWithContentsOfDirectory:filePath];
  788. } else {
  789. if (allowRangeRequests) {
  790. response = [GCDWebServerFileResponse responseWithFile:filePath byteRange:request.byteRange];
  791. [response setValue:@"bytes" forAdditionalHeader:@"Accept-Ranges"];
  792. } else {
  793. response = [GCDWebServerFileResponse responseWithFile:filePath];
  794. }
  795. }
  796. }
  797. if (response) {
  798. response.cacheControlMaxAge = cacheAge;
  799. } else {
  800. response = [GCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_NotFound];
  801. }
  802. return response;
  803. }];
  804. } else {
  805. DNOT_REACHED();
  806. }
  807. }
  808. @end
  809. @implementation GCDWebServer (Logging)
  810. #ifndef __GCDWEBSERVER_LOGGING_HEADER__
  811. + (void)setLogLevel:(GCDWebServerLogLevel)level {
  812. GCDLogLevel = level;
  813. }
  814. #endif
  815. - (void)logVerbose:(NSString*)format, ... {
  816. va_list arguments;
  817. va_start(arguments, format);
  818. NSString* message = [[NSString alloc] initWithFormat:format arguments:arguments];
  819. va_end(arguments);
  820. LOG_VERBOSE(@"%@", message);
  821. ARC_RELEASE(message);
  822. }
  823. - (void)logInfo:(NSString*)format, ... {
  824. va_list arguments;
  825. va_start(arguments, format);
  826. NSString* message = [[NSString alloc] initWithFormat:format arguments:arguments];
  827. va_end(arguments);
  828. LOG_INFO(@"%@", message);
  829. ARC_RELEASE(message);
  830. }
  831. - (void)logWarning:(NSString*)format, ... {
  832. va_list arguments;
  833. va_start(arguments, format);
  834. NSString* message = [[NSString alloc] initWithFormat:format arguments:arguments];
  835. va_end(arguments);
  836. LOG_WARNING(@"%@", message);
  837. ARC_RELEASE(message);
  838. }
  839. - (void)logError:(NSString*)format, ... {
  840. va_list arguments;
  841. va_start(arguments, format);
  842. NSString* message = [[NSString alloc] initWithFormat:format arguments:arguments];
  843. va_end(arguments);
  844. LOG_ERROR(@"%@", message);
  845. ARC_RELEASE(message);
  846. }
  847. @end