GCDWebServerFileResponse.m 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. #define kFileReadBufferSize (32 * 1024)
  28. @interface GCDWebServerFileResponse () {
  29. @private
  30. NSString* _path;
  31. NSUInteger _offset;
  32. NSUInteger _size;
  33. int _file;
  34. }
  35. @end
  36. static inline NSError* _MakePosixError(int code) {
  37. return [NSError errorWithDomain:NSPOSIXErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"%s", strerror(code)]}];
  38. }
  39. @implementation GCDWebServerFileResponse
  40. + (instancetype)responseWithFile:(NSString*)path {
  41. return ARC_AUTORELEASE([[[self class] alloc] initWithFile:path]);
  42. }
  43. + (instancetype)responseWithFile:(NSString*)path isAttachment:(BOOL)attachment {
  44. return ARC_AUTORELEASE([[[self class] alloc] initWithFile:path isAttachment:attachment]);
  45. }
  46. + (instancetype)responseWithFile:(NSString*)path byteRange:(NSRange)range {
  47. return ARC_AUTORELEASE([[[self class] alloc] initWithFile:path byteRange:range]);
  48. }
  49. + (instancetype)responseWithFile:(NSString*)path byteRange:(NSRange)range isAttachment:(BOOL)attachment {
  50. return ARC_AUTORELEASE([[[self class] alloc] initWithFile:path byteRange:range isAttachment:attachment]);
  51. }
  52. - (instancetype)initWithFile:(NSString*)path {
  53. return [self initWithFile:path byteRange:NSMakeRange(NSNotFound, 0) isAttachment:NO];
  54. }
  55. - (instancetype)initWithFile:(NSString*)path isAttachment:(BOOL)attachment {
  56. return [self initWithFile:path byteRange:NSMakeRange(NSNotFound, 0) isAttachment:attachment];
  57. }
  58. - (instancetype)initWithFile:(NSString*)path byteRange:(NSRange)range {
  59. return [self initWithFile:path byteRange:range isAttachment:NO];
  60. }
  61. static inline NSDate* _NSDateFromTimeSpec(const struct timespec* t) {
  62. return [NSDate dateWithTimeIntervalSince1970:((NSTimeInterval)t->tv_sec + (NSTimeInterval)t->tv_nsec / 1000000000.0)];
  63. }
  64. - (instancetype)initWithFile:(NSString*)path byteRange:(NSRange)range isAttachment:(BOOL)attachment {
  65. struct stat info;
  66. if (lstat([path fileSystemRepresentation], &info) || !(info.st_mode & S_IFREG)) {
  67. DNOT_REACHED();
  68. ARC_RELEASE(self);
  69. return nil;
  70. }
  71. if (GCDWebServerIsValidByteRange(range)) {
  72. if (range.location != NSNotFound) {
  73. range.location = MIN(range.location, (NSUInteger)info.st_size);
  74. range.length = MIN(range.length, (NSUInteger)info.st_size - range.location);
  75. } else {
  76. range.length = MIN(range.length, (NSUInteger)info.st_size);
  77. range.location = (NSUInteger)info.st_size - range.length;
  78. }
  79. if (range.length == 0) {
  80. ARC_RELEASE(self);
  81. return nil; // TODO: Return 416 status code and "Content-Range: bytes */{file length}" header
  82. }
  83. }
  84. if ((self = [super init])) {
  85. _path = [path copy];
  86. if (range.location != NSNotFound) {
  87. _offset = range.location;
  88. _size = range.length;
  89. [self setStatusCode:kGCDWebServerHTTPStatusCode_PartialContent];
  90. [self setValue:[NSString stringWithFormat:@"bytes %i-%i/%i", (int)range.location, (int)(range.location + range.length - 1), (int)info.st_size] forAdditionalHeader:@"Content-Range"];
  91. LOG_DEBUG(@"Using content bytes range [%i-%i] for file \"%@\"", (int)range.location, (int)(range.location + range.length - 1), path);
  92. } else {
  93. _offset = 0;
  94. _size = (NSUInteger)info.st_size;
  95. }
  96. 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
  97. NSData* data = [[path lastPathComponent] dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:YES];
  98. NSString* fileName = data ? [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding] : nil;
  99. if (fileName) {
  100. [self setValue:[NSString stringWithFormat:@"attachment; filename=\"%@\"", fileName] forAdditionalHeader:@"Content-Disposition"];
  101. ARC_RELEASE(fileName);
  102. } else {
  103. DNOT_REACHED();
  104. }
  105. }
  106. self.contentType = GCDWebServerGetMimeTypeForExtension([path pathExtension]);
  107. self.contentLength = (range.location != NSNotFound ? range.length : (NSUInteger)info.st_size);
  108. self.lastModifiedDate = _NSDateFromTimeSpec(&info.st_mtimespec);
  109. self.eTag = [NSString stringWithFormat:@"%llu/%li/%li", info.st_ino, info.st_mtimespec.tv_sec, info.st_mtimespec.tv_nsec];
  110. }
  111. return self;
  112. }
  113. - (void)dealloc {
  114. ARC_RELEASE(_path);
  115. ARC_DEALLOC(super);
  116. }
  117. - (BOOL)open:(NSError**)error {
  118. _file = open([_path fileSystemRepresentation], O_NOFOLLOW | O_RDONLY);
  119. if (_file <= 0) {
  120. *error = _MakePosixError(errno);
  121. return NO;
  122. }
  123. if (lseek(_file, _offset, SEEK_SET) != (off_t)_offset) {
  124. *error = _MakePosixError(errno);
  125. close(_file);
  126. return NO;
  127. }
  128. return YES;
  129. }
  130. - (NSData*)readData:(NSError**)error {
  131. size_t length = MIN((NSUInteger)kFileReadBufferSize, _size);
  132. NSMutableData* data = [[NSMutableData alloc] initWithLength:length];
  133. ssize_t result = read(_file, data.mutableBytes, length);
  134. if (result < 0) {
  135. *error = _MakePosixError(errno);
  136. return nil;
  137. }
  138. if (result > 0) {
  139. [data setLength:result];
  140. _size -= result;
  141. }
  142. return ARC_AUTORELEASE(data);
  143. }
  144. - (void)close {
  145. close(_file);
  146. }
  147. - (NSString*)description {
  148. NSMutableString* description = [NSMutableString stringWithString:[super description]];
  149. [description appendFormat:@"\n\n{%@}", _path];
  150. return description;
  151. }
  152. @end