GCDWebServer.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /*
  2. Copyright (c) 2012-2013, 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. * Neither the name of the <organization> nor the
  12. names of its contributors may be used to endorse or promote products
  13. derived from this software without specific 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 <COPYRIGHT HOLDER> 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. #endif
  29. #import <netinet/in.h>
  30. #import "GCDWebServerPrivate.h"
  31. static BOOL _run;
  32. NSString* GCDWebServerGetMimeTypeForExtension(NSString* extension) {
  33. static NSDictionary* _overrides = nil;
  34. if (_overrides == nil) {
  35. _overrides = [[NSDictionary alloc] initWithObjectsAndKeys:
  36. @"text/css", @"css",
  37. nil];
  38. }
  39. NSString* mimeType = nil;
  40. extension = [extension lowercaseString];
  41. if (extension.length) {
  42. mimeType = [_overrides objectForKey:extension];
  43. if (mimeType == nil) {
  44. CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)extension, NULL);
  45. if (uti) {
  46. mimeType = [(id)UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType) autorelease];
  47. CFRelease(uti);
  48. }
  49. }
  50. }
  51. return mimeType;
  52. }
  53. NSString* GCDWebServerUnescapeURLString(NSString* string) {
  54. return [(id)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)string, CFSTR(""),
  55. kCFStringEncodingUTF8) autorelease];
  56. }
  57. NSDictionary* GCDWebServerParseURLEncodedForm(NSString* form) {
  58. NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
  59. NSScanner* scanner = [[NSScanner alloc] initWithString:form];
  60. [scanner setCharactersToBeSkipped:nil];
  61. while (1) {
  62. NSString* key = nil;
  63. if (![scanner scanUpToString:@"=" intoString:&key] || [scanner isAtEnd]) {
  64. break;
  65. }
  66. [scanner setScanLocation:([scanner scanLocation] + 1)];
  67. NSString* value = nil;
  68. if (![scanner scanUpToString:@"&" intoString:&value]) {
  69. break;
  70. }
  71. key = [key stringByReplacingOccurrencesOfString:@"+" withString:@" "];
  72. value = [value stringByReplacingOccurrencesOfString:@"+" withString:@" "];
  73. [parameters setObject:GCDWebServerUnescapeURLString(value) forKey:GCDWebServerUnescapeURLString(key)];
  74. if ([scanner isAtEnd]) {
  75. break;
  76. }
  77. [scanner setScanLocation:([scanner scanLocation] + 1)];
  78. }
  79. [scanner release];
  80. return parameters;
  81. }
  82. static void _SignalHandler(int signal) {
  83. _run = NO;
  84. printf("\n");
  85. }
  86. @implementation GCDWebServerHandler
  87. @synthesize matchBlock=_matchBlock, processBlock=_processBlock;
  88. - (id)initWithMatchBlock:(GCDWebServerMatchBlock)matchBlock processBlock:(GCDWebServerProcessBlock)processBlock {
  89. if ((self = [super init])) {
  90. _matchBlock = Block_copy(matchBlock);
  91. _processBlock = Block_copy(processBlock);
  92. }
  93. return self;
  94. }
  95. - (void)dealloc {
  96. Block_release(_matchBlock);
  97. Block_release(_processBlock);
  98. [super dealloc];
  99. }
  100. @end
  101. @implementation GCDWebServer
  102. @synthesize handlers=_handlers, port=_port;
  103. + (void)initialize {
  104. [GCDWebServerConnection class]; // Initialize class immediately to make sure it happens on the main thread
  105. }
  106. - (id)init {
  107. if ((self = [super init])) {
  108. _handlers = [[NSMutableArray alloc] init];
  109. }
  110. return self;
  111. }
  112. - (void)dealloc {
  113. if (_runLoop) {
  114. [self stop];
  115. }
  116. [_handlers release];
  117. [super dealloc];
  118. }
  119. - (void)addHandlerWithMatchBlock:(GCDWebServerMatchBlock)matchBlock processBlock:(GCDWebServerProcessBlock)handlerBlock {
  120. DCHECK(_runLoop == nil);
  121. GCDWebServerHandler* handler = [[GCDWebServerHandler alloc] initWithMatchBlock:matchBlock processBlock:handlerBlock];
  122. [_handlers insertObject:handler atIndex:0];
  123. [handler release];
  124. }
  125. - (void)removeAllHandlers {
  126. DCHECK(_runLoop == nil);
  127. [_handlers removeAllObjects];
  128. }
  129. - (BOOL)start {
  130. return [self startWithRunloop:[NSRunLoop mainRunLoop] port:8080 bonjourName:@""];
  131. }
  132. static void _NetServiceClientCallBack(CFNetServiceRef service, CFStreamError* error, void* info) {
  133. @autoreleasepool {
  134. if (error->error) {
  135. LOG_ERROR(@"Bonjour error %i (domain %i)", error->error, (int)error->domain);
  136. } else {
  137. LOG_VERBOSE(@"Registered Bonjour service \"%@\" with type '%@' on port %i", CFNetServiceGetName(service), CFNetServiceGetType(service), CFNetServiceGetPortNumber(service));
  138. }
  139. }
  140. }
  141. static void _SocketCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void* data, void* info) {
  142. if (type == kCFSocketAcceptCallBack) {
  143. CFSocketNativeHandle handle = *(CFSocketNativeHandle*)data;
  144. int set = 1;
  145. setsockopt(handle, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int)); // Make sure this socket cannot generate SIG_PIPE
  146. @autoreleasepool {
  147. Class class = [[(GCDWebServer*)info class] connectionClass];
  148. GCDWebServerConnection* connection = [[class alloc] initWithServer:(GCDWebServer*)info address:(NSData*)address socket:handle];
  149. [connection release]; // Connection will automatically retain itself while opened
  150. }
  151. } else {
  152. DNOT_REACHED();
  153. }
  154. }
  155. - (BOOL)startWithRunloop:(NSRunLoop*)runloop port:(NSUInteger)port bonjourName:(NSString*)name {
  156. DCHECK(runloop);
  157. DCHECK(port);
  158. DCHECK(_runLoop == nil);
  159. CFSocketContext context = {0, self, NULL, NULL, NULL};
  160. _socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, _SocketCallBack, &context);
  161. if (_socket) {
  162. int yes = 1;
  163. setsockopt(CFSocketGetNative(_socket), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  164. struct sockaddr_in addr4;
  165. bzero(&addr4, sizeof(addr4));
  166. addr4.sin_len = sizeof(addr4);
  167. addr4.sin_family = AF_INET;
  168. addr4.sin_port = htons(port);
  169. addr4.sin_addr.s_addr = htonl(INADDR_ANY);
  170. if (CFSocketSetAddress(_socket, (CFDataRef)[NSData dataWithBytes:&addr4 length:sizeof(addr4)]) == kCFSocketSuccess) {
  171. CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, _socket, 0);
  172. CFRunLoopAddSource([runloop getCFRunLoop], source, kCFRunLoopCommonModes);
  173. CFRelease(source);
  174. if (name) {
  175. _service = CFNetServiceCreate(kCFAllocatorDefault, CFSTR("local."), CFSTR("_http._tcp"), (CFStringRef)name, port);
  176. if (_service) {
  177. CFNetServiceClientContext context = {0, self, NULL, NULL, NULL};
  178. CFNetServiceSetClient(_service, _NetServiceClientCallBack, &context);
  179. CFNetServiceScheduleWithRunLoop(_service, [runloop getCFRunLoop], kCFRunLoopCommonModes);
  180. CFStreamError error = {0};
  181. CFNetServiceRegisterWithOptions(_service, 0, &error);
  182. } else {
  183. LOG_ERROR(@"Failed creating CFNetService");
  184. }
  185. }
  186. _port = port;
  187. _runLoop = [runloop retain];
  188. LOG_VERBOSE(@"%@ started on port %i", [self class], (int)port);
  189. } else {
  190. LOG_ERROR(@"Failed binding socket");
  191. CFRelease(_socket);
  192. _socket = NULL;
  193. }
  194. } else {
  195. LOG_ERROR(@"Failed creating CFSocket");
  196. }
  197. return (_runLoop != nil ? YES : NO);
  198. }
  199. - (BOOL)isRunning {
  200. return (_runLoop != nil ? YES : NO);
  201. }
  202. - (void)stop {
  203. DCHECK(_runLoop != nil);
  204. if (_socket) {
  205. if (_service) {
  206. CFNetServiceUnscheduleFromRunLoop(_service, [_runLoop getCFRunLoop], kCFRunLoopCommonModes);
  207. CFNetServiceSetClient(_service, NULL, NULL);
  208. CFRelease(_service);
  209. }
  210. CFSocketInvalidate(_socket);
  211. CFRelease(_socket);
  212. _socket = NULL;
  213. LOG_VERBOSE(@"%@ stopped", [self class]);
  214. }
  215. [_runLoop release];
  216. _runLoop = nil;
  217. _port = 0;
  218. }
  219. @end
  220. @implementation GCDWebServer (Subclassing)
  221. + (Class)connectionClass {
  222. return [GCDWebServerConnection class];
  223. }
  224. + (NSString*)serverName {
  225. return NSStringFromClass(self);
  226. }
  227. @end
  228. @implementation GCDWebServer (Extensions)
  229. - (BOOL)runWithPort:(NSUInteger)port {
  230. BOOL success = NO;
  231. _run = YES;
  232. void* handler = signal(SIGINT, _SignalHandler);
  233. if (handler != SIG_ERR) {
  234. if ([self startWithRunloop:[NSRunLoop currentRunLoop] port:port bonjourName:@""]) {
  235. while (_run) {
  236. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
  237. }
  238. [self stop];
  239. success = YES;
  240. }
  241. signal(SIGINT, handler);
  242. }
  243. return success;
  244. }
  245. @end
  246. @implementation GCDWebServer (Handlers)
  247. - (void)addDefaultHandlerForMethod:(NSString*)method requestClass:(Class)class processBlock:(GCDWebServerProcessBlock)block {
  248. [self addHandlerWithMatchBlock:^GCDWebServerRequest *(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) {
  249. return [[[class alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery] autorelease];
  250. } processBlock:block];
  251. }
  252. - (GCDWebServerResponse*)_responseWithContentsOfFile:(NSString*)path {
  253. return [GCDWebServerFileResponse responseWithFile:path];
  254. }
  255. - (GCDWebServerResponse*)_responseWithContentsOfDirectory:(NSString*)path {
  256. NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:path];
  257. if (enumerator == nil) {
  258. return nil;
  259. }
  260. NSMutableString* html = [NSMutableString string];
  261. [html appendString:@"<html><body>\n"];
  262. [html appendString:@"<ul>\n"];
  263. for (NSString* file in enumerator) {
  264. if (![file hasPrefix:@"."]) {
  265. NSString* type = [[enumerator fileAttributes] objectForKey:NSFileType];
  266. NSString* escapedFile = [file stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  267. DCHECK(escapedFile);
  268. if ([type isEqualToString:NSFileTypeRegular]) {
  269. [html appendFormat:@"<li><a href=\"%@\">%@</a></li>\n", escapedFile, file];
  270. } else if ([type isEqualToString:NSFileTypeDirectory]) {
  271. [html appendFormat:@"<li><a href=\"%@/\">%@/</a></li>\n", escapedFile, file];
  272. }
  273. }
  274. [enumerator skipDescendents];
  275. }
  276. [html appendString:@"</ul>\n"];
  277. [html appendString:@"</body></html>\n"];
  278. return [GCDWebServerDataResponse responseWithHTML:html];
  279. }
  280. - (void)addHandlerForBasePath:(NSString*)basePath localPath:(NSString*)localPath indexFilename:(NSString*)indexFilename cacheAge:(NSUInteger)cacheAge {
  281. if ([basePath hasPrefix:@"/"] && [basePath hasSuffix:@"/"]) {
  282. [self addHandlerWithMatchBlock:^GCDWebServerRequest *(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) {
  283. if (![requestMethod isEqualToString:@"GET"]) {
  284. return nil;
  285. }
  286. if (![urlPath hasPrefix:basePath]) {
  287. return nil;
  288. }
  289. return [[[GCDWebServerRequest alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery] autorelease];
  290. } processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
  291. GCDWebServerResponse* response = nil;
  292. NSString* filePath = [localPath stringByAppendingPathComponent:[request.path substringFromIndex:basePath.length]];
  293. BOOL isDirectory;
  294. if ([[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory]) {
  295. if (isDirectory) {
  296. if (indexFilename) {
  297. NSString* indexPath = [filePath stringByAppendingPathComponent:indexFilename];
  298. if ([[NSFileManager defaultManager] fileExistsAtPath:indexPath isDirectory:&isDirectory] && !isDirectory) {
  299. return [self _responseWithContentsOfFile:indexPath];
  300. }
  301. }
  302. response = [self _responseWithContentsOfDirectory:filePath];
  303. } else {
  304. response = [self _responseWithContentsOfFile:filePath];
  305. }
  306. }
  307. if (response) {
  308. response.cacheControlMaxAge = cacheAge;
  309. } else {
  310. response = [GCDWebServerResponse responseWithStatusCode:404];
  311. }
  312. return response;
  313. }];
  314. } else {
  315. DNOT_REACHED();
  316. }
  317. }
  318. - (void)addHandlerForMethod:(NSString*)method path:(NSString*)path requestClass:(Class)class processBlock:(GCDWebServerProcessBlock)block {
  319. if ([path hasPrefix:@"/"] && [class isSubclassOfClass:[GCDWebServerRequest class]]) {
  320. [self addHandlerWithMatchBlock:^GCDWebServerRequest *(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) {
  321. if (![requestMethod isEqualToString:method]) {
  322. return nil;
  323. }
  324. if ([urlPath caseInsensitiveCompare:path] != NSOrderedSame) {
  325. return nil;
  326. }
  327. return [[[class alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery] autorelease];
  328. } processBlock:block];
  329. } else {
  330. DNOT_REACHED();
  331. }
  332. }
  333. - (void)addHandlerForMethod:(NSString*)method pathRegex:(NSString*)regex requestClass:(Class)class processBlock:(GCDWebServerProcessBlock)block {
  334. NSRegularExpression* expression = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:NULL];
  335. if (expression && [class isSubclassOfClass:[GCDWebServerRequest class]]) {
  336. [self addHandlerWithMatchBlock:^GCDWebServerRequest *(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) {
  337. if (![requestMethod isEqualToString:method]) {
  338. return nil;
  339. }
  340. if ([expression firstMatchInString:urlPath options:0 range:NSMakeRange(0, urlPath.length)] == nil) {
  341. return nil;
  342. }
  343. return [[[class alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery] autorelease];
  344. } processBlock:block];
  345. } else {
  346. DNOT_REACHED();
  347. }
  348. }
  349. @end