GCDWebServerConnection.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  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. #import <netdb.h>
  27. #if !TARGET_OS_IPHONE
  28. #import <libkern/OSAtomic.h>
  29. #endif
  30. #import "GCDWebServerPrivate.h"
  31. #define kHeadersReadBuffer 1024
  32. typedef void (^ReadBufferCompletionBlock)(dispatch_data_t buffer);
  33. typedef void (^ReadDataCompletionBlock)(NSData* data);
  34. typedef void (^ReadHeadersCompletionBlock)(NSData* extraData);
  35. typedef void (^ReadBodyCompletionBlock)(BOOL success);
  36. typedef void (^WriteBufferCompletionBlock)(BOOL success);
  37. typedef void (^WriteDataCompletionBlock)(BOOL success);
  38. typedef void (^WriteHeadersCompletionBlock)(BOOL success);
  39. typedef void (^WriteBodyCompletionBlock)(BOOL success);
  40. static NSData* _CRLFData = nil;
  41. static NSData* _CRLFCRLFData = nil;
  42. static NSData* _continueData = nil;
  43. static NSData* _lastChunkData = nil;
  44. #if !TARGET_OS_IPHONE
  45. static int32_t _connectionCounter = 0;
  46. #endif
  47. @interface GCDWebServerConnection () {
  48. @private
  49. GCDWebServer* _server;
  50. NSData* _localAddress;
  51. NSData* _remoteAddress;
  52. CFSocketNativeHandle _socket;
  53. NSUInteger _bytesRead;
  54. NSUInteger _bytesWritten;
  55. BOOL _virtualHEAD;
  56. CFHTTPMessageRef _requestMessage;
  57. GCDWebServerRequest* _request;
  58. GCDWebServerHandler* _handler;
  59. CFHTTPMessageRef _responseMessage;
  60. GCDWebServerResponse* _response;
  61. NSInteger _statusCode;
  62. #if !TARGET_OS_IPHONE
  63. NSUInteger _connectionIndex;
  64. NSString* _requestPath;
  65. int _requestFD;
  66. NSString* _responsePath;
  67. int _responseFD;
  68. #endif
  69. }
  70. @end
  71. @implementation GCDWebServerConnection (Read)
  72. - (void)_readBufferWithLength:(NSUInteger)length completionBlock:(ReadBufferCompletionBlock)block {
  73. dispatch_read(_socket, length, kGCDWebServerGCDQueue, ^(dispatch_data_t buffer, int error) {
  74. @autoreleasepool {
  75. if (error == 0) {
  76. size_t size = dispatch_data_get_size(buffer);
  77. if (size > 0) {
  78. LOG_DEBUG(@"Connection received %zu bytes on socket %i", size, _socket);
  79. _bytesRead += size;
  80. [self didUpdateBytesRead];
  81. #if !TARGET_OS_IPHONE
  82. if (_requestFD > 0) {
  83. bool success = dispatch_data_apply(buffer, ^bool(dispatch_data_t region, size_t chunkOffset, const void* chunkBytes, size_t chunkSize) {
  84. return (write(_requestFD, chunkBytes, chunkSize) == (ssize_t)chunkSize);
  85. });
  86. if (!success) {
  87. LOG_ERROR(@"Failed recording request data: %s (%i)", strerror(errno), errno);
  88. close(_requestFD);
  89. _requestFD = 0;
  90. }
  91. }
  92. #endif
  93. block(buffer);
  94. } else {
  95. if (_bytesRead > 0) {
  96. LOG_ERROR(@"No more data available on socket %i", _socket);
  97. } else {
  98. LOG_WARNING(@"No data received from socket %i", _socket);
  99. }
  100. block(NULL);
  101. }
  102. } else {
  103. LOG_ERROR(@"Error while reading from socket %i: %s (%i)", _socket, strerror(error), error);
  104. block(NULL);
  105. }
  106. }
  107. });
  108. }
  109. - (void)_readDataWithCompletionBlock:(ReadDataCompletionBlock)block {
  110. [self _readBufferWithLength:SIZE_T_MAX completionBlock:^(dispatch_data_t buffer) {
  111. if (buffer) {
  112. NSMutableData* data = [[NSMutableData alloc] initWithCapacity:dispatch_data_get_size(buffer)];
  113. dispatch_data_apply(buffer, ^bool(dispatch_data_t region, size_t chunkOffset, const void* chunkBytes, size_t chunkSize) {
  114. [data appendBytes:chunkBytes length:chunkSize];
  115. return true;
  116. });
  117. block(data);
  118. ARC_RELEASE(data);
  119. } else {
  120. block(nil);
  121. }
  122. }];
  123. }
  124. - (void)_readHeadersWithCompletionBlock:(ReadHeadersCompletionBlock)block {
  125. DCHECK(_requestMessage);
  126. [self _readBufferWithLength:SIZE_T_MAX completionBlock:^(dispatch_data_t buffer) {
  127. if (buffer) {
  128. NSMutableData* data = [NSMutableData dataWithCapacity:kHeadersReadBuffer];
  129. dispatch_data_apply(buffer, ^bool(dispatch_data_t region, size_t chunkOffset, const void* chunkBytes, size_t chunkSize) {
  130. [data appendBytes:chunkBytes length:chunkSize];
  131. return true;
  132. });
  133. NSRange range = [data rangeOfData:_CRLFCRLFData options:0 range:NSMakeRange(0, data.length)];
  134. if (range.location == NSNotFound) {
  135. if (CFHTTPMessageAppendBytes(_requestMessage, data.bytes, data.length)) {
  136. [self _readHeadersWithCompletionBlock:block];
  137. } else {
  138. LOG_ERROR(@"Failed appending request headers data from socket %i", _socket);
  139. block(nil);
  140. }
  141. } else {
  142. NSUInteger length = range.location + range.length;
  143. if (CFHTTPMessageAppendBytes(_requestMessage, data.bytes, length)) {
  144. if (CFHTTPMessageIsHeaderComplete(_requestMessage)) {
  145. block([data subdataWithRange:NSMakeRange(length, data.length - length)]);
  146. } else {
  147. LOG_ERROR(@"Failed parsing request headers from socket %i", _socket);
  148. block(nil);
  149. }
  150. } else {
  151. LOG_ERROR(@"Failed appending request headers data from socket %i", _socket);
  152. block(nil);
  153. }
  154. }
  155. } else {
  156. block(nil);
  157. }
  158. }];
  159. }
  160. - (void)_readBodyWithRemainingLength:(NSUInteger)length completionBlock:(ReadBodyCompletionBlock)block {
  161. DCHECK([_request hasBody] && ![_request usesChunkedTransferEncoding]);
  162. [self _readBufferWithLength:length completionBlock:^(dispatch_data_t buffer) {
  163. if (buffer) {
  164. if (dispatch_data_get_size(buffer) <= length) {
  165. bool success = dispatch_data_apply(buffer, ^bool(dispatch_data_t region, size_t chunkOffset, const void* chunkBytes, size_t chunkSize) {
  166. NSData* data = [NSData dataWithBytesNoCopy:(void*)chunkBytes length:chunkSize freeWhenDone:NO];
  167. NSError* error = nil;
  168. if (![_request performWriteData:data error:&error]) {
  169. LOG_ERROR(@"Failed writing request body on socket %i: %@", _socket, error);
  170. return false;
  171. }
  172. return true;
  173. });
  174. if (success) {
  175. NSUInteger remainingLength = length - dispatch_data_get_size(buffer);
  176. if (remainingLength) {
  177. [self _readBodyWithRemainingLength:remainingLength completionBlock:block];
  178. } else {
  179. block(YES);
  180. }
  181. } else {
  182. block(NO);
  183. }
  184. } else {
  185. LOG_ERROR(@"Unexpected extra content reading request body on socket %i", _socket);
  186. block(NO);
  187. DNOT_REACHED();
  188. }
  189. } else {
  190. block(NO);
  191. }
  192. }];
  193. }
  194. static inline NSUInteger _ScanHexNumber(const void* bytes, NSUInteger size) {
  195. char buffer[size + 1];
  196. bcopy(bytes, buffer, size);
  197. buffer[size] = 0;
  198. char* end = NULL;
  199. long result = strtol(buffer, &end, 16);
  200. return ((end != NULL) && (*end == 0) && (result >= 0) ? result : NSNotFound);
  201. }
  202. - (void)_readNextBodyChunk:(NSMutableData*)chunkData completionBlock:(ReadBodyCompletionBlock)block {
  203. DCHECK([_request hasBody] && [_request usesChunkedTransferEncoding]);
  204. while (1) {
  205. NSRange range = [chunkData rangeOfData:_CRLFData options:0 range:NSMakeRange(0, chunkData.length)];
  206. if (range.location == NSNotFound) {
  207. break;
  208. }
  209. NSRange extensionRange = [chunkData rangeOfData:[NSData dataWithBytes:";" length:1] options:0 range:NSMakeRange(0, range.location)]; // Ignore chunk extensions
  210. NSUInteger length = _ScanHexNumber((char*)chunkData.bytes, extensionRange.location != NSNotFound ? extensionRange.location : range.location);
  211. if (length != NSNotFound) {
  212. if (length) {
  213. if (chunkData.length < range.location + range.length + length + 2) {
  214. break;
  215. }
  216. const char* ptr = (char*)chunkData.bytes + range.location + range.length + length;
  217. if ((*ptr == '\r') && (*(ptr + 1) == '\n')) {
  218. NSError* error = nil;
  219. if ([_request performWriteData:[chunkData subdataWithRange:NSMakeRange(range.location + range.length, length)] error:&error]) {
  220. [chunkData replaceBytesInRange:NSMakeRange(0, range.location + range.length + length + 2) withBytes:NULL length:0];
  221. } else {
  222. LOG_ERROR(@"Failed writing request body on socket %i: %@", _socket, error);
  223. block(NO);
  224. return;
  225. }
  226. } else {
  227. LOG_ERROR(@"Missing terminating CRLF sequence for chunk reading request body on socket %i", _socket);
  228. block(NO);
  229. return;
  230. }
  231. } else {
  232. NSRange trailerRange = [chunkData rangeOfData:_CRLFCRLFData options:0 range:NSMakeRange(range.location, chunkData.length - range.location)]; // Ignore trailers
  233. if (trailerRange.location != NSNotFound) {
  234. block(YES);
  235. return;
  236. }
  237. }
  238. } else {
  239. LOG_ERROR(@"Invalid chunk length reading request body on socket %i", _socket);
  240. block(NO);
  241. return;
  242. }
  243. }
  244. [self _readBufferWithLength:SIZE_T_MAX completionBlock:^(dispatch_data_t buffer) {
  245. if (buffer) {
  246. dispatch_data_apply(buffer, ^bool(dispatch_data_t region, size_t chunkOffset, const void* chunkBytes, size_t chunkSize) {
  247. [chunkData appendBytes:chunkBytes length:chunkSize];
  248. return true;
  249. });
  250. [self _readNextBodyChunk:chunkData completionBlock:block];
  251. } else {
  252. block(NO);
  253. }
  254. }];
  255. }
  256. @end
  257. @implementation GCDWebServerConnection (Write)
  258. - (void)_writeBuffer:(dispatch_data_t)buffer withCompletionBlock:(WriteBufferCompletionBlock)block {
  259. size_t size = dispatch_data_get_size(buffer);
  260. #if !TARGET_OS_IPHONE
  261. ARC_DISPATCH_RETAIN(buffer);
  262. #endif
  263. dispatch_write(_socket, buffer, kGCDWebServerGCDQueue, ^(dispatch_data_t data, int error) {
  264. @autoreleasepool {
  265. if (error == 0) {
  266. DCHECK(data == NULL);
  267. LOG_DEBUG(@"Connection sent %zu bytes on socket %i", size, _socket);
  268. _bytesWritten += size;
  269. [self didUpdateBytesWritten];
  270. #if !TARGET_OS_IPHONE
  271. if (_responseFD > 0) {
  272. bool success = dispatch_data_apply(buffer, ^bool(dispatch_data_t region, size_t chunkOffset, const void* chunkBytes, size_t chunkSize) {
  273. return (write(_responseFD, chunkBytes, chunkSize) == (ssize_t)chunkSize);
  274. });
  275. if (!success) {
  276. LOG_ERROR(@"Failed recording response data: %s (%i)", strerror(errno), errno);
  277. close(_responseFD);
  278. _responseFD = 0;
  279. }
  280. }
  281. #endif
  282. block(YES);
  283. } else {
  284. LOG_ERROR(@"Error while writing to socket %i: %s (%i)", _socket, strerror(error), error);
  285. block(NO);
  286. }
  287. }
  288. #if !TARGET_OS_IPHONE
  289. ARC_DISPATCH_RELEASE(buffer);
  290. #endif
  291. });
  292. }
  293. - (void)_writeData:(NSData*)data withCompletionBlock:(WriteDataCompletionBlock)block {
  294. #if !__has_feature(objc_arc)
  295. [data retain];
  296. #endif
  297. dispatch_data_t buffer = dispatch_data_create(data.bytes, data.length, kGCDWebServerGCDQueue, ^{
  298. #if __has_feature(objc_arc)
  299. [data self]; // Keeps ARC from releasing data too early
  300. #else
  301. [data release];
  302. #endif
  303. });
  304. [self _writeBuffer:buffer withCompletionBlock:block];
  305. ARC_DISPATCH_RELEASE(buffer);
  306. }
  307. - (void)_writeHeadersWithCompletionBlock:(WriteHeadersCompletionBlock)block {
  308. DCHECK(_responseMessage);
  309. CFDataRef message = CFHTTPMessageCopySerializedMessage(_responseMessage);
  310. [self _writeData:(ARC_BRIDGE NSData*)message withCompletionBlock:block];
  311. CFRelease(message);
  312. }
  313. - (void)_writeBodyWithCompletionBlock:(WriteBodyCompletionBlock)block {
  314. DCHECK([_response hasBody]);
  315. NSError* error = nil;
  316. NSData* data = [_response performReadData:&error];
  317. if (data) {
  318. if (data.length) {
  319. if (_response.usesChunkedTransferEncoding) {
  320. const char* hexString = [[NSString stringWithFormat:@"%lx", (unsigned long)data.length] UTF8String];
  321. size_t hexLength = strlen(hexString);
  322. NSData* chunk = [NSMutableData dataWithLength:(hexLength + 2 + data.length + 2)];
  323. if (chunk == nil) {
  324. LOG_ERROR(@"Failed allocating memory for response body chunk for socket %i: %@", _socket, error);
  325. block(NO);
  326. return;
  327. }
  328. char* ptr = (char*)[(NSMutableData*)chunk mutableBytes];
  329. bcopy(hexString, ptr, hexLength);
  330. ptr += hexLength;
  331. *ptr++ = '\r';
  332. *ptr++ = '\n';
  333. bcopy(data.bytes, ptr, data.length);
  334. ptr += data.length;
  335. *ptr++ = '\r';
  336. *ptr = '\n';
  337. data = chunk;
  338. }
  339. [self _writeData:data withCompletionBlock:^(BOOL success) {
  340. if (success) {
  341. [self _writeBodyWithCompletionBlock:block];
  342. } else {
  343. block(NO);
  344. }
  345. }];
  346. } else {
  347. if (_response.usesChunkedTransferEncoding) {
  348. [self _writeData:_lastChunkData withCompletionBlock:^(BOOL success) {
  349. block(success);
  350. }];
  351. } else {
  352. block(YES);
  353. }
  354. }
  355. } else {
  356. LOG_ERROR(@"Failed reading response body for socket %i: %@", _socket, error);
  357. block(NO);
  358. }
  359. }
  360. @end
  361. @implementation GCDWebServerConnection
  362. @synthesize server=_server, localAddressData=_localAddress, remoteAddressData=_remoteAddress, totalBytesRead=_bytesRead, totalBytesWritten=_bytesWritten;
  363. + (void)initialize {
  364. if (_CRLFData == nil) {
  365. _CRLFData = [[NSData alloc] initWithBytes:"\r\n" length:2];
  366. DCHECK(_CRLFData);
  367. }
  368. if (_CRLFCRLFData == nil) {
  369. _CRLFCRLFData = [[NSData alloc] initWithBytes:"\r\n\r\n" length:4];
  370. DCHECK(_CRLFCRLFData);
  371. }
  372. if (_continueData == nil) {
  373. CFHTTPMessageRef message = CFHTTPMessageCreateResponse(kCFAllocatorDefault, 100, NULL, kCFHTTPVersion1_1);
  374. #if __has_feature(objc_arc)
  375. _continueData = CFBridgingRelease(CFHTTPMessageCopySerializedMessage(message));
  376. #else
  377. _continueData = (NSData*)CFHTTPMessageCopySerializedMessage(message);
  378. #endif
  379. CFRelease(message);
  380. DCHECK(_continueData);
  381. }
  382. if (_lastChunkData == nil) {
  383. _lastChunkData = [[NSData alloc] initWithBytes:"0\r\n\r\n" length:5];
  384. }
  385. }
  386. - (void)_initializeResponseHeadersWithStatusCode:(NSInteger)statusCode {
  387. _statusCode = statusCode;
  388. _responseMessage = CFHTTPMessageCreateResponse(kCFAllocatorDefault, statusCode, NULL, kCFHTTPVersion1_1);
  389. CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Connection"), CFSTR("Close"));
  390. CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Server"), (ARC_BRIDGE CFStringRef)[[_server class] serverName]);
  391. CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Date"), (ARC_BRIDGE CFStringRef)GCDWebServerFormatRFC822([NSDate date]));
  392. }
  393. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  394. - (void)_processRequest {
  395. DCHECK(_responseMessage == NULL);
  396. BOOL hasBody = NO;
  397. GCDWebServerResponse* response = [self processRequest:_request withBlock:_handler.processBlock];
  398. if (response) {
  399. response = [self replaceResponse:response forRequest:_request];
  400. if (response) {
  401. if ([response hasBody]) {
  402. [response prepareForReading];
  403. hasBody = !_virtualHEAD;
  404. }
  405. NSError* error = nil;
  406. if (hasBody && ![response performOpen:&error]) {
  407. LOG_ERROR(@"Failed opening response body for socket %i: %@", _socket, error);
  408. } else {
  409. _response = ARC_RETAIN(response);
  410. }
  411. }
  412. }
  413. if (_response) {
  414. [self _initializeResponseHeadersWithStatusCode:_response.statusCode];
  415. if (_response.lastModifiedDate) {
  416. CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Last-Modified"), (ARC_BRIDGE CFStringRef)GCDWebServerFormatRFC822(_response.lastModifiedDate));
  417. }
  418. if (_response.eTag) {
  419. CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("ETag"), (ARC_BRIDGE CFStringRef)_response.eTag);
  420. }
  421. if ((_response.statusCode >= 200) && (_response.statusCode < 300)) {
  422. if (_response.cacheControlMaxAge > 0) {
  423. CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Cache-Control"), (ARC_BRIDGE CFStringRef)[NSString stringWithFormat:@"max-age=%i, public", (int)_response.cacheControlMaxAge]);
  424. } else {
  425. CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Cache-Control"), CFSTR("no-cache"));
  426. }
  427. }
  428. if (_response.contentType != nil) {
  429. CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Content-Type"), (ARC_BRIDGE CFStringRef)GCDWebServerNormalizeHeaderValue(_response.contentType));
  430. }
  431. if (_response.contentLength != NSNotFound) {
  432. CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Content-Length"), (ARC_BRIDGE CFStringRef)[NSString stringWithFormat:@"%lu", (unsigned long)_response.contentLength]);
  433. }
  434. if (_response.usesChunkedTransferEncoding) {
  435. CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Transfer-Encoding"), CFSTR("chunked"));
  436. }
  437. [_response.additionalHeaders enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL* stop) {
  438. CFHTTPMessageSetHeaderFieldValue(_responseMessage, (ARC_BRIDGE CFStringRef)key, (ARC_BRIDGE CFStringRef)obj);
  439. }];
  440. [self _writeHeadersWithCompletionBlock:^(BOOL success) {
  441. if (success) {
  442. if (hasBody) {
  443. [self _writeBodyWithCompletionBlock:^(BOOL successInner) {
  444. [_response performClose]; // TODO: There's nothing we can do on failure as headers have already been sent
  445. }];
  446. }
  447. } else if (hasBody) {
  448. [_response performClose];
  449. }
  450. }];
  451. } else {
  452. [self abortRequest:_request withStatusCode:kGCDWebServerHTTPStatusCode_InternalServerError];
  453. }
  454. }
  455. - (void)_readBodyWithLength:(NSUInteger)length initialData:(NSData*)initialData {
  456. NSError* error = nil;
  457. if (![_request performOpen:&error]) {
  458. LOG_ERROR(@"Failed opening request body for socket %i: %@", _socket, error);
  459. [self abortRequest:_request withStatusCode:kGCDWebServerHTTPStatusCode_InternalServerError];
  460. return;
  461. }
  462. if (initialData.length) {
  463. if (![_request performWriteData:initialData error:&error]) {
  464. LOG_ERROR(@"Failed writing request body on socket %i: %@", _socket, error);
  465. if (![_request performClose:&error]) {
  466. LOG_ERROR(@"Failed closing request body for socket %i: %@", _socket, error);
  467. }
  468. [self abortRequest:_request withStatusCode:kGCDWebServerHTTPStatusCode_InternalServerError];
  469. return;
  470. }
  471. length -= initialData.length;
  472. }
  473. if (length) {
  474. [self _readBodyWithRemainingLength:length completionBlock:^(BOOL success) {
  475. NSError* localError = nil;
  476. if ([_request performClose:&localError]) {
  477. [self _processRequest];
  478. } else {
  479. LOG_ERROR(@"Failed closing request body for socket %i: %@", _socket, error);
  480. [self abortRequest:_request withStatusCode:kGCDWebServerHTTPStatusCode_InternalServerError];
  481. }
  482. }];
  483. } else {
  484. if ([_request performClose:&error]) {
  485. [self _processRequest];
  486. } else {
  487. LOG_ERROR(@"Failed closing request body for socket %i: %@", _socket, error);
  488. [self abortRequest:_request withStatusCode:kGCDWebServerHTTPStatusCode_InternalServerError];
  489. }
  490. }
  491. }
  492. - (void)_readChunkedBodyWithInitialData:(NSData*)initialData {
  493. NSError* error = nil;
  494. if (![_request performOpen:&error]) {
  495. LOG_ERROR(@"Failed opening request body for socket %i: %@", _socket, error);
  496. [self abortRequest:_request withStatusCode:kGCDWebServerHTTPStatusCode_InternalServerError];
  497. return;
  498. }
  499. NSMutableData* chunkData = [[NSMutableData alloc] initWithData:initialData];
  500. [self _readNextBodyChunk:chunkData completionBlock:^(BOOL success) {
  501. NSError* localError = nil;
  502. if ([_request performClose:&localError]) {
  503. [self _processRequest];
  504. } else {
  505. LOG_ERROR(@"Failed closing request body for socket %i: %@", _socket, error);
  506. [self abortRequest:_request withStatusCode:kGCDWebServerHTTPStatusCode_InternalServerError];
  507. }
  508. }];
  509. ARC_RELEASE(chunkData);
  510. }
  511. - (void)_readRequestHeaders {
  512. _requestMessage = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, true);
  513. [self _readHeadersWithCompletionBlock:^(NSData* extraData) {
  514. if (extraData) {
  515. NSString* requestMethod = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyRequestMethod(_requestMessage)); // Method verbs are case-sensitive and uppercase
  516. DCHECK(requestMethod);
  517. if ([[_server class] shouldAutomaticallyMapHEADToGET] && [requestMethod isEqualToString:@"HEAD"]) {
  518. requestMethod = @"GET";
  519. _virtualHEAD = YES;
  520. }
  521. NSURL* requestURL = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyRequestURL(_requestMessage));
  522. DCHECK(requestURL);
  523. NSString* requestPath = GCDWebServerUnescapeURLString(ARC_BRIDGE_RELEASE(CFURLCopyPath((CFURLRef)requestURL))); // Don't use -[NSURL path] which strips the ending slash
  524. DCHECK(requestPath);
  525. NSDictionary* requestQuery = nil;
  526. NSString* queryString = ARC_BRIDGE_RELEASE(CFURLCopyQueryString((CFURLRef)requestURL, NULL)); // Don't use -[NSURL query] to make sure query is not unescaped;
  527. if (queryString.length) {
  528. requestQuery = GCDWebServerParseURLEncodedForm(queryString);
  529. DCHECK(requestQuery);
  530. }
  531. NSDictionary* requestHeaders = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyAllHeaderFields(_requestMessage)); // Header names are case-insensitive but CFHTTPMessageCopyAllHeaderFields() will standardize the common ones
  532. DCHECK(requestHeaders);
  533. for (_handler in _server.handlers) {
  534. _request = ARC_RETAIN(_handler.matchBlock(requestMethod, requestURL, requestHeaders, requestPath, requestQuery));
  535. if (_request) {
  536. break;
  537. }
  538. }
  539. if (_request) {
  540. if ([_request hasBody]) {
  541. [_request prepareForWriting];
  542. if (_request.usesChunkedTransferEncoding || (extraData.length <= _request.contentLength)) {
  543. NSString* expectHeader = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyHeaderFieldValue(_requestMessage, CFSTR("Expect")));
  544. if (expectHeader) {
  545. if ([expectHeader caseInsensitiveCompare:@"100-continue"] == NSOrderedSame) {
  546. [self _writeData:_continueData withCompletionBlock:^(BOOL success) {
  547. if (success) {
  548. if (_request.usesChunkedTransferEncoding) {
  549. [self _readChunkedBodyWithInitialData:extraData];
  550. } else {
  551. [self _readBodyWithLength:_request.contentLength initialData:extraData];
  552. }
  553. }
  554. }];
  555. } else {
  556. LOG_ERROR(@"Unsupported 'Expect' / 'Content-Length' header combination on socket %i", _socket);
  557. [self abortRequest:_request withStatusCode:kGCDWebServerHTTPStatusCode_ExpectationFailed];
  558. }
  559. } else {
  560. if (_request.usesChunkedTransferEncoding) {
  561. [self _readChunkedBodyWithInitialData:extraData];
  562. } else {
  563. [self _readBodyWithLength:_request.contentLength initialData:extraData];
  564. }
  565. }
  566. } else {
  567. LOG_ERROR(@"Unexpected 'Content-Length' header value on socket %i", _socket);
  568. [self abortRequest:_request withStatusCode:kGCDWebServerHTTPStatusCode_BadRequest];
  569. }
  570. } else {
  571. [self _processRequest];
  572. }
  573. } else {
  574. _request = [[GCDWebServerRequest alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:requestPath query:requestQuery];
  575. DCHECK(_request);
  576. [self abortRequest:_request withStatusCode:kGCDWebServerHTTPStatusCode_MethodNotAllowed];
  577. }
  578. } else {
  579. [self abortRequest:nil withStatusCode:kGCDWebServerHTTPStatusCode_InternalServerError];
  580. }
  581. }];
  582. }
  583. - (id)initWithServer:(GCDWebServer*)server localAddress:(NSData*)localAddress remoteAddress:(NSData*)remoteAddress socket:(CFSocketNativeHandle)socket {
  584. if ((self = [super init])) {
  585. _server = ARC_RETAIN(server);
  586. _localAddress = ARC_RETAIN(localAddress);
  587. _remoteAddress = ARC_RETAIN(remoteAddress);
  588. _socket = socket;
  589. [self open];
  590. }
  591. return self;
  592. }
  593. static NSString* _StringFromAddressData(NSData* data) {
  594. NSString* string = nil;
  595. const struct sockaddr* addr = data.bytes;
  596. char hostBuffer[NI_MAXHOST];
  597. char serviceBuffer[NI_MAXSERV];
  598. if (getnameinfo(addr, addr->sa_len, hostBuffer, sizeof(hostBuffer), serviceBuffer, sizeof(serviceBuffer), NI_NUMERICHOST | NI_NUMERICSERV | NI_NOFQDN) >= 0) {
  599. string = [NSString stringWithFormat:@"%s:%s", hostBuffer, serviceBuffer];
  600. } else {
  601. DNOT_REACHED();
  602. }
  603. return string;
  604. }
  605. - (NSString*)localAddressString {
  606. return _StringFromAddressData(_localAddress);
  607. }
  608. - (NSString*)remoteAddressString {
  609. return _StringFromAddressData(_remoteAddress);
  610. }
  611. - (void)dealloc {
  612. [self close];
  613. ARC_RELEASE(_server);
  614. ARC_RELEASE(_localAddress);
  615. ARC_RELEASE(_remoteAddress);
  616. if (_requestMessage) {
  617. CFRelease(_requestMessage);
  618. }
  619. ARC_RELEASE(_request);
  620. if (_responseMessage) {
  621. CFRelease(_responseMessage);
  622. }
  623. ARC_RELEASE(_response);
  624. #if !TARGET_OS_IPHONE
  625. ARC_RELEASE(_requestPath);
  626. ARC_RELEASE(_responsePath);
  627. #endif
  628. ARC_DEALLOC(super);
  629. }
  630. @end
  631. @implementation GCDWebServerConnection (Subclassing)
  632. - (void)open {
  633. LOG_DEBUG(@"Did open connection on socket %i", _socket);
  634. #if !TARGET_OS_IPHONE
  635. if (_server.recordingEnabled) {
  636. _connectionIndex = OSAtomicIncrement32(&_connectionCounter);
  637. _requestPath = ARC_RETAIN([NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]);
  638. _requestFD = open([_requestPath fileSystemRepresentation], O_CREAT | O_TRUNC | O_WRONLY);
  639. DCHECK(_requestFD > 0);
  640. _responsePath = ARC_RETAIN([NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]);
  641. _responseFD = open([_responsePath fileSystemRepresentation], O_CREAT | O_TRUNC | O_WRONLY);
  642. DCHECK(_responseFD > 0);
  643. }
  644. #endif
  645. [self _readRequestHeaders];
  646. }
  647. - (void)didUpdateBytesRead {
  648. ;
  649. }
  650. - (void)didUpdateBytesWritten {
  651. ;
  652. }
  653. - (GCDWebServerResponse*)processRequest:(GCDWebServerRequest*)request withBlock:(GCDWebServerProcessBlock)block {
  654. LOG_DEBUG(@"Connection on socket %i processing request \"%@ %@\" with %lu bytes body", _socket, _virtualHEAD ? @"HEAD" : _request.method, _request.path, (unsigned long)_bytesRead);
  655. GCDWebServerResponse* response = nil;
  656. @try {
  657. response = block(request);
  658. }
  659. @catch (NSException* exception) {
  660. LOG_EXCEPTION(exception);
  661. }
  662. return response;
  663. }
  664. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
  665. static inline BOOL _CompareResources(NSString* responseETag, NSString* requestETag, NSDate* responseLastModified, NSDate* requestLastModified) {
  666. if ([requestETag isEqualToString:@"*"] && (!responseLastModified || !requestLastModified || ([responseLastModified compare:requestLastModified] != NSOrderedDescending))) {
  667. return YES;
  668. } else {
  669. if ([responseETag isEqualToString:requestETag]) {
  670. return YES;
  671. }
  672. if (responseLastModified && requestLastModified && ([responseLastModified compare:requestLastModified] != NSOrderedDescending)) {
  673. return YES;
  674. }
  675. }
  676. return NO;
  677. }
  678. - (GCDWebServerResponse*)replaceResponse:(GCDWebServerResponse*)response forRequest:(GCDWebServerRequest*)request {
  679. if ((response.statusCode >= 200) && (response.statusCode < 300) && _CompareResources(response.eTag, request.ifNoneMatch, response.lastModifiedDate, request.ifModifiedSince)) {
  680. NSInteger code = [request.method isEqualToString:@"HEAD"] || [request.method isEqualToString:@"GET"] ? kGCDWebServerHTTPStatusCode_NotModified : kGCDWebServerHTTPStatusCode_PreconditionFailed;
  681. GCDWebServerResponse* newResponse = [GCDWebServerResponse responseWithStatusCode:code];
  682. newResponse.cacheControlMaxAge = response.cacheControlMaxAge;
  683. newResponse.lastModifiedDate = response.lastModifiedDate;
  684. newResponse.eTag = response.eTag;
  685. DCHECK(newResponse);
  686. return newResponse;
  687. }
  688. return response;
  689. }
  690. - (void)abortRequest:(GCDWebServerRequest*)request withStatusCode:(NSInteger)statusCode {
  691. DCHECK(_responseMessage == NULL);
  692. DCHECK((statusCode >= 400) && (statusCode < 600));
  693. [self _initializeResponseHeadersWithStatusCode:statusCode];
  694. [self _writeHeadersWithCompletionBlock:^(BOOL success) {
  695. ; // Nothing more to do
  696. }];
  697. LOG_DEBUG(@"Connection aborted with status code %i on socket %i", (int)statusCode, _socket);
  698. }
  699. - (void)close {
  700. int result = close(_socket);
  701. if (result != 0) {
  702. LOG_ERROR(@"Failed closing socket %i for connection (%i): %s", _socket, errno, strerror(errno));
  703. } else {
  704. LOG_DEBUG(@"Did close connection on socket %i", _socket);
  705. }
  706. #if !TARGET_OS_IPHONE
  707. if (_requestPath) {
  708. BOOL success = NO;
  709. NSError* error = nil;
  710. if (_requestFD > 0) {
  711. close(_requestFD);
  712. NSString* name = [NSString stringWithFormat:@"%03lu-%@.request", (unsigned long)_connectionIndex, _virtualHEAD ? @"HEAD" : _request.method];
  713. success = [[NSFileManager defaultManager] moveItemAtPath:_requestPath toPath:[[[NSFileManager defaultManager] currentDirectoryPath] stringByAppendingPathComponent:name] error:&error];
  714. }
  715. if (!success) {
  716. LOG_ERROR(@"Failed saving recorded request: %@", error);
  717. DNOT_REACHED();
  718. }
  719. unlink([_requestPath fileSystemRepresentation]);
  720. }
  721. if (_responsePath) {
  722. BOOL success = NO;
  723. NSError* error = nil;
  724. if (_responseFD > 0) {
  725. close(_responseFD);
  726. NSString* name = [NSString stringWithFormat:@"%03lu-%i.response", (unsigned long)_connectionIndex, (int)_statusCode];
  727. success = [[NSFileManager defaultManager] moveItemAtPath:_responsePath toPath:[[[NSFileManager defaultManager] currentDirectoryPath] stringByAppendingPathComponent:name] error:&error];
  728. }
  729. if (!success) {
  730. LOG_ERROR(@"Failed saving recorded response: %@", error);
  731. DNOT_REACHED();
  732. }
  733. unlink([_responsePath fileSystemRepresentation]);
  734. }
  735. #endif
  736. if (_request) {
  737. LOG_VERBOSE(@"[%@] %@ %i \"%@ %@\" (%lu | %lu)", self.localAddressString, self.remoteAddressString, (int)_statusCode, _virtualHEAD ? @"HEAD" : _request.method, _request.path, (unsigned long)_bytesRead, (unsigned long)_bytesWritten);
  738. } else {
  739. LOG_VERBOSE(@"[%@] %@ %i \"(invalid request)\" (%lu | %lu)", self.localAddressString, self.remoteAddressString, (int)_statusCode, (unsigned long)_bytesRead, (unsigned long)_bytesWritten);
  740. }
  741. }
  742. @end