PageRenderTime 364ms CodeModel.GetById 51ms RepoModel.GetById 63ms app.codeStats 8ms

/io/libraries/CocoaHttpServer/HTTPConnection.m

https://gitlab.com/base.io/io
Objective C | 1547 lines | 804 code | 310 blank | 433 comment | 120 complexity | ef67afc2a1aa8f96411ce0d0150915f7 MD5 | raw file
  1. #import "GCDAsyncSocket.h"
  2. #import "HTTPServer.h"
  3. #import "HTTPConnection.h"
  4. #import "HTTPMessage.h"
  5. #import "HTTPResponse.h"
  6. #import "HTTPAuthenticationRequest.h"
  7. #import "DDNumber.h"
  8. #import "DDRange.h"
  9. #import "DDData.h"
  10. #import "HTTPFileResponse.h"
  11. #import "HTTPAsyncFileResponse.h"
  12. #import "WebSocket.h"
  13. #import "HTTPLogging.h"
  14. #if ! __has_feature(objc_arc)
  15. #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
  16. #endif
  17. // Log levels: off, error, warn, info, verbose
  18. // Other flags: trace
  19. static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; // | HTTP_LOG_FLAG_TRACE;
  20. // Define chunk size used to read in data for responses
  21. // This is how much data will be read from disk into RAM at a time
  22. #if TARGET_OS_IPHONE
  23. #define READ_CHUNKSIZE (1024 * 128)
  24. #else
  25. #define READ_CHUNKSIZE (1024 * 512)
  26. #endif
  27. // Define chunk size used to read in POST upload data
  28. #if TARGET_OS_IPHONE
  29. #define POST_CHUNKSIZE (1024 * 32)
  30. #else
  31. #define POST_CHUNKSIZE (1024 * 128)
  32. #endif
  33. // Define the various timeouts (in seconds) for various parts of the HTTP process
  34. #define TIMEOUT_READ_FIRST_HEADER_LINE 30
  35. #define TIMEOUT_READ_SUBSEQUENT_HEADER_LINE 30
  36. #define TIMEOUT_READ_BODY -1
  37. #define TIMEOUT_WRITE_HEAD 30
  38. #define TIMEOUT_WRITE_BODY -1
  39. #define TIMEOUT_WRITE_ERROR 30
  40. #define TIMEOUT_NONCE 300
  41. // Define the various limits
  42. // MAX_HEADER_LINE_LENGTH: Max length (in bytes) of any single line in a header (including \r\n)
  43. // MAX_HEADER_LINES : Max number of lines in a single header (including first GET line)
  44. #define MAX_HEADER_LINE_LENGTH 8190
  45. #define MAX_HEADER_LINES 100
  46. // MAX_CHUNK_LINE_LENGTH : For accepting chunked transfer uploads, max length of chunk size line (including \r\n)
  47. #define MAX_CHUNK_LINE_LENGTH 200
  48. // Define the various tags we'll use to differentiate what it is we're currently doing
  49. #define HTTP_REQUEST_HEADER 10
  50. #define HTTP_REQUEST_BODY 11
  51. #define HTTP_REQUEST_CHUNK_SIZE 12
  52. #define HTTP_REQUEST_CHUNK_DATA 13
  53. #define HTTP_REQUEST_CHUNK_TRAILER 14
  54. #define HTTP_REQUEST_CHUNK_FOOTER 15
  55. #define HTTP_PARTIAL_RESPONSE 20
  56. #define HTTP_PARTIAL_RESPONSE_HEADER 21
  57. #define HTTP_PARTIAL_RESPONSE_BODY 22
  58. #define HTTP_CHUNKED_RESPONSE_HEADER 30
  59. #define HTTP_CHUNKED_RESPONSE_BODY 31
  60. #define HTTP_CHUNKED_RESPONSE_FOOTER 32
  61. #define HTTP_PARTIAL_RANGE_RESPONSE_BODY 40
  62. #define HTTP_PARTIAL_RANGES_RESPONSE_BODY 50
  63. #define HTTP_RESPONSE 90
  64. #define HTTP_FINAL_RESPONSE 91
  65. // A quick note about the tags:
  66. //
  67. // The HTTP_RESPONSE and HTTP_FINAL_RESPONSE are designated tags signalling that the response is completely sent.
  68. // That is, in the onSocket:didWriteDataWithTag: method, if the tag is HTTP_RESPONSE or HTTP_FINAL_RESPONSE,
  69. // it is assumed that the response is now completely sent.
  70. // Use HTTP_RESPONSE if it's the end of a response, and you want to start reading more requests afterwards.
  71. // Use HTTP_FINAL_RESPONSE if you wish to terminate the connection after sending the response.
  72. //
  73. // If you are sending multiple data segments in a custom response, make sure that only the last segment has
  74. // the HTTP_RESPONSE tag. For all other segments prior to the last segment use HTTP_PARTIAL_RESPONSE, or some other
  75. // tag of your own invention.
  76. @interface HTTPConnection (PrivateAPI)
  77. - (void)startReadingRequest;
  78. - (void)sendResponseHeadersAndBody;
  79. @end
  80. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  81. #pragma mark -
  82. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  83. @implementation HTTPConnection
  84. static dispatch_queue_t recentNonceQueue;
  85. static NSMutableArray *recentNonces;
  86. /**
  87. * This method is automatically called (courtesy of Cocoa) before the first instantiation of this class.
  88. * We use it to initialize any static variables.
  89. **/
  90. + (void)initialize
  91. {
  92. static dispatch_once_t onceToken;
  93. dispatch_once(&onceToken, ^{
  94. // Initialize class variables
  95. recentNonceQueue = dispatch_queue_create("HTTPConnection-Nonce", NULL);
  96. recentNonces = [[NSMutableArray alloc] initWithCapacity:5];
  97. });
  98. }
  99. /**
  100. * Generates and returns an authentication nonce.
  101. * A nonce is a server-specified string uniquely generated for each 401 response.
  102. * The default implementation uses a single nonce for each session.
  103. **/
  104. + (NSString *)generateNonce
  105. {
  106. // We use the Core Foundation UUID class to generate a nonce value for us
  107. // UUIDs (Universally Unique Identifiers) are 128-bit values guaranteed to be unique.
  108. CFUUIDRef theUUID = CFUUIDCreate(NULL);
  109. NSString *newNonce = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, theUUID);
  110. CFRelease(theUUID);
  111. // We have to remember that the HTTP protocol is stateless.
  112. // Even though with version 1.1 persistent connections are the norm, they are not guaranteed.
  113. // Thus if we generate a nonce for this connection,
  114. // it should be honored for other connections in the near future.
  115. //
  116. // In fact, this is absolutely necessary in order to support QuickTime.
  117. // When QuickTime makes it's initial connection, it will be unauthorized, and will receive a nonce.
  118. // It then disconnects, and creates a new connection with the nonce, and proper authentication.
  119. // If we don't honor the nonce for the second connection, QuickTime will repeat the process and never connect.
  120. dispatch_async(recentNonceQueue, ^{ @autoreleasepool {
  121. [recentNonces addObject:newNonce];
  122. }});
  123. double delayInSeconds = TIMEOUT_NONCE;
  124. dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
  125. dispatch_after(popTime, recentNonceQueue, ^{ @autoreleasepool {
  126. [recentNonces removeObject:newNonce];
  127. }});
  128. return newNonce;
  129. }
  130. /**
  131. * Returns whether or not the given nonce is in the list of recently generated nonce's.
  132. **/
  133. + (BOOL)hasRecentNonce:(NSString *)recentNonce
  134. {
  135. __block BOOL result = NO;
  136. dispatch_sync(recentNonceQueue, ^{ @autoreleasepool {
  137. result = [recentNonces containsObject:recentNonce];
  138. }});
  139. return result;
  140. }
  141. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  142. #pragma mark Init, Dealloc:
  143. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  144. /**
  145. * Sole Constructor.
  146. * Associates this new HTTP connection with the given AsyncSocket.
  147. * This HTTP connection object will become the socket's delegate and take over responsibility for the socket.
  148. **/
  149. - (id)initWithAsyncSocket:(GCDAsyncSocket *)newSocket configuration:(HTTPConfig *)aConfig
  150. {
  151. if ((self = [super init]))
  152. {
  153. HTTPLogTrace();
  154. if (aConfig.queue)
  155. {
  156. connectionQueue = aConfig.queue;
  157. dispatch_retain(connectionQueue);
  158. }
  159. else
  160. {
  161. connectionQueue = dispatch_queue_create("HTTPConnection", NULL);
  162. }
  163. // Take over ownership of the socket
  164. asyncSocket = newSocket;
  165. [asyncSocket setDelegate:self delegateQueue:connectionQueue];
  166. // Store configuration
  167. config = aConfig;
  168. // Initialize lastNC (last nonce count).
  169. // Used with digest access authentication.
  170. // These must increment for each request from the client.
  171. lastNC = 0;
  172. // Create a new HTTP message
  173. request = [[HTTPMessage alloc] initEmptyRequest];
  174. numHeaderLines = 0;
  175. responseDataSizes = [[NSMutableArray alloc] initWithCapacity:5];
  176. }
  177. return self;
  178. }
  179. /**
  180. * Standard Deconstructor.
  181. **/
  182. - (void)dealloc
  183. {
  184. HTTPLogTrace();
  185. dispatch_release(connectionQueue);
  186. [asyncSocket setDelegate:nil delegateQueue:NULL];
  187. [asyncSocket disconnect];
  188. if ([httpResponse respondsToSelector:@selector(connectionDidClose)])
  189. {
  190. [httpResponse connectionDidClose];
  191. }
  192. }
  193. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  194. #pragma mark Method Support
  195. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  196. /**
  197. * Returns whether or not the server will accept messages of a given method
  198. * at a particular URI.
  199. **/
  200. - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
  201. {
  202. HTTPLogTrace();
  203. // Override me to support methods such as POST.
  204. //
  205. // Things you may want to consider:
  206. // - Does the given path represent a resource that is designed to accept this method?
  207. // - If accepting an upload, is the size of the data being uploaded too big?
  208. // To do this you can check the requestContentLength variable.
  209. //
  210. // For more information, you can always access the HTTPMessage request variable.
  211. //
  212. // You should fall through with a call to [super supportsMethod:method atPath:path]
  213. //
  214. // See also: expectsRequestBodyFromMethod:atPath:
  215. if ([method isEqualToString:@"GET"])
  216. return YES;
  217. if ([method isEqualToString:@"HEAD"])
  218. return YES;
  219. return NO;
  220. }
  221. /**
  222. * Returns whether or not the server expects a body from the given method.
  223. *
  224. * In other words, should the server expect a content-length header and associated body from this method.
  225. * This would be true in the case of a POST, where the client is sending data,
  226. * or for something like PUT where the client is supposed to be uploading a file.
  227. **/
  228. - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
  229. {
  230. HTTPLogTrace();
  231. // Override me to add support for other methods that expect the client
  232. // to send a body along with the request header.
  233. //
  234. // You should fall through with a call to [super expectsRequestBodyFromMethod:method atPath:path]
  235. //
  236. // See also: supportsMethod:atPath:
  237. if ([method isEqualToString:@"POST"])
  238. return YES;
  239. if ([method isEqualToString:@"PUT"])
  240. return YES;
  241. return NO;
  242. }
  243. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  244. #pragma mark HTTPS
  245. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  246. /**
  247. * Returns whether or not the server is configured to be a secure server.
  248. * In other words, all connections to this server are immediately secured, thus only secure connections are allowed.
  249. * This is the equivalent of having an https server, where it is assumed that all connections must be secure.
  250. * If this is the case, then unsecure connections will not be allowed on this server, and a separate unsecure server
  251. * would need to be run on a separate port in order to support unsecure connections.
  252. *
  253. * Note: In order to support secure connections, the sslIdentityAndCertificates method must be implemented.
  254. **/
  255. - (BOOL)isSecureServer
  256. {
  257. HTTPLogTrace();
  258. // Override me to create an https server...
  259. return NO;
  260. }
  261. /**
  262. * This method is expected to returns an array appropriate for use in kCFStreamSSLCertificates SSL Settings.
  263. * It should be an array of SecCertificateRefs except for the first element in the array, which is a SecIdentityRef.
  264. **/
  265. - (NSArray *)sslIdentityAndCertificates
  266. {
  267. HTTPLogTrace();
  268. // Override me to provide the proper required SSL identity.
  269. return nil;
  270. }
  271. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  272. #pragma mark Password Protection
  273. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  274. /**
  275. * Returns whether or not the requested resource is password protected.
  276. * In this generic implementation, nothing is password protected.
  277. **/
  278. - (BOOL)isPasswordProtected:(NSString *)path
  279. {
  280. HTTPLogTrace();
  281. // Override me to provide password protection...
  282. // You can configure it for the entire server, or based on the current request
  283. return NO;
  284. }
  285. /**
  286. * Returns whether or not the authentication challenge should use digest access authentication.
  287. * The alternative is basic authentication.
  288. *
  289. * If at all possible, digest access authentication should be used because it's more secure.
  290. * Basic authentication sends passwords in the clear and should be avoided unless using SSL/TLS.
  291. **/
  292. - (BOOL)useDigestAccessAuthentication
  293. {
  294. HTTPLogTrace();
  295. // Override me to customize the authentication scheme
  296. // Make sure you understand the security risks of using the weaker basic authentication
  297. return YES;
  298. }
  299. /**
  300. * Returns the authentication realm.
  301. * In this generic implmentation, a default realm is used for the entire server.
  302. **/
  303. - (NSString *)realm
  304. {
  305. HTTPLogTrace();
  306. // Override me to provide a custom realm...
  307. // You can configure it for the entire server, or based on the current request
  308. return @"defaultRealm@host.com";
  309. }
  310. /**
  311. * Returns the password for the given username.
  312. **/
  313. - (NSString *)passwordForUser:(NSString *)username
  314. {
  315. HTTPLogTrace();
  316. // Override me to provide proper password authentication
  317. // You can configure a password for the entire server, or custom passwords for users and/or resources
  318. // Security Note:
  319. // A nil password means no access at all. (Such as for user doesn't exist)
  320. // An empty string password is allowed, and will be treated as any other password. (To support anonymous access)
  321. return nil;
  322. }
  323. /**
  324. * Returns whether or not the user is properly authenticated.
  325. **/
  326. - (BOOL)isAuthenticated
  327. {
  328. HTTPLogTrace();
  329. // Extract the authentication information from the Authorization header
  330. HTTPAuthenticationRequest *auth = [[HTTPAuthenticationRequest alloc] initWithRequest:request];
  331. if ([self useDigestAccessAuthentication])
  332. {
  333. // Digest Access Authentication (RFC 2617)
  334. if(![auth isDigest])
  335. {
  336. // User didn't send proper digest access authentication credentials
  337. return NO;
  338. }
  339. if ([auth username] == nil)
  340. {
  341. // The client didn't provide a username
  342. // Most likely they didn't provide any authentication at all
  343. return NO;
  344. }
  345. NSString *password = [self passwordForUser:[auth username]];
  346. if (password == nil)
  347. {
  348. // No access allowed (username doesn't exist in system)
  349. return NO;
  350. }
  351. NSString *url = [[request url] relativeString];
  352. if (![url isEqualToString:[auth uri]])
  353. {
  354. // Requested URL and Authorization URI do not match
  355. // This could be a replay attack
  356. // IE - attacker provides same authentication information, but requests a different resource
  357. return NO;
  358. }
  359. // The nonce the client provided will most commonly be stored in our local (cached) nonce variable
  360. if (![nonce isEqualToString:[auth nonce]])
  361. {
  362. // The given nonce may be from another connection
  363. // We need to search our list of recent nonce strings that have been recently distributed
  364. if ([[self class] hasRecentNonce:[auth nonce]])
  365. {
  366. // Store nonce in local (cached) nonce variable to prevent array searches in the future
  367. nonce = [[auth nonce] copy];
  368. // The client has switched to using a different nonce value
  369. // This may happen if the client tries to get a file in a directory with different credentials.
  370. // The previous credentials wouldn't work, and the client would receive a 401 error
  371. // along with a new nonce value. The client then uses this new nonce value and requests the file again.
  372. // Whatever the case may be, we need to reset lastNC, since that variable is on a per nonce basis.
  373. lastNC = 0;
  374. }
  375. else
  376. {
  377. // We have no knowledge of ever distributing such a nonce.
  378. // This could be a replay attack from a previous connection in the past.
  379. return NO;
  380. }
  381. }
  382. long authNC = strtol([[auth nc] UTF8String], NULL, 16);
  383. if (authNC <= lastNC)
  384. {
  385. // The nc value (nonce count) hasn't been incremented since the last request.
  386. // This could be a replay attack.
  387. return NO;
  388. }
  389. lastNC = authNC;
  390. NSString *HA1str = [NSString stringWithFormat:@"%@:%@:%@", [auth username], [auth realm], password];
  391. NSString *HA2str = [NSString stringWithFormat:@"%@:%@", [request method], [auth uri]];
  392. NSString *HA1 = [[[HA1str dataUsingEncoding:NSUTF8StringEncoding] md5Digest] hexStringValue];
  393. NSString *HA2 = [[[HA2str dataUsingEncoding:NSUTF8StringEncoding] md5Digest] hexStringValue];
  394. NSString *responseStr = [NSString stringWithFormat:@"%@:%@:%@:%@:%@:%@",
  395. HA1, [auth nonce], [auth nc], [auth cnonce], [auth qop], HA2];
  396. NSString *response = [[[responseStr dataUsingEncoding:NSUTF8StringEncoding] md5Digest] hexStringValue];
  397. return [response isEqualToString:[auth response]];
  398. }
  399. else
  400. {
  401. // Basic Authentication
  402. if (![auth isBasic])
  403. {
  404. // User didn't send proper base authentication credentials
  405. return NO;
  406. }
  407. // Decode the base 64 encoded credentials
  408. NSString *base64Credentials = [auth base64Credentials];
  409. NSData *temp = [[base64Credentials dataUsingEncoding:NSUTF8StringEncoding] base64Decoded];
  410. NSString *credentials = [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
  411. // The credentials should be of the form "username:password"
  412. // The username is not allowed to contain a colon
  413. NSRange colonRange = [credentials rangeOfString:@":"];
  414. if (colonRange.length == 0)
  415. {
  416. // Malformed credentials
  417. return NO;
  418. }
  419. NSString *credUsername = [credentials substringToIndex:colonRange.location];
  420. NSString *credPassword = [credentials substringFromIndex:(colonRange.location + colonRange.length)];
  421. NSString *password = [self passwordForUser:credUsername];
  422. if (password == nil)
  423. {
  424. // No access allowed (username doesn't exist in system)
  425. return NO;
  426. }
  427. return [password isEqualToString:credPassword];
  428. }
  429. }
  430. /**
  431. * Adds a digest access authentication challenge to the given response.
  432. **/
  433. - (void)addDigestAuthChallenge:(HTTPMessage *)response
  434. {
  435. HTTPLogTrace();
  436. NSString *authFormat = @"Digest realm=\"%@\", qop=\"auth\", nonce=\"%@\"";
  437. NSString *authInfo = [NSString stringWithFormat:authFormat, [self realm], [[self class] generateNonce]];
  438. [response setHeaderField:@"WWW-Authenticate" value:authInfo];
  439. }
  440. /**
  441. * Adds a basic authentication challenge to the given response.
  442. **/
  443. - (void)addBasicAuthChallenge:(HTTPMessage *)response
  444. {
  445. HTTPLogTrace();
  446. NSString *authFormat = @"Basic realm=\"%@\"";
  447. NSString *authInfo = [NSString stringWithFormat:authFormat, [self realm]];
  448. [response setHeaderField:@"WWW-Authenticate" value:authInfo];
  449. }
  450. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  451. #pragma mark Core
  452. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  453. /**
  454. * Starting point for the HTTP connection after it has been fully initialized (including subclasses).
  455. * This method is called by the HTTP server.
  456. **/
  457. - (void)start
  458. {
  459. dispatch_async(connectionQueue, ^{ @autoreleasepool {
  460. if (!started)
  461. {
  462. started = YES;
  463. [self startConnection];
  464. }
  465. }});
  466. }
  467. /**
  468. * This method is called by the HTTPServer if it is asked to stop.
  469. * The server, in turn, invokes stop on each HTTPConnection instance.
  470. **/
  471. - (void)stop
  472. {
  473. dispatch_async(connectionQueue, ^{ @autoreleasepool {
  474. // Disconnect the socket.
  475. // The socketDidDisconnect delegate method will handle everything else.
  476. [asyncSocket disconnect];
  477. }});
  478. }
  479. /**
  480. * Starting point for the HTTP connection.
  481. **/
  482. - (void)startConnection
  483. {
  484. // Override me to do any custom work before the connection starts.
  485. //
  486. // Be sure to invoke [super startConnection] when you're done.
  487. HTTPLogTrace();
  488. if ([self isSecureServer])
  489. {
  490. // We are configured to be an HTTPS server.
  491. // That is, we secure via SSL/TLS the connection prior to any communication.
  492. NSArray *certificates = [self sslIdentityAndCertificates];
  493. if ([certificates count] > 0)
  494. {
  495. // All connections are assumed to be secure. Only secure connections are allowed on this server.
  496. NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:3];
  497. // Configure this connection as the server
  498. [settings setObject:[NSNumber numberWithBool:YES]
  499. forKey:(NSString *)kCFStreamSSLIsServer];
  500. [settings setObject:certificates
  501. forKey:(NSString *)kCFStreamSSLCertificates];
  502. // Configure this connection to use the highest possible SSL level
  503. [settings setObject:(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL
  504. forKey:(NSString *)kCFStreamSSLLevel];
  505. [asyncSocket startTLS:settings];
  506. }
  507. }
  508. [self startReadingRequest];
  509. }
  510. /**
  511. * Starts reading an HTTP request.
  512. **/
  513. - (void)startReadingRequest
  514. {
  515. HTTPLogTrace();
  516. [asyncSocket readDataToData:[GCDAsyncSocket CRLFData]
  517. withTimeout:TIMEOUT_READ_FIRST_HEADER_LINE
  518. maxLength:MAX_HEADER_LINE_LENGTH
  519. tag:HTTP_REQUEST_HEADER];
  520. }
  521. /**
  522. * Parses the given query string.
  523. *
  524. * For example, if the query is "q=John%20Mayer%20Trio&num=50"
  525. * then this method would return the following dictionary:
  526. * {
  527. * q = "John Mayer Trio"
  528. * num = "50"
  529. * }
  530. **/
  531. - (NSDictionary *)parseParams:(NSString *)query
  532. {
  533. NSArray *components = [query componentsSeparatedByString:@"&"];
  534. NSMutableDictionary *result = [NSMutableDictionary dictionaryWithCapacity:[components count]];
  535. NSUInteger i;
  536. for (i = 0; i < [components count]; i++)
  537. {
  538. NSString *component = [components objectAtIndex:i];
  539. if ([component length] > 0)
  540. {
  541. NSRange range = [component rangeOfString:@"="];
  542. if (range.location != NSNotFound)
  543. {
  544. NSString *escapedKey = [component substringToIndex:(range.location + 0)];
  545. NSString *escapedValue = [component substringFromIndex:(range.location + 1)];
  546. if ([escapedKey length] > 0)
  547. {
  548. CFStringRef k, v;
  549. k = CFURLCreateStringByReplacingPercentEscapes(NULL, (__bridge CFStringRef)escapedKey, CFSTR(""));
  550. v = CFURLCreateStringByReplacingPercentEscapes(NULL, (__bridge CFStringRef)escapedValue, CFSTR(""));
  551. NSString *key, *value;
  552. key = (__bridge_transfer NSString *)k;
  553. value = (__bridge_transfer NSString *)v;
  554. if (key)
  555. {
  556. if (value)
  557. [result setObject:value forKey:key];
  558. else
  559. [result setObject:[NSNull null] forKey:key];
  560. }
  561. }
  562. }
  563. }
  564. }
  565. return result;
  566. }
  567. /**
  568. * Parses the query variables in the request URI.
  569. *
  570. * For example, if the request URI was "/search.html?q=John%20Mayer%20Trio&num=50"
  571. * then this method would return the following dictionary:
  572. * {
  573. * q = "John Mayer Trio"
  574. * num = "50"
  575. * }
  576. **/
  577. - (NSDictionary *)parseGetParams
  578. {
  579. if(![request isHeaderComplete]) return nil;
  580. NSDictionary *result = nil;
  581. NSURL *url = [request url];
  582. if(url)
  583. {
  584. NSString *query = [url query];
  585. if (query)
  586. {
  587. result = [self parseParams:query];
  588. }
  589. }
  590. return result;
  591. }
  592. /**
  593. * Attempts to parse the given range header into a series of sequential non-overlapping ranges.
  594. * If successfull, the variables 'ranges' and 'rangeIndex' will be updated, and YES will be returned.
  595. * Otherwise, NO is returned, and the range request should be ignored.
  596. **/
  597. - (BOOL)parseRangeRequest:(NSString *)rangeHeader withContentLength:(UInt64)contentLength
  598. {
  599. HTTPLogTrace();
  600. // Examples of byte-ranges-specifier values (assuming an entity-body of length 10000):
  601. //
  602. // - The first 500 bytes (byte offsets 0-499, inclusive): bytes=0-499
  603. //
  604. // - The second 500 bytes (byte offsets 500-999, inclusive): bytes=500-999
  605. //
  606. // - The final 500 bytes (byte offsets 9500-9999, inclusive): bytes=-500
  607. //
  608. // - Or bytes=9500-
  609. //
  610. // - The first and last bytes only (bytes 0 and 9999): bytes=0-0,-1
  611. //
  612. // - Several legal but not canonical specifications of the second 500 bytes (byte offsets 500-999, inclusive):
  613. // bytes=500-600,601-999
  614. // bytes=500-700,601-999
  615. //
  616. NSRange eqsignRange = [rangeHeader rangeOfString:@"="];
  617. if(eqsignRange.location == NSNotFound) return NO;
  618. NSUInteger tIndex = eqsignRange.location;
  619. NSUInteger fIndex = eqsignRange.location + eqsignRange.length;
  620. NSMutableString *rangeType = [[rangeHeader substringToIndex:tIndex] mutableCopy];
  621. NSMutableString *rangeValue = [[rangeHeader substringFromIndex:fIndex] mutableCopy];
  622. CFStringTrimWhitespace((__bridge CFMutableStringRef)rangeType);
  623. CFStringTrimWhitespace((__bridge CFMutableStringRef)rangeValue);
  624. if([rangeType caseInsensitiveCompare:@"bytes"] != NSOrderedSame) return NO;
  625. NSArray *rangeComponents = [rangeValue componentsSeparatedByString:@","];
  626. if([rangeComponents count] == 0) return NO;
  627. ranges = [[NSMutableArray alloc] initWithCapacity:[rangeComponents count]];
  628. rangeIndex = 0;
  629. // Note: We store all range values in the form of DDRange structs, wrapped in NSValue objects.
  630. // Since DDRange consists of UInt64 values, the range extends up to 16 exabytes.
  631. NSUInteger i;
  632. for (i = 0; i < [rangeComponents count]; i++)
  633. {
  634. NSString *rangeComponent = [rangeComponents objectAtIndex:i];
  635. NSRange dashRange = [rangeComponent rangeOfString:@"-"];
  636. if (dashRange.location == NSNotFound)
  637. {
  638. // We're dealing with an individual byte number
  639. UInt64 byteIndex;
  640. if(![NSNumber parseString:rangeComponent intoUInt64:&byteIndex]) return NO;
  641. if(byteIndex >= contentLength) return NO;
  642. [ranges addObject:[NSValue valueWithDDRange:DDMakeRange(byteIndex, 1)]];
  643. }
  644. else
  645. {
  646. // We're dealing with a range of bytes
  647. tIndex = dashRange.location;
  648. fIndex = dashRange.location + dashRange.length;
  649. NSString *r1str = [rangeComponent substringToIndex:tIndex];
  650. NSString *r2str = [rangeComponent substringFromIndex:fIndex];
  651. UInt64 r1, r2;
  652. BOOL hasR1 = [NSNumber parseString:r1str intoUInt64:&r1];
  653. BOOL hasR2 = [NSNumber parseString:r2str intoUInt64:&r2];
  654. if (!hasR1)
  655. {
  656. // We're dealing with a "-[#]" range
  657. //
  658. // r2 is the number of ending bytes to include in the range
  659. if(!hasR2) return NO;
  660. if(r2 > contentLength) return NO;
  661. UInt64 startIndex = contentLength - r2;
  662. [ranges addObject:[NSValue valueWithDDRange:DDMakeRange(startIndex, r2)]];
  663. }
  664. else if (!hasR2)
  665. {
  666. // We're dealing with a "[#]-" range
  667. //
  668. // r1 is the starting index of the range, which goes all the way to the end
  669. if(r1 >= contentLength) return NO;
  670. [ranges addObject:[NSValue valueWithDDRange:DDMakeRange(r1, contentLength - r1)]];
  671. }
  672. else
  673. {
  674. // We're dealing with a normal "[#]-[#]" range
  675. //
  676. // Note: The range is inclusive. So 0-1 has a length of 2 bytes.
  677. if(r1 > r2) return NO;
  678. if(r2 >= contentLength) return NO;
  679. [ranges addObject:[NSValue valueWithDDRange:DDMakeRange(r1, r2 - r1 + 1)]];
  680. }
  681. }
  682. }
  683. if([ranges count] == 0) return NO;
  684. // Now make sure none of the ranges overlap
  685. for (i = 0; i < [ranges count] - 1; i++)
  686. {
  687. DDRange range1 = [[ranges objectAtIndex:i] ddrangeValue];
  688. NSUInteger j;
  689. for (j = i+1; j < [ranges count]; j++)
  690. {
  691. DDRange range2 = [[ranges objectAtIndex:j] ddrangeValue];
  692. DDRange iRange = DDIntersectionRange(range1, range2);
  693. if(iRange.length != 0)
  694. {
  695. return NO;
  696. }
  697. }
  698. }
  699. // Sort the ranges
  700. [ranges sortUsingSelector:@selector(ddrangeCompare:)];
  701. return YES;
  702. }
  703. - (NSString *)requestURI
  704. {
  705. if(request == nil) return nil;
  706. return [[request url] relativeString];
  707. }
  708. /**
  709. * This method is called after a full HTTP request has been received.
  710. * The current request is in the HTTPMessage request variable.
  711. **/
  712. - (void)replyToHTTPRequest
  713. {
  714. HTTPLogTrace();
  715. if (HTTP_LOG_VERBOSE)
  716. {
  717. NSData *tempData = [request messageData];
  718. NSString *tempStr = [[NSString alloc] initWithData:tempData encoding:NSUTF8StringEncoding];
  719. HTTPLogVerbose(@"%@[%p]: Received HTTP request:\n%@", THIS_FILE, self, tempStr);
  720. }
  721. // Check the HTTP version
  722. // We only support version 1.0 and 1.1
  723. NSString *version = [request version];
  724. if (![version isEqualToString:HTTPVersion1_1] && ![version isEqualToString:HTTPVersion1_0])
  725. {
  726. [self handleVersionNotSupported:version];
  727. return;
  728. }
  729. // Extract requested URI
  730. NSString *uri = [self requestURI];
  731. // Check for WebSocket request
  732. if ([WebSocket isWebSocketRequest:request])
  733. {
  734. HTTPLogVerbose(@"isWebSocket");
  735. WebSocket *ws = [self webSocketForURI:uri];
  736. if (ws == nil)
  737. {
  738. [self handleResourceNotFound];
  739. }
  740. else
  741. {
  742. [ws start];
  743. [[config server] addWebSocket:ws];
  744. // The WebSocket should now be the delegate of the underlying socket.
  745. // But gracefully handle the situation if it forgot.
  746. if ([asyncSocket delegate] == self)
  747. {
  748. HTTPLogWarn(@"%@[%p]: WebSocket forgot to set itself as socket delegate", THIS_FILE, self);
  749. // Disconnect the socket.
  750. // The socketDidDisconnect delegate method will handle everything else.
  751. [asyncSocket disconnect];
  752. }
  753. else
  754. {
  755. // The WebSocket is using the socket,
  756. // so make sure we don't disconnect it in the dealloc method.
  757. asyncSocket = nil;
  758. [self die];
  759. // Note: There is a timing issue here that should be pointed out.
  760. //
  761. // A bug that existed in previous versions happend like so:
  762. // - We invoked [self die]
  763. // - This caused us to get released, and our dealloc method to start executing
  764. // - Meanwhile, AsyncSocket noticed a disconnect, and began to dispatch a socketDidDisconnect at us
  765. // - The dealloc method finishes execution, and our instance gets freed
  766. // - The socketDidDisconnect gets run, and a crash occurs
  767. //
  768. // So the issue we want to avoid is releasing ourself when there is a possibility
  769. // that AsyncSocket might be gearing up to queue a socketDidDisconnect for us.
  770. //
  771. // In this particular situation notice that we invoke [asyncSocket delegate].
  772. // This method is synchronous concerning AsyncSocket's internal socketQueue.
  773. // Which means we can be sure, when it returns, that AsyncSocket has already
  774. // queued any delegate methods for us if it was going to.
  775. // And if the delegate methods are queued, then we've been properly retained.
  776. // Meaning we won't get released / dealloc'd until the delegate method has finished executing.
  777. //
  778. // In this rare situation, the die method will get invoked twice.
  779. }
  780. }
  781. return;
  782. }
  783. // Check Authentication (if needed)
  784. // If not properly authenticated for resource, issue Unauthorized response
  785. if ([self isPasswordProtected:uri] && ![self isAuthenticated])
  786. {
  787. [self handleAuthenticationFailed];
  788. return;
  789. }
  790. // Extract the method
  791. NSString *method = [request method];
  792. // Note: We already checked to ensure the method was supported in onSocket:didReadData:withTag:
  793. // Respond properly to HTTP 'GET' and 'HEAD' commands
  794. httpResponse = [self httpResponseForMethod:method URI:uri];
  795. if (httpResponse == nil)
  796. {
  797. [self handleResourceNotFound];
  798. return;
  799. }
  800. [self sendResponseHeadersAndBody];
  801. }
  802. /**
  803. * Prepares a single-range response.
  804. *
  805. * Note: The returned HTTPMessage is owned by the sender, who is responsible for releasing it.
  806. **/
  807. - (HTTPMessage *)newUniRangeResponse:(UInt64)contentLength
  808. {
  809. HTTPLogTrace();
  810. // Status Code 206 - Partial Content
  811. HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:206 description:nil version:HTTPVersion1_1];
  812. DDRange range = [[ranges objectAtIndex:0] ddrangeValue];
  813. NSString *contentLengthStr = [NSString stringWithFormat:@"%qu", range.length];
  814. [response setHeaderField:@"Content-Length" value:contentLengthStr];
  815. NSString *rangeStr = [NSString stringWithFormat:@"%qu-%qu", range.location, DDMaxRange(range) - 1];
  816. NSString *contentRangeStr = [NSString stringWithFormat:@"bytes %@/%qu", rangeStr, contentLength];
  817. [response setHeaderField:@"Content-Range" value:contentRangeStr];
  818. return response;
  819. }
  820. /**
  821. * Prepares a multi-range response.
  822. *
  823. * Note: The returned HTTPMessage is owned by the sender, who is responsible for releasing it.
  824. **/
  825. - (HTTPMessage *)newMultiRangeResponse:(UInt64)contentLength
  826. {
  827. HTTPLogTrace();
  828. // Status Code 206 - Partial Content
  829. HTTPMessage *response = [[HTTPMessage alloc] initResponseWithStatusCode:206 description:nil version:HTTPVersion1_1];
  830. // We have to send each range using multipart/byteranges
  831. // So each byterange has to be prefix'd and suffix'd with the boundry
  832. // Example:
  833. //
  834. // HTTP/1.1 206 Partial Content
  835. // Content-Length: 220
  836. // Content-Type: multipart/byteranges; boundary=4554d24e986f76dd6
  837. //
  838. //
  839. // --4554d24e986f76dd6
  840. // Content-Range: bytes 0-25/4025
  841. //
  842. // [...]
  843. // --4554d24e986f76dd6
  844. // Content-Range: bytes 3975-4024/4025
  845. //
  846. // [...]
  847. // --4554d24e986f76dd6--
  848. ranges_headers = [[NSMutableArray alloc] initWithCapacity:[ranges count]];
  849. CFUUIDRef theUUID = CFUUIDCreate(NULL);
  850. ranges_boundry = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, theUUID);
  851. CFRelease(theUUID);
  852. NSString *startingBoundryStr = [NSString stringWithFormat:@"\r\n--%@\r\n", ranges_boundry];
  853. NSString *endingBoundryStr = [NSString stringWithFormat:@"\r\n--%@--\r\n", ranges_boundry];
  854. UInt64 actualContentLength = 0;
  855. NSUInteger i;
  856. for (i = 0; i < [ranges count]; i++)
  857. {
  858. DDRange range = [[ranges objectAtIndex:i] ddrangeValue];
  859. NSString *rangeStr = [NSString stringWithFormat:@"%qu-%qu", range.location, DDMaxRange(range) - 1];
  860. NSString *contentRangeVal = [NSString stringWithFormat:@"bytes %@/%qu", rangeStr, contentLength];
  861. NSString *contentRangeStr = [NSString stringWithFormat:@"Content-Range: %@\r\n\r\n", contentRangeVal];
  862. NSString *fullHeader = [startingBoundryStr stringByAppendingString:contentRangeStr];
  863. NSData *fullHeaderData = [fullHeader dataUsingEncoding:NSUTF8StringEncoding];
  864. [ranges_headers addObject:fullHeaderData];
  865. actualContentLength += [fullHeaderData length];
  866. actualContentLength += range.length;
  867. }
  868. NSData *endingBoundryData = [endingBoundryStr dataUsingEncoding:NSUTF8StringEncoding];
  869. actualContentLength += [endingBoundryData length];
  870. NSString *contentLengthStr = [NSString stringWithFormat:@"%qu", actualContentLength];
  871. [response setHeaderField:@"Content-Length" value:contentLengthStr];
  872. NSString *contentTypeStr = [NSString stringWithFormat:@"multipart/byteranges; boundary=%@", ranges_boundry];
  873. [response setHeaderField:@"Content-Type" value:contentTypeStr];
  874. return response;
  875. }
  876. /**
  877. * Returns the chunk size line that must precede each chunk of data when using chunked transfer encoding.
  878. * This consists of the size of the data, in hexadecimal, followed by a CRLF.
  879. **/
  880. - (NSData *)chunkedTransferSizeLineForLength:(NSUInteger)length
  881. {
  882. return [[NSString stringWithFormat:@"%lx\r\n", (unsigned long)length] dataUsingEncoding:NSUTF8StringEncoding];
  883. }
  884. /**
  885. * Returns the data that signals the end of a chunked transfer.
  886. **/
  887. - (NSData *)chunkedTransferFooter
  888. {
  889. // Each data chunk is preceded by a size line (in hex and including a CRLF),
  890. // followed by the data itself, followed by another CRLF.
  891. // After every data chunk has been sent, a zero size line is sent,
  892. // followed by optional footer (which are just more headers),
  893. // and followed by a CRLF on a line by itself.
  894. return [@"\r\n0\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding];
  895. }
  896. - (void)sendResponseHeadersAndBody
  897. {
  898. if ([httpResponse respondsToSelector:@selector(delayResponseHeaders)])
  899. {
  900. if ([httpResponse delayResponseHeaders])
  901. {
  902. return;
  903. }
  904. }
  905. BOOL isChunked = NO;
  906. if ([httpResponse respondsToSelector:@selector(isChunked)])
  907. {
  908. isChunked = [httpResponse isChunked];
  909. }
  910. // If a response is "chunked", this simply means the HTTPResponse object
  911. // doesn't know the content-length in advance.
  912. UInt64 contentLength = 0;
  913. if (!isChunked)
  914. {
  915. contentLength = [httpResponse contentLength];
  916. }
  917. // Check for specific range request
  918. NSString *rangeHeader = [request headerField:@"Range"];
  919. BOOL isRangeRequest = NO;
  920. // If the response is "chunked" then we don't know the exact content-length.
  921. // This means we'll be unable to process any range requests.
  922. // This is because range requests might include a range like "give me the last 100 bytes"
  923. if (!isChunked && rangeHeader)
  924. {
  925. if ([self parseRangeRequest:rangeHeader withContentLength:contentLength])
  926. {
  927. isRangeRequest = YES;
  928. }
  929. }
  930. HTTPMessage *response;
  931. if (!isRangeRequest)
  932. {
  933. // Create response
  934. // Default status code: 200 - OK
  935. NSInteger status = 200;
  936. if ([httpResponse respondsToSelector:@selector(status)])
  937. {
  938. status = [httpResponse status];
  939. }
  940. response = [[HTTPMessage alloc] initResponseWithStatusCode:status description:nil version:HTTPVersion1_1];
  941. if (isChunked)
  942. {
  943. [response setHeaderField:@"Transfer-Encoding" value:@"chunked"];
  944. }
  945. else
  946. {
  947. NSString *contentLengthStr = [NSString stringWithFormat:@"%qu", contentLength];
  948. [response setHeaderField:@"Content-Length" value:contentLengthStr];
  949. }
  950. //------ JS additions
  951. //
  952. if ([httpResponse isKindOfClass:[HTTPFileResponse class]])
  953. {
  954. NSString *baseName = [(NSString *)[(HTTPFileResponse *)httpResponse filePath] lastPathComponent];
  955. NSArray *chunks = [baseName componentsSeparatedByString:@"."];
  956. NSString *ext = (NSString *)[chunks lastObject];
  957. // NSLog(@"baseName: %@, ext:'%@'", baseName, ext);
  958. if( [ext isEqualToString:@"js"] ){
  959. [response setHeaderField:@"Content-Type" value:@"application/x-javascript; charset=UTF-8"];
  960. }
  961. if( [ext isEqualToString:@"css"] ){
  962. [response setHeaderField:@"Content-Type" value:@"text/css; charset=UTF-8"];
  963. }
  964. if( [ext isEqualToString:@"ttf"] ){
  965. [response setHeaderField:@"Content-Type" value:@"font/opentype"];
  966. }
  967. if( [ext isEqualToString:@"php"] ){
  968. // http://snipplr.com/view.php?codeview&id=56345
  969. NSString* requestedFile = (NSString *)[(HTTPFileResponse *)httpResponse filePath];
  970. NSLog(@"Routed to PHP: %@", requestedFile);
  971. NSString* tempFilePath = [NSString stringWithFormat:@"%@/cocoaphp.txt", NSTemporaryDirectory()];
  972. NSString* script = [NSString stringWithFormat: @"php -f %@ >%@", requestedFile, tempFilePath];
  973. system([script UTF8String]);
  974. NSString* processedPHPCode = [NSString stringWithContentsOfFile:tempFilePath encoding:NSUTF8StringEncoding error:nil];
  975. NSData* data=[processedPHPCode dataUsingEncoding:NSUTF8StringEncoding];
  976. [response setBody:data];
  977. NSString *contentLengthStr = [NSString stringWithFormat:@"%qu", [processedPHPCode length]];
  978. [response setHeaderField:@"Content-Length" value:contentLengthStr];
  979. }
  980. }
  981. //
  982. //------
  983. }
  984. else
  985. {
  986. if ([ranges count] == 1)
  987. {
  988. response = [self newUniRangeResponse:contentLength];
  989. }
  990. else
  991. {
  992. response = [self newMultiRangeResponse:contentLength];
  993. }
  994. }
  995. BOOL isZeroLengthResponse = !isChunked && (contentLength == 0);
  996. // If they issue a 'HEAD' command, we don't have to include the file
  997. // If they issue a 'GET' command, we need to include the file
  998. if ([[request method] isEqualToString:@"HEAD"] || isZeroLengthResponse)
  999. {
  1000. NSData *responseData = [self preprocessResponse:response];
  1001. [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_RESPONSE];
  1002. sentResponseHeaders = YES;
  1003. }
  1004. else
  1005. {
  1006. // Write the header response
  1007. NSData *responseData = [self preprocessResponse:response];
  1008. [asyncSocket writeData:responseData withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_PARTIAL_RESPONSE_HEADER];
  1009. sentResponseHeaders = YES;
  1010. // Now we need to send the body of the response
  1011. if (!isRangeRequest)
  1012. {
  1013. // Regular request
  1014. NSData *data = [httpResponse readDataOfLength:READ_CHUNKSIZE];
  1015. if ([data length] > 0)
  1016. {
  1017. [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]];
  1018. if (isChunked)
  1019. {
  1020. NSData *chunkSize = [self chunkedTransferSizeLineForLength:[data length]];
  1021. [asyncSocket writeData:chunkSize withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_CHUNKED_RESPONSE_HEADER];
  1022. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:HTTP_CHUNKED_RESPONSE_BODY];
  1023. if ([httpResponse isDone])
  1024. {
  1025. NSData *footer = [self chunkedTransferFooter];
  1026. [asyncSocket writeData:footer withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_RESPONSE];
  1027. }
  1028. else
  1029. {
  1030. NSData *footer = [GCDAsyncSocket CRLFData];
  1031. [asyncSocket writeData:footer withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_CHUNKED_RESPONSE_FOOTER];
  1032. }
  1033. }
  1034. else
  1035. {
  1036. long tag = [httpResponse isDone] ? HTTP_RESPONSE : HTTP_PARTIAL_RESPONSE_BODY;
  1037. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:tag];
  1038. }
  1039. }
  1040. }
  1041. else
  1042. {
  1043. // Client specified a byte range in request
  1044. if ([ranges count] == 1)
  1045. {
  1046. // Client is requesting a single range
  1047. DDRange range = [[ranges objectAtIndex:0] ddrangeValue];
  1048. [httpResponse setOffset:range.location];
  1049. NSUInteger bytesToRead = range.length < READ_CHUNKSIZE ? (NSUInteger)range.length : READ_CHUNKSIZE;
  1050. NSData *data = [httpResponse readDataOfLength:bytesToRead];
  1051. if ([data length] > 0)
  1052. {
  1053. [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]];
  1054. long tag = [data length] == range.length ? HTTP_RESPONSE : HTTP_PARTIAL_RANGE_RESPONSE_BODY;
  1055. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:tag];
  1056. }
  1057. }
  1058. else
  1059. {
  1060. // Client is requesting multiple ranges
  1061. // We have to send each range using multipart/byteranges
  1062. // Write range header
  1063. NSData *rangeHeaderData = [ranges_headers objectAtIndex:0];
  1064. [asyncSocket writeData:rangeHeaderData withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_PARTIAL_RESPONSE_HEADER];
  1065. // Start writing range body
  1066. DDRange range = [[ranges objectAtIndex:0] ddrangeValue];
  1067. [httpResponse setOffset:range.location];
  1068. NSUInteger bytesToRead = range.length < READ_CHUNKSIZE ? (NSUInteger)range.length : READ_CHUNKSIZE;
  1069. NSData *data = [httpResponse readDataOfLength:bytesToRead];
  1070. if ([data length] > 0)
  1071. {
  1072. [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]];
  1073. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:HTTP_PARTIAL_RANGES_RESPONSE_BODY];
  1074. }
  1075. }
  1076. }
  1077. }
  1078. }
  1079. /**
  1080. * Returns the number of bytes of the http response body that are sitting in asyncSocket's write queue.
  1081. *
  1082. * We keep track of this information in order to keep our memory footprint low while
  1083. * working with asynchronous HTTPResponse objects.
  1084. **/
  1085. - (NSUInteger)writeQueueSize
  1086. {
  1087. NSUInteger result = 0;
  1088. NSUInteger i;
  1089. for(i = 0; i < [responseDataSizes count]; i++)
  1090. {
  1091. result += [[responseDataSizes objectAtIndex:i] unsignedIntegerValue];
  1092. }
  1093. return result;
  1094. }
  1095. /**
  1096. * Sends more data, if needed, without growing the write queue over its approximate size limit.
  1097. * The last chunk of the response body will be sent with a tag of HTTP_RESPONSE.
  1098. *
  1099. * This method should only be called for standard (non-range) responses.
  1100. **/
  1101. - (void)continueSendingStandardResponseBody
  1102. {
  1103. HTTPLogTrace();
  1104. // This method is called when either asyncSocket has finished writing one of the response data chunks,
  1105. // or when an asynchronous HTTPResponse object informs us that it has more available data for us to send.
  1106. // In the case of the asynchronous HTTPResponse, we don't want to blindly grab the new data,
  1107. // and shove it onto asyncSocket's write queue.
  1108. // Doing so could negatively affect the memory footprint of the application.
  1109. // Instead, we always ensure that we place no more than READ_CHUNKSIZE bytes onto the write queue.
  1110. //
  1111. // Note that this does not affect the rate at which the HTTPResponse object may generate data.
  1112. // The HTTPResponse is free to do as it pleases, and this is up to the application's developer.
  1113. // If the memory footprint is a concern, the developer creating the custom HTTPResponse object may freely
  1114. // use the calls to readDataOfLength as an indication to start generating more data.
  1115. // This provides an easy way for the HTTPResponse object to throttle its data allocation in step with the rate
  1116. // at which the socket is able to send it.
  1117. NSUInteger writeQueueSize = [self writeQueueSize];
  1118. if(writeQueueSize >= READ_CHUNKSIZE) return;
  1119. NSUInteger available = READ_CHUNKSIZE - writeQueueSize;
  1120. NSData *data = [httpResponse readDataOfLength:available];
  1121. if ([data length] > 0)
  1122. {
  1123. [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]];
  1124. BOOL isChunked = NO;
  1125. if ([httpResponse respondsToSelector:@selector(isChunked)])
  1126. {
  1127. isChunked = [httpResponse isChunked];
  1128. }
  1129. if (isChunked)
  1130. {
  1131. NSData *chunkSize = [self chunkedTransferSizeLineForLength:[data length]];
  1132. [asyncSocket writeData:chunkSize withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_CHUNKED_RESPONSE_HEADER];
  1133. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:HTTP_CHUNKED_RESPONSE_BODY];
  1134. if([httpResponse isDone])
  1135. {
  1136. NSData *footer = [self chunkedTransferFooter];
  1137. [asyncSocket writeData:footer withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_RESPONSE];
  1138. }
  1139. else
  1140. {
  1141. NSData *footer = [GCDAsyncSocket CRLFData];
  1142. [asyncSocket writeData:footer withTimeout:TIMEOUT_WRITE_HEAD tag:HTTP_CHUNKED_RESPONSE_FOOTER];
  1143. }
  1144. }
  1145. else
  1146. {
  1147. long tag = [httpResponse isDone] ? HTTP_RESPONSE : HTTP_PARTIAL_RESPONSE_BODY;
  1148. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:tag];
  1149. }
  1150. }
  1151. }
  1152. /**
  1153. * Sends more data, if needed, without growing the write queue over its approximate size limit.
  1154. * The last chunk of the response body will be sent with a tag of HTTP_RESPONSE.
  1155. *
  1156. * This method should only be called for single-range responses.
  1157. **/
  1158. - (void)continueSendingSingleRangeResponseBody
  1159. {
  1160. HTTPLogTrace();
  1161. // This method is called when either asyncSocket has finished writing one of the response data chunks,
  1162. // or when an asynchronous response informs us that is has more available data for us to send.
  1163. // In the case of the asynchronous response, we don't want to blindly grab the new data,
  1164. // and shove it onto asyncSocket's write queue.
  1165. // Doing so could negatively affect the memory footprint of the application.
  1166. // Instead, we always ensure that we place no more than READ_CHUNKSIZE bytes onto the write queue.
  1167. //
  1168. // Note that this does not affect the rate at which the HTTPResponse object may generate data.
  1169. // The HTTPResponse is free to do as it pleases, and this is up to the application's developer.
  1170. // If the memory footprint is a concern, the developer creating the custom HTTPResponse object may freely
  1171. // use the calls to readDataOfLength as an indication to start generating more data.
  1172. // This provides an easy way for the HTTPResponse object to throttle its data allocation in step with the rate
  1173. // at which the socket is able to send it.
  1174. NSUInteger writeQueueSize = [self writeQueueSize];
  1175. if(writeQueueSize >= READ_CHUNKSIZE) return;
  1176. DDRange range = [[ranges objectAtIndex:0] ddrangeValue];
  1177. UInt64 offset = [httpResponse offset];
  1178. UInt64 bytesRead = offset - range.location;
  1179. UInt64 bytesLeft = range.length - bytesRead;
  1180. if (bytesLeft > 0)
  1181. {
  1182. NSUInteger available = READ_CHUNKSIZE - writeQueueSize;
  1183. NSUInteger bytesToRead = bytesLeft < available ? (NSUInteger)bytesLeft : available;
  1184. NSData *data = [httpResponse readDataOfLength:bytesToRead];
  1185. if ([data length] > 0)
  1186. {
  1187. [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]];
  1188. long tag = [data length] == bytesLeft ? HTTP_RESPONSE : HTTP_PARTIAL_RANGE_RESPONSE_BODY;
  1189. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:tag];
  1190. }
  1191. }
  1192. }
  1193. /**
  1194. * Sends more data, if needed, without growing the write queue over its approximate size limit.
  1195. * The last chunk of the response body will be sent with a tag of HTTP_RESPONSE.
  1196. *
  1197. * This method should only be called for multi-range responses.
  1198. **/
  1199. - (void)continueSendingMultiRangeResponseBody
  1200. {
  1201. HTTPLogTrace();
  1202. // This method is called when either asyncSocket has finished writing one of the response data chunks,
  1203. // or when an asynchronous HTTPResponse object informs us that is has more available data for us to send.
  1204. // In the case of the asynchronous HTTPResponse, we don't want to blindly grab the new data,
  1205. // and shove it onto asyncSocket's write queue.
  1206. // Doing so could negatively affect the memory footprint of the application.
  1207. // Instead, we always ensure that we place no more than READ_CHUNKSIZE bytes onto the write queue.
  1208. //
  1209. // Note that this does not affect the rate at which the HTTPResponse object may generate data.
  1210. // The HTTPResponse is free to do as it pleases, and this is up to the application's developer.
  1211. // If the memory footprint is a concern, the developer creating the custom HTTPResponse object may freely
  1212. // use the calls to readDataOfLength as an indication to start generating more data.
  1213. // This provides an easy way for the HTTPResponse object to throttle its data allocation in step with the rate
  1214. // at which the socket is able to send it.
  1215. NSUInteger writeQueueSize = [self writeQueueSize];
  1216. if(writeQueueSize >= READ_CHUNKSIZE) return;
  1217. DDRange range = [[ranges objectAtIndex:rangeIndex] ddrangeValue];
  1218. UInt64 offset = [httpResponse offset];
  1219. UInt64 bytesRead = offset - range.location;
  1220. UInt64 bytesLeft = range.length - bytesRead;
  1221. if (bytesLeft > 0)
  1222. {
  1223. NSUInteger available = READ_CHUNKSIZE - writeQueueSize;
  1224. NSUInteger bytesToRead = bytesLeft < available ? (NSUInteger)bytesLeft : available;
  1225. NSData *data = [httpResponse readDataOfLength:bytesToRead];
  1226. if ([data length] > 0)
  1227. {
  1228. [responseDataSizes addObject:[NSNumber numberWithUnsignedInteger:[data length]]];
  1229. [asyncSocket writeData:data withTimeout:TIMEOUT_WRITE_BODY tag:HTTP_PARTIAL_RANGES_RESPONSE_BODY];
  1230. }
  1231. }
  1232. else
  1233. {
  1234. if (++rangeIndex < [ranges count])
  1235. {
  1236. // Write range header
  1237. NSData *rangeHeader = [ranges_headers objectAtIndex