HTTPConnection.m 99 KB

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