53 Commits
2.1.1 ... 2.3

Author SHA1 Message Date
Pierre-Olivier Latour
51e8dbe475 #41 Fixed linking issues with Podspec 2014-04-18 18:38:17 -03:00
Pierre-Olivier Latour
4a3d4537a3 Update README.md 2014-04-18 18:25:35 -03:00
Pierre-Olivier Latour
2597d6da00 Bumped version 2014-04-18 12:59:16 -03:00
Pierre-Olivier Latour
1ca5a56952 Allow multiple user accounts for authentication 2014-04-18 12:50:11 -03:00
Pierre-Olivier Latour
80cff01154 Update README.md 2014-04-18 12:33:59 -03:00
Pierre-Olivier Latour
1e17d5c455 #38 Added support for digest authentication 2014-04-18 12:32:55 -03:00
Pierre-Olivier Latour
ce1eb3c29a Fix 2014-04-18 12:31:41 -03:00
Pierre-Olivier Latour
f11647ee7f Fixed unit tests 2014-04-18 10:59:29 -03:00
Pierre-Olivier Latour
60f281fd30 #40 Allow non ISO Latin 1 file names when downloading files 2014-04-18 10:46:50 -03:00
Pierre-Olivier Latour
181984ba6d Update README.md 2014-04-17 23:10:10 -03:00
Pierre-Olivier Latour
4685fae29c Cleaned up authentication options 2014-04-17 23:08:16 -03:00
Pierre-Olivier Latour
8619799e62 Added -preflightRequest: and -overrideResponse:forRequest: APIs 2014-04-17 22:51:55 -03:00
Pierre-Olivier Latour
b1061378fb Fix 2014-04-17 22:16:25 -03:00
Pierre-Olivier Latour
9bc2bfa506 Update README.md 2014-04-17 18:06:15 -03:00
Pierre-Olivier Latour
078c5e7bc3 Bumped version 2014-04-17 11:50:17 -03:00
Pierre-Olivier Latour
3f304b3c14 Fixed parsing of 'multipart/form-data' with non-ASCII headers 2014-04-17 11:50:09 -03:00
Pierre-Olivier Latour
80348079a6 Added support for Basic Authentication 2014-04-17 11:14:17 -03:00
Pierre-Olivier Latour
099b2a03e6 Updated run APIs to use options 2014-04-17 11:12:18 -03:00
Pierre-Olivier Latour
f0c63f4776 Fixes 2014-04-17 10:41:33 -03:00
Pierre-Olivier Latour
4e3aa3bc5c Update README.md 2014-04-17 01:57:30 -03:00
Pierre-Olivier Latour
c5d82b85ed Update README.md 2014-04-17 01:55:15 -03:00
Pierre-Olivier Latour
b1181d2e40 Update README.md 2014-04-17 01:54:21 -03:00
Pierre-Olivier Latour
d931e04d47 Update README.md 2014-04-17 01:52:19 -03:00
Pierre-Olivier Latour
016c4da6d2 Update README.md 2014-04-17 01:50:07 -03:00
Pierre-Olivier Latour
38dd39a789 Update README.md 2014-04-17 01:49:03 -03:00
Pierre-Olivier Latour
748f6a8bc9 Update README.md 2014-04-17 01:48:22 -03:00
Pierre-Olivier Latour
0b3f825f1a Bumped version 2014-04-17 01:04:55 -03:00
Pierre-Olivier Latour
6b9142642e Update README.md 2014-04-17 00:47:34 -03:00
Pierre-Olivier Latour
0a21059d25 Added support for background mode on iOS 2014-04-16 23:49:35 -03:00
Pierre-Olivier Latour
14acb7b323 Fix 2014-04-16 23:30:22 -03:00
Pierre-Olivier Latour
2f7f7b7b50 Fix 2014-04-16 01:50:17 -03:00
Pierre-Olivier Latour
998a47b099 Replaced GCDWebServer subclassing with explicit options 2014-04-16 01:29:52 -03:00
Pierre-Olivier Latour
2d8996b91e Added connected state to GCDWebServer 2014-04-16 00:57:41 -03:00
Pierre-Olivier Latour
c5ca0f7cee Added GCDWebServerDelegate 2014-04-16 00:57:41 -03:00
Pierre-Olivier Latour
05a704bcef Fix 2014-04-16 00:57:41 -03:00
Pierre-Olivier Latour
c170fb4fd3 Use strerror() consistently 2014-04-16 00:57:41 -03:00
Pierre-Olivier Latour
55a9abd506 Fix 2014-04-16 00:57:39 -03:00
Pierre-Olivier Latour
489c8c6236 Added +[GCDWebServer maxPendingConnections] 2014-04-16 00:57:14 -03:00
Pierre-Olivier Latour
9c73736225 Fix 2014-04-15 21:53:02 -03:00
Pierre-Olivier Latour
1f503aa3b6 Fix 2014-04-15 18:02:38 -03:00
Pierre-Olivier Latour
4eeeab7dc2 Build iOS app using iOS Simulator SDK on Travis CI 2014-04-15 17:57:42 -03:00
Pierre-Olivier Latour
813f124f6a Fix 2014-04-15 17:57:15 -03:00
Pierre-Olivier Latour
8fe66444ae Cleaned up connections read / write implementation 2014-04-15 17:46:43 -03:00
Pierre-Olivier Latour
e3efc065df Build iOS app as part of unit tests 2014-04-15 16:50:57 -03:00
Pierre-Olivier Latour
016153f900 Isolated all testing code with __GCDWEBSERVER_ENABLE_TESTING__ 2014-04-15 16:50:57 -03:00
Pierre-Olivier Latour
a55781e2c1 Changed -[GCDWebServerConnection open] to return a BOOL 2014-04-15 16:50:57 -03:00
Pierre-Olivier Latour
4fb5d67e9b Fixed broken iOS build with __GCDWEBSERVER_ENABLE_TESTING__ 2014-04-15 16:50:57 -03:00
Pierre-Olivier Latour
14e04b445f Fixes 2014-04-15 16:50:57 -03:00
Pierre-Olivier Latour
ad01c15dcd Update README.md 2014-04-15 01:28:46 -03:00
Pierre-Olivier Latour
bb0f62416e Update README.md 2014-04-15 01:24:31 -03:00
Pierre-Olivier Latour
14228834d6 Update README.md 2014-04-15 01:09:10 -03:00
Pierre-Olivier Latour
eb16566605 Update README.md 2014-04-15 01:08:19 -03:00
Pierre-Olivier Latour
06e0fc531d Fixes 2014-04-15 01:01:55 -03:00
21 changed files with 1063 additions and 514 deletions

View File

@@ -29,14 +29,15 @@
@class GCDWebDAVServer;
@protocol GCDWebDAVServerDelegate <NSObject>
// These methods are always called on main thread
@protocol GCDWebDAVServerDelegate <GCDWebServerDelegate>
@optional
- (void)davServer:(GCDWebDAVServer*)uploader didDownloadFileAtPath:(NSString*)path;
- (void)davServer:(GCDWebDAVServer*)uploader didUploadFileAtPath:(NSString*)path;
- (void)davServer:(GCDWebDAVServer*)uploader didMoveItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath;
- (void)davServer:(GCDWebDAVServer*)uploader didCopyItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath;
- (void)davServer:(GCDWebDAVServer*)uploader didDeleteItemAtPath:(NSString*)path;
- (void)davServer:(GCDWebDAVServer*)uploader didCreateDirectoryAtPath:(NSString*)path;
- (void)davServer:(GCDWebDAVServer*)server didDownloadFileAtPath:(NSString*)path;
- (void)davServer:(GCDWebDAVServer*)server didUploadFileAtPath:(NSString*)path;
- (void)davServer:(GCDWebDAVServer*)server didMoveItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath;
- (void)davServer:(GCDWebDAVServer*)server didCopyItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath;
- (void)davServer:(GCDWebDAVServer*)server didDeleteItemAtPath:(NSString*)path;
- (void)davServer:(GCDWebDAVServer*)server didCreateDirectoryAtPath:(NSString*)path;
@end
@interface GCDWebDAVServer : GCDWebServer
@@ -47,6 +48,7 @@
- (instancetype)initWithUploadDirectory:(NSString*)path;
@end
// These methods can be called from any thread
@interface GCDWebDAVServer (Subclassing)
- (BOOL)shouldUploadFileAtPath:(NSString*)path withTemporaryFile:(NSString*)tempPath; // Default implementation returns YES
- (BOOL)shouldMoveItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath; // Default implementation returns YES

View File

