GCDWebServerRequest.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /*
  2. Copyright (c) 2012-2014, Pierre-Olivier Latour
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. * Redistributions of source code must retain the above copyright
  7. notice, this list of conditions and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. * The name of Pierre-Olivier Latour may not be used to endorse
  12. or promote products derived from this software without specific
  13. prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  15. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  16. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17. DISCLAIMED. IN NO EVENT SHALL PIERRE-OLIVIER LATOUR BE LIABLE FOR ANY
  18. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  19. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  20. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  21. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  22. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  23. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. #import <zlib.h>
  26. #import "GCDWebServerPrivate.h"
  27. #define kZlibErrorDomain @"ZlibErrorDomain"
  28. #define kGZipInitialBufferSize (256 * 1024)
  29. @interface GCDWebServerBodyDecoder : NSObject <GCDWebServerBodyWriter>
  30. - (id)initWithRequest:(GCDWebServerRequest*)request writer:(id<GCDWebServerBodyWriter>)writer;
  31. @end
  32. @interface GCDWebServerGZipDecoder : GCDWebServerBodyDecoder
  33. @end
  34. @interface GCDWebServerBodyDecoder () {
  35. @private
  36. GCDWebServerRequest* __unsafe_unretained _request;
  37. id<GCDWebServerBodyWriter> __unsafe_unretained _writer;
  38. }
  39. @end
  40. @implementation GCDWebServerBodyDecoder
  41. - (id)initWithRequest:(GCDWebServerRequest*)request writer:(id<GCDWebServerBodyWriter>)writer {
  42. if ((self = [super init])) {
  43. _request = request;
  44. _writer = writer;
  45. }
  46. return self;
  47. }
  48. - (BOOL)open:(NSError**)error {
  49. return [_writer open:error];
  50. }
  51. - (BOOL)writeData:(NSData*)data error:(NSError**)error {
  52. return [_writer writeData:data error:error];
  53. }
  54. - (BOOL)close:(NSError**)error {
  55. return [_writer close:error];
  56. }
  57. @end
  58. @interface GCDWebServerGZipDecoder () {
  59. @private
  60. z_stream _stream;
  61. BOOL _finished;
  62. }
  63. @end
  64. @implementation GCDWebServerGZipDecoder
  65. - (BOOL)open:(NSError**)error {
  66. int result = inflateInit2(&_stream, 15 + 16);
  67. if (result != Z_OK) {
  68. *error = [NSError errorWithDomain:kZlibErrorDomain code:result userInfo:nil];
  69. return NO;
  70. }
  71. if (![super open:error]) {
  72. deflateEnd(&_stream);
  73. return NO;
  74. }
  75. return YES;
  76. }
  77. - (BOOL)writeData:(NSData*)data error:(NSError**)error {
  78. DCHECK(!_finished);
  79. _stream.next_in = (Bytef*)data.bytes;
  80. _stream.avail_in = (uInt)data.length;
  81. NSMutableData* decodedData = [[NSMutableData alloc] initWithLength:kGZipInitialBufferSize];
  82. if (decodedData == nil) {
  83. DNOT_REACHED();
  84. return NO;
  85. }
  86. NSUInteger length = 0;
  87. while (1) {
  88. NSUInteger maxLength = decodedData.length - length;
  89. _stream.next_out = (Bytef*)((char*)decodedData.mutableBytes + length);
  90. _stream.avail_out = (uInt)maxLength;
  91. int result = inflate(&_stream, Z_NO_FLUSH);
  92. if ((result != Z_OK) && (result != Z_STREAM_END)) {
  93. ARC_RELEASE(decodedData);
  94. *error = [NSError errorWithDomain:kZlibErrorDomain code:result userInfo:nil];
  95. return NO;
  96. }
  97. length += maxLength - _stream.avail_out;
  98. if (_stream.avail_out > 0) {
  99. if (result == Z_STREAM_END) {
  100. _finished = YES;
  101. }
  102. break;
  103. }
  104. decodedData.length = 2 * decodedData.length; // zlib has used all the output buffer so resize it and try again in case more data is available
  105. }
  106. decodedData.length = length;
  107. BOOL success = length ? [super writeData:decodedData error:error] : YES; // No need to call writer if we have no data yet
  108. ARC_RELEASE(decodedData);
  109. return success;
  110. }
  111. - (BOOL)close:(NSError**)error {
  112. DCHECK(_finished);
  113. inflateEnd(&_stream);
  114. return [super close:error];
  115. }
  116. @end
  117. @interface GCDWebServerRequest () {
  118. @private
  119. NSString* _method;
  120. NSURL* _url;
  121. NSDictionary* _headers;
  122. NSString* _path;
  123. NSDictionary* _query;
  124. NSString* _type;
  125. BOOL _chunked;
  126. NSUInteger _length;
  127. NSDate* _modifiedSince;
  128. NSString* _noneMatch;
  129. NSRange _range;
  130. BOOL _gzipAccepted;
  131. BOOL _opened;
  132. NSMutableArray* _decoders;
  133. id<GCDWebServerBodyWriter> __unsafe_unretained _writer;
  134. }
  135. @end
  136. @implementation GCDWebServerRequest : NSObject
  137. @synthesize method=_method, URL=_url, headers=_headers, path=_path, query=_query, contentType=_type, contentLength=_length, ifModifiedSince=_modifiedSince, ifNoneMatch=_noneMatch,
  138. byteRange=_range, acceptsGzipContentEncoding=_gzipAccepted, usesChunkedTransferEncoding=_chunked;
  139. - (instancetype)initWithMethod:(NSString*)method url:(NSURL*)url headers:(NSDictionary*)headers path:(NSString*)path query:(NSDictionary*)query {
  140. if ((self = [super init])) {
  141. _method = [method copy];
  142. _url = ARC_RETAIN(url);
  143. _headers = ARC_RETAIN(headers);
  144. _path = [path copy];
  145. _query = ARC_RETAIN(query);
  146. _type = ARC_RETAIN(GCDWebServerNormalizeHeaderValue([_headers objectForKey:@"Content-Type"]));
  147. _chunked = [GCDWebServerNormalizeHeaderValue([_headers objectForKey:@"Transfer-Encoding"]) isEqualToString:@"chunked"];
  148. NSString* lengthHeader = [_headers objectForKey:@"Content-Length"];
  149. if (lengthHeader) {
  150. NSInteger length = [lengthHeader integerValue];
  151. if (_chunked || (length < 0)) {
  152. DNOT_REACHED();
  153. ARC_RELEASE(self);
  154. return nil;
  155. }
  156. _length = length;
  157. if (_type == nil) {
  158. _type = kGCDWebServerDefaultMimeType;
  159. }
  160. } else if (_chunked) {
  161. if (_type == nil) {
  162. _type = kGCDWebServerDefaultMimeType;
  163. }
  164. _length = NSNotFound;
  165. } else {
  166. if (_type) {
  167. DNOT_REACHED();
  168. ARC_RELEASE(self);
  169. return nil;
  170. }
  171. _length = NSNotFound;
  172. }
  173. NSString* modifiedHeader = [_headers objectForKey:@"If-Modified-Since"];
  174. if (modifiedHeader) {
  175. _modifiedSince = [GCDWebServerParseRFC822(modifiedHeader) copy];
  176. }
  177. _noneMatch = ARC_RETAIN([_headers objectForKey:@"If-None-Match"]);
  178. _range = NSMakeRange(NSNotFound, 0);
  179. NSString* rangeHeader = GCDWebServerNormalizeHeaderValue([_headers objectForKey:@"Range"]);
  180. if (rangeHeader) {
  181. if ([rangeHeader hasPrefix:@"bytes="]) {
  182. NSArray* components = [[rangeHeader substringFromIndex:6] componentsSeparatedByString:@","];
  183. if (components.count == 1) {
  184. components = [[components firstObject] componentsSeparatedByString:@"-"];
  185. if (components.count == 2) {
  186. NSString* startString = [components objectAtIndex:0];
  187. NSInteger startValue = [startString integerValue];
  188. NSString* endString = [components objectAtIndex:1];
  189. NSInteger endValue = [endString integerValue];
  190. if (startString.length && (startValue >= 0) && endString.length && (endValue >= startValue)) { // The second 500 bytes: "500-999"
  191. _range.location = startValue;
  192. _range.length = endValue - startValue + 1;
  193. } else if (startString.length && (startValue >= 0)) { // The bytes after 9500 bytes: "9500-"
  194. _range.location = startValue;
  195. _range.length = NSUIntegerMax;
  196. } else if (endString.length && (endValue > 0)) { // The final 500 bytes: "-500"
  197. _range.location = NSNotFound;
  198. _range.length = endValue;
  199. }
  200. }
  201. }
  202. }
  203. if ((_range.location == NSNotFound) && (_range.length == 0)) { // Ignore "Range" header if syntactically invalid
  204. LOG_WARNING(@"Failed to parse 'Range' header \"%@\" for url: %@", rangeHeader, url);
  205. }
  206. }
  207. if ([[_headers objectForKey:@"Accept-Encoding"] rangeOfString:@"gzip"].location != NSNotFound) {
  208. _gzipAccepted = YES;
  209. }
  210. _decoders = [[NSMutableArray alloc] init];
  211. }
  212. return self;
  213. }
  214. - (void)dealloc {
  215. ARC_RELEASE(_method);
  216. ARC_RELEASE(_url);
  217. ARC_RELEASE(_headers);
  218. ARC_RELEASE(_path);
  219. ARC_RELEASE(_query);
  220. ARC_RELEASE(_type);
  221. ARC_RELEASE(_modifiedSince);
  222. ARC_RELEASE(_noneMatch);
  223. ARC_RELEASE(_decoders);
  224. ARC_DEALLOC(super);
  225. }
  226. - (BOOL)hasBody {
  227. return _type ? YES : NO;
  228. }
  229. - (BOOL)hasByteRange {
  230. return GCDWebServerIsValidByteRange(_range);
  231. }
  232. - (BOOL)open:(NSError**)error {
  233. return YES;
  234. }
  235. - (BOOL)writeData:(NSData*)data error:(NSError**)error {
  236. return YES;
  237. }
  238. - (BOOL)close:(NSError**)error {
  239. return YES;
  240. }
  241. - (void)prepareForWriting {
  242. _writer = self;
  243. if ([GCDWebServerNormalizeHeaderValue([self.headers objectForKey:@"Content-Encoding"]) isEqualToString:@"gzip"]) {
  244. GCDWebServerGZipDecoder* decoder = [[GCDWebServerGZipDecoder alloc] initWithRequest:self writer:_writer];
  245. [_decoders addObject:decoder];
  246. ARC_RELEASE(decoder);
  247. _writer = decoder;
  248. }
  249. }
  250. - (BOOL)performOpen:(NSError**)error {
  251. DCHECK(_type);
  252. DCHECK(_writer);
  253. if (_opened) {
  254. DNOT_REACHED();
  255. return NO;
  256. }
  257. _opened = YES;
  258. return [_writer open:error];
  259. }
  260. - (BOOL)performWriteData:(NSData*)data error:(NSError**)error {
  261. DCHECK(_opened);
  262. return [_writer writeData:data error:error];
  263. }
  264. - (BOOL)performClose:(NSError**)error {
  265. DCHECK(_opened);
  266. return [_writer close:error];
  267. }
  268. - (NSString*)description {
  269. NSMutableString* description = [NSMutableString stringWithFormat:@"%@ %@", _method, _path];
  270. for (NSString* argument in [[_query allKeys] sortedArrayUsingSelector:@selector(compare:)]) {
  271. [description appendFormat:@"\n %@ = %@", argument, [_query objectForKey:argument]];
  272. }
  273. [description appendString:@"\n"];
  274. for (NSString* header in [[_headers allKeys] sortedArrayUsingSelector:@selector(compare:)]) {
  275. [description appendFormat:@"\n%@: %@", header, [_headers objectForKey:header]];
  276. }
  277. return description;
  278. }
  279. @end