├── CocoaHttpServer ├── CocoaAsyncSocket │ ├── About.txt │ ├── GCDAsyncSocket.h │ └── GCDAsyncSocket.m ├── CocoaLumberjack │ ├── About.txt │ ├── DDASLLogger.h │ ├── DDASLLogger.m │ ├── DDAbstractDatabaseLogger.h │ ├── DDAbstractDatabaseLogger.m │ ├── DDFileLogger.h │ ├── DDFileLogger.m │ ├── DDLog.h │ ├── DDLog.m │ ├── DDTTYLogger.h │ ├── DDTTYLogger.m │ └── Extensions │ │ ├── ContextFilterLogFormatter.h │ │ ├── ContextFilterLogFormatter.m │ │ ├── DispatchQueueLogFormatter.h │ │ ├── DispatchQueueLogFormatter.m │ │ └── README.txt └── Core │ ├── Categories │ ├── DDData.h │ ├── DDData.m │ ├── DDNumber.h │ ├── DDNumber.m │ ├── DDRange.h │ └── DDRange.m │ ├── HTTPAuthenticationRequest.h │ ├── HTTPAuthenticationRequest.m │ ├── HTTPConnection.h │ ├── HTTPConnection.m │ ├── HTTPLogging.h │ ├── HTTPMessage.h │ ├── HTTPMessage.m │ ├── HTTPResponse.h │ ├── HTTPServer.h │ ├── HTTPServer.m │ ├── Mime │ ├── MultipartFormDataParser.h │ ├── MultipartFormDataParser.m │ ├── MultipartMessageHeader.h │ ├── MultipartMessageHeader.m │ ├── MultipartMessageHeaderField.h │ └── MultipartMessageHeaderField.m │ ├── MyHTTPConnection.h │ ├── MyHTTPConnection.m │ ├── Responses │ ├── HTTPAsyncFileResponse.h │ ├── HTTPAsyncFileResponse.m │ ├── HTTPDataResponse.h │ ├── HTTPDataResponse.m │ ├── HTTPDynamicFileResponse.h │ ├── HTTPDynamicFileResponse.m │ ├── HTTPErrorResponse.h │ ├── HTTPErrorResponse.m │ ├── HTTPFileResponse.h │ ├── HTTPFileResponse.m │ ├── HTTPRedirectResponse.h │ └── HTTPRedirectResponse.m │ ├── WebSocket.h │ └── WebSocket.m ├── LocalWebServer.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── Smallfan.xcuserdatad │ │ └── UserInterfaceState.xcuserstate └── xcuserdata │ └── Smallfan.xcuserdatad │ ├── xcdebugger │ └── Breakpoints_v2.xcbkptlist │ └── xcschemes │ ├── LocalWebServer.xcscheme │ └── xcschememanagement.plist ├── LocalWebServer ├── AppDelegate.h ├── AppDelegate.m ├── Base.lproj │ └── LaunchScreen.storyboard ├── Info.plist ├── LocalWebServerManager.h ├── LocalWebServerManager.m ├── ViewController.h ├── ViewController.m └── main.m ├── README.md └── Resource ├── hi.js ├── index.html └── localhost.p12 /CocoaHttpServer/CocoaAsyncSocket/About.txt: -------------------------------------------------------------------------------- 1 | The CocoaAsyncSocket project is under Public Domain license. 2 | http://code.google.com/p/cocoaasyncsocket/ 3 | 4 | The AsyncSocket project has been around since 2001 and is used in many applications and frameworks. -------------------------------------------------------------------------------- /CocoaHttpServer/CocoaLumberjack/About.txt: -------------------------------------------------------------------------------- 1 | CocoaLumberjack is under the New BSD License. 2 | https://github.com/robbiehanson/CocoaLumberjack 3 | 4 | Extensive documentation, tutorials, etc are available: 5 | https://github.com/robbiehanson/CocoaLumberjack/wiki 6 | 7 | Overview of the project (copied from google code homepage): 8 | 9 | 10 | 11 | The lumberjack framework is fast & simple, yet powerful & flexible. 12 | It is similar in concept to other popular logging frameworks such as log4j, yet is designed specifically for objective-c, and takes advantage of features such as multi-threading, grand central dispatch (if available), lockless atomic operations, and the dynamic nature of the objective-c runtime. 13 | 14 | Lumberjack is fast: 15 | In most cases it is an order of magnitude faster than NSLog. 16 | 17 | Lumberjack is simple: 18 | It takes as little as a single line of code to configure lumberjack when your application launches. Then simply replace your NSLog statements with DDLog statements and that's about it. (And the DDLog macros have the exact same format and syntax as NSLog, so it's super easy.) 19 | 20 | Lumberjack is powerful: 21 | One log statement can be sent to multiple loggers, meaning you can log to a file and the console simultaneously. Want more? Create your own loggers (it's easy) and send your log statements over the network. Or to a database or distributed file system. The sky is the limit. 22 | 23 | Lumberjack is flexible: 24 | Configure your logging however you want. Change log levels per file (perfect for debugging). Change log levels per logger (verbose console, but concise log file). Change log levels per xcode configuration (verbose debug, but concise release). Have your log statements compiled out of the release build. Customize the number of log levels for your application. Add your own fine-grained logging. Dynamically change log levels during runtime. Choose how & when you want your log files to be rolled. Upload your log files to a central server. Compress archived log files to save disk space... 25 | 26 | 27 | 28 | This framework is for you if: 29 | 30 | You're looking for a way to track down that impossible-to-reproduce bug that keeps popping up in the field. 31 | You're frustrated with the super short console log on the iPhone. 32 | You're looking to take your application to the next level in terms of support and stability. 33 | You're looking for an enterprise level logging solution for your application (Mac or iPhone). -------------------------------------------------------------------------------- /CocoaHttpServer/CocoaLumberjack/DDASLLogger.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | 4 | #import "DDLog.h" 5 | 6 | /** 7 | * Welcome to Cocoa Lumberjack! 8 | * 9 | * The project page has a wealth of documentation if you have any questions. 10 | * https://github.com/robbiehanson/CocoaLumberjack 11 | * 12 | * If you're new to the project you may wish to read the "Getting Started" wiki. 13 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/GettingStarted 14 | * 15 | * 16 | * This class provides a logger for the Apple System Log facility. 17 | * 18 | * As described in the "Getting Started" page, 19 | * the traditional NSLog() function directs it's output to two places: 20 | * 21 | * - Apple System Log 22 | * - StdErr (if stderr is a TTY) so log statements show up in Xcode console 23 | * 24 | * To duplicate NSLog() functionality you can simply add this logger and a tty logger. 25 | * However, if you instead choose to use file logging (for faster performance), 26 | * you may choose to use a file logger and a tty logger. 27 | **/ 28 | 29 | @interface DDASLLogger : DDAbstractLogger 30 | { 31 | aslclient client; 32 | } 33 | 34 | + (DDASLLogger *)sharedInstance; 35 | 36 | // Inherited from DDAbstractLogger 37 | 38 | // - (id )logFormatter; 39 | // - (void)setLogFormatter:(id )formatter; 40 | 41 | @end 42 | -------------------------------------------------------------------------------- /CocoaHttpServer/CocoaLumberjack/DDASLLogger.m: -------------------------------------------------------------------------------- 1 | #import "DDASLLogger.h" 2 | 3 | #import 4 | 5 | /** 6 | * Welcome to Cocoa Lumberjack! 7 | * 8 | * The project page has a wealth of documentation if you have any questions. 9 | * https://github.com/robbiehanson/CocoaLumberjack 10 | * 11 | * If you're new to the project you may wish to read the "Getting Started" wiki. 12 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/GettingStarted 13 | **/ 14 | 15 | #if ! __has_feature(objc_arc) 16 | #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). 17 | #endif 18 | 19 | 20 | @implementation DDASLLogger 21 | 22 | static DDASLLogger *sharedInstance; 23 | 24 | /** 25 | * The runtime sends initialize to each class in a program exactly one time just before the class, 26 | * or any class that inherits from it, is sent its first message from within the program. (Thus the 27 | * method may never be invoked if the class is not used.) The runtime sends the initialize message to 28 | * classes in a thread-safe manner. Superclasses receive this message before their subclasses. 29 | * 30 | * This method may also be called directly (assumably by accident), hence the safety mechanism. 31 | **/ 32 | + (void)initialize 33 | { 34 | static BOOL initialized = NO; 35 | if (!initialized) 36 | { 37 | initialized = YES; 38 | 39 | sharedInstance = [[DDASLLogger alloc] init]; 40 | } 41 | } 42 | 43 | + (DDASLLogger *)sharedInstance 44 | { 45 | return sharedInstance; 46 | } 47 | 48 | - (id)init 49 | { 50 | if (sharedInstance != nil) 51 | { 52 | return nil; 53 | } 54 | 55 | if ((self = [super init])) 56 | { 57 | // A default asl client is provided for the main thread, 58 | // but background threads need to create their own client. 59 | 60 | client = asl_open(NULL, "com.apple.console", 0); 61 | } 62 | return self; 63 | } 64 | 65 | - (void)logMessage:(DDLogMessage *)logMessage 66 | { 67 | NSString *logMsg = logMessage->logMsg; 68 | 69 | if (formatter) 70 | { 71 | logMsg = [formatter formatLogMessage:logMessage]; 72 | } 73 | 74 | if (logMsg) 75 | { 76 | const char *msg = [logMsg UTF8String]; 77 | 78 | int aslLogLevel; 79 | switch (logMessage->logFlag) 80 | { 81 | // Note: By default ASL will filter anything above level 5 (Notice). 82 | // So our mappings shouldn't go above that level. 83 | 84 | case LOG_FLAG_ERROR : aslLogLevel = ASL_LEVEL_CRIT; break; 85 | case LOG_FLAG_WARN : aslLogLevel = ASL_LEVEL_ERR; break; 86 | case LOG_FLAG_INFO : aslLogLevel = ASL_LEVEL_WARNING; break; 87 | default : aslLogLevel = ASL_LEVEL_NOTICE; break; 88 | } 89 | 90 | asl_log(client, NULL, aslLogLevel, "%s", msg); 91 | } 92 | } 93 | 94 | - (NSString *)loggerName 95 | { 96 | return @"cocoa.lumberjack.aslLogger"; 97 | } 98 | 99 | @end 100 | -------------------------------------------------------------------------------- /CocoaHttpServer/CocoaLumberjack/DDAbstractDatabaseLogger.h: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | #import "DDLog.h" 4 | 5 | /** 6 | * Welcome to Cocoa Lumberjack! 7 | * 8 | * The project page has a wealth of documentation if you have any questions. 9 | * https://github.com/robbiehanson/CocoaLumberjack 10 | * 11 | * If you're new to the project you may wish to read the "Getting Started" wiki. 12 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/GettingStarted 13 | * 14 | * 15 | * This class provides an abstract implementation of a database logger. 16 | * 17 | * That is, it provides the base implementation for a database logger to build atop of. 18 | * All that is needed for a concrete database logger is to extend this class 19 | * and override the methods in the implementation file that are prefixed with "db_". 20 | **/ 21 | 22 | @interface DDAbstractDatabaseLogger : DDAbstractLogger { 23 | @protected 24 | NSUInteger saveThreshold; 25 | NSTimeInterval saveInterval; 26 | NSTimeInterval maxAge; 27 | NSTimeInterval deleteInterval; 28 | BOOL deleteOnEverySave; 29 | 30 | BOOL saveTimerSuspended; 31 | NSUInteger unsavedCount; 32 | dispatch_time_t unsavedTime; 33 | dispatch_source_t saveTimer; 34 | dispatch_time_t lastDeleteTime; 35 | dispatch_source_t deleteTimer; 36 | } 37 | 38 | /** 39 | * Specifies how often to save the data to disk. 40 | * Since saving is an expensive operation (disk io) it is not done after every log statement. 41 | * These properties allow you to configure how/when the logger saves to disk. 42 | * 43 | * A save is done when either (whichever happens first): 44 | * 45 | * - The number of unsaved log entries reaches saveThreshold 46 | * - The amount of time since the oldest unsaved log entry was created reaches saveInterval 47 | * 48 | * You can optionally disable the saveThreshold by setting it to zero. 49 | * If you disable the saveThreshold you are entirely dependent on the saveInterval. 50 | * 51 | * You can optionally disable the saveInterval by setting it to zero (or a negative value). 52 | * If you disable the saveInterval you are entirely dependent on the saveThreshold. 53 | * 54 | * It's not wise to disable both saveThreshold and saveInterval. 55 | * 56 | * The default saveThreshold is 500. 57 | * The default saveInterval is 60 seconds. 58 | **/ 59 | @property (assign, readwrite) NSUInteger saveThreshold; 60 | @property (assign, readwrite) NSTimeInterval saveInterval; 61 | 62 | /** 63 | * It is likely you don't want the log entries to persist forever. 64 | * Doing so would allow the database to grow infinitely large over time. 65 | * 66 | * The maxAge property provides a way to specify how old a log statement can get 67 | * before it should get deleted from the database. 68 | * 69 | * The deleteInterval specifies how often to sweep for old log entries. 70 | * Since deleting is an expensive operation (disk io) is is done on a fixed interval. 71 | * 72 | * An alternative to the deleteInterval is the deleteOnEverySave option. 73 | * This specifies that old log entries should be deleted during every save operation. 74 | * 75 | * You can optionally disable the maxAge by setting it to zero (or a negative value). 76 | * If you disable the maxAge then old log statements are not deleted. 77 | * 78 | * You can optionally disable the deleteInterval by setting it to zero (or a negative value). 79 | * 80 | * If you disable both deleteInterval and deleteOnEverySave then old log statements are not deleted. 81 | * 82 | * It's not wise to enable both deleteInterval and deleteOnEverySave. 83 | * 84 | * The default maxAge is 7 days. 85 | * The default deleteInterval is 5 minutes. 86 | * The default deleteOnEverySave is NO. 87 | **/ 88 | @property (assign, readwrite) NSTimeInterval maxAge; 89 | @property (assign, readwrite) NSTimeInterval deleteInterval; 90 | @property (assign, readwrite) BOOL deleteOnEverySave; 91 | 92 | /** 93 | * Forces a save of any pending log entries (flushes log entries to disk). 94 | **/ 95 | - (void)savePendingLogEntries; 96 | 97 | /** 98 | * Removes any log entries that are older than maxAge. 99 | **/ 100 | - (void)deleteOldLogEntries; 101 | 102 | @end 103 | -------------------------------------------------------------------------------- /CocoaHttpServer/CocoaLumberjack/DDAbstractDatabaseLogger.m: -------------------------------------------------------------------------------- 1 | #import "DDAbstractDatabaseLogger.h" 2 | #import 3 | 4 | /** 5 | * Welcome to Cocoa Lumberjack! 6 | * 7 | * The project page has a wealth of documentation if you have any questions. 8 | * https://github.com/robbiehanson/CocoaLumberjack 9 | * 10 | * If you're new to the project you may wish to read the "Getting Started" wiki. 11 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/GettingStarted 12 | **/ 13 | 14 | #if ! __has_feature(objc_arc) 15 | #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). 16 | #endif 17 | 18 | @interface DDAbstractDatabaseLogger () 19 | - (void)destroySaveTimer; 20 | - (void)destroyDeleteTimer; 21 | @end 22 | 23 | #pragma mark - 24 | 25 | @implementation DDAbstractDatabaseLogger 26 | 27 | - (id)init 28 | { 29 | if ((self = [super init])) 30 | { 31 | saveThreshold = 500; 32 | saveInterval = 60; // 60 seconds 33 | maxAge = (60 * 60 * 24 * 7); // 7 days 34 | deleteInterval = (60 * 5); // 5 minutes 35 | } 36 | return self; 37 | } 38 | 39 | - (void)dealloc 40 | { 41 | [self destroySaveTimer]; 42 | [self destroyDeleteTimer]; 43 | 44 | } 45 | 46 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 47 | #pragma mark Override Me 48 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 49 | 50 | - (BOOL)db_log:(DDLogMessage *)logMessage 51 | { 52 | // Override me and add your implementation. 53 | // 54 | // Return YES if an item was added to the buffer. 55 | // Return NO if the logMessage was ignored. 56 | 57 | return NO; 58 | } 59 | 60 | - (void)db_save 61 | { 62 | // Override me and add your implementation. 63 | } 64 | 65 | - (void)db_delete 66 | { 67 | // Override me and add your implementation. 68 | } 69 | 70 | - (void)db_saveAndDelete 71 | { 72 | // Override me and add your implementation. 73 | } 74 | 75 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 76 | #pragma mark Private API 77 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 78 | 79 | - (void)performSaveAndSuspendSaveTimer 80 | { 81 | if (unsavedCount > 0) 82 | { 83 | if (deleteOnEverySave) 84 | [self db_saveAndDelete]; 85 | else 86 | [self db_save]; 87 | } 88 | 89 | unsavedCount = 0; 90 | unsavedTime = 0; 91 | 92 | if (saveTimer && !saveTimerSuspended) 93 | { 94 | dispatch_suspend(saveTimer); 95 | saveTimerSuspended = YES; 96 | } 97 | } 98 | 99 | - (void)performDelete 100 | { 101 | if (maxAge > 0.0) 102 | { 103 | [self db_delete]; 104 | 105 | lastDeleteTime = dispatch_time(DISPATCH_TIME_NOW, 0); 106 | } 107 | } 108 | 109 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 110 | #pragma mark Timers 111 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 112 | 113 | - (void)destroySaveTimer 114 | { 115 | if (saveTimer) 116 | { 117 | dispatch_source_cancel(saveTimer); 118 | if (saveTimerSuspended) 119 | { 120 | // Must resume a timer before releasing it (or it will crash) 121 | dispatch_resume(saveTimer); 122 | saveTimerSuspended = NO; 123 | } 124 | #if !OS_OBJECT_USE_OBJC 125 | dispatch_release(saveTimer); 126 | #endif 127 | saveTimer = NULL; 128 | } 129 | } 130 | 131 | - (void)updateAndResumeSaveTimer 132 | { 133 | if ((saveTimer != NULL) && (saveInterval > 0.0) && (unsavedTime > 0.0)) 134 | { 135 | uint64_t interval = (uint64_t)(saveInterval * NSEC_PER_SEC); 136 | dispatch_time_t startTime = dispatch_time(unsavedTime, interval); 137 | 138 | dispatch_source_set_timer(saveTimer, startTime, interval, 1.0); 139 | 140 | if (saveTimerSuspended) 141 | { 142 | dispatch_resume(saveTimer); 143 | saveTimerSuspended = NO; 144 | } 145 | } 146 | } 147 | 148 | - (void)createSuspendedSaveTimer 149 | { 150 | if ((saveTimer == NULL) && (saveInterval > 0.0)) 151 | { 152 | saveTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, loggerQueue); 153 | 154 | dispatch_source_set_event_handler(saveTimer, ^{ @autoreleasepool { 155 | 156 | [self performSaveAndSuspendSaveTimer]; 157 | 158 | }}); 159 | 160 | saveTimerSuspended = YES; 161 | } 162 | } 163 | 164 | - (void)destroyDeleteTimer 165 | { 166 | if (deleteTimer) 167 | { 168 | dispatch_source_cancel(deleteTimer); 169 | #if !OS_OBJECT_USE_OBJC 170 | dispatch_release(deleteTimer); 171 | #endif 172 | deleteTimer = NULL; 173 | } 174 | } 175 | 176 | - (void)updateDeleteTimer 177 | { 178 | if ((deleteTimer != NULL) && (deleteInterval > 0.0) && (maxAge > 0.0)) 179 | { 180 | uint64_t interval = (uint64_t)(deleteInterval * NSEC_PER_SEC); 181 | dispatch_time_t startTime; 182 | 183 | if (lastDeleteTime > 0) 184 | startTime = dispatch_time(lastDeleteTime, interval); 185 | else 186 | startTime = dispatch_time(DISPATCH_TIME_NOW, interval); 187 | 188 | dispatch_source_set_timer(deleteTimer, startTime, interval, 1.0); 189 | } 190 | } 191 | 192 | - (void)createAndStartDeleteTimer 193 | { 194 | if ((deleteTimer == NULL) && (deleteInterval > 0.0) && (maxAge > 0.0)) 195 | { 196 | deleteTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, loggerQueue); 197 | 198 | if (deleteTimer != NULL) { 199 | dispatch_source_set_event_handler(deleteTimer, ^{ @autoreleasepool { 200 | 201 | [self performDelete]; 202 | 203 | }}); 204 | 205 | [self updateDeleteTimer]; 206 | 207 | dispatch_resume(deleteTimer); 208 | } 209 | } 210 | } 211 | 212 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 213 | #pragma mark Configuration 214 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 215 | 216 | - (NSUInteger)saveThreshold 217 | { 218 | // The design of this method is taken from the DDAbstractLogger implementation. 219 | // For extensive documentation please refer to the DDAbstractLogger implementation. 220 | 221 | // Note: The internal implementation MUST access the colorsEnabled variable directly, 222 | // This method is designed explicitly for external access. 223 | // 224 | // Using "self." syntax to go through this method will cause immediate deadlock. 225 | // This is the intended result. Fix it by accessing the ivar directly. 226 | // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster. 227 | 228 | NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); 229 | NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax."); 230 | 231 | dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; 232 | 233 | __block NSUInteger result; 234 | 235 | dispatch_sync(globalLoggingQueue, ^{ 236 | dispatch_sync(loggerQueue, ^{ 237 | result = saveThreshold; 238 | }); 239 | }); 240 | 241 | return result; 242 | } 243 | 244 | - (void)setSaveThreshold:(NSUInteger)threshold 245 | { 246 | dispatch_block_t block = ^{ @autoreleasepool { 247 | 248 | if (saveThreshold != threshold) 249 | { 250 | saveThreshold = threshold; 251 | 252 | // Since the saveThreshold has changed, 253 | // we check to see if the current unsavedCount has surpassed the new threshold. 254 | // 255 | // If it has, we immediately save the log. 256 | 257 | if ((unsavedCount >= saveThreshold) && (saveThreshold > 0)) 258 | { 259 | [self performSaveAndSuspendSaveTimer]; 260 | } 261 | } 262 | }}; 263 | 264 | // The design of the setter logic below is taken from the DDAbstractLogger implementation. 265 | // For documentation please refer to the DDAbstractLogger implementation. 266 | 267 | if ([self isOnInternalLoggerQueue]) 268 | { 269 | block(); 270 | } 271 | else 272 | { 273 | dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; 274 | NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); 275 | 276 | dispatch_async(globalLoggingQueue, ^{ 277 | dispatch_async(loggerQueue, block); 278 | }); 279 | } 280 | } 281 | 282 | - (NSTimeInterval)saveInterval 283 | { 284 | // The design of this method is taken from the DDAbstractLogger implementation. 285 | // For extensive documentation please refer to the DDAbstractLogger implementation. 286 | 287 | // Note: The internal implementation MUST access the colorsEnabled variable directly, 288 | // This method is designed explicitly for external access. 289 | // 290 | // Using "self." syntax to go through this method will cause immediate deadlock. 291 | // This is the intended result. Fix it by accessing the ivar directly. 292 | // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster. 293 | 294 | NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); 295 | NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax."); 296 | 297 | dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; 298 | 299 | __block NSTimeInterval result; 300 | 301 | dispatch_sync(globalLoggingQueue, ^{ 302 | dispatch_sync(loggerQueue, ^{ 303 | result = saveInterval; 304 | }); 305 | }); 306 | 307 | return result; 308 | } 309 | 310 | - (void)setSaveInterval:(NSTimeInterval)interval 311 | { 312 | dispatch_block_t block = ^{ @autoreleasepool { 313 | 314 | // C99 recommended floating point comparison macro 315 | // Read: isLessThanOrGreaterThan(floatA, floatB) 316 | 317 | if (/* saveInterval != interval */ islessgreater(saveInterval, interval)) 318 | { 319 | saveInterval = interval; 320 | 321 | // There are several cases we need to handle here. 322 | // 323 | // 1. If the saveInterval was previously enabled and it just got disabled, 324 | // then we need to stop the saveTimer. (And we might as well release it.) 325 | // 326 | // 2. If the saveInterval was previously disabled and it just got enabled, 327 | // then we need to setup the saveTimer. (Plus we might need to do an immediate save.) 328 | // 329 | // 3. If the saveInterval increased, then we need to reset the timer so that it fires at the later date. 330 | // 331 | // 4. If the saveInterval decreased, then we need to reset the timer so that it fires at an earlier date. 332 | // (Plus we might need to do an immediate save.) 333 | 334 | if (saveInterval > 0.0) 335 | { 336 | if (saveTimer == NULL) 337 | { 338 | // Handles #2 339 | // 340 | // Since the saveTimer uses the unsavedTime to calculate it's first fireDate, 341 | // if a save is needed the timer will fire immediately. 342 | 343 | [self createSuspendedSaveTimer]; 344 | [self updateAndResumeSaveTimer]; 345 | } 346 | else 347 | { 348 | // Handles #3 349 | // Handles #4 350 | // 351 | // Since the saveTimer uses the unsavedTime to calculate it's first fireDate, 352 | // if a save is needed the timer will fire immediately. 353 | 354 | [self updateAndResumeSaveTimer]; 355 | } 356 | } 357 | else if (saveTimer) 358 | { 359 | // Handles #1 360 | 361 | [self destroySaveTimer]; 362 | } 363 | } 364 | }}; 365 | 366 | // The design of the setter logic below is taken from the DDAbstractLogger implementation. 367 | // For documentation please refer to the DDAbstractLogger implementation. 368 | 369 | if ([self isOnInternalLoggerQueue]) 370 | { 371 | block(); 372 | } 373 | else 374 | { 375 | dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; 376 | NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); 377 | 378 | dispatch_async(globalLoggingQueue, ^{ 379 | dispatch_async(loggerQueue, block); 380 | }); 381 | } 382 | } 383 | 384 | - (NSTimeInterval)maxAge 385 | { 386 | // The design of this method is taken from the DDAbstractLogger implementation. 387 | // For extensive documentation please refer to the DDAbstractLogger implementation. 388 | 389 | // Note: The internal implementation MUST access the colorsEnabled variable directly, 390 | // This method is designed explicitly for external access. 391 | // 392 | // Using "self." syntax to go through this method will cause immediate deadlock. 393 | // This is the intended result. Fix it by accessing the ivar directly. 394 | // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster. 395 | 396 | NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); 397 | NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax."); 398 | 399 | dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; 400 | 401 | __block NSTimeInterval result; 402 | 403 | dispatch_sync(globalLoggingQueue, ^{ 404 | dispatch_sync(loggerQueue, ^{ 405 | result = maxAge; 406 | }); 407 | }); 408 | 409 | return result; 410 | } 411 | 412 | - (void)setMaxAge:(NSTimeInterval)interval 413 | { 414 | dispatch_block_t block = ^{ @autoreleasepool { 415 | 416 | // C99 recommended floating point comparison macro 417 | // Read: isLessThanOrGreaterThan(floatA, floatB) 418 | 419 | if (/* maxAge != interval */ islessgreater(maxAge, interval)) 420 | { 421 | NSTimeInterval oldMaxAge = maxAge; 422 | NSTimeInterval newMaxAge = interval; 423 | 424 | maxAge = interval; 425 | 426 | // There are several cases we need to handle here. 427 | // 428 | // 1. If the maxAge was previously enabled and it just got disabled, 429 | // then we need to stop the deleteTimer. (And we might as well release it.) 430 | // 431 | // 2. If the maxAge was previously disabled and it just got enabled, 432 | // then we need to setup the deleteTimer. (Plus we might need to do an immediate delete.) 433 | // 434 | // 3. If the maxAge was increased, 435 | // then we don't need to do anything. 436 | // 437 | // 4. If the maxAge was decreased, 438 | // then we should do an immediate delete. 439 | 440 | BOOL shouldDeleteNow = NO; 441 | 442 | if (oldMaxAge > 0.0) 443 | { 444 | if (newMaxAge <= 0.0) 445 | { 446 | // Handles #1 447 | 448 | [self destroyDeleteTimer]; 449 | } 450 | else if (oldMaxAge > newMaxAge) 451 | { 452 | // Handles #4 453 | shouldDeleteNow = YES; 454 | } 455 | } 456 | else if (newMaxAge > 0.0) 457 | { 458 | // Handles #2 459 | shouldDeleteNow = YES; 460 | } 461 | 462 | if (shouldDeleteNow) 463 | { 464 | [self performDelete]; 465 | 466 | if (deleteTimer) 467 | [self updateDeleteTimer]; 468 | else 469 | [self createAndStartDeleteTimer]; 470 | } 471 | } 472 | }}; 473 | 474 | // The design of the setter logic below is taken from the DDAbstractLogger implementation. 475 | // For documentation please refer to the DDAbstractLogger implementation. 476 | 477 | if ([self isOnInternalLoggerQueue]) 478 | { 479 | block(); 480 | } 481 | else 482 | { 483 | dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; 484 | NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); 485 | 486 | dispatch_async(globalLoggingQueue, ^{ 487 | dispatch_async(loggerQueue, block); 488 | }); 489 | } 490 | } 491 | 492 | - (NSTimeInterval)deleteInterval 493 | { 494 | // The design of this method is taken from the DDAbstractLogger implementation. 495 | // For extensive documentation please refer to the DDAbstractLogger implementation. 496 | 497 | // Note: The internal implementation MUST access the colorsEnabled variable directly, 498 | // This method is designed explicitly for external access. 499 | // 500 | // Using "self." syntax to go through this method will cause immediate deadlock. 501 | // This is the intended result. Fix it by accessing the ivar directly. 502 | // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster. 503 | 504 | NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); 505 | NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax."); 506 | 507 | dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; 508 | 509 | __block NSTimeInterval result; 510 | 511 | dispatch_sync(globalLoggingQueue, ^{ 512 | dispatch_sync(loggerQueue, ^{ 513 | result = deleteInterval; 514 | }); 515 | }); 516 | 517 | return result; 518 | } 519 | 520 | - (void)setDeleteInterval:(NSTimeInterval)interval 521 | { 522 | dispatch_block_t block = ^{ @autoreleasepool { 523 | 524 | // C99 recommended floating point comparison macro 525 | // Read: isLessThanOrGreaterThan(floatA, floatB) 526 | 527 | if (/* deleteInterval != interval */ islessgreater(deleteInterval, interval)) 528 | { 529 | deleteInterval = interval; 530 | 531 | // There are several cases we need to handle here. 532 | // 533 | // 1. If the deleteInterval was previously enabled and it just got disabled, 534 | // then we need to stop the deleteTimer. (And we might as well release it.) 535 | // 536 | // 2. If the deleteInterval was previously disabled and it just got enabled, 537 | // then we need to setup the deleteTimer. (Plus we might need to do an immediate delete.) 538 | // 539 | // 3. If the deleteInterval increased, then we need to reset the timer so that it fires at the later date. 540 | // 541 | // 4. If the deleteInterval decreased, then we need to reset the timer so that it fires at an earlier date. 542 | // (Plus we might need to do an immediate delete.) 543 | 544 | if (deleteInterval > 0.0) 545 | { 546 | if (deleteTimer == NULL) 547 | { 548 | // Handles #2 549 | // 550 | // Since the deleteTimer uses the lastDeleteTime to calculate it's first fireDate, 551 | // if a delete is needed the timer will fire immediately. 552 | 553 | [self createAndStartDeleteTimer]; 554 | } 555 | else 556 | { 557 | // Handles #3 558 | // Handles #4 559 | // 560 | // Since the deleteTimer uses the lastDeleteTime to calculate it's first fireDate, 561 | // if a save is needed the timer will fire immediately. 562 | 563 | [self updateDeleteTimer]; 564 | } 565 | } 566 | else if (deleteTimer) 567 | { 568 | // Handles #1 569 | 570 | [self destroyDeleteTimer]; 571 | } 572 | } 573 | }}; 574 | 575 | // The design of the setter logic below is taken from the DDAbstractLogger implementation. 576 | // For documentation please refer to the DDAbstractLogger implementation. 577 | 578 | if ([self isOnInternalLoggerQueue]) 579 | { 580 | block(); 581 | } 582 | else 583 | { 584 | dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; 585 | NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); 586 | 587 | dispatch_async(globalLoggingQueue, ^{ 588 | dispatch_async(loggerQueue, block); 589 | }); 590 | } 591 | } 592 | 593 | - (BOOL)deleteOnEverySave 594 | { 595 | // The design of this method is taken from the DDAbstractLogger implementation. 596 | // For extensive documentation please refer to the DDAbstractLogger implementation. 597 | 598 | // Note: The internal implementation MUST access the colorsEnabled variable directly, 599 | // This method is designed explicitly for external access. 600 | // 601 | // Using "self." syntax to go through this method will cause immediate deadlock. 602 | // This is the intended result. Fix it by accessing the ivar directly. 603 | // Great strides have been take to ensure this is safe to do. Plus it's MUCH faster. 604 | 605 | NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); 606 | NSAssert(![self isOnInternalLoggerQueue], @"MUST access ivar directly, NOT via self.* syntax."); 607 | 608 | dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; 609 | 610 | __block BOOL result; 611 | 612 | dispatch_sync(globalLoggingQueue, ^{ 613 | dispatch_sync(loggerQueue, ^{ 614 | result = deleteOnEverySave; 615 | }); 616 | }); 617 | 618 | return result; 619 | } 620 | 621 | - (void)setDeleteOnEverySave:(BOOL)flag 622 | { 623 | dispatch_block_t block = ^{ 624 | 625 | deleteOnEverySave = flag; 626 | }; 627 | 628 | // The design of the setter logic below is taken from the DDAbstractLogger implementation. 629 | // For documentation please refer to the DDAbstractLogger implementation. 630 | 631 | if ([self isOnInternalLoggerQueue]) 632 | { 633 | block(); 634 | } 635 | else 636 | { 637 | dispatch_queue_t globalLoggingQueue = [DDLog loggingQueue]; 638 | NSAssert(![self isOnGlobalLoggingQueue], @"Core architecture requirement failure"); 639 | 640 | dispatch_async(globalLoggingQueue, ^{ 641 | dispatch_async(loggerQueue, block); 642 | }); 643 | } 644 | } 645 | 646 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 647 | #pragma mark Public API 648 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 649 | 650 | - (void)savePendingLogEntries 651 | { 652 | dispatch_block_t block = ^{ @autoreleasepool { 653 | 654 | [self performSaveAndSuspendSaveTimer]; 655 | }}; 656 | 657 | if ([self isOnInternalLoggerQueue]) 658 | block(); 659 | else 660 | dispatch_async(loggerQueue, block); 661 | } 662 | 663 | - (void)deleteOldLogEntries 664 | { 665 | dispatch_block_t block = ^{ @autoreleasepool { 666 | 667 | [self performDelete]; 668 | }}; 669 | 670 | if ([self isOnInternalLoggerQueue]) 671 | block(); 672 | else 673 | dispatch_async(loggerQueue, block); 674 | } 675 | 676 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 677 | #pragma mark DDLogger 678 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 679 | 680 | - (void)didAddLogger 681 | { 682 | // If you override me be sure to invoke [super didAddLogger]; 683 | 684 | [self createSuspendedSaveTimer]; 685 | 686 | [self createAndStartDeleteTimer]; 687 | } 688 | 689 | - (void)willRemoveLogger 690 | { 691 | // If you override me be sure to invoke [super willRemoveLogger]; 692 | 693 | [self performSaveAndSuspendSaveTimer]; 694 | 695 | [self destroySaveTimer]; 696 | [self destroyDeleteTimer]; 697 | } 698 | 699 | - (void)logMessage:(DDLogMessage *)logMessage 700 | { 701 | if ([self db_log:logMessage]) 702 | { 703 | BOOL firstUnsavedEntry = (++unsavedCount == 1); 704 | 705 | if ((unsavedCount >= saveThreshold) && (saveThreshold > 0)) 706 | { 707 | [self performSaveAndSuspendSaveTimer]; 708 | } 709 | else if (firstUnsavedEntry) 710 | { 711 | unsavedTime = dispatch_time(DISPATCH_TIME_NOW, 0); 712 | [self updateAndResumeSaveTimer]; 713 | } 714 | } 715 | } 716 | 717 | - (void)flush 718 | { 719 | // This method is invoked by DDLog's flushLog method. 720 | // 721 | // It is called automatically when the application quits, 722 | // or if the developer invokes DDLog's flushLog method prior to crashing or something. 723 | 724 | [self performSaveAndSuspendSaveTimer]; 725 | } 726 | 727 | @end 728 | -------------------------------------------------------------------------------- /CocoaHttpServer/CocoaLumberjack/DDFileLogger.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import "DDLog.h" 3 | 4 | @class DDLogFileInfo; 5 | 6 | /** 7 | * Welcome to Cocoa Lumberjack! 8 | * 9 | * The project page has a wealth of documentation if you have any questions. 10 | * https://github.com/robbiehanson/CocoaLumberjack 11 | * 12 | * If you're new to the project you may wish to read the "Getting Started" wiki. 13 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/GettingStarted 14 | * 15 | * 16 | * This class provides a logger to write log statements to a file. 17 | **/ 18 | 19 | 20 | // Default configuration and safety/sanity values. 21 | // 22 | // maximumFileSize -> DEFAULT_LOG_MAX_FILE_SIZE 23 | // rollingFrequency -> DEFAULT_LOG_ROLLING_FREQUENCY 24 | // maximumNumberOfLogFiles -> DEFAULT_LOG_MAX_NUM_LOG_FILES 25 | // 26 | // You should carefully consider the proper configuration values for your application. 27 | 28 | #define DEFAULT_LOG_MAX_FILE_SIZE (1024 * 1024) // 1 MB 29 | #define DEFAULT_LOG_ROLLING_FREQUENCY (60 * 60 * 24) // 24 Hours 30 | #define DEFAULT_LOG_MAX_NUM_LOG_FILES (5) // 5 Files 31 | 32 | 33 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 34 | #pragma mark - 35 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 36 | 37 | // The LogFileManager protocol is designed to allow you to control all aspects of your log files. 38 | // 39 | // The primary purpose of this is to allow you to do something with the log files after they have been rolled. 40 | // Perhaps you want to compress them to save disk space. 41 | // Perhaps you want to upload them to an FTP server. 42 | // Perhaps you want to run some analytics on the file. 43 | // 44 | // A default LogFileManager is, of course, provided. 45 | // The default LogFileManager simply deletes old log files according to the maximumNumberOfLogFiles property. 46 | // 47 | // This protocol provides various methods to fetch the list of log files. 48 | // 49 | // There are two variants: sorted and unsorted. 50 | // If sorting is not necessary, the unsorted variant is obviously faster. 51 | // The sorted variant will return an array sorted by when the log files were created, 52 | // with the most recently created log file at index 0, and the oldest log file at the end of the array. 53 | // 54 | // You can fetch only the log file paths (full path including name), log file names (name only), 55 | // or an array of DDLogFileInfo objects. 56 | // The DDLogFileInfo class is documented below, and provides a handy wrapper that 57 | // gives you easy access to various file attributes such as the creation date or the file size. 58 | 59 | @protocol DDLogFileManager 60 | @required 61 | 62 | // Public properties 63 | 64 | /** 65 | * The maximum number of archived log files to keep on disk. 66 | * For example, if this property is set to 3, 67 | * then the LogFileManager will only keep 3 archived log files (plus the current active log file) on disk. 68 | * Once the active log file is rolled/archived, then the oldest of the existing 3 rolled/archived log files is deleted. 69 | * 70 | * You may optionally disable deleting old/rolled/archived log files by setting this property to zero. 71 | **/ 72 | @property (readwrite, assign) NSUInteger maximumNumberOfLogFiles; 73 | 74 | // Public methods 75 | 76 | - (NSString *)logsDirectory; 77 | 78 | - (NSArray *)unsortedLogFilePaths; 79 | - (NSArray *)unsortedLogFileNames; 80 | - (NSArray *)unsortedLogFileInfos; 81 | 82 | - (NSArray *)sortedLogFilePaths; 83 | - (NSArray *)sortedLogFileNames; 84 | - (NSArray *)sortedLogFileInfos; 85 | 86 | // Private methods (only to be used by DDFileLogger) 87 | 88 | - (NSString *)createNewLogFile; 89 | 90 | @optional 91 | 92 | // Notifications from DDFileLogger 93 | 94 | - (void)didArchiveLogFile:(NSString *)logFilePath; 95 | - (void)didRollAndArchiveLogFile:(NSString *)logFilePath; 96 | 97 | @end 98 | 99 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 100 | #pragma mark - 101 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 102 | 103 | /** 104 | * Default log file manager. 105 | * 106 | * All log files are placed inside the logsDirectory. 107 | * If a specific logsDirectory isn't specified, the default directory is used. 108 | * On Mac, this is in ~/Library/Logs/. 109 | * On iPhone, this is in ~/Library/Caches/Logs. 110 | * 111 | * Log files are named "log-.txt", 112 | * where uuid is a 6 character hexadecimal consisting of the set [0123456789ABCDEF]. 113 | * 114 | * Archived log files are automatically deleted according to the maximumNumberOfLogFiles property. 115 | **/ 116 | @interface DDLogFileManagerDefault : NSObject 117 | { 118 | NSUInteger maximumNumberOfLogFiles; 119 | NSString *_logsDirectory; 120 | } 121 | 122 | - (id)init; 123 | - (id)initWithLogsDirectory:(NSString *)logsDirectory; 124 | 125 | /* Inherited from DDLogFileManager protocol: 126 | 127 | @property (readwrite, assign) NSUInteger maximumNumberOfLogFiles; 128 | 129 | - (NSString *)logsDirectory; 130 | 131 | - (NSArray *)unsortedLogFilePaths; 132 | - (NSArray *)unsortedLogFileNames; 133 | - (NSArray *)unsortedLogFileInfos; 134 | 135 | - (NSArray *)sortedLogFilePaths; 136 | - (NSArray *)sortedLogFileNames; 137 | - (NSArray *)sortedLogFileInfos; 138 | 139 | */ 140 | 141 | @end 142 | 143 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 144 | #pragma mark - 145 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 146 | 147 | /** 148 | * Most users will want file log messages to be prepended with the date and time. 149 | * Rather than forcing the majority of users to write their own formatter, 150 | * we will supply a logical default formatter. 151 | * Users can easily replace this formatter with their own by invoking the setLogFormatter method. 152 | * It can also be removed by calling setLogFormatter, and passing a nil parameter. 153 | * 154 | * In addition to the convenience of having a logical default formatter, 155 | * it will also provide a template that makes it easy for developers to copy and change. 156 | **/ 157 | @interface DDLogFileFormatterDefault : NSObject 158 | { 159 | NSDateFormatter *dateFormatter; 160 | } 161 | 162 | - (id)init; 163 | - (id)initWithDateFormatter:(NSDateFormatter *)dateFormatter; 164 | 165 | @end 166 | 167 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 168 | #pragma mark - 169 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 170 | 171 | @interface DDFileLogger : DDAbstractLogger 172 | { 173 | __strong id logFileManager; 174 | 175 | DDLogFileInfo *currentLogFileInfo; 176 | NSFileHandle *currentLogFileHandle; 177 | 178 | dispatch_source_t rollingTimer; 179 | 180 | unsigned long long maximumFileSize; 181 | NSTimeInterval rollingFrequency; 182 | } 183 | 184 | - (id)init; 185 | - (id)initWithLogFileManager:(id )logFileManager; 186 | 187 | /** 188 | * Log File Rolling: 189 | * 190 | * maximumFileSize: 191 | * The approximate maximum size to allow log files to grow. 192 | * If a log file is larger than this value after a log statement is appended, 193 | * then the log file is rolled. 194 | * 195 | * rollingFrequency 196 | * How often to roll the log file. 197 | * The frequency is given as an NSTimeInterval, which is a double that specifies the interval in seconds. 198 | * Once the log file gets to be this old, it is rolled. 199 | * 200 | * Both the maximumFileSize and the rollingFrequency are used to manage rolling. 201 | * Whichever occurs first will cause the log file to be rolled. 202 | * 203 | * For example: 204 | * The rollingFrequency is 24 hours, 205 | * but the log file surpasses the maximumFileSize after only 20 hours. 206 | * The log file will be rolled at that 20 hour mark. 207 | * A new log file will be created, and the 24 hour timer will be restarted. 208 | * 209 | * You may optionally disable rolling due to filesize by setting maximumFileSize to zero. 210 | * If you do so, rolling is based solely on rollingFrequency. 211 | * 212 | * You may optionally disable rolling due to time by setting rollingFrequency to zero (or any non-positive number). 213 | * If you do so, rolling is based solely on maximumFileSize. 214 | * 215 | * If you disable both maximumFileSize and rollingFrequency, then the log file won't ever be rolled. 216 | * This is strongly discouraged. 217 | **/ 218 | @property (readwrite, assign) unsigned long long maximumFileSize; 219 | @property (readwrite, assign) NSTimeInterval rollingFrequency; 220 | 221 | /** 222 | * The DDLogFileManager instance can be used to retrieve the list of log files, 223 | * and configure the maximum number of archived log files to keep. 224 | * 225 | * @see DDLogFileManager.maximumNumberOfLogFiles 226 | **/ 227 | @property (strong, nonatomic, readonly) id logFileManager; 228 | 229 | 230 | // You can optionally force the current log file to be rolled with this method. 231 | 232 | - (void)rollLogFile; 233 | 234 | // Inherited from DDAbstractLogger 235 | 236 | // - (id )logFormatter; 237 | // - (void)setLogFormatter:(id )formatter; 238 | 239 | @end 240 | 241 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 242 | #pragma mark - 243 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 244 | 245 | /** 246 | * DDLogFileInfo is a simple class that provides access to various file attributes. 247 | * It provides good performance as it only fetches the information if requested, 248 | * and it caches the information to prevent duplicate fetches. 249 | * 250 | * It was designed to provide quick snapshots of the current state of log files, 251 | * and to help sort log files in an array. 252 | * 253 | * This class does not monitor the files, or update it's cached attribute values if the file changes on disk. 254 | * This is not what the class was designed for. 255 | * 256 | * If you absolutely must get updated values, 257 | * you can invoke the reset method which will clear the cache. 258 | **/ 259 | @interface DDLogFileInfo : NSObject 260 | { 261 | __strong NSString *filePath; 262 | __strong NSString *fileName; 263 | 264 | __strong NSDictionary *fileAttributes; 265 | 266 | __strong NSDate *creationDate; 267 | __strong NSDate *modificationDate; 268 | 269 | unsigned long long fileSize; 270 | } 271 | 272 | @property (strong, nonatomic, readonly) NSString *filePath; 273 | @property (strong, nonatomic, readonly) NSString *fileName; 274 | 275 | @property (strong, nonatomic, readonly) NSDictionary *fileAttributes; 276 | 277 | @property (strong, nonatomic, readonly) NSDate *creationDate; 278 | @property (strong, nonatomic, readonly) NSDate *modificationDate; 279 | 280 | @property (nonatomic, readonly) unsigned long long fileSize; 281 | 282 | @property (nonatomic, readonly) NSTimeInterval age; 283 | 284 | @property (nonatomic, readwrite) BOOL isArchived; 285 | 286 | + (id)logFileWithPath:(NSString *)filePath; 287 | 288 | - (id)initWithFilePath:(NSString *)filePath; 289 | 290 | - (void)reset; 291 | - (void)renameFile:(NSString *)newFileName; 292 | 293 | #if TARGET_IPHONE_SIMULATOR 294 | 295 | // So here's the situation. 296 | // Extended attributes are perfect for what we're trying to do here (marking files as archived). 297 | // This is exactly what extended attributes were designed for. 298 | // 299 | // But Apple screws us over on the simulator. 300 | // Everytime you build-and-go, they copy the application into a new folder on the hard drive, 301 | // and as part of the process they strip extended attributes from our log files. 302 | // Normally, a copy of a file preserves extended attributes. 303 | // So obviously Apple has gone to great lengths to piss us off. 304 | // 305 | // Thus we use a slightly different tactic for marking log files as archived in the simulator. 306 | // That way it "just works" and there's no confusion when testing. 307 | // 308 | // The difference in method names is indicative of the difference in functionality. 309 | // On the simulator we add an attribute by appending a filename extension. 310 | // 311 | // For example: 312 | // log-ABC123.txt -> log-ABC123.archived.txt 313 | 314 | - (BOOL)hasExtensionAttributeWithName:(NSString *)attrName; 315 | 316 | - (void)addExtensionAttributeWithName:(NSString *)attrName; 317 | - (void)removeExtensionAttributeWithName:(NSString *)attrName; 318 | 319 | #else 320 | 321 | // Normal use of extended attributes used everywhere else, 322 | // such as on Macs and on iPhone devices. 323 | 324 | - (BOOL)hasExtendedAttributeWithName:(NSString *)attrName; 325 | 326 | - (void)addExtendedAttributeWithName:(NSString *)attrName; 327 | - (void)removeExtendedAttributeWithName:(NSString *)attrName; 328 | 329 | #endif 330 | 331 | - (NSComparisonResult)reverseCompareByCreationDate:(DDLogFileInfo *)another; 332 | - (NSComparisonResult)reverseCompareByModificationDate:(DDLogFileInfo *)another; 333 | 334 | @end 335 | -------------------------------------------------------------------------------- /CocoaHttpServer/CocoaLumberjack/DDTTYLogger.h: -------------------------------------------------------------------------------- 1 | #import 2 | #if TARGET_OS_IPHONE 3 | #import 4 | #else 5 | #import 6 | #endif 7 | 8 | #import "DDLog.h" 9 | 10 | /** 11 | * Welcome to Cocoa Lumberjack! 12 | * 13 | * The project page has a wealth of documentation if you have any questions. 14 | * https://github.com/robbiehanson/CocoaLumberjack 15 | * 16 | * If you're new to the project you may wish to read the "Getting Started" wiki. 17 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/GettingStarted 18 | * 19 | * 20 | * This class provides a logger for Terminal output or Xcode console output, 21 | * depending on where you are running your code. 22 | * 23 | * As described in the "Getting Started" page, 24 | * the traditional NSLog() function directs it's output to two places: 25 | * 26 | * - Apple System Log (so it shows up in Console.app) 27 | * - StdErr (if stderr is a TTY, so log statements show up in Xcode console) 28 | * 29 | * To duplicate NSLog() functionality you can simply add this logger and an asl logger. 30 | * However, if you instead choose to use file logging (for faster performance), 31 | * you may choose to use only a file logger and a tty logger. 32 | **/ 33 | 34 | @interface DDTTYLogger : DDAbstractLogger 35 | { 36 | NSCalendar *calendar; 37 | NSUInteger calendarUnitFlags; 38 | 39 | NSString *appName; 40 | char *app; 41 | size_t appLen; 42 | 43 | NSString *processID; 44 | char *pid; 45 | size_t pidLen; 46 | 47 | BOOL colorsEnabled; 48 | NSMutableArray *colorProfilesArray; 49 | NSMutableDictionary *colorProfilesDict; 50 | } 51 | 52 | + (DDTTYLogger *)sharedInstance; 53 | 54 | /* Inherited from the DDLogger protocol: 55 | * 56 | * Formatters may optionally be added to any logger. 57 | * 58 | * If no formatter is set, the logger simply logs the message as it is given in logMessage, 59 | * or it may use its own built in formatting style. 60 | * 61 | * More information about formatters can be found here: 62 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/CustomFormatters 63 | * 64 | * The actual implementation of these methods is inherited from DDAbstractLogger. 65 | 66 | - (id )logFormatter; 67 | - (void)setLogFormatter:(id )formatter; 68 | 69 | */ 70 | 71 | /** 72 | * Want to use different colors for different log levels? 73 | * Enable this property. 74 | * 75 | * If you run the application via the Terminal (not Xcode), 76 | * the logger will map colors to xterm-256color or xterm-color (if available). 77 | * 78 | * Xcode does NOT natively support colors in the Xcode debugging console. 79 | * You'll need to install the XcodeColors plugin to see colors in the Xcode console. 80 | * https://github.com/robbiehanson/XcodeColors 81 | * 82 | * The default value if NO. 83 | **/ 84 | @property (readwrite, assign) BOOL colorsEnabled; 85 | 86 | /** 87 | * The default color set (foregroundColor, backgroundColor) is: 88 | * 89 | * - LOG_FLAG_ERROR = (red, nil) 90 | * - LOG_FLAG_WARN = (orange, nil) 91 | * 92 | * You can customize the colors however you see fit. 93 | * Please note that you are passing a flag, NOT a level. 94 | * 95 | * GOOD : [ttyLogger setForegroundColor:pink backgroundColor:nil forFlag:LOG_FLAG_INFO]; // <- Good :) 96 | * BAD : [ttyLogger setForegroundColor:pink backgroundColor:nil forFlag:LOG_LEVEL_INFO]; // <- BAD! :( 97 | * 98 | * LOG_FLAG_INFO = 0...00100 99 | * LOG_LEVEL_INFO = 0...00111 <- Would match LOG_FLAG_INFO and LOG_FLAG_WARN and LOG_FLAG_ERROR 100 | * 101 | * If you run the application within Xcode, then the XcodeColors plugin is required. 102 | * 103 | * If you run the application from a shell, then DDTTYLogger will automatically map the given color to 104 | * the closest available color. (xterm-256color or xterm-color which have 256 and 16 supported colors respectively.) 105 | * 106 | * This method invokes setForegroundColor:backgroundColor:forFlag:context: and passes the default context (0). 107 | **/ 108 | #if TARGET_OS_IPHONE 109 | - (void)setForegroundColor:(UIColor *)txtColor backgroundColor:(UIColor *)bgColor forFlag:(int)mask; 110 | #else 111 | - (void)setForegroundColor:(NSColor *)txtColor backgroundColor:(NSColor *)bgColor forFlag:(int)mask; 112 | #endif 113 | 114 | /** 115 | * Just like setForegroundColor:backgroundColor:flag, but allows you to specify a particular logging context. 116 | * 117 | * A logging context is often used to identify log messages coming from a 3rd party framework, 118 | * although logging context's can be used for many different functions. 119 | * 120 | * Logging context's are explained in further detail here: 121 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/CustomContext 122 | **/ 123 | #if TARGET_OS_IPHONE 124 | - (void)setForegroundColor:(UIColor *)txtColor backgroundColor:(UIColor *)bgColor forFlag:(int)mask context:(int)ctxt; 125 | #else 126 | - (void)setForegroundColor:(NSColor *)txtColor backgroundColor:(NSColor *)bgColor forFlag:(int)mask context:(int)ctxt; 127 | #endif 128 | 129 | /** 130 | * Similar to the methods above, but allows you to map DDLogMessage->tag to a particular color profile. 131 | * For example, you could do something like this: 132 | * 133 | * static NSString *const PurpleTag = @"PurpleTag"; 134 | * 135 | * #define DDLogPurple(frmt, ...) LOG_OBJC_TAG_MACRO(NO, 0, 0, 0, PurpleTag, frmt, ##__VA_ARGS__) 136 | * 137 | * And then in your applicationDidFinishLaunching, or wherever you configure Lumberjack: 138 | * 139 | * #if TARGET_OS_IPHONE 140 | * UIColor *purple = [UIColor colorWithRed:(64/255.0) green:(0/255.0) blue:(128/255.0) alpha:1.0]; 141 | * #else 142 | * NSColor *purple = [NSColor colorWithCalibratedRed:(64/255.0) green:(0/255.0) blue:(128/255.0) alpha:1.0]; 143 | * 144 | * [[DDTTYLogger sharedInstance] setForegroundColor:purple backgroundColor:nil forTag:PurpleTag]; 145 | * [DDLog addLogger:[DDTTYLogger sharedInstance]]; 146 | * 147 | * This would essentially give you a straight NSLog replacement that prints in purple: 148 | * 149 | * DDLogPurple(@"I'm a purple log message!"); 150 | **/ 151 | #if TARGET_OS_IPHONE 152 | - (void)setForegroundColor:(UIColor *)txtColor backgroundColor:(UIColor *)bgColor forTag:(id )tag; 153 | #else 154 | - (void)setForegroundColor:(NSColor *)txtColor backgroundColor:(NSColor *)bgColor forTag:(id )tag; 155 | #endif 156 | 157 | /** 158 | * Clearing color profiles. 159 | **/ 160 | - (void)clearColorsForFlag:(int)mask; 161 | - (void)clearColorsForFlag:(int)mask context:(int)context; 162 | - (void)clearColorsForTag:(id )tag; 163 | - (void)clearColorsForAllFlags; 164 | - (void)clearColorsForAllTags; 165 | - (void)clearAllColors; 166 | 167 | @end 168 | -------------------------------------------------------------------------------- /CocoaHttpServer/CocoaLumberjack/Extensions/ContextFilterLogFormatter.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import "DDLog.h" 3 | 4 | @class ContextFilterLogFormatter; 5 | 6 | /** 7 | * Welcome to Cocoa Lumberjack! 8 | * 9 | * The project page has a wealth of documentation if you have any questions. 10 | * https://github.com/robbiehanson/CocoaLumberjack 11 | * 12 | * If you're new to the project you may wish to read the "Getting Started" page. 13 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/GettingStarted 14 | * 15 | * 16 | * This class provides a log formatter that filters log statements from a logging context not on the whitelist. 17 | * 18 | * A log formatter can be added to any logger to format and/or filter its output. 19 | * You can learn more about log formatters here: 20 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/CustomFormatters 21 | * 22 | * You can learn more about logging context's here: 23 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/CustomContext 24 | * 25 | * But here's a quick overview / refresher: 26 | * 27 | * Every log statement has a logging context. 28 | * These come from the underlying logging macros defined in DDLog.h. 29 | * The default logging context is zero. 30 | * You can define multiple logging context's for use in your application. 31 | * For example, logically separate parts of your app each have a different logging context. 32 | * Also 3rd party frameworks that make use of Lumberjack generally use their own dedicated logging context. 33 | **/ 34 | @interface ContextWhitelistFilterLogFormatter : NSObject 35 | 36 | - (id)init; 37 | 38 | - (void)addToWhitelist:(int)loggingContext; 39 | - (void)removeFromWhitelist:(int)loggingContext; 40 | 41 | - (NSArray *)whitelist; 42 | 43 | - (BOOL)isOnWhitelist:(int)loggingContext; 44 | 45 | @end 46 | 47 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 48 | #pragma mark - 49 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 50 | 51 | /** 52 | * This class provides a log formatter that filters log statements from a logging context on the blacklist. 53 | **/ 54 | @interface ContextBlacklistFilterLogFormatter : NSObject 55 | 56 | - (id)init; 57 | 58 | - (void)addToBlacklist:(int)loggingContext; 59 | - (void)removeFromBlacklist:(int)loggingContext; 60 | 61 | - (NSArray *)blacklist; 62 | 63 | - (BOOL)isOnBlacklist:(int)loggingContext; 64 | 65 | @end 66 | -------------------------------------------------------------------------------- /CocoaHttpServer/CocoaLumberjack/Extensions/ContextFilterLogFormatter.m: -------------------------------------------------------------------------------- 1 | #import "ContextFilterLogFormatter.h" 2 | #import 3 | 4 | /** 5 | * Welcome to Cocoa Lumberjack! 6 | * 7 | * The project page has a wealth of documentation if you have any questions. 8 | * https://github.com/robbiehanson/CocoaLumberjack 9 | * 10 | * If you're new to the project you may wish to read the "Getting Started" wiki. 11 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/GettingStarted 12 | **/ 13 | 14 | #if ! __has_feature(objc_arc) 15 | #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). 16 | #endif 17 | 18 | @interface LoggingContextSet : NSObject 19 | 20 | - (void)addToSet:(int)loggingContext; 21 | - (void)removeFromSet:(int)loggingContext; 22 | 23 | - (NSArray *)currentSet; 24 | 25 | - (BOOL)isInSet:(int)loggingContext; 26 | 27 | @end 28 | 29 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 30 | #pragma mark - 31 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 32 | 33 | @implementation ContextWhitelistFilterLogFormatter 34 | { 35 | LoggingContextSet *contextSet; 36 | } 37 | 38 | - (id)init 39 | { 40 | if ((self = [super init])) 41 | { 42 | contextSet = [[LoggingContextSet alloc] init]; 43 | } 44 | return self; 45 | } 46 | 47 | 48 | - (void)addToWhitelist:(int)loggingContext 49 | { 50 | [contextSet addToSet:loggingContext]; 51 | } 52 | 53 | - (void)removeFromWhitelist:(int)loggingContext 54 | { 55 | [contextSet removeFromSet:loggingContext]; 56 | } 57 | 58 | - (NSArray *)whitelist 59 | { 60 | return [contextSet currentSet]; 61 | } 62 | 63 | - (BOOL)isOnWhitelist:(int)loggingContext 64 | { 65 | return [contextSet isInSet:loggingContext]; 66 | } 67 | 68 | - (NSString *)formatLogMessage:(DDLogMessage *)logMessage 69 | { 70 | if ([self isOnWhitelist:logMessage->logContext]) 71 | return logMessage->logMsg; 72 | else 73 | return nil; 74 | } 75 | 76 | @end 77 | 78 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 79 | #pragma mark - 80 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 81 | 82 | @implementation ContextBlacklistFilterLogFormatter 83 | { 84 | LoggingContextSet *contextSet; 85 | } 86 | 87 | - (id)init 88 | { 89 | if ((self = [super init])) 90 | { 91 | contextSet = [[LoggingContextSet alloc] init]; 92 | } 93 | return self; 94 | } 95 | 96 | 97 | - (void)addToBlacklist:(int)loggingContext 98 | { 99 | [contextSet addToSet:loggingContext]; 100 | } 101 | 102 | - (void)removeFromBlacklist:(int)loggingContext 103 | { 104 | [contextSet removeFromSet:loggingContext]; 105 | } 106 | 107 | - (NSArray *)blacklist 108 | { 109 | return [contextSet currentSet]; 110 | } 111 | 112 | - (BOOL)isOnBlacklist:(int)loggingContext 113 | { 114 | return [contextSet isInSet:loggingContext]; 115 | } 116 | 117 | - (NSString *)formatLogMessage:(DDLogMessage *)logMessage 118 | { 119 | if ([self isOnBlacklist:logMessage->logContext]) 120 | return nil; 121 | else 122 | return logMessage->logMsg; 123 | } 124 | 125 | @end 126 | 127 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 128 | #pragma mark - 129 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 130 | 131 | @implementation LoggingContextSet 132 | { 133 | OSSpinLock lock; 134 | NSMutableSet *set; 135 | } 136 | 137 | - (id)init 138 | { 139 | if ((self = [super init])) 140 | { 141 | set = [[NSMutableSet alloc] init]; 142 | } 143 | return self; 144 | } 145 | 146 | 147 | - (void)addToSet:(int)loggingContext 148 | { 149 | OSSpinLockLock(&lock); 150 | { 151 | [set addObject:@(loggingContext)]; 152 | } 153 | OSSpinLockUnlock(&lock); 154 | } 155 | 156 | - (void)removeFromSet:(int)loggingContext 157 | { 158 | OSSpinLockLock(&lock); 159 | { 160 | [set removeObject:@(loggingContext)]; 161 | } 162 | OSSpinLockUnlock(&lock); 163 | } 164 | 165 | - (NSArray *)currentSet 166 | { 167 | NSArray *result = nil; 168 | 169 | OSSpinLockLock(&lock); 170 | { 171 | result = [set allObjects]; 172 | } 173 | OSSpinLockUnlock(&lock); 174 | 175 | return result; 176 | } 177 | 178 | - (BOOL)isInSet:(int)loggingContext 179 | { 180 | BOOL result = NO; 181 | 182 | OSSpinLockLock(&lock); 183 | { 184 | result = [set containsObject:@(loggingContext)]; 185 | } 186 | OSSpinLockUnlock(&lock); 187 | 188 | return result; 189 | } 190 | 191 | @end 192 | -------------------------------------------------------------------------------- /CocoaHttpServer/CocoaLumberjack/Extensions/DispatchQueueLogFormatter.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import 3 | #import "DDLog.h" 4 | 5 | 6 | /** 7 | * Welcome to Cocoa Lumberjack! 8 | * 9 | * The project page has a wealth of documentation if you have any questions. 10 | * https://github.com/robbiehanson/CocoaLumberjack 11 | * 12 | * If you're new to the project you may wish to read the "Getting Started" page. 13 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/GettingStarted 14 | * 15 | * 16 | * This class provides a log formatter that prints the dispatch_queue label instead of the mach_thread_id. 17 | * 18 | * A log formatter can be added to any logger to format and/or filter its output. 19 | * You can learn more about log formatters here: 20 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/CustomFormatters 21 | * 22 | * A typical NSLog (or DDTTYLogger) prints detailed info as [:]. 23 | * For example: 24 | * 25 | * 2011-10-17 20:21:45.435 AppName[19928:5207] Your log message here 26 | * 27 | * Where: 28 | * - 19928 = process id 29 | * - 5207 = thread id (mach_thread_id printed in hex) 30 | * 31 | * When using grand central dispatch (GCD), this information is less useful. 32 | * This is because a single serial dispatch queue may be run on any thread from an internally managed thread pool. 33 | * For example: 34 | * 35 | * 2011-10-17 20:32:31.111 AppName[19954:4d07] Message from my_serial_dispatch_queue 36 | * 2011-10-17 20:32:31.112 AppName[19954:5207] Message from my_serial_dispatch_queue 37 | * 2011-10-17 20:32:31.113 AppName[19954:2c55] Message from my_serial_dispatch_queue 38 | * 39 | * This formatter allows you to replace the standard [box:info] with the dispatch_queue name. 40 | * For example: 41 | * 42 | * 2011-10-17 20:32:31.111 AppName[img-scaling] Message from my_serial_dispatch_queue 43 | * 2011-10-17 20:32:31.112 AppName[img-scaling] Message from my_serial_dispatch_queue 44 | * 2011-10-17 20:32:31.113 AppName[img-scaling] Message from my_serial_dispatch_queue 45 | * 46 | * If the dispatch_queue doesn't have a set name, then it falls back to the thread name. 47 | * If the current thread doesn't have a set name, then it falls back to the mach_thread_id in hex (like normal). 48 | * 49 | * Note: If manually creating your own background threads (via NSThread/alloc/init or NSThread/detachNeThread), 50 | * you can use [[NSThread currentThread] setName:(NSString *)]. 51 | **/ 52 | @interface DispatchQueueLogFormatter : NSObject { 53 | @protected 54 | 55 | NSString *dateFormatString; 56 | } 57 | 58 | /** 59 | * Standard init method. 60 | * Configure using properties as desired. 61 | **/ 62 | - (id)init; 63 | 64 | /** 65 | * The minQueueLength restricts the minimum size of the [detail box]. 66 | * If the minQueueLength is set to 0, there is no restriction. 67 | * 68 | * For example, say a dispatch_queue has a label of "diskIO": 69 | * 70 | * If the minQueueLength is 0: [diskIO] 71 | * If the minQueueLength is 4: [diskIO] 72 | * If the minQueueLength is 5: [diskIO] 73 | * If the minQueueLength is 6: [diskIO] 74 | * If the minQueueLength is 7: [diskIO ] 75 | * If the minQueueLength is 8: [diskIO ] 76 | * 77 | * The default minQueueLength is 0 (no minimum, so [detail box] won't be padded). 78 | * 79 | * If you want every [detail box] to have the exact same width, 80 | * set both minQueueLength and maxQueueLength to the same value. 81 | **/ 82 | @property (assign) NSUInteger minQueueLength; 83 | 84 | /** 85 | * The maxQueueLength restricts the number of characters that will be inside the [detail box]. 86 | * If the maxQueueLength is 0, there is no restriction. 87 | * 88 | * For example, say a dispatch_queue has a label of "diskIO": 89 | * 90 | * If the maxQueueLength is 0: [diskIO] 91 | * If the maxQueueLength is 4: [disk] 92 | * If the maxQueueLength is 5: [diskI] 93 | * If the maxQueueLength is 6: [diskIO] 94 | * If the maxQueueLength is 7: [diskIO] 95 | * If the maxQueueLength is 8: [diskIO] 96 | * 97 | * The default maxQueueLength is 0 (no maximum, so [detail box] won't be truncated). 98 | * 99 | * If you want every [detail box] to have the exact same width, 100 | * set both minQueueLength and maxQueueLength to the same value. 101 | **/ 102 | @property (assign) NSUInteger maxQueueLength; 103 | 104 | /** 105 | * Sometimes queue labels have long names like "com.apple.main-queue", 106 | * but you'd prefer something shorter like simply "main". 107 | * 108 | * This method allows you to set such preferred replacements. 109 | * The above example is set by default. 110 | * 111 | * To remove/undo a previous replacement, invoke this method with nil for the 'shortLabel' parameter. 112 | **/ 113 | - (NSString *)replacementStringForQueueLabel:(NSString *)longLabel; 114 | - (void)setReplacementString:(NSString *)shortLabel forQueueLabel:(NSString *)longLabel; 115 | 116 | @end 117 | -------------------------------------------------------------------------------- /CocoaHttpServer/CocoaLumberjack/Extensions/DispatchQueueLogFormatter.m: -------------------------------------------------------------------------------- 1 | #import "DispatchQueueLogFormatter.h" 2 | #import 3 | 4 | /** 5 | * Welcome to Cocoa Lumberjack! 6 | * 7 | * The project page has a wealth of documentation if you have any questions. 8 | * https://github.com/robbiehanson/CocoaLumberjack 9 | * 10 | * If you're new to the project you may wish to read the "Getting Started" wiki. 11 | * https://github.com/robbiehanson/CocoaLumberjack/wiki/GettingStarted 12 | **/ 13 | 14 | #if ! __has_feature(objc_arc) 15 | #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). 16 | #endif 17 | 18 | 19 | @implementation DispatchQueueLogFormatter 20 | { 21 | int32_t atomicLoggerCount; 22 | NSDateFormatter *threadUnsafeDateFormatter; // Use [self stringFromDate] 23 | 24 | OSSpinLock lock; 25 | 26 | NSUInteger _minQueueLength; // _prefix == Only access via atomic property 27 | NSUInteger _maxQueueLength; // _prefix == Only access via atomic property 28 | NSMutableDictionary *_replacements; // _prefix == Only access from within spinlock 29 | } 30 | 31 | - (id)init 32 | { 33 | if ((self = [super init])) 34 | { 35 | dateFormatString = @"yyyy-MM-dd HH:mm:ss:SSS"; 36 | 37 | atomicLoggerCount = 0; 38 | threadUnsafeDateFormatter = nil; 39 | 40 | _minQueueLength = 0; 41 | _maxQueueLength = 0; 42 | _replacements = [[NSMutableDictionary alloc] init]; 43 | 44 | // Set default replacements: 45 | 46 | [_replacements setObject:@"main" forKey:@"com.apple.main-thread"]; 47 | } 48 | return self; 49 | } 50 | 51 | 52 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 53 | #pragma mark Configuration 54 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 55 | 56 | @synthesize minQueueLength = _minQueueLength; 57 | @synthesize maxQueueLength = _maxQueueLength; 58 | 59 | - (NSString *)replacementStringForQueueLabel:(NSString *)longLabel 60 | { 61 | NSString *result = nil; 62 | 63 | OSSpinLockLock(&lock); 64 | { 65 | result = [_replacements objectForKey:longLabel]; 66 | } 67 | OSSpinLockUnlock(&lock); 68 | 69 | return result; 70 | } 71 | 72 | - (void)setReplacementString:(NSString *)shortLabel forQueueLabel:(NSString *)longLabel 73 | { 74 | OSSpinLockLock(&lock); 75 | { 76 | if (shortLabel) 77 | [_replacements setObject:shortLabel forKey:longLabel]; 78 | else 79 | [_replacements removeObjectForKey:longLabel]; 80 | } 81 | OSSpinLockUnlock(&lock); 82 | } 83 | 84 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 85 | #pragma mark DDLogFormatter 86 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 87 | 88 | - (NSString *)stringFromDate:(NSDate *)date 89 | { 90 | int32_t loggerCount = OSAtomicAdd32(0, &atomicLoggerCount); 91 | 92 | if (loggerCount <= 1) 93 | { 94 | // Single-threaded mode. 95 | 96 | if (threadUnsafeDateFormatter == nil) 97 | { 98 | threadUnsafeDateFormatter = [[NSDateFormatter alloc] init]; 99 | [threadUnsafeDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4]; 100 | [threadUnsafeDateFormatter setDateFormat:dateFormatString]; 101 | } 102 | 103 | return [threadUnsafeDateFormatter stringFromDate:date]; 104 | } 105 | else 106 | { 107 | // Multi-threaded mode. 108 | // NSDateFormatter is NOT thread-safe. 109 | 110 | NSString *key = @"DispatchQueueLogFormatter_NSDateFormatter"; 111 | 112 | NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary]; 113 | NSDateFormatter *dateFormatter = [threadDictionary objectForKey:key]; 114 | 115 | if (dateFormatter == nil) 116 | { 117 | dateFormatter = [[NSDateFormatter alloc] init]; 118 | [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4]; 119 | [dateFormatter setDateFormat:dateFormatString]; 120 | 121 | [threadDictionary setObject:dateFormatter forKey:key]; 122 | } 123 | 124 | return [dateFormatter stringFromDate:date]; 125 | } 126 | } 127 | 128 | - (NSString *)queueThreadLabelForLogMessage:(DDLogMessage *)logMessage 129 | { 130 | // As per the DDLogFormatter contract, this method is always invoked on the same thread/dispatch_queue 131 | 132 | NSUInteger minQueueLength = self.minQueueLength; 133 | NSUInteger maxQueueLength = self.maxQueueLength; 134 | 135 | // Get the name of the queue, thread, or machID (whichever we are to use). 136 | 137 | NSString *queueThreadLabel = nil; 138 | 139 | BOOL useQueueLabel = YES; 140 | BOOL useThreadName = NO; 141 | 142 | if (logMessage->queueLabel) 143 | { 144 | // If you manually create a thread, it's dispatch_queue will have one of the thread names below. 145 | // Since all such threads have the same name, we'd prefer to use the threadName or the machThreadID. 146 | 147 | char *names[] = { "com.apple.root.low-priority", 148 | "com.apple.root.default-priority", 149 | "com.apple.root.high-priority", 150 | "com.apple.root.low-overcommit-priority", 151 | "com.apple.root.default-overcommit-priority", 152 | "com.apple.root.high-overcommit-priority" }; 153 | 154 | int length = sizeof(names) / sizeof(char *); 155 | 156 | int i; 157 | for (i = 0; i < length; i++) 158 | { 159 | if (strcmp(logMessage->queueLabel, names[i]) == 0) 160 | { 161 | useQueueLabel = NO; 162 | useThreadName = [logMessage->threadName length] > 0; 163 | break; 164 | } 165 | } 166 | } 167 | else 168 | { 169 | useQueueLabel = NO; 170 | useThreadName = [logMessage->threadName length] > 0; 171 | } 172 | 173 | if (useQueueLabel || useThreadName) 174 | { 175 | NSString *fullLabel; 176 | NSString *abrvLabel; 177 | 178 | if (useQueueLabel) 179 | fullLabel = @(logMessage->queueLabel); 180 | else 181 | fullLabel = logMessage->threadName; 182 | 183 | OSSpinLockLock(&lock); 184 | { 185 | abrvLabel = [_replacements objectForKey:fullLabel]; 186 | } 187 | OSSpinLockUnlock(&lock); 188 | 189 | if (abrvLabel) 190 | queueThreadLabel = abrvLabel; 191 | else 192 | queueThreadLabel = fullLabel; 193 | } 194 | else 195 | { 196 | queueThreadLabel = [NSString stringWithFormat:@"%x", logMessage->machThreadID]; 197 | } 198 | 199 | // Now use the thread label in the output 200 | 201 | NSUInteger labelLength = [queueThreadLabel length]; 202 | 203 | // labelLength > maxQueueLength : truncate 204 | // labelLength < minQueueLength : padding 205 | // : exact 206 | 207 | if ((maxQueueLength > 0) && (labelLength > maxQueueLength)) 208 | { 209 | // Truncate 210 | 211 | return [queueThreadLabel substringToIndex:maxQueueLength]; 212 | } 213 | else if (labelLength < minQueueLength) 214 | { 215 | // Padding 216 | 217 | NSUInteger numSpaces = minQueueLength - labelLength; 218 | 219 | char spaces[numSpaces + 1]; 220 | memset(spaces, ' ', numSpaces); 221 | spaces[numSpaces] = '\0'; 222 | 223 | return [NSString stringWithFormat:@"%@%s", queueThreadLabel, spaces]; 224 | } 225 | else 226 | { 227 | // Exact 228 | 229 | return queueThreadLabel; 230 | } 231 | } 232 | 233 | - (NSString *)formatLogMessage:(DDLogMessage *)logMessage 234 | { 235 | NSString *timestamp = [self stringFromDate:(logMessage->timestamp)]; 236 | NSString *queueThreadLabel = [self queueThreadLabelForLogMessage:logMessage]; 237 | 238 | return [NSString stringWithFormat:@"%@ [%@] %@", timestamp, queueThreadLabel, logMessage->logMsg]; 239 | } 240 | 241 | - (void)didAddToLogger:(id )logger 242 | { 243 | OSAtomicIncrement32(&atomicLoggerCount); 244 | } 245 | 246 | - (void)willRemoveFromLogger:(id )logger 247 | { 248 | OSAtomicDecrement32(&atomicLoggerCount); 249 | } 250 | 251 | @end 252 | -------------------------------------------------------------------------------- /CocoaHttpServer/CocoaLumberjack/Extensions/README.txt: -------------------------------------------------------------------------------- 1 | This folder contains some sample formatters that may be helpful. 2 | 3 | Feel free to change them, extend them, or use them as the basis for your own custom formatter(s). 4 | 5 | More information about creating your own custom formatters can be found on the wiki: 6 | https://github.com/robbiehanson/CocoaLumberjack/wiki/CustomFormatters 7 | 8 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Categories/DDData.h: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | @interface NSData (DDData) 4 | 5 | - (NSData *)md5Digest; 6 | 7 | - (NSData *)sha1Digest; 8 | 9 | - (NSString *)hexStringValue; 10 | 11 | - (NSString *)base64Encoded; 12 | - (NSData *)base64Decoded; 13 | 14 | @end 15 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Categories/DDData.m: -------------------------------------------------------------------------------- 1 | #import "DDData.h" 2 | #import 3 | 4 | 5 | @implementation NSData (DDData) 6 | 7 | static char encodingTable[64] = { 8 | 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', 9 | 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f', 10 | 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v', 11 | 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' }; 12 | 13 | - (NSData *)md5Digest 14 | { 15 | unsigned char result[CC_MD5_DIGEST_LENGTH]; 16 | 17 | CC_MD5([self bytes], (CC_LONG)[self length], result); 18 | return [NSData dataWithBytes:result length:CC_MD5_DIGEST_LENGTH]; 19 | } 20 | 21 | - (NSData *)sha1Digest 22 | { 23 | unsigned char result[CC_SHA1_DIGEST_LENGTH]; 24 | 25 | CC_SHA1([self bytes], (CC_LONG)[self length], result); 26 | return [NSData dataWithBytes:result length:CC_SHA1_DIGEST_LENGTH]; 27 | } 28 | 29 | - (NSString *)hexStringValue 30 | { 31 | NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:([self length] * 2)]; 32 | 33 | const unsigned char *dataBuffer = [self bytes]; 34 | int i; 35 | 36 | for (i = 0; i < [self length]; ++i) 37 | { 38 | [stringBuffer appendFormat:@"%02x", (unsigned int)dataBuffer[i]]; 39 | } 40 | 41 | return [stringBuffer copy]; 42 | } 43 | 44 | - (NSString *)base64Encoded 45 | { 46 | const unsigned char *bytes = [self bytes]; 47 | NSMutableString *result = [NSMutableString stringWithCapacity:[self length]]; 48 | unsigned long ixtext = 0; 49 | unsigned long lentext = [self length]; 50 | long ctremaining = 0; 51 | unsigned char inbuf[3], outbuf[4]; 52 | unsigned short i = 0; 53 | unsigned short charsonline = 0, ctcopy = 0; 54 | unsigned long ix = 0; 55 | 56 | while( YES ) 57 | { 58 | ctremaining = lentext - ixtext; 59 | if( ctremaining <= 0 ) break; 60 | 61 | for( i = 0; i < 3; i++ ) { 62 | ix = ixtext + i; 63 | if( ix < lentext ) inbuf[i] = bytes[ix]; 64 | else inbuf [i] = 0; 65 | } 66 | 67 | outbuf [0] = (inbuf [0] & 0xFC) >> 2; 68 | outbuf [1] = ((inbuf [0] & 0x03) << 4) | ((inbuf [1] & 0xF0) >> 4); 69 | outbuf [2] = ((inbuf [1] & 0x0F) << 2) | ((inbuf [2] & 0xC0) >> 6); 70 | outbuf [3] = inbuf [2] & 0x3F; 71 | ctcopy = 4; 72 | 73 | switch( ctremaining ) 74 | { 75 | case 1: 76 | ctcopy = 2; 77 | break; 78 | case 2: 79 | ctcopy = 3; 80 | break; 81 | } 82 | 83 | for( i = 0; i < ctcopy; i++ ) 84 | [result appendFormat:@"%c", encodingTable[outbuf[i]]]; 85 | 86 | for( i = ctcopy; i < 4; i++ ) 87 | [result appendString:@"="]; 88 | 89 | ixtext += 3; 90 | charsonline += 4; 91 | } 92 | 93 | return [NSString stringWithString:result]; 94 | } 95 | 96 | - (NSData *)base64Decoded 97 | { 98 | const unsigned char *bytes = [self bytes]; 99 | NSMutableData *result = [NSMutableData dataWithCapacity:[self length]]; 100 | 101 | unsigned long ixtext = 0; 102 | unsigned long lentext = [self length]; 103 | unsigned char ch = 0; 104 | unsigned char inbuf[4] = {0, 0, 0, 0}; 105 | unsigned char outbuf[3] = {0, 0, 0}; 106 | short i = 0, ixinbuf = 0; 107 | BOOL flignore = NO; 108 | BOOL flendtext = NO; 109 | 110 | while( YES ) 111 | { 112 | if( ixtext >= lentext ) break; 113 | ch = bytes[ixtext++]; 114 | flignore = NO; 115 | 116 | if( ( ch >= 'A' ) && ( ch <= 'Z' ) ) ch = ch - 'A'; 117 | else if( ( ch >= 'a' ) && ( ch <= 'z' ) ) ch = ch - 'a' + 26; 118 | else if( ( ch >= '0' ) && ( ch <= '9' ) ) ch = ch - '0' + 52; 119 | else if( ch == '+' ) ch = 62; 120 | else if( ch == '=' ) flendtext = YES; 121 | else if( ch == '/' ) ch = 63; 122 | else flignore = YES; 123 | 124 | if( ! flignore ) 125 | { 126 | short ctcharsinbuf = 3; 127 | BOOL flbreak = NO; 128 | 129 | if( flendtext ) 130 | { 131 | if( ! ixinbuf ) break; 132 | if( ( ixinbuf == 1 ) || ( ixinbuf == 2 ) ) ctcharsinbuf = 1; 133 | else ctcharsinbuf = 2; 134 | ixinbuf = 3; 135 | flbreak = YES; 136 | } 137 | 138 | inbuf [ixinbuf++] = ch; 139 | 140 | if( ixinbuf == 4 ) 141 | { 142 | ixinbuf = 0; 143 | outbuf [0] = ( inbuf[0] << 2 ) | ( ( inbuf[1] & 0x30) >> 4 ); 144 | outbuf [1] = ( ( inbuf[1] & 0x0F ) << 4 ) | ( ( inbuf[2] & 0x3C ) >> 2 ); 145 | outbuf [2] = ( ( inbuf[2] & 0x03 ) << 6 ) | ( inbuf[3] & 0x3F ); 146 | 147 | for( i = 0; i < ctcharsinbuf; i++ ) 148 | [result appendBytes:&outbuf[i] length:1]; 149 | } 150 | 151 | if( flbreak ) break; 152 | } 153 | } 154 | 155 | return [NSData dataWithData:result]; 156 | } 157 | 158 | @end 159 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Categories/DDNumber.h: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | 4 | @interface NSNumber (DDNumber) 5 | 6 | + (BOOL)parseString:(NSString *)str intoSInt64:(SInt64 *)pNum; 7 | + (BOOL)parseString:(NSString *)str intoUInt64:(UInt64 *)pNum; 8 | 9 | + (BOOL)parseString:(NSString *)str intoNSInteger:(NSInteger *)pNum; 10 | + (BOOL)parseString:(NSString *)str intoNSUInteger:(NSUInteger *)pNum; 11 | 12 | @end 13 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Categories/DDNumber.m: -------------------------------------------------------------------------------- 1 | #import "DDNumber.h" 2 | 3 | 4 | @implementation NSNumber (DDNumber) 5 | 6 | + (BOOL)parseString:(NSString *)str intoSInt64:(SInt64 *)pNum 7 | { 8 | if(str == nil) 9 | { 10 | *pNum = 0; 11 | return NO; 12 | } 13 | 14 | errno = 0; 15 | 16 | // On both 32-bit and 64-bit machines, long long = 64 bit 17 | 18 | *pNum = strtoll([str UTF8String], NULL, 10); 19 | 20 | if(errno != 0) 21 | return NO; 22 | else 23 | return YES; 24 | } 25 | 26 | + (BOOL)parseString:(NSString *)str intoUInt64:(UInt64 *)pNum 27 | { 28 | if(str == nil) 29 | { 30 | *pNum = 0; 31 | return NO; 32 | } 33 | 34 | errno = 0; 35 | 36 | // On both 32-bit and 64-bit machines, unsigned long long = 64 bit 37 | 38 | *pNum = strtoull([str UTF8String], NULL, 10); 39 | 40 | if(errno != 0) 41 | return NO; 42 | else 43 | return YES; 44 | } 45 | 46 | + (BOOL)parseString:(NSString *)str intoNSInteger:(NSInteger *)pNum 47 | { 48 | if(str == nil) 49 | { 50 | *pNum = 0; 51 | return NO; 52 | } 53 | 54 | errno = 0; 55 | 56 | // On LP64, NSInteger = long = 64 bit 57 | // Otherwise, NSInteger = int = long = 32 bit 58 | 59 | *pNum = strtol([str UTF8String], NULL, 10); 60 | 61 | if(errno != 0) 62 | return NO; 63 | else 64 | return YES; 65 | } 66 | 67 | + (BOOL)parseString:(NSString *)str intoNSUInteger:(NSUInteger *)pNum 68 | { 69 | if(str == nil) 70 | { 71 | *pNum = 0; 72 | return NO; 73 | } 74 | 75 | errno = 0; 76 | 77 | // On LP64, NSUInteger = unsigned long = 64 bit 78 | // Otherwise, NSUInteger = unsigned int = unsigned long = 32 bit 79 | 80 | *pNum = strtoul([str UTF8String], NULL, 10); 81 | 82 | if(errno != 0) 83 | return NO; 84 | else 85 | return YES; 86 | } 87 | 88 | @end 89 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Categories/DDRange.h: -------------------------------------------------------------------------------- 1 | /** 2 | * DDRange is the functional equivalent of a 64 bit NSRange. 3 | * The HTTP Server is designed to support very large files. 4 | * On 32 bit architectures (ppc, i386) NSRange uses unsigned 32 bit integers. 5 | * This only supports a range of up to 4 gigabytes. 6 | * By defining our own variant, we can support a range up to 16 exabytes. 7 | * 8 | * All effort is given such that DDRange functions EXACTLY the same as NSRange. 9 | **/ 10 | 11 | #import 12 | #import 13 | 14 | @class NSString; 15 | 16 | typedef struct _DDRange { 17 | UInt64 location; 18 | UInt64 length; 19 | } DDRange; 20 | 21 | typedef DDRange *DDRangePointer; 22 | 23 | NS_INLINE DDRange DDMakeRange(UInt64 loc, UInt64 len) { 24 | DDRange r; 25 | r.location = loc; 26 | r.length = len; 27 | return r; 28 | } 29 | 30 | NS_INLINE UInt64 DDMaxRange(DDRange range) { 31 | return (range.location + range.length); 32 | } 33 | 34 | NS_INLINE BOOL DDLocationInRange(UInt64 loc, DDRange range) { 35 | return (loc - range.location < range.length); 36 | } 37 | 38 | NS_INLINE BOOL DDEqualRanges(DDRange range1, DDRange range2) { 39 | return ((range1.location == range2.location) && (range1.length == range2.length)); 40 | } 41 | 42 | FOUNDATION_EXPORT DDRange DDUnionRange(DDRange range1, DDRange range2); 43 | FOUNDATION_EXPORT DDRange DDIntersectionRange(DDRange range1, DDRange range2); 44 | FOUNDATION_EXPORT NSString *DDStringFromRange(DDRange range); 45 | FOUNDATION_EXPORT DDRange DDRangeFromString(NSString *aString); 46 | 47 | NSInteger DDRangeCompare(DDRangePointer pDDRange1, DDRangePointer pDDRange2); 48 | 49 | @interface NSValue (NSValueDDRangeExtensions) 50 | 51 | + (NSValue *)valueWithDDRange:(DDRange)range; 52 | - (DDRange)ddrangeValue; 53 | 54 | - (NSInteger)ddrangeCompare:(NSValue *)ddrangeValue; 55 | 56 | @end 57 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Categories/DDRange.m: -------------------------------------------------------------------------------- 1 | #import "DDRange.h" 2 | #import "DDNumber.h" 3 | 4 | DDRange DDUnionRange(DDRange range1, DDRange range2) 5 | { 6 | DDRange result; 7 | 8 | result.location = MIN(range1.location, range2.location); 9 | result.length = MAX(DDMaxRange(range1), DDMaxRange(range2)) - result.location; 10 | 11 | return result; 12 | } 13 | 14 | DDRange DDIntersectionRange(DDRange range1, DDRange range2) 15 | { 16 | DDRange result; 17 | 18 | if((DDMaxRange(range1) < range2.location) || (DDMaxRange(range2) < range1.location)) 19 | { 20 | return DDMakeRange(0, 0); 21 | } 22 | 23 | result.location = MAX(range1.location, range2.location); 24 | result.length = MIN(DDMaxRange(range1), DDMaxRange(range2)) - result.location; 25 | 26 | return result; 27 | } 28 | 29 | NSString *DDStringFromRange(DDRange range) 30 | { 31 | return [NSString stringWithFormat:@"{%qu, %qu}", range.location, range.length]; 32 | } 33 | 34 | DDRange DDRangeFromString(NSString *aString) 35 | { 36 | DDRange result = DDMakeRange(0, 0); 37 | 38 | // NSRange will ignore '-' characters, but not '+' characters 39 | NSCharacterSet *cset = [NSCharacterSet characterSetWithCharactersInString:@"+0123456789"]; 40 | 41 | NSScanner *scanner = [NSScanner scannerWithString:aString]; 42 | [scanner setCharactersToBeSkipped:[cset invertedSet]]; 43 | 44 | NSString *str1 = nil; 45 | NSString *str2 = nil; 46 | 47 | BOOL found1 = [scanner scanCharactersFromSet:cset intoString:&str1]; 48 | BOOL found2 = [scanner scanCharactersFromSet:cset intoString:&str2]; 49 | 50 | if(found1) [NSNumber parseString:str1 intoUInt64:&result.location]; 51 | if(found2) [NSNumber parseString:str2 intoUInt64:&result.length]; 52 | 53 | return result; 54 | } 55 | 56 | NSInteger DDRangeCompare(DDRangePointer pDDRange1, DDRangePointer pDDRange2) 57 | { 58 | // Comparison basis: 59 | // Which range would you encouter first if you started at zero, and began walking towards infinity. 60 | // If you encouter both ranges at the same time, which range would end first. 61 | 62 | if(pDDRange1->location < pDDRange2->location) 63 | { 64 | return NSOrderedAscending; 65 | } 66 | if(pDDRange1->location > pDDRange2->location) 67 | { 68 | return NSOrderedDescending; 69 | } 70 | if(pDDRange1->length < pDDRange2->length) 71 | { 72 | return NSOrderedAscending; 73 | } 74 | if(pDDRange1->length > pDDRange2->length) 75 | { 76 | return NSOrderedDescending; 77 | } 78 | 79 | return NSOrderedSame; 80 | } 81 | 82 | @implementation NSValue (NSValueDDRangeExtensions) 83 | 84 | + (NSValue *)valueWithDDRange:(DDRange)range 85 | { 86 | return [NSValue valueWithBytes:&range objCType:@encode(DDRange)]; 87 | } 88 | 89 | - (DDRange)ddrangeValue 90 | { 91 | DDRange result; 92 | [self getValue:&result]; 93 | return result; 94 | } 95 | 96 | - (NSInteger)ddrangeCompare:(NSValue *)other 97 | { 98 | DDRange r1 = [self ddrangeValue]; 99 | DDRange r2 = [other ddrangeValue]; 100 | 101 | return DDRangeCompare(&r1, &r2); 102 | } 103 | 104 | @end 105 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/HTTPAuthenticationRequest.h: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | #if TARGET_OS_IPHONE 4 | // Note: You may need to add the CFNetwork Framework to your project 5 | #import 6 | #endif 7 | 8 | @class HTTPMessage; 9 | 10 | 11 | @interface HTTPAuthenticationRequest : NSObject 12 | { 13 | BOOL isBasic; 14 | BOOL isDigest; 15 | 16 | NSString *base64Credentials; 17 | 18 | NSString *username; 19 | NSString *realm; 20 | NSString *nonce; 21 | NSString *uri; 22 | NSString *qop; 23 | NSString *nc; 24 | NSString *cnonce; 25 | NSString *response; 26 | } 27 | - (id)initWithRequest:(HTTPMessage *)request; 28 | 29 | - (BOOL)isBasic; 30 | - (BOOL)isDigest; 31 | 32 | // Basic 33 | - (NSString *)base64Credentials; 34 | 35 | // Digest 36 | - (NSString *)username; 37 | - (NSString *)realm; 38 | - (NSString *)nonce; 39 | - (NSString *)uri; 40 | - (NSString *)qop; 41 | - (NSString *)nc; 42 | - (NSString *)cnonce; 43 | - (NSString *)response; 44 | 45 | @end 46 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/HTTPAuthenticationRequest.m: -------------------------------------------------------------------------------- 1 | #import "HTTPAuthenticationRequest.h" 2 | #import "HTTPMessage.h" 3 | 4 | #if ! __has_feature(objc_arc) 5 | #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). 6 | #endif 7 | 8 | @interface HTTPAuthenticationRequest (PrivateAPI) 9 | - (NSString *)quotedSubHeaderFieldValue:(NSString *)param fromHeaderFieldValue:(NSString *)header; 10 | - (NSString *)nonquotedSubHeaderFieldValue:(NSString *)param fromHeaderFieldValue:(NSString *)header; 11 | @end 12 | 13 | 14 | @implementation HTTPAuthenticationRequest 15 | 16 | - (id)initWithRequest:(HTTPMessage *)request 17 | { 18 | if ((self = [super init])) 19 | { 20 | NSString *authInfo = [request headerField:@"Authorization"]; 21 | 22 | isBasic = NO; 23 | if ([authInfo length] >= 6) 24 | { 25 | isBasic = [[authInfo substringToIndex:6] caseInsensitiveCompare:@"Basic "] == NSOrderedSame; 26 | } 27 | 28 | isDigest = NO; 29 | if ([authInfo length] >= 7) 30 | { 31 | isDigest = [[authInfo substringToIndex:7] caseInsensitiveCompare:@"Digest "] == NSOrderedSame; 32 | } 33 | 34 | if (isBasic) 35 | { 36 | NSMutableString *temp = [[authInfo substringFromIndex:6] mutableCopy]; 37 | CFStringTrimWhitespace((__bridge CFMutableStringRef)temp); 38 | 39 | base64Credentials = [temp copy]; 40 | } 41 | 42 | if (isDigest) 43 | { 44 | username = [self quotedSubHeaderFieldValue:@"username" fromHeaderFieldValue:authInfo]; 45 | realm = [self quotedSubHeaderFieldValue:@"realm" fromHeaderFieldValue:authInfo]; 46 | nonce = [self quotedSubHeaderFieldValue:@"nonce" fromHeaderFieldValue:authInfo]; 47 | uri = [self quotedSubHeaderFieldValue:@"uri" fromHeaderFieldValue:authInfo]; 48 | 49 | // It appears from RFC 2617 that the qop is to be given unquoted 50 | // Tests show that Firefox performs this way, but Safari does not 51 | // Thus we'll attempt to retrieve the value as nonquoted, but we'll verify it doesn't start with a quote 52 | qop = [self nonquotedSubHeaderFieldValue:@"qop" fromHeaderFieldValue:authInfo]; 53 | if(qop && ([qop characterAtIndex:0] == '"')) 54 | { 55 | qop = [self quotedSubHeaderFieldValue:@"qop" fromHeaderFieldValue:authInfo]; 56 | } 57 | 58 | nc = [self nonquotedSubHeaderFieldValue:@"nc" fromHeaderFieldValue:authInfo]; 59 | cnonce = [self quotedSubHeaderFieldValue:@"cnonce" fromHeaderFieldValue:authInfo]; 60 | response = [self quotedSubHeaderFieldValue:@"response" fromHeaderFieldValue:authInfo]; 61 | } 62 | } 63 | return self; 64 | } 65 | 66 | 67 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 68 | #pragma mark Accessors: 69 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 70 | 71 | - (BOOL)isBasic { 72 | return isBasic; 73 | } 74 | 75 | - (BOOL)isDigest { 76 | return isDigest; 77 | } 78 | 79 | - (NSString *)base64Credentials { 80 | return base64Credentials; 81 | } 82 | 83 | - (NSString *)username { 84 | return username; 85 | } 86 | 87 | - (NSString *)realm { 88 | return realm; 89 | } 90 | 91 | - (NSString *)nonce { 92 | return nonce; 93 | } 94 | 95 | - (NSString *)uri { 96 | return uri; 97 | } 98 | 99 | - (NSString *)qop { 100 | return qop; 101 | } 102 | 103 | - (NSString *)nc { 104 | return nc; 105 | } 106 | 107 | - (NSString *)cnonce { 108 | return cnonce; 109 | } 110 | 111 | - (NSString *)response { 112 | return response; 113 | } 114 | 115 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 116 | #pragma mark Private API: 117 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 118 | 119 | /** 120 | * Retrieves a "Sub Header Field Value" from a given header field value. 121 | * The sub header field is expected to be quoted. 122 | * 123 | * In the following header field: 124 | * Authorization: Digest username="Mufasa", qop=auth, response="6629fae4939" 125 | * The sub header field titled 'username' is quoted, and this method would return the value @"Mufasa". 126 | **/ 127 | - (NSString *)quotedSubHeaderFieldValue:(NSString *)param fromHeaderFieldValue:(NSString *)header 128 | { 129 | NSRange startRange = [header rangeOfString:[NSString stringWithFormat:@"%@=\"", param]]; 130 | if(startRange.location == NSNotFound) 131 | { 132 | // The param was not found anywhere in the header 133 | return nil; 134 | } 135 | 136 | NSUInteger postStartRangeLocation = startRange.location + startRange.length; 137 | NSUInteger postStartRangeLength = [header length] - postStartRangeLocation; 138 | NSRange postStartRange = NSMakeRange(postStartRangeLocation, postStartRangeLength); 139 | 140 | NSRange endRange = [header rangeOfString:@"\"" options:0 range:postStartRange]; 141 | if(endRange.location == NSNotFound) 142 | { 143 | // The ending double-quote was not found anywhere in the header 144 | return nil; 145 | } 146 | 147 | NSRange subHeaderRange = NSMakeRange(postStartRangeLocation, endRange.location - postStartRangeLocation); 148 | return [header substringWithRange:subHeaderRange]; 149 | } 150 | 151 | /** 152 | * Retrieves a "Sub Header Field Value" from a given header field value. 153 | * The sub header field is expected to not be quoted. 154 | * 155 | * In the following header field: 156 | * Authorization: Digest username="Mufasa", qop=auth, response="6629fae4939" 157 | * The sub header field titled 'qop' is nonquoted, and this method would return the value @"auth". 158 | **/ 159 | - (NSString *)nonquotedSubHeaderFieldValue:(NSString *)param fromHeaderFieldValue:(NSString *)header 160 | { 161 | NSRange startRange = [header rangeOfString:[NSString stringWithFormat:@"%@=", param]]; 162 | if(startRange.location == NSNotFound) 163 | { 164 | // The param was not found anywhere in the header 165 | return nil; 166 | } 167 | 168 | NSUInteger postStartRangeLocation = startRange.location + startRange.length; 169 | NSUInteger postStartRangeLength = [header length] - postStartRangeLocation; 170 | NSRange postStartRange = NSMakeRange(postStartRangeLocation, postStartRangeLength); 171 | 172 | NSRange endRange = [header rangeOfString:@"," options:0 range:postStartRange]; 173 | if(endRange.location == NSNotFound) 174 | { 175 | // The ending comma was not found anywhere in the header 176 | // However, if the nonquoted param is at the end of the string, there would be no comma 177 | // This is only possible if there are no spaces anywhere 178 | NSRange endRange2 = [header rangeOfString:@" " options:0 range:postStartRange]; 179 | if(endRange2.location != NSNotFound) 180 | { 181 | return nil; 182 | } 183 | else 184 | { 185 | return [header substringWithRange:postStartRange]; 186 | } 187 | } 188 | else 189 | { 190 | NSRange subHeaderRange = NSMakeRange(postStartRangeLocation, endRange.location - postStartRangeLocation); 191 | return [header substringWithRange:subHeaderRange]; 192 | } 193 | } 194 | 195 | @end 196 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/HTTPConnection.h: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | @class GCDAsyncSocket; 4 | @class HTTPMessage; 5 | @class HTTPServer; 6 | @class WebSocket; 7 | @protocol HTTPResponse; 8 | 9 | 10 | #define HTTPConnectionDidDieNotification @"HTTPConnectionDidDie" 11 | 12 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 13 | #pragma mark - 14 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 15 | 16 | @interface HTTPConfig : NSObject 17 | { 18 | HTTPServer __unsafe_unretained *server; 19 | NSString __strong *documentRoot; 20 | dispatch_queue_t queue; 21 | } 22 | 23 | - (id)initWithServer:(HTTPServer *)server documentRoot:(NSString *)documentRoot; 24 | - (id)initWithServer:(HTTPServer *)server documentRoot:(NSString *)documentRoot queue:(dispatch_queue_t)q; 25 | 26 | @property (nonatomic, unsafe_unretained, readonly) HTTPServer *server; 27 | @property (nonatomic, strong, readonly) NSString *documentRoot; 28 | @property (nonatomic, readonly) dispatch_queue_t queue; 29 | 30 | @end 31 | 32 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 33 | #pragma mark - 34 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 35 | 36 | @interface HTTPConnection : NSObject 37 | { 38 | dispatch_queue_t connectionQueue; 39 | GCDAsyncSocket *asyncSocket; 40 | HTTPConfig *config; 41 | 42 | BOOL started; 43 | 44 | HTTPMessage *request; 45 | unsigned int numHeaderLines; 46 | 47 | BOOL sentResponseHeaders; 48 | 49 | NSString *nonce; 50 | long lastNC; 51 | 52 | NSObject *httpResponse; 53 | 54 | NSMutableArray *ranges; 55 | NSMutableArray *ranges_headers; 56 | NSString *ranges_boundry; 57 | int rangeIndex; 58 | 59 | UInt64 requestContentLength; 60 | UInt64 requestContentLengthReceived; 61 | UInt64 requestChunkSize; 62 | UInt64 requestChunkSizeReceived; 63 | 64 | NSMutableArray *responseDataSizes; 65 | } 66 | 67 | - (id)initWithAsyncSocket:(GCDAsyncSocket *)newSocket configuration:(HTTPConfig *)aConfig; 68 | 69 | - (void)start; 70 | - (void)stop; 71 | 72 | - (void)startConnection; 73 | 74 | - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path; 75 | - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path; 76 | 77 | - (BOOL)isSecureServer; 78 | - (NSArray *)sslIdentityAndCertificates; 79 | 80 | - (BOOL)isPasswordProtected:(NSString *)path; 81 | - (BOOL)useDigestAccessAuthentication; 82 | - (NSString *)realm; 83 | - (NSString *)passwordForUser:(NSString *)username; 84 | 85 | - (NSDictionary *)parseParams:(NSString *)query; 86 | - (NSDictionary *)parseGetParams; 87 | 88 | - (NSString *)requestURI; 89 | 90 | - (NSArray *)directoryIndexFileNames; 91 | - (NSString *)filePathForURI:(NSString *)path; 92 | - (NSString *)filePathForURI:(NSString *)path allowDirectory:(BOOL)allowDirectory; 93 | - (NSObject *)httpResponseForMethod:(NSString *)method URI:(NSString *)path; 94 | - (WebSocket *)webSocketForURI:(NSString *)path; 95 | 96 | - (void)prepareForBodyWithSize:(UInt64)contentLength; 97 | - (void)processBodyData:(NSData *)postDataChunk; 98 | - (void)finishBody; 99 | 100 | - (void)handleVersionNotSupported:(NSString *)version; 101 | - (void)handleAuthenticationFailed; 102 | - (void)handleResourceNotFound; 103 | - (void)handleInvalidRequest:(NSData *)data; 104 | - (void)handleUnknownMethod:(NSString *)method; 105 | 106 | - (NSData *)preprocessResponse:(HTTPMessage *)response; 107 | - (NSData *)preprocessErrorResponse:(HTTPMessage *)response; 108 | 109 | - (void)finishResponse; 110 | 111 | - (BOOL)shouldDie; 112 | - (void)die; 113 | 114 | @end 115 | 116 | @interface HTTPConnection (AsynchronousHTTPResponse) 117 | - (void)responseHasAvailableData:(NSObject *)sender; 118 | - (void)responseDidAbort:(NSObject *)sender; 119 | @end 120 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/HTTPLogging.h: -------------------------------------------------------------------------------- 1 | /** 2 | * In order to provide fast and flexible logging, this project uses Cocoa Lumberjack. 3 | * 4 | * The Google Code page has a wealth of documentation if you have any questions. 5 | * https://github.com/robbiehanson/CocoaLumberjack 6 | * 7 | * Here's what you need to know concerning how logging is setup for CocoaHTTPServer: 8 | * 9 | * There are 4 log levels: 10 | * - Error 11 | * - Warning 12 | * - Info 13 | * - Verbose 14 | * 15 | * In addition to this, there is a Trace flag that can be enabled. 16 | * When tracing is enabled, it spits out the methods that are being called. 17 | * 18 | * Please note that tracing is separate from the log levels. 19 | * For example, one could set the log level to warning, and enable tracing. 20 | * 21 | * All logging is asynchronous, except errors. 22 | * To use logging within your own custom files, follow the steps below. 23 | * 24 | * Step 1: 25 | * Import this header in your implementation file: 26 | * 27 | * #import "HTTPLogging.h" 28 | * 29 | * Step 2: 30 | * Define your logging level in your implementation file: 31 | * 32 | * // Log levels: off, error, warn, info, verbose 33 | * static const int httpLogLevel = HTTP_LOG_LEVEL_VERBOSE; 34 | * 35 | * If you wish to enable tracing, you could do something like this: 36 | * 37 | * // Debug levels: off, error, warn, info, verbose 38 | * static const int httpLogLevel = HTTP_LOG_LEVEL_INFO | HTTP_LOG_FLAG_TRACE; 39 | * 40 | * Step 3: 41 | * Replace your NSLog statements with HTTPLog statements according to the severity of the message. 42 | * 43 | * NSLog(@"Fatal error, no dohickey found!"); -> HTTPLogError(@"Fatal error, no dohickey found!"); 44 | * 45 | * HTTPLog works exactly the same as NSLog. 46 | * This means you can pass it multiple variables just like NSLog. 47 | **/ 48 | 49 | #import "DDLog.h" 50 | 51 | // Define logging context for every log message coming from the HTTP server. 52 | // The logging context can be extracted from the DDLogMessage from within the logging framework, 53 | // which gives loggers, formatters, and filters the ability to optionally process them differently. 54 | 55 | #define HTTP_LOG_CONTEXT 80 56 | 57 | // Configure log levels. 58 | 59 | #define HTTP_LOG_FLAG_ERROR (1 << 0) // 0...00001 60 | #define HTTP_LOG_FLAG_WARN (1 << 1) // 0...00010 61 | #define HTTP_LOG_FLAG_INFO (1 << 2) // 0...00100 62 | #define HTTP_LOG_FLAG_VERBOSE (1 << 3) // 0...01000 63 | 64 | #define HTTP_LOG_LEVEL_OFF 0 // 0...00000 65 | #define HTTP_LOG_LEVEL_ERROR (HTTP_LOG_LEVEL_OFF | HTTP_LOG_FLAG_ERROR) // 0...00001 66 | #define HTTP_LOG_LEVEL_WARN (HTTP_LOG_LEVEL_ERROR | HTTP_LOG_FLAG_WARN) // 0...00011 67 | #define HTTP_LOG_LEVEL_INFO (HTTP_LOG_LEVEL_WARN | HTTP_LOG_FLAG_INFO) // 0...00111 68 | #define HTTP_LOG_LEVEL_VERBOSE (HTTP_LOG_LEVEL_INFO | HTTP_LOG_FLAG_VERBOSE) // 0...01111 69 | 70 | // Setup fine grained logging. 71 | // The first 4 bits are being used by the standard log levels (0 - 3) 72 | // 73 | // We're going to add tracing, but NOT as a log level. 74 | // Tracing can be turned on and off independently of log level. 75 | 76 | #define HTTP_LOG_FLAG_TRACE (1 << 4) // 0...10000 77 | 78 | // Setup the usual boolean macros. 79 | 80 | #define HTTP_LOG_ERROR (httpLogLevel & HTTP_LOG_FLAG_ERROR) 81 | #define HTTP_LOG_WARN (httpLogLevel & HTTP_LOG_FLAG_WARN) 82 | #define HTTP_LOG_INFO (httpLogLevel & HTTP_LOG_FLAG_INFO) 83 | #define HTTP_LOG_VERBOSE (httpLogLevel & HTTP_LOG_FLAG_VERBOSE) 84 | #define HTTP_LOG_TRACE (httpLogLevel & HTTP_LOG_FLAG_TRACE) 85 | 86 | // Configure asynchronous logging. 87 | // We follow the default configuration, 88 | // but we reserve a special macro to easily disable asynchronous logging for debugging purposes. 89 | 90 | #define HTTP_LOG_ASYNC_ENABLED YES 91 | 92 | #define HTTP_LOG_ASYNC_ERROR ( NO && HTTP_LOG_ASYNC_ENABLED) 93 | #define HTTP_LOG_ASYNC_WARN (YES && HTTP_LOG_ASYNC_ENABLED) 94 | #define HTTP_LOG_ASYNC_INFO (YES && HTTP_LOG_ASYNC_ENABLED) 95 | #define HTTP_LOG_ASYNC_VERBOSE (YES && HTTP_LOG_ASYNC_ENABLED) 96 | #define HTTP_LOG_ASYNC_TRACE (YES && HTTP_LOG_ASYNC_ENABLED) 97 | 98 | // Define logging primitives. 99 | 100 | #define HTTPLogError(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_ERROR, httpLogLevel, HTTP_LOG_FLAG_ERROR, \ 101 | HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) 102 | 103 | #define HTTPLogWarn(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_WARN, httpLogLevel, HTTP_LOG_FLAG_WARN, \ 104 | HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) 105 | 106 | #define HTTPLogInfo(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_INFO, httpLogLevel, HTTP_LOG_FLAG_INFO, \ 107 | HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) 108 | 109 | #define HTTPLogVerbose(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_VERBOSE, httpLogLevel, HTTP_LOG_FLAG_VERBOSE, \ 110 | HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) 111 | 112 | #define HTTPLogTrace() LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_TRACE, httpLogLevel, HTTP_LOG_FLAG_TRACE, \ 113 | HTTP_LOG_CONTEXT, @"%@[%p]: %@", THIS_FILE, self, THIS_METHOD) 114 | 115 | #define HTTPLogTrace2(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_TRACE, httpLogLevel, HTTP_LOG_FLAG_TRACE, \ 116 | HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) 117 | 118 | 119 | #define HTTPLogCError(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_ERROR, httpLogLevel, HTTP_LOG_FLAG_ERROR, \ 120 | HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) 121 | 122 | #define HTTPLogCWarn(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_WARN, httpLogLevel, HTTP_LOG_FLAG_WARN, \ 123 | HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) 124 | 125 | #define HTTPLogCInfo(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_INFO, httpLogLevel, HTTP_LOG_FLAG_INFO, \ 126 | HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) 127 | 128 | #define HTTPLogCVerbose(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_VERBOSE, httpLogLevel, HTTP_LOG_FLAG_VERBOSE, \ 129 | HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) 130 | 131 | #define HTTPLogCTrace() LOG_C_MAYBE(HTTP_LOG_ASYNC_TRACE, httpLogLevel, HTTP_LOG_FLAG_TRACE, \ 132 | HTTP_LOG_CONTEXT, @"%@[%p]: %@", THIS_FILE, self, __FUNCTION__) 133 | 134 | #define HTTPLogCTrace2(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_TRACE, httpLogLevel, HTTP_LOG_FLAG_TRACE, \ 135 | HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) 136 | 137 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/HTTPMessage.h: -------------------------------------------------------------------------------- 1 | /** 2 | * The HTTPMessage class is a simple Objective-C wrapper around Apple's CFHTTPMessage class. 3 | **/ 4 | 5 | #import 6 | 7 | #if TARGET_OS_IPHONE 8 | // Note: You may need to add the CFNetwork Framework to your project 9 | #import 10 | #endif 11 | 12 | #define HTTPVersion1_0 ((NSString *)kCFHTTPVersion1_0) 13 | #define HTTPVersion1_1 ((NSString *)kCFHTTPVersion1_1) 14 | 15 | 16 | @interface HTTPMessage : NSObject 17 | { 18 | CFHTTPMessageRef message; 19 | } 20 | 21 | - (id)initEmptyRequest; 22 | 23 | - (id)initRequestWithMethod:(NSString *)method URL:(NSURL *)url version:(NSString *)version; 24 | 25 | - (id)initResponseWithStatusCode:(NSInteger)code description:(NSString *)description version:(NSString *)version; 26 | 27 | - (BOOL)appendData:(NSData *)data; 28 | 29 | - (BOOL)isHeaderComplete; 30 | 31 | - (NSString *)version; 32 | 33 | - (NSString *)method; 34 | - (NSURL *)url; 35 | 36 | - (NSInteger)statusCode; 37 | 38 | - (NSDictionary *)allHeaderFields; 39 | - (NSString *)headerField:(NSString *)headerField; 40 | 41 | - (void)setHeaderField:(NSString *)headerField value:(NSString *)headerFieldValue; 42 | 43 | - (NSData *)messageData; 44 | 45 | - (NSData *)body; 46 | - (void)setBody:(NSData *)body; 47 | 48 | @end 49 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/HTTPMessage.m: -------------------------------------------------------------------------------- 1 | #import "HTTPMessage.h" 2 | 3 | #if ! __has_feature(objc_arc) 4 | #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). 5 | #endif 6 | 7 | 8 | @implementation HTTPMessage 9 | 10 | - (id)initEmptyRequest 11 | { 12 | if ((self = [super init])) 13 | { 14 | message = CFHTTPMessageCreateEmpty(NULL, YES); 15 | } 16 | return self; 17 | } 18 | 19 | - (id)initRequestWithMethod:(NSString *)method URL:(NSURL *)url version:(NSString *)version 20 | { 21 | if ((self = [super init])) 22 | { 23 | message = CFHTTPMessageCreateRequest(NULL, 24 | (__bridge CFStringRef)method, 25 | (__bridge CFURLRef)url, 26 | (__bridge CFStringRef)version); 27 | } 28 | return self; 29 | } 30 | 31 | - (id)initResponseWithStatusCode:(NSInteger)code description:(NSString *)description version:(NSString *)version 32 | { 33 | if ((self = [super init])) 34 | { 35 | message = CFHTTPMessageCreateResponse(NULL, 36 | (CFIndex)code, 37 | (__bridge CFStringRef)description, 38 | (__bridge CFStringRef)version); 39 | } 40 | return self; 41 | } 42 | 43 | - (void)dealloc 44 | { 45 | if (message) 46 | { 47 | CFRelease(message); 48 | } 49 | } 50 | 51 | - (BOOL)appendData:(NSData *)data 52 | { 53 | return CFHTTPMessageAppendBytes(message, [data bytes], [data length]); 54 | } 55 | 56 | - (BOOL)isHeaderComplete 57 | { 58 | return CFHTTPMessageIsHeaderComplete(message); 59 | } 60 | 61 | - (NSString *)version 62 | { 63 | return (__bridge_transfer NSString *)CFHTTPMessageCopyVersion(message); 64 | } 65 | 66 | - (NSString *)method 67 | { 68 | return (__bridge_transfer NSString *)CFHTTPMessageCopyRequestMethod(message); 69 | } 70 | 71 | - (NSURL *)url 72 | { 73 | return (__bridge_transfer NSURL *)CFHTTPMessageCopyRequestURL(message); 74 | } 75 | 76 | - (NSInteger)statusCode 77 | { 78 | return (NSInteger)CFHTTPMessageGetResponseStatusCode(message); 79 | } 80 | 81 | - (NSDictionary *)allHeaderFields 82 | { 83 | return (__bridge_transfer NSDictionary *)CFHTTPMessageCopyAllHeaderFields(message); 84 | } 85 | 86 | - (NSString *)headerField:(NSString *)headerField 87 | { 88 | return (__bridge_transfer NSString *)CFHTTPMessageCopyHeaderFieldValue(message, (__bridge CFStringRef)headerField); 89 | } 90 | 91 | - (void)setHeaderField:(NSString *)headerField value:(NSString *)headerFieldValue 92 | { 93 | CFHTTPMessageSetHeaderFieldValue(message, 94 | (__bridge CFStringRef)headerField, 95 | (__bridge CFStringRef)headerFieldValue); 96 | } 97 | 98 | - (NSData *)messageData 99 | { 100 | return (__bridge_transfer NSData *)CFHTTPMessageCopySerializedMessage(message); 101 | } 102 | 103 | - (NSData *)body 104 | { 105 | return (__bridge_transfer NSData *)CFHTTPMessageCopyBody(message); 106 | } 107 | 108 | - (void)setBody:(NSData *)body 109 | { 110 | CFHTTPMessageSetBody(message, (__bridge CFDataRef)body); 111 | } 112 | 113 | @end 114 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/HTTPResponse.h: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | 4 | @protocol HTTPResponse 5 | 6 | /** 7 | * Returns the length of the data in bytes. 8 | * If you don't know the length in advance, implement the isChunked method and have it return YES. 9 | **/ 10 | - (UInt64)contentLength; 11 | 12 | /** 13 | * The HTTP server supports range requests in order to allow things like 14 | * file download resumption and optimized streaming on mobile devices. 15 | **/ 16 | - (UInt64)offset; 17 | - (void)setOffset:(UInt64)offset; 18 | 19 | /** 20 | * Returns the data for the response. 21 | * You do not have to return data of the exact length that is given. 22 | * You may optionally return data of a lesser length. 23 | * However, you must never return data of a greater length than requested. 24 | * Doing so could disrupt proper support for range requests. 25 | * 26 | * To support asynchronous responses, read the discussion at the bottom of this header. 27 | **/ 28 | - (NSData *)readDataOfLength:(NSUInteger)length; 29 | 30 | /** 31 | * Should only return YES after the HTTPConnection has read all available data. 32 | * That is, all data for the response has been returned to the HTTPConnection via the readDataOfLength method. 33 | **/ 34 | - (BOOL)isDone; 35 | 36 | @optional 37 | 38 | /** 39 | * If you need time to calculate any part of the HTTP response headers (status code or header fields), 40 | * this method allows you to delay sending the headers so that you may asynchronously execute the calculations. 41 | * Simply implement this method and return YES until you have everything you need concerning the headers. 42 | * 43 | * This method ties into the asynchronous response architecture of the HTTPConnection. 44 | * You should read the full discussion at the bottom of this header. 45 | * 46 | * If you return YES from this method, 47 | * the HTTPConnection will wait for you to invoke the responseHasAvailableData method. 48 | * After you do, the HTTPConnection will again invoke this method to see if the response is ready to send the headers. 49 | * 50 | * You should only delay sending the headers until you have everything you need concerning just the headers. 51 | * Asynchronously generating the body of the response is not an excuse to delay sending the headers. 52 | * Instead you should tie into the asynchronous response architecture, and use techniques such as the isChunked method. 53 | * 54 | * Important: You should read the discussion at the bottom of this header. 55 | **/ 56 | - (BOOL)delayResponseHeaders; 57 | 58 | /** 59 | * Status code for response. 60 | * Allows for responses such as redirect (301), etc. 61 | **/ 62 | - (NSInteger)status; 63 | 64 | /** 65 | * If you want to add any extra HTTP headers to the response, 66 | * simply return them in a dictionary in this method. 67 | **/ 68 | - (NSDictionary *)httpHeaders; 69 | 70 | /** 71 | * If you don't know the content-length in advance, 72 | * implement this method in your custom response class and return YES. 73 | * 74 | * Important: You should read the discussion at the bottom of this header. 75 | **/ 76 | - (BOOL)isChunked; 77 | 78 | /** 79 | * This method is called from the HTTPConnection class when the connection is closed, 80 | * or when the connection is finished with the response. 81 | * If your response is asynchronous, you should implement this method so you know not to 82 | * invoke any methods on the HTTPConnection after this method is called (as the connection may be deallocated). 83 | **/ 84 | - (void)connectionDidClose; 85 | 86 | @end 87 | 88 | 89 | /** 90 | * Important notice to those implementing custom asynchronous and/or chunked responses: 91 | * 92 | * HTTPConnection supports asynchronous responses. All you have to do in your custom response class is 93 | * asynchronously generate the response, and invoke HTTPConnection's responseHasAvailableData method. 94 | * You don't have to wait until you have all of the response ready to invoke this method. For example, if you 95 | * generate the response in incremental chunks, you could call responseHasAvailableData after generating 96 | * each chunk. Please see the HTTPAsyncFileResponse class for an example of how to do this. 97 | * 98 | * The normal flow of events for an HTTPConnection while responding to a request is like this: 99 | * - Send http resopnse headers 100 | * - Get data from response via readDataOfLength method. 101 | * - Add data to asyncSocket's write queue. 102 | * - Wait for asyncSocket to notify it that the data has been sent. 103 | * - Get more data from response via readDataOfLength method. 104 | * - ... continue this cycle until the entire response has been sent. 105 | * 106 | * With an asynchronous response, the flow is a little different. 107 | * 108 | * First the HTTPResponse is given the opportunity to postpone sending the HTTP response headers. 109 | * This allows the response to asynchronously execute any code needed to calculate a part of the header. 110 | * An example might be the response needs to generate some custom header fields, 111 | * or perhaps the response needs to look for a resource on network-attached storage. 112 | * Since the network-attached storage may be slow, the response doesn't know whether to send a 200 or 404 yet. 113 | * In situations such as this, the HTTPResponse simply implements the delayResponseHeaders method and returns YES. 114 | * After returning YES from this method, the HTTPConnection will wait until the response invokes its 115 | * responseHasAvailableData method. After this occurs, the HTTPConnection will again query the delayResponseHeaders 116 | * method to see if the response is ready to send the headers. 117 | * This cycle will continue until the delayResponseHeaders method returns NO. 118 | * 119 | * You should only delay sending the response headers until you have everything you need concerning just the headers. 120 | * Asynchronously generating the body of the response is not an excuse to delay sending the headers. 121 | * 122 | * After the response headers have been sent, the HTTPConnection calls your readDataOfLength method. 123 | * You may or may not have any available data at this point. If you don't, then simply return nil. 124 | * You should later invoke HTTPConnection's responseHasAvailableData when you have data to send. 125 | * 126 | * You don't have to keep track of when you return nil in the readDataOfLength method, or how many times you've invoked 127 | * responseHasAvailableData. Just simply call responseHasAvailableData whenever you've generated new data, and 128 | * return nil in your readDataOfLength whenever you don't have any available data in the requested range. 129 | * HTTPConnection will automatically detect when it should be requesting new data and will act appropriately. 130 | * 131 | * It's important that you also keep in mind that the HTTP server supports range requests. 132 | * The setOffset method is mandatory, and should not be ignored. 133 | * Make sure you take into account the offset within the readDataOfLength method. 134 | * You should also be aware that the HTTPConnection automatically sorts any range requests. 135 | * So if your setOffset method is called with a value of 100, then you can safely release bytes 0-99. 136 | * 137 | * HTTPConnection can also help you keep your memory footprint small. 138 | * Imagine you're dynamically generating a 10 MB response. You probably don't want to load all this data into 139 | * RAM, and sit around waiting for HTTPConnection to slowly send it out over the network. All you need to do 140 | * is pay attention to when HTTPConnection requests more data via readDataOfLength. This is because HTTPConnection 141 | * will never allow asyncSocket's write queue to get much bigger than READ_CHUNKSIZE bytes. You should 142 | * consider how you might be able to take advantage of this fact to generate your asynchronous response on demand, 143 | * while at the same time keeping your memory footprint small, and your application lightning fast. 144 | * 145 | * If you don't know the content-length in advanced, you should also implement the isChunked method. 146 | * This means the response will not include a Content-Length header, and will instead use "Transfer-Encoding: chunked". 147 | * There's a good chance that if your response is asynchronous and dynamic, it's also chunked. 148 | * If your response is chunked, you don't need to worry about range requests. 149 | **/ 150 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/HTTPServer.h: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | @class GCDAsyncSocket; 4 | @class WebSocket; 5 | 6 | #if TARGET_OS_IPHONE 7 | #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000 // iPhone 4.0 8 | #define IMPLEMENTED_PROTOCOLS 9 | #else 10 | #define IMPLEMENTED_PROTOCOLS 11 | #endif 12 | #else 13 | #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 // Mac OS X 10.6 14 | #define IMPLEMENTED_PROTOCOLS 15 | #else 16 | #define IMPLEMENTED_PROTOCOLS 17 | #endif 18 | #endif 19 | 20 | 21 | @interface HTTPServer : NSObject IMPLEMENTED_PROTOCOLS 22 | { 23 | // Underlying asynchronous TCP/IP socket 24 | GCDAsyncSocket *asyncSocket; 25 | 26 | // Dispatch queues 27 | dispatch_queue_t serverQueue; 28 | dispatch_queue_t connectionQueue; 29 | void *IsOnServerQueueKey; 30 | void *IsOnConnectionQueueKey; 31 | 32 | // HTTP server configuration 33 | NSString *documentRoot; 34 | Class connectionClass; 35 | NSString *interface; 36 | UInt16 port; 37 | 38 | // NSNetService and related variables 39 | NSNetService *netService; 40 | NSString *domain; 41 | NSString *type; 42 | NSString *name; 43 | NSString *publishedName; 44 | NSDictionary *txtRecordDictionary; 45 | 46 | // Connection management 47 | NSMutableArray *connections; 48 | NSMutableArray *webSockets; 49 | NSLock *connectionsLock; 50 | NSLock *webSocketsLock; 51 | 52 | BOOL isRunning; 53 | } 54 | 55 | /** 56 | * Specifies the document root to serve files from. 57 | * For example, if you set this to "/Users//Sites", 58 | * then it will serve files out of the local Sites directory (including subdirectories). 59 | * 60 | * The default value is nil. 61 | * The default server configuration will not serve any files until this is set. 62 | * 63 | * If you change the documentRoot while the server is running, 64 | * the change will affect future incoming http connections. 65 | **/ 66 | - (NSString *)documentRoot; 67 | - (void)setDocumentRoot:(NSString *)value; 68 | 69 | /** 70 | * The connection class is the class used to handle incoming HTTP connections. 71 | * 72 | * The default value is [HTTPConnection class]. 73 | * You can override HTTPConnection, and then set this to [MyHTTPConnection class]. 74 | * 75 | * If you change the connectionClass while the server is running, 76 | * the change will affect future incoming http connections. 77 | **/ 78 | - (Class)connectionClass; 79 | - (void)setConnectionClass:(Class)value; 80 | 81 | /** 82 | * Set what interface you'd like the server to listen on. 83 | * By default this is nil, which causes the server to listen on all available interfaces like en1, wifi etc. 84 | * 85 | * The interface may be specified by name (e.g. "en1" or "lo0") or by IP address (e.g. "192.168.4.34"). 86 | * You may also use the special strings "localhost" or "loopback" to specify that 87 | * the socket only accept connections from the local machine. 88 | **/ 89 | - (NSString *)interface; 90 | - (void)setInterface:(NSString *)value; 91 | 92 | /** 93 | * The port number to run the HTTP server on. 94 | * 95 | * The default port number is zero, meaning the server will automatically use any available port. 96 | * This is the recommended port value, as it avoids possible port conflicts with other applications. 97 | * Technologies such as Bonjour can be used to allow other applications to automatically discover the port number. 98 | * 99 | * Note: As is common on most OS's, you need root privledges to bind to port numbers below 1024. 100 | * 101 | * You can change the port property while the server is running, but it won't affect the running server. 102 | * To actually change the port the server is listening for connections on you'll need to restart the server. 103 | * 104 | * The listeningPort method will always return the port number the running server is listening for connections on. 105 | * If the server is not running this method returns 0. 106 | **/ 107 | - (UInt16)port; 108 | - (UInt16)listeningPort; 109 | - (void)setPort:(UInt16)value; 110 | 111 | /** 112 | * Bonjour domain for publishing the service. 113 | * The default value is "local.". 114 | * 115 | * Note: Bonjour publishing requires you set a type. 116 | * 117 | * If you change the domain property after the bonjour service has already been published (server already started), 118 | * you'll need to invoke the republishBonjour method to update the broadcasted bonjour service. 119 | **/ 120 | - (NSString *)domain; 121 | - (void)setDomain:(NSString *)value; 122 | 123 | /** 124 | * Bonjour name for publishing the service. 125 | * The default value is "". 126 | * 127 | * If using an empty string ("") for the service name when registering, 128 | * the system will automatically use the "Computer Name". 129 | * Using an empty string will also handle name conflicts 130 | * by automatically appending a digit to the end of the name. 131 | * 132 | * Note: Bonjour publishing requires you set a type. 133 | * 134 | * If you change the name after the bonjour service has already been published (server already started), 135 | * you'll need to invoke the republishBonjour method to update the broadcasted bonjour service. 136 | * 137 | * The publishedName method will always return the actual name that was published via the bonjour service. 138 | * If the service is not running this method returns nil. 139 | **/ 140 | - (NSString *)name; 141 | - (NSString *)publishedName; 142 | - (void)setName:(NSString *)value; 143 | 144 | /** 145 | * Bonjour type for publishing the service. 146 | * The default value is nil. 147 | * The service will not be published via bonjour unless the type is set. 148 | * 149 | * If you wish to publish the service as a traditional HTTP server, you should set the type to be "_http._tcp.". 150 | * 151 | * If you change the type after the bonjour service has already been published (server already started), 152 | * you'll need to invoke the republishBonjour method to update the broadcasted bonjour service. 153 | **/ 154 | - (NSString *)type; 155 | - (void)setType:(NSString *)value; 156 | 157 | /** 158 | * Republishes the service via bonjour if the server is running. 159 | * If the service was not previously published, this method will publish it (if the server is running). 160 | **/ 161 | - (void)republishBonjour; 162 | 163 | /** 164 | * 165 | **/ 166 | - (NSDictionary *)TXTRecordDictionary; 167 | - (void)setTXTRecordDictionary:(NSDictionary *)dict; 168 | 169 | /** 170 | * Attempts to starts the server on the configured port, interface, etc. 171 | * 172 | * If an error occurs, this method returns NO and sets the errPtr (if given). 173 | * Otherwise returns YES on success. 174 | * 175 | * Some examples of errors that might occur: 176 | * - You specified the server listen on a port which is already in use by another application. 177 | * - You specified the server listen on a port number below 1024, which requires root priviledges. 178 | * 179 | * Code Example: 180 | * 181 | * NSError *err = nil; 182 | * if (![httpServer start:&err]) 183 | * { 184 | * NSLog(@"Error starting http server: %@", err); 185 | * } 186 | **/ 187 | - (BOOL)start:(NSError **)errPtr; 188 | 189 | /** 190 | * Stops the server, preventing it from accepting any new connections. 191 | * You may specify whether or not you want to close the existing client connections. 192 | * 193 | * The default stop method (with no arguments) will close any existing connections. (It invokes [self stop:NO]) 194 | **/ 195 | - (void)stop; 196 | - (void)stop:(BOOL)keepExistingConnections; 197 | 198 | - (BOOL)isRunning; 199 | 200 | - (void)addWebSocket:(WebSocket *)ws; 201 | 202 | - (NSUInteger)numberOfHTTPConnections; 203 | - (NSUInteger)numberOfWebSocketConnections; 204 | 205 | @end 206 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Mime/MultipartFormDataParser.h: -------------------------------------------------------------------------------- 1 | 2 | #import "MultipartMessageHeader.h" 3 | 4 | /* 5 | Part one: http://tools.ietf.org/html/rfc2045 (Format of Internet Message Bodies) 6 | Part two: http://tools.ietf.org/html/rfc2046 (Media Types) 7 | Part three: http://tools.ietf.org/html/rfc2047 (Message Header Extensions for Non-ASCII Text) 8 | Part four: http://tools.ietf.org/html/rfc4289 (Registration Procedures) 9 | Part five: http://tools.ietf.org/html/rfc2049 (Conformance Criteria and Examples) 10 | 11 | Internet message format: http://tools.ietf.org/html/rfc2822 12 | 13 | Multipart/form-data http://tools.ietf.org/html/rfc2388 14 | */ 15 | 16 | @class MultipartFormDataParser; 17 | 18 | //----------------------------------------------------------------- 19 | // protocol MultipartFormDataParser 20 | //----------------------------------------------------------------- 21 | 22 | @protocol MultipartFormDataParserDelegate 23 | @optional 24 | - (void) processContent:(NSData*) data WithHeader:(MultipartMessageHeader*) header; 25 | - (void) processEndOfPartWithHeader:(MultipartMessageHeader*) header; 26 | - (void) processPreambleData:(NSData*) data; 27 | - (void) processEpilogueData:(NSData*) data; 28 | - (void) processStartOfPartWithHeader:(MultipartMessageHeader*) header; 29 | @end 30 | 31 | //----------------------------------------------------------------- 32 | // interface MultipartFormDataParser 33 | //----------------------------------------------------------------- 34 | 35 | @interface MultipartFormDataParser : NSObject { 36 | NSMutableData* pendingData; 37 | NSData* boundaryData; 38 | MultipartMessageHeader* currentHeader; 39 | 40 | BOOL waitingForCRLF; 41 | BOOL reachedEpilogue; 42 | BOOL processedPreamble; 43 | BOOL checkForContentEnd; 44 | 45 | #if __has_feature(objc_arc_weak) 46 | __weak id delegate; 47 | #else 48 | __unsafe_unretained id delegate; 49 | #endif 50 | int currentEncoding; 51 | NSStringEncoding formEncoding; 52 | } 53 | 54 | - (BOOL) appendData:(NSData*) data; 55 | 56 | - (id) initWithBoundary:(NSString*) boundary formEncoding:(NSStringEncoding) formEncoding; 57 | 58 | #if __has_feature(objc_arc_weak) 59 | @property(weak, readwrite) id delegate; 60 | #else 61 | @property(unsafe_unretained, readwrite) id delegate; 62 | #endif 63 | @property(readwrite) NSStringEncoding formEncoding; 64 | 65 | @end 66 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Mime/MultipartFormDataParser.m: -------------------------------------------------------------------------------- 1 | 2 | #import "MultipartFormDataParser.h" 3 | #import "DDData.h" 4 | #import "HTTPLogging.h" 5 | 6 | #pragma mark log level 7 | 8 | #ifdef DEBUG 9 | static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; 10 | #else 11 | static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; 12 | #endif 13 | 14 | #ifdef __x86_64__ 15 | #define FMTNSINT "li" 16 | #else 17 | #define FMTNSINT "i" 18 | #endif 19 | 20 | 21 | //----------------------------------------------------------------- 22 | // interface MultipartFormDataParser (private) 23 | //----------------------------------------------------------------- 24 | 25 | 26 | @interface MultipartFormDataParser (private) 27 | + (NSData*) decodedDataFromData:(NSData*) data encoding:(int) encoding; 28 | 29 | - (int) findHeaderEnd:(NSData*) workingData fromOffset:(int) offset; 30 | - (int) findContentEnd:(NSData*) data fromOffset:(int) offset; 31 | 32 | - (int) numberOfBytesToLeavePendingWithData:(NSData*) data length:(NSUInteger) length encoding:(int) encoding; 33 | - (int) offsetTillNewlineSinceOffset:(int) offset inData:(NSData*) data; 34 | 35 | - (int) processPreamble:(NSData*) workingData; 36 | 37 | @end 38 | 39 | 40 | //----------------------------------------------------------------- 41 | // implementation MultipartFormDataParser 42 | //----------------------------------------------------------------- 43 | 44 | 45 | @implementation MultipartFormDataParser 46 | @synthesize delegate,formEncoding; 47 | 48 | - (id) initWithBoundary:(NSString*) boundary formEncoding:(NSStringEncoding) _formEncoding { 49 | if( nil == (self = [super init]) ){ 50 | return self; 51 | } 52 | if( nil == boundary ) { 53 | HTTPLogWarn(@"MultipartFormDataParser: init with zero boundary"); 54 | return nil; 55 | } 56 | boundaryData = [[@"\r\n--" stringByAppendingString:boundary] dataUsingEncoding:NSASCIIStringEncoding]; 57 | 58 | pendingData = [[NSMutableData alloc] init]; 59 | currentEncoding = contentTransferEncoding_binary; 60 | currentHeader = nil; 61 | 62 | formEncoding = _formEncoding; 63 | reachedEpilogue = NO; 64 | processedPreamble = NO; 65 | 66 | return self; 67 | } 68 | 69 | 70 | - (BOOL) appendData:(NSData *)data { 71 | // Can't parse without boundary; 72 | if( nil == boundaryData ) { 73 | HTTPLogError(@"MultipartFormDataParser: Trying to parse multipart without specifying a valid boundary"); 74 | assert(false); 75 | return NO; 76 | } 77 | NSData* workingData = data; 78 | 79 | if( pendingData.length ) { 80 | [pendingData appendData:data]; 81 | workingData = pendingData; 82 | } 83 | 84 | // the parser saves parse stat in the offset variable, which indicates offset of unhandled part in 85 | // currently received chunk. Before returning, we always drop all data up to offset, leaving 86 | // only unhandled for the next call 87 | 88 | int offset = 0; 89 | 90 | // don't parse data unless its size is greater then boundary length, so we couldn't 91 | // misfind the boundary, if it got split into different data chunks 92 | NSUInteger sizeToLeavePending = boundaryData.length; 93 | 94 | if( !reachedEpilogue && workingData.length <= sizeToLeavePending ) { 95 | // not enough data even to start parsing. 96 | // save to pending data. 97 | if( !pendingData.length ) { 98 | [pendingData appendData:data]; 99 | } 100 | if( checkForContentEnd ) { 101 | if( pendingData.length >= 2 ) { 102 | if( *(uint16_t*)(pendingData.bytes + offset) == 0x2D2D ) { 103 | // we found the multipart end. all coming next is an epilogue. 104 | HTTPLogVerbose(@"MultipartFormDataParser: End of multipart message"); 105 | waitingForCRLF = YES; 106 | reachedEpilogue = YES; 107 | offset+= 2; 108 | } 109 | else { 110 | checkForContentEnd = NO; 111 | waitingForCRLF = YES; 112 | return YES; 113 | } 114 | } else { 115 | return YES; 116 | } 117 | 118 | } 119 | else { 120 | return YES; 121 | } 122 | } 123 | while( true ) { 124 | if( checkForContentEnd ) { 125 | // the flag will be raised to check if the last part was the last one. 126 | if( offset < workingData.length -1 ) { 127 | char* bytes = (char*) workingData.bytes; 128 | if( *(uint16_t*)(bytes + offset) == 0x2D2D ) { 129 | // we found the multipart end. all coming next is an epilogue. 130 | HTTPLogVerbose(@"MultipartFormDataParser: End of multipart message"); 131 | checkForContentEnd = NO; 132 | reachedEpilogue = YES; 133 | // still wait for CRLF, that comes after boundary, but before epilogue. 134 | waitingForCRLF = YES; 135 | offset += 2; 136 | } 137 | else { 138 | // it's not content end, we have to wait till separator line end before next part comes 139 | waitingForCRLF = YES; 140 | checkForContentEnd = NO; 141 | } 142 | } 143 | else { 144 | // we haven't got enough data to check for content end. 145 | // save current unhandled data (it may be 1 byte) to pending and recheck on next chunk received 146 | if( offset < workingData.length ) { 147 | [pendingData setData:[NSData dataWithBytes:workingData.bytes + workingData.length-1 length:1]]; 148 | } 149 | else { 150 | // there is no unhandled data now, wait for more chunks 151 | [pendingData setData:[NSData data]]; 152 | } 153 | return YES; 154 | } 155 | } 156 | if( waitingForCRLF ) { 157 | 158 | // the flag will be raised in the code below, meaning, we've read the boundary, but 159 | // didnt find the end of boundary line yet. 160 | 161 | offset = [self offsetTillNewlineSinceOffset:offset inData:workingData]; 162 | if( -1 == offset ) { 163 | // didnt find the endl again. 164 | if( offset ) { 165 | // we still have to save the unhandled data (maybe it's 1 byte CR) 166 | if( *((char*)workingData.bytes + workingData.length -1) == '\r' ) { 167 | [pendingData setData:[NSData dataWithBytes:workingData.bytes + workingData.length-1 length:1]]; 168 | } 169 | else { 170 | // or save nothing if it wasnt 171 | [pendingData setData:[NSData data]]; 172 | } 173 | } 174 | return YES; 175 | } 176 | waitingForCRLF = NO; 177 | } 178 | if( !processedPreamble ) { 179 | // got to find the first boundary before the actual content begins. 180 | offset = [self processPreamble:workingData]; 181 | // wait for more data for preamble 182 | if( -1 == offset ) 183 | return YES; 184 | // invoke continue to skip newline after boundary. 185 | continue; 186 | } 187 | 188 | if( reachedEpilogue ) { 189 | // parse all epilogue data to delegate. 190 | if( [delegate respondsToSelector:@selector(processEpilogueData:)] ) { 191 | NSData* epilogueData = [NSData dataWithBytesNoCopy: (char*) workingData.bytes + offset length: workingData.length - offset freeWhenDone:NO]; 192 | [delegate processEpilogueData: epilogueData]; 193 | } 194 | return YES; 195 | } 196 | 197 | if( nil == currentHeader ) { 198 | // nil == currentHeader is a state flag, indicating we are waiting for header now. 199 | // whenever part is over, currentHeader is set to nil. 200 | 201 | // try to find CRLFCRLF bytes in the data, which indicates header end. 202 | // we won't parse header parts, as they won't be too large. 203 | int headerEnd = [self findHeaderEnd:workingData fromOffset:offset]; 204 | if( -1 == headerEnd ) { 205 | // didn't recieve the full header yet. 206 | if( !pendingData.length) { 207 | // store the unprocessed data till next chunks come 208 | [pendingData appendBytes:data.bytes + offset length:data.length - offset]; 209 | } 210 | else { 211 | if( offset ) { 212 | // save the current parse state; drop all handled data and save unhandled only. 213 | pendingData = [[NSMutableData alloc] initWithBytes: (char*) workingData.bytes + offset length:workingData.length - offset]; 214 | } 215 | } 216 | return YES; 217 | } 218 | else { 219 | 220 | // let the header parser do it's job from now on. 221 | NSData * headerData = [NSData dataWithBytesNoCopy: (char*) workingData.bytes + offset length:headerEnd + 2 - offset freeWhenDone:NO]; 222 | currentHeader = [[MultipartMessageHeader alloc] initWithData:headerData formEncoding:formEncoding]; 223 | 224 | if( nil == currentHeader ) { 225 | // we've found the data is in wrong format. 226 | HTTPLogError(@"MultipartFormDataParser: MultipartFormDataParser: wrong input format, coulnd't get a valid header"); 227 | return NO; 228 | } 229 | if( [delegate respondsToSelector:@selector(processStartOfPartWithHeader:)] ) { 230 | [delegate processStartOfPartWithHeader:currentHeader]; 231 | } 232 | 233 | HTTPLogVerbose(@"MultipartFormDataParser: MultipartFormDataParser: Retrieved part header."); 234 | } 235 | // skip the two trailing \r\n, in addition to the whole header. 236 | offset = headerEnd + 4; 237 | } 238 | // after we've got the header, we try to 239 | // find the boundary in the data. 240 | int contentEnd = [self findContentEnd:workingData fromOffset:offset]; 241 | 242 | if( contentEnd == -1 ) { 243 | 244 | // this case, we didn't find the boundary, so the data is related to the current part. 245 | // we leave the sizeToLeavePending amount of bytes to make sure we don't include 246 | // boundary part in processed data. 247 | NSUInteger sizeToPass = workingData.length - offset - sizeToLeavePending; 248 | 249 | // if we parse BASE64 encoded data, or Quoted-Printable data, we will make sure we don't break the format 250 | int leaveTrailing = [self numberOfBytesToLeavePendingWithData:data length:sizeToPass encoding:currentEncoding]; 251 | sizeToPass -= leaveTrailing; 252 | 253 | if( sizeToPass <= 0 ) { 254 | // wait for more data! 255 | if( offset ) { 256 | [pendingData setData:[NSData dataWithBytes:(char*) workingData.bytes + offset length:workingData.length - offset]]; 257 | } 258 | return YES; 259 | } 260 | // decode the chunk and let the delegate use it (store in a file, for example) 261 | NSData* decodedData = [MultipartFormDataParser decodedDataFromData:[NSData dataWithBytesNoCopy:(char*)workingData.bytes + offset length:workingData.length - offset - sizeToLeavePending freeWhenDone:NO] encoding:currentEncoding]; 262 | 263 | if( [delegate respondsToSelector:@selector(processContent:WithHeader:)] ) { 264 | HTTPLogVerbose(@"MultipartFormDataParser: Processed %"FMTNSINT" bytes of body",sizeToPass); 265 | 266 | [delegate processContent: decodedData WithHeader:currentHeader]; 267 | } 268 | 269 | // store the unprocessed data till the next chunks come. 270 | [pendingData setData:[NSData dataWithBytes:(char*)workingData.bytes + workingData.length - sizeToLeavePending length:sizeToLeavePending]]; 271 | return YES; 272 | } 273 | else { 274 | 275 | // Here we found the boundary. 276 | // let the delegate process it, and continue going to the next parts. 277 | if( [delegate respondsToSelector:@selector(processContent:WithHeader:)] ) { 278 | [delegate processContent:[NSData dataWithBytesNoCopy:(char*) workingData.bytes + offset length:contentEnd - offset freeWhenDone:NO] WithHeader:currentHeader]; 279 | } 280 | 281 | if( [delegate respondsToSelector:@selector(processEndOfPartWithHeader:)] ){ 282 | [delegate processEndOfPartWithHeader:currentHeader]; 283 | HTTPLogVerbose(@"MultipartFormDataParser: End of body part"); 284 | } 285 | currentHeader = nil; 286 | 287 | // set up offset to continue with the remaining data (if any) 288 | // cast to int because above comment suggests a small number 289 | offset = contentEnd + (int)boundaryData.length; 290 | checkForContentEnd = YES; 291 | // setting the flag tells the parser to skip all the data till CRLF 292 | } 293 | } 294 | return YES; 295 | } 296 | 297 | 298 | //----------------------------------------------------------------- 299 | #pragma mark private methods 300 | 301 | - (int) offsetTillNewlineSinceOffset:(int) offset inData:(NSData*) data { 302 | char* bytes = (char*) data.bytes; 303 | NSUInteger length = data.length; 304 | if( offset >= length - 1 ) 305 | return -1; 306 | 307 | while ( *(uint16_t*)(bytes + offset) != 0x0A0D ) { 308 | // find the trailing \r\n after the boundary. The boundary line might have any number of whitespaces before CRLF, according to rfc2046 309 | 310 | // in debug, we might also want to know, if the file is somehow misformatted. 311 | #ifdef DEBUG 312 | if( !isspace(*(bytes+offset)) ) { 313 | HTTPLogWarn(@"MultipartFormDataParser: Warning, non-whitespace character '%c' between boundary bytes and CRLF in boundary line",*(bytes+offset) ); 314 | } 315 | if( !isspace(*(bytes+offset+1)) ) { 316 | HTTPLogWarn(@"MultipartFormDataParser: Warning, non-whitespace character '%c' between boundary bytes and CRLF in boundary line",*(bytes+offset+1) ); 317 | } 318 | #endif 319 | offset++; 320 | if( offset >= length ) { 321 | // no endl found within current data 322 | return -1; 323 | } 324 | } 325 | 326 | offset += 2; 327 | return offset; 328 | } 329 | 330 | 331 | - (int) processPreamble:(NSData*) data { 332 | int offset = 0; 333 | 334 | char* boundaryBytes = (char*) boundaryData.bytes + 2; // the first boundary won't have CRLF preceding. 335 | char* dataBytes = (char*) data.bytes; 336 | NSUInteger boundaryLength = boundaryData.length - 2; 337 | NSUInteger dataLength = data.length; 338 | 339 | // find the boundary without leading CRLF. 340 | while( offset < dataLength - boundaryLength +1 ) { 341 | int i; 342 | for( i = 0;i < boundaryLength; i++ ) { 343 | if( boundaryBytes[i] != dataBytes[offset + i] ) 344 | break; 345 | } 346 | if( i == boundaryLength ) { 347 | break; 348 | } 349 | offset++; 350 | } 351 | 352 | if( offset == dataLength ) { 353 | // the end of preamble wasn't found in this chunk 354 | NSUInteger sizeToProcess = dataLength - boundaryLength; 355 | if( sizeToProcess > 0) { 356 | if( [delegate respondsToSelector:@selector(processPreambleData:)] ) { 357 | NSData* preambleData = [NSData dataWithBytesNoCopy: (char*) data.bytes length: data.length - offset - boundaryLength freeWhenDone:NO]; 358 | [delegate processPreambleData:preambleData]; 359 | HTTPLogVerbose(@"MultipartFormDataParser: processed preamble"); 360 | } 361 | pendingData = [NSMutableData dataWithBytes: data.bytes + data.length - boundaryLength length:boundaryLength]; 362 | } 363 | return -1; 364 | } 365 | else { 366 | if ( offset && [delegate respondsToSelector:@selector(processPreambleData:)] ) { 367 | NSData* preambleData = [NSData dataWithBytesNoCopy: (char*) data.bytes length: offset freeWhenDone:NO]; 368 | [delegate processPreambleData:preambleData]; 369 | } 370 | offset +=boundaryLength; 371 | // tells to skip CRLF after the boundary. 372 | processedPreamble = YES; 373 | waitingForCRLF = YES; 374 | } 375 | return offset; 376 | } 377 | 378 | 379 | 380 | - (int) findHeaderEnd:(NSData*) workingData fromOffset:(int)offset { 381 | char* bytes = (char*) workingData.bytes; 382 | NSUInteger inputLength = workingData.length; 383 | uint16_t separatorBytes = 0x0A0D; 384 | 385 | while( true ) { 386 | if(inputLength < offset + 3 ) { 387 | // wait for more data 388 | return -1; 389 | } 390 | if( (*((uint16_t*) (bytes+offset)) == separatorBytes) && (*((uint16_t*) (bytes+offset)+1) == separatorBytes) ) { 391 | return offset; 392 | } 393 | offset++; 394 | } 395 | return -1; 396 | } 397 | 398 | 399 | - (int) findContentEnd:(NSData*) data fromOffset:(int) offset { 400 | char* boundaryBytes = (char*) boundaryData.bytes; 401 | char* dataBytes = (char*) data.bytes; 402 | NSUInteger boundaryLength = boundaryData.length; 403 | NSUInteger dataLength = data.length; 404 | 405 | while( offset < dataLength - boundaryLength +1 ) { 406 | int i; 407 | for( i = 0;i < boundaryLength; i++ ) { 408 | if( boundaryBytes[i] != dataBytes[offset + i] ) 409 | break; 410 | } 411 | if( i == boundaryLength ) { 412 | return offset; 413 | } 414 | offset++; 415 | } 416 | return -1; 417 | } 418 | 419 | 420 | - (int) numberOfBytesToLeavePendingWithData:(NSData*) data length:(int) length encoding:(int) encoding { 421 | // If we have BASE64 or Quoted-Printable encoded data, we have to be sure 422 | // we don't break the format. 423 | int sizeToLeavePending = 0; 424 | 425 | if( encoding == contentTransferEncoding_base64 ) { 426 | char* bytes = (char*) data.bytes; 427 | int i; 428 | for( i = length - 1; i > 0; i++ ) { 429 | if( * (uint16_t*) (bytes + i) == 0x0A0D ) { 430 | break; 431 | } 432 | } 433 | // now we've got to be sure that the length of passed data since last line 434 | // is multiplier of 4. 435 | sizeToLeavePending = (length - i) & ~0x11; // size to leave pending = length-i - (length-i) %4; 436 | return sizeToLeavePending; 437 | } 438 | 439 | if( encoding == contentTransferEncoding_quotedPrintable ) { 440 | // we don't pass more less then 3 bytes anyway. 441 | if( length <= 2 ) 442 | return length; 443 | // check the last bytes to be start of encoded symbol. 444 | const char* bytes = data.bytes + length - 2; 445 | if( bytes[0] == '=' ) 446 | return 2; 447 | if( bytes[1] == '=' ) 448 | return 1; 449 | return 0; 450 | } 451 | return 0; 452 | } 453 | 454 | 455 | //----------------------------------------------------------------- 456 | #pragma mark decoding 457 | 458 | 459 | + (NSData*) decodedDataFromData:(NSData*) data encoding:(int) encoding { 460 | switch (encoding) { 461 | case contentTransferEncoding_base64: { 462 | return [data base64Decoded]; 463 | } break; 464 | 465 | case contentTransferEncoding_quotedPrintable: { 466 | return [self decodedDataFromQuotedPrintableData:data]; 467 | } break; 468 | 469 | default: { 470 | return data; 471 | } break; 472 | } 473 | } 474 | 475 | 476 | + (NSData*) decodedDataFromQuotedPrintableData:(NSData *)data { 477 | // http://tools.ietf.org/html/rfc2045#section-6.7 478 | 479 | const char hex [] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', }; 480 | 481 | NSMutableData* result = [[NSMutableData alloc] initWithLength:data.length]; 482 | const char* bytes = (const char*) data.bytes; 483 | int count = 0; 484 | NSUInteger length = data.length; 485 | while( count < length ) { 486 | if( bytes[count] == '=' ) { 487 | [result appendBytes:bytes length:count]; 488 | bytes = bytes + count + 1; 489 | length -= count + 1; 490 | count = 0; 491 | 492 | if( length < 3 ) { 493 | HTTPLogWarn(@"MultipartFormDataParser: warning, trailing '=' in quoted printable data"); 494 | } 495 | // soft newline 496 | if( bytes[0] == '\r' ) { 497 | bytes += 1; 498 | if(bytes[1] == '\n' ) { 499 | bytes += 2; 500 | } 501 | continue; 502 | } 503 | char encodedByte = 0; 504 | 505 | for( int i = 0; i < sizeof(hex); i++ ) { 506 | if( hex[i] == bytes[0] ) { 507 | encodedByte += i << 4; 508 | } 509 | if( hex[i] == bytes[1] ) { 510 | encodedByte += i; 511 | } 512 | } 513 | [result appendBytes:&encodedByte length:1]; 514 | bytes += 2; 515 | } 516 | 517 | #ifdef DEBUG 518 | if( (unsigned char) bytes[count] > 126 ) { 519 | HTTPLogWarn(@"MultipartFormDataParser: Warning, character with code above 126 appears in quoted printable encoded data"); 520 | } 521 | #endif 522 | 523 | count++; 524 | } 525 | return result; 526 | } 527 | 528 | 529 | @end 530 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Mime/MultipartMessageHeader.h: -------------------------------------------------------------------------------- 1 | // 2 | // MultipartMessagePart.h 3 | // HttpServer 4 | // 5 | // Created by Валерий Гаврилов on 29.03.12. 6 | // Copyright (c) 2012 LLC "Online Publishing Partners" (onlinepp.ru). All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | 12 | //----------------------------------------------------------------- 13 | // interface MultipartMessageHeader 14 | //----------------------------------------------------------------- 15 | enum { 16 | contentTransferEncoding_unknown, 17 | contentTransferEncoding_7bit, 18 | contentTransferEncoding_8bit, 19 | contentTransferEncoding_binary, 20 | contentTransferEncoding_base64, 21 | contentTransferEncoding_quotedPrintable, 22 | }; 23 | 24 | @interface MultipartMessageHeader : NSObject { 25 | NSMutableDictionary* fields; 26 | int encoding; 27 | NSString* contentDispositionName; 28 | } 29 | @property (strong,readonly) NSDictionary* fields; 30 | @property (readonly) int encoding; 31 | 32 | - (id) initWithData:(NSData*) data formEncoding:(NSStringEncoding) encoding; 33 | @end 34 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Mime/MultipartMessageHeader.m: -------------------------------------------------------------------------------- 1 | // 2 | // MultipartMessagePart.m 3 | // HttpServer 4 | // 5 | // Created by Валерий Гаврилов on 29.03.12. 6 | // Copyright (c) 2012 LLC "Online Publishing Partners" (onlinepp.ru). All rights reserved. 7 | 8 | #import "MultipartMessageHeader.h" 9 | #import "MultipartMessageHeaderField.h" 10 | 11 | #import "HTTPLogging.h" 12 | 13 | //----------------------------------------------------------------- 14 | #pragma mark log level 15 | 16 | #ifdef DEBUG 17 | static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; 18 | #else 19 | static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; 20 | #endif 21 | 22 | //----------------------------------------------------------------- 23 | // implementation MultipartMessageHeader 24 | //----------------------------------------------------------------- 25 | 26 | 27 | @implementation MultipartMessageHeader 28 | @synthesize fields,encoding; 29 | 30 | 31 | - (id) initWithData:(NSData *)data formEncoding:(NSStringEncoding) formEncoding { 32 | if( nil == (self = [super init]) ) { 33 | return self; 34 | } 35 | 36 | fields = [[NSMutableDictionary alloc] initWithCapacity:1]; 37 | 38 | // In case encoding is not mentioned, 39 | encoding = contentTransferEncoding_unknown; 40 | 41 | char* bytes = (char*)data.bytes; 42 | NSUInteger length = data.length; 43 | int offset = 0; 44 | 45 | // split header into header fields, separated by \r\n 46 | uint16_t fields_separator = 0x0A0D; // \r\n 47 | while( offset < length - 2 ) { 48 | 49 | // the !isspace condition is to support header unfolding 50 | if( (*(uint16_t*) (bytes+offset) == fields_separator) && ((offset == length - 2) || !(isspace(bytes[offset+2])) )) { 51 | NSData* fieldData = [NSData dataWithBytesNoCopy:bytes length:offset freeWhenDone:NO]; 52 | MultipartMessageHeaderField* field = [[MultipartMessageHeaderField alloc] initWithData: fieldData contentEncoding:formEncoding]; 53 | if( field ) { 54 | [fields setObject:field forKey:field.name]; 55 | HTTPLogVerbose(@"MultipartFormDataParser: Processed Header field '%@'",field.name); 56 | } 57 | else { 58 | NSString* fieldStr = [[NSString alloc] initWithData:fieldData encoding:NSASCIIStringEncoding]; 59 | HTTPLogWarn(@"MultipartFormDataParser: Failed to parse MIME header field. Input ASCII string:%@",fieldStr); 60 | } 61 | 62 | // move to the next header field 63 | bytes += offset + 2; 64 | length -= offset + 2; 65 | offset = 0; 66 | continue; 67 | } 68 | ++ offset; 69 | } 70 | 71 | if( !fields.count ) { 72 | // it was an empty header. 73 | // we have to set default values. 74 | // default header. 75 | [fields setObject:@"text/plain" forKey:@"Content-Type"]; 76 | } 77 | 78 | return self; 79 | } 80 | 81 | - (NSString *)description { 82 | return [NSString stringWithFormat:@"%@",fields]; 83 | } 84 | 85 | 86 | @end 87 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Mime/MultipartMessageHeaderField.h: -------------------------------------------------------------------------------- 1 | 2 | #import 3 | 4 | //----------------------------------------------------------------- 5 | // interface MultipartMessageHeaderField 6 | //----------------------------------------------------------------- 7 | 8 | @interface MultipartMessageHeaderField : NSObject { 9 | NSString* name; 10 | NSString* value; 11 | NSMutableDictionary* params; 12 | } 13 | 14 | @property (strong, readonly) NSString* value; 15 | @property (strong, readonly) NSDictionary* params; 16 | @property (strong, readonly) NSString* name; 17 | 18 | //- (id) initWithLine:(NSString*) line; 19 | //- (id) initWithName:(NSString*) paramName value:(NSString*) paramValue; 20 | 21 | - (id) initWithData:(NSData*) data contentEncoding:(NSStringEncoding) encoding; 22 | 23 | @end 24 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Mime/MultipartMessageHeaderField.m: -------------------------------------------------------------------------------- 1 | 2 | #import "MultipartMessageHeaderField.h" 3 | #import "HTTPLogging.h" 4 | 5 | //----------------------------------------------------------------- 6 | #pragma mark log level 7 | 8 | #ifdef DEBUG 9 | static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; 10 | #else 11 | static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; 12 | #endif 13 | 14 | 15 | // helpers 16 | int findChar(const char* str,NSUInteger length, char c); 17 | NSString* extractParamValue(const char* bytes, NSUInteger length, NSStringEncoding encoding); 18 | 19 | //----------------------------------------------------------------- 20 | // interface MultipartMessageHeaderField (private) 21 | //----------------------------------------------------------------- 22 | 23 | 24 | @interface MultipartMessageHeaderField (private) 25 | -(BOOL) parseHeaderValueBytes:(char*) bytes length:(NSUInteger) length encoding:(NSStringEncoding) encoding; 26 | @end 27 | 28 | 29 | //----------------------------------------------------------------- 30 | // implementation MultipartMessageHeaderField 31 | //----------------------------------------------------------------- 32 | 33 | @implementation MultipartMessageHeaderField 34 | @synthesize name,value,params; 35 | 36 | - (id) initWithData:(NSData *)data contentEncoding:(NSStringEncoding)encoding { 37 | params = [[NSMutableDictionary alloc] initWithCapacity:1]; 38 | 39 | char* bytes = (char*)data.bytes; 40 | NSUInteger length = data.length; 41 | 42 | int separatorOffset = findChar(bytes, length, ':'); 43 | if( (-1 == separatorOffset) || (separatorOffset >= length-2) ) { 44 | HTTPLogError(@"MultipartFormDataParser: Bad format.No colon in field header."); 45 | // tear down 46 | return nil; 47 | } 48 | 49 | // header name is always ascii encoded; 50 | name = [[NSString alloc] initWithBytes: bytes length: separatorOffset encoding: NSASCIIStringEncoding]; 51 | if( nil == name ) { 52 | HTTPLogError(@"MultipartFormDataParser: Bad MIME header name."); 53 | // tear down 54 | return nil; 55 | } 56 | 57 | // skip the separator and the next ' ' symbol 58 | bytes += separatorOffset + 2; 59 | length -= separatorOffset + 2; 60 | 61 | separatorOffset = findChar(bytes, length, ';'); 62 | if( separatorOffset == -1 ) { 63 | // couldn't find ';', means we don't have extra params here. 64 | value = [[NSString alloc] initWithBytes:bytes length: length encoding:encoding]; 65 | 66 | if( nil == value ) { 67 | HTTPLogError(@"MultipartFormDataParser: Bad MIME header value for header name: '%@'",name); 68 | // tear down 69 | return nil; 70 | } 71 | return self; 72 | } 73 | 74 | value = [[NSString alloc] initWithBytes:bytes length: separatorOffset encoding:encoding]; 75 | HTTPLogVerbose(@"MultipartFormDataParser: Processing header field '%@' : '%@'",name,value); 76 | // skipe the separator and the next ' ' symbol 77 | bytes += separatorOffset + 2; 78 | length -= separatorOffset + 2; 79 | 80 | // parse the "params" part of the header 81 | if( ![self parseHeaderValueBytes:bytes length:length encoding:encoding] ) { 82 | NSString* paramsStr = [[NSString alloc] initWithBytes:bytes length:length encoding:NSASCIIStringEncoding]; 83 | HTTPLogError(@"MultipartFormDataParser: Bad params for header with name '%@' and value '%@'",name,value); 84 | HTTPLogError(@"MultipartFormDataParser: Params str: %@",paramsStr); 85 | 86 | return nil; 87 | } 88 | return self; 89 | } 90 | 91 | -(BOOL) parseHeaderValueBytes:(char*) bytes length:(NSUInteger) length encoding:(NSStringEncoding) encoding { 92 | int offset = 0; 93 | NSString* currentParam = nil; 94 | BOOL insideQuote = NO; 95 | while( offset < length ) { 96 | if( bytes[offset] == '\"' ) { 97 | if( !offset || bytes[offset-1] != '\\' ) { 98 | insideQuote = !insideQuote; 99 | } 100 | } 101 | 102 | // skip quoted symbols 103 | if( insideQuote ) { 104 | ++ offset; 105 | continue; 106 | } 107 | if( bytes[offset] == '=' ) { 108 | if( currentParam ) { 109 | // found '=' before terminating previous param. 110 | return NO; 111 | } 112 | currentParam = [[NSString alloc] initWithBytes:bytes length:offset encoding:NSASCIIStringEncoding]; 113 | 114 | bytes+=offset + 1; 115 | length -= offset + 1; 116 | offset = 0; 117 | continue; 118 | } 119 | if( bytes[offset] == ';' ) { 120 | if( !currentParam ) { 121 | // found ; before stating '='. 122 | HTTPLogError(@"MultipartFormDataParser: Unexpected ';' when parsing header"); 123 | return NO; 124 | } 125 | NSString* paramValue = extractParamValue(bytes, offset,encoding); 126 | if( nil == paramValue ) { 127 | HTTPLogWarn(@"MultipartFormDataParser: Failed to exctract paramValue for key %@ in header %@",currentParam,name); 128 | } 129 | else { 130 | #ifdef DEBUG 131 | if( [params objectForKey:currentParam] ) { 132 | HTTPLogWarn(@"MultipartFormDataParser: param %@ mentioned more then once in header %@",currentParam,name); 133 | } 134 | #endif 135 | [params setObject:paramValue forKey:currentParam]; 136 | HTTPLogVerbose(@"MultipartFormDataParser: header param: %@ = %@",currentParam,paramValue); 137 | } 138 | 139 | currentParam = nil; 140 | 141 | // ';' separator has ' ' following, skip them. 142 | bytes+=offset + 2; 143 | length -= offset + 2; 144 | offset = 0; 145 | } 146 | ++ offset; 147 | } 148 | 149 | // add last param 150 | if( insideQuote ) { 151 | HTTPLogWarn(@"MultipartFormDataParser: unterminated quote in header %@",name); 152 | // return YES; 153 | } 154 | if( currentParam ) { 155 | NSString* paramValue = extractParamValue(bytes, length, encoding); 156 | 157 | if( nil == paramValue ) { 158 | HTTPLogError(@"MultipartFormDataParser: Failed to exctract paramValue for key %@ in header %@",currentParam,name); 159 | } 160 | 161 | #ifdef DEBUG 162 | if( [params objectForKey:currentParam] ) { 163 | HTTPLogWarn(@"MultipartFormDataParser: param %@ mentioned more then once in one header",currentParam); 164 | } 165 | #endif 166 | [params setObject:paramValue forKey:currentParam]; 167 | HTTPLogVerbose(@"MultipartFormDataParser: header param: %@ = %@",currentParam,paramValue); 168 | currentParam = nil; 169 | } 170 | 171 | return YES; 172 | } 173 | 174 | - (NSString *)description { 175 | return [NSString stringWithFormat:@"%@:%@\n params: %@",name,value,params]; 176 | } 177 | 178 | @end 179 | 180 | int findChar(const char* str, NSUInteger length, char c) { 181 | int offset = 0; 182 | while( offset < length ) { 183 | if( str[offset] == c ) 184 | return offset; 185 | ++ offset; 186 | } 187 | return -1; 188 | } 189 | 190 | NSString* extractParamValue(const char* bytes, NSUInteger length, NSStringEncoding encoding) { 191 | if( !length ) 192 | return nil; 193 | NSMutableString* value = nil; 194 | 195 | if( bytes[0] == '"' ) { 196 | // values may be quoted. Strip the quotes to get what we need. 197 | value = [[NSMutableString alloc] initWithBytes:bytes + 1 length: length - 2 encoding:encoding]; 198 | } 199 | else { 200 | value = [[NSMutableString alloc] initWithBytes:bytes length: length encoding:encoding]; 201 | } 202 | // restore escaped symbols 203 | NSRange range= [value rangeOfString:@"\\"]; 204 | while ( range.length ) { 205 | [value deleteCharactersInRange:range]; 206 | range.location ++; 207 | range = [value rangeOfString:@"\\" options:NSLiteralSearch range: range]; 208 | } 209 | return value; 210 | } 211 | 212 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/MyHTTPConnection.h: -------------------------------------------------------------------------------- 1 | // 2 | // MyHTTPConnection.h 3 | // LocalWebServer 4 | // 5 | // Created by Smallfan on 23/08/2017. 6 | // Copyright © 2017 Smallfan. All rights reserved. 7 | // 8 | 9 | #import "HTTPConnection.h" 10 | 11 | @interface MyHTTPConnection : HTTPConnection 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/MyHTTPConnection.m: -------------------------------------------------------------------------------- 1 | // 2 | // MyHTTPConnection.m 3 | // LocalWebServer 4 | // 5 | // Created by Smallfan on 23/08/2017. 6 | // Copyright © 2017 Smallfan. All rights reserved. 7 | // 8 | 9 | #import "MyHTTPConnection.h" 10 | 11 | @implementation MyHTTPConnection 12 | 13 | - (BOOL)isSecureServer { 14 | return YES; 15 | } 16 | 17 | - (NSArray *)sslIdentityAndCertificates { 18 | 19 | SecIdentityRef identityRef = NULL; 20 | SecCertificateRef certificateRef = NULL; 21 | SecTrustRef trustRef = NULL; 22 | 23 | NSString *thePath = [[NSBundle bundleWithPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Resource"]] pathForResource:@"localhost" ofType:@"p12"]; 24 | NSData *PKCS12Data = [[NSData alloc] initWithContentsOfFile:thePath]; 25 | CFDataRef inPKCS12Data = (__bridge CFDataRef)PKCS12Data; 26 | CFStringRef password = CFSTR("b123456"); 27 | const void *keys[] = { kSecImportExportPassphrase }; 28 | const void *values[] = { password }; 29 | CFDictionaryRef optionsDictionary = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL); 30 | CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL); 31 | 32 | OSStatus securityError = errSecSuccess; 33 | securityError = SecPKCS12Import(inPKCS12Data, optionsDictionary, &items); 34 | if (securityError == 0) { 35 | CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex (items, 0); 36 | const void *tempIdentity = NULL; 37 | tempIdentity = CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemIdentity); 38 | identityRef = (SecIdentityRef)tempIdentity; 39 | const void *tempTrust = NULL; 40 | tempTrust = CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemTrust); 41 | trustRef = (SecTrustRef)tempTrust; 42 | } else { 43 | NSLog(@"Failed with error code %d",(int)securityError); 44 | return nil; 45 | } 46 | 47 | SecIdentityCopyCertificate(identityRef, &certificateRef); 48 | NSArray *result = [[NSArray alloc] initWithObjects:(__bridge id)identityRef, (__bridge id)certificateRef, nil]; 49 | 50 | return result; 51 | } 52 | 53 | @end 54 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Responses/HTTPAsyncFileResponse.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import "HTTPResponse.h" 3 | 4 | @class HTTPConnection; 5 | 6 | /** 7 | * This is an asynchronous version of HTTPFileResponse. 8 | * It reads data from the given file asynchronously via GCD. 9 | * 10 | * It may be overriden to allow custom post-processing of the data that has been read from the file. 11 | * An example of this is the HTTPDynamicFileResponse class. 12 | **/ 13 | 14 | @interface HTTPAsyncFileResponse : NSObject 15 | { 16 | HTTPConnection *connection; 17 | 18 | NSString *filePath; 19 | UInt64 fileLength; 20 | UInt64 fileOffset; // File offset as pertains to data given to connection 21 | UInt64 readOffset; // File offset as pertains to data read from file (but maybe not returned to connection) 22 | 23 | BOOL aborted; 24 | 25 | NSData *data; 26 | 27 | int fileFD; 28 | void *readBuffer; 29 | NSUInteger readBufferSize; // Malloced size of readBuffer 30 | NSUInteger readBufferOffset; // Offset within readBuffer where the end of existing data is 31 | NSUInteger readRequestLength; 32 | dispatch_queue_t readQueue; 33 | dispatch_source_t readSource; 34 | BOOL readSourceSuspended; 35 | } 36 | 37 | - (id)initWithFilePath:(NSString *)filePath forConnection:(HTTPConnection *)connection; 38 | - (NSString *)filePath; 39 | 40 | @end 41 | 42 | /** 43 | * Explanation of Variables (excluding those that are obvious) 44 | * 45 | * fileOffset 46 | * This is the number of bytes that have been returned to the connection via the readDataOfLength method. 47 | * If 1KB of data has been read from the file, but none of that data has yet been returned to the connection, 48 | * then the fileOffset variable remains at zero. 49 | * This variable is used in the calculation of the isDone method. 50 | * Only after all data has been returned to the connection are we actually done. 51 | * 52 | * readOffset 53 | * Represents the offset of the file descriptor. 54 | * In other words, the file position indidcator for our read stream. 55 | * It might be easy to think of it as the total number of bytes that have been read from the file. 56 | * However, this isn't entirely accurate, as the setOffset: method may have caused us to 57 | * jump ahead in the file (lseek). 58 | * 59 | * readBuffer 60 | * Malloc'd buffer to hold data read from the file. 61 | * 62 | * readBufferSize 63 | * Total allocation size of malloc'd buffer. 64 | * 65 | * readBufferOffset 66 | * Represents the position in the readBuffer where we should store new bytes. 67 | * 68 | * readRequestLength 69 | * The total number of bytes that were requested from the connection. 70 | * It's OK if we return a lesser number of bytes to the connection. 71 | * It's NOT OK if we return a greater number of bytes to the connection. 72 | * Doing so would disrupt proper support for range requests. 73 | * If, however, the response is chunked then we don't need to worry about this. 74 | * Chunked responses inheritly don't support range requests. 75 | **/ 76 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Responses/HTTPAsyncFileResponse.m: -------------------------------------------------------------------------------- 1 | #import "HTTPAsyncFileResponse.h" 2 | #import "HTTPConnection.h" 3 | #import "HTTPLogging.h" 4 | 5 | #import 6 | #import 7 | 8 | #if ! __has_feature(objc_arc) 9 | #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). 10 | #endif 11 | 12 | // Log levels : off, error, warn, info, verbose 13 | // Other flags: trace 14 | static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; // | HTTP_LOG_FLAG_TRACE; 15 | 16 | #define NULL_FD -1 17 | 18 | /** 19 | * Architecure overview: 20 | * 21 | * HTTPConnection will invoke our readDataOfLength: method to fetch data. 22 | * We will return nil, and then proceed to read the data via our readSource on our readQueue. 23 | * Once the requested amount of data has been read, we then pause our readSource, 24 | * and inform the connection of the available data. 25 | * 26 | * While our read is in progress, we don't have to worry about the connection calling any other methods, 27 | * except the connectionDidClose method, which would be invoked if the remote end closed the socket connection. 28 | * To safely handle this, we do a synchronous dispatch on the readQueue, 29 | * and nilify the connection as well as cancel our readSource. 30 | * 31 | * In order to minimize resource consumption during a HEAD request, 32 | * we don't open the file until we have to (until the connection starts requesting data). 33 | **/ 34 | 35 | @implementation HTTPAsyncFileResponse 36 | 37 | - (id)initWithFilePath:(NSString *)fpath forConnection:(HTTPConnection *)parent 38 | { 39 | if ((self = [super init])) 40 | { 41 | HTTPLogTrace(); 42 | 43 | connection = parent; // Parents retain children, children do NOT retain parents 44 | 45 | fileFD = NULL_FD; 46 | filePath = [fpath copy]; 47 | if (filePath == nil) 48 | { 49 | HTTPLogWarn(@"%@: Init failed - Nil filePath", THIS_FILE); 50 | 51 | return nil; 52 | } 53 | 54 | NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:NULL]; 55 | if (fileAttributes == nil) 56 | { 57 | HTTPLogWarn(@"%@: Init failed - Unable to get file attributes. filePath: %@", THIS_FILE, filePath); 58 | 59 | return nil; 60 | } 61 | 62 | fileLength = (UInt64)[[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue]; 63 | fileOffset = 0; 64 | 65 | aborted = NO; 66 | 67 | // We don't bother opening the file here. 68 | // If this is a HEAD request we only need to know the fileLength. 69 | } 70 | return self; 71 | } 72 | 73 | - (void)abort 74 | { 75 | HTTPLogTrace(); 76 | 77 | [connection responseDidAbort:self]; 78 | aborted = YES; 79 | } 80 | 81 | - (void)processReadBuffer 82 | { 83 | // This method is here to allow superclasses to perform post-processing of the data. 84 | // For an example, see the HTTPDynamicFileResponse class. 85 | // 86 | // At this point, the readBuffer has readBufferOffset bytes available. 87 | // This method is in charge of updating the readBufferOffset. 88 | // Failure to do so will cause the readBuffer to grow to fileLength. (Imagine a 1 GB file...) 89 | 90 | // Copy the data out of the temporary readBuffer. 91 | data = [[NSData alloc] initWithBytes:readBuffer length:readBufferOffset]; 92 | 93 | // Reset the read buffer. 94 | readBufferOffset = 0; 95 | 96 | // Notify the connection that we have data available for it. 97 | [connection responseHasAvailableData:self]; 98 | } 99 | 100 | - (void)pauseReadSource 101 | { 102 | if (!readSourceSuspended) 103 | { 104 | HTTPLogVerbose(@"%@[%p]: Suspending readSource", THIS_FILE, self); 105 | 106 | readSourceSuspended = YES; 107 | dispatch_suspend(readSource); 108 | } 109 | } 110 | 111 | - (void)resumeReadSource 112 | { 113 | if (readSourceSuspended) 114 | { 115 | HTTPLogVerbose(@"%@[%p]: Resuming readSource", THIS_FILE, self); 116 | 117 | readSourceSuspended = NO; 118 | dispatch_resume(readSource); 119 | } 120 | } 121 | 122 | - (void)cancelReadSource 123 | { 124 | HTTPLogVerbose(@"%@[%p]: Canceling readSource", THIS_FILE, self); 125 | 126 | dispatch_source_cancel(readSource); 127 | 128 | // Cancelling a dispatch source doesn't 129 | // invoke the cancel handler if the dispatch source is paused. 130 | 131 | if (readSourceSuspended) 132 | { 133 | readSourceSuspended = NO; 134 | dispatch_resume(readSource); 135 | } 136 | } 137 | 138 | - (BOOL)openFileAndSetupReadSource 139 | { 140 | HTTPLogTrace(); 141 | 142 | fileFD = open([filePath UTF8String], (O_RDONLY | O_NONBLOCK)); 143 | if (fileFD == NULL_FD) 144 | { 145 | HTTPLogError(@"%@: Unable to open file. filePath: %@", THIS_FILE, filePath); 146 | 147 | return NO; 148 | } 149 | 150 | HTTPLogVerbose(@"%@[%p]: Open fd[%i] -> %@", THIS_FILE, self, fileFD, filePath); 151 | 152 | readQueue = dispatch_queue_create("HTTPAsyncFileResponse", NULL); 153 | readSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, fileFD, 0, readQueue); 154 | 155 | 156 | dispatch_source_set_event_handler(readSource, ^{ 157 | 158 | HTTPLogTrace2(@"%@: eventBlock - fd[%i]", THIS_FILE, fileFD); 159 | 160 | // Determine how much data we should read. 161 | // 162 | // It is OK if we ask to read more bytes than exist in the file. 163 | // It is NOT OK to over-allocate the buffer. 164 | 165 | unsigned long long _bytesAvailableOnFD = dispatch_source_get_data(readSource); 166 | 167 | UInt64 _bytesLeftInFile = fileLength - readOffset; 168 | 169 | NSUInteger bytesAvailableOnFD; 170 | NSUInteger bytesLeftInFile; 171 | 172 | bytesAvailableOnFD = (_bytesAvailableOnFD > NSUIntegerMax) ? NSUIntegerMax : (NSUInteger)_bytesAvailableOnFD; 173 | bytesLeftInFile = (_bytesLeftInFile > NSUIntegerMax) ? NSUIntegerMax : (NSUInteger)_bytesLeftInFile; 174 | 175 | NSUInteger bytesLeftInRequest = readRequestLength - readBufferOffset; 176 | 177 | NSUInteger bytesLeft = MIN(bytesLeftInRequest, bytesLeftInFile); 178 | 179 | NSUInteger bytesToRead = MIN(bytesAvailableOnFD, bytesLeft); 180 | 181 | // Make sure buffer is big enough for read request. 182 | // Do not over-allocate. 183 | 184 | if (readBuffer == NULL || bytesToRead > (readBufferSize - readBufferOffset)) 185 | { 186 | readBufferSize = bytesToRead; 187 | readBuffer = reallocf(readBuffer, (size_t)bytesToRead); 188 | 189 | if (readBuffer == NULL) 190 | { 191 | HTTPLogError(@"%@[%p]: Unable to allocate buffer", THIS_FILE, self); 192 | 193 | [self pauseReadSource]; 194 | [self abort]; 195 | 196 | return; 197 | } 198 | } 199 | 200 | // Perform the read 201 | 202 | HTTPLogVerbose(@"%@[%p]: Attempting to read %lu bytes from file", THIS_FILE, self, (unsigned long)bytesToRead); 203 | 204 | ssize_t result = read(fileFD, readBuffer + readBufferOffset, (size_t)bytesToRead); 205 | 206 | // Check the results 207 | if (result < 0) 208 | { 209 | HTTPLogError(@"%@: Error(%i) reading file(%@)", THIS_FILE, errno, filePath); 210 | 211 | [self pauseReadSource]; 212 | [self abort]; 213 | } 214 | else if (result == 0) 215 | { 216 | HTTPLogError(@"%@: Read EOF on file(%@)", THIS_FILE, filePath); 217 | 218 | [self pauseReadSource]; 219 | [self abort]; 220 | } 221 | else // (result > 0) 222 | { 223 | HTTPLogVerbose(@"%@[%p]: Read %lu bytes from file", THIS_FILE, self, (unsigned long)result); 224 | 225 | readOffset += result; 226 | readBufferOffset += result; 227 | 228 | [self pauseReadSource]; 229 | [self processReadBuffer]; 230 | } 231 | 232 | }); 233 | 234 | int theFileFD = fileFD; 235 | #if !OS_OBJECT_USE_OBJC 236 | dispatch_source_t theReadSource = readSource; 237 | #endif 238 | 239 | dispatch_source_set_cancel_handler(readSource, ^{ 240 | 241 | // Do not access self from within this block in any way, shape or form. 242 | // 243 | // Note: You access self if you reference an iVar. 244 | 245 | HTTPLogTrace2(@"%@: cancelBlock - Close fd[%i]", THIS_FILE, theFileFD); 246 | 247 | #if !OS_OBJECT_USE_OBJC 248 | dispatch_release(theReadSource); 249 | #endif 250 | close(theFileFD); 251 | }); 252 | 253 | readSourceSuspended = YES; 254 | 255 | return YES; 256 | } 257 | 258 | - (BOOL)openFileIfNeeded 259 | { 260 | if (aborted) 261 | { 262 | // The file operation has been aborted. 263 | // This could be because we failed to open the file, 264 | // or the reading process failed. 265 | return NO; 266 | } 267 | 268 | if (fileFD != NULL_FD) 269 | { 270 | // File has already been opened. 271 | return YES; 272 | } 273 | 274 | return [self openFileAndSetupReadSource]; 275 | } 276 | 277 | - (UInt64)contentLength 278 | { 279 | HTTPLogTrace2(@"%@[%p]: contentLength - %llu", THIS_FILE, self, fileLength); 280 | 281 | return fileLength; 282 | } 283 | 284 | - (UInt64)offset 285 | { 286 | HTTPLogTrace(); 287 | 288 | return fileOffset; 289 | } 290 | 291 | - (void)setOffset:(UInt64)offset 292 | { 293 | HTTPLogTrace2(@"%@[%p]: setOffset:%llu", THIS_FILE, self, offset); 294 | 295 | if (![self openFileIfNeeded]) 296 | { 297 | // File opening failed, 298 | // or response has been aborted due to another error. 299 | return; 300 | } 301 | 302 | fileOffset = offset; 303 | readOffset = offset; 304 | 305 | off_t result = lseek(fileFD, (off_t)offset, SEEK_SET); 306 | if (result == -1) 307 | { 308 | HTTPLogError(@"%@[%p]: lseek failed - errno(%i) filePath(%@)", THIS_FILE, self, errno, filePath); 309 | 310 | [self abort]; 311 | } 312 | } 313 | 314 | - (NSData *)readDataOfLength:(NSUInteger)length 315 | { 316 | HTTPLogTrace2(@"%@[%p]: readDataOfLength:%lu", THIS_FILE, self, (unsigned long)length); 317 | 318 | if (data) 319 | { 320 | NSUInteger dataLength = [data length]; 321 | 322 | HTTPLogVerbose(@"%@[%p]: Returning data of length %lu", THIS_FILE, self, (unsigned long)dataLength); 323 | 324 | fileOffset += dataLength; 325 | 326 | NSData *result = data; 327 | data = nil; 328 | 329 | return result; 330 | } 331 | else 332 | { 333 | if (![self openFileIfNeeded]) 334 | { 335 | // File opening failed, 336 | // or response has been aborted due to another error. 337 | return nil; 338 | } 339 | 340 | dispatch_sync(readQueue, ^{ 341 | 342 | NSAssert(readSourceSuspended, @"Invalid logic - perhaps HTTPConnection has changed."); 343 | 344 | readRequestLength = length; 345 | [self resumeReadSource]; 346 | }); 347 | 348 | return nil; 349 | } 350 | } 351 | 352 | - (BOOL)isDone 353 | { 354 | BOOL result = (fileOffset == fileLength); 355 | 356 | HTTPLogTrace2(@"%@[%p]: isDone - %@", THIS_FILE, self, (result ? @"YES" : @"NO")); 357 | 358 | return result; 359 | } 360 | 361 | - (NSString *)filePath 362 | { 363 | return filePath; 364 | } 365 | 366 | - (BOOL)isAsynchronous 367 | { 368 | HTTPLogTrace(); 369 | 370 | return YES; 371 | } 372 | 373 | - (void)connectionDidClose 374 | { 375 | HTTPLogTrace(); 376 | 377 | if (fileFD != NULL_FD) 378 | { 379 | dispatch_sync(readQueue, ^{ 380 | 381 | // Prevent any further calls to the connection 382 | connection = nil; 383 | 384 | // Cancel the readSource. 385 | // We do this here because the readSource's eventBlock has retained self. 386 | // In other words, if we don't cancel the readSource, we will never get deallocated. 387 | 388 | [self cancelReadSource]; 389 | }); 390 | } 391 | } 392 | 393 | - (void)dealloc 394 | { 395 | HTTPLogTrace(); 396 | 397 | #if !OS_OBJECT_USE_OBJC 398 | if (readQueue) dispatch_release(readQueue); 399 | #endif 400 | 401 | if (readBuffer) 402 | free(readBuffer); 403 | } 404 | 405 | @end 406 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Responses/HTTPDataResponse.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import "HTTPResponse.h" 3 | 4 | 5 | @interface HTTPDataResponse : NSObject 6 | { 7 | NSUInteger offset; 8 | NSData *data; 9 | } 10 | 11 | - (id)initWithData:(NSData *)data; 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Responses/HTTPDataResponse.m: -------------------------------------------------------------------------------- 1 | #import "HTTPDataResponse.h" 2 | #import "HTTPLogging.h" 3 | 4 | #if ! __has_feature(objc_arc) 5 | #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). 6 | #endif 7 | 8 | // Log levels : off, error, warn, info, verbose 9 | // Other flags: trace 10 | static const int httpLogLevel = HTTP_LOG_LEVEL_OFF; // | HTTP_LOG_FLAG_TRACE; 11 | 12 | 13 | @implementation HTTPDataResponse 14 | 15 | - (id)initWithData:(NSData *)dataParam 16 | { 17 | if((self = [super init])) 18 | { 19 | HTTPLogTrace(); 20 | 21 | offset = 0; 22 | data = dataParam; 23 | } 24 | return self; 25 | } 26 | 27 | - (void)dealloc 28 | { 29 | HTTPLogTrace(); 30 | 31 | } 32 | 33 | - (UInt64)contentLength 34 | { 35 | UInt64 result = (UInt64)[data length]; 36 | 37 | HTTPLogTrace2(@"%@[%p]: contentLength - %llu", THIS_FILE, self, result); 38 | 39 | return result; 40 | } 41 | 42 | - (UInt64)offset 43 | { 44 | HTTPLogTrace(); 45 | 46 | return offset; 47 | } 48 | 49 | - (void)setOffset:(UInt64)offsetParam 50 | { 51 | HTTPLogTrace2(@"%@[%p]: setOffset:%lu", THIS_FILE, self, (unsigned long)offset); 52 | 53 | offset = (NSUInteger)offsetParam; 54 | } 55 | 56 | - (NSData *)readDataOfLength:(NSUInteger)lengthParameter 57 | { 58 | HTTPLogTrace2(@"%@[%p]: readDataOfLength:%lu", THIS_FILE, self, (unsigned long)lengthParameter); 59 | 60 | NSUInteger remaining = [data length] - offset; 61 | NSUInteger length = lengthParameter < remaining ? lengthParameter : remaining; 62 | 63 | void *bytes = (void *)([data bytes] + offset); 64 | 65 | offset += length; 66 | 67 | return [NSData dataWithBytesNoCopy:bytes length:length freeWhenDone:NO]; 68 | } 69 | 70 | - (BOOL)isDone 71 | { 72 | BOOL result = (offset == [data length]); 73 | 74 | HTTPLogTrace2(@"%@[%p]: isDone - %@", THIS_FILE, self, (result ? @"YES" : @"NO")); 75 | 76 | return result; 77 | } 78 | 79 | @end 80 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Responses/HTTPDynamicFileResponse.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import "HTTPResponse.h" 3 | #import "HTTPAsyncFileResponse.h" 4 | 5 | /** 6 | * This class is designed to assist with dynamic content. 7 | * Imagine you have a file that you want to make dynamic: 8 | * 9 | * 10 | * 11 | *

