HTTPConnection.m 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238
  1. #import "HTTPServer.h"
  2. #import "HTTPConnection.h"
  3. #import "HTTPMessage.h"
  4. #import "HTTPResponse.h"
  5. #import "DDNumber.h"
  6. #import "DDRange.h"
  7. #import "HTTPLogging.h"
  8. #import "GCDAsyncSocket.h"
  9. #if ! __has_feature(objc_arc)
  10. #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
  11. #endif
  12. #pragma clang diagnostic ignored "-Wunknown-warning-option"
  13. #pragma clang diagnostic ignored "-Wdirect-ivar-access"
  14. #pragma clang diagnostic ignored "-Wimplicit-retain-self"
  15. #pragma clang diagnostic ignored "-Wformat-non-iso"
  16. #pragma clang diagnostic ignored "-Wunused-variable"
  17. #pragma clang diagnostic ignored "-Wsign-compare"
  18. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  19. #pragma clang diagnostic ignored "-Wunreachable-code"
  20. #pragma clang diagnostic ignored "-Wfloat-conversion"
  21. // Log levels: off, error, warn, info, verbose
  22. // Other flags: trace
  23. static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; // | HTTP_LOG_FLAG_TRACE;
  24. // Define chunk size used to read in data for responses
  25. // This is how much data will be read from disk into RAM at a time
  26. #if TARGET_OS_IPHONE
  27. #define READ_CHUNKSIZE (1024 * 256)
  28. #else
  29. #define READ_CHUNKSIZE (1024 * 512)
  30. #endif
  31. // Define chunk size used to read in POST upload data
  32. #if TARGET_OS_IPHONE
  33. #define POST_CHUNKSIZE (1024 * 256)
  34. #else
  35. #define POST_CHUNKSIZE (1024 * 512)
  36. #endif
  37. // Define the various timeouts (in seconds) for various parts of the HTTP process
  38. #define TIMEOUT_READ_FIRST_HEADER_LINE 30
  39. #define TIMEOUT_READ_SUBSEQUENT_HEADER_LINE 30
  40. #define TIMEOUT_READ_BODY -1
  41. #define TIMEOUT_WRITE_HEAD 30
  42. #define TIMEOUT_WRITE_BODY -1
  43. #define TIMEOUT_WRITE_ERROR 30
  44. #define TIMEOUT_NONCE 300
  45. // Define the various limits
  46. // MAX_HEADER_LINE_LENGTH: Max length (in bytes) of any single line in a header (including \r\n)
  47. // MAX_HEADER_LINES : Max number of lines in a single header (including first GET line)
  48. #define MAX_HEADER_LINE_LENGTH 8190
  49. #define MAX_HEADER_LINES 100
  50. // MAX_CHUNK_LINE_LENGTH : For accepting chunked transfer uploads, max length of chunk size line (including \r\n)
  51. #define MAX_CHUNK_LINE_LENGTH 200
  52. // Define the various tags we'll use to differentiate what it is we're currently doing
  53. #define HTTP_REQUEST_HEADER 10
  54. #define HTTP_REQUEST_BODY 11
  55. #define HTTP_REQUEST_CHUNK_SIZE 12
  56. #define HTTP_REQUEST_CHUNK_DATA 13
  57. #define HTTP_REQUEST_CHUNK_TRAILER 14
  58. #define HTTP_REQUEST_CHUNK_FOOTER 15
  59. #define HTTP_PARTIAL_RESPONSE 20
  60. #define HTTP_PARTIAL_RESPONSE_HEADER 21
  61. #define HTTP_PARTIAL_RESPONSE_BODY 22
  62. #define HTTP_CHUNKED_RESPONSE_HEADER 30
  63. #define HTTP_CHUNKED_RESPONSE_BODY 31
  64. #define HTTP_CHUNKED_RESPONSE_FOOTER 32
  65. #define HTTP_PARTIAL_RANGE_RESPONSE_BODY 40
  66. #define HTTP_PARTIAL_RANGES_RESPONSE_BODY 50
  67. #define HTTP_RESPONSE 90
  68. #define HTTP_FINAL_RESPONSE 91
  69. // A quick note about the tags:
  70. //
  71. // The HTTP_RESPONSE and HTTP_FINAL_RESPONSE are designated tags signalling that the response is completely sent.
  72. // That is, in the onSocket:didWriteDataWithTag: method, if the tag is HTTP_RESPONSE or HTTP_FINAL_RESPONSE,
  73. // it is assumed that the response is now completely sent.
  74. // Use HTTP_RESPONSE if it's the end of a response, and you want to start reading more requests afterwards.
  75. // Use HTTP_FINAL_RESPONSE if you wish to terminate the connection after sending the response.
  76. //
  77. // If you are sending multiple data segments in a custom response, make sure that only the last segment has
  78. // the HTTP_RESPONSE tag. For all other segments prior to the last segment use HTTP_PARTIAL_RESPONSE, or some other
  79. // tag of your own invention.
  80. @interface HTTPConnection (PrivateAPI)
  81. - (void)startReadingRequest;
  82. - (void)sendResponseHeadersAndBody;
  83. @end
  84. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  85. #pragma mark -
  86. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  87. @implementation HTTPConnection
  88. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  89. #pragma mark Init, Dealloc:
  90. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  91. /**
  92. * Sole Constructor.
  93. * Associates this new HTTP connection with the given AsyncSocket.
  94. * This HTTP connection object will become the socket's delegate and take over responsibility for the socket.
  95. **/
  96. - (id)initWithAsyncSocket:(GCDAsyncSocket *)newSocket configuration:(HTTPConfig *)aConfig
  97. {
  98. if ((self = [super init]))
  99. {
  100. HTTPLogTrace();
  101. if (aConfig.queue)
  102. {
  103. connectionQueue = aConfig.queue;
  104. #if !OS_OBJECT_USE_OBJC
  105. dispatch_retain(connectionQueue);
  106. #endif
  107. }
  108. else
  109. {
  110. connectionQueue = dispatch_queue_create("HTTPConnection", NULL);
  111. }
  112. // Take over ownership of the socket
  113. asyncSocket = newSocket;
  114. [asyncSocket setDelegate:(id<GCDAsyncSocketDelegate>)self delegateQueue:connectionQueue];
  115. // Store configuration
  116. config = aConfig;
  117. // Create a new HTTP message
  118. request = [[HTTPMessage alloc] initEmptyRequest];
  119. numHeaderLines = 0;
  120. responseDataSizes = [[NSMutableArray alloc] initWithCapacity:5];
  121. }
  122. return self;
  123. }
  124. /**
  125. * Standard Deconstructor.
  126. **/
  127. - (void)dealloc
  128. {
  129. HTTPLogTrace();
  130. #if !OS_OBJECT_USE_OBJC
  131. dispatch_release(connectionQueue);
  132. #endif
  133. [asyncSocket setDelegate:nil delegateQueue:NULL];
  134. [asyncSocket disconnect];
  135. if ([httpResponse respondsToSelector:@selector(connectionDidClose)])
  136. {
  137. [httpResponse connectionDidClose];
  138. }
  139. }
  140. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  141. #pragma mark Method Support
  142. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  143. /**
  144. * Returns whether or not the server will accept messages of a given method
  145. * at a particular URI.
  146. **/
  147. - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
  148. {
  149. HTTPLogTrace();
  150. // Override me to support methods such as POST.
  151. //
  152. // Things you may want to consider:
  153. // - Does the given path represent a resource that is designed to accept this method?
  154. // - If accepting an upload, is the size of the data being uploaded too big?
  155. // To do this you can check the requestContentLength variable.
  156. //
  157. // For more information, you can always access the HTTPMessage request variable.
  158. //
  159. // You should fall through with a call to [super supportsMethod:method atPath:path]
  160. //
  161. // See also: expectsRequestBodyFromMethod:atPath:
  162. if ([method isEqualToString:@"GET"])
  163. return YES;
  164. if ([method isEqualToString:@"HEAD"])
  165. return YES;
  166. return NO;
  167. }
  168. /**
  169. * Returns whether or not the server expects a body from the given method.
  170. *
  171. * In other words, should the server expect a content-length header and associated body from this method.
  172. * This would be true in the case of a POST, where the client is sending data,
  173. * or for something like PUT where the client is supposed to be uploading a file.
  174. **/
  175. - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
  176. {
  177. HTTPLogTrace();
  178. // Override me to add support for other methods that expect the client
  179. // to send a body along with the request header.
  180. //
  181. // You should fall through with a call to [super expectsRequestBodyFromMethod:method atPath:path]
  182. //
  183. // See also: supportsMethod:atPath:
  184. if ([method isEqualToString:@"POST"])
  185. return YES;
  186. if ([method isEqualToString:@"PUT"])
  187. return YES;
  188. return NO;
  189. }
  190. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  191. #pragma mark Core
  192. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  193. /**
  194. * Starting point for the HTTP connection after it has been fully initialized (including subclasses).
  195. * This method is called by the HTTP server.
  196. **/
  197. - (void)start
  198. {
  199. dispatch_async(connectionQueue, ^{ @autoreleasepool {
  200. if (!started)
  201. {
  202. started = YES;
  203. [self startConnection];
  204. }
  205. }});
  206. }
  207. /**
  208. * This method is called by the HTTPServer if it is asked to stop.
  209. * The server, in turn, invokes stop on each HTTPConnection instance.
  210. **/
  211. - (void)stop
  212. {
  213. dispatch_async(connectionQueue, ^{ @autoreleasepool {
  214. // Disconnect the socket.
  215. // The socketDidDisconnect delegate method will handle everything else.
  216. [asyncSocket disconnect];
  217. }});
  218. }
  219. /**
  220. * Starting point for the HTTP connection.
  221. **/
  222. - (void)startConnection
  223. {
  224. // Override me to do any custom work before the connection starts.
  225. //
  226. // Be sure to invoke [super startConnection] when you're done.
  227. HTTPLogTrace();
  228. [self startReadingRequest];
  229. }
  230. /**
  231. * Starts reading an HTTP request.
  232. **/
  233. - (void)startReadingRequest
  234. {
  235. HTTPLogTrace();
  236. [asyncSocket readDataToData:[GCDAsyncSocket CRLFData]
  237. withTimeout:TIMEOUT_READ_FIRST_HEADER_LINE
  238. maxLength:MAX_HEADER_LINE_LENGTH
  239. tag:HTTP_REQUEST_HEADER];
  240. }
  241. /**
  242. * Parses the given query string.
  243. *
  244. * For example, if the query is "q=John%20Mayer%20Trio&num=50"
  245. * then this method would return the following dictionary:
  246. * {
  247. * q = "John Mayer Trio"
  248. * num = "50"
  249. * }
  250. **/
  251. - (NSDictionary *)parseParams:(NSString *)query
  252. {
  253. NSArray *components = [query componentsSeparatedByString:@"&"];
  254. NSMutableDictionary *result = [NSMutableDictionary dictionaryWithCapacity:[components count]];
  255. NSUInteger i;
  256. for (i = 0; i < [components count]; i++)
  257. {
  258. NSString *component = [components objectAtIndex:i];
  259. if ([component length] > 0)
  260. {
  261. NSRange range = [component rangeOfString:@"="];
  262. if (range.location != NSNotFound)
  263. {
  264. NSString *escapedKey = [component substringToIndex:(range.location + 0)];
  265. NSString *escapedValue = [component substringFromIndex:(range.location + 1)];
  266. if ([escapedKey length] > 0)
  267. {
  268. CFStringRef k, v;
  269. k = CFURLCreateStringByReplacingPercentEscapes(NULL, (__bridge CFStringRef)escapedKey, CFSTR(""));
  270. v = CFURLCreateStringByReplacingPercentEscapes(NULL, (__bridge CFStringRef)escapedValue, CFSTR(""));
  271. NSString *key, *value;
  272. key = (__bridge_transfer NSString *)k;
  273. value = (__bridge_transfer NSString *)v;
  274. if (key)
  275. {
  276. if (value)
  277. [result setObject:value forKey:key];
  278. else
  279. [result setObject:[NSNull null] forKey:key];
  280. }
  281. }
  282. }
  283. }
  284. }
  285. return result;
  286. }
  287. /**
  288. * Parses the query variables in the request URI.
  289. *
  290. * For example, if the request URI was "/search.html?q=John%20Mayer%20Trio&num=50"
  291. * then this method would return the following dictionary:
  292. * {
  293. * q = "John Mayer Trio"
  294. * num = "50"
  295. * }
  296. **/
  297. - (NSDictionary *)parseGetParams
  298. {
  299. if(![request isHeaderComplete]) return nil;
  300. NSDictionary *result = nil;
  301. NSURL *url = [request url];
  302. if(url)
  303. {
  304. NSString *query = [url query];
  305. if (query)
  306. {
  307. result = [self parseParams:query];
  308. }
  309. }
  310. return result;
  311. }
  312. /**
  313. * Attempts to parse the given range header into a series of sequential non-overlapping ranges.
  314. * If successfull, the variables 'ranges' and 'rangeIndex' will be updated, and YES will be returned.
  315. * Otherwise, NO is returned, and the range request should be ignored.
  316. **/
  317. - (BOOL)parseRangeRequest:(NSString *)rangeHeader withContentLength:(UInt64)contentLength
  318. {
  319. HTTPLogTrace();
  320. // Examples of byte-ranges-specifier values (assuming an entity-body of length 10000):
  321. //
  322. // - The first 500 bytes (byte offsets 0-499, inclusive): bytes=0-499
  323. //
  324. // - The second 500 bytes (byte offsets 500-999, inclusive): bytes=500-999
  325. //
  326. // - The final 500 bytes (byte offsets 9500-9999, inclusive): bytes=-500
  327. //
  328. // - Or bytes=9500-
  329. //
  330. // - The first and last bytes only (bytes 0 and 9999): bytes=0-0,-1
  331. //
  332. // - Several legal but not canonical specifications of the second 500 bytes (byte offsets 500-999, inclusive):
  333. // bytes=500-600,601-999
  334. // bytes=500-700,601-999
  335. //
  336. NSRange eqsignRange = [rangeHeader rangeOfString:@"="];
  337. if(eqsignRange.location == NSNotFound) return NO;
  338. NSUInteger tIndex = eqsignRange.location;
  339. NSUInteger fIndex = eqsignRange.location + eqsignRange.length;
  340. NSMutableString *rangeType = [[rangeHeader substringToIndex:tIndex] mutableCopy];
  341. NSMutableString *rangeValue = [[rangeHeader substringFromIndex:fIndex] mutableCopy];
  342. CFStringTrimWhitespace((__bridge CFMutableStringRef)rangeType);
  343. CFStringTrimWhitespace((__bridge CFMutableStringRef)rangeValue);
  344. if([rangeType caseInsensitiveCompare:@"bytes"] != NSOrderedSame) return NO;
  345. NSArray *rangeComponents = [rangeValue componentsSeparatedByString:@","];
  346. if([rangeComponents count] == 0) return NO;
  347. ranges = [[NSMutableArray alloc] initWithCapacity:[rangeComponents count]];
  348. rangeIndex = 0;
  349. // Note: We store all range values in the form of DDRange structs, wrapped in NSValue objects.
  350. // Since DDRange consists of UInt64 values, the range extends up to 16 exabytes.
  351. NSUInteger i;
  352. for (i = 0; i < [rangeComponents count]; i++)
  353. {
  354. NSString *rangeComponent = [rangeComponents objectAtIndex:i];
  355. NSRange dashRange = [rangeComponent rangeOfString:@"-"];
  356. if (dashRange.location == NSNotFound)
  357. {
  358. // We're dealing with an individual byte number
  359. UInt64 byteIndex;
  360. if(![NSNumber parseString:rangeComponent intoUInt64:&byteIndex]) return NO;
  361. if(byteIndex >= contentLength) return NO;
  362. [ranges addObject:[NSValue valueWithDDRange:DDMakeRange(byteIndex, 1)]];
  363. }
  364. else
  365. {
  366. // We're dealing with a range of bytes
  367. tIndex = dashRange.location;
  368. fIndex = dashRange.location + dashRange.length;
  369. NSString *r1str = [rangeComponent substringToIndex:tIndex];
  370. NSString *r2str = [rangeComponent substringFromIndex:fIndex];
  371. UInt64 r1, r2;
  372. BOOL hasR1 = [NSNumber parseString:r1str intoUInt64:&r1];
  373. BOOL hasR2 = [NSNumber parseString:r2str intoUInt64:&r2];
  374. if (!hasR1)
  375. {
  376. // We're dealing with a "-[#]" range
  377. //
  378. // r2 is the number of ending bytes to include in the range
  379. if(!hasR2) return NO;
  380. if(r2 > contentLength) return NO;
  381. UInt64 startIndex = contentLength - r2;
  382. [ranges addObject:[NSValue valueWithDDRange:DDMakeRange(startIndex, r2)]];
  383. }
  384. else if (!hasR2)
  385. {
  386. // We're dealing with a "[#]-" range
  387. //
  388. // r1 is the starting index of the range, which goes all the way to the end
  389. if(r1 >= contentLength) return NO;
  390. [ranges addObject:[NSValue valueWithDDRange:DDMakeRange(r1, contentLength - r1)]];
  391. }
  392. else
  393. {
  394. // We're dealing with a normal "[#]-[#]" range
  395. //
  396. // Note: The range is inclusive. So 0-1 has a length of 2 bytes.
  397. if(r1 > r2) return NO;
  398. if(r2 >= contentLength) return NO;
  399. [ranges addObject:[NSValue valueWithDDRange:DDMakeRange(r1, r2 - r1 + 1)]];
  400. }
  401. }
  402. }
  403. if([ranges count] == 0) return NO;
  404. // Now make sure none of the ranges overlap
  405. for (i = 0; i < [ranges count] - 1; i++)
  406. {
  407. DDRange range1 = [[ranges objectAtIndex:i] ddrangeValue];
  408. NSUInteger j;
  409. for (j = i+1; j < [ranges count]; j++)
  410. {
  411. DDRange range2 = [[ranges objectAtIndex:j] ddrangeValue];
  412. DDRange iRange = DDIntersectionRange(range1, range2);
  413. if(iRange.length != 0)
  414. {
  415. return NO;
  416. }
  417. }
  418. }
  419. // Sort the ranges
  420. [ranges sortUsingSelector:@selector(ddrangeCompare:)];
  421. return YES;
  422. }
  423. - (NSString *)requestURI
  424. {
  425. if(request == nil) return nil;
  426. return [[request url] relativeString];
  427. }
  428. /**
  429. * This method is called after a full HTTP request has been received.
  430. * The current request is in the HTTPMessage request variable.
  431. **/
  432. - (void)replyToHTTPRequest
  433. {
  434. HTTPLogTrace();
  435. if (HTTP_LOG_VERBOSE)
  436. {
  437. NSData *tempData = [request messageData];
  438. NSString *tempStr = [[NSString alloc] initWithData:tempData encoding:NSUTF8StringEncoding];
  439. HTTPLogVerbose(@"%@[%p]: Received HTTP request:\n%@", THIS_FILE, self, tempStr);
  440. }
  441. // Check the HTTP version
  442. // We only support version 1.0 and 1.1
  443. NSString *version = [request version];
  444. if (![version isEqualToString:HTTPVersion1_1] && ![version isEqualToString:HTTPVersion1_0])
  445. {
  446. [self handleVersionNotSupported:version];
  447. return;
  448. }
  449. // Extract requested URI
  450. NSString *uri = [self requestURI];
  451. // Extract the method
  452. NSString *method = [request method];
  453. // Note: We already checked to ensure the method was supported in onSocket:didReadData:withTag:
  454. // Respond properly to HTTP 'GET' and 'HEAD' commands
  455. httpResponse = [self httpResponseForMethod:method URI:uri];
  456. if (httpResponse == nil)
  457. {
  458. [self handleResourceNotFound];
  459. return;
  460. }
  461. [self sendResponseHeadersAndBody];
  462. }
  463. /**
  464. * Prepares a single-range response.
  465. *
  466. * Note: The returned HTTPMessage is owned by the sender, who is responsible for releasing it.
  467. **/
  468. - (HTTPMessage *)newUniRangeResponse:(UInt64)contentLength
  469. {
  470. HTTPLogTrace();
  471. // Status Code 206 - Partial Content
  472. HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:206 description:nil version:HTTPVersion1_1];
  473. DDRange range = [[ranges objectAtIndex:0] ddrangeValue];
  474. NSString *contentLengthStr = [NSString stringWithFormat:@"%qu", range.length];
  475. [response setHeaderField:@"Content-Length" value:contentLengthStr];
  476. NSString *rangeStr = [NSString stringWithFormat:@"%qu-%qu", range.location, DDMaxRange(range) - 1];
  477. NSString *contentRangeStr = [NSString stringWithFormat:@"bytes %@/%qu", rangeStr, contentLength];
  478. [response setHeaderField:@"Content-Range" value:contentRangeStr];
  479. return response;
  480. }
  481. /**
  482. * Prepares a multi-range response.
  483. *
  484. * Note: The returned HTTPMessage is owned by the sender, who is responsible for releasing it.
  485. **/
  486. - (HTTPMessage *)newMultiRangeResponse:(UInt64)contentLength
  487. {
  488. HTTPLogTrace();
  489. // Status Code 206 - Partial Content
  490. HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:206 description:nil version:HTTPVersion1_1];
  491. // We have to send each range using multipart/byteranges
  492. // So each byterange has to be prefix'd and suffix'd with the boundry
  493. // Example:
  494. //
  495. // HTTP/1.1 206 Partial Content
  496. // Content-Length: 220
  497. // Content-Type: multipart/byteranges; boundary=4554d24e986f76dd6
  498. //
  499. //
  500. // --4554d24e986f76dd6
  501. // Content-Range: bytes 0-25/4025
  502. //
  503. // [...]
  504. // --4554d24e986f76dd6
  505. // Content-Range: bytes 3975-4024/4025
  506. //
  507. // [...]
  508. // --4554d24e986f76dd6--
  509. ranges_headers = [[NSMutableArray alloc] initWithCapacity:[ranges count]];
  510. CFUUIDRef theUUID = CFUUIDCreate(NULL);
  511. ranges_boundry = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, theUUID);
  512. CFRelease(theUUID);
  513. NSString *startingBoundryStr = [NSString stringWithFormat:@"\r\n--%@\r\n", ranges_boundry];
  514. NSString *endingBoundryStr = [NSString stringWithFormat:@"\r\n--%@--\r\n", ranges_boundry];
  515. UInt64 actualContentLength = 0;
  516. NSUInteger i;
  517. for (i = 0; i < [ranges count]; i++)
  518. {
  519. DDRange range = [[ranges objectAtIndex:i] ddrangeValue];
  520. NSString *rangeStr = [NSString stringWithFormat:@"%qu-%qu", range.location, DDMaxRange(range) - 1];
  521. NSString *contentRangeVal = [NSString stringWithFormat:@"bytes %@/%qu", rangeStr, contentLength];
  522. NSString *contentRangeStr = [NSString stringWithFormat:@"Content-Range: %@\r\n\r\n", contentRangeVal];
  523. NSString *fullHeader = [startingBoundryStr stringByAppendingString:contentRangeStr];
  524. NSData *fullHeaderData = [fullHeader dataUsingEncoding:NSUTF8StringEncoding];
  525. [ranges_headers addObject:fullHeaderData];
  526. actualContentLength += [fullHeaderData length];
  527. actualContentLength += range.length;
  528. }
  529. NSData *endingBoundryData = [endingBoundryStr dataUsingEncoding:NSUTF8StringEncoding];
  530. actualContentLength += [endingBoundryData length];
  531. NSString *contentLengthStr = [NSString stringWithFormat:@"%qu", actualContentLength];
  532. [response setHeaderField:@"Content-Length" value:contentLengthStr];
  533. NSString *contentTypeStr = [NSString stringWithFormat:@"multipart/byteranges; boundary=%@", ranges_boundry];
  534. [response setHeaderField:@"Content-Type" value:contentTypeStr];
  535. return response;
  536. }
  537. /**
  538. * Returns the chunk size line that must precede each chunk of data when using chunked transfer encoding.
  539. * This consists of the size of the data, in hexadecimal, followed by a CRLF.
  540. **/
  541. - (NSData *)chunkedTransferSizeLineForLength:(NSUInteger)length
  542. {
  543. return [[NSString stringWithFormat:@"%lx\r\n", (unsigned long)length] dataUsingEncoding:NSUTF8StringEncoding];
  544. }
  545. /**
  546. * Returns the data that signals the end of a chunked transfer.
  547. **/
  548. - (NSData *)chunkedTransferFooter
  549. {
  550. // Each data chunk is preceded by a size line (in hex and including a CRLF),
  551. // followed by the data itself, followed by another CRLF.
  552. // After every data chunk has been sent, a zero size line is sent,
  553. // followed by optional footer (which are just more headers),
  554. // and followed by a CRLF on a line by itself.
  555. return [@"\r\n0\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding];
  556. }
  557. - (void)sendResponseHeadersAndBody
  558. {
  559. if ([httpResponse respondsToSelector:@selector(delayResponseHeaders)])
  560. {
  561. if ([httpResponse delayResponseHeaders])
  562. {
  563. return;
  564. }
  565. }
  566. BOOL isChunked = NO;
  567. if ([httpResponse respondsToSelector:@selector(isChunked)])
  568. {
  569. isChunked = [httpResponse isChunked];
  570. }
  571. // If a response is "chunked", this simply means the HTTPResponse object
  572. // doesn't know the content-length in advance.
  573. UInt64 contentLength = 0;
  574. if (!isChunked)
  575. {
  576. contentLength = [httpResponse contentLength];
  577. }
  578. // Check for specific range request
  579. NSString *rangeHeader = [request headerField:@"Range"];
  580. BOOL isRangeRequest = NO;
  581. // If the response is "chunked" then we don't know the exact content-length.
  582. // This means we'll be unable to process any range requests.
  583. // This is because range requests might include a range like "give me the last 100 bytes"
  584. if (!isChunked && rangeHeader)
  585. {
  586. if ([self parseRangeRequest:rangeHeader withContentLength:contentLength])
  587. {
  588. isRangeRequest = YES;
  589. }
  590. }
  591. HTTPMessage *response;
  592. if (!isRangeRequest)
  593. {
  594. // Create response
  595. // Default status code: 200 - OK
  596. NSInteger status = 200;
  597. if ([httpResponse respondsToSelector:@selector(status)])
  598. {
  599. status = [httpResponse status];
  600. }
  601. response = [[HTTPMessage alloc] initResponseWithStatusCode:status description:nil version:HTTPVersion1_1];
  602. if (isChunked)
  603. {
  604. [response setHeaderField:@"Transfer-Encoding" value:@"chunked"];
  605. }
  606. else
  607. {
  608. NSString *contentLengthStr = [NSString stringWithFormat:@"%qu", contentLength];
  609. [response setHeaderField:@"Content-Length" value:contentLengthStr];
  610. }
  611. }
  612. else
  613. {
  614. if ([ranges count] == 1)
  615. {
  616. response = [self newUniRangeResponse:contentLength];
  617. }
  618. else
  619. {
  620. response = [self newMultiRangeResponse:contentLength];
  621. }
  622. }
  623. BOOL isZeroLengthResponse = !isChunked && (contentLength == 0);
  624. // If they issue a 'HEAD' command, we don't have to include the file
  625. // If they issue a 'GET' command, we need to include the file
  626. if ([[request method] isEqualToString:@"HEAD"] || isZeroLengthResponse)
  627. {
  628. NSData *responseData = [self preprocessResponse:response];
  629. [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_RESPONSE];
  630. sentResponseHeaders = YES;
  631. }
  632. else
  633. {
  634. // Write the header response
  635. NSData *responseData = [self preprocessResponse:response];
  636. [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_PARTIAL_RESPONSE_HEADER];
  637. sentResponseHeaders = YES;
  638. // Now we need to send the body of the response
  639. if (!isRangeRequest)
  640. {
  641. // Regular request
  642. NSData *data = [httpResponse readDataOfLength:READ_CHUNKSIZE];
  643. if ([data length] > 0)
  644. {
  645. [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]];
  646. if (isChunked)
  647. {
  648. NSData *chunkSize = [self chunkedTransferSizeLineForLength:[data length]];
  649. [asyncSocket writeData:chunkSize withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_CHUNKED_RESPONSE_HEADER];
  650. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:HTTP_CHUNKED_RESPONSE_BODY];
  651. if ([httpResponse isDone])
  652. {
  653. NSData *footer = [self chunkedTransferFooter];
  654. [asyncSocket writeData:footer withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_RESPONSE];
  655. }
  656. else
  657. {
  658. NSData *footer = [GCDAsyncSocket CRLFData];
  659. [asyncSocket writeData:footer withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_CHUNKED_RESPONSE_FOOTER];
  660. }
  661. }
  662. else
  663. {
  664. long tag = [httpResponse isDone] ? HTTP_RESPONSE : HTTP_PARTIAL_RESPONSE_BODY;
  665. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:tag];
  666. }
  667. }
  668. }
  669. else
  670. {
  671. // Client specified a byte range in request
  672. if ([ranges count] == 1)
  673. {
  674. // Client is requesting a single range
  675. DDRange range = [[ranges objectAtIndex:0] ddrangeValue];
  676. [httpResponse setOffset:range.location];
  677. NSUInteger bytesToRead = range.length < READ_CHUNKSIZE ? (NSUInteger)range.length : READ_CHUNKSIZE;
  678. NSData *data = [httpResponse readDataOfLength:bytesToRead];
  679. if ([data length] > 0)
  680. {
  681. [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]];
  682. long tag = [data length] == range.length ? HTTP_RESPONSE : HTTP_PARTIAL_RANGE_RESPONSE_BODY;
  683. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:tag];
  684. }
  685. }
  686. else
  687. {
  688. // Client is requesting multiple ranges
  689. // We have to send each range using multipart/byteranges
  690. // Write range header
  691. NSData *rangeHeaderData = [ranges_headers objectAtIndex:0];
  692. [asyncSocket writeData:rangeHeaderData withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_PARTIAL_RESPONSE_HEADER];
  693. // Start writing range body
  694. DDRange range = [[ranges objectAtIndex:0] ddrangeValue];
  695. [httpResponse setOffset:range.location];
  696. NSUInteger bytesToRead = range.length < READ_CHUNKSIZE ? (NSUInteger)range.length : READ_CHUNKSIZE;
  697. NSData *data = [httpResponse readDataOfLength:bytesToRead];
  698. if ([data length] > 0)
  699. {
  700. [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]];
  701. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:HTTP_PARTIAL_RANGES_RESPONSE_BODY];
  702. }
  703. }
  704. }
  705. }
  706. }
  707. /**
  708. * Returns the number of bytes of the http response body that are sitting in asyncSocket's write queue.
  709. *
  710. * We keep track of this information in order to keep our memory footprint low while
  711. * working with asynchronous HTTPResponse objects.
  712. **/
  713. - (NSUInteger)writeQueueSize
  714. {
  715. NSUInteger result = 0;
  716. NSUInteger i;
  717. for(i = 0; i < [responseDataSizes count]; i++)
  718. {
  719. result += [[responseDataSizes objectAtIndex:i] unsignedIntegerValue];
  720. }
  721. return result;
  722. }
  723. /**
  724. * Sends more data, if needed, without growing the write queue over its approximate size limit.
  725. * The last chunk of the response body will be sent with a tag of HTTP_RESPONSE.
  726. *
  727. * This method should only be called for standard (non-range) responses.
  728. **/
  729. - (void)continueSendingStandardResponseBody
  730. {
  731. HTTPLogTrace();
  732. // This method is called when either asyncSocket has finished writing one of the response data chunks,
  733. // or when an asynchronous HTTPResponse object informs us that it has more available data for us to send.
  734. // In the case of the asynchronous HTTPResponse, we don't want to blindly grab the new data,
  735. // and shove it onto asyncSocket's write queue.
  736. // Doing so could negatively affect the memory footprint of the application.
  737. // Instead, we always ensure that we place no more than READ_CHUNKSIZE bytes onto the write queue.
  738. //
  739. // Note that this does not affect the rate at which the HTTPResponse object may generate data.
  740. // The HTTPResponse is free to do as it pleases, and this is up to the application's developer.
  741. // If the memory footprint is a concern, the developer creating the custom HTTPResponse object may freely
  742. // use the calls to readDataOfLength as an indication to start generating more data.
  743. // This provides an easy way for the HTTPResponse object to throttle its data allocation in step with the rate
  744. // at which the socket is able to send it.
  745. NSUInteger writeQueueSize = [self writeQueueSize];
  746. if(writeQueueSize >= READ_CHUNKSIZE) return;
  747. NSUInteger available = READ_CHUNKSIZE - writeQueueSize;
  748. NSData *data = [httpResponse readDataOfLength:available];
  749. if ([data length] > 0)
  750. {
  751. [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]];
  752. BOOL isChunked = NO;
  753. if ([httpResponse respondsToSelector:@selector(isChunked)])
  754. {
  755. isChunked = [httpResponse isChunked];
  756. }
  757. if (isChunked)
  758. {
  759. NSData *chunkSize = [self chunkedTransferSizeLineForLength:[data length]];
  760. [asyncSocket writeData:chunkSize withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_CHUNKED_RESPONSE_HEADER];
  761. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:HTTP_CHUNKED_RESPONSE_BODY];
  762. if([httpResponse isDone])
  763. {
  764. NSData *footer = [self chunkedTransferFooter];
  765. [asyncSocket writeData:footer withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_RESPONSE];
  766. }
  767. else
  768. {
  769. NSData *footer = [GCDAsyncSocket CRLFData];
  770. [asyncSocket writeData:footer withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_CHUNKED_RESPONSE_FOOTER];
  771. }
  772. }
  773. else
  774. {
  775. long tag = [httpResponse isDone] ? HTTP_RESPONSE : HTTP_PARTIAL_RESPONSE_BODY;
  776. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:tag];
  777. }
  778. }
  779. }
  780. /**
  781. * Sends more data, if needed, without growing the write queue over its approximate size limit.
  782. * The last chunk of the response body will be sent with a tag of HTTP_RESPONSE.
  783. *
  784. * This method should only be called for single-range responses.
  785. **/
  786. - (void)continueSendingSingleRangeResponseBody
  787. {
  788. HTTPLogTrace();
  789. // This method is called when either asyncSocket has finished writing one of the response data chunks,
  790. // or when an asynchronous response informs us that is has more available data for us to send.
  791. // In the case of the asynchronous response, we don't want to blindly grab the new data,
  792. // and shove it onto asyncSocket's write queue.
  793. // Doing so could negatively affect the memory footprint of the application.
  794. // Instead, we always ensure that we place no more than READ_CHUNKSIZE bytes onto the write queue.
  795. //
  796. // Note that this does not affect the rate at which the HTTPResponse object may generate data.
  797. // The HTTPResponse is free to do as it pleases, and this is up to the application's developer.
  798. // If the memory footprint is a concern, the developer creating the custom HTTPResponse object may freely
  799. // use the calls to readDataOfLength as an indication to start generating more data.
  800. // This provides an easy way for the HTTPResponse object to throttle its data allocation in step with the rate
  801. // at which the socket is able to send it.
  802. NSUInteger writeQueueSize = [self writeQueueSize];
  803. if(writeQueueSize >= READ_CHUNKSIZE) return;
  804. DDRange range = [[ranges objectAtIndex:0] ddrangeValue];
  805. UInt64 offset = [httpResponse offset];
  806. UInt64 bytesRead = offset - range.location;
  807. UInt64 bytesLeft = range.length - bytesRead;
  808. if (bytesLeft > 0)
  809. {
  810. NSUInteger available = READ_CHUNKSIZE - writeQueueSize;
  811. NSUInteger bytesToRead = bytesLeft < available ? (NSUInteger)bytesLeft : available;
  812. NSData *data = [httpResponse readDataOfLength:bytesToRead];
  813. if ([data length] > 0)
  814. {
  815. [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]];
  816. long tag = [data length] == bytesLeft ? HTTP_RESPONSE : HTTP_PARTIAL_RANGE_RESPONSE_BODY;
  817. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:tag];
  818. }
  819. }
  820. }
  821. /**
  822. * Sends more data, if needed, without growing the write queue over its approximate size limit.
  823. * The last chunk of the response body will be sent with a tag of HTTP_RESPONSE.
  824. *
  825. * This method should only be called for multi-range responses.
  826. **/
  827. - (void)continueSendingMultiRangeResponseBody
  828. {
  829. HTTPLogTrace();
  830. // This method is called when either asyncSocket has finished writing one of the response data chunks,
  831. // or when an asynchronous HTTPResponse object informs us that is has more available data for us to send.
  832. // In the case of the asynchronous HTTPResponse, we don't want to blindly grab the new data,
  833. // and shove it onto asyncSocket's write queue.
  834. // Doing so could negatively affect the memory footprint of the application.
  835. // Instead, we always ensure that we place no more than READ_CHUNKSIZE bytes onto the write queue.
  836. //
  837. // Note that this does not affect the rate at which the HTTPResponse object may generate data.
  838. // The HTTPResponse is free to do as it pleases, and this is up to the application's developer.
  839. // If the memory footprint is a concern, the developer creating the custom HTTPResponse object may freely
  840. // use the calls to readDataOfLength as an indication to start generating more data.
  841. // This provides an easy way for the HTTPResponse object to throttle its data allocation in step with the rate
  842. // at which the socket is able to send it.
  843. NSUInteger writeQueueSize = [self writeQueueSize];
  844. if(writeQueueSize >= READ_CHUNKSIZE) return;
  845. DDRange range = [[ranges objectAtIndex:rangeIndex] ddrangeValue];
  846. UInt64 offset = [httpResponse offset];
  847. UInt64 bytesRead = offset - range.location;
  848. UInt64 bytesLeft = range.length - bytesRead;
  849. if (bytesLeft > 0)
  850. {
  851. NSUInteger available = READ_CHUNKSIZE - writeQueueSize;
  852. NSUInteger bytesToRead = bytesLeft < available ? (NSUInteger)bytesLeft : available;
  853. NSData *data = [httpResponse readDataOfLength:bytesToRead];
  854. if ([data length] > 0)
  855. {
  856. [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]];
  857. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:HTTP_PARTIAL_RANGES_RESPONSE_BODY];
  858. }
  859. }
  860. else
  861. {
  862. if (++rangeIndex < [ranges count])
  863. {
  864. // Write range header
  865. NSData *rangeHeader = [ranges_headers objectAtIndex:rangeIndex];
  866. [asyncSocket writeData:rangeHeader withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_PARTIAL_RESPONSE_HEADER];
  867. // Start writing range body
  868. range = [[ranges objectAtIndex:rangeIndex] ddrangeValue];
  869. [httpResponse setOffset:range.location];
  870. NSUInteger available = READ_CHUNKSIZE - writeQueueSize;
  871. NSUInteger bytesToRead = range.length < available ? (NSUInteger)range.length : available;
  872. NSData *data = [httpResponse readDataOfLength:bytesToRead];
  873. if ([data length] > 0)
  874. {
  875. [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]];
  876. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:HTTP_PARTIAL_RANGES_RESPONSE_BODY];
  877. }
  878. }
  879. else
  880. {
  881. // We're not done yet - we still have to send the closing boundry tag
  882. NSString *endingBoundryStr = [NSString stringWithFormat:@"\r\n--%@--\r\n", ranges_boundry];
  883. NSData *endingBoundryData = [endingBoundryStr dataUsingEncoding:NSUTF8StringEncoding];
  884. [asyncSocket writeData:endingBoundryData withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_RESPONSE];
  885. }
  886. }
  887. }
  888. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  889. #pragma mark Responses
  890. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  891. /**
  892. * Returns an array of possible index pages.
  893. * For example: {"index.html", "index.htm"}
  894. **/
  895. - (NSArray *)directoryIndexFileNames
  896. {
  897. HTTPLogTrace();
  898. // Override me to support other index pages.
  899. return [NSArray arrayWithObjects:@"index.html", @"index.htm", nil];
  900. }
  901. - (NSString *)filePathForURI:(NSString *)path
  902. {
  903. return [self filePathForURI:path allowDirectory:NO];
  904. }
  905. /**
  906. * Converts relative URI path into full file-system path.
  907. **/
  908. - (NSString *)filePathForURI:(NSString *)path allowDirectory:(BOOL)allowDirectory
  909. {
  910. HTTPLogTrace();
  911. // Override me to perform custom path mapping.
  912. // For example you may want to use a default file other than index.html, or perhaps support multiple types.
  913. NSString *documentRoot = [config documentRoot];
  914. // Part 0: Validate document root setting.
  915. //
  916. // If there is no configured documentRoot,
  917. // then it makes no sense to try to return anything.
  918. if (documentRoot == nil)
  919. {
  920. HTTPLogWarn(@"%@[%p]: No configured document root", THIS_FILE, self);
  921. return nil;
  922. }
  923. // Part 1: Strip parameters from the url
  924. //
  925. // E.g.: /page.html?q=22&var=abc -> /page.html
  926. NSURL *docRoot = [NSURL fileURLWithPath:documentRoot isDirectory:YES];
  927. if (docRoot == nil)
  928. {
  929. HTTPLogWarn(@"%@[%p]: Document root is invalid file path", THIS_FILE, self);
  930. return nil;
  931. }
  932. NSString *relativePath = [[NSURL URLWithString:path relativeToURL:docRoot] relativePath];
  933. // Part 2: Append relative path to document root (base path)
  934. //
  935. // E.g.: relativePath="/images/icon.png"
  936. // documentRoot="/Users/robbie/Sites"
  937. // fullPath="/Users/robbie/Sites/images/icon.png"
  938. //
  939. // We also standardize the path.
  940. //
  941. // E.g.: "Users/robbie/Sites/images/../index.html" -> "/Users/robbie/Sites/index.html"
  942. NSString *fullPath = [[documentRoot stringByAppendingPathComponent:relativePath] stringByStandardizingPath];
  943. if ([relativePath isEqualToString:@"/"])
  944. {
  945. fullPath = [fullPath stringByAppendingString:@"/"];
  946. }
  947. // Part 3: Prevent serving files outside the document root.
  948. //
  949. // Sneaky requests may include ".." in the path.
  950. //
  951. // E.g.: relativePath="../Documents/TopSecret.doc"
  952. // documentRoot="/Users/robbie/Sites"
  953. // fullPath="/Users/robbie/Documents/TopSecret.doc"
  954. //
  955. // E.g.: relativePath="../Sites_Secret/TopSecret.doc"
  956. // documentRoot="/Users/robbie/Sites"
  957. // fullPath="/Users/robbie/Sites_Secret/TopSecret"
  958. if (![documentRoot hasSuffix:@"/"])
  959. {
  960. documentRoot = [documentRoot stringByAppendingString:@"/"];
  961. }
  962. if (![fullPath hasPrefix:documentRoot])
  963. {
  964. HTTPLogWarn(@"%@[%p]: Request for file outside document root", THIS_FILE, self);
  965. return nil;
  966. }
  967. // Part 4: Search for index page if path is pointing to a directory
  968. if (!allowDirectory)
  969. {
  970. BOOL isDir = NO;
  971. if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath isDirectory:&isDir] && isDir)
  972. {
  973. NSArray *indexFileNames = [self directoryIndexFileNames];
  974. for (NSString *indexFileName in indexFileNames)
  975. {
  976. NSString *indexFilePath = [fullPath stringByAppendingPathComponent:indexFileName];
  977. if ([[NSFileManager defaultManager] fileExistsAtPath:indexFilePath isDirectory:&isDir] && !isDir)
  978. {
  979. return indexFilePath;
  980. }
  981. }
  982. // No matching index files found in directory
  983. return nil;
  984. }
  985. }
  986. return fullPath;
  987. }
  988. /**
  989. * This method is called to get a response for a request.
  990. * You may return any object that adopts the HTTPResponse protocol.
  991. * The HTTPServer comes with two such classes: HTTPFileResponse and HTTPDataResponse.
  992. * HTTPFileResponse is a wrapper for an NSFileHandle object, and is the preferred way to send a file response.
  993. * HTTPDataResponse is a wrapper for an NSData object, and may be used to send a custom response.
  994. **/
  995. - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
  996. {
  997. HTTPLogTrace();
  998. // Override me to provide custom responses.
  999. return nil;
  1000. }
  1001. - (WebSocket *)webSocketForURI:(NSString *)path
  1002. {
  1003. HTTPLogTrace();
  1004. // Override me to provide custom WebSocket responses.
  1005. // To do so, simply override the base WebSocket implementation, and add your custom functionality.
  1006. // Then return an instance of your custom WebSocket here.
  1007. //
  1008. // For example:
  1009. //
  1010. // if ([path isEqualToString:@"/myAwesomeWebSocketStream"])
  1011. // {
  1012. // return [[[MyWebSocket alloc] initWithRequest:request socket:asyncSocket] autorelease];
  1013. // }
  1014. //
  1015. // return [super webSocketForURI:path];
  1016. return nil;
  1017. }
  1018. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1019. #pragma mark Uploads
  1020. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1021. /**
  1022. * This method is called after receiving all HTTP headers, but before reading any of the request body.
  1023. **/
  1024. - (void)prepareForBodyWithSize:(UInt64)contentLength
  1025. {
  1026. // Override me to allocate buffers, file handles, etc.
  1027. }
  1028. /**
  1029. * This method is called to handle data read from a POST / PUT.
  1030. * The given data is part of the request body.
  1031. **/
  1032. - (void)processBodyData:(NSData *)postDataChunk
  1033. {
  1034. // Override me to do something useful with a POST / PUT.
  1035. // If the post is small, such as a simple form, you may want to simply append the data to the request.
  1036. // If the post is big, such as a file upload, you may want to store the file to disk.
  1037. //
  1038. // Remember: In order to support LARGE POST uploads, the data is read in chunks.
  1039. // This prevents a 50 MB upload from being stored in RAM.
  1040. // The size of the chunks are limited by the POST_CHUNKSIZE definition.
  1041. // Therefore, this method may be called multiple times for the same POST request.
  1042. }
  1043. /**
  1044. * This method is called after the request body has been fully read but before the HTTP request is processed.
  1045. **/
  1046. - (void)finishBody
  1047. {
  1048. // Override me to perform any final operations on an upload.
  1049. // For example, if you were saving the upload to disk this would be
  1050. // the hook to flush any pending data to disk and maybe close the file.
  1051. }
  1052. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1053. #pragma mark Errors
  1054. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1055. /**
  1056. * Called if the HTML version is other than what is supported
  1057. **/
  1058. - (void)handleVersionNotSupported:(NSString *)version
  1059. {
  1060. // Override me for custom error handling of unsupported http version responses
  1061. // If you simply want to add a few extra header fields, see the preprocessErrorResponse: method.
  1062. // You can also use preprocessErrorResponse: to add an optional HTML body.
  1063. HTTPLogWarn(@"HTTP Server: Error 505 - Version Not Supported: %@ (%@)", version, [self requestURI]);
  1064. HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:505 description:nil version:HTTPVersion1_1];
  1065. [response setHeaderField:@"Content-Length" value:@"0"];
  1066. NSData *responseData = [self preprocessErrorResponse:response];
  1067. [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_ERROR tag:HTTP_RESPONSE];
  1068. }
  1069. /**
  1070. * Called if we receive some sort of malformed HTTP request.
  1071. * The data parameter is the invalid HTTP header line, including CRLF, as read from GCDAsyncSocket.
  1072. * The data parameter may also be nil if the request as a whole was invalid, such as a POST with no Content-Length.
  1073. **/
  1074. - (void)handleInvalidRequest:(NSData *)data
  1075. {
  1076. // Override me for custom error handling of invalid HTTP requests
  1077. // If you simply want to add a few extra header fields, see the preprocessErrorResponse: method.
  1078. // You can also use preprocessErrorResponse: to add an optional HTML body.
  1079. HTTPLogWarn(@"HTTP Server: Error 400 - Bad Request (%@)", [self requestURI]);
  1080. // Status Code 400 - Bad Request
  1081. HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:400 description:nil version:HTTPVersion1_1];
  1082. [response setHeaderField:@"Content-Length" value:@"0"];
  1083. [response setHeaderField:@"Connection" value:@"close"];
  1084. NSData *responseData = [self preprocessErrorResponse:response];
  1085. [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_ERROR tag:HTTP_FINAL_RESPONSE];
  1086. // Note: We used the HTTP_FINAL_RESPONSE tag to disconnect after the response is sent.
  1087. // We do this because we couldn't parse the request,
  1088. // so we won't be able to recover and move on to another request afterwards.
  1089. // In other words, we wouldn't know where the first request ends and the second request begins.
  1090. }
  1091. /**
  1092. * Called if we receive a HTTP request with a method other than GET or HEAD.
  1093. **/
  1094. - (void)handleUnknownMethod:(NSString *)method
  1095. {
  1096. // Override me for custom error handling of 405 method not allowed responses.
  1097. // If you simply want to add a few extra header fields, see the preprocessErrorResponse: method.
  1098. // You can also use preprocessErrorResponse: to add an optional HTML body.
  1099. //
  1100. // See also: supportsMethod:atPath:
  1101. HTTPLogWarn(@"HTTP Server: Error 405 - Method Not Allowed: %@ (%@)", method, [self requestURI]);
  1102. // Status code 405 - Method Not Allowed
  1103. HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:405 description:nil version:HTTPVersion1_1];
  1104. [response setHeaderField:@"Content-Length" value:@"0"];
  1105. [response setHeaderField:@"Connection" value:@"close"];
  1106. NSData *responseData = [self preprocessErrorResponse:response];
  1107. [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_ERROR tag:HTTP_FINAL_RESPONSE];
  1108. // Note: We used the HTTP_FINAL_RESPONSE tag to disconnect after the response is sent.
  1109. // We do this because the method may include an http body.
  1110. // Since we can't be sure, we should close the connection.
  1111. }
  1112. /**
  1113. * Called if we're unable to find the requested resource.
  1114. **/
  1115. - (void)handleResourceNotFound
  1116. {
  1117. // Override me for custom error handling of 404 not found responses
  1118. // If you simply want to add a few extra header fields, see the preprocessErrorResponse: method.
  1119. // You can also use preprocessErrorResponse: to add an optional HTML body.
  1120. HTTPLogInfo(@"HTTP Server: Error 404 - Not Found (%@)", [self requestURI]);
  1121. // Status Code 404 - Not Found
  1122. HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:404 description:nil version:HTTPVersion1_1];
  1123. [response setHeaderField:@"Content-Length" value:@"0"];
  1124. NSData *responseData = [self preprocessErrorResponse:response];
  1125. [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_ERROR tag:HTTP_RESPONSE];
  1126. }
  1127. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1128. #pragma mark Headers
  1129. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1130. /**
  1131. * Gets the current date and time, formatted properly (according to RFC) for insertion into an HTTP header.
  1132. **/
  1133. - (NSString *)dateAsString:(NSDate *)date
  1134. {
  1135. // From Apple's Documentation (Data Formatting Guide -> Date Formatters -> Cache Formatters for Efficiency):
  1136. //
  1137. // "Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently,
  1138. // it is typically more efficient to cache a single instance than to create and dispose of multiple instances.
  1139. // One approach is to use a static variable."
  1140. //
  1141. // This was discovered to be true in massive form via issue #46:
  1142. //
  1143. // "Was doing some performance benchmarking using instruments and httperf. Using this single optimization
  1144. // I got a 26% speed improvement - from 1000req/sec to 3800req/sec. Not insignificant.
  1145. // The culprit? Why, NSDateFormatter, of course!"
  1146. //
  1147. // Thus, we are using a static NSDateFormatter here.
  1148. static NSDateFormatter *df;
  1149. static dispatch_once_t onceToken;
  1150. dispatch_once(&onceToken, ^{
  1151. // Example: Sun, 06 Nov 1994 08:49:37 GMT
  1152. df = [[NSDateFormatter alloc] init];
  1153. [df setFormatterBehavior:NSDateFormatterBehavior10_4];
  1154. [df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
  1155. [df setDateFormat:@"EEE, dd MMM y HH:mm:ss 'GMT'"];
  1156. [df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
  1157. // For some reason, using zzz in the format string produces GMT+00:00
  1158. });
  1159. return [df stringFromDate:date];
  1160. }
  1161. /**
  1162. * This method is called immediately prior to sending the response headers.
  1163. * This method adds standard header fields, and then converts the response to an NSData object.
  1164. **/
  1165. - (NSData *)preprocessResponse:(HTTPMessage *)response
  1166. {
  1167. HTTPLogTrace();
  1168. // Override me to customize the response headers
  1169. // You'll likely want to add your own custom headers, and then return [super preprocessResponse:response]
  1170. // Add standard headers
  1171. NSString *now = [self dateAsString:[NSDate date]];
  1172. [response setHeaderField:@"Date" value:now];
  1173. // Add server capability headers
  1174. [response setHeaderField:@"Accept-Ranges" value:@"bytes"];
  1175. // Add optional response headers
  1176. if ([httpResponse respondsToSelector:@selector(httpHeaders)])
  1177. {
  1178. NSDictionary *responseHeaders = [httpResponse httpHeaders];
  1179. NSEnumerator *keyEnumerator = [responseHeaders keyEnumerator];
  1180. NSString *key;
  1181. while ((key = [keyEnumerator nextObject]))
  1182. {
  1183. NSString *value = [responseHeaders objectForKey:key];
  1184. [response setHeaderField:key value:value];
  1185. }
  1186. }
  1187. return [response messageData];
  1188. }
  1189. /**
  1190. * This method is called immediately prior to sending the response headers (for an error).
  1191. * This method adds standard header fields, and then converts the response to an NSData object.
  1192. **/
  1193. - (NSData *)preprocessErrorResponse:(HTTPMessage *)response
  1194. {
  1195. HTTPLogTrace();
  1196. // Override me to customize the error response headers
  1197. // You'll likely want to add your own custom headers, and then return [super preprocessErrorResponse:response]
  1198. //
  1199. // Notes:
  1200. // You can use [response statusCode] to get the type of error.
  1201. // You can use [response setBody:data] to add an optional HTML body.
  1202. // If you add a body, don't forget to update the Content-Length.
  1203. //
  1204. // if ([response statusCode] == 404)
  1205. // {
  1206. // NSString *msg = @"<html><body>Error 404 - Not Found</body></html>";
  1207. // NSData *msgData = [msg dataUsingEncoding:NSUTF8StringEncoding];
  1208. //
  1209. // [response setBody:msgData];
  1210. //
  1211. // NSString *contentLengthStr = [NSString stringWithFormat:@"%lu", (unsigned long)[msgData length]];
  1212. // [response setHeaderField:@"Content-Length" value:contentLengthStr];
  1213. // }
  1214. // Add standard headers
  1215. NSString *now = [self dateAsString:[NSDate date]];
  1216. [response setHeaderField:@"Date" value:now];
  1217. // Add server capability headers
  1218. [response setHeaderField:@"Accept-Ranges" value:@"bytes"];
  1219. // Add optional response headers
  1220. if ([httpResponse respondsToSelector:@selector(httpHeaders)])
  1221. {
  1222. NSDictionary *responseHeaders = [httpResponse httpHeaders];
  1223. NSEnumerator *keyEnumerator = [responseHeaders keyEnumerator];
  1224. NSString *key;
  1225. while((key = [keyEnumerator nextObject]))
  1226. {
  1227. NSString *value = [responseHeaders objectForKey:key];
  1228. [response setHeaderField:key value:value];
  1229. }
  1230. }
  1231. return [response messageData];
  1232. }
  1233. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1234. #pragma mark GCDAsyncSocket Delegate
  1235. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1236. /**
  1237. * This method is called after the socket has successfully read data from the stream.
  1238. * Remember that this method will only be called after the socket reaches a CRLF, or after it's read the proper length.
  1239. **/
  1240. - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData*)data withTag:(long)tag
  1241. {
  1242. if (tag == HTTP_REQUEST_HEADER)
  1243. {
  1244. // Append the header line to the http message
  1245. BOOL result = [request appendData:data];
  1246. if (!result)
  1247. {
  1248. HTTPLogWarn(@"%@[%p]: Malformed request", THIS_FILE, self);
  1249. [self handleInvalidRequest:data];
  1250. }
  1251. else if (![request isHeaderComplete])
  1252. {
  1253. // We don't have a complete header yet
  1254. // That is, we haven't yet received a CRLF on a line by itself, indicating the end of the header
  1255. if (++numHeaderLines > MAX_HEADER_LINES)
  1256. {
  1257. // Reached the maximum amount of header lines in a single HTTP request
  1258. // This could be an attempted DOS attack
  1259. [asyncSocket disconnect];
  1260. // Explictly return to ensure we don't do anything after the socket disconnect
  1261. return;
  1262. }
  1263. else
  1264. {
  1265. [asyncSocket readDataToData:[GCDAsyncSocket CRLFData]
  1266. withTimeout:TIMEOUT_READ_SUBSEQUENT_HEADER_LINE
  1267. maxLength:MAX_HEADER_LINE_LENGTH
  1268. tag:HTTP_REQUEST_HEADER];
  1269. }
  1270. }
  1271. else
  1272. {
  1273. // We have an entire HTTP request header from the client
  1274. // Extract the method (such as GET, HEAD, POST, etc)
  1275. NSString *method = [request method];
  1276. // Extract the uri (such as "/index.html")
  1277. NSString *uri = [self requestURI];
  1278. // Check for a Transfer-Encoding field
  1279. NSString *transferEncoding = [request headerField:@"Transfer-Encoding"];
  1280. // Check for a Content-Length field
  1281. NSString *contentLength = [request headerField:@"Content-Length"];
  1282. // Content-Length MUST be present for upload methods (such as POST or PUT)
  1283. // and MUST NOT be present for other methods.
  1284. BOOL expectsUpload = [self expectsRequestBodyFromMethod:method atPath:uri];
  1285. if (expectsUpload)
  1286. {
  1287. if (transferEncoding && ![transferEncoding caseInsensitiveCompare:@"Chunked"])
  1288. {
  1289. requestContentLength = -1;
  1290. }
  1291. else
  1292. {
  1293. if (contentLength == nil)
  1294. {
  1295. HTTPLogWarn(@"%@[%p]: Method expects request body, but had no specified Content-Length",
  1296. THIS_FILE, self);
  1297. [self handleInvalidRequest:nil];
  1298. return;
  1299. }
  1300. if (![NSNumber parseString:(NSString *)contentLength intoUInt64:&requestContentLength])
  1301. {
  1302. HTTPLogWarn(@"%@[%p]: Unable to parse Content-Length header into a valid number",
  1303. THIS_FILE, self);
  1304. [self handleInvalidRequest:nil];
  1305. return;
  1306. }
  1307. }
  1308. }
  1309. else
  1310. {
  1311. if (contentLength != nil)
  1312. {
  1313. // Received Content-Length header for method not expecting an upload.
  1314. // This better be zero...
  1315. if (![NSNumber parseString:(NSString *)contentLength intoUInt64:&requestContentLength])
  1316. {
  1317. HTTPLogWarn(@"%@[%p]: Unable to parse Content-Length header into a valid number",
  1318. THIS_FILE, self);
  1319. [self handleInvalidRequest:nil];
  1320. return;
  1321. }
  1322. if (requestContentLength > 0)
  1323. {
  1324. HTTPLogWarn(@"%@[%p]: Method not expecting request body had non-zero Content-Length",
  1325. THIS_FILE, self);
  1326. [self handleInvalidRequest:nil];
  1327. return;
  1328. }
  1329. }
  1330. requestContentLength = 0;
  1331. requestContentLengthReceived = 0;
  1332. }
  1333. // Check to make sure the given method is supported
  1334. if (![self supportsMethod:method atPath:uri])
  1335. {
  1336. // The method is unsupported - either in general, or for this specific request
  1337. // Send a 405 - Method not allowed response
  1338. [self handleUnknownMethod:method];
  1339. return;
  1340. }
  1341. if (expectsUpload)
  1342. {
  1343. // Reset the total amount of data received for the upload
  1344. requestContentLengthReceived = 0;
  1345. // Prepare for the upload
  1346. [self prepareForBodyWithSize:requestContentLength];
  1347. if (requestContentLength > 0)
  1348. {
  1349. // Start reading the request body
  1350. if (requestContentLength == -1)
  1351. {
  1352. // Chunked transfer
  1353. [asyncSocket readDataToData:[GCDAsyncSocket CRLFData]
  1354. withTimeout:TIMEOUT_READ_BODY
  1355. maxLength:MAX_CHUNK_LINE_LENGTH
  1356. tag:HTTP_REQUEST_CHUNK_SIZE];
  1357. }
  1358. else
  1359. {
  1360. NSUInteger bytesToRead;
  1361. if (requestContentLength < POST_CHUNKSIZE)
  1362. bytesToRead = (NSUInteger)requestContentLength;
  1363. else
  1364. bytesToRead = POST_CHUNKSIZE;
  1365. [asyncSocket readDataToLength:bytesToRead
  1366. withTimeout:TIMEOUT_READ_BODY
  1367. tag:HTTP_REQUEST_BODY];
  1368. }
  1369. }
  1370. else
  1371. {
  1372. // Empty upload
  1373. [self finishBody];
  1374. [self replyToHTTPRequest];
  1375. }
  1376. }
  1377. else
  1378. {
  1379. // Now we need to reply to the request
  1380. [self replyToHTTPRequest];
  1381. }
  1382. }
  1383. }
  1384. else
  1385. {
  1386. BOOL doneReadingRequest = NO;
  1387. // A chunked message body contains a series of chunks,
  1388. // followed by a line with "0" (zero),
  1389. // followed by optional footers (just like headers),
  1390. // and a blank line.
  1391. //
  1392. // Each chunk consists of two parts:
  1393. //
  1394. // 1. A line with the size of the chunk data, in hex,
  1395. // possibly followed by a semicolon and extra parameters you can ignore (none are currently standard),
  1396. // and ending with CRLF.
  1397. // 2. The data itself, followed by CRLF.
  1398. //
  1399. // Part 1 is represented by HTTP_REQUEST_CHUNK_SIZE
  1400. // Part 2 is represented by HTTP_REQUEST_CHUNK_DATA and HTTP_REQUEST_CHUNK_TRAILER
  1401. // where the trailer is the CRLF that follows the data.
  1402. //
  1403. // The optional footers and blank line are represented by HTTP_REQUEST_CHUNK_FOOTER.
  1404. if (tag == HTTP_REQUEST_CHUNK_SIZE)
  1405. {
  1406. // We have just read in a line with the size of the chunk data, in hex,
  1407. // possibly followed by a semicolon and extra parameters that can be ignored,
  1408. // and ending with CRLF.
  1409. NSString *sizeLine = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  1410. errno = 0; // Reset errno before calling strtoull() to ensure it is always zero on success
  1411. requestChunkSize = (UInt64)strtoull([sizeLine UTF8String], NULL, 16);
  1412. requestChunkSizeReceived = 0;
  1413. if (errno != 0)
  1414. {
  1415. HTTPLogWarn(@"%@[%p]: Method expects chunk size, but received something else", THIS_FILE, self);
  1416. [self handleInvalidRequest:nil];
  1417. return;
  1418. }
  1419. if (requestChunkSize > 0)
  1420. {
  1421. NSUInteger bytesToRead;
  1422. bytesToRead = (requestChunkSize < POST_CHUNKSIZE) ? (NSUInteger)requestChunkSize : POST_CHUNKSIZE;
  1423. [asyncSocket readDataToLength:bytesToRead
  1424. withTimeout:TIMEOUT_READ_BODY
  1425. tag:HTTP_REQUEST_CHUNK_DATA];
  1426. }
  1427. else
  1428. {
  1429. // This is the "0" (zero) line,
  1430. // which is to be followed by optional footers (just like headers) and finally a blank line.
  1431. [asyncSocket readDataToData:[GCDAsyncSocket CRLFData]
  1432. withTimeout:TIMEOUT_READ_BODY
  1433. maxLength:MAX_HEADER_LINE_LENGTH
  1434. tag:HTTP_REQUEST_CHUNK_FOOTER];
  1435. }
  1436. return;
  1437. }
  1438. else if (tag == HTTP_REQUEST_CHUNK_DATA)
  1439. {
  1440. // We just read part of the actual data.
  1441. requestContentLengthReceived += [data length];
  1442. requestChunkSizeReceived += [data length];
  1443. [self processBodyData:data];
  1444. UInt64 bytesLeft = requestChunkSize - requestChunkSizeReceived;
  1445. if (bytesLeft > 0)
  1446. {
  1447. NSUInteger bytesToRead = (bytesLeft < POST_CHUNKSIZE) ? (NSUInteger)bytesLeft : POST_CHUNKSIZE;
  1448. [asyncSocket readDataToLength:bytesToRead
  1449. withTimeout:TIMEOUT_READ_BODY
  1450. tag:HTTP_REQUEST_CHUNK_DATA];
  1451. }
  1452. else
  1453. {
  1454. // We've read in all the data for this chunk.
  1455. // The data is followed by a CRLF, which we need to read (and basically ignore)
  1456. [asyncSocket readDataToLength:2
  1457. withTimeout:TIMEOUT_READ_BODY
  1458. tag:HTTP_REQUEST_CHUNK_TRAILER];
  1459. }
  1460. return;
  1461. }
  1462. else if (tag == HTTP_REQUEST_CHUNK_TRAILER)
  1463. {
  1464. // This should be the CRLF following the data.
  1465. // Just ensure it's a CRLF.
  1466. if (![data isEqualToData:[GCDAsyncSocket CRLFData]])
  1467. {
  1468. HTTPLogWarn(@"%@[%p]: Method expects chunk trailer, but is missing", THIS_FILE, self);
  1469. [self handleInvalidRequest:nil];
  1470. return;
  1471. }
  1472. // Now continue with the next chunk
  1473. [asyncSocket readDataToData:[GCDAsyncSocket CRLFData]
  1474. withTimeout:TIMEOUT_READ_BODY
  1475. maxLength:MAX_CHUNK_LINE_LENGTH
  1476. tag:HTTP_REQUEST_CHUNK_SIZE];
  1477. }
  1478. else if (tag == HTTP_REQUEST_CHUNK_FOOTER)
  1479. {
  1480. if (++numHeaderLines > MAX_HEADER_LINES)
  1481. {
  1482. // Reached the maximum amount of header lines in a single HTTP request
  1483. // This could be an attempted DOS attack
  1484. [asyncSocket disconnect];
  1485. // Explictly return to ensure we don't do anything after the socket disconnect
  1486. return;
  1487. }
  1488. if ([data length] > 2)
  1489. {
  1490. // We read in a footer.
  1491. // In the future we may want to append these to the request.
  1492. // For now we ignore, and continue reading the footers, waiting for the final blank line.
  1493. [asyncSocket readDataToData:[GCDAsyncSocket CRLFData]
  1494. withTimeout:TIMEOUT_READ_BODY
  1495. maxLength:MAX_HEADER_LINE_LENGTH
  1496. tag:HTTP_REQUEST_CHUNK_FOOTER];
  1497. }
  1498. else
  1499. {
  1500. doneReadingRequest = YES;
  1501. }
  1502. }
  1503. else // HTTP_REQUEST_BODY
  1504. {
  1505. // Handle a chunk of data from the POST body
  1506. requestContentLengthReceived += [data length];
  1507. [self processBodyData:data];
  1508. if (requestContentLengthReceived < requestContentLength)
  1509. {
  1510. // We're not done reading the post body yet...
  1511. UInt64 bytesLeft = requestContentLength - requestContentLengthReceived;
  1512. NSUInteger bytesToRead = bytesLeft < POST_CHUNKSIZE ? (NSUInteger)bytesLeft : POST_CHUNKSIZE;
  1513. [asyncSocket readDataToLength:bytesToRead
  1514. withTimeout:TIMEOUT_READ_BODY
  1515. tag:HTTP_REQUEST_BODY];
  1516. }
  1517. else
  1518. {
  1519. doneReadingRequest = YES;
  1520. }
  1521. }
  1522. // Now that the entire body has been received, we need to reply to the request
  1523. if (doneReadingRequest)
  1524. {
  1525. [self finishBody];
  1526. [self replyToHTTPRequest];
  1527. }
  1528. }
  1529. }
  1530. /**
  1531. * This method is called after the socket has successfully written data to the stream.
  1532. **/
  1533. - (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
  1534. {
  1535. BOOL doneSendingResponse = NO;
  1536. if (tag == HTTP_PARTIAL_RESPONSE_BODY)
  1537. {
  1538. // Update the amount of data we have in asyncSocket's write queue
  1539. if ([responseDataSizes count] > 0) {
  1540. [responseDataSizes removeObjectAtIndex:0];
  1541. }
  1542. // We only wrote a part of the response - there may be more
  1543. [self continueSendingStandardResponseBody];
  1544. }
  1545. else if (tag == HTTP_CHUNKED_RESPONSE_BODY)
  1546. {
  1547. // Update the amount of data we have in asyncSocket's write queue.
  1548. // This will allow asynchronous responses to continue sending more data.
  1549. if ([responseDataSizes count] > 0) {
  1550. [responseDataSizes removeObjectAtIndex:0];
  1551. }
  1552. // Don't continue sending the response yet.
  1553. // The chunked footer that was sent after the body will tell us if we have more data to send.
  1554. }
  1555. else if (tag == HTTP_CHUNKED_RESPONSE_FOOTER)
  1556. {
  1557. // Normal chunked footer indicating we have more data to send (non final footer).
  1558. [self continueSendingStandardResponseBody];
  1559. }
  1560. else if (tag == HTTP_PARTIAL_RANGE_RESPONSE_BODY)
  1561. {
  1562. // Update the amount of data we have in asyncSocket's write queue
  1563. if ([responseDataSizes count] > 0) {
  1564. [responseDataSizes removeObjectAtIndex:0];
  1565. }
  1566. // We only wrote a part of the range - there may be more
  1567. [self continueSendingSingleRangeResponseBody];
  1568. }
  1569. else if (tag == HTTP_PARTIAL_RANGES_RESPONSE_BODY)
  1570. {
  1571. // Update the amount of data we have in asyncSocket's write queue
  1572. if ([responseDataSizes count] > 0) {
  1573. [responseDataSizes removeObjectAtIndex:0];
  1574. }
  1575. // We only wrote part of the range - there may be more, or there may be more ranges
  1576. [self continueSendingMultiRangeResponseBody];
  1577. }
  1578. else if (tag == HTTP_RESPONSE || tag == HTTP_FINAL_RESPONSE)
  1579. {
  1580. // Update the amount of data we have in asyncSocket's write queue
  1581. if ([responseDataSizes count] > 0)
  1582. {
  1583. [responseDataSizes removeObjectAtIndex:0];
  1584. }
  1585. doneSendingResponse = YES;
  1586. }
  1587. if (doneSendingResponse)
  1588. {
  1589. // Inform the http response that we're done
  1590. if ([httpResponse respondsToSelector:@selector(connectionDidClose)])
  1591. {
  1592. [httpResponse connectionDidClose];
  1593. }
  1594. if (tag == HTTP_FINAL_RESPONSE)
  1595. {
  1596. // Cleanup after the last request
  1597. [self finishResponse];
  1598. // Terminate the connection
  1599. [asyncSocket disconnect];
  1600. // Explictly return to ensure we don't do anything after the socket disconnects
  1601. return;
  1602. }
  1603. else
  1604. {
  1605. if ([self shouldDie])
  1606. {
  1607. // Cleanup after the last request
  1608. // Note: Don't do this before calling shouldDie, as it needs the request object still.
  1609. [self finishResponse];
  1610. // The only time we should invoke [self die] is from socketDidDisconnect,
  1611. // or if the socket gets taken over by someone else like a WebSocket.
  1612. [asyncSocket disconnect];
  1613. }
  1614. else
  1615. {
  1616. // Cleanup after the last request
  1617. [self finishResponse];
  1618. // Prepare for the next request
  1619. // If this assertion fails, it likely means you overrode the
  1620. // finishBody method and forgot to call [super finishBody].
  1621. NSAssert(request == nil, @"Request not properly released in finishBody");
  1622. request = [[HTTPMessage alloc] initEmptyRequest];
  1623. numHeaderLines = 0;
  1624. sentResponseHeaders = NO;
  1625. // And start listening for more requests
  1626. [self startReadingRequest];
  1627. }
  1628. }
  1629. }
  1630. }
  1631. /**
  1632. * Sent after the socket has been disconnected.
  1633. **/
  1634. - (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
  1635. {
  1636. HTTPLogTrace();
  1637. asyncSocket = nil;
  1638. [self die];
  1639. }
  1640. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1641. #pragma mark HTTPResponse Notifications
  1642. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1643. /**
  1644. * This method may be called by asynchronous HTTPResponse objects.
  1645. * That is, HTTPResponse objects that return YES in their "- (BOOL)isAsynchronous" method.
  1646. *
  1647. * This informs us that the response object has generated more data that we may be able to send.
  1648. **/
  1649. - (void)responseHasAvailableData:(NSObject<HTTPResponse> *)sender
  1650. {
  1651. HTTPLogTrace();
  1652. // We always dispatch this asynchronously onto our connectionQueue,
  1653. // even if the connectionQueue is the current queue.
  1654. //
  1655. // We do this to give the HTTPResponse classes the flexibility to call
  1656. // this method whenever they want, even from within a readDataOfLength method.
  1657. dispatch_async(connectionQueue, ^{ @autoreleasepool {
  1658. if (sender != httpResponse)
  1659. {
  1660. HTTPLogWarn(@"%@[%p]: %@ - Sender is not current httpResponse", THIS_FILE, self, THIS_METHOD);
  1661. return;
  1662. }
  1663. if (!sentResponseHeaders)
  1664. {
  1665. [self sendResponseHeadersAndBody];
  1666. }
  1667. else
  1668. {
  1669. if (ranges == nil)
  1670. {
  1671. [self continueSendingStandardResponseBody];
  1672. }
  1673. else
  1674. {
  1675. if ([ranges count] == 1)
  1676. [self continueSendingSingleRangeResponseBody];
  1677. else
  1678. [self continueSendingMultiRangeResponseBody];
  1679. }
  1680. }
  1681. }});
  1682. }
  1683. /**
  1684. * This method is called if the response encounters some critical error,
  1685. * and it will be unable to fullfill the request.
  1686. **/
  1687. - (void)responseDidAbort:(NSObject<HTTPResponse> *)sender
  1688. {
  1689. HTTPLogTrace();
  1690. // We always dispatch this asynchronously onto our connectionQueue,
  1691. // even if the connectionQueue is the current queue.
  1692. //
  1693. // We do this to give the HTTPResponse classes the flexibility to call
  1694. // this method whenever they want, even from within a readDataOfLength method.
  1695. dispatch_async(connectionQueue, ^{ @autoreleasepool {
  1696. if (sender != httpResponse)
  1697. {
  1698. HTTPLogWarn(@"%@[%p]: %@ - Sender is not current httpResponse", THIS_FILE, self, THIS_METHOD);
  1699. return;
  1700. }
  1701. [asyncSocket disconnectAfterWriting];
  1702. }});
  1703. }
  1704. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1705. #pragma mark Post Request
  1706. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1707. /**
  1708. * This method is called after each response has been fully sent.
  1709. * Since a single connection may handle multiple request/responses, this method may be called multiple times.
  1710. * That is, it will be called after completion of each response.
  1711. **/
  1712. - (void)finishResponse
  1713. {
  1714. HTTPLogTrace();
  1715. // Override me if you want to perform any custom actions after a response has been fully sent.
  1716. // This is the place to release memory or resources associated with the last request.
  1717. //
  1718. // If you override this method, you should take care to invoke [super finishResponse] at some point.
  1719. request = nil;
  1720. httpResponse = nil;
  1721. ranges = nil;
  1722. ranges_headers = nil;
  1723. ranges_boundry = nil;
  1724. }
  1725. /**
  1726. * This method is called after each successful response has been fully sent.
  1727. * It determines whether the connection should stay open and handle another request.
  1728. **/
  1729. - (BOOL)shouldDie
  1730. {
  1731. HTTPLogTrace();
  1732. // Override me if you have any need to force close the connection.
  1733. // You may do so by simply returning YES.
  1734. //
  1735. // If you override this method, you should take care to fall through with [super shouldDie]
  1736. // instead of returning NO.
  1737. BOOL shouldDie = NO;
  1738. NSString *version = [request version];
  1739. if ([version isEqualToString:HTTPVersion1_1])
  1740. {
  1741. // HTTP version 1.1
  1742. // Connection should only be closed if request included "Connection: close" header
  1743. NSString *connection = [request headerField:@"Connection"];
  1744. shouldDie = (connection && ([connection caseInsensitiveCompare:@"close"] == NSOrderedSame));
  1745. }
  1746. else if ([version isEqualToString:HTTPVersion1_0])
  1747. {
  1748. // HTTP version 1.0
  1749. // Connection should be closed unless request included "Connection: Keep-Alive" header
  1750. NSString *connection = [request headerField:@"Connection"];
  1751. if (connection == nil)
  1752. shouldDie = YES;
  1753. else
  1754. shouldDie = [connection caseInsensitiveCompare:@"Keep-Alive"] != NSOrderedSame;
  1755. }
  1756. return shouldDie;
  1757. }
  1758. - (void)die
  1759. {
  1760. HTTPLogTrace();
  1761. // Override me if you want to perform any custom actions when a connection is closed.
  1762. // Then call [super die] when you're done.
  1763. //
  1764. // See also the finishResponse method.
  1765. //
  1766. // Important: There is a rare timing condition where this method might get invoked twice.
  1767. // If you override this method, you should be prepared for this situation.
  1768. // Inform the http response that we're done
  1769. if ([httpResponse respondsToSelector:@selector(connectionDidClose)])
  1770. {
  1771. [httpResponse connectionDidClose];
  1772. }
  1773. // Release the http response so we don't call it's connectionDidClose method again in our dealloc method
  1774. httpResponse = nil;
  1775. // Post notification of dead connection
  1776. // This will allow our server to release us from its array of connections
  1777. [[NSNotificationCenter defaultCenter] postNotificationName:HTTPConnectionDidDieNotification object:self];
  1778. }
  1779. @end
  1780. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1781. #pragma mark -
  1782. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1783. @implementation HTTPConfig
  1784. @synthesize server;
  1785. @synthesize documentRoot;
  1786. @synthesize queue;
  1787. - (id)initWithServer:(HTTPServer *)aServer documentRoot:(NSString *)aDocumentRoot
  1788. {
  1789. if ((self = [super init]))
  1790. {
  1791. server = aServer;
  1792. documentRoot = aDocumentRoot;
  1793. }
  1794. return self;
  1795. }
  1796. - (id)initWithServer:(HTTPServer *)aServer documentRoot:(NSString *)aDocumentRoot queue:(dispatch_queue_t)q
  1797. {
  1798. if ((self = [super init]))
  1799. {
  1800. server = aServer;
  1801. documentRoot = [aDocumentRoot stringByStandardizingPath];
  1802. if ([documentRoot hasSuffix:@"/"])
  1803. {
  1804. documentRoot = [documentRoot stringByAppendingString:@"/"];
  1805. }
  1806. if (q)
  1807. {
  1808. queue = q;
  1809. #if !OS_OBJECT_USE_OBJC
  1810. dispatch_retain(queue);
  1811. #endif
  1812. }
  1813. }
  1814. return self;
  1815. }
  1816. - (void)dealloc
  1817. {
  1818. #if !OS_OBJECT_USE_OBJC
  1819. if (queue) dispatch_release(queue);
  1820. #endif
  1821. }
  1822. @end