HTTPConnection.m 85 KB

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