ComputerName Control Panel

12 | * ... 13 | *
  • System Time: SysTime
  • 14 | * 15 | * 16 | * 17 | * Now you could generate the entire file in Objective-C, 18 | * but this would be a horribly tedious process. 19 | * Beside, you want to design the file with professional tools to make it look pretty. 20 | * 21 | * So all you have to do is escape your dynamic content like this: 22 | * 23 | * ... 24 | *

    %%ComputerName%% Control Panel

    25 | * ... 26 | *
  • System Time: %%SysTime%%
  • 27 | * 28 | * And then you create an instance of this class with: 29 | * 30 | * - separator = @"%%" 31 | * - replacementDictionary = { "ComputerName"="Black MacBook", "SysTime"="2010-04-30 03:18:24" } 32 | * 33 | * This class will then perform the replacements for you, on the fly, as it reads the file data. 34 | * This class is also asynchronous, so it will perform the file IO using its own GCD queue. 35 | * 36 | * All keys for the replacementDictionary must be NSString's. 37 | * Values for the replacementDictionary may be NSString's, or any object that 38 | * returns what you want when its description method is invoked. 39 | **/ 40 | 41 | @interface HTTPDynamicFileResponse : HTTPAsyncFileResponse 42 | { 43 | NSData *separator; 44 | NSDictionary *replacementDict; 45 | } 46 | 47 | - (id)initWithFilePath:(NSString *)filePath 48 | forConnection:(HTTPConnection *)connection 49 | separator:(NSString *)separatorStr 50 | replacementDictionary:(NSDictionary *)dictionary; 51 | 52 | @end 53 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Responses/HTTPDynamicFileResponse.m: -------------------------------------------------------------------------------- 1 | #import "HTTPDynamicFileResponse.h" 2 | #import "HTTPConnection.h" 3 | #import "HTTPLogging.h" 4 | 5 | #if ! __has_feature(objc_arc) 6 | #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). 7 | #endif 8 | 9 | // Log levels : off, error, warn, info, verbose 10 | // Other flags: trace 11 | static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; // | HTTP_LOG_FLAG_TRACE; 12 | 13 | #define NULL_FD -1 14 | 15 | 16 | @implementation HTTPDynamicFileResponse 17 | 18 | - (id)initWithFilePath:(NSString *)fpath 19 | forConnection:(HTTPConnection *)parent 20 | separator:(NSString *)separatorStr 21 | replacementDictionary:(NSDictionary *)dict 22 | { 23 | if ((self = [super initWithFilePath:fpath forConnection:parent])) 24 | { 25 | HTTPLogTrace(); 26 | 27 | separator = [separatorStr dataUsingEncoding:NSUTF8StringEncoding]; 28 | replacementDict = dict; 29 | } 30 | return self; 31 | } 32 | 33 | - (BOOL)isChunked 34 | { 35 | HTTPLogTrace(); 36 | 37 | return YES; 38 | } 39 | 40 | - (UInt64)contentLength 41 | { 42 | // This method shouldn't be called since we're using a chunked response. 43 | // We override it just to be safe. 44 | 45 | HTTPLogTrace(); 46 | 47 | return 0; 48 | } 49 | 50 | - (void)setOffset:(UInt64)offset 51 | { 52 | // This method shouldn't be called since we're using a chunked response. 53 | // We override it just to be safe. 54 | 55 | HTTPLogTrace(); 56 | } 57 | 58 | - (BOOL)isDone 59 | { 60 | BOOL result = (readOffset == fileLength) && (readBufferOffset == 0); 61 | 62 | HTTPLogTrace2(@"%@[%p]: isDone - %@", THIS_FILE, self, (result ? @"YES" : @"NO")); 63 | 64 | return result; 65 | } 66 | 67 | - (void)processReadBuffer 68 | { 69 | HTTPLogTrace(); 70 | 71 | // At this point, the readBuffer has readBufferOffset bytes available. 72 | // This method is in charge of updating the readBufferOffset. 73 | 74 | NSUInteger bufLen = readBufferOffset; 75 | NSUInteger sepLen = [separator length]; 76 | 77 | // We're going to start looking for the separator at the beginning of the buffer, 78 | // and stop when we get to the point where the separator would no longer fit in the buffer. 79 | 80 | NSUInteger offset = 0; 81 | NSUInteger stopOffset = (bufLen > sepLen) ? bufLen - sepLen + 1 : 0; 82 | 83 | // In order to do the replacement, we need to find the starting and ending separator. 84 | // For example: 85 | // 86 | // %%USER_NAME%% 87 | // 88 | // Where "%%" is the separator. 89 | 90 | BOOL found1 = NO; 91 | BOOL found2 = NO; 92 | 93 | NSUInteger s1 = 0; 94 | NSUInteger s2 = 0; 95 | 96 | const void *sep = [separator bytes]; 97 | 98 | while (offset < stopOffset) 99 | { 100 | const void *subBuffer = readBuffer + offset; 101 | 102 | if (memcmp(subBuffer, sep, sepLen) == 0) 103 | { 104 | if (!found1) 105 | { 106 | // Found the first separator 107 | 108 | found1 = YES; 109 | s1 = offset; 110 | offset += sepLen; 111 | 112 | HTTPLogVerbose(@"%@[%p]: Found s1 at %lu", THIS_FILE, self, (unsigned long)s1); 113 | } 114 | else 115 | { 116 | // Found the second separator 117 | 118 | found2 = YES; 119 | s2 = offset; 120 | offset += sepLen; 121 | 122 | HTTPLogVerbose(@"%@[%p]: Found s2 at %lu", THIS_FILE, self, (unsigned long)s2); 123 | } 124 | 125 | if (found1 && found2) 126 | { 127 | // We found our separators. 128 | // Now extract the string between the two separators. 129 | 130 | NSRange fullRange = NSMakeRange(s1, (s2 - s1 + sepLen)); 131 | NSRange strRange = NSMakeRange(s1 + sepLen, (s2 - s1 - sepLen)); 132 | 133 | // Wish we could use the simple subdataWithRange method. 134 | // But that method copies the bytes... 135 | // So for performance reasons, we need to use the methods that don't copy the bytes. 136 | 137 | void *strBuf = readBuffer + strRange.location; 138 | NSUInteger strLen = strRange.length; 139 | 140 | NSString *key = [[NSString alloc] initWithBytes:strBuf length:strLen encoding:NSUTF8StringEncoding]; 141 | if (key) 142 | { 143 | // Is there a given replacement for this key? 144 | 145 | id value = [replacementDict objectForKey:key]; 146 | if (value) 147 | { 148 | // Found the replacement value. 149 | // Now perform the replacement in the buffer. 150 | 151 | HTTPLogVerbose(@"%@[%p]: key(%@) -> value(%@)", THIS_FILE, self, key, value); 152 | 153 | NSData *v = [[value description] dataUsingEncoding:NSUTF8StringEncoding]; 154 | NSUInteger vLength = [v length]; 155 | 156 | if (fullRange.length == vLength) 157 | { 158 | // Replacement is exactly the same size as what it is replacing 159 | 160 | // memcpy(void *restrict dst, const void *restrict src, size_t n); 161 | 162 | memcpy(readBuffer + fullRange.location, [v bytes], vLength); 163 | } 164 | else // (fullRange.length != vLength) 165 | { 166 | NSInteger diff = (NSInteger)vLength - (NSInteger)fullRange.length; 167 | 168 | if (diff > 0) 169 | { 170 | // Replacement is bigger than what it is replacing. 171 | // Make sure there is room in the buffer for the replacement. 172 | 173 | if (diff > (readBufferSize - bufLen)) 174 | { 175 | NSUInteger inc = MAX(diff, 256); 176 | 177 | readBufferSize += inc; 178 | readBuffer = reallocf(readBuffer, readBufferSize); 179 | } 180 | } 181 | 182 | // Move the data that comes after the replacement. 183 | // 184 | // If replacement is smaller than what it is replacing, 185 | // then we are shifting the data toward the beginning of the buffer. 186 | // 187 | // If replacement is bigger than what it is replacing, 188 | // then we are shifting the data toward the end of the buffer. 189 | // 190 | // memmove(void *dst, const void *src, size_t n); 191 | // 192 | // The memmove() function copies n bytes from src to dst. 193 | // The two areas may overlap; the copy is always done in a non-destructive manner. 194 | 195 | void *src = readBuffer + fullRange.location + fullRange.length; 196 | void *dst = readBuffer + fullRange.location + vLength; 197 | 198 | NSUInteger remaining = bufLen - (fullRange.location + fullRange.length); 199 | 200 | memmove(dst, src, remaining); 201 | 202 | // Now copy the replacement into its location. 203 | // 204 | // memcpy(void *restrict dst, const void *restrict src, size_t n) 205 | // 206 | // The memcpy() function copies n bytes from src to dst. 207 | // If the two areas overlap, behavior is undefined. 208 | 209 | memcpy(readBuffer + fullRange.location, [v bytes], vLength); 210 | 211 | // And don't forget to update our indices. 212 | 213 | bufLen += diff; 214 | offset += diff; 215 | stopOffset += diff; 216 | } 217 | } 218 | 219 | } 220 | 221 | found1 = found2 = NO; 222 | } 223 | } 224 | else 225 | { 226 | offset++; 227 | } 228 | } 229 | 230 | // We've gone through our buffer now, and performed all the replacements that we could. 231 | // It's now time to update the amount of available data we have. 232 | 233 | if (readOffset == fileLength) 234 | { 235 | // We've read in the entire file. 236 | // So there can be no more replacements. 237 | 238 | data = [[NSData alloc] initWithBytes:readBuffer length:bufLen]; 239 | readBufferOffset = 0; 240 | } 241 | else 242 | { 243 | // There are a couple different situations that we need to take into account here. 244 | // 245 | // Imagine the following file: 246 | // My name is %%USER_NAME%% 247 | // 248 | // Situation 1: 249 | // The first chunk of data we read was "My name is %%". 250 | // So we found the first separator, but not the second. 251 | // In this case we can only return the data that precedes the first separator. 252 | // 253 | // Situation 2: 254 | // The first chunk of data we read was "My name is %". 255 | // So we didn't find any separators, but part of a separator may be included in our buffer. 256 | 257 | NSUInteger available; 258 | if (found1) 259 | { 260 | // Situation 1 261 | available = s1; 262 | } 263 | else 264 | { 265 | // Situation 2 266 | available = stopOffset; 267 | } 268 | 269 | // Copy available data 270 | 271 | data = [[NSData alloc] initWithBytes:readBuffer length:available]; 272 | 273 | // Remove the copied data from the buffer. 274 | // We do this by shifting the remaining data toward the beginning of the buffer. 275 | 276 | NSUInteger remaining = bufLen - available; 277 | 278 | memmove(readBuffer, readBuffer + available, remaining); 279 | readBufferOffset = remaining; 280 | } 281 | 282 | [connection responseHasAvailableData:self]; 283 | } 284 | 285 | - (void)dealloc 286 | { 287 | HTTPLogTrace(); 288 | 289 | 290 | } 291 | 292 | @end 293 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Responses/HTTPErrorResponse.h: -------------------------------------------------------------------------------- 1 | #import "HTTPResponse.h" 2 | 3 | @interface HTTPErrorResponse : NSObject { 4 | NSInteger _status; 5 | } 6 | 7 | - (id)initWithErrorCode:(int)httpErrorCode; 8 | 9 | @end 10 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Responses/HTTPErrorResponse.m: -------------------------------------------------------------------------------- 1 | #import "HTTPErrorResponse.h" 2 | 3 | @implementation HTTPErrorResponse 4 | 5 | -(id)initWithErrorCode:(int)httpErrorCode 6 | { 7 | if ((self = [super init])) 8 | { 9 | _status = httpErrorCode; 10 | } 11 | 12 | return self; 13 | } 14 | 15 | - (UInt64) contentLength { 16 | return 0; 17 | } 18 | 19 | - (UInt64) offset { 20 | return 0; 21 | } 22 | 23 | - (void)setOffset:(UInt64)offset { 24 | ; 25 | } 26 | 27 | - (NSData*) readDataOfLength:(NSUInteger)length { 28 | return nil; 29 | } 30 | 31 | - (BOOL) isDone { 32 | return YES; 33 | } 34 | 35 | - (NSInteger) status { 36 | return _status; 37 | } 38 | @end 39 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Responses/HTTPFileResponse.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import "HTTPResponse.h" 3 | 4 | @class HTTPConnection; 5 | 6 | 7 | @interface HTTPFileResponse : NSObject 8 | { 9 | HTTPConnection *connection; 10 | 11 | NSString *filePath; 12 | UInt64 fileLength; 13 | UInt64 fileOffset; 14 | 15 | BOOL aborted; 16 | 17 | int fileFD; 18 | void *buffer; 19 | NSUInteger bufferSize; 20 | } 21 | 22 | - (id)initWithFilePath:(NSString *)filePath forConnection:(HTTPConnection *)connection; 23 | - (NSString *)filePath; 24 | 25 | @end 26 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Responses/HTTPFileResponse.m: -------------------------------------------------------------------------------- 1 | #import "HTTPFileResponse.h" 2 | #import "HTTPConnection.h" 3 | #import "HTTPLogging.h" 4 | 5 | #import 6 | #import 7 | 8 | #if ! __has_feature(objc_arc) 9 | #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). 10 | #endif 11 | 12 | // Log levels : off, error, warn, info, verbose 13 | // Other flags: trace 14 | static const int httpLogLevel = HTTP_LOG_LEVEL_WARN; // | HTTP_LOG_FLAG_TRACE; 15 | 16 | #define NULL_FD -1 17 | 18 | 19 | @implementation HTTPFileResponse 20 | 21 | - (id)initWithFilePath:(NSString *)fpath forConnection:(HTTPConnection *)parent 22 | { 23 | if((self = [super init])) 24 | { 25 | HTTPLogTrace(); 26 | 27 | connection = parent; // Parents retain children, children do NOT retain parents 28 | 29 | fileFD = NULL_FD; 30 | filePath = [[fpath copy] stringByResolvingSymlinksInPath]; 31 | if (filePath == nil) 32 | { 33 | HTTPLogWarn(@"%@: Init failed - Nil filePath", THIS_FILE); 34 | 35 | return nil; 36 | } 37 | 38 | NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil]; 39 | if (fileAttributes == nil) 40 | { 41 | HTTPLogWarn(@"%@: Init failed - Unable to get file attributes. filePath: %@", THIS_FILE, filePath); 42 | 43 | return nil; 44 | } 45 | 46 | fileLength = (UInt64)[[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue]; 47 | fileOffset = 0; 48 | 49 | aborted = NO; 50 | 51 | // We don't bother opening the file here. 52 | // If this is a HEAD request we only need to know the fileLength. 53 | } 54 | return self; 55 | } 56 | 57 | - (void)abort 58 | { 59 | HTTPLogTrace(); 60 | 61 | [connection responseDidAbort:self]; 62 | aborted = YES; 63 | } 64 | 65 | - (BOOL)openFile 66 | { 67 | HTTPLogTrace(); 68 | 69 | fileFD = open([filePath UTF8String], O_RDONLY); 70 | if (fileFD == NULL_FD) 71 | { 72 | HTTPLogError(@"%@[%p]: Unable to open file. filePath: %@", THIS_FILE, self, filePath); 73 | 74 | [self abort]; 75 | return NO; 76 | } 77 | 78 | HTTPLogVerbose(@"%@[%p]: Open fd[%i] -> %@", THIS_FILE, self, fileFD, filePath); 79 | 80 | return YES; 81 | } 82 | 83 | - (BOOL)openFileIfNeeded 84 | { 85 | if (aborted) 86 | { 87 | // The file operation has been aborted. 88 | // This could be because we failed to open the file, 89 | // or the reading process failed. 90 | return NO; 91 | } 92 | 93 | if (fileFD != NULL_FD) 94 | { 95 | // File has already been opened. 96 | return YES; 97 | } 98 | 99 | return [self openFile]; 100 | } 101 | 102 | - (UInt64)contentLength 103 | { 104 | HTTPLogTrace(); 105 | 106 | return fileLength; 107 | } 108 | 109 | - (UInt64)offset 110 | { 111 | HTTPLogTrace(); 112 | 113 | return fileOffset; 114 | } 115 | 116 | - (void)setOffset:(UInt64)offset 117 | { 118 | HTTPLogTrace2(@"%@[%p]: setOffset:%llu", THIS_FILE, self, offset); 119 | 120 | if (![self openFileIfNeeded]) 121 | { 122 | // File opening failed, 123 | // or response has been aborted due to another error. 124 | return; 125 | } 126 | 127 | fileOffset = offset; 128 | 129 | off_t result = lseek(fileFD, (off_t)offset, SEEK_SET); 130 | if (result == -1) 131 | { 132 | HTTPLogError(@"%@[%p]: lseek failed - errno(%i) filePath(%@)", THIS_FILE, self, errno, filePath); 133 | 134 | [self abort]; 135 | } 136 | } 137 | 138 | - (NSData *)readDataOfLength:(NSUInteger)length 139 | { 140 | HTTPLogTrace2(@"%@[%p]: readDataOfLength:%lu", THIS_FILE, self, (unsigned long)length); 141 | 142 | if (![self openFileIfNeeded]) 143 | { 144 | // File opening failed, 145 | // or response has been aborted due to another error. 146 | return nil; 147 | } 148 | 149 | // Determine how much data we should read. 150 | // 151 | // It is OK if we ask to read more bytes than exist in the file. 152 | // It is NOT OK to over-allocate the buffer. 153 | 154 | UInt64 bytesLeftInFile = fileLength - fileOffset; 155 | 156 | NSUInteger bytesToRead = (NSUInteger)MIN(length, bytesLeftInFile); 157 | 158 | // Make sure buffer is big enough for read request. 159 | // Do not over-allocate. 160 | 161 | if (buffer == NULL || bufferSize < bytesToRead) 162 | { 163 | bufferSize = bytesToRead; 164 | buffer = reallocf(buffer, (size_t)bufferSize); 165 | 166 | if (buffer == NULL) 167 | { 168 | HTTPLogError(@"%@[%p]: Unable to allocate buffer", THIS_FILE, self); 169 | 170 | [self abort]; 171 | return nil; 172 | } 173 | } 174 | 175 | // Perform the read 176 | 177 | HTTPLogVerbose(@"%@[%p]: Attempting to read %lu bytes from file", THIS_FILE, self, (unsigned long)bytesToRead); 178 | 179 | ssize_t result = read(fileFD, buffer, bytesToRead); 180 | 181 | // Check the results 182 | 183 | if (result < 0) 184 | { 185 | HTTPLogError(@"%@: Error(%i) reading file(%@)", THIS_FILE, errno, filePath); 186 | 187 | [self abort]; 188 | return nil; 189 | } 190 | else if (result == 0) 191 | { 192 | HTTPLogError(@"%@: Read EOF on file(%@)", THIS_FILE, filePath); 193 | 194 | [self abort]; 195 | return nil; 196 | } 197 | else // (result > 0) 198 | { 199 | HTTPLogVerbose(@"%@[%p]: Read %ld bytes from file", THIS_FILE, self, (long)result); 200 | 201 | fileOffset += result; 202 | 203 | return [NSData dataWithBytes:buffer length:result]; 204 | } 205 | } 206 | 207 | - (BOOL)isDone 208 | { 209 | BOOL result = (fileOffset == fileLength); 210 | 211 | HTTPLogTrace2(@"%@[%p]: isDone - %@", THIS_FILE, self, (result ? @"YES" : @"NO")); 212 | 213 | return result; 214 | } 215 | 216 | - (NSString *)filePath 217 | { 218 | return filePath; 219 | } 220 | 221 | - (void)dealloc 222 | { 223 | HTTPLogTrace(); 224 | 225 | if (fileFD != NULL_FD) 226 | { 227 | HTTPLogVerbose(@"%@[%p]: Close fd[%i]", THIS_FILE, self, fileFD); 228 | 229 | close(fileFD); 230 | } 231 | 232 | if (buffer) 233 | free(buffer); 234 | 235 | } 236 | 237 | @end 238 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Responses/HTTPRedirectResponse.h: -------------------------------------------------------------------------------- 1 | #import 2 | #import "HTTPResponse.h" 3 | 4 | 5 | @interface HTTPRedirectResponse : NSObject 6 | { 7 | NSString *redirectPath; 8 | } 9 | 10 | - (id)initWithPath:(NSString *)redirectPath; 11 | 12 | @end 13 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/Responses/HTTPRedirectResponse.m: -------------------------------------------------------------------------------- 1 | #import "HTTPRedirectResponse.h" 2 | #import "HTTPLogging.h" 3 | 4 | #if ! __has_feature(objc_arc) 5 | #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). 6 | #endif 7 | 8 | // Log levels : off, error, warn, info, verbose 9 | // Other flags: trace 10 | static const int httpLogLevel = HTTP_LOG_LEVEL_OFF; // | HTTP_LOG_FLAG_TRACE; 11 | 12 | 13 | @implementation HTTPRedirectResponse 14 | 15 | - (id)initWithPath:(NSString *)path 16 | { 17 | if ((self = [super init])) 18 | { 19 | HTTPLogTrace(); 20 | 21 | redirectPath = [path copy]; 22 | } 23 | return self; 24 | } 25 | 26 | - (UInt64)contentLength 27 | { 28 | return 0; 29 | } 30 | 31 | - (UInt64)offset 32 | { 33 | return 0; 34 | } 35 | 36 | - (void)setOffset:(UInt64)offset 37 | { 38 | // Nothing to do 39 | } 40 | 41 | - (NSData *)readDataOfLength:(NSUInteger)length 42 | { 43 | HTTPLogTrace(); 44 | 45 | return nil; 46 | } 47 | 48 | - (BOOL)isDone 49 | { 50 | return YES; 51 | } 52 | 53 | - (NSDictionary *)httpHeaders 54 | { 55 | HTTPLogTrace(); 56 | 57 | return [NSDictionary dictionaryWithObject:redirectPath forKey:@"Location"]; 58 | } 59 | 60 | - (NSInteger)status 61 | { 62 | HTTPLogTrace(); 63 | 64 | return 302; 65 | } 66 | 67 | - (void)dealloc 68 | { 69 | HTTPLogTrace(); 70 | 71 | } 72 | 73 | @end 74 | -------------------------------------------------------------------------------- /CocoaHttpServer/Core/WebSocket.h: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | @class HTTPMessage; 4 | @class GCDAsyncSocket; 5 | 6 | 7 | #define WebSocketDidDieNotification @"WebSocketDidDie" 8 | 9 | @interface WebSocket : NSObject 10 | { 11 | dispatch_queue_t websocketQueue; 12 | 13 | HTTPMessage *request; 14 | GCDAsyncSocket *asyncSocket; 15 | 16 | NSData *term; 17 | 18 | BOOL isStarted; 19 | BOOL isOpen; 20 | BOOL isVersion76; 21 | 22 | id __unsafe_unretained delegate; 23 | } 24 | 25 | + (BOOL)isWebSocketRequest:(HTTPMessage *)request; 26 | 27 | - (id)initWithRequest:(HTTPMessage *)request socket:(GCDAsyncSocket *)socket; 28 | 29 | /** 30 | * Delegate option. 31 | * 32 | * In most cases it will be easier to subclass WebSocket, 33 | * but some circumstances may lead one to prefer standard delegate callbacks instead. 34 | **/ 35 | @property (/* atomic */ unsafe_unretained) id delegate; 36 | 37 | /** 38 | * The WebSocket class is thread-safe, generally via it's GCD queue. 39 | * All public API methods are thread-safe, 40 | * and the subclass API methods are thread-safe as they are all invoked on the same GCD queue. 41 | **/ 42 | @property (nonatomic, readonly) dispatch_queue_t websocketQueue; 43 | 44 | /** 45 | * Public API 46 | * 47 | * These methods are automatically called by the HTTPServer. 48 | * You may invoke the stop method yourself to close the WebSocket manually. 49 | **/ 50 | - (void)start; 51 | - (void)stop; 52 | 53 | /** 54 | * Public API 55 | * 56 | * Sends a message over the WebSocket. 57 | * This method is thread-safe. 58 | **/ 59 | - (void)sendMessage:(NSString *)msg; 60 | 61 | /** 62 | * Public API 63 | * 64 | * Sends a message over the WebSocket. 65 | * This method is thread-safe. 66 | **/ 67 | - (void)sendData:(NSData *)msg; 68 | 69 | /** 70 | * Subclass API 71 | * 72 | * These methods are designed to be overriden by subclasses. 73 | **/ 74 | - (void)didOpen; 75 | - (void)didReceiveMessage:(NSString *)msg; 76 | - (void)didClose; 77 | 78 | @end 79 | 80 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 81 | #pragma mark - 82 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 83 | 84 | /** 85 | * There are two ways to create your own custom WebSocket: 86 | * 87 | * - Subclass it and override the methods you're interested in. 88 | * - Use traditional delegate paradigm along with your own custom class. 89 | * 90 | * They both exist to allow for maximum flexibility. 91 | * In most cases it will be easier to subclass WebSocket. 92 | * However some circumstances may lead one to prefer standard delegate callbacks instead. 93 | * One such example, you're already subclassing another class, so subclassing WebSocket isn't an option. 94 | **/ 95 | 96 | @protocol WebSocketDelegate 97 | @optional 98 | 99 | - (void)webSocketDidOpen:(WebSocket *)ws; 100 | 101 | - (void)webSocket:(WebSocket *)ws didReceiveMessage:(NSString *)msg; 102 | 103 | - (void)webSocketDidClose:(WebSocket *)ws; 104 | 105 | @end 106 | -------------------------------------------------------------------------------- /LocalWebServer.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /LocalWebServer.xcodeproj/project.xcworkspace/xcuserdata/Smallfan.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Smallfan/LocalWebServer/a27bc4644528fdcef30975fb0c485ec852af48d8/LocalWebServer.xcodeproj/project.xcworkspace/xcuserdata/Smallfan.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /LocalWebServer.xcodeproj/xcuserdata/Smallfan.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /LocalWebServer.xcodeproj/xcuserdata/Smallfan.xcuserdatad/xcschemes/LocalWebServer.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 39 | 40 | 41 | 42 | 43 | 44 | 54 | 56 | 62 | 63 | 64 | 65 | 66 | 67 | 73 | 75 | 81 | 82 | 83 | 84 | 86 | 87 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /LocalWebServer.xcodeproj/xcuserdata/Smallfan.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | LocalWebServer.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | C417E84A1F4D281C0005FA12 16 | 17 | primary 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /LocalWebServer/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // LocalWebServer 4 | // 5 | // Created by Smallfan on 23/08/2017. 6 | // Copyright © 2017 Smallfan. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : UIResponder 12 | 13 | @property (strong, nonatomic) UIWindow *window; 14 | 15 | 16 | @end 17 | 18 | -------------------------------------------------------------------------------- /LocalWebServer/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // LocalWebServer 4 | // 5 | // Created by Smallfan on 23/08/2017. 6 | // Copyright © 2017 Smallfan. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | #import "ViewController.h" 11 | 12 | @interface AppDelegate () 13 | 14 | @end 15 | 16 | @implementation AppDelegate 17 | 18 | 19 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 20 | // Override point for customization after application launch. 21 | 22 | self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 23 | self.window.backgroundColor = [UIColor blackColor]; 24 | 25 | self.window.rootViewController = [[ViewController alloc] init]; 26 | [self.window makeKeyAndVisible]; 27 | 28 | return YES; 29 | } 30 | 31 | 32 | - (void)applicationWillResignActive:(UIApplication *)application { 33 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 34 | // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 35 | } 36 | 37 | 38 | - (void)applicationDidEnterBackground:(UIApplication *)application { 39 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 40 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 41 | } 42 | 43 | 44 | - (void)applicationWillEnterForeground:(UIApplication *)application { 45 | // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 46 | } 47 | 48 | 49 | - (void)applicationDidBecomeActive:(UIApplication *)application { 50 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 51 | } 52 | 53 | 54 | - (void)applicationWillTerminate:(UIApplication *)application { 55 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 56 | } 57 | 58 | 59 | @end 60 | -------------------------------------------------------------------------------- /LocalWebServer/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /LocalWebServer/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | NSAppTransportSecurity 6 | 7 | NSAllowsArbitraryLoadsForMedia 8 | 9 | NSAllowsArbitraryLoadsInWebContent 10 | 11 | NSAllowsArbitraryLoads 12 | 13 | 14 | CFBundleDevelopmentRegion 15 | en 16 | CFBundleExecutable 17 | $(EXECUTABLE_NAME) 18 | CFBundleIdentifier 19 | $(PRODUCT_BUNDLE_IDENTIFIER) 20 | CFBundleInfoDictionaryVersion 21 | 6.0 22 | CFBundleName 23 | $(PRODUCT_NAME) 24 | CFBundlePackageType 25 | APPL 26 | CFBundleShortVersionString 27 | 1.0 28 | CFBundleVersion 29 | 1 30 | LSRequiresIPhoneOS 31 | 32 | UILaunchStoryboardName 33 | LaunchScreen 34 | UIRequiredDeviceCapabilities 35 | 36 | armv7 37 | 38 | UISupportedInterfaceOrientations 39 | 40 | UIInterfaceOrientationPortrait 41 | UIInterfaceOrientationLandscapeLeft 42 | UIInterfaceOrientationLandscapeRight 43 | 44 | UISupportedInterfaceOrientations~ipad 45 | 46 | UIInterfaceOrientationPortrait 47 | UIInterfaceOrientationPortraitUpsideDown 48 | UIInterfaceOrientationLandscapeLeft 49 | UIInterfaceOrientationLandscapeRight 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /LocalWebServer/LocalWebServerManager.h: -------------------------------------------------------------------------------- 1 | // 2 | // LocalWebServerManager.h 3 | // LocalWebServer 4 | // 5 | // Created by Smallfan on 23/08/2017. 6 | // Copyright © 2017 Smallfan. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface LocalWebServerManager : NSObject 12 | 13 | @property (nonatomic, assign, readonly) NSUInteger port; 14 | 15 | + (instancetype)sharedInstance; 16 | 17 | - (void)start; 18 | - (void)stop; 19 | 20 | @end 21 | -------------------------------------------------------------------------------- /LocalWebServer/LocalWebServerManager.m: -------------------------------------------------------------------------------- 1 | // 2 | // LocalWebServerManager.m 3 | // LocalWebServer 4 | // 5 | // Created by Smallfan on 23/08/2017. 6 | // Copyright © 2017 Smallfan. All rights reserved. 7 | // 8 | 9 | #import "LocalWebServerManager.h" 10 | 11 | #import "HTTPServer.h" 12 | #import "MyHTTPConnection.h" 13 | 14 | @interface LocalWebServerManager () 15 | { 16 | HTTPServer *_httpServer; 17 | } 18 | @end 19 | 20 | @implementation LocalWebServerManager 21 | 22 | + (instancetype)sharedInstance { 23 | static LocalWebServerManager *_sharedInstance = nil; 24 | static dispatch_once_t onceToken; 25 | dispatch_once(&onceToken, ^{ 26 | _sharedInstance = [[LocalWebServerManager alloc] init]; 27 | }); 28 | return _sharedInstance; 29 | } 30 | 31 | - (void)start { 32 | 33 | _port = 60000; 34 | 35 | if (!_httpServer) { 36 | _httpServer = [[HTTPServer alloc] init]; 37 | [_httpServer setConnectionClass:[MyHTTPConnection class]]; 38 | [_httpServer setType:@"_http._tcp."]; 39 | [_httpServer setPort:_port]; 40 | NSString * webLocalPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Resource"]; 41 | [_httpServer setDocumentRoot:webLocalPath]; 42 | 43 | NSLog(@"Setting document root: %@", webLocalPath); 44 | 45 | } 46 | 47 | if (_httpServer && ![_httpServer isRunning]) { 48 | NSError *error; 49 | if([_httpServer start:&error]) { 50 | NSLog(@"start server success in port %d %@", [_httpServer listeningPort], [_httpServer publishedName]); 51 | } else { 52 | NSLog(@"启动失败"); 53 | } 54 | } 55 | 56 | } 57 | 58 | - (void)stop { 59 | if (_httpServer && [_httpServer isRunning]) { 60 | [_httpServer stop]; 61 | } 62 | } 63 | 64 | @end 65 | -------------------------------------------------------------------------------- /LocalWebServer/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // LocalWebServer 4 | // 5 | // Created by Smallfan on 23/08/2017. 6 | // Copyright © 2017 Smallfan. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /LocalWebServer/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // LocalWebServer 4 | // 5 | // Created by Smallfan on 23/08/2017. 6 | // Copyright © 2017 Smallfan. All rights reserved. 7 | // 8 | // 9 | // 10 | 11 | #import "ViewController.h" 12 | #import 13 | #import "LocalWebServerManager.h" 14 | 15 | @interface ViewController () 16 | { 17 | WKWebView *_wkWebView; 18 | } 19 | @end 20 | 21 | @implementation ViewController 22 | 23 | - (void)viewDidLoad { 24 | [super viewDidLoad]; 25 | [self setupWebView]; 26 | 27 | //Start local web server 28 | [[LocalWebServerManager sharedInstance] start]; 29 | 30 | //Local request which use local resource 31 | [self loadLocalRequest]; 32 | 33 | //Remote request which use local resource 34 | // [self loadRemoteRequest]; 35 | 36 | } 37 | 38 | - (void)setupWebView { 39 | if (!_wkWebView) { 40 | WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; 41 | WKUserContentController *controller = [[WKUserContentController alloc] init]; 42 | configuration.userContentController = controller; 43 | configuration.processPool = [[WKProcessPool alloc] init]; 44 | 45 | _wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds 46 | configuration:configuration]; 47 | _wkWebView.navigationDelegate = self; 48 | _wkWebView.UIDelegate = self; 49 | 50 | [self.view addSubview:_wkWebView]; 51 | } 52 | } 53 | 54 | - (void)loadRemoteRequest { 55 | if (_wkWebView) { 56 | [_wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://smallfan.net/demo.html"]]]; 57 | } 58 | } 59 | 60 | - (void)loadLocalRequest { 61 | if (_wkWebView) { 62 | [_wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://localhost:%ld/index.html", [[LocalWebServerManager sharedInstance] port] ] ]]]; 63 | } 64 | } 65 | 66 | #pragma mark - WKNavigationDelegate 67 | - (void)webView:(WKWebView *)webView 68 | didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 69 | completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler { 70 | 71 | if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { 72 | NSURLCredential *card = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust]; 73 | completionHandler(NSURLSessionAuthChallengeUseCredential, card); 74 | } 75 | } 76 | 77 | #pragma mark - UIDelegate 78 | - (void)webView:(WKWebView *)webView 79 | runJavaScriptAlertPanelWithMessage:(NSString *)message 80 | initiatedByFrame:(WKFrameInfo *)frame 81 | completionHandler:(void (^)(void))completionHandler { 82 | 83 | NSString *alertTitle = @"温馨提示"; 84 | UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle 85 | message:message 86 | preferredStyle:UIAlertControllerStyleAlert]; 87 | [alertController addAction:[UIAlertAction actionWithTitle:@"确定" 88 | style:UIAlertActionStyleDefault 89 | handler:^(UIAlertAction * _Nonnull action) { 90 | completionHandler(); 91 | }]]; 92 | [self presentViewController:alertController animated:YES completion:nil]; 93 | } 94 | 95 | 96 | @end 97 | -------------------------------------------------------------------------------- /LocalWebServer/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // LocalWebServer 4 | // 5 | // Created by Smallfan on 23/08/2017. 6 | // Copyright © 2017 Smallfan. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LocalWebServer 2 | 3 | LocalWebServer is an iOS SDK demo that showcases how to implement a local web server using CocoaHttpServer and HTTPS. The project provides a simple example of how to serve content locally from an iOS device, making it useful for local development, testing, and debugging. 4 | 5 | ## Features 6 | 7 | - Provides a simple example of how to implement a local web server in iOS using CocoaHttpServer. 8 | - Supports HTTPS for secure local connections. 9 | - Demonstrates how to serve static files and dynamic content from an iOS device. 10 | - Provides a set of default certificates to enable HTTPS support. 11 | - Includes a demo app that showcases how to use the local web server to serve content. 12 | 13 | ## Safety 14 | 15 | LocalWebServer takes safety seriously and has implemented several security measures to ensure the safety of the local web server. HTTPS support ensures secure communication between the server and clients. The default certificates provided with the project have been generated using the best practices and are designed to provide strong encryption for secure connections. 16 | 17 | In addition, LocalWebServer follows the best practices of secure coding and has been designed to minimize the risk of common vulnerabilities, such as buffer overflows, SQL injection, and cross-site scripting. 18 | 19 | ## Speed 20 | 21 | LocalWebServer has been optimized for speed and provides a fast and efficient way to serve content locally from an iOS device. The project uses the highly efficient CocoaHttpServer library, which has been optimized for performance and provides a highly scalable and reliable web server implementation. 22 | 23 | In addition, LocalWebServer uses caching and other performance optimizations to ensure that content is served as quickly as possible, even on low-end devices. 24 | 25 | ## Getting started 26 | To get started with LocalWebServer, simply clone the project and open the demo app in Xcode. The demo app provides a simple example of how to use the local web server to serve content from an iOS device. 27 | 28 | ## License 29 | 30 | LocalWebServer is available under the MIT license. See the LICENSE file for more information. 31 | 32 | ## Contributing 33 | 34 | Contributions to LocalWebServer are welcome and encouraged! If you have any suggestions or improvements, please feel free to submit a pull request or open an issue. 35 | -------------------------------------------------------------------------------- /Resource/hi.js: -------------------------------------------------------------------------------- 1 | function invokeAlert() { 2 | alert('Perfect!') 3 | } 4 | -------------------------------------------------------------------------------- /Resource/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Hello 6 | 7 | 8 | 9 |
    10 |







    恭喜你 服务器运行成功!

    11 |

    点击下面按钮试一下
    12 | 13 |
    14 | 15 | 16 | -------------------------------------------------------------------------------- /Resource/localhost.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Smallfan/LocalWebServer/a27bc4644528fdcef30975fb0c485ec852af48d8/Resource/localhost.p12 --------------------------------------------------------------------------------