GCDWebServerResponse.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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 <sys/stat.h>
  26. #import "GCDWebServerPrivate.h"
  27. @interface GCDWebServerResponse () {
  28. @private
  29. NSString* _type;
  30. NSUInteger _length;
  31. NSInteger _status;
  32. NSUInteger _maxAge;
  33. NSMutableDictionary* _headers;
  34. }
  35. @end
  36. @interface GCDWebServerDataResponse () {
  37. @private
  38. NSData* _data;
  39. NSInteger _offset;
  40. }
  41. @end
  42. @interface GCDWebServerFileResponse () {
  43. @private
  44. NSString* _path;
  45. NSUInteger _offset;
  46. NSUInteger _size;
  47. int _file;
  48. }
  49. @end
  50. @implementation GCDWebServerResponse
  51. @synthesize contentType=_type, contentLength=_length, statusCode=_status, cacheControlMaxAge=_maxAge, additionalHeaders=_headers;
  52. + (GCDWebServerResponse*)response {
  53. return ARC_AUTORELEASE([[[self class] alloc] init]);
  54. }
  55. - (id)init {
  56. return [self initWithContentType:nil contentLength:0];
  57. }
  58. - (id)initWithContentType:(NSString*)type contentLength:(NSUInteger)length {
  59. if ((self = [super init])) {
  60. _type = [type copy];
  61. _length = length;
  62. _status = 200;
  63. _maxAge = 0;
  64. _headers = [[NSMutableDictionary alloc] init];
  65. if ((_length > 0) && (_type == nil)) {
  66. _type = [kGCDWebServerDefaultMimeType copy];
  67. }
  68. }
  69. return self;
  70. }
  71. - (void)dealloc {
  72. ARC_RELEASE(_type);
  73. ARC_RELEASE(_headers);
  74. ARC_DEALLOC(super);
  75. }
  76. - (void)setValue:(NSString*)value forAdditionalHeader:(NSString*)header {
  77. [_headers setValue:value forKey:header];
  78. }
  79. - (BOOL)hasBody {
  80. return _type ? YES : NO;
  81. }
  82. @end
  83. @implementation GCDWebServerResponse (Subclassing)
  84. - (BOOL)open {
  85. [self doesNotRecognizeSelector:_cmd];
  86. return NO;
  87. }
  88. - (NSInteger)read:(void*)buffer maxLength:(NSUInteger)length {
  89. [self doesNotRecognizeSelector:_cmd];
  90. return -1;
  91. }
  92. - (BOOL)close {
  93. [self doesNotRecognizeSelector:_cmd];
  94. return NO;
  95. }
  96. @end
  97. @implementation GCDWebServerResponse (Extensions)
  98. + (GCDWebServerResponse*)responseWithStatusCode:(NSInteger)statusCode {
  99. return ARC_AUTORELEASE([[self alloc] initWithStatusCode:statusCode]);
  100. }
  101. + (GCDWebServerResponse*)responseWithRedirect:(NSURL*)location permanent:(BOOL)permanent {
  102. return ARC_AUTORELEASE([[self alloc] initWithRedirect:location permanent:permanent]);
  103. }
  104. - (id)initWithStatusCode:(NSInteger)statusCode {
  105. if ((self = [self initWithContentType:nil contentLength:0])) {
  106. self.statusCode = statusCode;
  107. }
  108. return self;
  109. }
  110. - (id)initWithRedirect:(NSURL*)location permanent:(BOOL)permanent {
  111. if ((self = [self initWithContentType:nil contentLength:0])) {
  112. self.statusCode = permanent ? 301 : 307;
  113. [self setValue:[location absoluteString] forAdditionalHeader:@"Location"];
  114. }
  115. return self;
  116. }
  117. @end
  118. @implementation GCDWebServerDataResponse
  119. + (GCDWebServerDataResponse*)responseWithData:(NSData*)data contentType:(NSString*)type {
  120. return ARC_AUTORELEASE([[[self class] alloc] initWithData:data contentType:type]);
  121. }
  122. - (id)initWithData:(NSData*)data contentType:(NSString*)type {
  123. if (data == nil) {
  124. DNOT_REACHED();
  125. ARC_RELEASE(self);
  126. return nil;
  127. }
  128. if ((self = [super initWithContentType:type contentLength:data.length])) {
  129. _data = ARC_RETAIN(data);
  130. _offset = -1;
  131. }
  132. return self;
  133. }
  134. - (void)dealloc {
  135. DCHECK(_offset < 0);
  136. ARC_RELEASE(_data);
  137. ARC_DEALLOC(super);
  138. }
  139. - (BOOL)open {
  140. DCHECK(_offset < 0);
  141. _offset = 0;
  142. return YES;
  143. }
  144. - (NSInteger)read:(void*)buffer maxLength:(NSUInteger)length {
  145. DCHECK(_offset >= 0);
  146. NSInteger size = 0;
  147. if (_offset < (NSInteger)_data.length) {
  148. size = MIN(_data.length - _offset, length);
  149. bcopy((char*)_data.bytes + _offset, buffer, size);
  150. _offset += size;
  151. }
  152. return size;
  153. }
  154. - (BOOL)close {
  155. DCHECK(_offset >= 0);
  156. _offset = -1;
  157. return YES;
  158. }
  159. @end
  160. @implementation GCDWebServerDataResponse (Extensions)
  161. + (GCDWebServerDataResponse*)responseWithText:(NSString*)text {
  162. return ARC_AUTORELEASE([[self alloc] initWithText:text]);
  163. }
  164. + (GCDWebServerDataResponse*)responseWithHTML:(NSString*)html {
  165. return ARC_AUTORELEASE([[self alloc] initWithHTML:html]);
  166. }
  167. + (GCDWebServerDataResponse*)responseWithHTMLTemplate:(NSString*)path variables:(NSDictionary*)variables {
  168. return ARC_AUTORELEASE([[self alloc] initWithHTMLTemplate:path variables:variables]);
  169. }
  170. + (GCDWebServerDataResponse*)responseWithJSONObject:(id)object {
  171. return ARC_AUTORELEASE([[self alloc] initWithJSONObject:object]);
  172. }
  173. + (GCDWebServerDataResponse*)responseWithJSONObject:(id)object contentType:(NSString*)type {
  174. return ARC_AUTORELEASE([[self alloc] initWithJSONObject:object contentType:type]);
  175. }
  176. - (id)initWithText:(NSString*)text {
  177. NSData* data = [text dataUsingEncoding:NSUTF8StringEncoding];
  178. if (data == nil) {
  179. DNOT_REACHED();
  180. ARC_RELEASE(self);
  181. return nil;
  182. }
  183. return [self initWithData:data contentType:@"text/plain; charset=utf-8"];
  184. }
  185. - (id)initWithHTML:(NSString*)html {
  186. NSData* data = [html dataUsingEncoding:NSUTF8StringEncoding];
  187. if (data == nil) {
  188. DNOT_REACHED();
  189. ARC_RELEASE(self);
  190. return nil;
  191. }
  192. return [self initWithData:data contentType:@"text/html; charset=utf-8"];
  193. }
  194. - (id)initWithHTMLTemplate:(NSString*)path variables:(NSDictionary*)variables {
  195. NSMutableString* html = [[NSMutableString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
  196. [variables enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSString* value, BOOL* stop) {
  197. [html replaceOccurrencesOfString:[NSString stringWithFormat:@"%%%@%%", key] withString:value options:0 range:NSMakeRange(0, html.length)];
  198. }];
  199. id response = [self initWithHTML:html];
  200. ARC_RELEASE(html);
  201. return response;
  202. }
  203. - (id)initWithJSONObject:(id)object {
  204. return [self initWithJSONObject:object contentType:@"application/json"];
  205. }
  206. - (id)initWithJSONObject:(id)object contentType:(NSString*)type {
  207. NSData* data = [NSJSONSerialization dataWithJSONObject:object options:0 error:NULL];
  208. if (data == nil) {
  209. ARC_RELEASE(self);
  210. return nil;
  211. }
  212. return [self initWithData:data contentType:type];
  213. }
  214. @end
  215. @implementation GCDWebServerFileResponse
  216. + (GCDWebServerFileResponse*)responseWithFile:(NSString*)path {
  217. return ARC_AUTORELEASE([[[self class] alloc] initWithFile:path]);
  218. }
  219. + (GCDWebServerFileResponse*)responseWithFile:(NSString*)path isAttachment:(BOOL)attachment {
  220. return ARC_AUTORELEASE([[[self class] alloc] initWithFile:path isAttachment:attachment]);
  221. }
  222. + (GCDWebServerFileResponse*)responseWithFile:(NSString*)path byteRange:(NSRange)range {
  223. return ARC_AUTORELEASE([[[self class] alloc] initWithFile:path byteRange:range]);
  224. }
  225. + (GCDWebServerFileResponse*)responseWithFile:(NSString*)path byteRange:(NSRange)range isAttachment:(BOOL)attachment {
  226. return ARC_AUTORELEASE([[[self class] alloc] initWithFile:path byteRange:range isAttachment:attachment]);
  227. }
  228. - (id)initWithFile:(NSString*)path {
  229. return [self initWithFile:path byteRange:NSMakeRange(NSNotFound, 0) isAttachment:NO];
  230. }
  231. - (id)initWithFile:(NSString*)path isAttachment:(BOOL)attachment {
  232. return [self initWithFile:path byteRange:NSMakeRange(NSNotFound, 0) isAttachment:attachment];
  233. }
  234. - (id)initWithFile:(NSString*)path byteRange:(NSRange)range {
  235. return [self initWithFile:path byteRange:range isAttachment:NO];
  236. }
  237. - (id)initWithFile:(NSString*)path byteRange:(NSRange)range isAttachment:(BOOL)attachment {
  238. struct stat info;
  239. if (lstat([path fileSystemRepresentation], &info) || !(info.st_mode & S_IFREG)) {
  240. DNOT_REACHED();
  241. ARC_RELEASE(self);
  242. return nil;
  243. }
  244. if ((range.location != NSNotFound) || (range.length > 0)) {
  245. if (range.location != NSNotFound) {
  246. range.location = MIN(range.location, (NSUInteger)info.st_size);
  247. range.length = MIN(range.length, (NSUInteger)info.st_size - range.location);
  248. } else {
  249. range.length = MIN(range.length, (NSUInteger)info.st_size);
  250. range.location = (NSUInteger)info.st_size - range.length;
  251. }
  252. if (range.length == 0) {
  253. ARC_RELEASE(self);
  254. return nil; // TODO: Return 416 status code and "Content-Range: bytes */{file length}" header
  255. }
  256. }
  257. if ((self = [super initWithContentType:GCDWebServerGetMimeTypeForExtension([path pathExtension]) contentLength:(range.location != NSNotFound ? range.length : (NSUInteger)info.st_size)])) {
  258. _path = [path copy];
  259. if (range.location != NSNotFound) {
  260. _offset = range.location;
  261. _size = range.length;
  262. [self setStatusCode:206];
  263. [self setValue:[NSString stringWithFormat:@"bytes %i-%i/%i", (int)range.location, (int)(range.location + range.length - 1), (int)info.st_size] forAdditionalHeader:@"Content-Range"];
  264. LOG_DEBUG(@"Using content bytes range [%i-%i] for file \"%@\"", (int)range.location, (int)(range.location + range.length - 1), path);
  265. } else {
  266. _offset = 0;
  267. _size = (NSUInteger)info.st_size;
  268. }
  269. if (attachment) { // TODO: Use http://tools.ietf.org/html/rfc5987 to encode file names with special characters instead of using lossy conversion to ISO 8859-1
  270. NSData* data = [[path lastPathComponent] dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:YES];
  271. NSString* fileName = data ? [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding] : nil;
  272. if (fileName) {
  273. [self setValue:[NSString stringWithFormat:@"attachment; filename=\"%@\"", fileName] forAdditionalHeader:@"Content-Disposition"];
  274. ARC_RELEASE(fileName);
  275. } else {
  276. DNOT_REACHED();
  277. }
  278. }
  279. }
  280. return self;
  281. }
  282. - (void)dealloc {
  283. DCHECK(_file <= 0);
  284. ARC_RELEASE(_path);
  285. ARC_DEALLOC(super);
  286. }
  287. - (BOOL)open {
  288. DCHECK(_file <= 0);
  289. _file = open([_path fileSystemRepresentation], O_NOFOLLOW | O_RDONLY);
  290. if (_file <= 0) {
  291. return NO;
  292. }
  293. if (lseek(_file, _offset, SEEK_SET) != (off_t)_offset) {
  294. close(_file);
  295. _file = 0;
  296. return NO;
  297. }
  298. return YES;
  299. }
  300. - (NSInteger)read:(void*)buffer maxLength:(NSUInteger)length {
  301. DCHECK(_file > 0);
  302. ssize_t result = read(_file, buffer, MIN(length, _size));
  303. if (result > 0) {
  304. _size -= result;
  305. }
  306. return result;
  307. }
  308. - (BOOL)close {
  309. DCHECK(_file > 0);
  310. int result = close(_file);
  311. _file = 0;
  312. return (result == 0 ? YES : NO);
  313. }
  314. @end