VLCHTTPUploaderController.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. // Refer to the COPYING file of the official project for license.
  9. //
  10. #import "VLCHTTPUploaderController.h"
  11. #import "VLCAppDelegate.h"
  12. #import "DDLog.h"
  13. #import "DDTTYLogger.h"
  14. #import "DDNumber.h"
  15. #import "HTTPServer.h"
  16. #import "HTTPMessage.h"
  17. #import "HTTPDataResponse.h"
  18. #import "HTTPLogging.h"
  19. #import "HTTPDynamicFileResponse.h"
  20. #import "HTTPFileResponse.h"
  21. #import "MultipartFormDataParser.h"
  22. #import "MultipartMessageHeaderField.h"
  23. #import <ifaddrs.h>
  24. #import <arpa/inet.h>
  25. #if TARGET_IPHONE_SIMULATOR
  26. NSString *const WifiInterfaceName = @"en1";
  27. #else
  28. NSString *const WifiInterfaceName = @"en0";
  29. #endif
  30. static const int ddLogLevel = LOG_LEVEL_VERBOSE;
  31. static const int httpLogLevel = HTTP_LOG_LEVEL_VERBOSE; // | HTTP_LOG_FLAG_TRACE;
  32. @interface VLCHTTPUploaderController ()
  33. @end
  34. @implementation VLCHTTPUploaderController
  35. - (id)init
  36. {
  37. if ( self = [super init] ) {
  38. // Just log to the Xcode console.
  39. [DDLog addLogger:[DDTTYLogger sharedInstance]];
  40. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  41. [center addObserver:self selector:@selector(applicationDidBecomeActive:)
  42. name:UIApplicationDidBecomeActiveNotification object:nil];
  43. [center addObserver:self selector:@selector(applicationDidEnterBackground:)
  44. name:UIApplicationDidEnterBackgroundNotification object:nil];
  45. return self;
  46. }
  47. else
  48. return nil;
  49. }
  50. - (void)applicationDidBecomeActive: (NSNotification *)notification
  51. {
  52. BOOL isHTTPServerOn = [[NSUserDefaults standardUserDefaults] boolForKey:kVLCSettingSaveHTTPUploadServerStatus];
  53. [self changeHTTPServerState:isHTTPServerOn];
  54. }
  55. - (void)applicationDidEnterBackground: (NSNotification *)notification
  56. {
  57. [self changeHTTPServerState:NO];
  58. }
  59. -(BOOL)changeHTTPServerState:(BOOL)state
  60. {
  61. if(state) {
  62. // Initalize our http server
  63. _httpServer = [[HTTPServer alloc] init];
  64. [_httpServer setInterface:WifiInterfaceName];
  65. // Tell the server to broadcast its presence via Bonjour.
  66. // This allows browsers such as Safari to automatically discover our service.
  67. [self.httpServer setType:@"_http._tcp."];
  68. // Serve files from the standard Sites folder
  69. NSString *docRoot = [[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"] stringByDeletingLastPathComponent];
  70. DDLogInfo(@"Setting document root: %@", docRoot);
  71. [self.httpServer setDocumentRoot:docRoot];
  72. [self.httpServer setPort:80];
  73. [self.httpServer setConnectionClass:[VLCHTTPConnection class]];
  74. NSError *error = nil;
  75. if(![self.httpServer start:&error])
  76. {
  77. if (error.code == 13) {
  78. DDLogError(@"Port forbidden by OS, trying another one");
  79. [self.httpServer setPort:8888];
  80. if(![self.httpServer start:&error])
  81. return true;
  82. }
  83. /* Address already in Use, take a random one */
  84. if(error.code == 48) {
  85. DDLogError(@"Port already in use, trying another one");
  86. [self.httpServer setPort:0];
  87. if(![self.httpServer start:&error])
  88. return true;
  89. }
  90. if (error.code != 0)
  91. DDLogError(@"Error starting HTTP Server: %@", error.localizedDescription);
  92. return false;
  93. }
  94. return true;
  95. } else {
  96. [self.httpServer stop];
  97. return true;
  98. }
  99. }
  100. - (NSString *)currentIPAddress
  101. {
  102. NSString *address = @"";
  103. struct ifaddrs *interfaces = NULL;
  104. struct ifaddrs *temp_addr = NULL;
  105. int success = getifaddrs(&interfaces);
  106. if (success == 0) {
  107. temp_addr = interfaces;
  108. while(temp_addr != NULL) {
  109. if(temp_addr->ifa_addr->sa_family == AF_INET) {
  110. if([@(temp_addr->ifa_name) isEqualToString:WifiInterfaceName])
  111. address = @(inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr));
  112. }
  113. temp_addr = temp_addr->ifa_next;
  114. }
  115. }
  116. // Free memory
  117. freeifaddrs(interfaces);
  118. return address;
  119. }
  120. @end
  121. /**
  122. * All we have to do is override appropriate methods in HTTPConnection.
  123. **/
  124. @implementation VLCHTTPConnection
  125. - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
  126. {
  127. HTTPLogTrace();
  128. // Add support for POST
  129. if ([method isEqualToString:@"POST"])
  130. {
  131. if ([path isEqualToString:@"/upload.json"])
  132. {
  133. return YES;
  134. }
  135. }
  136. return [super supportsMethod:method atPath:path];
  137. }
  138. - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
  139. {
  140. HTTPLogTrace();
  141. // Inform HTTP server that we expect a body to accompany a POST request
  142. if([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  143. // here we need to make sure, boundary is set in header
  144. NSString* contentType = [request headerField:@"Content-Type"];
  145. NSUInteger paramsSeparator = [contentType rangeOfString:@";"].location;
  146. if( NSNotFound == paramsSeparator ) {
  147. return NO;
  148. }
  149. if( paramsSeparator >= contentType.length - 1 ) {
  150. return NO;
  151. }
  152. NSString* type = [contentType substringToIndex:paramsSeparator];
  153. if( ![type isEqualToString:@"multipart/form-data"] ) {
  154. // we expect multipart/form-data content type
  155. return NO;
  156. }
  157. // enumerate all params in content-type, and find boundary there
  158. NSArray* params = [[contentType substringFromIndex:paramsSeparator + 1] componentsSeparatedByString:@";"];
  159. for( NSString* param in params ) {
  160. paramsSeparator = [param rangeOfString:@"="].location;
  161. if( (NSNotFound == paramsSeparator) || paramsSeparator >= param.length - 1 ) {
  162. continue;
  163. }
  164. NSString* paramName = [param substringWithRange:NSMakeRange(1, paramsSeparator-1)];
  165. NSString* paramValue = [param substringFromIndex:paramsSeparator+1];
  166. if( [paramName isEqualToString: @"boundary"] ) {
  167. // let's separate the boundary from content-type, to make it more handy to handle
  168. [request setHeaderField:@"boundary" value:paramValue];
  169. }
  170. }
  171. // check if boundary specified
  172. if( nil == [request headerField:@"boundary"] ) {
  173. return NO;
  174. }
  175. return YES;
  176. }
  177. return [super expectsRequestBodyFromMethod:method atPath:path];
  178. }
  179. - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
  180. {
  181. HTTPLogTrace();
  182. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"])
  183. {
  184. return [[HTTPDataResponse alloc] initWithData:[@"\"OK\"" dataUsingEncoding:NSUTF8StringEncoding]];
  185. }
  186. if( [method isEqualToString:@"GET"] && [path hasPrefix:@"/upload/"] ) {
  187. // let download the uploaded files
  188. return [[HTTPFileResponse alloc] initWithFilePath: [[config documentRoot] stringByAppendingString:path] forConnection:self];
  189. }
  190. return [super httpResponseForMethod:method URI:path];
  191. }
  192. - (void)prepareForBodyWithSize:(UInt64)contentLength
  193. {
  194. HTTPLogTrace();
  195. // set up mime parser
  196. NSString* boundary = [request headerField:@"boundary"];
  197. parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  198. parser.delegate = self;
  199. uploadedFiles = [[NSMutableArray alloc] init];
  200. }
  201. - (void)processBodyData:(NSData *)postDataChunk
  202. {
  203. HTTPLogTrace();
  204. // append data to the parser. It will invoke callbacks to let us handle
  205. // parsed data.
  206. [parser appendData:postDataChunk];
  207. }
  208. //-----------------------------------------------------------------
  209. #pragma mark multipart form data parser delegate
  210. - (void) processStartOfPartWithHeader:(MultipartMessageHeader*) header {
  211. // in this sample, we are not interested in parts, other then file parts.
  212. // check content disposition to find out filename
  213. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  214. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  215. if ( (nil == filename) || [filename isEqualToString: @""] ) {
  216. // it's either not a file part, or
  217. // an empty form sent. we won't handle it.
  218. return;
  219. }
  220. // create the path where to store the media
  221. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  222. NSString* uploadDirPath = searchPaths[0];
  223. BOOL isDir = YES;
  224. if (![[NSFileManager defaultManager]fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
  225. [[NSFileManager defaultManager]createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  226. }
  227. NSString* filePath = [uploadDirPath stringByAppendingPathComponent: filename];
  228. if( [[NSFileManager defaultManager] fileExistsAtPath:filePath] ) {
  229. storeFile = nil;
  230. }
  231. else {
  232. HTTPLogVerbose(@"Saving file to %@", filePath);
  233. if(![[NSFileManager defaultManager] createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil]) {
  234. HTTPLogError(@"Could not create directory at path: %@", filePath);
  235. }
  236. if(![[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]) {
  237. HTTPLogError(@"Could not create file at path: %@", filePath);
  238. }
  239. storeFile = [NSFileHandle fileHandleForWritingAtPath:filePath];
  240. [uploadedFiles addObject: [NSString stringWithFormat:@"/upload/%@", filename]];
  241. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  242. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate disableIdleTimer];
  243. }
  244. }
  245. - (void) processContent:(NSData*) data WithHeader:(MultipartMessageHeader*) header
  246. {
  247. // here we just write the output from parser to the file.
  248. if( storeFile ) {
  249. [storeFile writeData:data];
  250. }
  251. }
  252. - (void) processEndOfPartWithHeader:(MultipartMessageHeader*) header
  253. {
  254. // as the file part is over, we close the file.
  255. [storeFile closeFile];
  256. storeFile = nil;
  257. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  258. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate activateIdleTimer];
  259. /* update media library when file upload was completed */
  260. VLCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
  261. [appDelegate updateMediaList];
  262. }
  263. @end