@@ -54,7 +54,6 @@ typedef NS_ENUM(NSInteger, DAVProperties) {
@interface GCDWebDAVServer () {
@private
NSString* _uploadDirectory;
id<GCDWebDAVServerDelegate> __unsafe_unretained _delegate;
NSArray* _allowedExtensions;
BOOL _showHidden;
}
@@ -102,9 +101,9 @@ static inline BOOL _IsMacFinder(GCDWebServerRequest* request) {
return [GCDWebServerResponse response];
}
if ([_delegate respondsToSelector:@selector(davServer:didDownloadFileAtPath:)]) {
if ([self.delegate respondsToSelector:@selector(davServer:didDownloadFileAtPath:)]) {
dispatch_async(dispatch_get_main_queue(), ^{
[_delegate davServer:self didDownloadFileAtPath:absolutePath];
[self.delegate davServer:self didDownloadFileAtPath:absolutePath];
});
}
return [GCDWebServerFileResponse responseWithFile:absolutePath];
@@ -145,9 +144,9 @@ static inline BOOL _IsMacFinder(GCDWebServerRequest* request) {
return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed moving uploaded file to \"%@\"", relativePath];
}
if ([_delegate respondsToSelector:@selector(davServer:didUploadFileAtPath:)]) {
if ([self.delegate respondsToSelector:@selector(davServer:didUploadFileAtPath:)]) {
dispatch_async(dispatch_get_main_queue(), ^{
[_delegate davServer:self didUploadFileAtPath:absolutePath];
[self.delegate davServer:self didUploadFileAtPath:absolutePath];
});
}
return [GCDWebServerResponse responseWithStatusCode:(existing ? kGCDWebServerHTTPStatusCode_NoContent : kGCDWebServerHTTPStatusCode_Created)];
@@ -180,9 +179,9 @@ static inline BOOL _IsMacFinder(GCDWebServerRequest* request) {
return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed deleting \"%@\"", relativePath];
}
if ([_delegate respondsToSelector:@selector(davServer:didDeleteItemAtPath:)]) {
if ([self.delegate respondsToSelector:@selector(davServer:didDeleteItemAtPath:)]) {
dispatch_async(dispatch_get_main_queue(), ^{
[_delegate davServer:self didDeleteItemAtPath:absolutePath];
[self.delegate davServer:self didDeleteItemAtPath:absolutePath];
});
}
return [GCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_NoContent];
@@ -226,9 +225,9 @@ static inline BOOL _IsMacFinder(GCDWebServerRequest* request) {
}
#endif
if ([_delegate respondsToSelector:@selector(davServer:didCreateDirectoryAtPath:)]) {
if ([self.delegate respondsToSelector:@selector(davServer:didCreateDirectoryAtPath:)]) {
dispatch_async(dispatch_get_main_queue(), ^{
[_delegate davServer:self didCreateDirectoryAtPath:absolutePath];
[self.delegate davServer:self didCreateDirectoryAtPath:absolutePath];
});
}
return [GCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_Created];
@@ -298,15 +297,15 @@ static inline BOOL _IsMacFinder(GCDWebServerRequest* request) {
}
if (isMove) {
if ([_delegate respondsToSelector:@selector(davServer:didMoveItemFromPath:toPath:)]) {
if ([self.delegate respondsToSelector:@selector(davServer:didMoveItemFromPath:toPath:)]) {
dispatch_async(dispatch_get_main_queue(), ^{
[_delegate davServer:self didMoveItemFromPath:srcAbsolutePath toPath:dstAbsolutePath];
[self.delegate davServer:self didMoveItemFromPath:srcAbsolutePath toPath:dstAbsolutePath];
});
}
} else {
if ([_delegate respondsToSelector:@selector(davServer:didCopyItemFromPath:toPath:)]) {
if ([self.delegate respondsToSelector:@selector(davServer:didCopyItemFromPath:toPath:)]) {
dispatch_async(dispatch_get_main_queue(), ^{
[_delegate davServer:self didCopyItemFromPath:srcAbsolutePath toPath:dstAbsolutePath];
[self.delegate davServer:self didCopyItemFromPath:srcAbsolutePath toPath:dstAbsolutePath];
});
}
}
@@ -598,7 +597,7 @@ static inline xmlNodePtr _XMLChildWithName(xmlNodePtr child, const xmlChar* name
@implementation GCDWebDAVServer
@synthesize uploadDirectory=_uploadDirectory, delegate=_delegate, allowedFileExtensions=_allowedExtensions, showHiddenFiles=_showHidden;
@synthesize uploadDirectory=_uploadDirectory, allowedFileExtensions=_allowedExtensions, showHiddenFiles=_showHidden;
- (instancetype)initWithUploadDirectory:(NSString*)path {
if ((self = [super init])) {

View File

@@ -7,7 +7,7 @@
Pod::Spec.new do |s|
s.name = 'GCDWebServer'
s.version = '2.1.1'
s.version = '2.3'
s.author = { 'Pierre-Olivier Latour' => 'info@pol-online.net' }
s.license = { :type => 'BSD', :file => 'LICENSE' }
s.homepage = 'https://github.com/swisspol/GCDWebServer'
@@ -24,7 +24,9 @@ Pod::Spec.new do |s|
cs.source_files = 'GCDWebServer/**/*.{h,m}'
cs.requires_arc = true
cs.ios.library = 'z'
cs.ios.frameworks = 'MobileCoreServices', 'CFNetwork'
cs.osx.library = 'z'
cs.osx.framework = 'SystemConfiguration'
cs.compiler_flags = '-DNDEBUG' # TODO: Only set this for Release configuration
end

View File

@@ -42,34 +42,55 @@ typedef NS_ENUM(int, GCDWebServerLogLevel) {
typedef GCDWebServerRequest* (^GCDWebServerMatchBlock)(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery);
typedef GCDWebServerResponse* (^GCDWebServerProcessBlock)(GCDWebServerRequest* request);
extern NSString* const GCDWebServerOption_Port; // NSNumber / NSUInteger (default is 0 i.e. use a random port)
extern NSString* const GCDWebServerOption_BonjourName; // NSString (default is empty string i.e. use computer name)
extern NSString* const GCDWebServerOption_MaxPendingConnections; // NSNumber / NSUInteger (default is 16)
extern NSString* const GCDWebServerOption_ServerName; // NSString (default is server class name)
extern NSString* const GCDWebServerOption_AuthenticationMethod; // One of "GCDWebServerAuthenticationMethod_..." (default is nil i.e. no authentication)
extern NSString* const GCDWebServerOption_AuthenticationRealm; // NSString (default is server name)
extern NSString* const GCDWebServerOption_AuthenticationAccounts; // NSDictionary of username / password (default is nil i.e. no accounts)
extern NSString* const GCDWebServerOption_ConnectionClass; // Subclass of GCDWebServerConnection (default is GCDWebServerConnection class)
extern NSString* const GCDWebServerOption_AutomaticallyMapHEADToGET; // NSNumber / BOOL (default is YES)
extern NSString* const GCDWebServerOption_ConnectedStateCoalescingInterval; // NSNumber / double (default is 1.0 seconds - set to <=0.0 to disable coaslescing of -webServerDidConnect: / -webServerDidDisconnect:)
#if TARGET_OS_IPHONE
extern NSString* const GCDWebServerOption_AutomaticallySuspendInBackground; // NSNumber / BOOL (default is YES)
#endif
extern NSString* const GCDWebServerAuthenticationMethod_Basic; // Not recommended as password is sent in clear
extern NSString* const GCDWebServerAuthenticationMethod_DigestAccess;
@class GCDWebServer;
// These methods are always called on main thread
@protocol GCDWebServerDelegate <NSObject>
@optional
- (void)webServerDidStart:(GCDWebServer*)server;
- (void)webServerDidConnect:(GCDWebServer*)server; // Called when first connection is opened
- (void)webServerDidDisconnect:(GCDWebServer*)server; // Called when last connection is closed
- (void)webServerDidStop:(GCDWebServer*)server;
@end
@interface GCDWebServer : NSObject
@property(nonatomic, assign) id<GCDWebServerDelegate> delegate;
@property(nonatomic, readonly, getter=isRunning) BOOL running;
@property(nonatomic, readonly) NSUInteger port;
@property(nonatomic, readonly) NSUInteger port; // Only non-zero if running
@property(nonatomic, readonly) NSString* bonjourName; // Only non-nil if Bonjour registration is active
- (instancetype)init;
- (void)addHandlerWithMatchBlock:(GCDWebServerMatchBlock)matchBlock processBlock:(GCDWebServerProcessBlock)processBlock;
- (void)removeAllHandlers;
- (BOOL)start; // Default is port 8080 (OS X & iOS Simulator) or 80 (iOS) and computer name
- (BOOL)start; // Default is port 8080 (OS X & iOS Simulator) or 80 (iOS) and computer / device name for Bonjour
- (BOOL)startWithPort:(NSUInteger)port bonjourName:(NSString*)name; // Pass nil name to disable Bonjour or empty string to use computer name
- (void)stop;
@end
@interface GCDWebServer (Subclassing)
+ (Class)connectionClass;
+ (NSString*)serverName; // Default is class name
+ (BOOL)shouldAutomaticallyMapHEADToGET; // Default is YES which means HEAD requests are mapped to GET requests with the response body being discarded
- (BOOL)startWithOptions:(NSDictionary*)options;
- (void)stop; // Does not abort any currently opened connections
@end
@interface GCDWebServer (Extensions)
@property(nonatomic, readonly) NSURL* serverURL; // Only non-nil if server is running
@property(nonatomic, readonly) NSURL* bonjourServerURL; // Only non-nil if server is running and Bonjour registration is active
#if !TARGET_OS_IPHONE
@property(nonatomic, getter=isRecordingEnabled) BOOL recordingEnabled; // Creates files in the current directory containing the raw data for all requests and responses (directory most NOT contain prior recordings)
- (BOOL)runWithPort:(NSUInteger)port; // Starts then automatically stops on SIGINT i.e. Ctrl-C (use on main thread only)
#endif
#ifdef __GCDWEBSERVER_ENABLE_TESTING__
- (NSInteger)runTestsInDirectory:(NSString*)path withPort:(NSUInteger)port; // Returns number of failed tests or -1 if server failed to start
- (BOOL)runWithPort:(NSUInteger)port bonjourName:(NSString*)name;
- (BOOL)runWithOptions:(NSDictionary*)options; // Starts then automatically stops on SIGINT i.e. Ctrl-C (use on main thread only)
#endif
@end
@@ -94,3 +115,12 @@ typedef GCDWebServerResponse* (^GCDWebServerProcessBlock)(GCDWebServerRequest* r
- (void)logWarning:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2);
- (void)logError:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2);
@end
#ifdef __GCDWEBSERVER_ENABLE_TESTING__
@interface GCDWebServer (Testing)
@property(nonatomic, getter=isRecordingEnabled) BOOL recordingEnabled; // Creates files in the current directory containing the raw data for all requests and responses (directory most NOT contain prior recordings)
- (NSInteger)runTestsWithOptions:(NSDictionary*)options inDirectory:(NSString*)path; // Returns number of failed tests or -1 if server failed to start
@end
#endif

View File

@@ -26,6 +26,13 @@
*/
#import <TargetConditionals.h>
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#else
#ifdef __GCDWEBSERVER_ENABLE_TESTING__
#import <AppKit/AppKit.h>
#endif
#endif
#import <netinet/in.h>
#import "GCDWebServerPrivate.h"
@@ -35,16 +42,32 @@
#else
#define kDefaultPort 8080
#endif
#define kMaxPendingConnections 16
@interface GCDWebServer () {
@private
id<GCDWebServerDelegate> __unsafe_unretained _delegate;
dispatch_queue_t _syncQueue;
NSMutableArray* _handlers;
NSInteger _activeConnections; // Accessed only with _syncQueue
BOOL _connected;
CFRunLoopTimerRef _connectedTimer;
NSDictionary* _options;
NSString* _serverName;
NSString* _authenticationRealm;
NSMutableDictionary* _authenticationBasicAccounts;
NSMutableDictionary* _authenticationDigestAccounts;
Class _connectionClass;
BOOL _mapHEADToGET;
CFTimeInterval _disconnectDelay;
NSUInteger _port;
dispatch_source_t _source;
CFNetServiceRef _service;
#if !TARGET_OS_IPHONE
#if TARGET_OS_IPHONE
BOOL _suspendInBackground;
UIBackgroundTaskIdentifier _backgroundTask;
#endif
#ifdef __GCDWEBSERVER_ENABLE_TESTING__
BOOL _recording;
#endif
}
@@ -57,6 +80,23 @@
}
@end
NSString* const GCDWebServerOption_Port = @"Port";
NSString* const GCDWebServerOption_BonjourName = @"BonjourName";
NSString* const GCDWebServerOption_MaxPendingConnections = @"MaxPendingConnections";
NSString* const GCDWebServerOption_ServerName = @"ServerName";
NSString* const GCDWebServerOption_AuthenticationMethod = @"AuthenticationMethod";
NSString* const GCDWebServerOption_AuthenticationRealm = @"AuthenticationRealm";
NSString* const GCDWebServerOption_AuthenticationAccounts = @"AuthenticationAccounts";
NSString* const GCDWebServerOption_ConnectionClass = @"ConnectionClass";
NSString* const GCDWebServerOption_AutomaticallyMapHEADToGET = @"AutomaticallyMapHEADToGET";
NSString* const GCDWebServerOption_ConnectedStateCoalescingInterval = @"ConnectedStateCoalescingInterval";
#if TARGET_OS_IPHONE
NSString* const GCDWebServerOption_AutomaticallySuspendInBackground = @"AutomaticallySuspendInBackground";
#endif
NSString* const GCDWebServerAuthenticationMethod_Basic = @"Basic";
NSString* const GCDWebServerAuthenticationMethod_DigestAccess = @"DigestAccess";
#ifndef __GCDWEBSERVER_LOGGING_HEADER__
#ifdef NDEBUG
GCDWebServerLogLevel GCDLogLevel = kGCDWebServerLogLevel_Info;
@@ -115,7 +155,9 @@ static void _SignalHandler(int signal) {
@implementation GCDWebServer
@synthesize handlers=_handlers, port=_port;
@synthesize delegate=_delegate, handlers=_handlers, port=_port, serverName=_serverName, authenticationRealm=_authenticationRealm,
authenticationBasicAccounts=_authenticationBasicAccounts, authenticationDigestAccounts=_authenticationDigestAccounts,
shouldAutomaticallyMapHEADToGET=_mapHEADToGET;
#ifndef __GCDWEBSERVER_LOGGING_HEADER__
@@ -132,44 +174,166 @@ static void _SignalHandler(int signal) {
GCDWebServerInitializeFunctions();
}
static void _ConnectedTimerCallBack(CFRunLoopTimerRef timer, void* info) {
@autoreleasepool {
[(ARC_BRIDGE GCDWebServer*)info _didDisconnect];
}
}
- (instancetype)init {
if ((self = [super init])) {
_syncQueue = dispatch_queue_create([NSStringFromClass([self class]) UTF8String], DISPATCH_QUEUE_SERIAL);
_handlers = [[NSMutableArray alloc] init];
CFRunLoopTimerContext context = {0, (ARC_BRIDGE void*)self, NULL, NULL, NULL};
_connectedTimer = CFRunLoopTimerCreate(kCFAllocatorDefault, HUGE_VAL, HUGE_VAL, 0, 0, _ConnectedTimerCallBack, &context);
CFRunLoopAddTimer(CFRunLoopGetMain(), _connectedTimer, kCFRunLoopCommonModes);
#if TARGET_OS_IPHONE
_backgroundTask = UIBackgroundTaskInvalid;
#endif
}
return self;
}
- (void)dealloc {
if (_source) {
DCHECK(_connected == NO);
DCHECK(_activeConnections == 0);
_delegate = nil;
if (_options) {
[self stop];
}
CFRunLoopTimerInvalidate(_connectedTimer);
CFRelease(_connectedTimer);
ARC_RELEASE(_handlers);
ARC_DISPATCH_RELEASE(_syncQueue);
ARC_DEALLOC(super);
}
#if TARGET_OS_IPHONE
// Always called on main thread
- (void)_startBackgroundTask {
DCHECK([NSThread isMainThread]);
if (_backgroundTask == UIBackgroundTaskInvalid) {
LOG_DEBUG(@"Did start background task");
_backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
LOG_WARNING(@"Application is being suspended while %@ is still connected", [self class]);
[self _endBackgroundTask];
}];
} else {
DNOT_REACHED();
}
}
#endif
// Always called on main thread
- (void)_didConnect {
DCHECK([NSThread isMainThread]);
DCHECK(_connected == NO);
_connected = YES;
LOG_DEBUG(@"Did connect");
#if TARGET_OS_IPHONE
[self _startBackgroundTask];
#endif
if ([_delegate respondsToSelector:@selector(webServerDidConnect:)]) {
[_delegate webServerDidConnect:self];
}
}
- (void)willStartConnection:(GCDWebServerConnection*)connection {
dispatch_sync(_syncQueue, ^{
DCHECK(_activeConnections >= 0);
if (_activeConnections == 0) {
dispatch_async(dispatch_get_main_queue(), ^{
if (_disconnectDelay > 0.0) {
CFRunLoopTimerSetNextFireDate(_connectedTimer, HUGE_VAL);
}
if (_connected == NO) {
[self _didConnect];
}
});
}
_activeConnections += 1;
});
}
#if TARGET_OS_IPHONE
// Always called on main thread
- (void)_endBackgroundTask {
DCHECK([NSThread isMainThread]);
if (_backgroundTask != UIBackgroundTaskInvalid) {
if (_suspendInBackground && ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) && _source) {
[self _stop];
}
[[UIApplication sharedApplication] endBackgroundTask:_backgroundTask];
_backgroundTask = UIBackgroundTaskInvalid;
LOG_DEBUG(@"Did end background task");
} else {
DNOT_REACHED();
}
}
#endif
// Always called on main thread
- (void)_didDisconnect {
DCHECK([NSThread isMainThread]);
DCHECK(_connected == YES);
_connected = NO;
LOG_DEBUG(@"Did disconnect");
#if TARGET_OS_IPHONE
[self _endBackgroundTask];
#endif
if ([_delegate respondsToSelector:@selector(webServerDidDisconnect:)]) {
[_delegate webServerDidDisconnect:self];
}
}
- (void)didEndConnection:(GCDWebServerConnection*)connection {
dispatch_sync(_syncQueue, ^{
DCHECK(_activeConnections > 0);
_activeConnections -= 1;
if (_activeConnections == 0) {
dispatch_async(dispatch_get_main_queue(), ^{
if (_disconnectDelay > 0.0) {
CFRunLoopTimerSetNextFireDate(_connectedTimer, CFAbsoluteTimeGetCurrent() + _disconnectDelay);
} else {
[self _didDisconnect];
}
});
}
});
}
- (NSString*)bonjourName {
CFStringRef name = _service ? CFNetServiceGetName(_service) : NULL;
return name && CFStringGetLength(name) ? ARC_BRIDGE_RELEASE(CFStringCreateCopy(kCFAllocatorDefault, name)) : nil;
}
- (void)addHandlerWithMatchBlock:(GCDWebServerMatchBlock)matchBlock processBlock:(GCDWebServerProcessBlock)handlerBlock {
DCHECK(_source == NULL);
DCHECK(_options == nil);
GCDWebServerHandler* handler = [[GCDWebServerHandler alloc] initWithMatchBlock:matchBlock processBlock:handlerBlock];
[_handlers insertObject:handler atIndex:0];
ARC_RELEASE(handler);
}
- (void)removeAllHandlers {
DCHECK(_source == NULL);
DCHECK(_options == nil);
[_handlers removeAllObjects];
}
- (BOOL)start {
return [self startWithPort:kDefaultPort bonjourName:@""];
}
static void _NetServiceClientCallBack(CFNetServiceRef service, CFStreamError* error, void* info) {
@autoreleasepool {
if (error->error) {
@@ -181,8 +345,25 @@ static void _NetServiceClientCallBack(CFNetServiceRef service, CFStreamError* er
}
}
- (BOOL)startWithPort:(NSUInteger)port bonjourName:(NSString*)name {
static inline id _GetOption(NSDictionary* options, NSString* key, id defaultValue) {
id value = [options objectForKey:key];
return value ? value : defaultValue;
}
static inline NSString* _EncodeBase64(NSString* string) {
NSData* data = [string dataUsingEncoding:NSUTF8StringEncoding];
#if (TARGET_OS_IPHONE && !(__IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0)) || (!TARGET_OS_IPHONE && !(__MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_9))
if (![data respondsToSelector:@selector(base64EncodedDataWithOptions:)]) {
return [data base64Encoding];
}
#endif
return ARC_AUTORELEASE([[NSString alloc] initWithData:[data base64EncodedDataWithOptions:0] encoding:NSASCIIStringEncoding]);
}
- (BOOL)_start {
DCHECK(_source == NULL);
NSUInteger port = [_GetOption(_options, GCDWebServerOption_Port, @0) unsignedIntegerValue];
NSString* name = _GetOption(_options, GCDWebServerOption_BonjourName, @"");
NSUInteger maxPendingConnections = [_GetOption(_options, GCDWebServerOption_MaxPendingConnections, @16) unsignedIntegerValue];
int listeningSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listeningSocket > 0) {
int yes = 1;
@@ -195,16 +376,37 @@ static void _NetServiceClientCallBack(CFNetServiceRef service, CFStreamError* er
addr4.sin_port = htons(port);
addr4.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(listeningSocket, (void*)&addr4, sizeof(addr4)) == 0) {
if (listen(listeningSocket, kMaxPendingConnections) == 0) {
if (listen(listeningSocket, (int)maxPendingConnections) == 0) {
LOG_DEBUG(@"Did open listening socket %i", listeningSocket);
_serverName = [_GetOption(_options, GCDWebServerOption_ServerName, NSStringFromClass([self class])) copy];
NSString* authenticationMethod = _GetOption(_options, GCDWebServerOption_AuthenticationMethod, nil);
if ([authenticationMethod isEqualToString:GCDWebServerAuthenticationMethod_Basic]) {
_authenticationRealm = [_GetOption(_options, GCDWebServerOption_AuthenticationRealm, _serverName) copy];
_authenticationBasicAccounts = [[NSMutableDictionary alloc] init];
NSDictionary* accounts = _GetOption(_options, GCDWebServerOption_AuthenticationAccounts, @{});
[accounts enumerateKeysAndObjectsUsingBlock:^(NSString* username, NSString* password, BOOL* stop) {
[_authenticationBasicAccounts setObject:_EncodeBase64([NSString stringWithFormat:@"%@:%@", username, password]) forKey:username];
}];
} else if ([authenticationMethod isEqualToString:GCDWebServerAuthenticationMethod_DigestAccess]) {
_authenticationRealm = [_GetOption(_options, GCDWebServerOption_AuthenticationRealm, _serverName) copy];
_authenticationDigestAccounts = [[NSMutableDictionary alloc] init];
NSDictionary* accounts = _GetOption(_options, GCDWebServerOption_AuthenticationAccounts, @{});
[accounts enumerateKeysAndObjectsUsingBlock:^(NSString* username, NSString* password, BOOL* stop) {
[_authenticationDigestAccounts setObject:GCDWebServerComputeMD5Digest(@"%@:%@:%@", username, _authenticationRealm, password) forKey:username];
}];
}
_connectionClass = _GetOption(_options, GCDWebServerOption_ConnectionClass, [GCDWebServerConnection class]);
_mapHEADToGET = [_GetOption(_options, GCDWebServerOption_AutomaticallyMapHEADToGET, @YES) boolValue];
_disconnectDelay = [_GetOption(_options, GCDWebServerOption_ConnectedStateCoalescingInterval, @1.0) doubleValue];
_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, listeningSocket, 0, kGCDWebServerGCDQueue);
dispatch_source_set_cancel_handler(_source, ^{
@autoreleasepool {
int result = close(listeningSocket);
if (result != 0) {
LOG_ERROR(@"Failed closing socket (%i): %s", errno, strerror(errno));
LOG_ERROR(@"Failed closing listening socket: %s (%i)", strerror(errno), errno);
} else {
LOG_DEBUG(@"Closed listening socket");
LOG_DEBUG(@"Did close listening socket %i", listeningSocket);
}
}
@@ -230,28 +432,27 @@ static void _NetServiceClientCallBack(CFNetServiceRef service, CFStreamError* er
int noSigPipe = 1;
setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, sizeof(noSigPipe)); // Make sure this socket cannot generate SIG_PIPE
Class connectionClass = [[self class] connectionClass];
GCDWebServerConnection* connection = [[connectionClass alloc] initWithServer:self localAddress:localAddress remoteAddress:remoteAddress socket:socket]; // Connection will automatically retain itself while opened
GCDWebServerConnection* connection = [[_connectionClass alloc] initWithServer:self localAddress:localAddress remoteAddress:remoteAddress socket:socket]; // Connection will automatically retain itself while opened
#if __has_feature(objc_arc)
[connection self]; // Prevent compiler from complaining about unused variable / useless statement
#else
[connection release];
#endif
} else {
LOG_ERROR(@"Failed accepting socket (%i): %s", errno, strerror(errno));
LOG_ERROR(@"Failed accepting socket: %s (%i)", strerror(errno), errno);
}
}
});
if (port == 0) { // Determine the actual port we are listening on
if (port == 0) {
struct sockaddr addr;
socklen_t addrlen = sizeof(addr);
if (getsockname(listeningSocket, &addr, &addrlen) == 0) {
struct sockaddr_in* sockaddr = (struct sockaddr_in*)&addr;
_port = ntohs(sockaddr->sin_port);
} else {
LOG_ERROR(@"Failed retrieving socket address (%i): %s", errno, strerror(errno));
LOG_ERROR(@"Failed retrieving socket address: %s (%i)", strerror(errno), errno);
}
} else {
_port = port;
@@ -272,75 +473,141 @@ static void _NetServiceClientCallBack(CFNetServiceRef service, CFStreamError* er
dispatch_resume(_source);
LOG_INFO(@"%@ started on port %i and reachable at %@", [self class], (int)_port, self.serverURL);
if ([_delegate respondsToSelector:@selector(webServerDidStart:)]) {
dispatch_async(dispatch_get_main_queue(), ^{
[_delegate webServerDidStart:self];
});
}
} else {
LOG_ERROR(@"Failed listening on socket (%i): %s", errno, strerror(errno));
LOG_ERROR(@"Failed listening on socket: %s (%i)", strerror(errno), errno);
close(listeningSocket);
}
} else {
LOG_ERROR(@"Failed binding socket (%i): %s", errno, strerror(errno));
LOG_ERROR(@"Failed binding socket: %s (%i)", strerror(errno), errno);
close(listeningSocket);
}
} else {
LOG_ERROR(@"Failed creating socket (%i): %s", errno, strerror(errno));
LOG_ERROR(@"Failed creating socket: %s (%i)", strerror(errno), errno);
}
return (_source ? YES : NO);
}
- (void)_stop {
DCHECK(_source != NULL);
if (_service) {
CFNetServiceUnscheduleFromRunLoop(_service, CFRunLoopGetMain(), kCFRunLoopCommonModes);
CFNetServiceSetClient(_service, NULL, NULL);
CFRelease(_service);
_service = NULL;
}
dispatch_source_cancel(_source); // This will close the socket
ARC_DISPATCH_RELEASE(_source);
_source = NULL;
_port = 0;
ARC_RELEASE(_serverName);
_serverName = nil;
ARC_RELEASE(_authenticationRealm);
_authenticationRealm = nil;
ARC_RELEASE(_authenticationBasicAccounts);
_authenticationBasicAccounts = nil;
ARC_RELEASE(_authenticationDigestAccounts);
_authenticationDigestAccounts = nil;
LOG_INFO(@"%@ stopped", [self class]);
if ([_delegate respondsToSelector:@selector(webServerDidStop:)]) {
dispatch_async(dispatch_get_main_queue(), ^{
[_delegate webServerDidStop:self];
});
}
}
- (BOOL)start {
return [self startWithPort:kDefaultPort bonjourName:@""];
}
- (BOOL)startWithPort:(NSUInteger)port bonjourName:(NSString*)name {
NSMutableDictionary* options = [NSMutableDictionary dictionary];
[options setObject:[NSNumber numberWithInteger:port] forKey:GCDWebServerOption_Port];
[options setValue:name forKey:GCDWebServerOption_BonjourName];
return [self startWithOptions:options];
}
#if TARGET_OS_IPHONE
- (void)_didEnterBackground:(NSNotification*)notification {
DCHECK([NSThread isMainThread]);
LOG_DEBUG(@"Did enter background");
if ((_backgroundTask == UIBackgroundTaskInvalid) && _source) {
[self _stop];
}
}
- (void)_willEnterForeground:(NSNotification*)notification {
DCHECK([NSThread isMainThread]);
LOG_DEBUG(@"Will enter foreground");
if (!_source) {
[self _start]; // TODO: There's probably nothing we can do on failure
}
}
#endif
- (BOOL)startWithOptions:(NSDictionary*)options {
if (_options == nil) {
_options = [options copy];
#if TARGET_OS_IPHONE
_suspendInBackground = [_GetOption(_options, GCDWebServerOption_AutomaticallySuspendInBackground, @YES) boolValue];
if (((_suspendInBackground == NO) || ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground)) && ![self _start])
#else
if (![self _start])
#endif
{
ARC_RELEASE(_options);
_options = nil;
return NO;
}
#if TARGET_OS_IPHONE
if (_suspendInBackground) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_didEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_willEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
}
#endif
return YES;
} else {
DNOT_REACHED();
}
return NO;
}
- (BOOL)isRunning {
return (_source ? YES : NO);
}
- (void)stop {
DCHECK(_source != NULL);
if (_source) {
if (_service) {
CFNetServiceUnscheduleFromRunLoop(_service, CFRunLoopGetMain(), kCFRunLoopCommonModes);
CFNetServiceSetClient(_service, NULL, NULL);
CFRelease(_service);
_service = NULL;
if (_options) {
#if TARGET_OS_IPHONE
if (_suspendInBackground) {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
}
dispatch_source_cancel(_source); // This will close the socket
ARC_DISPATCH_RELEASE(_source);
_source = NULL;
LOG_INFO(@"%@ stopped", [self class]);
#endif
if (_source) {
[self _stop];
}
ARC_RELEASE(_options);
_options = nil;
} else {
DNOT_REACHED();
}
_port = 0;
}
@end
@implementation GCDWebServer (Subclassing)
+ (Class)connectionClass {
return [GCDWebServerConnection class];
}
+ (NSString*)serverName {
return NSStringFromClass(self);
}
+ (BOOL)shouldAutomaticallyMapHEADToGET {
return YES;
}
@end
@implementation GCDWebServer (Extensions)
#if !TARGET_OS_IPHONE
- (void)setRecordingEnabled:(BOOL)flag {
_recording = flag;
}
- (BOOL)isRecordingEnabled {
return _recording;
}
#endif
- (NSURL*)serverURL {
if (_source) {
NSString* ipAddress = GCDWebServerGetPrimaryIPv4Address();
@@ -371,12 +638,20 @@ static void _NetServiceClientCallBack(CFNetServiceRef service, CFStreamError* er
#if !TARGET_OS_IPHONE
- (BOOL)runWithPort:(NSUInteger)port {
- (BOOL)runWithPort:(NSUInteger)port bonjourName:(NSString*)name {
NSMutableDictionary* options = [NSMutableDictionary dictionary];
[options setObject:[NSNumber numberWithInteger:port] forKey:GCDWebServerOption_Port];
[options setValue:name forKey:GCDWebServerOption_BonjourName];
return [self runWithOptions:options];
}
- (BOOL)runWithOptions:(NSDictionary*)options {
DCHECK([NSThread isMainThread]);
BOOL success = NO;
_run = YES;
void (*handler)(int) = signal(SIGINT, _SignalHandler);
if (handler != SIG_ERR) {
if ([self startWithPort:port bonjourName:@""]) {
if ([self startWithOptions:options]) {
while (_run) {
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0, true);
}
@@ -390,175 +665,6 @@ static void _NetServiceClientCallBack(CFNetServiceRef service, CFStreamError* er
#endif
#ifdef __GCDWEBSERVER_ENABLE_TESTING__
static CFHTTPMessageRef _CreateHTTPMessageFromData(NSData* data, BOOL isRequest) {
CFHTTPMessageRef message = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, isRequest);
if (CFHTTPMessageAppendBytes(message, data.bytes, data.length)) {
return message;
}
CFRelease(message);
return NULL;
}
static CFHTTPMessageRef _CreateHTTPMessageFromPerformingRequest(NSData* inData, NSUInteger port) {
CFHTTPMessageRef response = NULL;
int httpSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (httpSocket > 0) {
struct sockaddr_in addr4;
bzero(&addr4, sizeof(addr4));
addr4.sin_len = sizeof(port);
addr4.sin_family = AF_INET;
addr4.sin_port = htons(8080);
addr4.sin_addr.s_addr = htonl(INADDR_ANY);
if (connect(httpSocket, (void*)&addr4, sizeof(addr4)) == 0) {
if (write(httpSocket, inData.bytes, inData.length) == (ssize_t)inData.length) {
NSMutableData* outData = [[NSMutableData alloc] initWithLength:(256 * 1024)];
NSUInteger length = 0;
while (1) {
ssize_t result = read(httpSocket, (char*)outData.mutableBytes + length, outData.length - length);
if (result < 0) {
length = NSNotFound;
break;
} else if (result == 0) {
break;
}
length += result;
if (length >= outData.length) {
outData.length = 2 * outData.length;
}
}
if (length != NSNotFound) {
outData.length = length;
response = _CreateHTTPMessageFromData(outData, NO);
} else {
DNOT_REACHED();
}
ARC_RELEASE(outData);
}
}
close(httpSocket);
}
return response;
}
static void _LogResult(NSString* format, ...) {
va_list arguments;
va_start(arguments, format);
NSString* message = [[NSString alloc] initWithFormat:format arguments:arguments];
va_end(arguments);
fprintf(stdout, "%s\n", [message UTF8String]);
ARC_RELEASE(message);
}
- (NSInteger)runTestsInDirectory:(NSString*)path withPort:(NSUInteger)port {
NSArray* ignoredHeaders = @[@"Date", @"Etag"]; // Dates are always different by definition and ETags depend on file system node IDs
NSInteger result = -1;
if ([self startWithPort:port bonjourName:nil]) {
result = 0;
NSArray* files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
for (NSString* requestFile in files) {
if (![requestFile hasSuffix:@".request"]) {
continue;
}
@autoreleasepool {
NSString* index = [[requestFile componentsSeparatedByString:@"-"] firstObject];
BOOL success = NO;
NSData* requestData = [NSData dataWithContentsOfFile:[path stringByAppendingPathComponent:requestFile]];
if (requestData) {
CFHTTPMessageRef request = _CreateHTTPMessageFromData(requestData, YES);
if (request) {
NSString* requestMethod = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyRequestMethod(request));
NSURL* requestURL = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyRequestURL(request));
_LogResult(@"[%i] %@ %@", (int)[index integerValue], requestMethod, requestURL.path);
NSString* prefix = [index stringByAppendingString:@"-"];
for (NSString* responseFile in files) {
if ([responseFile hasPrefix:prefix] && [responseFile hasSuffix:@".response"]) {
NSData* responseData = [NSData dataWithContentsOfFile:[path stringByAppendingPathComponent:responseFile]];
if (responseData) {
CFHTTPMessageRef expectedResponse = _CreateHTTPMessageFromData(responseData, NO);
if (expectedResponse) {
CFHTTPMessageRef actualResponse = _CreateHTTPMessageFromPerformingRequest(requestData, port);
if (actualResponse) {
success = YES;
CFIndex expectedStatusCode = CFHTTPMessageGetResponseStatusCode(expectedResponse);
CFIndex actualStatusCode = CFHTTPMessageGetResponseStatusCode(actualResponse);
if (actualStatusCode != expectedStatusCode) {
_LogResult(@" Status code not matching:\n Expected: %i\n Actual: %i", (int)expectedStatusCode, (int)actualStatusCode);
success = NO;
}
NSDictionary* expectedHeaders = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyAllHeaderFields(expectedResponse));
NSDictionary* actualHeaders = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyAllHeaderFields(actualResponse));
for (NSString* expectedHeader in expectedHeaders) {
if ([ignoredHeaders containsObject:expectedHeader]) {
continue;
}
NSString* expectedValue = [expectedHeaders objectForKey:expectedHeader];
NSString* actualValue = [actualHeaders objectForKey:expectedHeader];
if (![actualValue isEqualToString:expectedValue]) {
_LogResult(@" Header '%@' not matching:\n Expected: \"%@\"\n Actual: \"%@\"", expectedHeader, expectedValue, actualValue);
success = NO;
}
}
for (NSString* actualHeader in actualHeaders) {
if (![expectedHeaders objectForKey:actualHeader]) {
_LogResult(@" Header '%@' not matching:\n Expected: \"%@\"\n Actual: \"%@\"", actualHeader, nil, [actualHeaders objectForKey:actualHeader]);
success = NO;
}
}
NSData* expectedBody = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyBody(expectedResponse));
NSData* actualBody = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyBody(actualResponse));
if (![actualBody isEqualToData:expectedBody]) {
_LogResult(@" Bodies not matching:\n Expected: %lu bytes\n Actual: %lu bytes", (unsigned long)expectedBody.length, (unsigned long)actualBody.length);
success = NO;
#ifndef NDEBUG
if (GCDWebServerIsTextContentType([expectedHeaders objectForKey:@"Content-Type"])) {
NSString* expectedPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[[NSProcessInfo processInfo] globallyUniqueString] stringByAppendingPathExtension:@"txt"]];
NSString* actualPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[[NSProcessInfo processInfo] globallyUniqueString] stringByAppendingPathExtension:@"txt"]];
if ([expectedBody writeToFile:expectedPath atomically:YES] && [actualBody writeToFile:actualPath atomically:YES]) {
NSTask* task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/opendiff"];
[task setArguments:@[expectedPath, actualPath]];
[task launch];
ARC_RELEASE(task);
}
}
#endif
}
CFRelease(actualResponse);
}
CFRelease(expectedResponse);
}
} else {
DNOT_REACHED();
}
break;
}
}
CFRelease(request);
}
} else {
DNOT_REACHED();
}
_LogResult(@"");
if (!success) {
++result;
}
}
}
[self stop];
}
return result;
}
#endif
@end
@implementation GCDWebServer (Handlers)
@@ -770,3 +876,186 @@ static void _LogResult(NSString* format, ...) {
}
@end
#ifdef __GCDWEBSERVER_ENABLE_TESTING__
@implementation GCDWebServer (Testing)
- (void)setRecordingEnabled:(BOOL)flag {
_recording = flag;
}
- (BOOL)isRecordingEnabled {
return _recording;
}
static CFHTTPMessageRef _CreateHTTPMessageFromData(NSData* data, BOOL isRequest) {
CFHTTPMessageRef message = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, isRequest);
if (CFHTTPMessageAppendBytes(message, data.bytes, data.length)) {
return message;
}
CFRelease(message);
return NULL;
}
static CFHTTPMessageRef _CreateHTTPMessageFromPerformingRequest(NSData* inData, NSUInteger port) {
CFHTTPMessageRef response = NULL;
int httpSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (httpSocket > 0) {
struct sockaddr_in addr4;
bzero(&addr4, sizeof(addr4));
addr4.sin_len = sizeof(port);
addr4.sin_family = AF_INET;
addr4.sin_port = htons(8080);
addr4.sin_addr.s_addr = htonl(INADDR_ANY);
if (connect(httpSocket, (void*)&addr4, sizeof(addr4)) == 0) {
if (write(httpSocket, inData.bytes, inData.length) == (ssize_t)inData.length) {
NSMutableData* outData = [[NSMutableData alloc] initWithLength:(256 * 1024)];
NSUInteger length = 0;
while (1) {
ssize_t result = read(httpSocket, (char*)outData.mutableBytes + length, outData.length - length);
if (result < 0) {
length = NSNotFound;
break;
} else if (result == 0) {
break;
}
length += result;
if (length >= outData.length) {
outData.length = 2 * outData.length;
}
}
if (length != NSNotFound) {
outData.length = length;
response = _CreateHTTPMessageFromData(outData, NO);
} else {
DNOT_REACHED();
}
ARC_RELEASE(outData);
}
}
close(httpSocket);
}
return response;
}
static void _LogResult(NSString* format, ...) {
va_list arguments;
va_start(arguments, format);
NSString* message = [[NSString alloc] initWithFormat:format arguments:arguments];
va_end(arguments);
fprintf(stdout, "%s\n", [message UTF8String]);
ARC_RELEASE(message);
}
- (NSInteger)runTestsWithOptions:(NSDictionary*)options inDirectory:(NSString*)path {
NSArray* ignoredHeaders = @[@"Date", @"Etag"]; // Dates are always different by definition and ETags depend on file system node IDs
NSInteger result = -1;
if ([self startWithOptions:options]) {
result = 0;
NSArray* files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
for (NSString* requestFile in files) {
if (![requestFile hasSuffix:@".request"]) {
continue;
}
@autoreleasepool {
NSString* index = [[requestFile componentsSeparatedByString:@"-"] firstObject];
BOOL success = NO;
NSData* requestData = [NSData dataWithContentsOfFile:[path stringByAppendingPathComponent:requestFile]];
if (requestData) {
CFHTTPMessageRef request = _CreateHTTPMessageFromData(requestData, YES);
if (request) {
NSString* requestMethod = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyRequestMethod(request));
NSURL* requestURL = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyRequestURL(request));
_LogResult(@"[%i] %@ %@", (int)[index integerValue], requestMethod, requestURL.path);
NSString* prefix = [index stringByAppendingString:@"-"];
for (NSString* responseFile in files) {
if ([responseFile hasPrefix:prefix] && [responseFile hasSuffix:@".response"]) {
NSData* responseData = [NSData dataWithContentsOfFile:[path stringByAppendingPathComponent:responseFile]];
if (responseData) {
CFHTTPMessageRef expectedResponse = _CreateHTTPMessageFromData(responseData, NO);
if (expectedResponse) {
CFHTTPMessageRef actualResponse = _CreateHTTPMessageFromPerformingRequest(requestData, self.port);
if (actualResponse) {
success = YES;
CFIndex expectedStatusCode = CFHTTPMessageGetResponseStatusCode(expectedResponse);
CFIndex actualStatusCode = CFHTTPMessageGetResponseStatusCode(actualResponse);
if (actualStatusCode != expectedStatusCode) {
_LogResult(@" Status code not matching:\n Expected: %i\n Actual: %i", (int)expectedStatusCode, (int)actualStatusCode);
success = NO;
}
NSDictionary* expectedHeaders = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyAllHeaderFields(expectedResponse));
NSDictionary* actualHeaders = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyAllHeaderFields(actualResponse));
for (NSString* expectedHeader in expectedHeaders) {
if ([ignoredHeaders containsObject:expectedHeader]) {
continue;
}
NSString* expectedValue = [expectedHeaders objectForKey:expectedHeader];
NSString* actualValue = [actualHeaders objectForKey:expectedHeader];
if (![actualValue isEqualToString:expectedValue]) {
_LogResult(@" Header '%@' not matching:\n Expected: \"%@\"\n Actual: \"%@\"", expectedHeader, expectedValue, actualValue);
success = NO;
}
}
for (NSString* actualHeader in actualHeaders) {
if (![expectedHeaders objectForKey:actualHeader]) {
_LogResult(@" Header '%@' not matching:\n Expected: \"%@\"\n Actual: \"%@\"", actualHeader, nil, [actualHeaders objectForKey:actualHeader]);
success = NO;
}
}
NSData* expectedBody = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyBody(expectedResponse));
NSData* actualBody = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyBody(actualResponse));
if (![actualBody isEqualToData:expectedBody]) {
_LogResult(@" Bodies not matching:\n Expected: %lu bytes\n Actual: %lu bytes", (unsigned long)expectedBody.length, (unsigned long)actualBody.length);
success = NO;
#if !TARGET_OS_IPHONE
#ifndef NDEBUG
if (GCDWebServerIsTextContentType([expectedHeaders objectForKey:@"Content-Type"])) {
NSString* expectedPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[[NSProcessInfo processInfo] globallyUniqueString] stringByAppendingPathExtension:@"txt"]];
NSString* actualPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[[NSProcessInfo processInfo] globallyUniqueString] stringByAppendingPathExtension:@"txt"]];
if ([expectedBody writeToFile:expectedPath atomically:YES] && [actualBody writeToFile:actualPath atomically:YES]) {
NSTask* task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/opendiff"];
[task setArguments:@[expectedPath, actualPath]];
[task launch];
ARC_RELEASE(task);
}
}
#endif
#endif
}
CFRelease(actualResponse);
}
CFRelease(expectedResponse);
}
} else {
DNOT_REACHED();
}
break;
}
}
CFRelease(request);
}
} else {
DNOT_REACHED();
}
_LogResult(@"");
if (!success) {
++result;
}
}
}
[self stop];
}
return result;
}
@end
#endif

