VLCHTTPUploaderController.m 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. //
  2. // VLCHTTPUploaderViewController.m
  3. // VLC for iOS
  4. //
  5. // Created by Jean-Baptiste Kempf on 19/05/13.
  6. // Copyright (c) 2013 VideoLAN. All rights reserved.
  7. //
  8. #import "VLCHTTPUploaderController.h"
  9. #import "DDLog.h"
  10. #import "DDTTYLogger.h"
  11. #import "DDNumber.h"
  12. #import "HTTPServer.h"
  13. #import "HTTPMessage.h"
  14. #import "HTTPDataResponse.h"
  15. #import "HTTPLogging.h"
  16. #import "HTTPDynamicFileResponse.h"
  17. #import "HTTPFileResponse.h"
  18. #import "MultipartFormDataParser.h"
  19. #import "MultipartMessageHeaderField.h"
  20. static const int ddLogLevel = LOG_LEVEL_VERBOSE;
  21. static const int httpLogLevel = HTTP_LOG_LEVEL_VERBOSE; // | HTTP_LOG_FLAG_TRACE;
  22. @interface VLCHTTPUploaderController ()
  23. @end
  24. @implementation VLCHTTPUploaderController
  25. -(BOOL)changeHTTPServerState:(BOOL)state
  26. {
  27. if(state) {
  28. // To keep things simple and fast, we're just going to log to the Xcode console.
  29. [DDLog addLogger:[DDTTYLogger sharedInstance]];
  30. // Initalize our http server
  31. _httpServer = [[HTTPServer alloc] init];
  32. // Tell the server to broadcast its presence via Bonjour.
  33. // This allows browsers such as Safari to automatically discover our service.
  34. [self.httpServer setType:@"_http._tcp."];
  35. // Serve files from the standard Sites folder
  36. NSString *docRoot = [[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"] stringByDeletingLastPathComponent];
  37. DDLogInfo(@"Setting document root: %@", docRoot);
  38. [self.httpServer setDocumentRoot:docRoot];
  39. [self.httpServer setConnectionClass:[VLCHTTPConnection class]];
  40. NSError *error = nil;
  41. if(![self.httpServer start:&error])
  42. {
  43. DDLogError(@"Error starting HTTP Server: %@", error);
  44. return false;
  45. }
  46. return true;
  47. } else {
  48. [self.httpServer stop];
  49. return true;
  50. }
  51. }
  52. @end
  53. /**
  54. * All we have to do is override appropriate methods in HTTPConnection.
  55. **/
  56. @implementation VLCHTTPConnection
  57. - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
  58. {
  59. HTTPLogTrace();
  60. // Add support for POST
  61. if ([method isEqualToString:@"POST"])
  62. {
  63. if ([path isEqualToString:@"/upload.html"])
  64. {
  65. return YES;
  66. }
  67. }
  68. return [super supportsMethod:method atPath:path];
  69. }
  70. - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
  71. {
  72. HTTPLogTrace();
  73. // Inform HTTP server that we expect a body to accompany a POST request
  74. if([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.html"]) {
  75. // here we need to make sure, boundary is set in header
  76. NSString* contentType = [request headerField:@"Content-Type"];
  77. NSUInteger paramsSeparator = [contentType rangeOfString:@";"].location;
  78. if( NSNotFound == paramsSeparator ) {
  79. return NO;
  80. }
  81. if( paramsSeparator >= contentType.length - 1 ) {
  82. return NO;
  83. }
  84. NSString* type = [contentType substringToIndex:paramsSeparator];
  85. if( ![type isEqualToString:@"multipart/form-data"] ) {
  86. // we expect multipart/form-data content type
  87. return NO;
  88. }
  89. // enumerate all params in content-type, and find boundary there
  90. NSArray* params = [[contentType substringFromIndex:paramsSeparator + 1] componentsSeparatedByString:@";"];
  91. for( NSString* param in params ) {
  92. paramsSeparator = [param rangeOfString:@"="].location;
  93. if( (NSNotFound == paramsSeparator) || paramsSeparator >= param.length - 1 ) {
  94. continue;
  95. }
  96. NSString* paramName = [param substringWithRange:NSMakeRange(1, paramsSeparator-1)];
  97. NSString* paramValue = [param substringFromIndex:paramsSeparator+1];
  98. if( [paramName isEqualToString: @"boundary"] ) {
  99. // let's separate the boundary from content-type, to make it more handy to handle
  100. [request setHeaderField:@"boundary" value:paramValue];
  101. }
  102. }
  103. // check if boundary specified
  104. if( nil == [request headerField:@"boundary"] ) {
  105. return NO;
  106. }
  107. return YES;
  108. }
  109. return [super expectsRequestBodyFromMethod:method atPath:path];
  110. }
  111. - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
  112. {
  113. HTTPLogTrace();
  114. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.html"])
  115. {
  116. // this method will generate response with links to uploaded file
  117. NSMutableString* filesStr = [[NSMutableString alloc] init];
  118. for( NSString* filePath in uploadedFiles ) {
  119. //generate links
  120. [filesStr appendFormat:@"<a href=\"%@\"> %@ </a><br/>",filePath, [filePath lastPathComponent]];
  121. }
  122. NSString* templatePath = [[config documentRoot] stringByAppendingPathComponent:@"upload.html"];
  123. NSDictionary* replacementDict = [NSDictionary dictionaryWithObject:filesStr forKey:@"MyFiles"];
  124. // use dynamic file response to apply our links to response template
  125. return [[HTTPDynamicFileResponse alloc] initWithFilePath:templatePath forConnection:self separator:@"%" replacementDictionary:replacementDict];
  126. }
  127. if( [method isEqualToString:@"GET"] && [path hasPrefix:@"/upload/"] ) {
  128. // let download the uploaded files
  129. return [[HTTPFileResponse alloc] initWithFilePath: [[config documentRoot] stringByAppendingString:path] forConnection:self];
  130. }
  131. return [super httpResponseForMethod:method URI:path];
  132. }
  133. - (void)prepareForBodyWithSize:(UInt64)contentLength
  134. {
  135. HTTPLogTrace();
  136. // set up mime parser
  137. NSString* boundary = [request headerField:@"boundary"];
  138. parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  139. parser.delegate = self;
  140. uploadedFiles = [[NSMutableArray alloc] init];
  141. }
  142. - (void)processBodyData:(NSData *)postDataChunk
  143. {
  144. HTTPLogTrace();
  145. // append data to the parser. It will invoke callbacks to let us handle
  146. // parsed data.
  147. [parser appendData:postDataChunk];
  148. }
  149. //-----------------------------------------------------------------
  150. #pragma mark multipart form data parser delegate
  151. - (void) processStartOfPartWithHeader:(MultipartMessageHeader*) header {
  152. // in this sample, we are not interested in parts, other then file parts.
  153. // check content disposition to find out filename
  154. MultipartMessageHeaderField* disposition = [header.fields objectForKey:@"Content-Disposition"];
  155. NSString* filename = [[disposition.params objectForKey:@"filename"] lastPathComponent];
  156. if ( (nil == filename) || [filename isEqualToString: @""] ) {
  157. // it's either not a file part, or
  158. // an empty form sent. we won't handle it.
  159. return;
  160. }
  161. NSString* uploadDirPath = [[config documentRoot] stringByAppendingPathComponent:@"upload"];
  162. BOOL isDir = YES;
  163. if (![[NSFileManager defaultManager]fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
  164. [[NSFileManager defaultManager]createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  165. }
  166. NSString* filePath = [uploadDirPath stringByAppendingPathComponent: filename];
  167. if( [[NSFileManager defaultManager] fileExistsAtPath:filePath] ) {
  168. storeFile = nil;
  169. }
  170. else {
  171. HTTPLogVerbose(@"Saving file to %@", filePath);
  172. if(![[NSFileManager defaultManager] createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil]) {
  173. HTTPLogError(@"Could not create directory at path: %@", filePath);
  174. }
  175. if(![[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]) {
  176. HTTPLogError(@"Could not create file at path: %@", filePath);
  177. }
  178. storeFile = [NSFileHandle fileHandleForWritingAtPath:filePath];
  179. [uploadedFiles addObject: [NSString stringWithFormat:@"/upload/%@", filename]];
  180. }
  181. }
  182. - (void) processContent:(NSData*) data WithHeader:(MultipartMessageHeader*) header
  183. {
  184. // here we just write the output from parser to the file.
  185. if( storeFile ) {
  186. [storeFile writeData:data];
  187. }
  188. }
  189. - (void) processEndOfPartWithHeader:(MultipartMessageHeader*) header
  190. {
  191. // as the file part is over, we close the file.
  192. [storeFile closeFile];
  193. storeFile = nil;
  194. }
  195. @end