GCDWebServerResponse.m 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 GCDWebServerBodyEncoder : NSObject <GCDWebServerBodyReader>
  30. - (id)initWithResponse:(GCDWebServerResponse*)response reader:(id<GCDWebServerBodyReader>)reader;
  31. @end
  32. @interface GCDWebServerGZipEncoder : GCDWebServerBodyEncoder
  33. @end
  34. @interface GCDWebServerBodyEncoder () {
  35. @private
  36. GCDWebServerResponse* __unsafe_unretained _response;
  37. id<GCDWebServerBodyReader> __unsafe_unretained _reader;
  38. }
  39. @end
  40. @implementation GCDWebServerBodyEncoder
  41. - (id)initWithResponse:(GCDWebServerResponse*)response reader:(id<GCDWebServerBodyReader>)reader {
  42. if ((self = [super init])) {
  43. _response = response;
  44. _reader = reader;
  45. }
  46. return self;
  47. }
  48. - (BOOL)open:(NSError**)error {
  49. return [_reader open:error];
  50. }
  51. - (NSData*)readData:(NSError**)error {
  52. return [_reader readData:error];
  53. }
  54. - (void)close {
  55. [_reader close];
  56. }
  57. @end
  58. @interface GCDWebServerGZipEncoder () {
  59. @private
  60. z_stream _stream;
  61. BOOL _finished;
  62. }
  63. @end
  64. @implementation GCDWebServerGZipEncoder
  65. - (id)initWithResponse:(GCDWebServerResponse*)response reader:(id<GCDWebServerBodyReader>)reader {
  66. if ((self = [super initWithResponse:response reader:reader])) {
  67. response.contentLength = NSNotFound; // Make sure "Content-Length" header is not set since we don't know it (client will determine body length when connection is closed)
  68. [response setValue:@"gzip" forAdditionalHeader:@"Content-Encoding"];
  69. }
  70. return self;
  71. }
  72. - (BOOL)open:(NSError**)error {
  73. int result = deflateInit2(&_stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY);
  74. if (result != Z_OK) {
  75. *error = [NSError errorWithDomain:kZlibErrorDomain code:result userInfo:nil];
  76. return NO;
  77. }
  78. if (![super open:error]) {
  79. deflateEnd(&_stream);
  80. return NO;
  81. }
  82. return YES;
  83. }
  84. - (NSData*)readData:(NSError**)error {
  85. NSMutableData* encodedData;
  86. if (_finished) {
  87. encodedData = [[NSMutableData alloc] init];
  88. } else {
  89. encodedData = [[NSMutableData alloc] initWithLength:kGZipInitialBufferSize];
  90. if (encodedData == nil) {
  91. DNOT_REACHED();
  92. return nil;
  93. }
  94. NSUInteger length = 0;
  95. do {
  96. NSData* data = [super readData:error];
  97. if (data == nil) {
  98. return nil;
  99. }
  100. _stream.next_in = (Bytef*)data.bytes;
  101. _stream.avail_in = (uInt)data.length;
  102. while (1) {
  103. NSUInteger maxLength = encodedData.length - length;
  104. _stream.next_out = (Bytef*)((char*)encodedData.mutableBytes + length);
  105. _stream.avail_out = (uInt)maxLength;
  106. int result = deflate(&_stream, data.length ? Z_NO_FLUSH : Z_FINISH);
  107. if (result == Z_STREAM_END) {
  108. _finished = YES;
  109. } else if (result != Z_OK) {
  110. ARC_RELEASE(encodedData);
  111. *error = [NSError errorWithDomain:kZlibErrorDomain code:result userInfo:nil];
  112. return nil;
  113. }
  114. length += maxLength - _stream.avail_out;
  115. if (_stream.avail_out > 0) {
  116. break;
  117. }
  118. encodedData.length = 2 * encodedData.length; // zlib has used all the output buffer so resize it and try again in case more data is available
  119. }
  120. DCHECK(_stream.avail_in == 0);
  121. } while (length == 0); // Make sure we don't return an empty NSData if not in finished state
  122. encodedData.length = length;
  123. }
  124. return ARC_AUTORELEASE(encodedData);
  125. }
  126. - (void)close {
  127. deflateEnd(&_stream);
  128. [super close];
  129. }
  130. @end
  131. @interface GCDWebServerResponse () {
  132. @private
  133. NSString* _type;
  134. NSUInteger _length;
  135. NSInteger _status;
  136. NSUInteger _maxAge;
  137. NSDate* _lastModified;
  138. NSString* _eTag;
  139. NSMutableDictionary* _headers;
  140. BOOL _chunked;
  141. BOOL _gzipped;
  142. BOOL _opened;
  143. NSMutableArray* _encoders;
  144. id<GCDWebServerBodyReader> __unsafe_unretained _reader;
  145. }
  146. @end
  147. @implementation GCDWebServerResponse
  148. @synthesize contentType=_type, contentLength=_length, statusCode=_status, cacheControlMaxAge=_maxAge, lastModifiedDate=_lastModified, eTag=_eTag,
  149. gzipContentEncodingEnabled=_gzipped, additionalHeaders=_headers;
  150. + (instancetype)response {
  151. return ARC_AUTORELEASE([[[self class] alloc] init]);
  152. }
  153. - (instancetype)init {
  154. if ((self = [super init])) {
  155. _type = nil;
  156. _length = NSNotFound;
  157. _status = kGCDWebServerHTTPStatusCode_OK;
  158. _maxAge = 0;
  159. _headers = [[NSMutableDictionary alloc] init];
  160. _encoders = [[NSMutableArray alloc] init];
  161. }
  162. return self;
  163. }
  164. - (void)dealloc {
  165. ARC_RELEASE(_type);
  166. ARC_RELEASE(_lastModified);
  167. ARC_RELEASE(_eTag);
  168. ARC_RELEASE(_headers);
  169. ARC_RELEASE(_encoders);
  170. ARC_DEALLOC(super);
  171. }
  172. - (void)setValue:(NSString*)value forAdditionalHeader:(NSString*)header {
  173. [_headers setValue:value forKey:header];
  174. }
  175. - (BOOL)hasBody {
  176. return _type ? YES : NO;
  177. }
  178. - (BOOL)usesChunkedTransferEncoding {
  179. return (_type != nil) && (_length == NSNotFound);
  180. }
  181. - (BOOL)open:(NSError**)error {
  182. return YES;
  183. }
  184. - (NSData*)readData:(NSError**)error {
  185. return [NSData data];
  186. }
  187. - (void)close {
  188. ;
  189. }
  190. - (void)prepareForReading {
  191. _reader = self;
  192. if (_gzipped) {
  193. GCDWebServerGZipEncoder* encoder = [[GCDWebServerGZipEncoder alloc] initWithResponse:self reader:_reader];
  194. [_encoders addObject:encoder];
  195. ARC_RELEASE(encoder);
  196. _reader = encoder;
  197. }
  198. }
  199. - (BOOL)performOpen:(NSError**)error {
  200. DCHECK(_type);
  201. DCHECK(_reader);
  202. if (_opened) {
  203. DNOT_REACHED();
  204. return NO;
  205. }
  206. _opened = YES;
  207. return [_reader open:error];
  208. }
  209. - (NSData*)performReadData:(NSError**)error {
  210. DCHECK(_opened);
  211. return [_reader readData:error];
  212. }
  213. - (void)performClose {
  214. DCHECK(_opened);
  215. [_reader close];
  216. }
  217. - (NSString*)description {
  218. NSMutableString* description = [NSMutableString stringWithFormat:@"Status Code = %i", (int)_status];
  219. if (_type) {
  220. [description appendFormat:@"\nContent Type = %@", _type];
  221. }
  222. if (_length != NSNotFound) {
  223. [description appendFormat:@"\nContent Length = %lu", (unsigned long)_length];
  224. }
  225. [description appendFormat:@"\nCache Control Max Age = %lu", (unsigned long)_maxAge];
  226. if (_lastModified) {
  227. [description appendFormat:@"\nLast Modified Date = %@", _lastModified];
  228. }
  229. if (_eTag) {
  230. [description appendFormat:@"\nETag = %@", _eTag];
  231. }
  232. if (_headers.count) {
  233. [description appendString:@"\n"];
  234. for (NSString* header in [[_headers allKeys] sortedArrayUsingSelector:@selector(compare:)]) {
  235. [description appendFormat:@"\n%@: %@", header, [_headers objectForKey:header]];
  236. }
  237. }
  238. return description;
  239. }
  240. @end
  241. @implementation GCDWebServerResponse (Extensions)
  242. + (instancetype)responseWithStatusCode:(NSInteger)statusCode {
  243. return ARC_AUTORELEASE([[self alloc] initWithStatusCode:statusCode]);
  244. }
  245. + (instancetype)responseWithRedirect:(NSURL*)location permanent:(BOOL)permanent {
  246. return ARC_AUTORELEASE([[self alloc] initWithRedirect:location permanent:permanent]);
  247. }
  248. - (instancetype)initWithStatusCode:(NSInteger)statusCode {
  249. if ((self = [self init])) {
  250. self.statusCode = statusCode;
  251. }
  252. return self;
  253. }
  254. - (instancetype)initWithRedirect:(NSURL*)location permanent:(BOOL)permanent {
  255. if ((self = [self init])) {
  256. self.statusCode = permanent ? kGCDWebServerHTTPStatusCode_MovedPermanently : kGCDWebServerHTTPStatusCode_TemporaryRedirect;
  257. [self setValue:[location absoluteString] forAdditionalHeader:@"Location"];
  258. }
  259. return self;
  260. }
  261. @end