View File

@@ -39,12 +39,14 @@
@property(nonatomic, readonly) NSUInteger totalBytesWritten;
@end
// These methods can be called from any thread
@interface GCDWebServerConnection (Subclassing)
- (void)open;
- (void)didUpdateBytesRead; // Called from arbitrary thread after @totalBytesRead is updated - Default implementation does nothing
- (void)didUpdateBytesWritten; // Called from arbitrary thread after @totalBytesWritten is updated - Default implementation does nothing
- (BOOL)open; // Return NO to reject connection e.g. after validating local or remote addresses
- (void)didReadBytes:(const void*)bytes length:(NSUInteger)length; // Called after data has been read from the connection
- (void)didWriteBytes:(const void*)bytes length:(NSUInteger)length; // Called after data has been written to the connection
- (GCDWebServerResponse*)preflightRequest:(GCDWebServerRequest*)request; // Called before request is processed to return an override response bypassing processing or nil to continue - Default implementation checks authentication if applicable
- (GCDWebServerResponse*)processRequest:(GCDWebServerRequest*)request withBlock:(GCDWebServerProcessBlock)block; // Only called if the request can be processed
- (GCDWebServerResponse*)replaceResponse:(GCDWebServerResponse*)response forRequest:(GCDWebServerRequest*)request; // Default implementation replaces any response matching the "ETag" or "Last-Modified-Date" header of the request by a barebone "Not-Modified" (304) one
- (void)abortRequest:(GCDWebServerRequest*)request withStatusCode:(NSInteger)statusCode; // If request headers was malformed, "request" will be nil
- (GCDWebServerResponse*)overrideResponse:(GCDWebServerResponse*)response forRequest:(GCDWebServerRequest*)request; // Default implementation replaces any response matching the "ETag" or "Last-Modified-Date" header of the request by a barebone "Not-Modified" (304) one
- (void)abortRequest:(GCDWebServerRequest*)request withStatusCode:(NSInteger)statusCode; // If request headers were malformed, "request" will be nil
- (void)close;
@end

