GCDWebServerFileResponse.m 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /*
  2. Copyright (c) 2012-2015, 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. #if !__has_feature(objc_arc)
  26. #error GCDWebServer requires ARC
  27. #endif
  28. #import <sys/stat.h>
  29. #import "GCDWebServerPrivate.h"
  30. #define kFileReadBufferSize (32 * 1024)
  31. @implementation GCDWebServerFileResponse {
  32. NSString* _path;
  33. NSUInteger _offset;
  34. NSUInteger _size;
  35. int _file;
  36. }
  37. @dynamic contentType, lastModifiedDate, eTag;
  38. + (instancetype)responseWithFile:(NSString*)path {
  39. return [[[self class] alloc] initWithFile:path];
  40. }
  41. + (instancetype)responseWithFile:(NSString*)path isAttachment:(BOOL)attachment {
  42. return [[[self class] alloc] initWithFile:path isAttachment:attachment];
  43. }
  44. + (instancetype)responseWithFile:(NSString*)path byteRange:(NSRange)range {
  45. return [[[self class] alloc] initWithFile:path byteRange:range];
  46. }
  47. + (instancetype)responseWithFile:(NSString*)path byteRange:(NSRange)range isAttachment:(BOOL)attachment {
  48. return [[[self class] alloc] initWithFile:path byteRange:range isAttachment:attachment];
  49. }
  50. - (instancetype)initWithFile:(NSString*)path {
  51. return [self initWithFile:path byteRange:NSMakeRange(NSUIntegerMax, 0) isAttachment:NO];
  52. }
  53. - (instancetype)initWithFile:(NSString*)path isAttachment:(BOOL)attachment {
  54. return [self initWithFile:path byteRange:NSMakeRange(NSUIntegerMax, 0) isAttachment:attachment];
  55. }
  56. - (instancetype)initWithFile:(NSString*)path byteRange:(NSRange)range {
  57. return [self initWithFile:path byteRange:range isAttachment:NO];
  58. }
  59. static inline NSDate* _NSDateFromTimeSpec(const struct timespec* t) {
  60. return [NSDate dateWithTimeIntervalSince1970:((NSTimeInterval)t->tv_sec + (NSTimeInterval)t->tv_nsec / 1000000000.0)];
  61. }
  62. - (instancetype)initWithFile:(NSString*)path byteRange:(NSRange)range isAttachment:(BOOL)attachment {
  63. struct stat info;
  64. if (lstat([path fileSystemRepresentation], &info) || !(info.st_mode & S_IFREG)) {
  65. GWS_DNOT_REACHED();
  66. return nil;
  67. }
  68. #ifndef __LP64__
  69. if (info.st_size >= (off_t)4294967295) { // In 32 bit mode, we can't handle files greater than 4 GiBs (don't use "NSUIntegerMax" here to avoid potential unsigned to signed conversion issues)
  70. GWS_DNOT_REACHED();
  71. return nil;
  72. }
  73. #endif
  74. NSUInteger fileSize = (NSUInteger)info.st_size;
  75. BOOL hasByteRange = GCDWebServerIsValidByteRange(range);
  76. if (hasByteRange) {
  77. if (range.location != NSUIntegerMax) {
  78. range.location = MIN(range.location, fileSize);
  79. range.length = MIN(range.length, fileSize - range.location);
  80. } else {
  81. range.length = MIN(range.length, fileSize);
  82. range.location = fileSize - range.length;
  83. }
  84. if (range.length == 0) {
  85. return nil; // TODO: Return 416 status code and "Content-Range: bytes */{file length}" header
  86. }
  87. } else {
  88. range.location = 0;
  89. range.length = fileSize;
  90. }
  91. if ((self = [super init])) {
  92. _path = [path copy];
  93. _offset = range.location;
  94. _size = range.length;
  95. if (hasByteRange) {
  96. [self setStatusCode:kGCDWebServerHTTPStatusCode_PartialContent];
  97. [self setValue:[NSString stringWithFormat:@"bytes %lu-%lu/%lu", (unsigned long)_offset, (unsigned long)(_offset + _size - 1), (unsigned long)fileSize] forAdditionalHeader:@"Content-Range"];
  98. GWS_LOG_DEBUG(@"Using content bytes range [%lu-%lu] for file \"%@\"", (unsigned long)_offset, (unsigned long)(_offset + _size - 1), path);
  99. }
  100. if (attachment) {
  101. NSString* fileName = [path lastPathComponent];
  102. NSData* data = [[fileName stringByReplacingOccurrencesOfString:@"\"" withString:@""] dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:YES];
  103. NSString* lossyFileName = data ? [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding] : nil;
  104. if (lossyFileName) {
  105. NSString* value = [NSString stringWithFormat:@"attachment; filename=\"%@\"; filename*=UTF-8''%@", lossyFileName, GCDWebServerEscapeURLString(fileName)];
  106. [self setValue:value forAdditionalHeader:@"Content-Disposition"];
  107. } else {
  108. GWS_DNOT_REACHED();
  109. }
  110. }
  111. self.contentType = GCDWebServerGetMimeTypeForExtension([_path pathExtension]);
  112. self.contentLength = _size;
  113. self.lastModifiedDate = _NSDateFromTimeSpec(&info.st_mtimespec);
  114. self.eTag = [NSString stringWithFormat:@"%llu/%li/%li", info.st_ino, info.st_mtimespec.tv_sec, info.st_mtimespec.tv_nsec];
  115. }
  116. return self;
  117. }
  118. - (BOOL)open:(NSError**)error {
  119. _file = open([_path fileSystemRepresentation], O_NOFOLLOW | O_RDONLY);
  120. if (_file <= 0) {
  121. if (error) {
  122. *error = GCDWebServerMakePosixError(errno);
  123. }
  124. return NO;
  125. }
  126. if (lseek(_file, _offset, SEEK_SET) != (off_t)_offset) {
  127. if (error) {
  128. *error = GCDWebServerMakePosixError(errno);
  129. }
  130. close(_file);
  131. return NO;
  132. }
  133. return YES;
  134. }
  135. - (NSData*)readData:(NSError**)error {
  136. size_t length = MIN((NSUInteger)kFileReadBufferSize, _size);
  137. NSMutableData* data = [[NSMutableData alloc] initWithLength:length];
  138. ssize_t result = read(_file, data.mutableBytes, length);
  139. if (result < 0) {
  140. if (error) {
  141. *error = GCDWebServerMakePosixError(errno);
  142. }
  143. return nil;
  144. }
  145. if (result > 0) {
  146. [data setLength:result];
  147. _size -= result;
  148. }
  149. return data;
  150. }
  151. - (void)close {
  152. close(_file);
  153. }
  154. - (NSString*)description {
  155. NSMutableString* description = [NSMutableString stringWithString:[super description]];
  156. [description appendFormat:@"\n\n{%@}", _path];
  157. return description;
  158. }
  159. @end