GCDWebServerResponse.m 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /*
  2. Copyright (c) 2012-2013, 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. * Neither the name of the <organization> nor the
  12. names of its contributors may be used to endorse or promote products
  13. derived from this software without specific 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 <COPYRIGHT HOLDER> 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. @implementation GCDWebServerResponse
  28. @synthesize contentType=_type, contentLength=_length, statusCode=_status, cacheControlMaxAge=_maxAge, additionalHeaders=_headers;
  29. +(GCDWebServerResponse*) response {
  30. return [[[[self class] alloc] init] autorelease];
  31. }
  32. - (id)init {
  33. return [self initWithContentType:nil contentLength:0];
  34. }
  35. - (id)initWithContentType:(NSString*)type contentLength:(NSUInteger)length {
  36. if ((self = [super init])) {
  37. _type = [type copy];
  38. _length = length;
  39. _status = 200;
  40. _maxAge = 0;
  41. _headers = [[NSMutableDictionary alloc] init];
  42. if ((_length > 0) && (_type == nil)) {
  43. _type = [kGCDWebServerDefaultMimeType copy];
  44. }
  45. }
  46. return self;
  47. }
  48. - (void)dealloc {
  49. [_type release];
  50. [_headers release];
  51. [super dealloc];
  52. }
  53. - (void)setValue:(NSString*)value forAdditionalHeader:(NSString*)header {
  54. [_headers setValue:value forKey:header];
  55. }
  56. - (BOOL)hasBody {
  57. return _type ? YES : NO;
  58. }
  59. @end
  60. @implementation GCDWebServerResponse (Subclassing)
  61. - (BOOL)open {
  62. [self doesNotRecognizeSelector:_cmd];
  63. return NO;
  64. }
  65. - (NSInteger)read:(void*)buffer maxLength:(NSUInteger)length {
  66. [self doesNotRecognizeSelector:_cmd];
  67. return -1;
  68. }
  69. - (BOOL)close {
  70. [self doesNotRecognizeSelector:_cmd];
  71. return NO;
  72. }
  73. @end
  74. @implementation GCDWebServerResponse (Extensions)
  75. + (GCDWebServerResponse*)responseWithStatusCode:(NSInteger)statusCode {
  76. return [[[self alloc] initWithStatusCode:statusCode] autorelease];
  77. }
  78. + (GCDWebServerResponse*)responseWithRedirect:(NSURL*)location permanent:(BOOL)permanent {
  79. return [[[self alloc] initWithRedirect:location permanent:permanent] autorelease];
  80. }
  81. - (id)initWithStatusCode:(NSInteger)statusCode {
  82. if ((self = [self initWithContentType:nil contentLength:0])) {
  83. self.statusCode = statusCode;
  84. }
  85. return self;
  86. }
  87. - (id)initWithRedirect:(NSURL*)location permanent:(BOOL)permanent {
  88. if ((self = [self initWithContentType:nil contentLength:0])) {
  89. self.statusCode = permanent ? 301 : 307;
  90. [self setValue:[location absoluteString] forAdditionalHeader:@"Location"];
  91. }
  92. return self;
  93. }
  94. @end
  95. @implementation GCDWebServerDataResponse
  96. + (GCDWebServerDataResponse*)responseWithData:(NSData*)data contentType:(NSString*)type {
  97. return [[[[self class] alloc] initWithData:data contentType:type] autorelease];
  98. }
  99. - (id)initWithData:(NSData*)data contentType:(NSString*)type {
  100. if (data == nil) {
  101. DNOT_REACHED();
  102. [self release];
  103. return nil;
  104. }
  105. if ((self = [super initWithContentType:type contentLength:data.length])) {
  106. _data = [data retain];
  107. _offset = -1;
  108. }
  109. return self;
  110. }
  111. - (void)dealloc {
  112. DCHECK(_offset < 0);
  113. [_data release];
  114. [super dealloc];
  115. }
  116. - (BOOL)open {
  117. DCHECK(_offset < 0);
  118. _offset = 0;
  119. return YES;
  120. }
  121. - (NSInteger)read:(void*)buffer maxLength:(NSUInteger)length {
  122. DCHECK(_offset >= 0);
  123. NSInteger size = 0;
  124. if (_offset < _data.length) {
  125. size = MIN(_data.length - _offset, length);
  126. bcopy((char*)_data.bytes + _offset, buffer, size);
  127. _offset += size;
  128. }
  129. return size;
  130. }
  131. - (BOOL)close {
  132. DCHECK(_offset >= 0);
  133. _offset = -1;
  134. return YES;
  135. }
  136. @end
  137. @implementation GCDWebServerDataResponse (Extensions)
  138. + (GCDWebServerDataResponse*)responseWithText:(NSString*)text {
  139. return [[[self alloc] initWithText:text] autorelease];
  140. }
  141. + (GCDWebServerDataResponse*)responseWithHTML:(NSString*)html {
  142. return [[[self alloc] initWithHTML:html] autorelease];
  143. }
  144. + (GCDWebServerDataResponse*)responseWithHTMLTemplate:(NSString*)path variables:(NSDictionary*)variables {
  145. return [[[self alloc] initWithHTMLTemplate:path variables:variables] autorelease];
  146. }
  147. - (id)initWithText:(NSString*)text {
  148. NSData* data = [text dataUsingEncoding:NSUTF8StringEncoding];
  149. if (data == nil) {
  150. DNOT_REACHED();
  151. [self release];
  152. return nil;
  153. }
  154. return [self initWithData:data contentType:@"text/plain; charset=utf-8"];
  155. }
  156. - (id)initWithHTML:(NSString*)html {
  157. NSData* data = [html dataUsingEncoding:NSUTF8StringEncoding];
  158. if (data == nil) {
  159. DNOT_REACHED();
  160. [self release];
  161. return nil;
  162. }
  163. return [self initWithData:data contentType:@"text/html; charset=utf-8"];
  164. }
  165. - (id)initWithHTMLTemplate:(NSString*)path variables:(NSDictionary*)variables {
  166. NSMutableString* html = [[NSMutableString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
  167. [variables enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSString* value, BOOL* stop) {
  168. [html replaceOccurrencesOfString:[NSString stringWithFormat:@"%%%@%%", key] withString:value options:0 range:NSMakeRange(0, html.length)];
  169. }];
  170. id response = [self initWithHTML:html];
  171. [html release];
  172. return response;
  173. }
  174. @end
  175. @implementation GCDWebServerFileResponse
  176. + (GCDWebServerFileResponse*)responseWithFile:(NSString*)path {
  177. return [[[[self class] alloc] initWithFile:path] autorelease];
  178. }
  179. + (GCDWebServerFileResponse*)responseWithFile:(NSString*)path isAttachment:(BOOL)attachment {
  180. return [[[[self class] alloc] initWithFile:path isAttachment:attachment] autorelease];
  181. }
  182. - (id)initWithFile:(NSString*)path {
  183. return [self initWithFile:path isAttachment:NO];
  184. }
  185. - (id)initWithFile:(NSString*)path isAttachment:(BOOL)attachment {
  186. struct stat info;
  187. if (lstat([path fileSystemRepresentation], &info) || !(info.st_mode & S_IFREG)) {
  188. DNOT_REACHED();
  189. [self release];
  190. return nil;
  191. }
  192. NSString* type = GCDWebServerGetMimeTypeForExtension([path pathExtension]);
  193. if (type == nil) {
  194. type = kGCDWebServerDefaultMimeType;
  195. }
  196. if ((self = [super initWithContentType:type contentLength:info.st_size])) {
  197. _path = [path copy];
  198. 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
  199. NSData* data = [[path lastPathComponent] dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:YES];
  200. NSString* fileName = data ? [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding] : nil;
  201. if (fileName) {
  202. [self setValue:[NSString stringWithFormat:@"attachment; filename=\"%@\"", fileName] forAdditionalHeader:@"Content-Disposition"];
  203. [fileName release];
  204. } else {
  205. DNOT_REACHED();
  206. }
  207. }
  208. }
  209. return self;
  210. }
  211. - (void)dealloc {
  212. DCHECK(_file <= 0);
  213. [_path release];
  214. [super dealloc];
  215. }
  216. - (BOOL)open {
  217. DCHECK(_file <= 0);
  218. _file = open([_path fileSystemRepresentation], O_NOFOLLOW | O_RDONLY);
  219. return (_file > 0 ? YES : NO);
  220. }
  221. - (NSInteger)read:(void*)buffer maxLength:(NSUInteger)length {
  222. DCHECK(_file > 0);
  223. return read(_file, buffer, length);
  224. }
  225. - (BOOL)close {
  226. DCHECK(_file > 0);
  227. int result = close(_file);
  228. _file = 0;
  229. return (result == 0 ? YES : NO);
  230. }
  231. @end