View File

@@ -27,20 +27,19 @@
#import <TargetConditionals.h>
#import <netdb.h>
#if !TARGET_OS_IPHONE
#ifdef __GCDWEBSERVER_ENABLE_TESTING__
#import <libkern/OSAtomic.h>
#endif
#import "GCDWebServerPrivate.h"
#define kHeadersReadBuffer 1024
#define kHeadersReadCapacity (1 * 1024)
#define kBodyReadCapacity (256 * 1024)
typedef void (^ReadBufferCompletionBlock)(dispatch_data_t buffer);
typedef void (^ReadDataCompletionBlock)(NSData* data);
typedef void (^ReadDataCompletionBlock)(BOOL success);
typedef void (^ReadHeadersCompletionBlock)(NSData* extraData);
typedef void (^ReadBodyCompletionBlock)(BOOL success);
typedef void (^WriteBufferCompletionBlock)(BOOL success);
typedef void (^WriteDataCompletionBlock)(BOOL success);
typedef void (^WriteHeadersCompletionBlock)(BOOL success);
typedef void (^WriteBodyCompletionBlock)(BOOL success);
@@ -49,7 +48,8 @@ static NSData* _CRLFData = nil;
static NSData* _CRLFCRLFData = nil;
static NSData* _continueData = nil;
static NSData* _lastChunkData = nil;
#if !TARGET_OS_IPHONE
static NSString* _digestAuthenticationNonce = nil;
#ifdef __GCDWEBSERVER_ENABLE_TESTING__
static int32_t _connectionCounter = 0;
#endif
@@ -70,7 +70,8 @@ static int32_t _connectionCounter = 0;
GCDWebServerResponse* _response;
NSInteger _statusCode;
#if !TARGET_OS_IPHONE
BOOL _opened;
#ifdef __GCDWEBSERVER_ENABLE_TESTING__
NSUInteger _connectionIndex;
NSString* _requestPath;
int _requestFD;
@@ -82,87 +83,50 @@ static int32_t _connectionCounter = 0;
@implementation GCDWebServerConnection (Read)
- (void)_readBufferWithLength:(NSUInteger)length completionBlock:(ReadBufferCompletionBlock)block {
- (void)_readData:(NSMutableData*)data withLength:(NSUInteger)length completionBlock:(ReadDataCompletionBlock)block {
dispatch_read(_socket, length, kGCDWebServerGCDQueue, ^(dispatch_data_t buffer, int error) {
@autoreleasepool {
if (error == 0) {
size_t size = dispatch_data_get_size(buffer);
if (size > 0) {
LOG_DEBUG(@"Connection received %zu bytes on socket %i", size, _socket);
_bytesRead += size;
[self didUpdateBytesRead];
#if !TARGET_OS_IPHONE
if (_requestFD > 0) {
bool success = dispatch_data_apply(buffer, ^bool(dispatch_data_t region, size_t chunkOffset, const void* chunkBytes, size_t chunkSize) {
return (write(_requestFD, chunkBytes, chunkSize) == (ssize_t)chunkSize);
});
if (!success) {
LOG_ERROR(@"Failed recording request data: %s (%i)", strerror(errno), errno);
close(_requestFD);
_requestFD = 0;
}
}
#endif
block(buffer);
NSUInteger originalLength = data.length;
dispatch_data_apply(buffer, ^bool(dispatch_data_t region, size_t chunkOffset, const void* chunkBytes, size_t chunkSize) {
[data appendBytes:chunkBytes length:chunkSize];
return true;
});
[self didReadBytes:((char*)data.bytes + originalLength) length:(data.length - originalLength)];
block(YES);
} else {
if (_bytesRead > 0) {
LOG_ERROR(@"No more data available on socket %i", _socket);
} else {
LOG_WARNING(@"No data received from socket %i", _socket);
}
block(NULL);
block(NO);
}
} else {
LOG_ERROR(@"Error while reading from socket %i: %s (%i)", _socket, strerror(error), error);
block(NULL);
block(NO);
}
}
});
}
- (void)_readDataWithCompletionBlock:(ReadDataCompletionBlock)block {
[self _readBufferWithLength:SIZE_T_MAX completionBlock:^(dispatch_data_t buffer) {
if (buffer) {
NSMutableData* data = [[NSMutableData alloc] initWithCapacity:dispatch_data_get_size(buffer)];
dispatch_data_apply(buffer, ^bool(dispatch_data_t region, size_t chunkOffset, const void* chunkBytes, size_t chunkSize) {
[data appendBytes:chunkBytes length:chunkSize];
return true;
});
block(data);
ARC_RELEASE(data);
} else {
block(nil);
}
}];
}
- (void)_readHeadersWithCompletionBlock:(ReadHeadersCompletionBlock)block {
- (void)_readHeaders:(NSMutableData*)headersData withCompletionBlock:(ReadHeadersCompletionBlock)block {
DCHECK(_requestMessage);
[self _readBufferWithLength:SIZE_T_MAX completionBlock:^(dispatch_data_t buffer) {
[self _readData:headersData withLength:NSUIntegerMax completionBlock:^(BOOL success) {
if (buffer) {
NSMutableData* data = [NSMutableData dataWithCapacity:kHeadersReadBuffer];
dispatch_data_apply(buffer, ^bool(dispatch_data_t region, size_t chunkOffset, const void* chunkBytes, size_t chunkSize) {
[data appendBytes:chunkBytes length:chunkSize];
return true;
});
NSRange range = [data rangeOfData:_CRLFCRLFData options:0 range:NSMakeRange(0, data.length)];
if (success) {
NSRange range = [headersData rangeOfData:_CRLFCRLFData options:0 range:NSMakeRange(0, headersData.length)];
if (range.location == NSNotFound) {
if (CFHTTPMessageAppendBytes(_requestMessage, data.bytes, data.length)) {
[self _readHeadersWithCompletionBlock:block];
} else {
LOG_ERROR(@"Failed appending request headers data from socket %i", _socket);
block(nil);
}
[self _readHeaders:headersData withCompletionBlock:block];
} else {
NSUInteger length = range.location + range.length;
if (CFHTTPMessageAppendBytes(_requestMessage, data.bytes, length)) {
if (CFHTTPMessageAppendBytes(_requestMessage, headersData.bytes, length)) {
if (CFHTTPMessageIsHeaderComplete(_requestMessage)) {
block([data subdataWithRange:NSMakeRange(length, data.length - length)]);
block([headersData subdataWithRange:NSMakeRange(length, headersData.length - length)]);
} else {
LOG_ERROR(@"Failed parsing request headers from socket %i", _socket);
block(nil);
@@ -181,27 +145,21 @@ static int32_t _connectionCounter = 0;
- (void)_readBodyWithRemainingLength:(NSUInteger)length completionBlock:(ReadBodyCompletionBlock)block {
DCHECK([_request hasBody] && ![_request usesChunkedTransferEncoding]);
[self _readBufferWithLength:length completionBlock:^(dispatch_data_t buffer) {
NSMutableData* bodyData = [[NSMutableData alloc] initWithCapacity:kBodyReadCapacity];
[self _readData:bodyData withLength:length completionBlock:^(BOOL success) {
if (buffer) {
if (dispatch_data_get_size(buffer) <= length) {
bool success = dispatch_data_apply(buffer, ^bool(dispatch_data_t region, size_t chunkOffset, const void* chunkBytes, size_t chunkSize) {
NSData* data = [NSData dataWithBytesNoCopy:(void*)chunkBytes length:chunkSize freeWhenDone:NO];
NSError* error = nil;
if (![_request performWriteData:data error:&error]) {
LOG_ERROR(@"Failed writing request body on socket %i: %@", _socket, error);
return false;
}
return true;
});
if (success) {
NSUInteger remainingLength = length - dispatch_data_get_size(buffer);
if (success) {
if (bodyData.length <= length) {
NSError* error = nil;
if ([_request performWriteData:bodyData error:&error]) {
NSUInteger remainingLength = length - bodyData.length;
if (remainingLength) {
[self _readBodyWithRemainingLength:remainingLength completionBlock:block];
} else {
block(YES);
}
} else {
LOG_ERROR(@"Failed writing request body on socket %i: %@", _socket, error);
block(NO);
}
} else {
@@ -214,6 +172,7 @@ static int32_t _connectionCounter = 0;
}
}];
ARC_RELEASE(bodyData);
}
static inline NSUInteger _ScanHexNumber(const void* bytes, NSUInteger size) {
@@ -269,13 +228,9 @@ static inline NSUInteger _ScanHexNumber(const void* bytes, NSUInteger size) {
}
}
[self _readBufferWithLength:SIZE_T_MAX completionBlock:^(dispatch_data_t buffer) {
[self _readData:chunkData withLength:NSUIntegerMax completionBlock:^(BOOL success) {
if (buffer) {
dispatch_data_apply(buffer, ^bool(dispatch_data_t region, size_t chunkOffset, const void* chunkBytes, size_t chunkSize) {
[chunkData appendBytes:chunkBytes length:chunkSize];
return true;
});
if (success) {
[self _readNextBodyChunk:chunkData completionBlock:block];
} else {
block(NO);
@@ -288,44 +243,6 @@ static inline NSUInteger _ScanHexNumber(const void* bytes, NSUInteger size) {
@implementation GCDWebServerConnection (Write)
- (void)_writeBuffer:(dispatch_data_t)buffer withCompletionBlock:(WriteBufferCompletionBlock)block {
size_t size = dispatch_data_get_size(buffer);
#if !TARGET_OS_IPHONE
ARC_DISPATCH_RETAIN(buffer);
#endif
dispatch_write(_socket, buffer, kGCDWebServerGCDQueue, ^(dispatch_data_t data, int error) {
@autoreleasepool {
if (error == 0) {
DCHECK(data == NULL);
LOG_DEBUG(@"Connection sent %zu bytes on socket %i", size, _socket);
_bytesWritten += size;
[self didUpdateBytesWritten];
#if !TARGET_OS_IPHONE
if (_responseFD > 0) {
bool success = dispatch_data_apply(buffer, ^bool(dispatch_data_t region, size_t chunkOffset, const void* chunkBytes, size_t chunkSize) {
return (write(_responseFD, chunkBytes, chunkSize) == (ssize_t)chunkSize);
});
if (!success) {
LOG_ERROR(@"Failed recording response data: %s (%i)", strerror(errno), errno);
close(_responseFD);
_responseFD = 0;
}
}
#endif
block(YES);
} else {
LOG_ERROR(@"Error while writing to socket %i: %s (%i)", _socket, strerror(error), error);
block(NO);
}
}
#if !TARGET_OS_IPHONE
ARC_DISPATCH_RELEASE(buffer);
#endif
});
}
- (void)_writeData:(NSData*)data withCompletionBlock:(WriteDataCompletionBlock)block {
#if !__has_feature(objc_arc)
[data retain];
@@ -337,15 +254,28 @@ static inline NSUInteger _ScanHexNumber(const void* bytes, NSUInteger size) {
[data release];
#endif
});
[self _writeBuffer:buffer withCompletionBlock:block];
dispatch_write(_socket, buffer, kGCDWebServerGCDQueue, ^(dispatch_data_t remainingData, int error) {
@autoreleasepool {
if (error == 0) {
DCHECK(remainingData == NULL);
[self didWriteBytes:data.bytes length:data.length];
block(YES);
} else {
LOG_ERROR(@"Error while writing to socket %i: %s (%i)", _socket, strerror(error), error);
block(NO);
}
}
});
ARC_DISPATCH_RELEASE(buffer);
}
- (void)_writeHeadersWithCompletionBlock:(WriteHeadersCompletionBlock)block {
DCHECK(_responseMessage);
CFDataRef message = CFHTTPMessageCopySerializedMessage(_responseMessage);
[self _writeData:(ARC_BRIDGE NSData*)message withCompletionBlock:block];
CFRelease(message);
CFDataRef data = CFHTTPMessageCopySerializedMessage(_responseMessage);
[self _writeData:(ARC_BRIDGE NSData*)data withCompletionBlock:block];
CFRelease(data);
}
- (void)_writeBodyWithCompletionBlock:(WriteBodyCompletionBlock)block {
@@ -428,13 +358,18 @@ static inline NSUInteger _ScanHexNumber(const void* bytes, NSUInteger size) {
if (_lastChunkData == nil) {
_lastChunkData = [[NSData alloc] initWithBytes:"0\r\n\r\n" length:5];
}
if (_digestAuthenticationNonce == nil) {
CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
_digestAuthenticationNonce = ARC_RETAIN(GCDWebServerComputeMD5Digest(@"%@", ARC_BRIDGE_RELEASE(CFUUIDCreateString(kCFAllocatorDefault, uuid))));
CFRelease(uuid);
}
}
- (void)_initializeResponseHeadersWithStatusCode:(NSInteger)statusCode {
_statusCode = statusCode;
_responseMessage = CFHTTPMessageCreateResponse(kCFAllocatorDefault, statusCode, NULL, kCFHTTPVersion1_1);
CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Connection"), CFSTR("Close"));
CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Server"), (ARC_BRIDGE CFStringRef)[[_server class] serverName]);
CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Server"), (ARC_BRIDGE CFStringRef)_server.serverName);
CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Date"), (ARC_BRIDGE CFStringRef)GCDWebServerFormatRFC822([NSDate date]));
}
@@ -443,20 +378,23 @@ static inline NSUInteger _ScanHexNumber(const void* bytes, NSUInteger size) {
DCHECK(_responseMessage == NULL);
BOOL hasBody = NO;
GCDWebServerResponse* response = [self processRequest:_request withBlock:_handler.processBlock];
GCDWebServerResponse* response = [self preflightRequest:_request];
if (!response) {
response = [self processRequest:_request withBlock:_handler.processBlock];
}
if (response) {
response = [self replaceResponse:response forRequest:_request];
if (response) {
if ([response hasBody]) {
[response prepareForReading];
hasBody = !_virtualHEAD;
}
NSError* error = nil;
if (hasBody && ![response performOpen:&error]) {
LOG_ERROR(@"Failed opening response body for socket %i: %@", _socket, error);
} else {
_response = ARC_RETAIN(response);
}
response = [self overrideResponse:response forRequest:_request];
}
if (response) {
if ([response hasBody]) {
[response prepareForReading];
hasBody = !_virtualHEAD;
}
NSError* error = nil;
if (hasBody && ![response performOpen:&error]) {
LOG_ERROR(@"Failed opening response body for socket %i: %@", _socket, error);
} else {
_response = ARC_RETAIN(response);
}
}
@@ -575,11 +513,12 @@ static inline NSUInteger _ScanHexNumber(const void* bytes, NSUInteger size) {
- (void)_readRequestHeaders {
_requestMessage = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, true);
[self _readHeadersWithCompletionBlock:^(NSData* extraData) {
NSMutableData* headersData = [[NSMutableData alloc] initWithCapacity:kHeadersReadCapacity];
[self _readHeaders:headersData withCompletionBlock:^(NSData* extraData) {
if (extraData) {
NSString* requestMethod = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyRequestMethod(_requestMessage)); // Method verbs are case-sensitive and uppercase
if ([[_server class] shouldAutomaticallyMapHEADToGET] && [requestMethod isEqualToString:@"HEAD"]) {
if (_server.shouldAutomaticallyMapHEADToGET && [requestMethod isEqualToString:@"HEAD"]) {
requestMethod = @"GET";
_virtualHEAD = YES;
}
@@ -599,9 +538,9 @@ static inline NSUInteger _ScanHexNumber(const void* bytes, NSUInteger size) {
if ([_request hasBody]) {
[_request prepareForWriting];
if (_request.usesChunkedTransferEncoding || (extraData.length <= _request.contentLength)) {
NSString* expectHeader = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyHeaderFieldValue(_requestMessage, CFSTR("Expect")));
NSString* expectHeader = [requestHeaders objectForKey:@"Expect"];
if (expectHeader) {
if ([expectHeader caseInsensitiveCompare:@"100-continue"] == NSOrderedSame) {
if ([expectHeader caseInsensitiveCompare:@"100-continue"] == NSOrderedSame) { // TODO: Actually validate request before continuing
[self _writeData:_continueData withCompletionBlock:^(BOOL success) {
if (success) {
@@ -645,6 +584,7 @@ static inline NSUInteger _ScanHexNumber(const void* bytes, NSUInteger size) {
}
}];
ARC_RELEASE(headersData);
}
- (id)initWithServer:(GCDWebServer*)server localAddress:(NSData*)localAddress remoteAddress:(NSData*)remoteAddress socket:(CFSocketNativeHandle)socket {
@@ -653,8 +593,18 @@ static inline NSUInteger _ScanHexNumber(const void* bytes, NSUInteger size) {
_localAddress = ARC_RETAIN(localAddress);
_remoteAddress = ARC_RETAIN(remoteAddress);
_socket = socket;
LOG_DEBUG(@"Did open connection on socket %i", _socket);
[self open];
[_server willStartConnection:self];
if (![self open]) {
close(_socket);
ARC_RELEASE(self);
return nil;
}
_opened = YES;
[self _readRequestHeaders];
}
return self;
}
@@ -681,8 +631,18 @@ static NSString* _StringFromAddressData(NSData* data) {
}
- (void)dealloc {
[self close];
int result = close(_socket);
if (result != 0) {
LOG_ERROR(@"Failed closing socket %i for connection: %s (%i)", _socket, strerror(errno), errno);
} else {
LOG_DEBUG(@"Did close connection on socket %i", _socket);
}
if (_opened) {
[self close];
}
[_server didEndConnection:self];
ARC_RELEASE(_server);
ARC_RELEASE(_localAddress);
ARC_RELEASE(_remoteAddress);
@@ -697,7 +657,7 @@ static NSString* _StringFromAddressData(NSData* data) {
}
ARC_RELEASE(_response);
#if !TARGET_OS_IPHONE
#ifdef __GCDWEBSERVER_ENABLE_TESTING__
ARC_RELEASE(_requestPath);
ARC_RELEASE(_responsePath);
#endif
@@ -709,10 +669,8 @@ static NSString* _StringFromAddressData(NSData* data) {
@implementation GCDWebServerConnection (Subclassing)
- (void)open {
LOG_DEBUG(@"Did open connection on socket %i", _socket);
#if !TARGET_OS_IPHONE
- (BOOL)open {
#ifdef __GCDWEBSERVER_ENABLE_TESTING__
if (_server.recordingEnabled) {
_connectionIndex = OSAtomicIncrement32(&_connectionCounter);
@@ -726,15 +684,84 @@ static NSString* _StringFromAddressData(NSData* data) {
}
#endif
[self _readRequestHeaders];
return YES;
}
- (void)didUpdateBytesRead {
;
- (void)didReadBytes:(const void*)bytes length:(NSUInteger)length {
LOG_DEBUG(@"Connection received %lu bytes on socket %i", (unsigned long)length, _socket);
_bytesRead += length;
#ifdef __GCDWEBSERVER_ENABLE_TESTING__
if ((_requestFD > 0) && (write(_requestFD, bytes, length) != (ssize_t)length)) {
LOG_ERROR(@"Failed recording request data: %s (%i)", strerror(errno), errno);
close(_requestFD);
_requestFD = 0;
}
#endif
}
- (void)didUpdateBytesWritten {
;
- (void)didWriteBytes:(const void*)bytes length:(NSUInteger)length {
LOG_DEBUG(@"Connection sent %lu bytes on socket %i", (unsigned long)length, _socket);
_bytesWritten += length;
#ifdef __GCDWEBSERVER_ENABLE_TESTING__
if ((_responseFD > 0) && (write(_responseFD, bytes, length) != (ssize_t)length)) {
LOG_ERROR(@"Failed recording response data: %s (%i)", strerror(errno), errno);
close(_responseFD);
_responseFD = 0;
}
#endif
}
// https://tools.ietf.org/html/rfc2617
- (GCDWebServerResponse*)preflightRequest:(GCDWebServerRequest*)request {
LOG_DEBUG(@"Connection on socket %i preflighting request \"%@ %@\" with %lu bytes body", _socket, _virtualHEAD ? @"HEAD" : _request.method, _request.path, (unsigned long)_bytesRead);
GCDWebServerResponse* response = nil;
if (_server.authenticationBasicAccounts) {
__block BOOL authenticated = NO;
NSString* authorizationHeader = [request.headers objectForKey:@"Authorization"];
if ([authorizationHeader hasPrefix:@"Basic "]) {
NSString* basicAccount = [authorizationHeader substringFromIndex:6];
[_server.authenticationBasicAccounts enumerateKeysAndObjectsUsingBlock:^(NSString* username, NSString* digest, BOOL* stop) {
if ([basicAccount isEqualToString:digest]) {
authenticated = YES;
*stop = YES;
}
}];
}
if (!authenticated) {
response = [GCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_Unauthorized];
[response setValue:[NSString stringWithFormat:@"Basic realm=\"%@\"", _server.authenticationRealm] forAdditionalHeader:@"WWW-Authenticate"];
}
} else if (_server.authenticationDigestAccounts) {
BOOL authenticated = NO;
BOOL isStaled = NO;
NSString* authorizationHeader = [request.headers objectForKey:@"Authorization"];
if ([authorizationHeader hasPrefix:@"Digest "]) {
NSString* realm = GCDWebServerExtractHeaderValueParameter(authorizationHeader, @"realm");
if ([realm isEqualToString:_server.authenticationRealm]) {
NSString* nonce = GCDWebServerExtractHeaderValueParameter(authorizationHeader, @"nonce");
if ([nonce isEqualToString:_digestAuthenticationNonce]) {
NSString* username = GCDWebServerExtractHeaderValueParameter(authorizationHeader, @"username");
NSString* uri = GCDWebServerExtractHeaderValueParameter(authorizationHeader, @"uri");
NSString* actualResponse = GCDWebServerExtractHeaderValueParameter(authorizationHeader, @"response");
NSString* ha1 = [_server.authenticationDigestAccounts objectForKey:username];
NSString* ha2 = GCDWebServerComputeMD5Digest(@"%@:%@", request.method, uri); // We cannot use "request.path" as the query string is required
NSString* expectedResponse = GCDWebServerComputeMD5Digest(@"%@:%@:%@", ha1, _digestAuthenticationNonce, ha2);
if ([actualResponse isEqualToString:expectedResponse]) {
authenticated = YES;
}
} else if (nonce.length) {
isStaled = YES;
}
}
}
if (!authenticated) {
response = [GCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_Unauthorized];
[response setValue:[NSString stringWithFormat:@"Digest realm=\"%@\", nonce=\"%@\"%@", _server.authenticationRealm, _digestAuthenticationNonce, isStaled ? @", stale=TRUE" : @""] forAdditionalHeader:@"WWW-Authenticate"]; // TODO: Support Quality of Protection ("qop")
}
}
return response;
}
- (GCDWebServerResponse*)processRequest:(GCDWebServerRequest*)request withBlock:(GCDWebServerProcessBlock)block {
@@ -764,7 +791,7 @@ static inline BOOL _CompareResources(NSString* responseETag, NSString* requestET
return NO;
}
- (GCDWebServerResponse*)replaceResponse:(GCDWebServerResponse*)response forRequest:(GCDWebServerRequest*)request {
- (GCDWebServerResponse*)overrideResponse:(GCDWebServerResponse*)response forRequest:(GCDWebServerRequest*)request {
if ((response.statusCode >= 200) && (response.statusCode < 300) && _CompareResources(response.eTag, request.ifNoneMatch, response.lastModifiedDate, request.ifModifiedSince)) {
NSInteger code = [request.method isEqualToString:@"HEAD"] || [request.method isEqualToString:@"GET"] ? kGCDWebServerHTTPStatusCode_NotModified : kGCDWebServerHTTPStatusCode_PreconditionFailed;
GCDWebServerResponse* newResponse = [GCDWebServerResponse responseWithStatusCode:code];
@@ -788,14 +815,7 @@ static inline BOOL _CompareResources(NSString* responseETag, NSString* requestET
}
- (void)close {
int result = close(_socket);
if (result != 0) {
LOG_ERROR(@"Failed closing socket %i for connection (%i): %s", _socket, errno, strerror(errno));
} else {
LOG_DEBUG(@"Did close connection on socket %i", _socket);
}
#if !TARGET_OS_IPHONE
#ifdef __GCDWEBSERVER_ENABLE_TESTING__
if (_requestPath) {
BOOL success = NO;
NSError* error = nil;
@@ -826,6 +846,7 @@ static inline BOOL _CompareResources(NSString* responseETag, NSString* requestET
unlink([_responsePath fileSystemRepresentation]);
}
#endif
if (_request) {
LOG_VERBOSE(@"[%@] %@ %i \"%@ %@\" (%lu | %lu)", self.localAddressString, self.remoteAddressString, (int)_statusCode, _virtualHEAD ? @"HEAD" : _request.method, _request.path, (unsigned long)_bytesRead, (unsigned long)_bytesWritten);
} else {

View File

@@ -31,6 +31,7 @@
#else
#import <SystemConfiguration/SystemConfiguration.h>
#endif
#import <CommonCrypto/CommonDigest.h>
#import <ifaddrs.h>
#import <net/if.h>
@@ -79,13 +80,11 @@ NSString* GCDWebServerNormalizeHeaderValue(NSString* value) {
}
NSString* GCDWebServerTruncateHeaderValue(NSString* value) {
DCHECK([value isEqualToString:GCDWebServerNormalizeHeaderValue(value)]);
NSRange range = [value rangeOfString:@";"];
return range.location != NSNotFound ? [value substringToIndex:range.location] : value;
}
NSString* GCDWebServerExtractHeaderValueParameter(NSString* value, NSString* name) {
DCHECK([value isEqualToString:GCDWebServerNormalizeHeaderValue(value)]);
NSString* parameter = nil;
NSScanner* scanner = [[NSScanner alloc] initWithString:value];
[scanner setCaseSensitive:NO]; // Assume parameter names are case-insensitive
@@ -266,3 +265,22 @@ NSString* GCDWebServerGetPrimaryIPv4Address() {
}
return address;
}
NSString* GCDWebServerComputeMD5Digest(NSString* format, ...) {
va_list arguments;
va_start(arguments, format);
const char* string = [ARC_AUTORELEASE([[NSString alloc] initWithFormat:format arguments:arguments]) UTF8String];
va_end(arguments);
unsigned char md5[CC_MD5_DIGEST_LENGTH];
CC_MD5(string, (CC_LONG)strlen(string), md5);
char buffer[2 * CC_MD5_DIGEST_LENGTH + 1];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
unsigned char byte = md5[i];
unsigned char byteHi = (byte & 0xF0) >> 4;
buffer[2 * i + 0] = byteHi >= 10 ? 'a' + byteHi - 10 : '0' + byteHi;
unsigned char byteLo = byte & 0x0F;
buffer[2 * i + 1] = byteLo >= 10 ? 'a' + byteLo - 10 : '0' + byteLo;
}
buffer[2 * CC_MD5_DIGEST_LENGTH] = 0;
return [NSString stringWithUTF8String:buffer];
}

View File

@@ -121,6 +121,7 @@ extern NSString* GCDWebServerExtractHeaderValueParameter(NSString* header, NSStr
extern NSStringEncoding GCDWebServerStringEncodingFromCharset(NSString* charset);
extern BOOL GCDWebServerIsTextContentType(NSString* type);
extern NSString* GCDWebServerDescribeData(NSData* data, NSString* contentType);
extern NSString* GCDWebServerComputeMD5Digest(NSString* format, ...) NS_FORMAT_FUNCTION(1,2);
@interface GCDWebServerConnection ()
- (id)initWithServer:(GCDWebServer*)server localAddress:(NSData*)localAddress remoteAddress:(NSData*)remoteAddress socket:(CFSocketNativeHandle)socket;
@@ -128,6 +129,13 @@ extern NSString* GCDWebServerDescribeData(NSData* data, NSString* contentType);
@interface GCDWebServer ()
@property(nonatomic, readonly) NSArray* handlers;
@property(nonatomic, readonly) NSString* serverName;
@property(nonatomic, readonly) NSString* authenticationRealm;
@property(nonatomic, readonly) NSDictionary* authenticationBasicAccounts;
@property(nonatomic, readonly) NSDictionary* authenticationDigestAccounts;
@property(nonatomic, readonly) BOOL shouldAutomaticallyMapHEADToGET;
- (void)willStartConnection:(GCDWebServerConnection*)connection;
- (void)didEndConnection:(GCDWebServerConnection*)connection;
@end
@interface GCDWebServerHandler : NSObject

View File

@@ -43,7 +43,7 @@
@property(nonatomic, readonly) NSUInteger contentLength; // Automatically parsed from headers (NSNotFound if request has no "Content-Length" header)
@property(nonatomic, readonly) NSDate* ifModifiedSince; // Automatically parsed from headers (nil if request has no "If-Modified-Since" header or it is malformatted)
@property(nonatomic, readonly) NSString* ifNoneMatch; // Automatically parsed from headers (nil if request has no "If-None-Match" header)
@property(nonatomic, readonly) NSRange byteRange; // Automatically parsed from headers ([NSNotFound, 0] if request has no "Range" header, [offset, length] for byte range from beginning or [NSNotFound, -bytes] from end)
@property(nonatomic, readonly) NSRange byteRange; // Automatically parsed from headers ([NSNotFound, 0] if request has no "Range" header, [offset, length] for byte range from beginning or [NSNotFound, -length] from end)
@property(nonatomic, readonly) BOOL acceptsGzipContentEncoding; // Automatically parsed from headers
- (instancetype)initWithMethod:(NSString*)method url:(NSURL*)url headers:(NSDictionary*)headers path:(NSString*)path query:(NSDictionary*)query;
- (BOOL)hasBody; // Convenience method that checks if "contentType" is not nil

View File

@@ -28,7 +28,7 @@
#import "GCDWebServerRequest.h"
@interface GCDWebServerMultiPart : NSObject
@property(nonatomic, readonly) NSString* contentType; // Defaults to "text/plain" per specifications if undefined
@property(nonatomic, readonly) NSString* contentType; // Defaults to "text/plain" per specification if undefined
@property(nonatomic, readonly) NSString* mimeType;
@end

View File

@@ -228,27 +228,34 @@ static NSData* _dashNewlineData = nil;
_contentType = nil;
ARC_RELEASE(_tmpPath);
_tmpPath = nil;
CFHTTPMessageRef message = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, true);
const char* temp = "GET / HTTP/1.0\r\n";
CFHTTPMessageAppendBytes(message, (const UInt8*)temp, strlen(temp));
CFHTTPMessageAppendBytes(message, _parserData.bytes, range.location + range.length);
if (CFHTTPMessageIsHeaderComplete(message)) {
NSString* controlName = nil;
NSString* fileName = nil;
NSDictionary* headers = ARC_BRIDGE_RELEASE(CFHTTPMessageCopyAllHeaderFields(message));
NSString* contentDisposition = GCDWebServerNormalizeHeaderValue([headers objectForKey:@"Content-Disposition"]);
if ([GCDWebServerTruncateHeaderValue(contentDisposition) isEqualToString:@"form-data"]) {
controlName = GCDWebServerExtractHeaderValueParameter(contentDisposition, @"name");
fileName = GCDWebServerExtractHeaderValueParameter(contentDisposition, @"filename");
NSString* headers = [[NSString alloc] initWithData:[_parserData subdataWithRange:NSMakeRange(0, range.location)] encoding:NSUTF8StringEncoding];
if (headers) {
for (NSString* header in [headers componentsSeparatedByString:@"\r\n"]) {
NSRange subRange = [header rangeOfString:@":"];
if (subRange.location != NSNotFound) {
NSString* name = [header substringToIndex:subRange.location];
NSString* value = [[header substringFromIndex:(subRange.location + subRange.length)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if ([name caseInsensitiveCompare:@"Content-Type"] == NSOrderedSame) {
_contentType = ARC_RETAIN(GCDWebServerNormalizeHeaderValue(value));
} else if ([name caseInsensitiveCompare:@"Content-Disposition"] == NSOrderedSame) {
NSString* contentDisposition = GCDWebServerNormalizeHeaderValue(value);
if ([GCDWebServerTruncateHeaderValue(contentDisposition) isEqualToString:@"form-data"]) {
_controlName = ARC_RETAIN(GCDWebServerExtractHeaderValueParameter(contentDisposition, @"name"));
_fileName = ARC_RETAIN(GCDWebServerExtractHeaderValueParameter(contentDisposition, @"filename"));
}
}
} else {
DNOT_REACHED();
}
}
_controlName = [controlName copy];
_fileName = [fileName copy];
_contentType = ARC_RETAIN(GCDWebServerNormalizeHeaderValue([headers objectForKey:@"Content-Type"]));
if (_contentType == nil) {
_contentType = @"text/plain";
}
ARC_RELEASE(headers);
} else {
LOG_ERROR(@"Failed decoding headers in part of 'multipart/form-data'");
DNOT_REACHED();
}
CFRelease(message);
if (_controlName) {
if (_fileName) {
NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]];

View File

@@ -33,7 +33,7 @@
+ (instancetype)responseWithFile:(NSString*)path byteRange:(NSRange)range;
+ (instancetype)responseWithFile:(NSString*)path byteRange:(NSRange)range isAttachment:(BOOL)attachment;
- (instancetype)initWithFile:(NSString*)path;
- (instancetype)initWithFile:(NSString*)path isAttachment:(BOOL)attachment;
- (instancetype)initWithFile:(NSString*)path byteRange:(NSRange)range; // Pass [NSNotFound, 0] to disable byte range entirely, [offset, length] to enable byte range from beginning of file or [NSNotFound, -bytes] from end of file
- (instancetype)initWithFile:(NSString*)path isAttachment:(BOOL)attachment; // If in attachment mode, "Content-Disposition" header will be set accordingly
- (instancetype)initWithFile:(NSString*)path byteRange:(NSRange)range; // Pass [NSNotFound, 0] to disable byte range entirely, [offset, length] to enable byte range from beginning of file or [NSNotFound, -length] from end of file
- (instancetype)initWithFile:(NSString*)path byteRange:(NSRange)range isAttachment:(BOOL)attachment;
@end

View File

@@ -112,12 +112,14 @@ static inline NSDate* _NSDateFromTimeSpec(const struct timespec* t) {
_size = (NSUInteger)info.st_size;
}
if (attachment) { // TODO: Use http://tools.ietf.org/html/rfc5987 to encode file names with special characters instead of using lossy conversion to ISO 8859-1
NSData* data = [[path lastPathComponent] dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:YES];
NSString* fileName = data ? [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding] : nil;
if (fileName) {
[self setValue:[NSString stringWithFormat:@"attachment; filename=\"%@\"", fileName] forAdditionalHeader:@"Content-Disposition"];
ARC_RELEASE(fileName);
if (attachment) {
NSString* fileName = [path lastPathComponent];
NSData* data = [[fileName stringByReplacingOccurrencesOfString:@"\"" withString:@""] dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:YES];
NSString* lossyFileName = data ? [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding] : nil;
if (lossyFileName) {
NSString* value = [NSString stringWithFormat:@"attachment; filename=\"%@\"; filename*=UTF-8''%@", lossyFileName, GCDWebServerEscapeURLString(fileName)];
[self setValue:value forAdditionalHeader:@"Content-Disposition"];
ARC_RELEASE(lossyFileName);
} else {
DNOT_REACHED();
}

View File

@@ -29,7 +29,7 @@
typedef NSData* (^GCDWebServerStreamBlock)(NSError** error);
@interface GCDWebServerStreamingResponse : GCDWebServerResponse // Automatically enables chunked transfer encoding
@interface GCDWebServerStreamingResponse : GCDWebServerResponse
+ (instancetype)responseWithContentType:(NSString*)type streamBlock:(GCDWebServerStreamBlock)block;
- (instancetype)initWithContentType:(NSString*)type streamBlock:(GCDWebServerStreamBlock)block; // Block must return empty NSData when done or nil on error
- (instancetype)initWithContentType:(NSString*)type streamBlock:(GCDWebServerStreamBlock)block; // Block must return empty NSData when done or nil on error and set the "error" argument accordingly
@end

View File

@@ -29,7 +29,8 @@
@class GCDWebUploader;
@protocol GCDWebUploaderDelegate <NSObject>
// These methods are always called on main thread
@protocol GCDWebUploaderDelegate <GCDWebServerDelegate>
@optional
- (void)webUploader:(GCDWebUploader*)uploader didDownloadFileAtPath:(NSString*)path;
- (void)webUploader:(GCDWebUploader*)uploader didUploadFileAtPath:(NSString*)path;
@@ -51,6 +52,7 @@
- (instancetype)initWithUploadDirectory:(NSString*)path;
@end
// These methods can be called from any thread
@interface GCDWebUploader (Subclassing)
- (BOOL)shouldUploadFileAtPath:(NSString*)path withTemporaryFile:(NSString*)tempPath; // Default implementation returns YES
- (BOOL)shouldMoveItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath; // Default implementation returns YES

View File

@@ -45,7 +45,6 @@
@interface GCDWebUploader () {
@private
NSString* _uploadDirectory;
id<GCDWebUploaderDelegate> __unsafe_unretained _delegate;
NSArray* _allowedExtensions;
BOOL _showHidden;
NSString* _title;
@@ -143,9 +142,9 @@
return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Downlading file name \"%@\" is not allowed", fileName];
}
if ([_delegate respondsToSelector:@selector(webUploader:didDownloadFileAtPath: )]) {
if ([self.delegate respondsToSelector:@selector(webUploader:didDownloadFileAtPath: )]) {
dispatch_async(dispatch_get_main_queue(), ^{
[_delegate webUploader:self didDownloadFileAtPath:absolutePath];
[self.delegate webUploader:self didDownloadFileAtPath:absolutePath];
});
}
return [GCDWebServerFileResponse responseWithFile:absolutePath isAttachment:YES];
@@ -171,9 +170,9 @@
return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed moving uploaded file to \"%@\"", relativePath];
}
if ([_delegate respondsToSelector:@selector(webUploader:didUploadFileAtPath:)]) {
if ([self.delegate respondsToSelector:@selector(webUploader:didUploadFileAtPath:)]) {
dispatch_async(dispatch_get_main_queue(), ^{
[_delegate webUploader:self didUploadFileAtPath:absolutePath];
[self.delegate webUploader:self didUploadFileAtPath:absolutePath];
});
}
return [GCDWebServerDataResponse responseWithJSONObject:@{} contentType:contentType];
@@ -204,9 +203,9 @@
return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed moving \"%@\" to \"%@\"", oldRelativePath, newRelativePath];
}
if ([_delegate respondsToSelector:@selector(webUploader:didMoveItemFromPath:toPath:)]) {
if ([self.delegate respondsToSelector:@selector(webUploader:didMoveItemFromPath:toPath:)]) {
dispatch_async(dispatch_get_main_queue(), ^{
[_delegate webUploader:self didMoveItemFromPath:oldAbsolutePath toPath:newAbsolutePath];
[self.delegate webUploader:self didMoveItemFromPath:oldAbsolutePath toPath:newAbsolutePath];
});
}
return [GCDWebServerDataResponse responseWithJSONObject:@{}];
@@ -234,9 +233,9 @@
return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed deleting \"%@\"", relativePath];
}
if ([_delegate respondsToSelector:@selector(webUploader:didDeleteItemAtPath:)]) {
if ([self.delegate respondsToSelector:@selector(webUploader:didDeleteItemAtPath:)]) {
dispatch_async(dispatch_get_main_queue(), ^{
[_delegate webUploader:self didDeleteItemAtPath:absolutePath];
[self.delegate webUploader:self didDeleteItemAtPath:absolutePath];
});
}
return [GCDWebServerDataResponse responseWithJSONObject:@{}];
@@ -260,9 +259,9 @@
return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed creating directory \"%@\"", relativePath];
}
if ([_delegate respondsToSelector:@selector(webUploader:didCreateDirectoryAtPath:)]) {
if ([self.delegate respondsToSelector:@selector(webUploader:didCreateDirectoryAtPath:)]) {
dispatch_async(dispatch_get_main_queue(), ^{
[_delegate webUploader:self didCreateDirectoryAtPath:absolutePath];
[self.delegate webUploader:self didCreateDirectoryAtPath:absolutePath];
});
}
return [GCDWebServerDataResponse responseWithJSONObject:@{}];
@@ -272,7 +271,7 @@
@implementation GCDWebUploader
@synthesize uploadDirectory=_uploadDirectory, delegate=_delegate, allowedFileExtensions=_allowedExtensions, showHiddenFiles=_showHidden,
@synthesize uploadDirectory=_uploadDirectory, allowedFileExtensions=_allowedExtensions, showHiddenFiles=_showHidden,
title=_title, header=_header, prologue=_prologue, epilogue=_epilogue, footer=_footer;
- (instancetype)initWithUploadDirectory:(NSString*)path {

View File

@@ -39,6 +39,10 @@
#import "GCDWebUploader.h"
#ifndef __GCDWEBSERVER_ENABLE_TESTING__
#error __GCDWEBSERVER_ENABLE_TESTING__ must be defined
#endif
typedef enum {
kMode_WebServer = 0,
kMode_HTMLPage,
@@ -48,6 +52,77 @@ typedef enum {
kMode_StreamingResponse
} Mode;
@interface Delegate : NSObject <GCDWebServerDelegate, GCDWebDAVServerDelegate, GCDWebUploaderDelegate>
@end
@implementation Delegate
- (void)_logDelegateCall:(SEL)selector {
fprintf(stdout, "<DELEGATE METHOD \"%s\" CALLED>\n", [NSStringFromSelector(selector) UTF8String]);
}
- (void)webServerDidStart:(GCDWebServer*)server {
[self _logDelegateCall:_cmd];
}
- (void)webServerDidConnect:(GCDWebServer*)server {
[self _logDelegateCall:_cmd];
}
- (void)webServerDidDisconnect:(GCDWebServer*)server {
[self _logDelegateCall:_cmd];
}
- (void)webServerDidStop:(GCDWebServer*)server {
[self _logDelegateCall:_cmd];
}
- (void)davServer:(GCDWebDAVServer*)server didDownloadFileAtPath:(NSString*)path {
[self _logDelegateCall:_cmd];
}
- (void)davServer:(GCDWebDAVServer*)server didUploadFileAtPath:(NSString*)path {
[self _logDelegateCall:_cmd];
}
- (void)davServer:(GCDWebDAVServer*)server didMoveItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath {
[self _logDelegateCall:_cmd];
}
- (void)davServer:(GCDWebDAVServer*)server didCopyItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath {
[self _logDelegateCall:_cmd];
}
- (void)davServer:(GCDWebDAVServer*)server didDeleteItemAtPath:(NSString*)path {
[self _logDelegateCall:_cmd];
}
- (void)davServer:(GCDWebDAVServer*)server didCreateDirectoryAtPath:(NSString*)path {
[self _logDelegateCall:_cmd];
}
- (void)webUploader:(GCDWebUploader*)uploader didDownloadFileAtPath:(NSString*)path {
[self _logDelegateCall:_cmd];
}
- (void)webUploader:(GCDWebUploader*)uploader didUploadFileAtPath:(NSString*)path {
[self _logDelegateCall:_cmd];
}
- (void)webUploader:(GCDWebUploader*)uploader didMoveItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath {
[self _logDelegateCall:_cmd];
}
- (void)webUploader:(GCDWebUploader*)uploader didDeleteItemAtPath:(NSString*)path {
[self _logDelegateCall:_cmd];
}
- (void)webUploader:(GCDWebUploader*)uploader didCreateDirectoryAtPath:(NSString*)path {
[self _logDelegateCall:_cmd];
}
@end
int main(int argc, const char* argv[]) {
int result = -1;
@autoreleasepool {
@@ -55,9 +130,13 @@ int main(int argc, const char* argv[]) {
BOOL recording = NO;
NSString* rootDirectory = NSHomeDirectory();
NSString* testDirectory = nil;
NSString* authenticationMethod = nil;
NSString* authenticationRealm = nil;
NSString* authenticationUser = nil;
NSString* authenticationPassword = nil;
if (argc == 1) {
fprintf(stdout, "Usage: %s [-mode webServer | htmlPage | htmlForm | webDAV | webUploader | streamingResponse] [-record] [-root directory] [-tests directory]\n\n", basename((char*)argv[0]));
fprintf(stdout, "Usage: %s [-mode webServer | htmlPage | htmlForm | webDAV | webUploader | streamingResponse] [-record] [-root directory] [-tests directory] [-authenticationMethod Basic | Digest] [-authenticationRealm realm] [-authenticationUser user] [-authenticationPassword password]\n\n", basename((char*)argv[0]));
} else {
for (int i = 1; i < argc; ++i) {
if (argv[i][0] != '-') {
@@ -86,6 +165,18 @@ int main(int argc, const char* argv[]) {
} else if (!strcmp(argv[i], "-tests") && (i + 1 < argc)) {
++i;
testDirectory = [[[NSFileManager defaultManager] stringWithFileSystemRepresentation:argv[i] length:strlen(argv[i])] stringByStandardizingPath];
} else if (!strcmp(argv[i], "-authenticationMethod") && (i + 1 < argc)) {
++i;
authenticationMethod = [NSString stringWithUTF8String:argv[i]];
} else if (!strcmp(argv[i], "-authenticationRealm") && (i + 1 < argc)) {
++i;
authenticationRealm = [NSString stringWithUTF8String:argv[i]];
} else if (!strcmp(argv[i], "-authenticationUser") && (i + 1 < argc)) {
++i;
authenticationUser = [NSString stringWithUTF8String:argv[i]];
} else if (!strcmp(argv[i], "-authenticationPassword") && (i + 1 < argc)) {
++i;
authenticationPassword = [NSString stringWithUTF8String:argv[i]];
}
}
}
@@ -195,21 +286,36 @@ int main(int argc, const char* argv[]) {
#endif
if (webServer) {
Delegate* delegate = [[Delegate alloc] init];
webServer.delegate = delegate;
if (testDirectory) {
fprintf(stdout, "<RUNNING TESTS FROM \"%s\">\n\n", [testDirectory UTF8String]);
result = (int)[webServer runTestsInDirectory:testDirectory withPort:8080];
result = (int)[webServer runTestsWithOptions:@{GCDWebServerOption_Port: @8080} inDirectory:testDirectory];
} else {
if (recording) {
fprintf(stdout, "<RECORDING ENABLED>\n");
webServer.recordingEnabled = YES;
}
fprintf(stdout, "\n");
if ([webServer runWithPort:8080]) {
NSMutableDictionary* options = [NSMutableDictionary dictionary];
[options setObject:@8080 forKey:GCDWebServerOption_Port];
[options setObject:@"" forKey:GCDWebServerOption_BonjourName];
if (authenticationUser && authenticationPassword) {
[options setValue:authenticationRealm forKey:GCDWebServerOption_AuthenticationRealm];
[options setObject:@{authenticationUser: authenticationPassword} forKey:GCDWebServerOption_AuthenticationAccounts];
if ([authenticationMethod isEqualToString:@"Basic"]) {
[options setObject:GCDWebServerAuthenticationMethod_Basic forKey:GCDWebServerOption_AuthenticationMethod];
} else if ([authenticationMethod isEqualToString:@"Digest"]) {
[options setObject:GCDWebServerAuthenticationMethod_DigestAccess forKey:GCDWebServerOption_AuthenticationMethod];
}
}
if ([webServer runWithOptions:options]) {
result = 0;
}
}
#if !__has_feature(objc_arc)
[webServer release];
[delegate release];
#endif
}
}

View File

@@ -3,7 +3,7 @@ Overview
[![Build Status](https://travis-ci.org/swisspol/GCDWebServer.svg?branch=master)](https://travis-ci.org/swisspol/GCDWebServer)
GCDWebServer is a modern and lightweight GCD based HTTP 1.1 server designed to be embedded in Mac & iOS apps. It was written from scratch with the following goals in mind:
GCDWebServer is a modern and lightweight GCD based HTTP 1.1 server designed to be embedded in OS X & iOS apps. It was written from scratch with the following goals in mind:
* Easy to use and understand architecture with only 4 core classes: server, connection, request and response (see "Understanding GCDWebServer's Architecture" below)
* Well designed API for easy integration and customization
* Entirely built with an event-driven design using [Grand Central Dispatch](http://en.wikipedia.org/wiki/Grand_Central_Dispatch) for maximal performance and concurrency
@@ -17,15 +17,13 @@ Extra built-in features:
* [Chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding) for request and response HTTP bodies
* [HTTP compression](https://en.wikipedia.org/wiki/HTTP_compression) with gzip for request and response HTTP bodies
* [HTTP range](https://en.wikipedia.org/wiki/Byte_serving) support for requests of local files
* [Basic](https://en.wikipedia.org/wiki/Basic_access_authentication) and [Digest Access](https://en.wikipedia.org/wiki/Digest_access_authentication) authentications for password protection
* Automatically handle transitions between foreground, background and suspended modes in iOS apps
Included extensions:
* [GCDWebUploader](GCDWebUploader/GCDWebUploader.h): subclass of ```GCDWebServer``` that implements an interface for uploading and downloading files from an iOS app's sandbox using a web browser
* [GCDWebUploader](GCDWebUploader/GCDWebUploader.h): subclass of ```GCDWebServer``` that implements an interface for uploading and downloading files using a web browser
* [GCDWebDAVServer](GCDWebDAVServer/GCDWebDAVServer.h): subclass of ```GCDWebServer``` that implements a class 1 [WebDAV](https://en.wikipedia.org/wiki/WebDAV) server (with partial class 2 support for OS X Finder)
What's not available out of the box but can be implemented on top of the API:
* Authentication like [Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication)
* Web forms submitted using "multipart/mixed"
What's not supported (but not really required from an embedded HTTP server):
* Keep-alive connections
* HTTPS
@@ -37,7 +35,7 @@ Requirements:
Getting Started
===============
Download or checkout the source for GCDWebServer then add the entire "GCDWebServer" subfolder to your Xcode project. If you intend to use one of the extensions like GCDWebDAVServer or GCDWebUploader, add these subfolders as well.
Download or check out the [latest release](https://github.com/swisspol/GCDWebServer/releases) of GCDWebServer then add the entire "GCDWebServer" subfolder to your Xcode project. If you intend to use one of the extensions like GCDWebDAVServer or GCDWebUploader, add these subfolders as well.
Alternatively, you can install GCDWebServer using [CocoaPods](http://cocoapods.org/) by simply adding this line to your Xcode project's Podfile:
```
@@ -55,10 +53,12 @@ pod "GCDWebServer/WebDAV", "~> 2.0"
Hello World
===========
This code snippet shows how to implement a custom HTTP server that runs on port 8080 and returns a "Hello World" HTML page to any request &mdash; since GCDWebServer uses GCD blocks to handle requests, no subclassing or delegates are needed, which results in very clean code:
These code snippets show how to implement a custom HTTP server that runs on port 8080 and returns a "Hello World" HTML page to any request. Since GCDWebServer uses GCD blocks to handle requests, no subclassing or delegates are needed, which results in very clean code.
**OS X version (command line tool):**
```objectivec
#import "GCDWebServer.h"
#import "GCDWebServerDataResponse.h"
int main(int argc, const char* argv[]) {
@autoreleasepool {
@@ -75,10 +75,10 @@ int main(int argc, const char* argv[]) {
}];
// Use convenience method that runs server on port 8080 until SIGINT received
// Use convenience method that runs server on port 8080 until SIGINT received (i.e. Ctrl-C in Terminal)
[webServer runWithPort:8080];
// Destroy server
// Destroy server (unnecessary if using ARC)
[webServer release];
}
@@ -86,21 +86,51 @@ int main(int argc, const char* argv[]) {
}
```
**iOS version:**
```objectivec
#import "GCDWebServer.h"
#import "GCDWebServerDataResponse.h"
static GCDWebServer* _webServer = nil; // This should really be an ivar of your application's delegate class
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
// Create server
_webServer = [[GCDWebServer alloc] init];
// Add a handler to respond to GET requests on any URL
[_webServer addDefaultHandlerForMethod:@"GET"
requestClass:[GCDWebServerRequest class]
processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
return [GCDWebServerDataResponse responseWithHTML:@"<html><body><p>Hello World</p></body></html>"];
}];
// Start server on port 8080
[_webServer startWithPort:8080 bonjourName:nil];
return YES;
}
```
Web Based Uploads in iOS Apps
=============================
GCDWebUploader is a subclass of ```GCDWebServer``` that provides a ready-to-use HTML 5 file uploader & downloader. This lets users upload, download, delete files and create directories from a directory inside your iOS app's sandbox using a clean user interface in their web browser.
Simply instantiate and run a GCDWebUploader instance then visit http://{YOUR-IOS-DEVICE-IP-ADDRESS}/ from your web browser:
Simply instantiate and run a ```GCDWebUploader``` instance then visit ```http://{YOUR-IOS-DEVICE-IP-ADDRESS}/``` from your web browser:
```objectivec
#import "GCDWebUploader.h"
static GCDWebUploader* _webUploader = nil; // This should really be an ivar of your application's delegate class
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
GCDWebUploader* webUploader = [[GCDWebUploader alloc] initWithUploadDirectory:documentsPath];
[webUploader start];
NSLog(@"Visit %@ in your web browser", webUploader.serverURL);
_webUploader = [[GCDWebUploader alloc] initWithUploadDirectory:documentsPath];
[_webUploader start];
NSLog(@"Visit %@ in your web browser", _webUploader.serverURL);
return YES;
}
```
@@ -112,16 +142,18 @@ GCDWebDAVServer is a subclass of ```GCDWebServer``` that provides a class 1 comp
GCDWebDAVServer should also work with the [OS X Finder](http://support.apple.com/kb/PH13859) as it is partially class 2 compliant (but only when the client is the OS X WebDAV implementation).
Simply instantiate and run a GCDWebDAVServer instance then connect to http://{YOUR-IOS-DEVICE-IP-ADDRESS}/ using a WebDAV client:
Simply instantiate and run a ```GCDWebDAVServer``` instance then connect to ```http://{YOUR-IOS-DEVICE-IP-ADDRESS}/``` using a WebDAV client:
```objectivec
#import "GCDWebDAVServer.h"
static GCDWebDAVServer* _davServer = nil; // This should really be an ivar of your application's delegate class
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
GCDWebDAVServer* davServer = [[GCDWebDAVServer alloc] initWithUploadDirectory:documentsPath];
[davServer start];
NSLog(@"Visit %@ in your WebDAV client", davServer.serverURL);
_davServer = [[GCDWebDAVServer alloc] initWithUploadDirectory:documentsPath];
[_davServer start];
NSLog(@"Visit %@ in your WebDAV client", _davServer.serverURL);
return YES;
}
```
@@ -140,7 +172,7 @@ int main(int argc, const char* argv[]) {
GCDWebServer* webServer = [[GCDWebServer alloc] init];
[webServer addGETHandlerForBasePath:@"/" directoryPath:NSHomeDirectory() indexFilename:nil cacheAge:3600 allowRangeRequests:YES];
[webServer runWithPort:8080];
[webServer release];
[webServer release]; // Remove if using ARC
}
return 0;
@@ -171,11 +203,25 @@ Implementing Handlers
GCDWebServer relies on "handlers" to process incoming web requests and generating responses. Handlers are implemented with GCD blocks which makes it very easy to provide your owns. However, they are executed on arbitrary threads within GCD so __special attention must be paid to thread-safety and re-entrancy__.
Handlers require 2 GCD blocks:
* The ```GCDWebServerMatchBlock``` is called on every handler added to the ```GCDWebServer``` instance whenever a web request has started (i.e. HTTP headers have been received). It is passed the basic info for the web request (HTTP method, URL, headers...) and must decide if it wants to handle it or not. If yes, it must return a ```GCDWebServerRequest``` instance (see above). Otherwise, it simply returns nil.
* The ```GCDWebServerProcessBlock``` is called after the web request has been fully received and is passed the ```GCDWebServerRequest``` instance created at the previous step. It must return a ```GCDWebServerResponse``` instance (see above) or nil on error.
* The ```GCDWebServerMatchBlock``` is called on every handler added to the ```GCDWebServer``` instance whenever a web request has started (i.e. HTTP headers have been received). It is passed the basic info for the web request (HTTP method, URL, headers...) and must decide if it wants to handle it or not. If yes, it must return a new ```GCDWebServerRequest``` instance (see above) created with this info. Otherwise, it simply returns nil.
* The ```GCDWebServerProcessBlock``` is called after the web request has been fully received and is passed the ```GCDWebServerRequest``` instance created at the previous step. It must return a ```GCDWebServerResponse``` instance (see above) or nil on error, which will result in a 500 HTTP status code returned to the client. It's however recommended to return an instance of [GCDWebServerErrorResponse](GCDWebServer/Responses/GCDWebServerErrorResponse.h) on error so more useful information can be returned to the client.
Note that most methods on ```GCDWebServer``` to add handlers only require the ```GCDWebServerProcessBlock``` as they already provide a built-in ```GCDWebServerMatchBlock``` e.g. to match a URL path with a Regex.
GCDWebServer & Background Mode for iOS Apps
===========================================
When doing networking operations in iOS apps, you must handle carefully [what happens when iOS puts the app in the background](https://developer.apple.com/library/ios/technotes/tn2277/_index.html). Typically you must stop any network servers while the app is in the background and restart them when the app comes back to the foreground. This can become quite complex considering servers might have ongoing connections when they need to be stopped.
Fortunately, GCDWebServer does all of this automatically for you:
- GCDWebServer begins a [background task](https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html) whenever the first HTTP connection is opened and ends it only when the last one is closed. This prevents iOS from suspending the app after it goes in the background, which would immediately kill HTTP connections to the client.
- While the app is in the background, as long as new HTTP connections keep being initiated, the background task will continue to exist and iOS will not suspend the app (unless under sudden and unexpected memory pressure).
- If the app is still in the background when the last HTTP connection is closed, GCDWebServer will suspend itself and stop accepting new connections as if you had called ```-stop``` (this behavior can be disabled with the ```GCDWebServerOption_AutomaticallySuspendInBackground``` option).
- If the app goes in the background while no HTTP connections are opened, GCDWebServer will immediately suspend itself and stop accepting new connections as if you had called ```-stop``` (this behavior can be disabled with the ```GCDWebServerOption_AutomaticallySuspendInBackground``` option).
- If the app comes back to the foreground and GCDWebServer had been suspended, it will automatically resume itself and start accepting again new HTTP connections as if you had called ```-start```.
HTTP connections are often initiated in batches (or bursts), for instance when loading a web page with multiple resources. This makes it difficult to accurately detect when the *very last* HTTP connection has been closed: it's possible 2 consecutive HTTP connections part of the same batch would be separated by a small delay instead of overlapping. It would be bad for the client if GCDWebServer suspended itself right in between. The ```GCDWebServerOption_ConnectedStateCoalescingInterval``` option solves this problem elegantly by forcing GCDWebServer to wait some extra delay before performing any action after the last HTTP connection has been closed, just in case a new HTTP connection is initiated within this delay.
Advanced Example 1: Implementing HTTP Redirects
===============================================
@@ -274,4 +320,4 @@ Final Example: File Downloads and Uploads From iOS App
GCDWebServer was originally written for the [ComicFlow](http://itunes.apple.com/us/app/comicflow/id409290355?mt=8) comic reader app for iPad. It allow users to connect to their iPad with their web browser over WiFi and then upload, download and organize comic files inside the app.
ComicFlow is [entirely open-source](https://github.com/swisspol/ComicFlow) and you can see how it uses GCDWebUploader in the [WebServer.m](https://github.com/swisspol/ComicFlow/blob/master/Classes/WebServer.m) file.
ComicFlow is [entirely open-source](https://github.com/swisspol/ComicFlow) and you can see how it uses GCDWebServer in the [WebServer.h](https://github.com/swisspol/ComicFlow/blob/master/Classes/WebServer.h) and [WebServer.m](https://github.com/swisspol/ComicFlow/blob/master/Classes/WebServer.m) files.

View File

@@ -1,6 +1,14 @@
#!/bin/bash -ex
TARGET="GCDWebServer (Mac)"
OSX_SDK="macosx"
if [ -z "$TRAVIS" ]; then
IOS_SDK="iphoneos"
else
IOS_SDK="iphonesimulator"
fi
OSX_TARGET="GCDWebServer (Mac)"
IOS_TARGET="GCDWebServer (iOS)"
CONFIGURATION="Release"
MRC_BUILD_DIR="/tmp/GCDWebServer-MRC"
@@ -18,13 +26,21 @@ function runTests {
logLevel=2 $1 -mode "$2" -root "$PAYLOAD_DIR/Payload" -tests "$3"
}
# Build in manual memory management mode
rm -rf "MRC_BUILD_DIR"
xcodebuild -target "$TARGET" -configuration "$CONFIGURATION" build "SYMROOT=$MRC_BUILD_DIR" "CLANG_ENABLE_OBJC_ARC=NO" > /dev/null
# Build for iOS in manual memory management mode (TODO: run tests on iOS)
rm -rf "$MRC_BUILD_DIR"
xcodebuild -sdk "$IOS_SDK" -target "$IOS_TARGET" -configuration "$CONFIGURATION" build "SYMROOT=$MRC_BUILD_DIR" "CLANG_ENABLE_OBJC_ARC=NO" > /dev/null
# Build in ARC mode
rm -rf "ARC_BUILD_DIR"
xcodebuild -target "$TARGET" -configuration "$CONFIGURATION" build "SYMROOT=$ARC_BUILD_DIR" "CLANG_ENABLE_OBJC_ARC=YES" > /dev/null
# Build for iOS in ARC mode (TODO: run tests on iOS)
rm -rf "$ARC_BUILD_DIR"
xcodebuild -sdk "$IOS_SDK" -target "$IOS_TARGET" -configuration "$CONFIGURATION" build "SYMROOT=$ARC_BUILD_DIR" "CLANG_ENABLE_OBJC_ARC=YES" > /dev/null
# Build for OS X in manual memory management mode
rm -rf "$MRC_BUILD_DIR"
xcodebuild -sdk "$OSX_SDK" -target "$OSX_TARGET" -configuration "$CONFIGURATION" build "SYMROOT=$MRC_BUILD_DIR" "CLANG_ENABLE_OBJC_ARC=NO" > /dev/null
# Build for OS X in ARC mode
rm -rf "$ARC_BUILD_DIR"
xcodebuild -sdk "$OSX_SDK" -target "$OSX_TARGET" -configuration "$CONFIGURATION" build "SYMROOT=$ARC_BUILD_DIR" "CLANG_ENABLE_OBJC_ARC=YES" > /dev/null
# Run tests
runTests $MRC_PRODUCT "webServer" "Tests/WebServer"

View File

@@ -4,7 +4,7 @@ Server: GCDWebUploader
Content-Type: text/plain
Last-Modified: Thu, 10 Apr 2014 11:10:14 GMT
Date: Sat, 12 Apr 2014 05:36:17 GMT
Content-Disposition: attachment; filename="Copy.txt"
Content-Disposition: attachment; filename="Copy.txt"; filename*=UTF-8''Copy.txt
Content-Length: 271
Cache-Control: no-cache
Etag: 73598983/1397128214/0