From 8c555d6f059418713a73d76781bf51749bd45c56 Mon Sep 17 00:00:00 2001 From: Ettore Pasquini Date: Wed, 20 Mar 2024 15:15:48 -0700 Subject: [PATCH] Add 'Readium' prefix to all symbols Since this fork is not guaranteed to be compatible with the upstream repo, we need to ensure there are no symbols name collisions in case a host app needs to integrate our fork together with the original GCDWebServer as a dependency. --- Frameworks/Tests.m | 34 +-- GCDWebDAVServer/GCDWebDAVServer.h | 30 +-- GCDWebDAVServer/GCDWebDAVServer.m | 236 +++++++++--------- GCDWebServer/Core/GCDWebServer.h | 190 +++++++------- GCDWebServer/Core/GCDWebServer.m | 228 ++++++++--------- GCDWebServer/Core/GCDWebServerConnection.h | 34 +-- GCDWebServer/Core/GCDWebServerConnection.m | 78 +++--- GCDWebServer/Core/GCDWebServerFunctions.h | 20 +- GCDWebServer/Core/GCDWebServerFunctions.m | 54 ++-- .../Core/GCDWebServerHTTPStatusCodes.h | 10 +- GCDWebServer/Core/GCDWebServerPrivate.h | 72 +++--- GCDWebServer/Core/GCDWebServerRequest.h | 26 +- GCDWebServer/Core/GCDWebServerRequest.m | 42 ++-- GCDWebServer/Core/GCDWebServerResponse.h | 38 +-- GCDWebServer/Core/GCDWebServerResponse.m | 36 +-- .../Requests/GCDWebServerDataRequest.h | 6 +- .../Requests/GCDWebServerDataRequest.m | 16 +- .../Requests/GCDWebServerFileRequest.h | 6 +- .../Requests/GCDWebServerFileRequest.m | 18 +- .../GCDWebServerMultiPartFormRequest.h | 30 +-- .../GCDWebServerMultiPartFormRequest.m | 78 +++--- .../GCDWebServerURLEncodedFormRequest.h | 6 +- .../GCDWebServerURLEncodedFormRequest.m | 10 +- .../Responses/GCDWebServerDataResponse.h | 6 +- .../Responses/GCDWebServerDataResponse.m | 20 +- .../Responses/GCDWebServerErrorResponse.h | 20 +- .../Responses/GCDWebServerErrorResponse.m | 28 +-- .../Responses/GCDWebServerFileResponse.h | 8 +- .../Responses/GCDWebServerFileResponse.m | 24 +- .../Responses/GCDWebServerStreamedResponse.h | 20 +- .../Responses/GCDWebServerStreamedResponse.m | 22 +- GCDWebUploader/GCDWebUploader.h | 30 +-- GCDWebUploader/GCDWebUploader.m | 148 +++++------ iOS/ViewController.swift | 22 +- 34 files changed, 823 insertions(+), 823 deletions(-) diff --git a/Frameworks/Tests.m b/Frameworks/Tests.m index 22a2616d..85e87314 100644 --- a/Frameworks/Tests.m +++ b/Frameworks/Tests.m @@ -9,35 +9,35 @@ @interface Tests : XCTestCase @implementation Tests - (void)testWebServer { - GCDWebServer* server = [[GCDWebServer alloc] init]; + ReadiumGCDWebServer* server = [[ReadiumGCDWebServer alloc] init]; XCTAssertNotNil(server); } - (void)testDAVServer { - GCDWebDAVServer* server = [[GCDWebDAVServer alloc] init]; + ReadiumGCDWebDAVServer* server = [[ReadiumGCDWebDAVServer alloc] init]; XCTAssertNotNil(server); } - (void)testWebUploader { - GCDWebUploader* server = [[GCDWebUploader alloc] init]; + ReadiumGCDWebUploader* server = [[ReadiumGCDWebUploader alloc] init]; XCTAssertNotNil(server); } - (void)testPaths { - XCTAssertEqualObjects(GCDWebServerNormalizePath(@""), @""); - XCTAssertEqualObjects(GCDWebServerNormalizePath(@"/foo/"), @"/foo"); - XCTAssertEqualObjects(GCDWebServerNormalizePath(@"foo/bar"), @"foo/bar"); - XCTAssertEqualObjects(GCDWebServerNormalizePath(@"foo//bar"), @"foo/bar"); - XCTAssertEqualObjects(GCDWebServerNormalizePath(@"foo/bar//"), @"foo/bar"); - XCTAssertEqualObjects(GCDWebServerNormalizePath(@"foo/./bar"), @"foo/bar"); - XCTAssertEqualObjects(GCDWebServerNormalizePath(@"foo/bar/."), @"foo/bar"); - XCTAssertEqualObjects(GCDWebServerNormalizePath(@"foo/../bar"), @"bar"); - XCTAssertEqualObjects(GCDWebServerNormalizePath(@"/foo/../bar"), @"/bar"); - XCTAssertEqualObjects(GCDWebServerNormalizePath(@"/foo/.."), @"/"); - XCTAssertEqualObjects(GCDWebServerNormalizePath(@"/.."), @"/"); - XCTAssertEqualObjects(GCDWebServerNormalizePath(@"."), @""); - XCTAssertEqualObjects(GCDWebServerNormalizePath(@".."), @""); - XCTAssertEqualObjects(GCDWebServerNormalizePath(@"../.."), @""); + XCTAssertEqualObjects(ReadiumGCDWebServerNormalizePath(@""), @""); + XCTAssertEqualObjects(ReadiumGCDWebServerNormalizePath(@"/foo/"), @"/foo"); + XCTAssertEqualObjects(ReadiumGCDWebServerNormalizePath(@"foo/bar"), @"foo/bar"); + XCTAssertEqualObjects(ReadiumGCDWebServerNormalizePath(@"foo//bar"), @"foo/bar"); + XCTAssertEqualObjects(ReadiumGCDWebServerNormalizePath(@"foo/bar//"), @"foo/bar"); + XCTAssertEqualObjects(ReadiumGCDWebServerNormalizePath(@"foo/./bar"), @"foo/bar"); + XCTAssertEqualObjects(ReadiumGCDWebServerNormalizePath(@"foo/bar/."), @"foo/bar"); + XCTAssertEqualObjects(ReadiumGCDWebServerNormalizePath(@"foo/../bar"), @"bar"); + XCTAssertEqualObjects(ReadiumGCDWebServerNormalizePath(@"/foo/../bar"), @"/bar"); + XCTAssertEqualObjects(ReadiumGCDWebServerNormalizePath(@"/foo/.."), @"/"); + XCTAssertEqualObjects(ReadiumGCDWebServerNormalizePath(@"/.."), @"/"); + XCTAssertEqualObjects(ReadiumGCDWebServerNormalizePath(@"."), @""); + XCTAssertEqualObjects(ReadiumGCDWebServerNormalizePath(@".."), @""); + XCTAssertEqualObjects(ReadiumGCDWebServerNormalizePath(@"../.."), @""); } @end diff --git a/GCDWebDAVServer/GCDWebDAVServer.h b/GCDWebDAVServer/GCDWebDAVServer.h index 0df2ce3c..b1e8211e 100644 --- a/GCDWebDAVServer/GCDWebDAVServer.h +++ b/GCDWebDAVServer/GCDWebDAVServer.h @@ -29,56 +29,56 @@ NS_ASSUME_NONNULL_BEGIN -@class GCDWebDAVServer; +@class ReadiumGCDWebDAVServer; /** - * Delegate methods for GCDWebDAVServer. + * Delegate methods for ReadiumGCDWebDAVServer. * * @warning These methods are always called on the main thread in a serialized way. */ -@protocol GCDWebDAVServerDelegate +@protocol ReadiumGCDWebDAVServerDelegate @optional /** * This method is called whenever a file has been downloaded. */ -- (void)davServer:(GCDWebDAVServer*)server didDownloadFileAtPath:(NSString*)path; +- (void)davServer:(ReadiumGCDWebDAVServer*)server didDownloadFileAtPath:(NSString*)path; /** * This method is called whenever a file has been uploaded. */ -- (void)davServer:(GCDWebDAVServer*)server didUploadFileAtPath:(NSString*)path; +- (void)davServer:(ReadiumGCDWebDAVServer*)server didUploadFileAtPath:(NSString*)path; /** * This method is called whenever a file or directory has been moved. */ -- (void)davServer:(GCDWebDAVServer*)server didMoveItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath; +- (void)davServer:(ReadiumGCDWebDAVServer*)server didMoveItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath; /** * This method is called whenever a file or directory has been copied. */ -- (void)davServer:(GCDWebDAVServer*)server didCopyItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath; +- (void)davServer:(ReadiumGCDWebDAVServer*)server didCopyItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath; /** * This method is called whenever a file or directory has been deleted. */ -- (void)davServer:(GCDWebDAVServer*)server didDeleteItemAtPath:(NSString*)path; +- (void)davServer:(ReadiumGCDWebDAVServer*)server didDeleteItemAtPath:(NSString*)path; /** * This method is called whenever a directory has been created. */ -- (void)davServer:(GCDWebDAVServer*)server didCreateDirectoryAtPath:(NSString*)path; +- (void)davServer:(ReadiumGCDWebDAVServer*)server didCreateDirectoryAtPath:(NSString*)path; @end /** - * The GCDWebDAVServer subclass of GCDWebServer implements a class 1 compliant + * The ReadiumGCDWebDAVServer subclass of ReadiumGCDWebServer implements a class 1 compliant * WebDAV server. It is also partially class 2 compliant but only when the * client is the OS X WebDAV implementation (so it can work with the OS X Finder). * - * See the README.md file for more information about the features of GCDWebDAVServer. + * See the README.md file for more information about the features of ReadiumGCDWebDAVServer. */ -@interface GCDWebDAVServer : GCDWebServer +@interface ReadiumGCDWebDAVServer : ReadiumGCDWebServer /** * Returns the upload directory as specified when the server was initialized. @@ -88,7 +88,7 @@ NS_ASSUME_NONNULL_BEGIN /** * Sets the delegate for the server. */ -@property(nonatomic, weak, nullable) id delegate; +@property(nonatomic, weak, nullable) id delegate; /** * Sets which files are allowed to be operated on depending on their extension. @@ -113,11 +113,11 @@ NS_ASSUME_NONNULL_BEGIN @end /** - * Hooks to customize the behavior of GCDWebDAVServer. + * Hooks to customize the behavior of ReadiumGCDWebDAVServer. * * @warning These methods can be called on any GCD thread. */ -@interface GCDWebDAVServer (Subclassing) +@interface ReadiumGCDWebDAVServer (Subclassing) /** * This method is called to check if a file upload is allowed to complete. diff --git a/GCDWebDAVServer/GCDWebDAVServer.m b/GCDWebDAVServer/GCDWebDAVServer.m index eaac9aaa..c43131fb 100644 --- a/GCDWebDAVServer/GCDWebDAVServer.m +++ b/GCDWebDAVServer/GCDWebDAVServer.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebDAVServer requires ARC +#error ReadiumGCDWebDAVServer requires ARC #endif // WebDAV specifications: http://webdav.org/specs/rfc4918.html @@ -57,96 +57,96 @@ typedef NS_ENUM(NSInteger, DAVProperties) { NS_ASSUME_NONNULL_BEGIN -@interface GCDWebDAVServer (Methods) -- (nullable GCDWebServerResponse*)performOPTIONS:(GCDWebServerRequest*)request; -- (nullable GCDWebServerResponse*)performGET:(GCDWebServerRequest*)request; -- (nullable GCDWebServerResponse*)performPUT:(GCDWebServerFileRequest*)request; -- (nullable GCDWebServerResponse*)performDELETE:(GCDWebServerRequest*)request; -- (nullable GCDWebServerResponse*)performMKCOL:(GCDWebServerDataRequest*)request; -- (nullable GCDWebServerResponse*)performCOPY:(GCDWebServerRequest*)request isMove:(BOOL)isMove; -- (nullable GCDWebServerResponse*)performPROPFIND:(GCDWebServerDataRequest*)request; -- (nullable GCDWebServerResponse*)performLOCK:(GCDWebServerDataRequest*)request; -- (nullable GCDWebServerResponse*)performUNLOCK:(GCDWebServerRequest*)request; +@interface ReadiumGCDWebDAVServer (Methods) +- (nullable ReadiumGCDWebServerResponse*)performOPTIONS:(ReadiumGCDWebServerRequest*)request; +- (nullable ReadiumGCDWebServerResponse*)performGET:(ReadiumGCDWebServerRequest*)request; +- (nullable ReadiumGCDWebServerResponse*)performPUT:(ReadiumGCDWebServerFileRequest*)request; +- (nullable ReadiumGCDWebServerResponse*)performDELETE:(ReadiumGCDWebServerRequest*)request; +- (nullable ReadiumGCDWebServerResponse*)performMKCOL:(ReadiumGCDWebServerDataRequest*)request; +- (nullable ReadiumGCDWebServerResponse*)performCOPY:(ReadiumGCDWebServerRequest*)request isMove:(BOOL)isMove; +- (nullable ReadiumGCDWebServerResponse*)performPROPFIND:(ReadiumGCDWebServerDataRequest*)request; +- (nullable ReadiumGCDWebServerResponse*)performLOCK:(ReadiumGCDWebServerDataRequest*)request; +- (nullable ReadiumGCDWebServerResponse*)performUNLOCK:(ReadiumGCDWebServerRequest*)request; @end NS_ASSUME_NONNULL_END -@implementation GCDWebDAVServer +@implementation ReadiumGCDWebDAVServer @dynamic delegate; - (instancetype)initWithUploadDirectory:(NSString*)path { if ((self = [super init])) { _uploadDirectory = [path copy]; - GCDWebDAVServer* __unsafe_unretained server = self; + ReadiumGCDWebDAVServer* __unsafe_unretained server = self; // 9.1 PROPFIND method [self addDefaultHandlerForMethod:@"PROPFIND" - requestClass:[GCDWebServerDataRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { - return [server performPROPFIND:(GCDWebServerDataRequest*)request]; + requestClass:[ReadiumGCDWebServerDataRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { + return [server performPROPFIND:(ReadiumGCDWebServerDataRequest*)request]; }]; // 9.3 MKCOL Method [self addDefaultHandlerForMethod:@"MKCOL" - requestClass:[GCDWebServerDataRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { - return [server performMKCOL:(GCDWebServerDataRequest*)request]; + requestClass:[ReadiumGCDWebServerDataRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { + return [server performMKCOL:(ReadiumGCDWebServerDataRequest*)request]; }]; // 9.4 GET & HEAD methods [self addDefaultHandlerForMethod:@"GET" - requestClass:[GCDWebServerRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { + requestClass:[ReadiumGCDWebServerRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { return [server performGET:request]; }]; // 9.6 DELETE method [self addDefaultHandlerForMethod:@"DELETE" - requestClass:[GCDWebServerRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { + requestClass:[ReadiumGCDWebServerRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { return [server performDELETE:request]; }]; // 9.7 PUT method [self addDefaultHandlerForMethod:@"PUT" - requestClass:[GCDWebServerFileRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { - return [server performPUT:(GCDWebServerFileRequest*)request]; + requestClass:[ReadiumGCDWebServerFileRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { + return [server performPUT:(ReadiumGCDWebServerFileRequest*)request]; }]; // 9.8 COPY method [self addDefaultHandlerForMethod:@"COPY" - requestClass:[GCDWebServerRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { + requestClass:[ReadiumGCDWebServerRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { return [server performCOPY:request isMove:NO]; }]; // 9.9 MOVE method [self addDefaultHandlerForMethod:@"MOVE" - requestClass:[GCDWebServerRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { + requestClass:[ReadiumGCDWebServerRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { return [server performCOPY:request isMove:YES]; }]; // 9.10 LOCK method [self addDefaultHandlerForMethod:@"LOCK" - requestClass:[GCDWebServerDataRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { - return [server performLOCK:(GCDWebServerDataRequest*)request]; + requestClass:[ReadiumGCDWebServerDataRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { + return [server performLOCK:(ReadiumGCDWebServerDataRequest*)request]; }]; // 9.11 UNLOCK method [self addDefaultHandlerForMethod:@"UNLOCK" - requestClass:[GCDWebServerRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { + requestClass:[ReadiumGCDWebServerRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { return [server performUNLOCK:request]; }]; // 10.1 OPTIONS method / DAV Header [self addDefaultHandlerForMethod:@"OPTIONS" - requestClass:[GCDWebServerRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { + requestClass:[ReadiumGCDWebServerRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { return [server performOPTIONS:request]; }]; } @@ -155,7 +155,7 @@ - (instancetype)initWithUploadDirectory:(NSString*)path { @end -@implementation GCDWebDAVServer (Methods) +@implementation ReadiumGCDWebDAVServer (Methods) - (BOOL)_checkFileExtension:(NSString*)fileName { if (_allowedFileExtensions && ![_allowedFileExtensions containsObject:[[fileName pathExtension] lowercaseString]]) { @@ -164,13 +164,13 @@ - (BOOL)_checkFileExtension:(NSString*)fileName { return YES; } -static inline BOOL _IsMacFinder(GCDWebServerRequest* request) { +static inline BOOL _IsMacFinder(ReadiumGCDWebServerRequest* request) { NSString* userAgentHeader = [request.headers objectForKey:@"User-Agent"]; return ([userAgentHeader hasPrefix:@"WebDAVFS/"] || [userAgentHeader hasPrefix:@"WebDAVLib/"]); // OS X WebDAV client } -- (GCDWebServerResponse*)performOPTIONS:(GCDWebServerRequest*)request { - GCDWebServerResponse* response = [GCDWebServerResponse response]; +- (ReadiumGCDWebServerResponse*)performOPTIONS:(ReadiumGCDWebServerRequest*)request { + ReadiumGCDWebServerResponse* response = [ReadiumGCDWebServerResponse response]; if (_IsMacFinder(request)) { [response setValue:@"1, 2" forAdditionalHeader:@"DAV"]; // Classes 1 and 2 } else { @@ -179,22 +179,22 @@ - (GCDWebServerResponse*)performOPTIONS:(GCDWebServerRequest*)request { return response; } -- (GCDWebServerResponse*)performGET:(GCDWebServerRequest*)request { +- (ReadiumGCDWebServerResponse*)performGET:(ReadiumGCDWebServerRequest*)request { NSString* relativePath = request.path; - NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(relativePath)]; + NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(relativePath)]; BOOL isDirectory = NO; if (![[NSFileManager defaultManager] fileExistsAtPath:absolutePath isDirectory:&isDirectory]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; } NSString* itemName = [absolutePath lastPathComponent]; if (([itemName hasPrefix:@"."] && !_allowHiddenItems) || (!isDirectory && ![self _checkFileExtension:itemName])) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Downlading item name \"%@\" is not allowed", itemName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Downlading item name \"%@\" is not allowed", itemName]; } // Because HEAD requests are mapped to GET ones, we need to handle directories but it's OK to return nothing per http://webdav.org/specs/rfc4918.html#rfc.section.9.4 if (isDirectory) { - return [GCDWebServerResponse response]; + return [ReadiumGCDWebServerResponse response]; } if ([self.delegate respondsToSelector:@selector(davServer:didDownloadFileAtPath:)]) { @@ -204,42 +204,42 @@ - (GCDWebServerResponse*)performGET:(GCDWebServerRequest*)request { } if ([request hasByteRange]) { - return [GCDWebServerFileResponse responseWithFile:absolutePath byteRange:request.byteRange]; + return [ReadiumGCDWebServerFileResponse responseWithFile:absolutePath byteRange:request.byteRange]; } - return [GCDWebServerFileResponse responseWithFile:absolutePath]; + return [ReadiumGCDWebServerFileResponse responseWithFile:absolutePath]; } -- (GCDWebServerResponse*)performPUT:(GCDWebServerFileRequest*)request { +- (ReadiumGCDWebServerResponse*)performPUT:(ReadiumGCDWebServerFileRequest*)request { if ([request hasByteRange]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Range uploads not supported"]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Range uploads not supported"]; } NSString* relativePath = request.path; - NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(relativePath)]; + NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(relativePath)]; BOOL isDirectory; if (![[NSFileManager defaultManager] fileExistsAtPath:[absolutePath stringByDeletingLastPathComponent] isDirectory:&isDirectory] || !isDirectory) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Conflict message:@"Missing intermediate collection(s) for \"%@\"", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Conflict message:@"Missing intermediate collection(s) for \"%@\"", relativePath]; } BOOL existing = [[NSFileManager defaultManager] fileExistsAtPath:absolutePath isDirectory:&isDirectory]; if (existing && isDirectory) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_MethodNotAllowed message:@"PUT not allowed on existing collection \"%@\"", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_MethodNotAllowed message:@"PUT not allowed on existing collection \"%@\"", relativePath]; } NSString* fileName = [absolutePath lastPathComponent]; if (([fileName hasPrefix:@"."] && !_allowHiddenItems) || ![self _checkFileExtension:fileName]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Uploading file name \"%@\" is not allowed", fileName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Uploading file name \"%@\" is not allowed", fileName]; } if (![self shouldUploadFileAtPath:absolutePath withTemporaryFile:request.temporaryPath]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Uploading file to \"%@\" is not permitted", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Uploading file to \"%@\" is not permitted", relativePath]; } [[NSFileManager defaultManager] removeItemAtPath:absolutePath error:NULL]; NSError* error = nil; if (![[NSFileManager defaultManager] moveItemAtPath:request.temporaryPath toPath:absolutePath error:&error]) { - return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed moving uploaded file to \"%@\"", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed moving uploaded file to \"%@\"", relativePath]; } if ([self.delegate respondsToSelector:@selector(davServer:didUploadFileAtPath:)]) { @@ -247,34 +247,34 @@ - (GCDWebServerResponse*)performPUT:(GCDWebServerFileRequest*)request { [self.delegate davServer:self didUploadFileAtPath:absolutePath]; }); } - return [GCDWebServerResponse responseWithStatusCode:(existing ? kGCDWebServerHTTPStatusCode_NoContent : kGCDWebServerHTTPStatusCode_Created)]; + return [ReadiumGCDWebServerResponse responseWithStatusCode:(existing ? kGCDWebServerHTTPStatusCode_NoContent : kGCDWebServerHTTPStatusCode_Created)]; } -- (GCDWebServerResponse*)performDELETE:(GCDWebServerRequest*)request { +- (ReadiumGCDWebServerResponse*)performDELETE:(ReadiumGCDWebServerRequest*)request { NSString* depthHeader = [request.headers objectForKey:@"Depth"]; if (depthHeader && ![depthHeader isEqualToString:@"infinity"]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Unsupported 'Depth' header: %@", depthHeader]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Unsupported 'Depth' header: %@", depthHeader]; } NSString* relativePath = request.path; - NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(relativePath)]; + NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(relativePath)]; BOOL isDirectory = NO; if (![[NSFileManager defaultManager] fileExistsAtPath:absolutePath isDirectory:&isDirectory]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; } NSString* itemName = [absolutePath lastPathComponent]; if (([itemName hasPrefix:@"."] && !_allowHiddenItems) || (!isDirectory && ![self _checkFileExtension:itemName])) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Deleting item name \"%@\" is not allowed", itemName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Deleting item name \"%@\" is not allowed", itemName]; } if (![self shouldDeleteItemAtPath:absolutePath]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Deleting \"%@\" is not permitted", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Deleting \"%@\" is not permitted", relativePath]; } NSError* error = nil; if (![[NSFileManager defaultManager] removeItemAtPath:absolutePath error:&error]) { - return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed deleting \"%@\"", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed deleting \"%@\"", relativePath]; } if ([self.delegate respondsToSelector:@selector(davServer:didDeleteItemAtPath:)]) { @@ -282,40 +282,40 @@ - (GCDWebServerResponse*)performDELETE:(GCDWebServerRequest*)request { [self.delegate davServer:self didDeleteItemAtPath:absolutePath]; }); } - return [GCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_NoContent]; + return [ReadiumGCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_NoContent]; } -- (GCDWebServerResponse*)performMKCOL:(GCDWebServerDataRequest*)request { +- (ReadiumGCDWebServerResponse*)performMKCOL:(ReadiumGCDWebServerDataRequest*)request { if ([request hasBody] && (request.contentLength > 0)) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_UnsupportedMediaType message:@"Unexpected request body for MKCOL method"]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_UnsupportedMediaType message:@"Unexpected request body for MKCOL method"]; } NSString* relativePath = request.path; - NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(relativePath)]; + NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(relativePath)]; BOOL isDirectory; if (![[NSFileManager defaultManager] fileExistsAtPath:[absolutePath stringByDeletingLastPathComponent] isDirectory:&isDirectory] || !isDirectory) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Conflict message:@"Missing intermediate collection(s) for \"%@\"", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Conflict message:@"Missing intermediate collection(s) for \"%@\"", relativePath]; } NSString* directoryName = [absolutePath lastPathComponent]; if (!_allowHiddenItems && [directoryName hasPrefix:@"."]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Creating directory name \"%@\" is not allowed", directoryName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Creating directory name \"%@\" is not allowed", directoryName]; } if (![self shouldCreateDirectoryAtPath:absolutePath]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Creating directory \"%@\" is not permitted", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Creating directory \"%@\" is not permitted", relativePath]; } NSError* error = nil; if (![[NSFileManager defaultManager] createDirectoryAtPath:absolutePath withIntermediateDirectories:NO attributes:nil error:&error]) { - return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed creating directory \"%@\"", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed creating directory \"%@\"", relativePath]; } #ifdef __GCDWEBSERVER_ENABLE_TESTING__ - NSString* creationDateHeader = [request.headers objectForKey:@"X-GCDWebServer-CreationDate"]; + NSString* creationDateHeader = [request.headers objectForKey:@"X-ReadiumGCDWebServer-CreationDate"]; if (creationDateHeader) { - NSDate* date = GCDWebServerParseISO8601(creationDateHeader); + NSDate* date = ReadiumGCDWebServerParseISO8601(creationDateHeader); if (!date || ![[NSFileManager defaultManager] setAttributes:@{NSFileCreationDate : date} ofItemAtPath:absolutePath error:&error]) { - return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed setting creation date for directory \"%@\"", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed setting creation date for directory \"%@\"", relativePath]; } } #endif @@ -325,62 +325,62 @@ - (GCDWebServerResponse*)performMKCOL:(GCDWebServerDataRequest*)request { [self.delegate davServer:self didCreateDirectoryAtPath:absolutePath]; }); } - return [GCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_Created]; + return [ReadiumGCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_Created]; } -- (GCDWebServerResponse*)performCOPY:(GCDWebServerRequest*)request isMove:(BOOL)isMove { +- (ReadiumGCDWebServerResponse*)performCOPY:(ReadiumGCDWebServerRequest*)request isMove:(BOOL)isMove { if (!isMove) { NSString* depthHeader = [request.headers objectForKey:@"Depth"]; // TODO: Support "Depth: 0" if (depthHeader && ![depthHeader isEqualToString:@"infinity"]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Unsupported 'Depth' header: %@", depthHeader]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Unsupported 'Depth' header: %@", depthHeader]; } } NSString* srcRelativePath = request.path; - NSString* srcAbsolutePath = [_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(srcRelativePath)]; + NSString* srcAbsolutePath = [_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(srcRelativePath)]; NSString* dstRelativePath = [request.headers objectForKey:@"Destination"]; NSRange range = [dstRelativePath rangeOfString:(NSString*)[request.headers objectForKey:@"Host"]]; if ((dstRelativePath == nil) || (range.location == NSNotFound)) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Malformed 'Destination' header: %@", dstRelativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Malformed 'Destination' header: %@", dstRelativePath]; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" dstRelativePath = [[dstRelativePath substringFromIndex:(range.location + range.length)] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; #pragma clang diagnostic pop - NSString* dstAbsolutePath = [_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(dstRelativePath)]; + NSString* dstAbsolutePath = [_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(dstRelativePath)]; if (!dstAbsolutePath) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", srcRelativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", srcRelativePath]; } BOOL isDirectory; if (![[NSFileManager defaultManager] fileExistsAtPath:[dstAbsolutePath stringByDeletingLastPathComponent] isDirectory:&isDirectory] || !isDirectory) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Conflict message:@"Invalid destination \"%@\"", dstRelativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Conflict message:@"Invalid destination \"%@\"", dstRelativePath]; } NSString* srcName = [srcAbsolutePath lastPathComponent]; if ((!_allowHiddenItems && [srcName hasPrefix:@"."]) || (!isDirectory && ![self _checkFileExtension:srcName])) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"%@ from item name \"%@\" is not allowed", isMove ? @"Moving" : @"Copying", srcName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"%@ from item name \"%@\" is not allowed", isMove ? @"Moving" : @"Copying", srcName]; } NSString* dstName = [dstAbsolutePath lastPathComponent]; if ((!_allowHiddenItems && [dstName hasPrefix:@"."]) || (!isDirectory && ![self _checkFileExtension:dstName])) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"%@ to item name \"%@\" is not allowed", isMove ? @"Moving" : @"Copying", dstName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"%@ to item name \"%@\" is not allowed", isMove ? @"Moving" : @"Copying", dstName]; } NSString* overwriteHeader = [request.headers objectForKey:@"Overwrite"]; BOOL existing = [[NSFileManager defaultManager] fileExistsAtPath:dstAbsolutePath]; if (existing && ((isMove && ![overwriteHeader isEqualToString:@"T"]) || (!isMove && [overwriteHeader isEqualToString:@"F"]))) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_PreconditionFailed message:@"Destination \"%@\" already exists", dstRelativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_PreconditionFailed message:@"Destination \"%@\" already exists", dstRelativePath]; } if (isMove) { if (![self shouldMoveItemFromPath:srcAbsolutePath toPath:dstAbsolutePath]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Moving \"%@\" to \"%@\" is not permitted", srcRelativePath, dstRelativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Moving \"%@\" to \"%@\" is not permitted", srcRelativePath, dstRelativePath]; } } else { if (![self shouldCopyItemFromPath:srcAbsolutePath toPath:dstAbsolutePath]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Copying \"%@\" to \"%@\" is not permitted", srcRelativePath, dstRelativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Copying \"%@\" to \"%@\" is not permitted", srcRelativePath, dstRelativePath]; } } @@ -388,11 +388,11 @@ - (GCDWebServerResponse*)performCOPY:(GCDWebServerRequest*)request isMove:(BOOL) if (isMove) { [[NSFileManager defaultManager] removeItemAtPath:dstAbsolutePath error:NULL]; if (![[NSFileManager defaultManager] moveItemAtPath:srcAbsolutePath toPath:dstAbsolutePath error:&error]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden underlyingError:error message:@"Failed copying \"%@\" to \"%@\"", srcRelativePath, dstRelativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden underlyingError:error message:@"Failed copying \"%@\" to \"%@\"", srcRelativePath, dstRelativePath]; } } else { if (![[NSFileManager defaultManager] copyItemAtPath:srcAbsolutePath toPath:dstAbsolutePath error:&error]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden underlyingError:error message:@"Failed copying \"%@\" to \"%@\"", srcRelativePath, dstRelativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden underlyingError:error message:@"Failed copying \"%@\" to \"%@\"", srcRelativePath, dstRelativePath]; } } @@ -410,7 +410,7 @@ - (GCDWebServerResponse*)performCOPY:(GCDWebServerRequest*)request isMove:(BOOL) } } - return [GCDWebServerResponse responseWithStatusCode:(existing ? kGCDWebServerHTTPStatusCode_NoContent : kGCDWebServerHTTPStatusCode_Created)]; + return [ReadiumGCDWebServerResponse responseWithStatusCode:(existing ? kGCDWebServerHTTPStatusCode_NoContent : kGCDWebServerHTTPStatusCode_Created)]; } static inline xmlNodePtr _XMLChildWithName(xmlNodePtr child, const xmlChar* name) { @@ -448,11 +448,11 @@ - (void)_addPropertyResponseForItem:(NSString*)itemPath resource:(NSString*)reso } if ((properties & kDAVProperty_CreationDate) && [attributes objectForKey:NSFileCreationDate]) { - [xmlString appendFormat:@"%@", GCDWebServerFormatISO8601((NSDate*)[attributes fileCreationDate])]; + [xmlString appendFormat:@"%@", ReadiumGCDWebServerFormatISO8601((NSDate*)[attributes fileCreationDate])]; } if ((properties & kDAVProperty_LastModified) && isFile && [attributes objectForKey:NSFileModificationDate]) { // Last modification date is not useful for directories as it changes implicitely and 'Last-Modified' header is not provided for directories anyway - [xmlString appendFormat:@"%@", GCDWebServerFormatRFC822((NSDate*)[attributes fileModificationDate])]; + [xmlString appendFormat:@"%@", ReadiumGCDWebServerFormatRFC822((NSDate*)[attributes fileModificationDate])]; } if ((properties & kDAVProperty_ContentLength) && !isDirectory && [attributes objectForKey:NSFileSize]) { @@ -470,7 +470,7 @@ - (void)_addPropertyResponseForItem:(NSString*)itemPath resource:(NSString*)reso } } -- (GCDWebServerResponse*)performPROPFIND:(GCDWebServerDataRequest*)request { +- (ReadiumGCDWebServerResponse*)performPROPFIND:(ReadiumGCDWebServerDataRequest*)request { NSInteger depth; NSString* depthHeader = [request.headers objectForKey:@"Depth"]; if ([depthHeader isEqualToString:@"0"]) { @@ -478,7 +478,7 @@ - (GCDWebServerResponse*)performPROPFIND:(GCDWebServerDataRequest*)request { } else if ([depthHeader isEqualToString:@"1"]) { depth = 1; } else { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Unsupported 'Depth' header: %@", depthHeader]; // TODO: Return 403 / propfind-finite-depth for "infinity" depth + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Unsupported 'Depth' header: %@", depthHeader]; // TODO: Return 403 / propfind-finite-depth for "infinity" depth } DAVProperties properties = 0; @@ -516,22 +516,22 @@ - (GCDWebServerResponse*)performPROPFIND:(GCDWebServerDataRequest*)request { } if (!success) { NSString* string = [[NSString alloc] initWithData:request.data encoding:NSUTF8StringEncoding]; - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Invalid DAV properties:\n%@", string]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Invalid DAV properties:\n%@", string]; } } else { properties = kDAVAllProperties; } NSString* relativePath = request.path; - NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(relativePath)]; + NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(relativePath)]; BOOL isDirectory = NO; if (![[NSFileManager defaultManager] fileExistsAtPath:absolutePath isDirectory:&isDirectory]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; } NSString* itemName = [absolutePath lastPathComponent]; if (([itemName hasPrefix:@"."] && !_allowHiddenItems) || (!isDirectory && ![self _checkFileExtension:itemName])) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Retrieving properties for item name \"%@\" is not allowed", itemName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Retrieving properties for item name \"%@\" is not allowed", itemName]; } NSArray* items = nil; @@ -539,7 +539,7 @@ - (GCDWebServerResponse*)performPROPFIND:(GCDWebServerDataRequest*)request { NSError* error = nil; items = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:absolutePath error:&error] sortedArrayUsingSelector:@selector(localizedStandardCompare:)]; if (items == nil) { - return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed listing directory \"%@\"", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed listing directory \"%@\"", relativePath]; } } @@ -561,22 +561,22 @@ - (GCDWebServerResponse*)performPROPFIND:(GCDWebServerDataRequest*)request { } [xmlString appendString:@""]; - GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithData:(NSData*)[xmlString dataUsingEncoding:NSUTF8StringEncoding] + ReadiumGCDWebServerDataResponse* response = [ReadiumGCDWebServerDataResponse responseWithData:(NSData*)[xmlString dataUsingEncoding:NSUTF8StringEncoding] contentType:@"application/xml; charset=\"utf-8\""]; response.statusCode = kGCDWebServerHTTPStatusCode_MultiStatus; return response; } -- (GCDWebServerResponse*)performLOCK:(GCDWebServerDataRequest*)request { +- (ReadiumGCDWebServerResponse*)performLOCK:(ReadiumGCDWebServerDataRequest*)request { if (!_IsMacFinder(request)) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_MethodNotAllowed message:@"LOCK method only allowed for Mac Finder"]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_MethodNotAllowed message:@"LOCK method only allowed for Mac Finder"]; } NSString* relativePath = request.path; - NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(relativePath)]; + NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(relativePath)]; BOOL isDirectory = NO; if (![[NSFileManager defaultManager] fileExistsAtPath:absolutePath isDirectory:&isDirectory]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; } NSString* depthHeader = [request.headers objectForKey:@"Depth"]; @@ -614,20 +614,20 @@ - (GCDWebServerResponse*)performLOCK:(GCDWebServerDataRequest*)request { } if (!success) { NSString* string = [[NSString alloc] initWithData:request.data encoding:NSUTF8StringEncoding]; - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Invalid DAV properties:\n%@", string]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Invalid DAV properties:\n%@", string]; } if (![scope isEqualToString:@"exclusive"] || ![type isEqualToString:@"write"] || ![depthHeader isEqualToString:@"0"]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Locking request \"%@/%@/%@\" for \"%@\" is not allowed", scope, type, depthHeader, relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Locking request \"%@/%@/%@\" for \"%@\" is not allowed", scope, type, depthHeader, relativePath]; } NSString* itemName = [absolutePath lastPathComponent]; if ((!_allowHiddenItems && [itemName hasPrefix:@"."]) || (!isDirectory && ![self _checkFileExtension:itemName])) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Locking item name \"%@\" is not allowed", itemName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Locking item name \"%@\" is not allowed", itemName]; } #ifdef __GCDWEBSERVER_ENABLE_TESTING__ - NSString* lockTokenHeader = [request.headers objectForKey:@"X-GCDWebServer-LockToken"]; + NSString* lockTokenHeader = [request.headers objectForKey:@"X-ReadiumGCDWebServer-LockToken"]; if (lockTokenHeader) { token = lockTokenHeader; } @@ -659,40 +659,40 @@ - (GCDWebServerResponse*)performLOCK:(GCDWebServerDataRequest*)request { [xmlString appendString:@""]; [self logVerbose:@"WebDAV pretending to lock \"%@\"", relativePath]; - GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithData:(NSData*)[xmlString dataUsingEncoding:NSUTF8StringEncoding] + ReadiumGCDWebServerDataResponse* response = [ReadiumGCDWebServerDataResponse responseWithData:(NSData*)[xmlString dataUsingEncoding:NSUTF8StringEncoding] contentType:@"application/xml; charset=\"utf-8\""]; return response; } -- (GCDWebServerResponse*)performUNLOCK:(GCDWebServerRequest*)request { +- (ReadiumGCDWebServerResponse*)performUNLOCK:(ReadiumGCDWebServerRequest*)request { if (!_IsMacFinder(request)) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_MethodNotAllowed message:@"UNLOCK method only allowed for Mac Finder"]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_MethodNotAllowed message:@"UNLOCK method only allowed for Mac Finder"]; } NSString* relativePath = request.path; - NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(relativePath)]; + NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(relativePath)]; BOOL isDirectory = NO; if (![[NSFileManager defaultManager] fileExistsAtPath:absolutePath isDirectory:&isDirectory]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; } NSString* tokenHeader = [request.headers objectForKey:@"Lock-Token"]; if (!tokenHeader.length) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Missing 'Lock-Token' header"]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"Missing 'Lock-Token' header"]; } NSString* itemName = [absolutePath lastPathComponent]; if ((!_allowHiddenItems && [itemName hasPrefix:@"."]) || (!isDirectory && ![self _checkFileExtension:itemName])) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Unlocking item name \"%@\" is not allowed", itemName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Unlocking item name \"%@\" is not allowed", itemName]; } [self logVerbose:@"WebDAV pretending to unlock \"%@\"", relativePath]; - return [GCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_NoContent]; + return [ReadiumGCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_NoContent]; } @end -@implementation GCDWebDAVServer (Subclassing) +@implementation ReadiumGCDWebDAVServer (Subclassing) - (BOOL)shouldUploadFileAtPath:(NSString*)path withTemporaryFile:(NSString*)tempPath { return YES; diff --git a/GCDWebServer/Core/GCDWebServer.h b/GCDWebServer/Core/GCDWebServer.h index 70cb70c6..18be903a 100644 --- a/GCDWebServer/Core/GCDWebServer.h +++ b/GCDWebServer/Core/GCDWebServer.h @@ -33,71 +33,71 @@ NS_ASSUME_NONNULL_BEGIN /** - * The GCDWebServerMatchBlock is called for every handler added to the - * GCDWebServer whenever a new HTTP request has started (i.e. HTTP headers have + * The ReadiumGCDWebServerMatchBlock is called for every handler added to the + * ReadiumGCDWebServer whenever a new HTTP request has started (i.e. HTTP headers have * been received). The block is passed the basic info for the request (HTTP method, * URL, headers...) and must decide if it wants to handle it or not. * * If the handler can handle the request, the block must return a new - * GCDWebServerRequest instance created with the same basic info. + * ReadiumGCDWebServerRequest instance created with the same basic info. * Otherwise, it simply returns nil. */ -typedef GCDWebServerRequest* _Nullable (^GCDWebServerMatchBlock)(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery); +typedef ReadiumGCDWebServerRequest* _Nullable (^ReadiumGCDWebServerMatchBlock)(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery); /** - * The GCDWebServerProcessBlock is called after the HTTP request has been fully + * The ReadiumGCDWebServerProcessBlock is called after the HTTP request has been fully * received (i.e. the entire HTTP body has been read). The block is passed the - * GCDWebServerRequest created at the previous step by the GCDWebServerMatchBlock. + * ReadiumGCDWebServerRequest created at the previous step by the ReadiumGCDWebServerMatchBlock. * - * The block must return a GCDWebServerResponse or nil on error, which will + * The block must return a ReadiumGCDWebServerResponse or nil on error, which will * result in a 500 HTTP status code returned to the client. It's however - * recommended to return a GCDWebServerErrorResponse on error so more useful + * recommended to return a ReadiumGCDWebServerErrorResponse on error so more useful * information can be returned to the client. */ -typedef GCDWebServerResponse* _Nullable (^GCDWebServerProcessBlock)(__kindof GCDWebServerRequest* request); +typedef ReadiumGCDWebServerResponse* _Nullable (^ReadiumGCDWebServerProcessBlock)(__kindof ReadiumGCDWebServerRequest* request); /** - * The GCDWebServerAsynchronousProcessBlock works like the GCDWebServerProcessBlock - * except the GCDWebServerResponse can be returned to the server at a later time + * The ReadiumGCDWebServerAsynchronousProcessBlock works like the ReadiumGCDWebServerProcessBlock + * except the ReadiumGCDWebServerResponse can be returned to the server at a later time * allowing for asynchronous generation of the response. * - * The block must eventually call "completionBlock" passing a GCDWebServerResponse + * The block must eventually call "completionBlock" passing a ReadiumGCDWebServerResponse * or nil on error, which will result in a 500 HTTP status code returned to the client. - * It's however recommended to return a GCDWebServerErrorResponse on error so more + * It's however recommended to return a ReadiumGCDWebServerErrorResponse on error so more * useful information can be returned to the client. */ -typedef void (^GCDWebServerCompletionBlock)(GCDWebServerResponse* _Nullable response); -typedef void (^GCDWebServerAsyncProcessBlock)(__kindof GCDWebServerRequest* request, GCDWebServerCompletionBlock completionBlock); +typedef void (^ReadiumGCDWebServerCompletionBlock)(ReadiumGCDWebServerResponse* _Nullable response); +typedef void (^ReadiumGCDWebServerAsyncProcessBlock)(__kindof ReadiumGCDWebServerRequest* request, ReadiumGCDWebServerCompletionBlock completionBlock); /** - * The GCDWebServerBuiltInLoggerBlock is used to override the built-in logger at runtime. + * The ReadiumGCDWebServerBuiltInLoggerBlock is used to override the built-in logger at runtime. * The block will be passed the log level and the log message, see setLogLevel for * documentation of the log levels for the built-in logger. */ -typedef void (^GCDWebServerBuiltInLoggerBlock)(int level, NSString* _Nonnull message); +typedef void (^ReadiumGCDWebServerBuiltInLoggerBlock)(int level, NSString* _Nonnull message); /** - * The port used by the GCDWebServer (NSNumber / NSUInteger). + * The port used by the ReadiumGCDWebServer (NSNumber / NSUInteger). * * The default value is 0 i.e. let the OS pick a random port. */ -extern NSString* const GCDWebServerOption_Port; +extern NSString* const ReadiumGCDWebServerOption_Port; /** - * The Bonjour name used by the GCDWebServer (NSString). If set to an empty string, - * the name will automatically take the value of the GCDWebServerOption_ServerName + * The Bonjour name used by the ReadiumGCDWebServer (NSString). If set to an empty string, + * the name will automatically take the value of the ReadiumGCDWebServerOption_ServerName * option. If this option is set to nil, Bonjour will be disabled. * * The default value is nil. */ -extern NSString* const GCDWebServerOption_BonjourName; +extern NSString* const ReadiumGCDWebServerOption_BonjourName; /** - * The Bonjour service type used by the GCDWebServer (NSString). + * The Bonjour service type used by the ReadiumGCDWebServer (NSString). * * The default value is "_http._tcp", the service type for HTTP web servers. */ -extern NSString* const GCDWebServerOption_BonjourType; +extern NSString* const ReadiumGCDWebServerOption_BonjourType; /** * Request a port mapping in the NAT gateway (NSNumber / BOOL). @@ -107,9 +107,9 @@ extern NSString* const GCDWebServerOption_BonjourType; * The default value is NO. * * @warning The external port set up by the NAT gateway may be different than - * the one used by the GCDWebServer. + * the one used by the ReadiumGCDWebServer. */ -extern NSString* const GCDWebServerOption_RequestNATPortMapping; +extern NSString* const ReadiumGCDWebServerOption_RequestNATPortMapping; /** * Only accept HTTP requests coming from localhost i.e. not from the outside @@ -120,7 +120,7 @@ extern NSString* const GCDWebServerOption_RequestNATPortMapping; * @warning Bonjour and NAT port mapping should be disabled if using this option * since the server will not be reachable from the outside network anyway. */ -extern NSString* const GCDWebServerOption_BindToLocalhost; +extern NSString* const ReadiumGCDWebServerOption_BindToLocalhost; /** * The maximum number of incoming HTTP requests that can be queued waiting to @@ -128,62 +128,62 @@ extern NSString* const GCDWebServerOption_BindToLocalhost; * * The default value is 16. */ -extern NSString* const GCDWebServerOption_MaxPendingConnections; +extern NSString* const ReadiumGCDWebServerOption_MaxPendingConnections; /** - * The value for "Server" HTTP header used by the GCDWebServer (NSString). + * The value for "Server" HTTP header used by the ReadiumGCDWebServer (NSString). * - * The default value is the GCDWebServer class name. + * The default value is the ReadiumGCDWebServer class name. */ -extern NSString* const GCDWebServerOption_ServerName; +extern NSString* const ReadiumGCDWebServerOption_ServerName; /** - * The authentication method used by the GCDWebServer - * (one of "GCDWebServerAuthenticationMethod_..."). + * The authentication method used by the ReadiumGCDWebServer + * (one of "ReadiumGCDWebServerAuthenticationMethod_..."). * * The default value is nil i.e. authentication is disabled. */ -extern NSString* const GCDWebServerOption_AuthenticationMethod; +extern NSString* const ReadiumGCDWebServerOption_AuthenticationMethod; /** - * The authentication realm used by the GCDWebServer (NSString). + * The authentication realm used by the ReadiumGCDWebServer (NSString). * - * The default value is the same as the GCDWebServerOption_ServerName option. + * The default value is the same as the ReadiumGCDWebServerOption_ServerName option. */ -extern NSString* const GCDWebServerOption_AuthenticationRealm; +extern NSString* const ReadiumGCDWebServerOption_AuthenticationRealm; /** - * The authentication accounts used by the GCDWebServer + * The authentication accounts used by the ReadiumGCDWebServer * (NSDictionary of username / password pairs). * * The default value is nil i.e. no accounts. */ -extern NSString* const GCDWebServerOption_AuthenticationAccounts; +extern NSString* const ReadiumGCDWebServerOption_AuthenticationAccounts; /** - * The class used by the GCDWebServer when instantiating GCDWebServerConnection - * (subclass of GCDWebServerConnection). + * The class used by the ReadiumGCDWebServer when instantiating ReadiumGCDWebServerConnection + * (subclass of ReadiumGCDWebServerConnection). * - * The default value is the GCDWebServerConnection class. + * The default value is the ReadiumGCDWebServerConnection class. */ -extern NSString* const GCDWebServerOption_ConnectionClass; +extern NSString* const ReadiumGCDWebServerOption_ConnectionClass; /** - * Allow the GCDWebServer to pretend "HEAD" requests are actually "GET" ones + * Allow the ReadiumGCDWebServer to pretend "HEAD" requests are actually "GET" ones * and automatically discard the HTTP body of the response (NSNumber / BOOL). * * The default value is YES. */ -extern NSString* const GCDWebServerOption_AutomaticallyMapHEADToGET; +extern NSString* const ReadiumGCDWebServerOption_AutomaticallyMapHEADToGET; /** - * The interval expressed in seconds used by the GCDWebServer to decide how to + * The interval expressed in seconds used by the ReadiumGCDWebServer to decide how to * coalesce calls to -webServerDidConnect: and -webServerDidDisconnect: * (NSNumber / double). Coalescing will be disabled if the interval is <= 0.0. * * The default value is 1.0 second. */ -extern NSString* const GCDWebServerOption_ConnectedStateCoalescingInterval; +extern NSString* const ReadiumGCDWebServerOption_ConnectedStateCoalescingInterval; /** * Set the dispatch queue priority on which server connection will be @@ -192,23 +192,23 @@ extern NSString* const GCDWebServerOption_ConnectedStateCoalescingInterval; * * The default value is DISPATCH_QUEUE_PRIORITY_DEFAULT. */ -extern NSString* const GCDWebServerOption_DispatchQueuePriority; +extern NSString* const ReadiumGCDWebServerOption_DispatchQueuePriority; #if TARGET_OS_IPHONE /** - * Enables the GCDWebServer to automatically suspend itself (as if -stop was + * Enables the ReadiumGCDWebServer to automatically suspend itself (as if -stop was * called) when the iOS app goes into the background and the last - * GCDWebServerConnection is closed, then resume itself (as if -start was called) + * ReadiumGCDWebServerConnection is closed, then resume itself (as if -start was called) * when the iOS app comes back to the foreground (NSNumber / BOOL). * * See the README.md file for more information about this option. * * The default value is YES. * - * @warning The running property will be NO while the GCDWebServer is suspended. + * @warning The running property will be NO while the ReadiumGCDWebServer is suspended. */ -extern NSString* const GCDWebServerOption_AutomaticallySuspendInBackground; +extern NSString* const ReadiumGCDWebServerOption_AutomaticallySuspendInBackground; #endif @@ -218,27 +218,27 @@ extern NSString* const GCDWebServerOption_AutomaticallySuspendInBackground; * @warning Use of this authentication scheme is not recommended as the * passwords are sent in clear. */ -extern NSString* const GCDWebServerAuthenticationMethod_Basic; +extern NSString* const ReadiumGCDWebServerAuthenticationMethod_Basic; /** * HTTP Digest Access Authentication scheme (see https://tools.ietf.org/html/rfc2617). */ -extern NSString* const GCDWebServerAuthenticationMethod_DigestAccess; +extern NSString* const ReadiumGCDWebServerAuthenticationMethod_DigestAccess; -@class GCDWebServer; +@class ReadiumGCDWebServer; /** - * Delegate methods for GCDWebServer. + * Delegate methods for ReadiumGCDWebServer. * * @warning These methods are always called on the main thread in a serialized way. */ -@protocol GCDWebServerDelegate +@protocol ReadiumGCDWebServerDelegate @optional /** * This method is called after the server has successfully started. */ -- (void)webServerDidStart:(GCDWebServer*)server; +- (void)webServerDidStart:(ReadiumGCDWebServer*)server; /** * This method is called after the Bonjour registration for the server has @@ -247,7 +247,7 @@ extern NSString* const GCDWebServerAuthenticationMethod_DigestAccess; * Use the "bonjourServerURL" property to retrieve the Bonjour address of the * server. */ -- (void)webServerDidCompleteBonjourRegistration:(GCDWebServer*)server; +- (void)webServerDidCompleteBonjourRegistration:(ReadiumGCDWebServer*)server; /** * This method is called after the NAT port mapping for the server has been @@ -256,55 +256,55 @@ extern NSString* const GCDWebServerAuthenticationMethod_DigestAccess; * Use the "publicServerURL" property to retrieve the public address of the * server. */ -- (void)webServerDidUpdateNATPortMapping:(GCDWebServer*)server; +- (void)webServerDidUpdateNATPortMapping:(ReadiumGCDWebServer*)server; /** - * This method is called when the first GCDWebServerConnection is opened by the + * This method is called when the first ReadiumGCDWebServerConnection is opened by the * server to serve a series of HTTP requests. * * A series of HTTP requests is considered ongoing as long as new HTTP requests - * keep coming (and new GCDWebServerConnection instances keep being opened), + * keep coming (and new ReadiumGCDWebServerConnection instances keep being opened), * until before the last HTTP request has been responded to (and the - * corresponding last GCDWebServerConnection closed). + * corresponding last ReadiumGCDWebServerConnection closed). */ -- (void)webServerDidConnect:(GCDWebServer*)server; +- (void)webServerDidConnect:(ReadiumGCDWebServer*)server; /** - * This method is called when the last GCDWebServerConnection is closed after + * This method is called when the last ReadiumGCDWebServerConnection is closed after * the server has served a series of HTTP requests. * - * The GCDWebServerOption_ConnectedStateCoalescingInterval option can be used + * The ReadiumGCDWebServerOption_ConnectedStateCoalescingInterval option can be used * to have the server wait some extra delay before considering that the series * of HTTP requests has ended (in case there some latency between consecutive * requests). This effectively coalesces the calls to -webServerDidConnect: * and -webServerDidDisconnect:. */ -- (void)webServerDidDisconnect:(GCDWebServer*)server; +- (void)webServerDidDisconnect:(ReadiumGCDWebServer*)server; /** * This method is called after the server has stopped. */ -- (void)webServerDidStop:(GCDWebServer*)server; +- (void)webServerDidStop:(ReadiumGCDWebServer*)server; @end /** - * The GCDWebServer class listens for incoming HTTP requests on a given port, + * The ReadiumGCDWebServer class listens for incoming HTTP requests on a given port, * then passes each one to a "handler" capable of generating an HTTP response * for it, which is then sent back to the client. * - * GCDWebServer instances can be created and used from any thread but it's + * ReadiumGCDWebServer instances can be created and used from any thread but it's * recommended to have the main thread's runloop be running so internal callbacks * can be handled e.g. for Bonjour registration. * - * See the README.md file for more information about the architecture of GCDWebServer. + * See the README.md file for more information about the architecture of ReadiumGCDWebServer. */ -@interface GCDWebServer : NSObject +@interface ReadiumGCDWebServer : NSObject /** * Sets the delegate for the server. */ -@property(nonatomic, weak, nullable) id delegate; +@property(nonatomic, weak, nullable) id delegate; /** * Returns YES if the server is currently running. @@ -347,7 +347,7 @@ extern NSString* const GCDWebServerAuthenticationMethod_DigestAccess; * * @warning Addling handlers while the server is running is not allowed. */ -- (void)addHandlerWithMatchBlock:(GCDWebServerMatchBlock)matchBlock processBlock:(GCDWebServerProcessBlock)processBlock; +- (void)addHandlerWithMatchBlock:(ReadiumGCDWebServerMatchBlock)matchBlock processBlock:(ReadiumGCDWebServerProcessBlock)processBlock; /** * Adds to the server a handler that generates responses asynchronously when handling incoming HTTP requests. @@ -357,7 +357,7 @@ extern NSString* const GCDWebServerAuthenticationMethod_DigestAccess; * * @warning Addling handlers while the server is running is not allowed. */ -- (void)addHandlerWithMatchBlock:(GCDWebServerMatchBlock)matchBlock asyncProcessBlock:(GCDWebServerAsyncProcessBlock)processBlock; +- (void)addHandlerWithMatchBlock:(ReadiumGCDWebServerMatchBlock)matchBlock asyncProcessBlock:(ReadiumGCDWebServerAsyncProcessBlock)processBlock; /** * Removes all handlers previously added to the server. @@ -377,7 +377,7 @@ extern NSString* const GCDWebServerAuthenticationMethod_DigestAccess; /** * Stops the server and prevents it to accepts new HTTP requests. * - * @warning Stopping the server does not abort GCDWebServerConnection instances + * @warning Stopping the server does not abort ReadiumGCDWebServerConnection instances * currently handling already received HTTP requests. These connections will * continue to execute normally until completion. */ @@ -385,7 +385,7 @@ extern NSString* const GCDWebServerAuthenticationMethod_DigestAccess; @end -@interface GCDWebServer (Extensions) +@interface ReadiumGCDWebServer (Extensions) /** * Returns the server's URL. @@ -457,51 +457,51 @@ extern NSString* const GCDWebServerAuthenticationMethod_DigestAccess; @end -@interface GCDWebServer (Handlers) +@interface ReadiumGCDWebServer (Handlers) /** * Adds a default handler to the server to handle all incoming HTTP requests * with a given HTTP method and generate responses synchronously. */ -- (void)addDefaultHandlerForMethod:(NSString*)method requestClass:(Class)aClass processBlock:(GCDWebServerProcessBlock)block; +- (void)addDefaultHandlerForMethod:(NSString*)method requestClass:(Class)aClass processBlock:(ReadiumGCDWebServerProcessBlock)block; /** * Adds a default handler to the server to handle all incoming HTTP requests * with a given HTTP method and generate responses asynchronously. */ -- (void)addDefaultHandlerForMethod:(NSString*)method requestClass:(Class)aClass asyncProcessBlock:(GCDWebServerAsyncProcessBlock)block; +- (void)addDefaultHandlerForMethod:(NSString*)method requestClass:(Class)aClass asyncProcessBlock:(ReadiumGCDWebServerAsyncProcessBlock)block; /** * Adds a handler to the server to handle incoming HTTP requests with a given * HTTP method and a specific case-insensitive path and generate responses * synchronously. */ -- (void)addHandlerForMethod:(NSString*)method path:(NSString*)path requestClass:(Class)aClass processBlock:(GCDWebServerProcessBlock)block; +- (void)addHandlerForMethod:(NSString*)method path:(NSString*)path requestClass:(Class)aClass processBlock:(ReadiumGCDWebServerProcessBlock)block; /** * Adds a handler to the server to handle incoming HTTP requests with a given * HTTP method and a specific case-insensitive path and generate responses * asynchronously. */ -- (void)addHandlerForMethod:(NSString*)method path:(NSString*)path requestClass:(Class)aClass asyncProcessBlock:(GCDWebServerAsyncProcessBlock)block; +- (void)addHandlerForMethod:(NSString*)method path:(NSString*)path requestClass:(Class)aClass asyncProcessBlock:(ReadiumGCDWebServerAsyncProcessBlock)block; /** * Adds a handler to the server to handle incoming HTTP requests with a given * HTTP method and a path matching a case-insensitive regular expression and * generate responses synchronously. */ -- (void)addHandlerForMethod:(NSString*)method pathRegex:(NSString*)regex requestClass:(Class)aClass processBlock:(GCDWebServerProcessBlock)block; +- (void)addHandlerForMethod:(NSString*)method pathRegex:(NSString*)regex requestClass:(Class)aClass processBlock:(ReadiumGCDWebServerProcessBlock)block; /** * Adds a handler to the server to handle incoming HTTP requests with a given * HTTP method and a path matching a case-insensitive regular expression and * generate responses asynchronously. */ -- (void)addHandlerForMethod:(NSString*)method pathRegex:(NSString*)regex requestClass:(Class)aClass asyncProcessBlock:(GCDWebServerAsyncProcessBlock)block; +- (void)addHandlerForMethod:(NSString*)method pathRegex:(NSString*)regex requestClass:(Class)aClass asyncProcessBlock:(ReadiumGCDWebServerAsyncProcessBlock)block; @end -@interface GCDWebServer (GETHandlers) +@interface ReadiumGCDWebServer (GETHandlers) /** * Adds a handler to the server to respond to incoming "GET" HTTP requests @@ -529,22 +529,22 @@ extern NSString* const GCDWebServerAuthenticationMethod_DigestAccess; @end /** - * GCDWebServer provides its own built-in logging facility which is used by + * ReadiumGCDWebServer provides its own built-in logging facility which is used by * default. It simply sends log messages to stderr assuming it is connected * to a terminal type device. * - * GCDWebServer is also compatible with a limited set of third-party logging - * facilities. If one of them is available at compile time, GCDWebServer will + * ReadiumGCDWebServer is also compatible with a limited set of third-party logging + * facilities. If one of them is available at compile time, ReadiumGCDWebServer will * automatically use it in place of the built-in one. * * Currently supported third-party logging facilities are: - * - XLFacility (by the same author as GCDWebServer): https://github.com/swisspol/XLFacility + * - XLFacility (by the same author as ReadiumGCDWebServer): https://github.com/swisspol/XLFacility * * For the built-in logging facility, the default logging level is INFO * (or DEBUG if the preprocessor constant "DEBUG" evaluates to non-zero at * compile time). * - * It's possible to have GCDWebServer use a custom logging facility by defining + * It's possible to have ReadiumGCDWebServer use a custom logging facility by defining * the "__GCDWEBSERVER_LOGGING_HEADER__" preprocessor constant in Xcode build * settings to the name of a custom header file (escaped like \"MyLogging.h\"). * This header file must define the following set of macros: @@ -560,10 +560,10 @@ extern NSString* const GCDWebServerAuthenticationMethod_DigestAccess; * to non-zero. * * The logging methods below send log messages to the same logging facility - * used by GCDWebServer. They can be used for consistency wherever you interact - * with GCDWebServer in your code (e.g. in the implementation of handlers). + * used by ReadiumGCDWebServer. They can be used for consistency wherever you interact + * with ReadiumGCDWebServer in your code (e.g. in the implementation of handlers). */ -@interface GCDWebServer (Logging) +@interface ReadiumGCDWebServer (Logging) /** * Sets the log level of the logging facility below which log messages are discarded. @@ -586,7 +586,7 @@ extern NSString* const GCDWebServerAuthenticationMethod_DigestAccess; * IMPORTANT: In order for this override to work, you should not be specifying * a custom logger at compile time with "__GCDWEBSERVER_LOGGING_HEADER__". */ -+ (void)setBuiltInLogger:(GCDWebServerBuiltInLoggerBlock)block; ++ (void)setBuiltInLogger:(ReadiumGCDWebServerBuiltInLoggerBlock)block; /** * Logs a message to the logging facility at the VERBOSE level. @@ -612,7 +612,7 @@ extern NSString* const GCDWebServerAuthenticationMethod_DigestAccess; #ifdef __GCDWEBSERVER_ENABLE_TESTING__ -@interface GCDWebServer (Testing) +@interface ReadiumGCDWebServer (Testing) /** * Activates recording of HTTP requests and responses which create files in the diff --git a/GCDWebServer/Core/GCDWebServer.m b/GCDWebServer/Core/GCDWebServer.m index dc769ebe..eca34ed2 100644 --- a/GCDWebServer/Core/GCDWebServer.m +++ b/GCDWebServer/Core/GCDWebServer.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebServer requires ARC +#error ReadiumGCDWebServer requires ARC #endif #import @@ -54,32 +54,32 @@ #define kBonjourResolutionTimeout 5.0 -NSString* const GCDWebServerOption_Port = @"Port"; -NSString* const GCDWebServerOption_BonjourName = @"BonjourName"; -NSString* const GCDWebServerOption_BonjourType = @"BonjourType"; -NSString* const GCDWebServerOption_RequestNATPortMapping = @"RequestNATPortMapping"; -NSString* const GCDWebServerOption_BindToLocalhost = @"BindToLocalhost"; -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"; -NSString* const GCDWebServerOption_DispatchQueuePriority = @"DispatchQueuePriority"; +NSString* const ReadiumGCDWebServerOption_Port = @"Port"; +NSString* const ReadiumGCDWebServerOption_BonjourName = @"BonjourName"; +NSString* const ReadiumGCDWebServerOption_BonjourType = @"BonjourType"; +NSString* const ReadiumGCDWebServerOption_RequestNATPortMapping = @"RequestNATPortMapping"; +NSString* const ReadiumGCDWebServerOption_BindToLocalhost = @"BindToLocalhost"; +NSString* const ReadiumGCDWebServerOption_MaxPendingConnections = @"MaxPendingConnections"; +NSString* const ReadiumGCDWebServerOption_ServerName = @"ServerName"; +NSString* const ReadiumGCDWebServerOption_AuthenticationMethod = @"AuthenticationMethod"; +NSString* const ReadiumGCDWebServerOption_AuthenticationRealm = @"AuthenticationRealm"; +NSString* const ReadiumGCDWebServerOption_AuthenticationAccounts = @"AuthenticationAccounts"; +NSString* const ReadiumGCDWebServerOption_ConnectionClass = @"ConnectionClass"; +NSString* const ReadiumGCDWebServerOption_AutomaticallyMapHEADToGET = @"AutomaticallyMapHEADToGET"; +NSString* const ReadiumGCDWebServerOption_ConnectedStateCoalescingInterval = @"ConnectedStateCoalescingInterval"; +NSString* const ReadiumGCDWebServerOption_DispatchQueuePriority = @"DispatchQueuePriority"; #if TARGET_OS_IPHONE -NSString* const GCDWebServerOption_AutomaticallySuspendInBackground = @"AutomaticallySuspendInBackground"; +NSString* const ReadiumGCDWebServerOption_AutomaticallySuspendInBackground = @"AutomaticallySuspendInBackground"; #endif -NSString* const GCDWebServerAuthenticationMethod_Basic = @"Basic"; -NSString* const GCDWebServerAuthenticationMethod_DigestAccess = @"DigestAccess"; +NSString* const ReadiumGCDWebServerAuthenticationMethod_Basic = @"Basic"; +NSString* const ReadiumGCDWebServerAuthenticationMethod_DigestAccess = @"DigestAccess"; #if defined(__GCDWEBSERVER_LOGGING_FACILITY_BUILTIN__) #if DEBUG -GCDWebServerLoggingLevel GCDWebServerLogLevel = kGCDWebServerLoggingLevel_Debug; +ReadiumGCDWebServerLoggingLevel ReadiumGCDWebServerLogLevel = kGCDWebServerLoggingLevel_Debug; #else -GCDWebServerLoggingLevel GCDWebServerLogLevel = kGCDWebServerLoggingLevel_Info; +ReadiumGCDWebServerLoggingLevel ReadiumGCDWebServerLogLevel = kGCDWebServerLoggingLevel_Info; #endif #endif @@ -89,9 +89,9 @@ #ifdef __GCDWEBSERVER_LOGGING_FACILITY_BUILTIN__ -static GCDWebServerBuiltInLoggerBlock _builtInLoggerBlock; +static ReadiumGCDWebServerBuiltInLoggerBlock _builtInLoggerBlock; -void GCDWebServerLogMessage(GCDWebServerLoggingLevel level, NSString* format, ...) { +void ReadiumGCDWebServerLogMessage(ReadiumGCDWebServerLoggingLevel level, NSString* format, ...) { static const char* levelNames[] = {"DEBUG", "VERBOSE", "INFO", "WARNING", "ERROR"}; static int enableLogging = -1; if (enableLogging < 0) { @@ -127,7 +127,7 @@ static void _SignalHandler(int signal) { // https://developer.apple.com/library/mac/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html // The main queue works with the application’s run loop to interleave the execution of queued tasks with the execution of other event sources attached to the run loop // TODO: Ensure all scheduled blocks on the main queue are also executed -static void _ExecuteMainThreadRunLoopSources() { +static void _ExecuteMainThreadRunLoopSources(void) { SInt32 result; do { result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0, true); @@ -136,9 +136,9 @@ static void _ExecuteMainThreadRunLoopSources() { #endif -@implementation GCDWebServerHandler +@implementation ReadiumGCDWebServerHandler -- (instancetype)initWithMatchBlock:(GCDWebServerMatchBlock _Nonnull)matchBlock asyncProcessBlock:(GCDWebServerAsyncProcessBlock _Nonnull)processBlock { +- (instancetype)initWithMatchBlock:(ReadiumGCDWebServerMatchBlock _Nonnull)matchBlock asyncProcessBlock:(ReadiumGCDWebServerAsyncProcessBlock _Nonnull)processBlock { if ((self = [super init])) { _matchBlock = [matchBlock copy]; _asyncProcessBlock = [processBlock copy]; @@ -148,10 +148,10 @@ - (instancetype)initWithMatchBlock:(GCDWebServerMatchBlock _Nonnull)matchBlock a @end -@implementation GCDWebServer { +@implementation ReadiumGCDWebServer { dispatch_queue_t _syncQueue; dispatch_group_t _sourceGroup; - NSMutableArray* _handlers; + NSMutableArray* _handlers; NSInteger _activeConnections; // Accessed through _syncQueue only BOOL _connected; // Accessed on main thread only CFRunLoopTimerRef _disconnectTimer; // Accessed on main thread only @@ -181,7 +181,7 @@ @implementation GCDWebServer { } + (void)initialize { - GCDWebServerInitializeFunctions(); + ReadiumGCDWebServerInitializeFunctions(); } - (instancetype)init { @@ -244,7 +244,7 @@ - (void)_didConnect { } } -- (void)willStartConnection:(GCDWebServerConnection*)connection { +- (void)willStartConnection:(ReadiumGCDWebServerConnection*)connection { dispatch_sync(_syncQueue, ^{ GWS_DCHECK(self->_activeConnections >= 0); if (self->_activeConnections == 0) { @@ -296,7 +296,7 @@ - (void)_didDisconnect { } } -- (void)didEndConnection:(GCDWebServerConnection*)connection { +- (void)didEndConnection:(ReadiumGCDWebServerConnection*)connection { dispatch_sync(_syncQueue, ^{ GWS_DCHECK(self->_activeConnections > 0); self->_activeConnections -= 1; @@ -332,16 +332,16 @@ - (NSString*)bonjourType { return type && CFStringGetLength(type) ? CFBridgingRelease(CFStringCreateCopy(kCFAllocatorDefault, type)) : nil; } -- (void)addHandlerWithMatchBlock:(GCDWebServerMatchBlock)matchBlock processBlock:(GCDWebServerProcessBlock)processBlock { +- (void)addHandlerWithMatchBlock:(ReadiumGCDWebServerMatchBlock)matchBlock processBlock:(ReadiumGCDWebServerProcessBlock)processBlock { [self addHandlerWithMatchBlock:matchBlock - asyncProcessBlock:^(GCDWebServerRequest* request, GCDWebServerCompletionBlock completionBlock) { + asyncProcessBlock:^(ReadiumGCDWebServerRequest* request, ReadiumGCDWebServerCompletionBlock completionBlock) { completionBlock(processBlock(request)); }]; } -- (void)addHandlerWithMatchBlock:(GCDWebServerMatchBlock)matchBlock asyncProcessBlock:(GCDWebServerAsyncProcessBlock)processBlock { +- (void)addHandlerWithMatchBlock:(ReadiumGCDWebServerMatchBlock)matchBlock asyncProcessBlock:(ReadiumGCDWebServerAsyncProcessBlock)processBlock { GWS_DCHECK(_options == nil); - GCDWebServerHandler* handler = [[GCDWebServerHandler alloc] initWithMatchBlock:matchBlock asyncProcessBlock:processBlock]; + ReadiumGCDWebServerHandler* handler = [[ReadiumGCDWebServerHandler alloc] initWithMatchBlock:matchBlock asyncProcessBlock:processBlock]; [_handlers insertObject:handler atIndex:0]; } @@ -356,7 +356,7 @@ static void _NetServiceRegisterCallBack(CFNetServiceRef service, CFStreamError* if (error->error) { GWS_LOG_ERROR(@"Bonjour registration error %i (domain %i)", (int)error->error, (int)error->domain); } else { - GCDWebServer* server = (__bridge GCDWebServer*)info; + ReadiumGCDWebServer* server = (__bridge ReadiumGCDWebServer*)info; GWS_LOG_VERBOSE(@"Bonjour registration complete for %@", [server class]); if (!CFNetServiceResolveWithTimeout(server->_resolutionService, kBonjourResolutionTimeout, NULL)) { GWS_LOG_ERROR(@"Failed starting Bonjour resolution"); @@ -374,7 +374,7 @@ static void _NetServiceResolveCallBack(CFNetServiceRef service, CFStreamError* e GWS_LOG_ERROR(@"Bonjour resolution error %i (domain %i)", (int)error->error, (int)error->domain); } } else { - GCDWebServer* server = (__bridge GCDWebServer*)info; + ReadiumGCDWebServer* server = (__bridge ReadiumGCDWebServer*)info; GWS_LOG_INFO(@"%@ now locally reachable at %@", [server class], server.bonjourServerURL); if ([server.delegate respondsToSelector:@selector(webServerDidCompleteBonjourRegistration:)]) { [server.delegate webServerDidCompleteBonjourRegistration:server]; @@ -386,14 +386,14 @@ static void _NetServiceResolveCallBack(CFNetServiceRef service, CFStreamError* e static void _DNSServiceCallBack(DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, uint32_t externalAddress, DNSServiceProtocol protocol, uint16_t internalPort, uint16_t externalPort, uint32_t ttl, void* context) { GWS_DCHECK([NSThread isMainThread]); @autoreleasepool { - GCDWebServer* server = (__bridge GCDWebServer*)context; + ReadiumGCDWebServer* server = (__bridge ReadiumGCDWebServer*)context; if ((errorCode == kDNSServiceErr_NoError) || (errorCode == kDNSServiceErr_DoubleNAT)) { struct sockaddr_in addr4; bzero(&addr4, sizeof(addr4)); addr4.sin_len = sizeof(addr4); addr4.sin_family = AF_INET; addr4.sin_addr.s_addr = externalAddress; // Already in network byte order - server->_dnsAddress = GCDWebServerStringFromSockAddr((const struct sockaddr*)&addr4, NO); + server->_dnsAddress = ReadiumGCDWebServerStringFromSockAddr((const struct sockaddr*)&addr4, NO); server->_dnsPort = ntohs(externalPort); GWS_LOG_INFO(@"%@ now publicly reachable at %@", [server class], server.publicServerURL); } else { @@ -410,7 +410,7 @@ static void _DNSServiceCallBack(DNSServiceRef sdRef, DNSServiceFlags flags, uint static void _SocketCallBack(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void* data, void* info) { GWS_DCHECK([NSThread isMainThread]); @autoreleasepool { - GCDWebServer* server = (__bridge GCDWebServer*)info; + ReadiumGCDWebServer* server = (__bridge ReadiumGCDWebServer*)info; DNSServiceErrorType status = DNSServiceProcessResult(server->_dnsService); if (status != kDNSServiceErr_NoError) { GWS_LOG_ERROR(@"DNS service error %i", status); @@ -451,14 +451,14 @@ - (int)_createListeningSocket:(BOOL)useIPv6 return listeningSocket; } else { if (error) { - *error = GCDWebServerMakePosixError(errno); + *error = ReadiumGCDWebServerMakePosixError(errno); } GWS_LOG_ERROR(@"Failed starting %s listening socket: %s (%i)", useIPv6 ? "IPv6" : "IPv4", strerror(errno), errno); close(listeningSocket); } } else { if (error) { - *error = GCDWebServerMakePosixError(errno); + *error = ReadiumGCDWebServerMakePosixError(errno); } GWS_LOG_ERROR(@"Failed binding %s listening socket: %s (%i)", useIPv6 ? "IPv6" : "IPv4", strerror(errno), errno); close(listeningSocket); @@ -466,7 +466,7 @@ - (int)_createListeningSocket:(BOOL)useIPv6 } else { if (error) { - *error = GCDWebServerMakePosixError(errno); + *error = ReadiumGCDWebServerMakePosixError(errno); } GWS_LOG_ERROR(@"Failed creating %s listening socket: %s (%i)", useIPv6 ? "IPv6" : "IPv4", strerror(errno), errno); } @@ -508,7 +508,7 @@ - (dispatch_source_t)_createDispatchSourceWithListeningSocket:(int)listeningSock int noSigPipe = 1; setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, sizeof(noSigPipe)); // Make sure this socket cannot generate SIG_PIPE - GCDWebServerConnection* connection = [(GCDWebServerConnection*)[self->_connectionClass alloc] initWithServer:self localAddress:localAddress remoteAddress:remoteAddress socket:socket]; // Connection will automatically retain itself while opened + ReadiumGCDWebServerConnection* connection = [(ReadiumGCDWebServerConnection*)[self->_connectionClass alloc] initWithServer:self localAddress:localAddress remoteAddress:remoteAddress socket:socket]; // Connection will automatically retain itself while opened [connection self]; // Prevent compiler from complaining about unused variable / useless statement } else { GWS_LOG_ERROR(@"Failed accepting %s socket: %s (%i)", isIPv6 ? "IPv6" : "IPv4", strerror(errno), errno); @@ -521,9 +521,9 @@ - (dispatch_source_t)_createDispatchSourceWithListeningSocket:(int)listeningSock - (BOOL)_start:(NSError**)error { GWS_DCHECK(_source4 == NULL); - NSUInteger port = [(NSNumber*)_GetOption(_options, GCDWebServerOption_Port, @0) unsignedIntegerValue]; - BOOL bindToLocalhost = [(NSNumber*)_GetOption(_options, GCDWebServerOption_BindToLocalhost, @NO) boolValue]; - NSUInteger maxPendingConnections = [(NSNumber*)_GetOption(_options, GCDWebServerOption_MaxPendingConnections, @16) unsignedIntegerValue]; + NSUInteger port = [(NSNumber*)_GetOption(_options, ReadiumGCDWebServerOption_Port, @0) unsignedIntegerValue]; + BOOL bindToLocalhost = [(NSNumber*)_GetOption(_options, ReadiumGCDWebServerOption_BindToLocalhost, @NO) boolValue]; + NSUInteger maxPendingConnections = [(NSNumber*)_GetOption(_options, ReadiumGCDWebServerOption_MaxPendingConnections, @16) unsignedIntegerValue]; struct sockaddr_in addr4; bzero(&addr4, sizeof(addr4)); @@ -557,35 +557,35 @@ - (BOOL)_start:(NSError**)error { return NO; } - _serverName = [(NSString*)_GetOption(_options, GCDWebServerOption_ServerName, NSStringFromClass([self class])) copy]; - NSString* authenticationMethod = _GetOption(_options, GCDWebServerOption_AuthenticationMethod, nil); - if ([authenticationMethod isEqualToString:GCDWebServerAuthenticationMethod_Basic]) { - _authenticationRealm = [(NSString*)_GetOption(_options, GCDWebServerOption_AuthenticationRealm, _serverName) copy]; + _serverName = [(NSString*)_GetOption(_options, ReadiumGCDWebServerOption_ServerName, NSStringFromClass([self class])) copy]; + NSString* authenticationMethod = _GetOption(_options, ReadiumGCDWebServerOption_AuthenticationMethod, nil); + if ([authenticationMethod isEqualToString:ReadiumGCDWebServerAuthenticationMethod_Basic]) { + _authenticationRealm = [(NSString*)_GetOption(_options, ReadiumGCDWebServerOption_AuthenticationRealm, _serverName) copy]; _authenticationBasicAccounts = [[NSMutableDictionary alloc] init]; - NSDictionary* accounts = _GetOption(_options, GCDWebServerOption_AuthenticationAccounts, @{}); + NSDictionary* accounts = _GetOption(_options, ReadiumGCDWebServerOption_AuthenticationAccounts, @{}); [accounts enumerateKeysAndObjectsUsingBlock:^(NSString* username, NSString* password, BOOL* stop) { [self->_authenticationBasicAccounts setObject:_EncodeBase64([NSString stringWithFormat:@"%@:%@", username, password]) forKey:username]; }]; - } else if ([authenticationMethod isEqualToString:GCDWebServerAuthenticationMethod_DigestAccess]) { - _authenticationRealm = [(NSString*)_GetOption(_options, GCDWebServerOption_AuthenticationRealm, _serverName) copy]; + } else if ([authenticationMethod isEqualToString:ReadiumGCDWebServerAuthenticationMethod_DigestAccess]) { + _authenticationRealm = [(NSString*)_GetOption(_options, ReadiumGCDWebServerOption_AuthenticationRealm, _serverName) copy]; _authenticationDigestAccounts = [[NSMutableDictionary alloc] init]; - NSDictionary* accounts = _GetOption(_options, GCDWebServerOption_AuthenticationAccounts, @{}); + NSDictionary* accounts = _GetOption(_options, ReadiumGCDWebServerOption_AuthenticationAccounts, @{}); [accounts enumerateKeysAndObjectsUsingBlock:^(NSString* username, NSString* password, BOOL* stop) { - [self->_authenticationDigestAccounts setObject:GCDWebServerComputeMD5Digest(@"%@:%@:%@", username, self->_authenticationRealm, password) forKey:username]; + [self->_authenticationDigestAccounts setObject:ReadiumGCDWebServerComputeMD5Digest(@"%@:%@:%@", username, self->_authenticationRealm, password) forKey:username]; }]; } - _connectionClass = _GetOption(_options, GCDWebServerOption_ConnectionClass, [GCDWebServerConnection class]); - _shouldAutomaticallyMapHEADToGET = [(NSNumber*)_GetOption(_options, GCDWebServerOption_AutomaticallyMapHEADToGET, @YES) boolValue]; - _disconnectDelay = [(NSNumber*)_GetOption(_options, GCDWebServerOption_ConnectedStateCoalescingInterval, @1.0) doubleValue]; - _dispatchQueuePriority = [(NSNumber*)_GetOption(_options, GCDWebServerOption_DispatchQueuePriority, @(DISPATCH_QUEUE_PRIORITY_DEFAULT)) longValue]; + _connectionClass = _GetOption(_options, ReadiumGCDWebServerOption_ConnectionClass, [ReadiumGCDWebServerConnection class]); + _shouldAutomaticallyMapHEADToGET = [(NSNumber*)_GetOption(_options, ReadiumGCDWebServerOption_AutomaticallyMapHEADToGET, @YES) boolValue]; + _disconnectDelay = [(NSNumber*)_GetOption(_options, ReadiumGCDWebServerOption_ConnectedStateCoalescingInterval, @1.0) doubleValue]; + _dispatchQueuePriority = [(NSNumber*)_GetOption(_options, ReadiumGCDWebServerOption_DispatchQueuePriority, @(DISPATCH_QUEUE_PRIORITY_DEFAULT)) longValue]; _source4 = [self _createDispatchSourceWithListeningSocket:listeningSocket4 isIPv6:NO]; _source6 = [self _createDispatchSourceWithListeningSocket:listeningSocket6 isIPv6:YES]; _port = port; _bindToLocalhost = bindToLocalhost; - NSString* bonjourName = _GetOption(_options, GCDWebServerOption_BonjourName, nil); - NSString* bonjourType = _GetOption(_options, GCDWebServerOption_BonjourType, @"_http._tcp"); + NSString* bonjourName = _GetOption(_options, ReadiumGCDWebServerOption_BonjourName, nil); + NSString* bonjourType = _GetOption(_options, ReadiumGCDWebServerOption_BonjourType, @"_http._tcp"); if (bonjourName) { _registrationService = CFNetServiceCreate(kCFAllocatorDefault, CFSTR("local."), (__bridge CFStringRef)bonjourType, (__bridge CFStringRef)(bonjourName.length ? bonjourName : _serverName), (SInt32)_port); if (_registrationService) { @@ -608,7 +608,7 @@ - (BOOL)_start:(NSError**)error { } } - if ([(NSNumber*)_GetOption(_options, GCDWebServerOption_RequestNATPortMapping, @NO) boolValue]) { + if ([(NSNumber*)_GetOption(_options, ReadiumGCDWebServerOption_RequestNATPortMapping, @NO) boolValue]) { DNSServiceErrorType status = DNSServiceNATPortMappingCreate(&_dnsService, 0, 0, kDNSServiceProtocol_TCP, htons(port), htons(port), 0, _DNSServiceCallBack, (__bridge void*)self); if (status == kDNSServiceErr_NoError) { CFSocketContext context = {0, (__bridge void*)self, NULL, NULL, NULL}; @@ -737,7 +737,7 @@ - (BOOL)startWithOptions:(NSDictionary*)options error:(NSError**) if (_options == nil) { _options = options ? [options copy] : @{}; #if TARGET_OS_IPHONE - _suspendInBackground = [(NSNumber*)_GetOption(_options, GCDWebServerOption_AutomaticallySuspendInBackground, @YES) boolValue]; + _suspendInBackground = [(NSNumber*)_GetOption(_options, ReadiumGCDWebServerOption_AutomaticallySuspendInBackground, @YES) boolValue]; if (((_suspendInBackground == NO) || ([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground)) && ![self _start:error]) #else if (![self _start:error]) @@ -782,11 +782,11 @@ - (void)stop { @end -@implementation GCDWebServer (Extensions) +@implementation ReadiumGCDWebServer (Extensions) - (NSURL*)serverURL { if (_source4) { - NSString* ipAddress = _bindToLocalhost ? @"localhost" : GCDWebServerGetPrimaryIPAddress(NO); // We can't really use IPv6 anyway as it doesn't work great with HTTP URLs in practice + NSString* ipAddress = _bindToLocalhost ? @"localhost" : ReadiumGCDWebServerGetPrimaryIPAddress(NO); // We can't really use IPv6 anyway as it doesn't work great with HTTP URLs in practice if (ipAddress) { if (_port != 80) { return [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%i/", ipAddress, (int)_port]]; @@ -830,8 +830,8 @@ - (BOOL)start { - (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]; + [options setObject:[NSNumber numberWithInteger:port] forKey:ReadiumGCDWebServerOption_Port]; + [options setValue:name forKey:ReadiumGCDWebServerOption_BonjourName]; return [self startWithOptions:options error:NULL]; } @@ -839,8 +839,8 @@ - (BOOL)startWithPort:(NSUInteger)port bonjourName:(NSString*)name { - (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]; + [options setObject:[NSNumber numberWithInteger:port] forKey:ReadiumGCDWebServerOption_Port]; + [options setValue:name forKey:ReadiumGCDWebServerOption_BonjourName]; return [self runWithOptions:options error:NULL]; } @@ -869,45 +869,45 @@ - (BOOL)runWithOptions:(NSDictionary*)options error:(NSError**)er @end -@implementation GCDWebServer (Handlers) +@implementation ReadiumGCDWebServer (Handlers) -- (void)addDefaultHandlerForMethod:(NSString*)method requestClass:(Class)aClass processBlock:(GCDWebServerProcessBlock)block { +- (void)addDefaultHandlerForMethod:(NSString*)method requestClass:(Class)aClass processBlock:(ReadiumGCDWebServerProcessBlock)block { [self addDefaultHandlerForMethod:method requestClass:aClass - asyncProcessBlock:^(GCDWebServerRequest* request, GCDWebServerCompletionBlock completionBlock) { + asyncProcessBlock:^(ReadiumGCDWebServerRequest* request, ReadiumGCDWebServerCompletionBlock completionBlock) { completionBlock(block(request)); }]; } -- (void)addDefaultHandlerForMethod:(NSString*)method requestClass:(Class)aClass asyncProcessBlock:(GCDWebServerAsyncProcessBlock)block { - [self addHandlerWithMatchBlock:^GCDWebServerRequest*(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) { +- (void)addDefaultHandlerForMethod:(NSString*)method requestClass:(Class)aClass asyncProcessBlock:(ReadiumGCDWebServerAsyncProcessBlock)block { + [self addHandlerWithMatchBlock:^ReadiumGCDWebServerRequest*(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) { if (![requestMethod isEqualToString:method]) { return nil; } - return [(GCDWebServerRequest*)[aClass alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery]; + return [(ReadiumGCDWebServerRequest*)[aClass alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery]; } asyncProcessBlock:block]; } -- (void)addHandlerForMethod:(NSString*)method path:(NSString*)path requestClass:(Class)aClass processBlock:(GCDWebServerProcessBlock)block { +- (void)addHandlerForMethod:(NSString*)method path:(NSString*)path requestClass:(Class)aClass processBlock:(ReadiumGCDWebServerProcessBlock)block { [self addHandlerForMethod:method path:path requestClass:aClass - asyncProcessBlock:^(GCDWebServerRequest* request, GCDWebServerCompletionBlock completionBlock) { + asyncProcessBlock:^(ReadiumGCDWebServerRequest* request, ReadiumGCDWebServerCompletionBlock completionBlock) { completionBlock(block(request)); }]; } -- (void)addHandlerForMethod:(NSString*)method path:(NSString*)path requestClass:(Class)aClass asyncProcessBlock:(GCDWebServerAsyncProcessBlock)block { - if ([path hasPrefix:@"/"] && [aClass isSubclassOfClass:[GCDWebServerRequest class]]) { - [self addHandlerWithMatchBlock:^GCDWebServerRequest*(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) { +- (void)addHandlerForMethod:(NSString*)method path:(NSString*)path requestClass:(Class)aClass asyncProcessBlock:(ReadiumGCDWebServerAsyncProcessBlock)block { + if ([path hasPrefix:@"/"] && [aClass isSubclassOfClass:[ReadiumGCDWebServerRequest class]]) { + [self addHandlerWithMatchBlock:^ReadiumGCDWebServerRequest*(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) { if (![requestMethod isEqualToString:method]) { return nil; } if ([urlPath caseInsensitiveCompare:path] != NSOrderedSame) { return nil; } - return [(GCDWebServerRequest*)[aClass alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery]; + return [(ReadiumGCDWebServerRequest*)[aClass alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery]; } asyncProcessBlock:block]; } else { @@ -915,19 +915,19 @@ - (void)addHandlerForMethod:(NSString*)method path:(NSString*)path requestClass: } } -- (void)addHandlerForMethod:(NSString*)method pathRegex:(NSString*)regex requestClass:(Class)aClass processBlock:(GCDWebServerProcessBlock)block { +- (void)addHandlerForMethod:(NSString*)method pathRegex:(NSString*)regex requestClass:(Class)aClass processBlock:(ReadiumGCDWebServerProcessBlock)block { [self addHandlerForMethod:method pathRegex:regex requestClass:aClass - asyncProcessBlock:^(GCDWebServerRequest* request, GCDWebServerCompletionBlock completionBlock) { + asyncProcessBlock:^(ReadiumGCDWebServerRequest* request, ReadiumGCDWebServerCompletionBlock completionBlock) { completionBlock(block(request)); }]; } -- (void)addHandlerForMethod:(NSString*)method pathRegex:(NSString*)regex requestClass:(Class)aClass asyncProcessBlock:(GCDWebServerAsyncProcessBlock)block { +- (void)addHandlerForMethod:(NSString*)method pathRegex:(NSString*)regex requestClass:(Class)aClass asyncProcessBlock:(ReadiumGCDWebServerAsyncProcessBlock)block { NSRegularExpression* expression = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:NULL]; - if (expression && [aClass isSubclassOfClass:[GCDWebServerRequest class]]) { - [self addHandlerWithMatchBlock:^GCDWebServerRequest*(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) { + if (expression && [aClass isSubclassOfClass:[ReadiumGCDWebServerRequest class]]) { + [self addHandlerWithMatchBlock:^ReadiumGCDWebServerRequest*(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) { if (![requestMethod isEqualToString:method]) { return nil; } @@ -950,8 +950,8 @@ - (void)addHandlerForMethod:(NSString*)method pathRegex:(NSString*)regex request } } - GCDWebServerRequest* request = [(GCDWebServerRequest*)[aClass alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery]; - [request setAttribute:captures forKey:GCDWebServerRequestAttribute_RegexCaptures]; + ReadiumGCDWebServerRequest* request = [(ReadiumGCDWebServerRequest*)[aClass alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery]; + [request setAttribute:captures forKey:ReadiumGCDWebServerRequestAttribute_RegexCaptures]; return request; } asyncProcessBlock:block]; @@ -962,14 +962,14 @@ - (void)addHandlerForMethod:(NSString*)method pathRegex:(NSString*)regex request @end -@implementation GCDWebServer (GETHandlers) +@implementation ReadiumGCDWebServer (GETHandlers) - (void)addGETHandlerForPath:(NSString*)path staticData:(NSData*)staticData contentType:(NSString*)contentType cacheAge:(NSUInteger)cacheAge { [self addHandlerForMethod:@"GET" path:path - requestClass:[GCDWebServerRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { - GCDWebServerResponse* response = [GCDWebServerDataResponse responseWithData:staticData contentType:contentType]; + requestClass:[ReadiumGCDWebServerRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { + ReadiumGCDWebServerResponse* response = [ReadiumGCDWebServerDataResponse responseWithData:staticData contentType:contentType]; response.cacheControlMaxAge = cacheAge; return response; }]; @@ -978,21 +978,21 @@ - (void)addGETHandlerForPath:(NSString*)path staticData:(NSData*)staticData cont - (void)addGETHandlerForPath:(NSString*)path filePath:(NSString*)filePath isAttachment:(BOOL)isAttachment cacheAge:(NSUInteger)cacheAge allowRangeRequests:(BOOL)allowRangeRequests { [self addHandlerForMethod:@"GET" path:path - requestClass:[GCDWebServerRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { - GCDWebServerResponse* response = nil; + requestClass:[ReadiumGCDWebServerRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { + ReadiumGCDWebServerResponse* response = nil; if (allowRangeRequests) { - response = [GCDWebServerFileResponse responseWithFile:filePath byteRange:request.byteRange isAttachment:isAttachment]; + response = [ReadiumGCDWebServerFileResponse responseWithFile:filePath byteRange:request.byteRange isAttachment:isAttachment]; [response setValue:@"bytes" forAdditionalHeader:@"Accept-Ranges"]; } else { - response = [GCDWebServerFileResponse responseWithFile:filePath isAttachment:isAttachment]; + response = [ReadiumGCDWebServerFileResponse responseWithFile:filePath isAttachment:isAttachment]; } response.cacheControlMaxAge = cacheAge; return response; }]; } -- (GCDWebServerResponse*)_responseWithContentsOfDirectory:(NSString*)path { +- (ReadiumGCDWebServerResponse*)_responseWithContentsOfDirectory:(NSString*)path { NSArray* contents = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL] sortedArrayUsingSelector:@selector(localizedStandardCompare:)]; if (contents == nil) { return nil; @@ -1019,24 +1019,24 @@ - (GCDWebServerResponse*)_responseWithContentsOfDirectory:(NSString*)path { } [html appendString:@"\n"]; [html appendString:@"\n"]; - return [GCDWebServerDataResponse responseWithHTML:html]; + return [ReadiumGCDWebServerDataResponse responseWithHTML:html]; } - (void)addGETHandlerForBasePath:(NSString*)basePath directoryPath:(NSString*)directoryPath indexFilename:(NSString*)indexFilename cacheAge:(NSUInteger)cacheAge allowRangeRequests:(BOOL)allowRangeRequests { if ([basePath hasPrefix:@"/"] && [basePath hasSuffix:@"/"]) { - GCDWebServer* __unsafe_unretained server = self; - [self addHandlerWithMatchBlock:^GCDWebServerRequest*(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) { + ReadiumGCDWebServer* __unsafe_unretained server = self; + [self addHandlerWithMatchBlock:^ReadiumGCDWebServerRequest*(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery) { if (![requestMethod isEqualToString:@"GET"]) { return nil; } if (![urlPath hasPrefix:basePath]) { return nil; } - return [[GCDWebServerRequest alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery]; + return [[ReadiumGCDWebServerRequest alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:urlPath query:urlQuery]; } - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { - GCDWebServerResponse* response = nil; - NSString* filePath = [directoryPath stringByAppendingPathComponent:GCDWebServerNormalizePath([request.path substringFromIndex:basePath.length])]; + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { + ReadiumGCDWebServerResponse* response = nil; + NSString* filePath = [directoryPath stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath([request.path substringFromIndex:basePath.length])]; NSString* fileType = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:NULL] fileType]; if (fileType) { if ([fileType isEqualToString:NSFileTypeDirectory]) { @@ -1044,23 +1044,23 @@ - (void)addGETHandlerForBasePath:(NSString*)basePath directoryPath:(NSString*)di NSString* indexPath = [filePath stringByAppendingPathComponent:indexFilename]; NSString* indexType = [[[NSFileManager defaultManager] attributesOfItemAtPath:indexPath error:NULL] fileType]; if ([indexType isEqualToString:NSFileTypeRegular]) { - return [GCDWebServerFileResponse responseWithFile:indexPath]; + return [ReadiumGCDWebServerFileResponse responseWithFile:indexPath]; } } response = [server _responseWithContentsOfDirectory:filePath]; } else if ([fileType isEqualToString:NSFileTypeRegular]) { if (allowRangeRequests) { - response = [GCDWebServerFileResponse responseWithFile:filePath byteRange:request.byteRange]; + response = [ReadiumGCDWebServerFileResponse responseWithFile:filePath byteRange:request.byteRange]; [response setValue:@"bytes" forAdditionalHeader:@"Accept-Ranges"]; } else { - response = [GCDWebServerFileResponse responseWithFile:filePath]; + response = [ReadiumGCDWebServerFileResponse responseWithFile:filePath]; } } } if (response) { response.cacheControlMaxAge = cacheAge; } else { - response = [GCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_NotFound]; + response = [ReadiumGCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_NotFound]; } return response; }]; @@ -1071,17 +1071,17 @@ - (void)addGETHandlerForBasePath:(NSString*)basePath directoryPath:(NSString*)di @end -@implementation GCDWebServer (Logging) +@implementation ReadiumGCDWebServer (Logging) + (void)setLogLevel:(int)level { #if defined(__GCDWEBSERVER_LOGGING_FACILITY_XLFACILITY__) [XLSharedFacility setMinLogLevel:level]; #elif defined(__GCDWEBSERVER_LOGGING_FACILITY_BUILTIN__) - GCDWebServerLogLevel = level; + ReadiumGCDWebServerLogLevel = level; #endif } -+ (void)setBuiltInLogger:(GCDWebServerBuiltInLoggerBlock)block { ++ (void)setBuiltInLogger:(ReadiumGCDWebServerBuiltInLoggerBlock)block { #if defined(__GCDWEBSERVER_LOGGING_FACILITY_BUILTIN__) _builtInLoggerBlock = block; #else @@ -1121,7 +1121,7 @@ - (void)logError:(NSString*)format, ... { #ifdef __GCDWEBSERVER_ENABLE_TESTING__ -@implementation GCDWebServer (Testing) +@implementation ReadiumGCDWebServer (Testing) - (void)setRecordingEnabled:(BOOL)flag { _recording = flag; @@ -1261,7 +1261,7 @@ - (NSInteger)runTestsWithOptions:(NSDictionary*)options inDirecto success = NO; #if !TARGET_OS_IPHONE #if DEBUG - if (GCDWebServerIsTextContentType((NSString*)[expectedHeaders objectForKey:@"Content-Type"])) { + if (ReadiumGCDWebServerIsTextContentType((NSString*)[expectedHeaders objectForKey:@"Content-Type"])) { NSString* expectedPath = [NSTemporaryDirectory() stringByAppendingPathComponent:(NSString*)[[[NSProcessInfo processInfo] globallyUniqueString] stringByAppendingPathExtension:@"txt"]]; NSString* actualPath = [NSTemporaryDirectory() stringByAppendingPathComponent:(NSString*)[[[NSProcessInfo processInfo] globallyUniqueString] stringByAppendingPathExtension:@"txt"]]; if ([expectedBody writeToFile:expectedPath atomically:YES] && [actualBody writeToFile:actualPath atomically:YES]) { diff --git a/GCDWebServer/Core/GCDWebServerConnection.h b/GCDWebServer/Core/GCDWebServerConnection.h index 4d59b9f1..ed2fe96b 100644 --- a/GCDWebServer/Core/GCDWebServerConnection.h +++ b/GCDWebServer/Core/GCDWebServerConnection.h @@ -29,26 +29,26 @@ NS_ASSUME_NONNULL_BEGIN -@class GCDWebServerHandler; +@class ReadiumGCDWebServerHandler; /** - * The GCDWebServerConnection class is instantiated by GCDWebServer to handle + * The ReadiumGCDWebServerConnection class is instantiated by ReadiumGCDWebServer to handle * each new HTTP connection. Each instance stays alive until the connection is * closed. * * You cannot use this class directly, but it is made public so you can - * subclass it to override some hooks. Use the GCDWebServerOption_ConnectionClass - * option for GCDWebServer to install your custom subclass. + * subclass it to override some hooks. Use the ReadiumGCDWebServerOption_ConnectionClass + * option for ReadiumGCDWebServer to install your custom subclass. * - * @warning The GCDWebServerConnection retains the GCDWebServer until the + * @warning The ReadiumGCDWebServerConnection retains the ReadiumGCDWebServer until the * connection is closed. */ -@interface GCDWebServerConnection : NSObject +@interface ReadiumGCDWebServerConnection : NSObject /** - * Returns the GCDWebServer that owns the connection. + * Returns the ReadiumGCDWebServer that owns the connection. */ -@property(nonatomic, readonly) GCDWebServer* server; +@property(nonatomic, readonly) ReadiumGCDWebServer* server; /** * Returns YES if the connection is using IPv6. @@ -93,12 +93,12 @@ NS_ASSUME_NONNULL_BEGIN @end /** - * Hooks to customize the behavior of GCDWebServer HTTP connections. + * Hooks to customize the behavior of ReadiumGCDWebServer HTTP connections. * * @warning These methods can be called on any GCD thread. * Be sure to also call "super" when overriding them. */ -@interface GCDWebServerConnection (Subclassing) +@interface ReadiumGCDWebServerConnection (Subclassing) /** * This method is called when the connection is opened. @@ -136,23 +136,23 @@ NS_ASSUME_NONNULL_BEGIN * Assuming a valid HTTP request was received, this method is called before * the request is processed. * - * Return a non-nil GCDWebServerResponse to bypass the request processing entirely. + * Return a non-nil ReadiumGCDWebServerResponse to bypass the request processing entirely. * * The default implementation checks for HTTP authentication if applicable * and returns a barebone 401 status code response if authentication failed. */ -- (nullable GCDWebServerResponse*)preflightRequest:(GCDWebServerRequest*)request; +- (nullable ReadiumGCDWebServerResponse*)preflightRequest:(ReadiumGCDWebServerRequest*)request; /** * Assuming a valid HTTP request was received and -preflightRequest: returned nil, * this method is called to process the request by executing the handler's * process block. */ -- (void)processRequest:(GCDWebServerRequest*)request completion:(GCDWebServerCompletionBlock)completion; +- (void)processRequest:(ReadiumGCDWebServerRequest*)request completion:(ReadiumGCDWebServerCompletionBlock)completion; /** * Assuming a valid HTTP request was received and either -preflightRequest: - * or -processRequest:completion: returned a non-nil GCDWebServerResponse, + * or -processRequest:completion: returned a non-nil ReadiumGCDWebServerResponse, * this method is called to override the response. * * You can either modify the current response and return it, or return a @@ -162,16 +162,16 @@ NS_ASSUME_NONNULL_BEGIN * "Last-Modified-Date" header of the request by a barebone "Not-Modified" (304) * one. */ -- (GCDWebServerResponse*)overrideResponse:(GCDWebServerResponse*)response forRequest:(GCDWebServerRequest*)request; +- (ReadiumGCDWebServerResponse*)overrideResponse:(ReadiumGCDWebServerResponse*)response forRequest:(ReadiumGCDWebServerRequest*)request; /** * This method is called if any error happens while validing or processing - * the request or if no GCDWebServerResponse was generated during processing. + * the request or if no ReadiumGCDWebServerResponse was generated during processing. * * @warning If the request was invalid (e.g. the HTTP headers were malformed), * the "request" argument will be nil. */ -- (void)abortRequest:(nullable GCDWebServerRequest*)request withStatusCode:(NSInteger)statusCode; +- (void)abortRequest:(nullable ReadiumGCDWebServerRequest*)request withStatusCode:(NSInteger)statusCode; /** * Called when the connection is closed. diff --git a/GCDWebServer/Core/GCDWebServerConnection.m b/GCDWebServer/Core/GCDWebServerConnection.m index e4f37e87..c1b9cc22 100644 --- a/GCDWebServer/Core/GCDWebServerConnection.m +++ b/GCDWebServer/Core/GCDWebServerConnection.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebServer requires ARC +#error ReadiumGCDWebServer requires ARC #endif #import @@ -63,14 +63,14 @@ NS_ASSUME_NONNULL_BEGIN -@interface GCDWebServerConnection (Read) +@interface ReadiumGCDWebServerConnection (Read) - (void)readData:(NSMutableData*)data withLength:(NSUInteger)length completionBlock:(ReadDataCompletionBlock)block; - (void)readHeaders:(NSMutableData*)headersData withCompletionBlock:(ReadHeadersCompletionBlock)block; - (void)readBodyWithRemainingLength:(NSUInteger)length completionBlock:(ReadBodyCompletionBlock)block; - (void)readNextBodyChunk:(NSMutableData*)chunkData completionBlock:(ReadBodyCompletionBlock)block; @end -@interface GCDWebServerConnection (Write) +@interface ReadiumGCDWebServerConnection (Write) - (void)writeData:(NSData*)data withCompletionBlock:(WriteDataCompletionBlock)block; - (void)writeHeadersWithCompletionBlock:(WriteHeadersCompletionBlock)block; - (void)writeBodyWithCompletionBlock:(WriteBodyCompletionBlock)block; @@ -78,15 +78,15 @@ - (void)writeBodyWithCompletionBlock:(WriteBodyCompletionBlock)block; NS_ASSUME_NONNULL_END -@implementation GCDWebServerConnection { +@implementation ReadiumGCDWebServerConnection { CFSocketNativeHandle _socket; BOOL _virtualHEAD; CFHTTPMessageRef _requestMessage; - GCDWebServerRequest* _request; - GCDWebServerHandler* _handler; // this is where the response is received + ReadiumGCDWebServerRequest* _request; + ReadiumGCDWebServerHandler* _handler; // this is where the response is received CFHTTPMessageRef _responseMessage; - GCDWebServerResponse* _response; + ReadiumGCDWebServerResponse* _response; NSInteger _statusCode; BOOL _opened; @@ -119,7 +119,7 @@ + (void)initialize { } if (_digestAuthenticationNonce == nil) { CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault); - _digestAuthenticationNonce = GCDWebServerComputeMD5Digest(@"%@", CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid))); + _digestAuthenticationNonce = ReadiumGCDWebServerComputeMD5Digest(@"%@", CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid))); CFRelease(uuid); } } @@ -134,25 +134,25 @@ - (void)_initializeResponseHeadersWithStatusCode:(NSInteger)statusCode { _responseMessage = CFHTTPMessageCreateResponse(kCFAllocatorDefault, statusCode, NULL, kCFHTTPVersion1_1); CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Connection"), CFSTR("Close")); CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Server"), (__bridge CFStringRef)_server.serverName); - CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Date"), (__bridge CFStringRef)GCDWebServerFormatRFC822([NSDate date])); + CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Date"), (__bridge CFStringRef)ReadiumGCDWebServerFormatRFC822([NSDate date])); } - (void)_startProcessingRequest { GWS_DCHECK(_responseMessage == NULL); - GCDWebServerResponse* preflightResponse = [self preflightRequest:_request]; + ReadiumGCDWebServerResponse* preflightResponse = [self preflightRequest:_request]; if (preflightResponse) { [self _finishProcessingRequest:preflightResponse]; } else { [self processRequest:_request - completion:^(GCDWebServerResponse* processResponse) { + completion:^(ReadiumGCDWebServerResponse* processResponse) { [self _finishProcessingRequest:processResponse]; }]; } } // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html -- (void)_finishProcessingRequest:(GCDWebServerResponse*)response { +- (void)_finishProcessingRequest:(ReadiumGCDWebServerResponse*)response { GWS_DCHECK(_responseMessage == NULL); BOOL hasBody = NO; @@ -175,7 +175,7 @@ - (void)_finishProcessingRequest:(GCDWebServerResponse*)response { if (_response) { [self _initializeResponseHeadersWithStatusCode:_response.statusCode]; if (_response.lastModifiedDate) { - CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Last-Modified"), (__bridge CFStringRef)GCDWebServerFormatRFC822((NSDate*)_response.lastModifiedDate)); + CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Last-Modified"), (__bridge CFStringRef)ReadiumGCDWebServerFormatRFC822((NSDate*)_response.lastModifiedDate)); } if (_response.eTag) { CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("ETag"), (__bridge CFStringRef)_response.eTag); @@ -188,7 +188,7 @@ - (void)_finishProcessingRequest:(GCDWebServerResponse*)response { } } if (_response.contentType != nil) { - CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Content-Type"), (__bridge CFStringRef)GCDWebServerNormalizeHeaderValue(_response.contentType)); + CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Content-Type"), (__bridge CFStringRef)ReadiumGCDWebServerNormalizeHeaderValue(_response.contentType)); } if (_response.contentLength != NSUIntegerMax) { CFHTTPMessageSetHeaderFieldValue(_responseMessage, CFSTR("Content-Length"), (__bridge CFStringRef)[NSString stringWithFormat:@"%lu", (unsigned long)_response.contentLength]); @@ -298,9 +298,9 @@ - (void)_readRequestHeaders { if (urlPath == nil) { urlPath = @"/"; // CFURLCopyPath() returns NULL for a relative URL with path "//" contrary to -[NSURL path] which returns "/" } - NSString* requestPath = urlPath ? GCDWebServerUnescapeURLString(urlPath) : nil; + NSString* requestPath = urlPath ? ReadiumGCDWebServerUnescapeURLString(urlPath) : nil; NSString* queryString = requestURL ? CFBridgingRelease(CFURLCopyQueryString((CFURLRef)requestURL, NULL)) : nil; // Don't use -[NSURL query] to make sure query is not unescaped; - NSDictionary* requestQuery = queryString ? GCDWebServerParseURLEncodedForm(queryString) : @{}; + NSDictionary* requestQuery = queryString ? ReadiumGCDWebServerParseURLEncodedForm(queryString) : @{}; if (requestMethod && requestURL && requestHeaders && requestPath && requestQuery) { for (self->_handler in self->_server.handlers) { self->_request = self->_handler.matchBlock(requestMethod, requestURL, requestHeaders, requestPath, requestQuery); @@ -346,7 +346,7 @@ - (void)_readRequestHeaders { [self _startProcessingRequest]; } } else { - self->_request = [[GCDWebServerRequest alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:requestPath query:requestQuery]; + self->_request = [[ReadiumGCDWebServerRequest alloc] initWithMethod:requestMethod url:requestURL headers:requestHeaders path:requestPath query:requestQuery]; GWS_DCHECK(self->_request); [self abortRequest:self->_request withStatusCode:kGCDWebServerHTTPStatusCode_NotImplemented]; } @@ -360,7 +360,7 @@ - (void)_readRequestHeaders { }]; } -- (instancetype)initWithServer:(GCDWebServer*)server localAddress:(NSData*)localAddress remoteAddress:(NSData*)remoteAddress socket:(CFSocketNativeHandle)socket { +- (instancetype)initWithServer:(ReadiumGCDWebServer*)server localAddress:(NSData*)localAddress remoteAddress:(NSData*)remoteAddress socket:(CFSocketNativeHandle)socket { if ((self = [super init])) { _server = server; _localAddressData = localAddress; @@ -382,11 +382,11 @@ - (instancetype)initWithServer:(GCDWebServer*)server localAddress:(NSData*)local } - (NSString*)localAddressString { - return GCDWebServerStringFromSockAddr(_localAddressData.bytes, YES); + return ReadiumGCDWebServerStringFromSockAddr(_localAddressData.bytes, YES); } - (NSString*)remoteAddressString { - return GCDWebServerStringFromSockAddr(_remoteAddressData.bytes, YES); + return ReadiumGCDWebServerStringFromSockAddr(_remoteAddressData.bytes, YES); } - (void)dealloc { @@ -414,7 +414,7 @@ - (void)dealloc { @end -@implementation GCDWebServerConnection (Read) +@implementation ReadiumGCDWebServerConnection (Read) - (void)readData:(NSMutableData*)data withLength:(NSUInteger)length completionBlock:(ReadDataCompletionBlock)block { dispatch_read(_socket, length, dispatch_get_global_queue(_server.dispatchQueuePriority, 0), ^(dispatch_data_t buffer, int error) { @@ -571,7 +571,7 @@ - (void)readNextBodyChunk:(NSMutableData*)chunkData completionBlock:(ReadBodyCom @end -@implementation GCDWebServerConnection (Write) +@implementation ReadiumGCDWebServerConnection (Write) - (void)writeData:(NSData*)data withCompletionBlock:(WriteDataCompletionBlock)block { dispatch_data_t buffer = dispatch_data_create(data.bytes, data.length, dispatch_get_global_queue(_server.dispatchQueuePriority, 0), ^{ @@ -653,7 +653,7 @@ - (void)writeBodyWithCompletionBlock:(WriteBodyCompletionBlock)block { @end -@implementation GCDWebServerConnection (Subclassing) +@implementation ReadiumGCDWebServerConnection (Subclassing) - (BOOL)open { #ifdef __GCDWEBSERVER_ENABLE_TESTING__ @@ -707,9 +707,9 @@ - (NSURL*)rewriteRequestURL:(NSURL*)url withMethod:(NSString*)method headers:(NS } // https://tools.ietf.org/html/rfc2617 -- (GCDWebServerResponse*)preflightRequest:(GCDWebServerRequest*)request { +- (ReadiumGCDWebServerResponse*)preflightRequest:(ReadiumGCDWebServerRequest*)request { GWS_LOG_DEBUG(@"Connection on socket %i preflighting request \"%@ %@\" with %lu bytes body", _socket, _virtualHEAD ? @"HEAD" : _request.method, _request.path, (unsigned long)_totalBytesRead); - GCDWebServerResponse* response = nil; + ReadiumGCDWebServerResponse* response = nil; if (_server.authenticationBasicAccounts) { __block BOOL authenticated = NO; NSString* authorizationHeader = [request.headers objectForKey:@"Authorization"]; @@ -723,7 +723,7 @@ - (GCDWebServerResponse*)preflightRequest:(GCDWebServerRequest*)request { }]; } if (!authenticated) { - response = [GCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_Unauthorized]; + response = [ReadiumGCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_Unauthorized]; [response setValue:[NSString stringWithFormat:@"Basic realm=\"%@\"", _server.authenticationRealm] forAdditionalHeader:@"WWW-Authenticate"]; } } else if (_server.authenticationDigestAccounts) { @@ -731,16 +731,16 @@ - (GCDWebServerResponse*)preflightRequest:(GCDWebServerRequest*)request { BOOL isStaled = NO; NSString* authorizationHeader = [request.headers objectForKey:@"Authorization"]; if ([authorizationHeader hasPrefix:@"Digest "]) { - NSString* realm = GCDWebServerExtractHeaderValueParameter(authorizationHeader, @"realm"); + NSString* realm = ReadiumGCDWebServerExtractHeaderValueParameter(authorizationHeader, @"realm"); if (realm && [_server.authenticationRealm isEqualToString:realm]) { - NSString* nonce = GCDWebServerExtractHeaderValueParameter(authorizationHeader, @"nonce"); + NSString* nonce = ReadiumGCDWebServerExtractHeaderValueParameter(authorizationHeader, @"nonce"); if ([nonce isEqualToString:_digestAuthenticationNonce]) { - NSString* username = GCDWebServerExtractHeaderValueParameter(authorizationHeader, @"username"); - NSString* uri = GCDWebServerExtractHeaderValueParameter(authorizationHeader, @"uri"); - NSString* actualResponse = GCDWebServerExtractHeaderValueParameter(authorizationHeader, @"response"); + NSString* username = ReadiumGCDWebServerExtractHeaderValueParameter(authorizationHeader, @"username"); + NSString* uri = ReadiumGCDWebServerExtractHeaderValueParameter(authorizationHeader, @"uri"); + NSString* actualResponse = ReadiumGCDWebServerExtractHeaderValueParameter(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); + NSString* ha2 = ReadiumGCDWebServerComputeMD5Digest(@"%@:%@", request.method, uri); // We cannot use "request.path" as the query string is required + NSString* expectedResponse = ReadiumGCDWebServerComputeMD5Digest(@"%@:%@:%@", ha1, _digestAuthenticationNonce, ha2); if ([actualResponse isEqualToString:expectedResponse]) { authenticated = YES; } @@ -750,16 +750,16 @@ - (GCDWebServerResponse*)preflightRequest:(GCDWebServerRequest*)request { } } if (!authenticated) { - response = [GCDWebServerResponse responseWithStatusCode:kGCDWebServerHTTPStatusCode_Unauthorized]; + response = [ReadiumGCDWebServerResponse 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; } -- (void)processRequest:(GCDWebServerRequest*)request completion:(GCDWebServerCompletionBlock)completion { +- (void)processRequest:(ReadiumGCDWebServerRequest*)request completion:(ReadiumGCDWebServerCompletionBlock)completion { GWS_LOG_DEBUG(@"Connection on socket %i processing request \"%@ %@\" with %lu bytes body", _socket, _virtualHEAD ? @"HEAD" : _request.method, _request.path, (unsigned long)_totalBytesRead); - // `completion` will receive the `GCDWebServerResponse` object + // `completion` will receive the `ReadiumGCDWebServerResponse` object _handler.asyncProcessBlock(request, [completion copy]); } @@ -782,10 +782,10 @@ static inline BOOL _CompareResources(NSString* responseETag, NSString* requestET return NO; } -- (GCDWebServerResponse*)overrideResponse:(GCDWebServerResponse*)response forRequest:(GCDWebServerRequest*)request { +- (ReadiumGCDWebServerResponse*)overrideResponse:(ReadiumGCDWebServerResponse*)response forRequest:(ReadiumGCDWebServerRequest*)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]; + ReadiumGCDWebServerResponse* newResponse = [ReadiumGCDWebServerResponse responseWithStatusCode:code]; newResponse.cacheControlMaxAge = response.cacheControlMaxAge; newResponse.lastModifiedDate = response.lastModifiedDate; newResponse.eTag = response.eTag; @@ -795,7 +795,7 @@ - (GCDWebServerResponse*)overrideResponse:(GCDWebServerResponse*)response forReq return response; } -- (void)abortRequest:(GCDWebServerRequest*)request withStatusCode:(NSInteger)statusCode { +- (void)abortRequest:(ReadiumGCDWebServerRequest*)request withStatusCode:(NSInteger)statusCode { GWS_DCHECK(_responseMessage == NULL); GWS_DCHECK((statusCode >= 400) && (statusCode < 600)); [self _initializeResponseHeadersWithStatusCode:statusCode]; diff --git a/GCDWebServer/Core/GCDWebServerFunctions.h b/GCDWebServer/Core/GCDWebServerFunctions.h index 217fb143..4dcfef74 100644 --- a/GCDWebServer/Core/GCDWebServerFunctions.h +++ b/GCDWebServer/Core/GCDWebServerFunctions.h @@ -41,26 +41,26 @@ extern "C" { * types. Keys of the dictionary must be lowercased file extensions without * the period, and the values must be the corresponding MIME types. */ -NSString* GCDWebServerGetMimeTypeForExtension(NSString* extension, NSDictionary* _Nullable overrides); +NSString* ReadiumGCDWebServerGetMimeTypeForExtension(NSString* extension, NSDictionary* _Nullable overrides); /** * Add percent-escapes to a string so it can be used in a URL. * The legal characters ":@/?&=+" are also escaped to ensure compatibility * with URL encoded forms and URL queries. */ -NSString* _Nullable GCDWebServerEscapeURLString(NSString* string); +NSString* _Nullable ReadiumGCDWebServerEscapeURLString(NSString* string); /** * Unescapes a URL percent-encoded string. */ -NSString* _Nullable GCDWebServerUnescapeURLString(NSString* string); +NSString* _Nullable ReadiumGCDWebServerUnescapeURLString(NSString* string); /** * Extracts the unescaped names and values from an * "application/x-www-form-urlencoded" form. * http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 */ -NSDictionary* GCDWebServerParseURLEncodedForm(NSString* form); +NSDictionary* ReadiumGCDWebServerParseURLEncodedForm(NSString* form); /** * On OS X, returns the IPv4 or IPv6 address as a string of the primary @@ -69,14 +69,14 @@ NSDictionary* GCDWebServerParseURLEncodedForm(NSString* fo * On iOS, returns the IPv4 or IPv6 address as a string of the WiFi * interface if connected or nil otherwise. */ -NSString* _Nullable GCDWebServerGetPrimaryIPAddress(BOOL useIPv6); +NSString* _Nullable ReadiumGCDWebServerGetPrimaryIPAddress(BOOL useIPv6); /** * Converts a date into a string using RFC822 formatting. * https://tools.ietf.org/html/rfc822#section-5 * https://tools.ietf.org/html/rfc1123#section-5.2.14 */ -NSString* GCDWebServerFormatRFC822(NSDate* date); +NSString* ReadiumGCDWebServerFormatRFC822(NSDate* date); /** * Converts a RFC822 formatted string into a date. @@ -85,13 +85,13 @@ NSString* GCDWebServerFormatRFC822(NSDate* date); * * @warning Timezones other than GMT are not supported by this function. */ -NSDate* _Nullable GCDWebServerParseRFC822(NSString* string); +NSDate* _Nullable ReadiumGCDWebServerParseRFC822(NSString* string); /** * Converts a date into a string using IOS 8601 formatting. * http://tools.ietf.org/html/rfc3339#section-5.6 */ -NSString* GCDWebServerFormatISO8601(NSDate* date); +NSString* ReadiumGCDWebServerFormatISO8601(NSDate* date); /** * Converts a ISO 8601 formatted string into a date. @@ -100,12 +100,12 @@ NSString* GCDWebServerFormatISO8601(NSDate* date); * @warning Only "calendar" variant is supported at this time and timezones * other than GMT are not supported either. */ -NSDate* _Nullable GCDWebServerParseISO8601(NSString* string); +NSDate* _Nullable ReadiumGCDWebServerParseISO8601(NSString* string); /** * Removes "//", "/./" and "/../" components from path as well as any trailing slash. */ -NSString* GCDWebServerNormalizePath(NSString* path); +NSString* ReadiumGCDWebServerNormalizePath(NSString* path); #ifdef __cplusplus } diff --git a/GCDWebServer/Core/GCDWebServerFunctions.m b/GCDWebServer/Core/GCDWebServerFunctions.m index 34151ad0..48424bf8 100644 --- a/GCDWebServer/Core/GCDWebServerFunctions.m +++ b/GCDWebServer/Core/GCDWebServerFunctions.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebServer requires ARC +#error ReadiumGCDWebServer requires ARC #endif #import @@ -52,7 +52,7 @@ static dispatch_queue_t _dateFormatterQueue = NULL; // TODO: Handle RFC 850 and ANSI C's asctime() format -void GCDWebServerInitializeFunctions() { +void ReadiumGCDWebServerInitializeFunctions(void) { GWS_DCHECK([NSThread isMainThread]); // NSDateFormatter should be initialized on main thread if (_dateFormatterRFC822 == nil) { _dateFormatterRFC822 = [[NSDateFormatter alloc] init]; @@ -74,7 +74,7 @@ void GCDWebServerInitializeFunctions() { } } -NSString* GCDWebServerNormalizeHeaderValue(NSString* value) { +NSString* ReadiumGCDWebServerNormalizeHeaderValue(NSString* value) { if (value) { NSRange range = [value rangeOfString:@";"]; // Assume part before ";" separator is case-insensitive if (range.location != NSNotFound) { @@ -86,7 +86,7 @@ void GCDWebServerInitializeFunctions() { return value; } -NSString* GCDWebServerTruncateHeaderValue(NSString* value) { +NSString* ReadiumGCDWebServerTruncateHeaderValue(NSString* value) { if (value) { NSRange range = [value rangeOfString:@";"]; if (range.location != NSNotFound) { @@ -96,7 +96,7 @@ void GCDWebServerInitializeFunctions() { return value; } -NSString* GCDWebServerExtractHeaderValueParameter(NSString* value, NSString* name) { +NSString* ReadiumGCDWebServerExtractHeaderValueParameter(NSString* value, NSString* name) { NSString* parameter = nil; if (value) { NSScanner* scanner = [[NSScanner alloc] initWithString:value]; @@ -115,7 +115,7 @@ void GCDWebServerInitializeFunctions() { } // http://www.w3schools.com/tags/ref_charactersets.asp -NSStringEncoding GCDWebServerStringEncodingFromCharset(NSString* charset) { +NSStringEncoding ReadiumGCDWebServerStringEncodingFromCharset(NSString* charset) { NSStringEncoding encoding = kCFStringEncodingInvalidId; if (charset) { encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)charset)); @@ -123,7 +123,7 @@ NSStringEncoding GCDWebServerStringEncodingFromCharset(NSString* charset) { return (encoding != kCFStringEncodingInvalidId ? encoding : NSUTF8StringEncoding); } -NSString* GCDWebServerFormatRFC822(NSDate* date) { +NSString* ReadiumGCDWebServerFormatRFC822(NSDate* date) { __block NSString* string; dispatch_sync(_dateFormatterQueue, ^{ string = [_dateFormatterRFC822 stringFromDate:date]; @@ -131,7 +131,7 @@ NSStringEncoding GCDWebServerStringEncodingFromCharset(NSString* charset) { return string; } -NSDate* GCDWebServerParseRFC822(NSString* string) { +NSDate* ReadiumGCDWebServerParseRFC822(NSString* string) { __block NSDate* date; dispatch_sync(_dateFormatterQueue, ^{ date = [_dateFormatterRFC822 dateFromString:string]; @@ -139,7 +139,7 @@ NSStringEncoding GCDWebServerStringEncodingFromCharset(NSString* charset) { return date; } -NSString* GCDWebServerFormatISO8601(NSDate* date) { +NSString* ReadiumGCDWebServerFormatISO8601(NSDate* date) { __block NSString* string; dispatch_sync(_dateFormatterQueue, ^{ string = [_dateFormatterISO8601 stringFromDate:date]; @@ -147,7 +147,7 @@ NSStringEncoding GCDWebServerStringEncodingFromCharset(NSString* charset) { return string; } -NSDate* GCDWebServerParseISO8601(NSString* string) { +NSDate* ReadiumGCDWebServerParseISO8601(NSString* string) { __block NSDate* date; dispatch_sync(_dateFormatterQueue, ^{ date = [_dateFormatterISO8601 dateFromString:string]; @@ -155,14 +155,14 @@ NSStringEncoding GCDWebServerStringEncodingFromCharset(NSString* charset) { return date; } -BOOL GCDWebServerIsTextContentType(NSString* type) { +BOOL ReadiumGCDWebServerIsTextContentType(NSString* type) { return ([type hasPrefix:@"text/"] || [type hasPrefix:@"application/json"] || [type hasPrefix:@"application/xml"]); } -NSString* GCDWebServerDescribeData(NSData* data, NSString* type) { - if (GCDWebServerIsTextContentType(type)) { - NSString* charset = GCDWebServerExtractHeaderValueParameter(type, @"charset"); - NSString* string = [[NSString alloc] initWithData:data encoding:GCDWebServerStringEncodingFromCharset(charset)]; +NSString* ReadiumGCDWebServerDescribeData(NSData* data, NSString* type) { + if (ReadiumGCDWebServerIsTextContentType(type)) { + NSString* charset = ReadiumGCDWebServerExtractHeaderValueParameter(type, @"charset"); + NSString* string = [[NSString alloc] initWithData:data encoding:ReadiumGCDWebServerStringEncodingFromCharset(charset)]; if (string) { return string; } @@ -170,7 +170,7 @@ BOOL GCDWebServerIsTextContentType(NSString* type) { return [NSString stringWithFormat:@"<%lu bytes>", (unsigned long)data.length]; } -NSString* GCDWebServerGetMimeTypeForExtension(NSString* extension, NSDictionary* overrides) { +NSString* ReadiumGCDWebServerGetMimeTypeForExtension(NSString* extension, NSDictionary* overrides) { NSDictionary* builtInOverrides = @{@"css" : @"text/css"}; NSString* mimeType = nil; extension = [extension lowercaseString]; @@ -190,21 +190,21 @@ BOOL GCDWebServerIsTextContentType(NSString* type) { return mimeType ? mimeType : kGCDWebServerDefaultMimeType; } -NSString* GCDWebServerEscapeURLString(NSString* string) { +NSString* ReadiumGCDWebServerEscapeURLString(NSString* string) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(":@/?&=+"), kCFStringEncodingUTF8)); #pragma clang diagnostic pop } -NSString* GCDWebServerUnescapeURLString(NSString* string) { +NSString* ReadiumGCDWebServerUnescapeURLString(NSString* string) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" return CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)string, CFSTR(""), kCFStringEncodingUTF8)); #pragma clang diagnostic pop } -NSDictionary* GCDWebServerParseURLEncodedForm(NSString* form) { +NSDictionary* ReadiumGCDWebServerParseURLEncodedForm(NSString* form) { NSMutableDictionary* parameters = [NSMutableDictionary dictionary]; NSScanner* scanner = [[NSScanner alloc] initWithString:form]; [scanner setCharactersToBeSkipped:nil]; @@ -222,9 +222,9 @@ BOOL GCDWebServerIsTextContentType(NSString* type) { } key = [key stringByReplacingOccurrencesOfString:@"+" withString:@" "]; - NSString* unescapedKey = key ? GCDWebServerUnescapeURLString(key) : nil; + NSString* unescapedKey = key ? ReadiumGCDWebServerUnescapeURLString(key) : nil; value = [value stringByReplacingOccurrencesOfString:@"+" withString:@" "]; - NSString* unescapedValue = value ? GCDWebServerUnescapeURLString(value) : nil; + NSString* unescapedValue = value ? ReadiumGCDWebServerUnescapeURLString(value) : nil; if (unescapedKey && unescapedValue) { [parameters setObject:unescapedValue forKey:unescapedKey]; } else { @@ -240,7 +240,7 @@ BOOL GCDWebServerIsTextContentType(NSString* type) { return parameters; } -NSString* GCDWebServerStringFromSockAddr(const struct sockaddr* addr, BOOL includeService) { +NSString* ReadiumGCDWebServerStringFromSockAddr(const struct sockaddr* addr, BOOL includeService) { char hostBuffer[NI_MAXHOST]; char serviceBuffer[NI_MAXSERV]; if (getnameinfo(addr, addr->sa_len, hostBuffer, sizeof(hostBuffer), serviceBuffer, sizeof(serviceBuffer), NI_NUMERICHOST | NI_NUMERICSERV | NI_NOFQDN) != 0) { @@ -253,7 +253,7 @@ BOOL GCDWebServerIsTextContentType(NSString* type) { return includeService ? [NSString stringWithFormat:@"%s:%s", hostBuffer, serviceBuffer] : (NSString*)[NSString stringWithUTF8String:hostBuffer]; } -NSString* GCDWebServerGetPrimaryIPAddress(BOOL useIPv6) { +NSString* ReadiumGCDWebServerGetPrimaryIPAddress(BOOL useIPv6) { NSString* address = nil; #if TARGET_OS_IPHONE #if !TARGET_IPHONE_SIMULATOR && !TARGET_OS_TV @@ -261,7 +261,7 @@ BOOL GCDWebServerIsTextContentType(NSString* type) { #endif #else const char* primaryInterface = NULL; - SCDynamicStoreRef store = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("GCDWebServer"), NULL, NULL); + SCDynamicStoreRef store = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("ReadiumGCDWebServer"), NULL, NULL); if (store) { CFPropertyListRef info = SCDynamicStoreCopyValue(store, CFSTR("State:/Network/Global/IPv4")); // There is no equivalent for IPv6 but the primary interface should be the same if (info) { @@ -291,7 +291,7 @@ BOOL GCDWebServerIsTextContentType(NSString* type) { continue; } if ((ifap->ifa_flags & IFF_UP) && ((!useIPv6 && (ifap->ifa_addr->sa_family == AF_INET)) || (useIPv6 && (ifap->ifa_addr->sa_family == AF_INET6)))) { - address = GCDWebServerStringFromSockAddr(ifap->ifa_addr, NO); + address = ReadiumGCDWebServerStringFromSockAddr(ifap->ifa_addr, NO); break; } } @@ -300,7 +300,7 @@ BOOL GCDWebServerIsTextContentType(NSString* type) { return address; } -NSString* GCDWebServerComputeMD5Digest(NSString* format, ...) { +NSString* ReadiumGCDWebServerComputeMD5Digest(NSString* format, ...) { va_list arguments; va_start(arguments, format); const char* string = [[[NSString alloc] initWithFormat:format arguments:arguments] UTF8String]; @@ -319,7 +319,7 @@ BOOL GCDWebServerIsTextContentType(NSString* type) { return (NSString*)[NSString stringWithUTF8String:buffer]; } -NSString* GCDWebServerNormalizePath(NSString* path) { +NSString* ReadiumGCDWebServerNormalizePath(NSString* path) { NSMutableArray* components = [[NSMutableArray alloc] init]; for (NSString* component in [path componentsSeparatedByString:@"/"]) { if ([component isEqualToString:@".."]) { diff --git a/GCDWebServer/Core/GCDWebServerHTTPStatusCodes.h b/GCDWebServer/Core/GCDWebServerHTTPStatusCodes.h index 12b697e3..0d18c1a1 100644 --- a/GCDWebServer/Core/GCDWebServerHTTPStatusCodes.h +++ b/GCDWebServer/Core/GCDWebServerHTTPStatusCodes.h @@ -33,7 +33,7 @@ /** * Convenience constants for "informational" HTTP status codes. */ -typedef NS_ENUM(NSInteger, GCDWebServerInformationalHTTPStatusCode) { +typedef NS_ENUM(NSInteger, ReadiumGCDWebServerInformationalHTTPStatusCode) { kGCDWebServerHTTPStatusCode_Continue = 100, kGCDWebServerHTTPStatusCode_SwitchingProtocols = 101, kGCDWebServerHTTPStatusCode_Processing = 102 @@ -42,7 +42,7 @@ typedef NS_ENUM(NSInteger, GCDWebServerInformationalHTTPStatusCode) { /** * Convenience constants for "successful" HTTP status codes. */ -typedef NS_ENUM(NSInteger, GCDWebServerSuccessfulHTTPStatusCode) { +typedef NS_ENUM(NSInteger, ReadiumGCDWebServerSuccessfulHTTPStatusCode) { kGCDWebServerHTTPStatusCode_OK = 200, kGCDWebServerHTTPStatusCode_Created = 201, kGCDWebServerHTTPStatusCode_Accepted = 202, @@ -57,7 +57,7 @@ typedef NS_ENUM(NSInteger, GCDWebServerSuccessfulHTTPStatusCode) { /** * Convenience constants for "redirection" HTTP status codes. */ -typedef NS_ENUM(NSInteger, GCDWebServerRedirectionHTTPStatusCode) { +typedef NS_ENUM(NSInteger, ReadiumGCDWebServerRedirectionHTTPStatusCode) { kGCDWebServerHTTPStatusCode_MultipleChoices = 300, kGCDWebServerHTTPStatusCode_MovedPermanently = 301, kGCDWebServerHTTPStatusCode_Found = 302, @@ -71,7 +71,7 @@ typedef NS_ENUM(NSInteger, GCDWebServerRedirectionHTTPStatusCode) { /** * Convenience constants for "client error" HTTP status codes. */ -typedef NS_ENUM(NSInteger, GCDWebServerClientErrorHTTPStatusCode) { +typedef NS_ENUM(NSInteger, ReadiumGCDWebServerClientErrorHTTPStatusCode) { kGCDWebServerHTTPStatusCode_BadRequest = 400, kGCDWebServerHTTPStatusCode_Unauthorized = 401, kGCDWebServerHTTPStatusCode_PaymentRequired = 402, @@ -102,7 +102,7 @@ typedef NS_ENUM(NSInteger, GCDWebServerClientErrorHTTPStatusCode) { /** * Convenience constants for "server error" HTTP status codes. */ -typedef NS_ENUM(NSInteger, GCDWebServerServerErrorHTTPStatusCode) { +typedef NS_ENUM(NSInteger, ReadiumGCDWebServerServerErrorHTTPStatusCode) { kGCDWebServerHTTPStatusCode_InternalServerError = 500, kGCDWebServerHTTPStatusCode_NotImplemented = 501, kGCDWebServerHTTPStatusCode_BadGateway = 502, diff --git a/GCDWebServer/Core/GCDWebServerPrivate.h b/GCDWebServer/Core/GCDWebServerPrivate.h index 5352c3d8..b6aa8cc6 100644 --- a/GCDWebServer/Core/GCDWebServerPrivate.h +++ b/GCDWebServer/Core/GCDWebServerPrivate.h @@ -29,7 +29,7 @@ #import /** - * All GCDWebServer headers. + * All ReadiumGCDWebServer headers. */ #import "GCDWebServerHTTPStatusCodes.h" @@ -94,7 +94,7 @@ #define GWS_DNOT_REACHED() XLOG_DEBUG_UNREACHABLE() /** - * If all of the above fail, then use GCDWebServer built-in + * If all of the above fail, then use ReadiumGCDWebServer built-in * logging facility. */ @@ -102,7 +102,7 @@ #define __GCDWEBSERVER_LOGGING_FACILITY_BUILTIN__ -typedef NS_ENUM(int, GCDWebServerLoggingLevel) { +typedef NS_ENUM(int, ReadiumGCDWebServerLoggingLevel) { kGCDWebServerLoggingLevel_Debug = 0, kGCDWebServerLoggingLevel_Verbose, kGCDWebServerLoggingLevel_Info, @@ -110,32 +110,32 @@ typedef NS_ENUM(int, GCDWebServerLoggingLevel) { kGCDWebServerLoggingLevel_Error }; -extern GCDWebServerLoggingLevel GCDWebServerLogLevel; -extern void GCDWebServerLogMessage(GCDWebServerLoggingLevel level, NSString* _Nonnull format, ...) NS_FORMAT_FUNCTION(2, 3); +extern ReadiumGCDWebServerLoggingLevel ReadiumGCDWebServerLogLevel; +extern void ReadiumGCDWebServerLogMessage(ReadiumGCDWebServerLoggingLevel level, NSString* _Nonnull format, ...) NS_FORMAT_FUNCTION(2, 3); #if DEBUG #define GWS_LOG_DEBUG(...) \ do { \ - if (GCDWebServerLogLevel <= kGCDWebServerLoggingLevel_Debug) GCDWebServerLogMessage(kGCDWebServerLoggingLevel_Debug, __VA_ARGS__); \ + if (ReadiumGCDWebServerLogLevel <= kGCDWebServerLoggingLevel_Debug) ReadiumGCDWebServerLogMessage(kGCDWebServerLoggingLevel_Debug, __VA_ARGS__); \ } while (0) #else #define GWS_LOG_DEBUG(...) #endif #define GWS_LOG_VERBOSE(...) \ do { \ - if (GCDWebServerLogLevel <= kGCDWebServerLoggingLevel_Verbose) GCDWebServerLogMessage(kGCDWebServerLoggingLevel_Verbose, __VA_ARGS__); \ + if (ReadiumGCDWebServerLogLevel <= kGCDWebServerLoggingLevel_Verbose) ReadiumGCDWebServerLogMessage(kGCDWebServerLoggingLevel_Verbose, __VA_ARGS__); \ } while (0) #define GWS_LOG_INFO(...) \ do { \ - if (GCDWebServerLogLevel <= kGCDWebServerLoggingLevel_Info) GCDWebServerLogMessage(kGCDWebServerLoggingLevel_Info, __VA_ARGS__); \ + if (ReadiumGCDWebServerLogLevel <= kGCDWebServerLoggingLevel_Info) ReadiumGCDWebServerLogMessage(kGCDWebServerLoggingLevel_Info, __VA_ARGS__); \ } while (0) #define GWS_LOG_WARNING(...) \ do { \ - if (GCDWebServerLogLevel <= kGCDWebServerLoggingLevel_Warning) GCDWebServerLogMessage(kGCDWebServerLoggingLevel_Warning, __VA_ARGS__); \ + if (ReadiumGCDWebServerLogLevel <= kGCDWebServerLoggingLevel_Warning) ReadiumGCDWebServerLogMessage(kGCDWebServerLoggingLevel_Warning, __VA_ARGS__); \ } while (0) #define GWS_LOG_ERROR(...) \ do { \ - if (GCDWebServerLogLevel <= kGCDWebServerLoggingLevel_Error) GCDWebServerLogMessage(kGCDWebServerLoggingLevel_Error, __VA_ARGS__); \ + if (ReadiumGCDWebServerLogLevel <= kGCDWebServerLoggingLevel_Error) ReadiumGCDWebServerLogMessage(kGCDWebServerLoggingLevel_Error, __VA_ARGS__); \ } while (0) #endif @@ -168,52 +168,52 @@ extern void GCDWebServerLogMessage(GCDWebServerLoggingLevel level, NSString* _No NS_ASSUME_NONNULL_BEGIN /** - * GCDWebServer internal constants and APIs. + * ReadiumGCDWebServer internal constants and APIs. */ #define kGCDWebServerDefaultMimeType @"application/octet-stream" -#define kGCDWebServerErrorDomain @"GCDWebServerErrorDomain" +#define kGCDWebServerErrorDomain @"ReadiumGCDWebServerErrorDomain" -static inline BOOL GCDWebServerIsValidByteRange(NSRange range) { +static inline BOOL ReadiumGCDWebServerIsValidByteRange(NSRange range) { return ((range.location != NSUIntegerMax) || (range.length > 0)); } -static inline NSError* GCDWebServerMakePosixError(int code) { +static inline NSError* ReadiumGCDWebServerMakePosixError(int code) { return [NSError errorWithDomain:NSPOSIXErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey : (NSString*)[NSString stringWithUTF8String:strerror(code)]}]; } -extern void GCDWebServerInitializeFunctions(void); -extern NSString* _Nullable GCDWebServerNormalizeHeaderValue(NSString* _Nullable value); -extern NSString* _Nullable GCDWebServerTruncateHeaderValue(NSString* _Nullable value); -extern NSString* _Nullable GCDWebServerExtractHeaderValueParameter(NSString* _Nullable value, NSString* attribute); -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); -extern NSString* GCDWebServerStringFromSockAddr(const struct sockaddr* addr, BOOL includeService); - -@interface GCDWebServerConnection () -- (instancetype)initWithServer:(GCDWebServer*)server localAddress:(NSData*)localAddress remoteAddress:(NSData*)remoteAddress socket:(CFSocketNativeHandle)socket; +extern void ReadiumGCDWebServerInitializeFunctions(void); +extern NSString* _Nullable ReadiumGCDWebServerNormalizeHeaderValue(NSString* _Nullable value); +extern NSString* _Nullable ReadiumGCDWebServerTruncateHeaderValue(NSString* _Nullable value); +extern NSString* _Nullable ReadiumGCDWebServerExtractHeaderValueParameter(NSString* _Nullable value, NSString* attribute); +extern NSStringEncoding ReadiumGCDWebServerStringEncodingFromCharset(NSString* charset); +extern BOOL ReadiumGCDWebServerIsTextContentType(NSString* type); +extern NSString* ReadiumGCDWebServerDescribeData(NSData* data, NSString* contentType); +extern NSString* ReadiumGCDWebServerComputeMD5Digest(NSString* format, ...) NS_FORMAT_FUNCTION(1, 2); +extern NSString* ReadiumGCDWebServerStringFromSockAddr(const struct sockaddr* addr, BOOL includeService); + +@interface ReadiumGCDWebServerConnection () +- (instancetype)initWithServer:(ReadiumGCDWebServer*)server localAddress:(NSData*)localAddress remoteAddress:(NSData*)remoteAddress socket:(CFSocketNativeHandle)socket; @end -@interface GCDWebServer () -@property(nonatomic, readonly) NSMutableArray* handlers; +@interface ReadiumGCDWebServer () +@property(nonatomic, readonly) NSMutableArray* handlers; @property(nonatomic, readonly, nullable) NSString* serverName; @property(nonatomic, readonly, nullable) NSString* authenticationRealm; @property(nonatomic, readonly, nullable) NSMutableDictionary* authenticationBasicAccounts; @property(nonatomic, readonly, nullable) NSMutableDictionary* authenticationDigestAccounts; @property(nonatomic, readonly) BOOL shouldAutomaticallyMapHEADToGET; @property(nonatomic, readonly) dispatch_queue_priority_t dispatchQueuePriority; -- (void)willStartConnection:(GCDWebServerConnection*)connection; -- (void)didEndConnection:(GCDWebServerConnection*)connection; +- (void)willStartConnection:(ReadiumGCDWebServerConnection*)connection; +- (void)didEndConnection:(ReadiumGCDWebServerConnection*)connection; @end -@interface GCDWebServerHandler : NSObject -@property(nonatomic, readonly) GCDWebServerMatchBlock matchBlock; -@property(nonatomic, readonly) GCDWebServerAsyncProcessBlock asyncProcessBlock; +@interface ReadiumGCDWebServerHandler : NSObject +@property(nonatomic, readonly) ReadiumGCDWebServerMatchBlock matchBlock; +@property(nonatomic, readonly) ReadiumGCDWebServerAsyncProcessBlock asyncProcessBlock; @end -@interface GCDWebServerRequest () +@interface ReadiumGCDWebServerRequest () @property(nonatomic, readonly) BOOL usesChunkedTransferEncoding; @property(nonatomic) NSData* localAddressData; @property(nonatomic) NSData* remoteAddressData; @@ -224,12 +224,12 @@ extern NSString* GCDWebServerStringFromSockAddr(const struct sockaddr* addr, BOO - (void)setAttribute:(nullable id)attribute forKey:(NSString*)key; @end -@interface GCDWebServerResponse () +@interface ReadiumGCDWebServerResponse () @property(nonatomic, readonly) NSDictionary* additionalHeaders; @property(nonatomic, readonly) BOOL usesChunkedTransferEncoding; - (void)prepareForReading; - (BOOL)performOpen:(NSError**)error; -- (void)performReadDataWithCompletion:(GCDWebServerBodyReaderCompletionBlock)block; +- (void)performReadDataWithCompletion:(ReadiumGCDWebServerBodyReaderCompletionBlock)block; - (void)performClose; @end diff --git a/GCDWebServer/Core/GCDWebServerRequest.h b/GCDWebServer/Core/GCDWebServerRequest.h index 79b446a5..e352d296 100644 --- a/GCDWebServer/Core/GCDWebServerRequest.h +++ b/GCDWebServer/Core/GCDWebServerRequest.h @@ -30,25 +30,25 @@ NS_ASSUME_NONNULL_BEGIN /** - * Attribute key to retrieve an NSArray containing NSStrings from a GCDWebServerRequest + * Attribute key to retrieve an NSArray containing NSStrings from a ReadiumGCDWebServerRequest * with the contents of any regular expression captures done on the request path. * * @warning This attribute will only be set on the request if adding a handler using * -addHandlerForMethod:pathRegex:requestClass:processBlock:. */ -extern NSString* const GCDWebServerRequestAttribute_RegexCaptures; +extern NSString* const ReadiumGCDWebServerRequestAttribute_RegexCaptures; /** - * This protocol is used by the GCDWebServerConnection to communicate with - * the GCDWebServerRequest and write the received HTTP body data. + * This protocol is used by the ReadiumGCDWebServerConnection to communicate with + * the ReadiumGCDWebServerRequest and write the received HTTP body data. * - * Note that multiple GCDWebServerBodyWriter objects can be chained together + * Note that multiple ReadiumGCDWebServerBodyWriter objects can be chained together * internally e.g. to automatically decode gzip encoded content before - * passing it on to the GCDWebServerRequest. + * passing it on to the ReadiumGCDWebServerRequest. * * @warning These methods can be called on any GCD thread. */ -@protocol GCDWebServerBodyWriter +@protocol ReadiumGCDWebServerBodyWriter /** * This method is called before any body data is received. @@ -77,17 +77,17 @@ extern NSString* const GCDWebServerRequestAttribute_RegexCaptures; @end /** - * The GCDWebServerRequest class is instantiated by the GCDWebServerConnection + * The ReadiumGCDWebServerRequest class is instantiated by the ReadiumGCDWebServerConnection * after the HTTP headers have been received. Each instance wraps a single HTTP - * request. If a body is present, the methods from the GCDWebServerBodyWriter - * protocol will be called by the GCDWebServerConnection to receive it. + * request. If a body is present, the methods from the ReadiumGCDWebServerBodyWriter + * protocol will be called by the ReadiumGCDWebServerConnection to receive it. * - * The default implementation of the GCDWebServerBodyWriter protocol on the class + * The default implementation of the ReadiumGCDWebServerBodyWriter protocol on the class * simply ignores the body data. * - * @warning GCDWebServerRequest instances can be created and used on any GCD thread. + * @warning ReadiumGCDWebServerRequest instances can be created and used on any GCD thread. */ -@interface GCDWebServerRequest : NSObject +@interface ReadiumGCDWebServerRequest : NSObject /** * Returns the HTTP method for the request. diff --git a/GCDWebServer/Core/GCDWebServerRequest.m b/GCDWebServer/Core/GCDWebServerRequest.m index 4c14542c..04cb82cc 100644 --- a/GCDWebServer/Core/GCDWebServerRequest.m +++ b/GCDWebServer/Core/GCDWebServerRequest.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebServer requires ARC +#error ReadiumGCDWebServer requires ARC #endif #import @@ -37,23 +37,23 @@ #import "GCDWebServerPrivate.h" #endif -NSString* const GCDWebServerRequestAttribute_RegexCaptures = @"GCDWebServerRequestAttribute_RegexCaptures"; +NSString* const ReadiumGCDWebServerRequestAttribute_RegexCaptures = @"ReadiumGCDWebServerRequestAttribute_RegexCaptures"; #define kZlibErrorDomain @"ZlibErrorDomain" #define kGZipInitialBufferSize (256 * 1024) -@interface GCDWebServerBodyDecoder : NSObject +@interface ReadiumGCDWebServerBodyDecoder : NSObject @end -@interface GCDWebServerGZipDecoder : GCDWebServerBodyDecoder +@interface ReadiumGCDWebServerGZipDecoder : ReadiumGCDWebServerBodyDecoder @end -@implementation GCDWebServerBodyDecoder { - GCDWebServerRequest* __unsafe_unretained _request; - id __unsafe_unretained _writer; +@implementation ReadiumGCDWebServerBodyDecoder { + ReadiumGCDWebServerRequest* __unsafe_unretained _request; + id __unsafe_unretained _writer; } -- (instancetype)initWithRequest:(GCDWebServerRequest* _Nonnull)request writer:(id _Nonnull)writer { +- (instancetype)initWithRequest:(ReadiumGCDWebServerRequest* _Nonnull)request writer:(id _Nonnull)writer { if ((self = [super init])) { _request = request; _writer = writer; @@ -75,7 +75,7 @@ - (BOOL)close:(NSError**)error { @end -@implementation GCDWebServerGZipDecoder { +@implementation ReadiumGCDWebServerGZipDecoder { z_stream _stream; BOOL _finished; } @@ -138,10 +138,10 @@ - (BOOL)close:(NSError**)error { @end -@implementation GCDWebServerRequest { +@implementation ReadiumGCDWebServerRequest { BOOL _opened; - NSMutableArray* _decoders; - id __unsafe_unretained _writer; + NSMutableArray* _decoders; + id __unsafe_unretained _writer; NSMutableDictionary* _attributes; } @@ -153,8 +153,8 @@ - (instancetype)initWithMethod:(NSString*)method url:(NSURL*)url headers:(NSDict _path = [path copy]; _query = query; - _contentType = GCDWebServerNormalizeHeaderValue([_headers objectForKey:@"Content-Type"]); - _usesChunkedTransferEncoding = [GCDWebServerNormalizeHeaderValue([_headers objectForKey:@"Transfer-Encoding"]) isEqualToString:@"chunked"]; + _contentType = ReadiumGCDWebServerNormalizeHeaderValue([_headers objectForKey:@"Content-Type"]); + _usesChunkedTransferEncoding = [ReadiumGCDWebServerNormalizeHeaderValue([_headers objectForKey:@"Transfer-Encoding"]) isEqualToString:@"chunked"]; NSString* lengthHeader = [_headers objectForKey:@"Content-Length"]; if (lengthHeader) { NSInteger length = [lengthHeader integerValue]; @@ -182,12 +182,12 @@ - (instancetype)initWithMethod:(NSString*)method url:(NSURL*)url headers:(NSDict NSString* modifiedHeader = [_headers objectForKey:@"If-Modified-Since"]; if (modifiedHeader) { - _ifModifiedSince = [GCDWebServerParseRFC822(modifiedHeader) copy]; + _ifModifiedSince = [ReadiumGCDWebServerParseRFC822(modifiedHeader) copy]; } _ifNoneMatch = [_headers objectForKey:@"If-None-Match"]; _byteRange = NSMakeRange(NSUIntegerMax, 0); - NSString* rangeHeader = GCDWebServerNormalizeHeaderValue([_headers objectForKey:@"Range"]); + NSString* rangeHeader = ReadiumGCDWebServerNormalizeHeaderValue([_headers objectForKey:@"Range"]); if (rangeHeader) { if ([rangeHeader hasPrefix:@"bytes="]) { NSArray* components = [[rangeHeader substringFromIndex:6] componentsSeparatedByString:@","]; @@ -231,7 +231,7 @@ - (BOOL)hasBody { } - (BOOL)hasByteRange { - return GCDWebServerIsValidByteRange(_byteRange); + return ReadiumGCDWebServerIsValidByteRange(_byteRange); } - (id)attributeForKey:(NSString*)key { @@ -252,8 +252,8 @@ - (BOOL)close:(NSError**)error { - (void)prepareForWriting { _writer = self; - if ([GCDWebServerNormalizeHeaderValue([self.headers objectForKey:@"Content-Encoding"]) isEqualToString:@"gzip"]) { - GCDWebServerGZipDecoder* decoder = [[GCDWebServerGZipDecoder alloc] initWithRequest:self writer:_writer]; + if ([ReadiumGCDWebServerNormalizeHeaderValue([self.headers objectForKey:@"Content-Encoding"]) isEqualToString:@"gzip"]) { + ReadiumGCDWebServerGZipDecoder* decoder = [[ReadiumGCDWebServerGZipDecoder alloc] initWithRequest:self writer:_writer]; [_decoders addObject:decoder]; _writer = decoder; } @@ -285,11 +285,11 @@ - (void)setAttribute:(id)attribute forKey:(NSString*)key { } - (NSString*)localAddressString { - return GCDWebServerStringFromSockAddr(_localAddressData.bytes, YES); + return ReadiumGCDWebServerStringFromSockAddr(_localAddressData.bytes, YES); } - (NSString*)remoteAddressString { - return GCDWebServerStringFromSockAddr(_remoteAddressData.bytes, YES); + return ReadiumGCDWebServerStringFromSockAddr(_remoteAddressData.bytes, YES); } - (NSString*)description { diff --git a/GCDWebServer/Core/GCDWebServerResponse.h b/GCDWebServer/Core/GCDWebServerResponse.h index 2e1365bf..111842b2 100644 --- a/GCDWebServer/Core/GCDWebServerResponse.h +++ b/GCDWebServer/Core/GCDWebServerResponse.h @@ -30,22 +30,22 @@ NS_ASSUME_NONNULL_BEGIN /** - * The GCDWebServerBodyReaderCompletionBlock is passed by GCDWebServer to the - * GCDWebServerBodyReader object when reading data from it asynchronously. + * The ReadiumGCDWebServerBodyReaderCompletionBlock is passed by ReadiumGCDWebServer to the + * ReadiumGCDWebServerBodyReader object when reading data from it asynchronously. */ -typedef void (^GCDWebServerBodyReaderCompletionBlock)(NSData* _Nullable data, NSError* _Nullable error); +typedef void (^ReadiumGCDWebServerBodyReaderCompletionBlock)(NSData* _Nullable data, NSError* _Nullable error); /** - * This protocol is used by the GCDWebServerConnection to communicate with - * the GCDWebServerResponse and read the HTTP body data to send. + * This protocol is used by the ReadiumGCDWebServerConnection to communicate with + * the ReadiumGCDWebServerResponse and read the HTTP body data to send. * - * Note that multiple GCDWebServerBodyReader objects can be chained together + * Note that multiple ReadiumGCDWebServerBodyReader objects can be chained together * internally e.g. to automatically apply gzip encoding to the content before - * passing it on to the GCDWebServerResponse. + * passing it on to the ReadiumGCDWebServerResponse. * * @warning These methods can be called on any GCD thread. */ -@protocol GCDWebServerBodyReader +@protocol ReadiumGCDWebServerBodyReader @required @@ -80,22 +80,22 @@ typedef void (^GCDWebServerBodyReaderCompletionBlock)(NSData* _Nullable data, NS * NSData if there is body data available, or an empty NSData there is no more * body data, or nil on error and pass an NSError along. */ -- (void)asyncReadDataWithCompletion:(GCDWebServerBodyReaderCompletionBlock)block; +- (void)asyncReadDataWithCompletion:(ReadiumGCDWebServerBodyReaderCompletionBlock)block; @end /** - * The GCDWebServerResponse class is used to wrap a single HTTP response. - * It is instantiated by the handler of the GCDWebServer that handled the request. - * If a body is present, the methods from the GCDWebServerBodyReader protocol - * will be called by the GCDWebServerConnection to send it. + * The ReadiumGCDWebServerResponse class is used to wrap a single HTTP response. + * It is instantiated by the handler of the ReadiumGCDWebServer that handled the request. + * If a body is present, the methods from the ReadiumGCDWebServerBodyReader protocol + * will be called by the ReadiumGCDWebServerConnection to send it. * - * The default implementation of the GCDWebServerBodyReader protocol + * The default implementation of the ReadiumGCDWebServerBodyReader protocol * on the class simply returns an empty body. * - * @warning GCDWebServerResponse instances can be created and used on any GCD thread. + * @warning ReadiumGCDWebServerResponse instances can be created and used on any GCD thread. */ -@interface GCDWebServerResponse : NSObject +@interface ReadiumGCDWebServerResponse : NSObject /** * Sets the content type for the body of the response. @@ -110,7 +110,7 @@ typedef void (^GCDWebServerBodyReaderCompletionBlock)(NSData* _Nullable data, NS * Sets the content length for the body of the response. If a body is present * but this property is set to "NSUIntegerMax", this means the length of the body * cannot be known ahead of time. Chunked transfer encoding will be - * automatically enabled by the GCDWebServerConnection to comply with HTTP/1.1 + * automatically enabled by the ReadiumGCDWebServerConnection to comply with HTTP/1.1 * specifications. * * The default value is "NSUIntegerMax" i.e. the response has no body or its length @@ -174,7 +174,7 @@ typedef void (^GCDWebServerBodyReaderCompletionBlock)(NSData* _Nullable data, NS * Pass a nil value to remove an additional header. * * @warning Do not attempt to override the primary headers used - * by GCDWebServerResponse like "Content-Type", "ETag", etc... + * by ReadiumGCDWebServerResponse like "Content-Type", "ETag", etc... */ - (void)setValue:(nullable NSString*)value forAdditionalHeader:(NSString*)header; @@ -185,7 +185,7 @@ typedef void (^GCDWebServerBodyReaderCompletionBlock)(NSData* _Nullable data, NS @end -@interface GCDWebServerResponse (Extensions) +@interface ReadiumGCDWebServerResponse (Extensions) /** * Creates a empty response with a specific HTTP status code. diff --git a/GCDWebServer/Core/GCDWebServerResponse.m b/GCDWebServer/Core/GCDWebServerResponse.m index fc3d6200..e9d9c2c2 100644 --- a/GCDWebServer/Core/GCDWebServerResponse.m +++ b/GCDWebServer/Core/GCDWebServerResponse.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebServer requires ARC +#error ReadiumGCDWebServer requires ARC #endif #import @@ -40,18 +40,18 @@ #define kZlibErrorDomain @"ZlibErrorDomain" #define kGZipInitialBufferSize (256 * 1024) -@interface GCDWebServerBodyEncoder : NSObject +@interface R2GCDWebServerBodyEncoder : NSObject @end -@interface GCDWebServerGZipEncoder : GCDWebServerBodyEncoder +@interface ReadiumGCDWebServerGZipEncoder : R2GCDWebServerBodyEncoder @end -@implementation GCDWebServerBodyEncoder { - GCDWebServerResponse* __unsafe_unretained _response; - id __unsafe_unretained _reader; +@implementation R2GCDWebServerBodyEncoder { + ReadiumGCDWebServerResponse* __unsafe_unretained _response; + id __unsafe_unretained _reader; } -- (instancetype)initWithResponse:(GCDWebServerResponse* _Nonnull)response reader:(id _Nonnull)reader { +- (instancetype)initWithResponse:(ReadiumGCDWebServerResponse* _Nonnull)response reader:(id _Nonnull)reader { if ((self = [super init])) { _response = response; _reader = reader; @@ -73,12 +73,12 @@ - (void)close { @end -@implementation GCDWebServerGZipEncoder { +@implementation ReadiumGCDWebServerGZipEncoder { z_stream _stream; BOOL _finished; } -- (instancetype)initWithResponse:(GCDWebServerResponse* _Nonnull)response reader:(id _Nonnull)reader { +- (instancetype)initWithResponse:(ReadiumGCDWebServerResponse* _Nonnull)response reader:(id _Nonnull)reader { if ((self = [super initWithResponse:response reader:reader])) { response.contentLength = NSUIntegerMax; // Make sure "Content-Length" header is not set since we don't know it [response setValue:@"gzip" forAdditionalHeader:@"Content-Encoding"]; @@ -152,14 +152,14 @@ - (void)close { @end -@implementation GCDWebServerResponse { +@implementation ReadiumGCDWebServerResponse { BOOL _opened; - NSMutableArray* _encoders; - id __unsafe_unretained _reader; + NSMutableArray* _encoders; + id __unsafe_unretained _reader; } + (instancetype)response { - return [(GCDWebServerResponse*)[[self class] alloc] init]; + return [(ReadiumGCDWebServerResponse*)[[self class] alloc] init]; } - (instancetype)init { @@ -201,7 +201,7 @@ - (void)close { - (void)prepareForReading { _reader = self; if (_gzipContentEncodingEnabled) { - GCDWebServerGZipEncoder* encoder = [[GCDWebServerGZipEncoder alloc] initWithResponse:self reader:_reader]; + ReadiumGCDWebServerGZipEncoder* encoder = [[ReadiumGCDWebServerGZipEncoder alloc] initWithResponse:self reader:_reader]; [_encoders addObject:encoder]; _reader = encoder; } @@ -218,7 +218,7 @@ - (BOOL)performOpen:(NSError**)error { return [_reader open:error]; } -- (void)performReadDataWithCompletion:(GCDWebServerBodyReaderCompletionBlock)block { +- (void)performReadDataWithCompletion:(ReadiumGCDWebServerBodyReaderCompletionBlock)block { GWS_DCHECK(_opened); if ([_reader respondsToSelector:@selector(asyncReadDataWithCompletion:)]) { [_reader asyncReadDataWithCompletion:[block copy]]; @@ -260,14 +260,14 @@ - (NSString*)description { @end -@implementation GCDWebServerResponse (Extensions) +@implementation ReadiumGCDWebServerResponse (Extensions) + (instancetype)responseWithStatusCode:(NSInteger)statusCode { - return [(GCDWebServerResponse*)[self alloc] initWithStatusCode:statusCode]; + return [(ReadiumGCDWebServerResponse*)[self alloc] initWithStatusCode:statusCode]; } + (instancetype)responseWithRedirect:(NSURL*)location permanent:(BOOL)permanent { - return [(GCDWebServerResponse*)[self alloc] initWithRedirect:location permanent:permanent]; + return [(ReadiumGCDWebServerResponse*)[self alloc] initWithRedirect:location permanent:permanent]; } - (instancetype)initWithStatusCode:(NSInteger)statusCode { diff --git a/GCDWebServer/Requests/GCDWebServerDataRequest.h b/GCDWebServer/Requests/GCDWebServerDataRequest.h index b105ce76..ea93c87b 100644 --- a/GCDWebServer/Requests/GCDWebServerDataRequest.h +++ b/GCDWebServer/Requests/GCDWebServerDataRequest.h @@ -30,10 +30,10 @@ NS_ASSUME_NONNULL_BEGIN /** - * The GCDWebServerDataRequest subclass of GCDWebServerRequest stores the body + * The ReadiumGCDWebServerDataRequest subclass of ReadiumGCDWebServerRequest stores the body * of the HTTP request in memory. */ -@interface GCDWebServerDataRequest : GCDWebServerRequest +@interface ReadiumGCDWebServerDataRequest : ReadiumGCDWebServerRequest /** * Returns the data for the request body. @@ -42,7 +42,7 @@ NS_ASSUME_NONNULL_BEGIN @end -@interface GCDWebServerDataRequest (Extensions) +@interface ReadiumGCDWebServerDataRequest (Extensions) /** * Returns the data for the request body interpreted as text. If the content diff --git a/GCDWebServer/Requests/GCDWebServerDataRequest.m b/GCDWebServer/Requests/GCDWebServerDataRequest.m index 7f682d91..a59e34a1 100644 --- a/GCDWebServer/Requests/GCDWebServerDataRequest.m +++ b/GCDWebServer/Requests/GCDWebServerDataRequest.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebServer requires ARC +#error ReadiumGCDWebServer requires ARC #endif #ifdef SWIFT_PACKAGE @@ -35,11 +35,11 @@ #import "GCDWebServerPrivate.h" #endif -@interface GCDWebServerDataRequest () +@interface ReadiumGCDWebServerDataRequest () @property(nonatomic) NSMutableData* data; @end -@implementation GCDWebServerDataRequest { +@implementation ReadiumGCDWebServerDataRequest { NSString* _text; id _jsonObject; } @@ -72,20 +72,20 @@ - (NSString*)description { NSMutableString* description = [NSMutableString stringWithString:[super description]]; if (_data) { [description appendString:@"\n\n"]; - [description appendString:GCDWebServerDescribeData(_data, (NSString*)self.contentType)]; + [description appendString:ReadiumGCDWebServerDescribeData(_data, (NSString*)self.contentType)]; } return description; } @end -@implementation GCDWebServerDataRequest (Extensions) +@implementation ReadiumGCDWebServerDataRequest (Extensions) - (NSString*)text { if (_text == nil) { if ([self.contentType hasPrefix:@"text/"]) { - NSString* charset = GCDWebServerExtractHeaderValueParameter(self.contentType, @"charset"); - _text = [[NSString alloc] initWithData:self.data encoding:GCDWebServerStringEncodingFromCharset(charset)]; + NSString* charset = ReadiumGCDWebServerExtractHeaderValueParameter(self.contentType, @"charset"); + _text = [[NSString alloc] initWithData:self.data encoding:ReadiumGCDWebServerStringEncodingFromCharset(charset)]; } else { GWS_DNOT_REACHED(); } @@ -95,7 +95,7 @@ - (NSString*)text { - (id)jsonObject { if (_jsonObject == nil) { - NSString* mimeType = GCDWebServerTruncateHeaderValue(self.contentType); + NSString* mimeType = ReadiumGCDWebServerTruncateHeaderValue(self.contentType); if ([mimeType isEqualToString:@"application/json"] || [mimeType isEqualToString:@"text/json"] || [mimeType isEqualToString:@"text/javascript"]) { _jsonObject = [NSJSONSerialization JSONObjectWithData:_data options:0 error:NULL]; } else { diff --git a/GCDWebServer/Requests/GCDWebServerFileRequest.h b/GCDWebServer/Requests/GCDWebServerFileRequest.h index 3c6a6d24..644c894e 100644 --- a/GCDWebServer/Requests/GCDWebServerFileRequest.h +++ b/GCDWebServer/Requests/GCDWebServerFileRequest.h @@ -30,16 +30,16 @@ NS_ASSUME_NONNULL_BEGIN /** - * The GCDWebServerFileRequest subclass of GCDWebServerRequest stores the body + * The ReadiumGCDWebServerFileRequest subclass of ReadiumGCDWebServerRequest stores the body * of the HTTP request to a file on disk. */ -@interface GCDWebServerFileRequest : GCDWebServerRequest +@interface ReadiumGCDWebServerFileRequest : ReadiumGCDWebServerRequest /** * Returns the path to the temporary file containing the request body. * * @warning This temporary file will be automatically deleted when the - * GCDWebServerFileRequest is deallocated. If you want to preserve this file, + * ReadiumGCDWebServerFileRequest is deallocated. If you want to preserve this file, * you must move it to a different location beforehand. */ @property(nonatomic, readonly) NSString* temporaryPath; diff --git a/GCDWebServer/Requests/GCDWebServerFileRequest.m b/GCDWebServer/Requests/GCDWebServerFileRequest.m index f201a938..918ce3b8 100644 --- a/GCDWebServer/Requests/GCDWebServerFileRequest.m +++ b/GCDWebServer/Requests/GCDWebServerFileRequest.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebServer requires ARC +#error ReadiumGCDWebServer requires ARC #endif #ifdef SWIFT_PACKAGE @@ -35,7 +35,7 @@ #import "GCDWebServerPrivate.h" #endif -@implementation GCDWebServerFileRequest { +@implementation ReadiumGCDWebServerFileRequest { int _file; } @@ -54,7 +54,7 @@ - (BOOL)open:(NSError**)error { _file = open([_temporaryPath fileSystemRepresentation], O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (_file <= 0) { if (error) { - *error = GCDWebServerMakePosixError(errno); + *error = ReadiumGCDWebServerMakePosixError(errno); } return NO; } @@ -64,7 +64,7 @@ - (BOOL)open:(NSError**)error { - (BOOL)writeData:(NSData*)data error:(NSError**)error { if (write(_file, data.bytes, data.length) != (ssize_t)data.length) { if (error) { - *error = GCDWebServerMakePosixError(errno); + *error = ReadiumGCDWebServerMakePosixError(errno); } return NO; } @@ -74,21 +74,21 @@ - (BOOL)writeData:(NSData*)data error:(NSError**)error { - (BOOL)close:(NSError**)error { if (close(_file) < 0) { if (error) { - *error = GCDWebServerMakePosixError(errno); + *error = ReadiumGCDWebServerMakePosixError(errno); } return NO; } #ifdef __GCDWEBSERVER_ENABLE_TESTING__ - NSString* creationDateHeader = [self.headers objectForKey:@"X-GCDWebServer-CreationDate"]; + NSString* creationDateHeader = [self.headers objectForKey:@"X-ReadiumGCDWebServer-CreationDate"]; if (creationDateHeader) { - NSDate* date = GCDWebServerParseISO8601(creationDateHeader); + NSDate* date = ReadiumGCDWebServerParseISO8601(creationDateHeader); if (!date || ![[NSFileManager defaultManager] setAttributes:@{NSFileCreationDate : date} ofItemAtPath:_temporaryPath error:error]) { return NO; } } - NSString* modifiedDateHeader = [self.headers objectForKey:@"X-GCDWebServer-ModifiedDate"]; + NSString* modifiedDateHeader = [self.headers objectForKey:@"X-ReadiumGCDWebServer-ModifiedDate"]; if (modifiedDateHeader) { - NSDate* date = GCDWebServerParseRFC822(modifiedDateHeader); + NSDate* date = ReadiumGCDWebServerParseRFC822(modifiedDateHeader); if (!date || ![[NSFileManager defaultManager] setAttributes:@{NSFileModificationDate : date} ofItemAtPath:_temporaryPath error:error]) { return NO; } diff --git a/GCDWebServer/Requests/GCDWebServerMultiPartFormRequest.h b/GCDWebServer/Requests/GCDWebServerMultiPartFormRequest.h index cbe838ea..5ef1149a 100644 --- a/GCDWebServer/Requests/GCDWebServerMultiPartFormRequest.h +++ b/GCDWebServer/Requests/GCDWebServerMultiPartFormRequest.h @@ -30,10 +30,10 @@ NS_ASSUME_NONNULL_BEGIN /** - * The GCDWebServerMultiPart class is an abstract class that wraps the content + * The ReadiumGCDWebServerMultiPart class is an abstract class that wraps the content * of a part. */ -@interface GCDWebServerMultiPart : NSObject +@interface ReadiumGCDWebServerMultiPart : NSObject /** * Returns the control name retrieved from the part headers. @@ -54,10 +54,10 @@ NS_ASSUME_NONNULL_BEGIN @end /** - * The GCDWebServerMultiPartArgument subclass of GCDWebServerMultiPart wraps + * The ReadiumGCDWebServerMultiPartArgument subclass of ReadiumGCDWebServerMultiPart wraps * the content of a part as data in memory. */ -@interface GCDWebServerMultiPartArgument : GCDWebServerMultiPart +@interface ReadiumGCDWebServerMultiPartArgument : ReadiumGCDWebServerMultiPart /** * Returns the data for the part. @@ -76,10 +76,10 @@ NS_ASSUME_NONNULL_BEGIN @end /** - * The GCDWebServerMultiPartFile subclass of GCDWebServerMultiPart wraps + * The ReadiumGCDWebServerMultiPartFile subclass of ReadiumGCDWebServerMultiPart wraps * the content of a part as a file on disk. */ -@interface GCDWebServerMultiPartFile : GCDWebServerMultiPart +@interface ReadiumGCDWebServerMultiPartFile : ReadiumGCDWebServerMultiPart /** * Returns the file name retrieved from the part headers. @@ -90,7 +90,7 @@ NS_ASSUME_NONNULL_BEGIN * Returns the path to the temporary file containing the part data. * * @warning This temporary file will be automatically deleted when the - * GCDWebServerMultiPartFile is deallocated. If you want to preserve this file, + * ReadiumGCDWebServerMultiPartFile is deallocated. If you want to preserve this file, * you must move it to a different location beforehand. */ @property(nonatomic, readonly) NSString* temporaryPath; @@ -98,22 +98,22 @@ NS_ASSUME_NONNULL_BEGIN @end /** - * The GCDWebServerMultiPartFormRequest subclass of GCDWebServerRequest + * The ReadiumGCDWebServerMultiPartFormRequest subclass of ReadiumGCDWebServerRequest * parses the body of the HTTP request as a multipart encoded form. */ -@interface GCDWebServerMultiPartFormRequest : GCDWebServerRequest +@interface ReadiumGCDWebServerMultiPartFormRequest : ReadiumGCDWebServerRequest /** * Returns the argument parts from the multipart encoded form as - * name / GCDWebServerMultiPartArgument pairs. + * name / ReadiumGCDWebServerMultiPartArgument pairs. */ -@property(nonatomic, readonly) NSArray* arguments; +@property(nonatomic, readonly) NSArray* arguments; /** * Returns the files parts from the multipart encoded form as - * name / GCDWebServerMultiPartFile pairs. + * name / ReadiumGCDWebServerMultiPartFile pairs. */ -@property(nonatomic, readonly) NSArray* files; +@property(nonatomic, readonly) NSArray* files; /** * Returns the MIME type for multipart encoded forms @@ -124,12 +124,12 @@ NS_ASSUME_NONNULL_BEGIN /** * Returns the first argument for a given control name or nil if not found. */ -- (nullable GCDWebServerMultiPartArgument*)firstArgumentForControlName:(NSString*)name; +- (nullable ReadiumGCDWebServerMultiPartArgument*)firstArgumentForControlName:(NSString*)name; /** * Returns the first file for a given control name or nil if not found. */ -- (nullable GCDWebServerMultiPartFile*)firstFileForControlName:(NSString*)name; +- (nullable ReadiumGCDWebServerMultiPartFile*)firstFileForControlName:(NSString*)name; @end diff --git a/GCDWebServer/Requests/GCDWebServerMultiPartFormRequest.m b/GCDWebServer/Requests/GCDWebServerMultiPartFormRequest.m index 5c495cd2..73a6ce96 100644 --- a/GCDWebServer/Requests/GCDWebServerMultiPartFormRequest.m +++ b/GCDWebServer/Requests/GCDWebServerMultiPartFormRequest.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebServer requires ARC +#error ReadiumGCDWebServer requires ARC #endif #ifdef SWIFT_PACKAGE @@ -45,35 +45,35 @@ kParserState_End } ParserState; -@interface GCDWebServerMIMEStreamParser : NSObject +@interface ReadiumGCDWebServerMIMEStreamParser : NSObject @end static NSData* _newlineData = nil; static NSData* _newlinesData = nil; static NSData* _dashNewlineData = nil; -@implementation GCDWebServerMultiPart +@implementation ReadiumGCDWebServerMultiPart - (instancetype)initWithControlName:(NSString* _Nonnull)name contentType:(NSString* _Nonnull)type { if ((self = [super init])) { _controlName = [name copy]; _contentType = [type copy]; - _mimeType = (NSString*)GCDWebServerTruncateHeaderValue(_contentType); + _mimeType = (NSString*)ReadiumGCDWebServerTruncateHeaderValue(_contentType); } return self; } @end -@implementation GCDWebServerMultiPartArgument +@implementation ReadiumGCDWebServerMultiPartArgument - (instancetype)initWithControlName:(NSString* _Nonnull)name contentType:(NSString* _Nonnull)type data:(NSData* _Nonnull)data { if ((self = [super initWithControlName:name contentType:type])) { _data = data; if ([self.contentType hasPrefix:@"text/"]) { - NSString* charset = GCDWebServerExtractHeaderValueParameter(self.contentType, @"charset"); - _string = [[NSString alloc] initWithData:_data encoding:GCDWebServerStringEncodingFromCharset(charset)]; + NSString* charset = ReadiumGCDWebServerExtractHeaderValueParameter(self.contentType, @"charset"); + _string = [[NSString alloc] initWithData:_data encoding:ReadiumGCDWebServerStringEncodingFromCharset(charset)]; } } return self; @@ -85,7 +85,7 @@ - (NSString*)description { @end -@implementation GCDWebServerMultiPartFile +@implementation ReadiumGCDWebServerMultiPartFile - (instancetype)initWithControlName:(NSString* _Nonnull)name contentType:(NSString* _Nonnull)type fileName:(NSString* _Nonnull)fileName temporaryPath:(NSString* _Nonnull)temporaryPath { if ((self = [super initWithControlName:name contentType:type])) { @@ -105,20 +105,20 @@ - (NSString*)description { @end -@implementation GCDWebServerMIMEStreamParser { +@implementation ReadiumGCDWebServerMIMEStreamParser { NSData* _boundary; NSString* _defaultcontrolName; ParserState _state; NSMutableData* _data; - NSMutableArray* _arguments; - NSMutableArray* _files; + NSMutableArray* _arguments; + NSMutableArray* _files; NSString* _controlName; NSString* _fileName; NSString* _contentType; NSString* _tmpPath; int _tmpFile; - GCDWebServerMIMEStreamParser* _subParser; + ReadiumGCDWebServerMIMEStreamParser* _subParser; } + (void)initialize { @@ -136,7 +136,7 @@ + (void)initialize { } } -- (instancetype)initWithBoundary:(NSString* _Nonnull)boundary defaultControlName:(NSString* _Nullable)name arguments:(NSMutableArray* _Nonnull)arguments files:(NSMutableArray* _Nonnull)files { +- (instancetype)initWithBoundary:(NSString* _Nonnull)boundary defaultControlName:(NSString* _Nullable)name arguments:(NSMutableArray* _Nonnull)arguments files:(NSMutableArray* _Nonnull)files { NSData* data = boundary.length ? [[NSString stringWithFormat:@"--%@", boundary] dataUsingEncoding:NSASCIIStringEncoding] : nil; if (data == nil) { GWS_DNOT_REACHED(); @@ -180,15 +180,15 @@ - (BOOL)_parseData { NSString* name = [header substringToIndex:subRange.location]; NSString* value = [[header substringFromIndex:(subRange.location + subRange.length)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; if ([name caseInsensitiveCompare:@"Content-Type"] == NSOrderedSame) { - _contentType = GCDWebServerNormalizeHeaderValue(value); + _contentType = ReadiumGCDWebServerNormalizeHeaderValue(value); } else if ([name caseInsensitiveCompare:@"Content-Disposition"] == NSOrderedSame) { - NSString* contentDisposition = GCDWebServerNormalizeHeaderValue(value); - if ([GCDWebServerTruncateHeaderValue(contentDisposition) isEqualToString:@"form-data"]) { - _controlName = GCDWebServerExtractHeaderValueParameter(contentDisposition, @"name"); - _fileName = GCDWebServerExtractHeaderValueParameter(contentDisposition, @"filename"); - } else if ([GCDWebServerTruncateHeaderValue(contentDisposition) isEqualToString:@"file"]) { + NSString* contentDisposition = ReadiumGCDWebServerNormalizeHeaderValue(value); + if ([ReadiumGCDWebServerTruncateHeaderValue(contentDisposition) isEqualToString:@"form-data"]) { + _controlName = ReadiumGCDWebServerExtractHeaderValueParameter(contentDisposition, @"name"); + _fileName = ReadiumGCDWebServerExtractHeaderValueParameter(contentDisposition, @"filename"); + } else if ([ReadiumGCDWebServerTruncateHeaderValue(contentDisposition) isEqualToString:@"file"]) { _controlName = _defaultcontrolName; - _fileName = GCDWebServerExtractHeaderValueParameter(contentDisposition, @"filename"); + _fileName = ReadiumGCDWebServerExtractHeaderValueParameter(contentDisposition, @"filename"); } } } else { @@ -203,9 +203,9 @@ - (BOOL)_parseData { GWS_DNOT_REACHED(); } if (_controlName) { - if ([GCDWebServerTruncateHeaderValue(_contentType) isEqualToString:@"multipart/mixed"]) { - NSString* boundary = GCDWebServerExtractHeaderValueParameter(_contentType, @"boundary"); - _subParser = [[GCDWebServerMIMEStreamParser alloc] initWithBoundary:boundary defaultControlName:_controlName arguments:_arguments files:_files]; + if ([ReadiumGCDWebServerTruncateHeaderValue(_contentType) isEqualToString:@"multipart/mixed"]) { + NSString* boundary = ReadiumGCDWebServerExtractHeaderValueParameter(_contentType, @"boundary"); + _subParser = [[ReadiumGCDWebServerMIMEStreamParser alloc] initWithBoundary:boundary defaultControlName:_controlName arguments:_arguments files:_files]; if (_subParser == nil) { GWS_DNOT_REACHED(); success = NO; @@ -251,7 +251,7 @@ - (BOOL)_parseData { if (result == (ssize_t)dataLength) { if (close(_tmpFile) == 0) { _tmpFile = 0; - GCDWebServerMultiPartFile* file = [[GCDWebServerMultiPartFile alloc] initWithControlName:_controlName contentType:_contentType fileName:_fileName temporaryPath:_tmpPath]; + ReadiumGCDWebServerMultiPartFile* file = [[ReadiumGCDWebServerMultiPartFile alloc] initWithControlName:_controlName contentType:_contentType fileName:_fileName temporaryPath:_tmpPath]; [_files addObject:file]; } else { GWS_DNOT_REACHED(); @@ -264,7 +264,7 @@ - (BOOL)_parseData { _tmpPath = nil; } else { NSData* data = [[NSData alloc] initWithBytes:(void*)dataBytes length:dataLength]; - GCDWebServerMultiPartArgument* argument = [[GCDWebServerMultiPartArgument alloc] initWithControlName:_controlName contentType:_contentType data:data]; + ReadiumGCDWebServerMultiPartArgument* argument = [[ReadiumGCDWebServerMultiPartArgument alloc] initWithControlName:_controlName contentType:_contentType data:data]; [_arguments addObject:argument]; } } @@ -315,13 +315,13 @@ - (BOOL)isAtEnd { @end -@interface GCDWebServerMultiPartFormRequest () -@property(nonatomic) NSMutableArray* arguments; -@property(nonatomic) NSMutableArray* files; +@interface ReadiumGCDWebServerMultiPartFormRequest () +@property(nonatomic) NSMutableArray* arguments; +@property(nonatomic) NSMutableArray* files; @end -@implementation GCDWebServerMultiPartFormRequest { - GCDWebServerMIMEStreamParser* _parser; +@implementation ReadiumGCDWebServerMultiPartFormRequest { + ReadiumGCDWebServerMIMEStreamParser* _parser; } + (NSString*)mimeType { @@ -337,8 +337,8 @@ - (instancetype)initWithMethod:(NSString*)method url:(NSURL*)url headers:(NSDict } - (BOOL)open:(NSError**)error { - NSString* boundary = GCDWebServerExtractHeaderValueParameter(self.contentType, @"boundary"); - _parser = [[GCDWebServerMIMEStreamParser alloc] initWithBoundary:boundary defaultControlName:nil arguments:_arguments files:_files]; + NSString* boundary = ReadiumGCDWebServerExtractHeaderValueParameter(self.contentType, @"boundary"); + _parser = [[ReadiumGCDWebServerMIMEStreamParser alloc] initWithBoundary:boundary defaultControlName:nil arguments:_arguments files:_files]; if (_parser == nil) { if (error) { *error = [NSError errorWithDomain:kGCDWebServerErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Failed starting to parse multipart form data"}]; @@ -370,8 +370,8 @@ - (BOOL)close:(NSError**)error { return YES; } -- (GCDWebServerMultiPartArgument*)firstArgumentForControlName:(NSString*)name { - for (GCDWebServerMultiPartArgument* argument in _arguments) { +- (ReadiumGCDWebServerMultiPartArgument*)firstArgumentForControlName:(NSString*)name { + for (ReadiumGCDWebServerMultiPartArgument* argument in _arguments) { if ([argument.controlName isEqualToString:name]) { return argument; } @@ -379,8 +379,8 @@ - (GCDWebServerMultiPartArgument*)firstArgumentForControlName:(NSString*)name { return nil; } -- (GCDWebServerMultiPartFile*)firstFileForControlName:(NSString*)name { - for (GCDWebServerMultiPartFile* file in _files) { +- (ReadiumGCDWebServerMultiPartFile*)firstFileForControlName:(NSString*)name { + for (ReadiumGCDWebServerMultiPartFile* file in _files) { if ([file.controlName isEqualToString:name]) { return file; } @@ -392,14 +392,14 @@ - (NSString*)description { NSMutableString* description = [NSMutableString stringWithString:[super description]]; if (_arguments.count) { [description appendString:@"\n"]; - for (GCDWebServerMultiPartArgument* argument in _arguments) { + for (ReadiumGCDWebServerMultiPartArgument* argument in _arguments) { [description appendFormat:@"\n%@ (%@)\n", argument.controlName, argument.contentType]; - [description appendString:GCDWebServerDescribeData(argument.data, argument.contentType)]; + [description appendString:ReadiumGCDWebServerDescribeData(argument.data, argument.contentType)]; } } if (_files.count) { [description appendString:@"\n"]; - for (GCDWebServerMultiPartFile* file in _files) { + for (ReadiumGCDWebServerMultiPartFile* file in _files) { [description appendFormat:@"\n%@ (%@): %@\n{%@}", file.controlName, file.contentType, file.fileName, file.temporaryPath]; } } diff --git a/GCDWebServer/Requests/GCDWebServerURLEncodedFormRequest.h b/GCDWebServer/Requests/GCDWebServerURLEncodedFormRequest.h index c0168b76..d94d8a35 100644 --- a/GCDWebServer/Requests/GCDWebServerURLEncodedFormRequest.h +++ b/GCDWebServer/Requests/GCDWebServerURLEncodedFormRequest.h @@ -30,11 +30,11 @@ NS_ASSUME_NONNULL_BEGIN /** - * The GCDWebServerURLEncodedFormRequest subclass of GCDWebServerRequest + * The ReadiumGCDWebServerURLEncodedFormRequest subclass of ReadiumGCDWebServerRequest * parses the body of the HTTP request as a URL encoded form using - * GCDWebServerParseURLEncodedForm(). + * ReadiumGCDWebServerParseURLEncodedForm(). */ -@interface GCDWebServerURLEncodedFormRequest : GCDWebServerDataRequest +@interface ReadiumGCDWebServerURLEncodedFormRequest : ReadiumGCDWebServerDataRequest /** * Returns the unescaped control names and values for the URL encoded form. diff --git a/GCDWebServer/Requests/GCDWebServerURLEncodedFormRequest.m b/GCDWebServer/Requests/GCDWebServerURLEncodedFormRequest.m index a9745bf9..7ff5d08d 100644 --- a/GCDWebServer/Requests/GCDWebServerURLEncodedFormRequest.m +++ b/GCDWebServer/Requests/GCDWebServerURLEncodedFormRequest.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebServer requires ARC +#error ReadiumGCDWebServer requires ARC #endif #ifdef SWIFT_PACKAGE @@ -35,7 +35,7 @@ #import "GCDWebServerPrivate.h" #endif -@implementation GCDWebServerURLEncodedFormRequest +@implementation ReadiumGCDWebServerURLEncodedFormRequest + (NSString*)mimeType { return @"application/x-www-form-urlencoded"; @@ -46,9 +46,9 @@ - (BOOL)close:(NSError**)error { return NO; } - NSString* charset = GCDWebServerExtractHeaderValueParameter(self.contentType, @"charset"); - NSString* string = [[NSString alloc] initWithData:self.data encoding:GCDWebServerStringEncodingFromCharset(charset)]; - _arguments = GCDWebServerParseURLEncodedForm(string); + NSString* charset = ReadiumGCDWebServerExtractHeaderValueParameter(self.contentType, @"charset"); + NSString* string = [[NSString alloc] initWithData:self.data encoding:ReadiumGCDWebServerStringEncodingFromCharset(charset)]; + _arguments = ReadiumGCDWebServerParseURLEncodedForm(string); return YES; } diff --git a/GCDWebServer/Responses/GCDWebServerDataResponse.h b/GCDWebServer/Responses/GCDWebServerDataResponse.h index e5121c33..e1c94843 100644 --- a/GCDWebServer/Responses/GCDWebServerDataResponse.h +++ b/GCDWebServer/Responses/GCDWebServerDataResponse.h @@ -30,10 +30,10 @@ NS_ASSUME_NONNULL_BEGIN /** - * The GCDWebServerDataResponse subclass of GCDWebServerResponse reads the body + * The ReadiumGCDWebServerDataResponse subclass of ReadiumGCDWebServerResponse reads the body * of the HTTP response from memory. */ -@interface GCDWebServerDataResponse : GCDWebServerResponse +@interface ReadiumGCDWebServerDataResponse : ReadiumGCDWebServerResponse @property(nonatomic, copy) NSString* contentType; // Redeclare as non-null /** @@ -48,7 +48,7 @@ NS_ASSUME_NONNULL_BEGIN @end -@interface GCDWebServerDataResponse (Extensions) +@interface ReadiumGCDWebServerDataResponse (Extensions) /** * Creates a data response from text encoded using UTF-8. diff --git a/GCDWebServer/Responses/GCDWebServerDataResponse.m b/GCDWebServer/Responses/GCDWebServerDataResponse.m index ea977cd0..98cdbe63 100644 --- a/GCDWebServer/Responses/GCDWebServerDataResponse.m +++ b/GCDWebServer/Responses/GCDWebServerDataResponse.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebServer requires ARC +#error ReadiumGCDWebServer requires ARC #endif #ifdef SWIFT_PACKAGE @@ -35,7 +35,7 @@ #import "GCDWebServerPrivate.h" #endif -@implementation GCDWebServerDataResponse { +@implementation ReadiumGCDWebServerDataResponse { NSData* _data; BOOL _done; } @@ -43,7 +43,7 @@ @implementation GCDWebServerDataResponse { @dynamic contentType; + (instancetype)responseWithData:(NSData*)data contentType:(NSString*)type { - return [(GCDWebServerDataResponse*)[[self class] alloc] initWithData:data contentType:type]; + return [(ReadiumGCDWebServerDataResponse*)[[self class] alloc] initWithData:data contentType:type]; } - (instancetype)initWithData:(NSData*)data contentType:(NSString*)type { @@ -70,32 +70,32 @@ - (NSData*)readData:(NSError**)error { - (NSString*)description { NSMutableString* description = [NSMutableString stringWithString:[super description]]; [description appendString:@"\n\n"]; - [description appendString:GCDWebServerDescribeData(_data, self.contentType)]; + [description appendString:ReadiumGCDWebServerDescribeData(_data, self.contentType)]; return description; } @end -@implementation GCDWebServerDataResponse (Extensions) +@implementation ReadiumGCDWebServerDataResponse (Extensions) + (instancetype)responseWithText:(NSString*)text { - return [(GCDWebServerDataResponse*)[self alloc] initWithText:text]; + return [(ReadiumGCDWebServerDataResponse*)[self alloc] initWithText:text]; } + (instancetype)responseWithHTML:(NSString*)html { - return [(GCDWebServerDataResponse*)[self alloc] initWithHTML:html]; + return [(ReadiumGCDWebServerDataResponse*)[self alloc] initWithHTML:html]; } + (instancetype)responseWithHTMLTemplate:(NSString*)path variables:(NSDictionary*)variables { - return [(GCDWebServerDataResponse*)[self alloc] initWithHTMLTemplate:path variables:variables]; + return [(ReadiumGCDWebServerDataResponse*)[self alloc] initWithHTMLTemplate:path variables:variables]; } + (instancetype)responseWithJSONObject:(id)object { - return [(GCDWebServerDataResponse*)[self alloc] initWithJSONObject:object]; + return [(ReadiumGCDWebServerDataResponse*)[self alloc] initWithJSONObject:object]; } + (instancetype)responseWithJSONObject:(id)object contentType:(NSString*)type { - return [(GCDWebServerDataResponse*)[self alloc] initWithJSONObject:object contentType:type]; + return [(ReadiumGCDWebServerDataResponse*)[self alloc] initWithJSONObject:object contentType:type]; } - (instancetype)initWithText:(NSString*)text { diff --git a/GCDWebServer/Responses/GCDWebServerErrorResponse.h b/GCDWebServer/Responses/GCDWebServerErrorResponse.h index e427c071..ebb20191 100644 --- a/GCDWebServer/Responses/GCDWebServerErrorResponse.h +++ b/GCDWebServer/Responses/GCDWebServerErrorResponse.h @@ -31,32 +31,32 @@ NS_ASSUME_NONNULL_BEGIN /** - * The GCDWebServerDataResponse subclass of GCDWebServerDataResponse generates + * The ReadiumGCDWebServerDataResponse subclass of ReadiumGCDWebServerDataResponse generates * an HTML body from an HTTP status code and an error message. */ -@interface GCDWebServerErrorResponse : GCDWebServerDataResponse +@interface ReadiumGCDWebServerErrorResponse : ReadiumGCDWebServerDataResponse /** * Creates a client error response with the corresponding HTTP status code. */ -+ (instancetype)responseWithClientError:(GCDWebServerClientErrorHTTPStatusCode)errorCode message:(NSString*)format, ... NS_FORMAT_FUNCTION(2, 3); ++ (instancetype)responseWithClientError:(ReadiumGCDWebServerClientErrorHTTPStatusCode)errorCode message:(NSString*)format, ... NS_FORMAT_FUNCTION(2, 3); /** * Creates a server error response with the corresponding HTTP status code. */ -+ (instancetype)responseWithServerError:(GCDWebServerServerErrorHTTPStatusCode)errorCode message:(NSString*)format, ... NS_FORMAT_FUNCTION(2, 3); ++ (instancetype)responseWithServerError:(ReadiumGCDWebServerServerErrorHTTPStatusCode)errorCode message:(NSString*)format, ... NS_FORMAT_FUNCTION(2, 3); /** * Creates a client error response with the corresponding HTTP status code * and an underlying NSError. */ -+ (instancetype)responseWithClientError:(GCDWebServerClientErrorHTTPStatusCode)errorCode underlyingError:(nullable NSError*)underlyingError message:(NSString*)format, ... NS_FORMAT_FUNCTION(3, 4); ++ (instancetype)responseWithClientError:(ReadiumGCDWebServerClientErrorHTTPStatusCode)errorCode underlyingError:(nullable NSError*)underlyingError message:(NSString*)format, ... NS_FORMAT_FUNCTION(3, 4); /** * Creates a server error response with the corresponding HTTP status code * and an underlying NSError. */ -+ (instancetype)responseWithServerError:(GCDWebServerServerErrorHTTPStatusCode)errorCode underlyingError:(nullable NSError*)underlyingError message:(NSString*)format, ... NS_FORMAT_FUNCTION(3, 4); ++ (instancetype)responseWithServerError:(ReadiumGCDWebServerServerErrorHTTPStatusCode)errorCode underlyingError:(nullable NSError*)underlyingError message:(NSString*)format, ... NS_FORMAT_FUNCTION(3, 4); /** * Initializes an empty response with a specific HTTP status code and error. @@ -66,24 +66,24 @@ NS_ASSUME_NONNULL_BEGIN /** * Initializes a client error response with the corresponding HTTP status code. */ -- (instancetype)initWithClientError:(GCDWebServerClientErrorHTTPStatusCode)errorCode message:(NSString*)format, ... NS_FORMAT_FUNCTION(2, 3); +- (instancetype)initWithClientError:(ReadiumGCDWebServerClientErrorHTTPStatusCode)errorCode message:(NSString*)format, ... NS_FORMAT_FUNCTION(2, 3); /** * Initializes a server error response with the corresponding HTTP status code. */ -- (instancetype)initWithServerError:(GCDWebServerServerErrorHTTPStatusCode)errorCode message:(NSString*)format, ... NS_FORMAT_FUNCTION(2, 3); +- (instancetype)initWithServerError:(ReadiumGCDWebServerServerErrorHTTPStatusCode)errorCode message:(NSString*)format, ... NS_FORMAT_FUNCTION(2, 3); /** * Initializes a client error response with the corresponding HTTP status code * and an underlying NSError. */ -- (instancetype)initWithClientError:(GCDWebServerClientErrorHTTPStatusCode)errorCode underlyingError:(nullable NSError*)underlyingError message:(NSString*)format, ... NS_FORMAT_FUNCTION(3, 4); +- (instancetype)initWithClientError:(ReadiumGCDWebServerClientErrorHTTPStatusCode)errorCode underlyingError:(nullable NSError*)underlyingError message:(NSString*)format, ... NS_FORMAT_FUNCTION(3, 4); /** * Initializes a server error response with the corresponding HTTP status code * and an underlying NSError. */ -- (instancetype)initWithServerError:(GCDWebServerServerErrorHTTPStatusCode)errorCode underlyingError:(nullable NSError*)underlyingError message:(NSString*)format, ... NS_FORMAT_FUNCTION(3, 4); +- (instancetype)initWithServerError:(ReadiumGCDWebServerServerErrorHTTPStatusCode)errorCode underlyingError:(nullable NSError*)underlyingError message:(NSString*)format, ... NS_FORMAT_FUNCTION(3, 4); @end diff --git a/GCDWebServer/Responses/GCDWebServerErrorResponse.m b/GCDWebServer/Responses/GCDWebServerErrorResponse.m index 3b5d71a8..dedcf468 100644 --- a/GCDWebServer/Responses/GCDWebServerErrorResponse.m +++ b/GCDWebServer/Responses/GCDWebServerErrorResponse.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebServer requires ARC +#error ReadiumGCDWebServer requires ARC #endif #ifdef SWIFT_PACKAGE @@ -35,42 +35,42 @@ #import "GCDWebServerPrivate.h" #endif -@implementation GCDWebServerErrorResponse { +@implementation ReadiumGCDWebServerErrorResponse { NSError *_error; } -+ (instancetype)responseWithClientError:(GCDWebServerClientErrorHTTPStatusCode)errorCode message:(NSString*)format, ... { ++ (instancetype)responseWithClientError:(ReadiumGCDWebServerClientErrorHTTPStatusCode)errorCode message:(NSString*)format, ... { GWS_DCHECK(((NSInteger)errorCode >= 400) && ((NSInteger)errorCode < 500)); va_list arguments; va_start(arguments, format); - GCDWebServerErrorResponse* response = [(GCDWebServerErrorResponse*)[self alloc] initWithStatusCode:errorCode underlyingError:nil messageFormat:format arguments:arguments]; + ReadiumGCDWebServerErrorResponse* response = [(ReadiumGCDWebServerErrorResponse*)[self alloc] initWithStatusCode:errorCode underlyingError:nil messageFormat:format arguments:arguments]; va_end(arguments); return response; } -+ (instancetype)responseWithServerError:(GCDWebServerServerErrorHTTPStatusCode)errorCode message:(NSString*)format, ... { ++ (instancetype)responseWithServerError:(ReadiumGCDWebServerServerErrorHTTPStatusCode)errorCode message:(NSString*)format, ... { GWS_DCHECK(((NSInteger)errorCode >= 500) && ((NSInteger)errorCode < 600)); va_list arguments; va_start(arguments, format); - GCDWebServerErrorResponse* response = [(GCDWebServerErrorResponse*)[self alloc] initWithStatusCode:errorCode underlyingError:nil messageFormat:format arguments:arguments]; + ReadiumGCDWebServerErrorResponse* response = [(ReadiumGCDWebServerErrorResponse*)[self alloc] initWithStatusCode:errorCode underlyingError:nil messageFormat:format arguments:arguments]; va_end(arguments); return response; } -+ (instancetype)responseWithClientError:(GCDWebServerClientErrorHTTPStatusCode)errorCode underlyingError:(NSError*)underlyingError message:(NSString*)format, ... { ++ (instancetype)responseWithClientError:(ReadiumGCDWebServerClientErrorHTTPStatusCode)errorCode underlyingError:(NSError*)underlyingError message:(NSString*)format, ... { GWS_DCHECK(((NSInteger)errorCode >= 400) && ((NSInteger)errorCode < 500)); va_list arguments; va_start(arguments, format); - GCDWebServerErrorResponse* response = [(GCDWebServerErrorResponse*)[self alloc] initWithStatusCode:errorCode underlyingError:underlyingError messageFormat:format arguments:arguments]; + ReadiumGCDWebServerErrorResponse* response = [(ReadiumGCDWebServerErrorResponse*)[self alloc] initWithStatusCode:errorCode underlyingError:underlyingError messageFormat:format arguments:arguments]; va_end(arguments); return response; } -+ (instancetype)responseWithServerError:(GCDWebServerServerErrorHTTPStatusCode)errorCode underlyingError:(NSError*)underlyingError message:(NSString*)format, ... { ++ (instancetype)responseWithServerError:(ReadiumGCDWebServerServerErrorHTTPStatusCode)errorCode underlyingError:(NSError*)underlyingError message:(NSString*)format, ... { GWS_DCHECK(((NSInteger)errorCode >= 500) && ((NSInteger)errorCode < 600)); va_list arguments; va_start(arguments, format); - GCDWebServerErrorResponse* response = [(GCDWebServerErrorResponse*)[self alloc] initWithStatusCode:errorCode underlyingError:underlyingError messageFormat:format arguments:arguments]; + ReadiumGCDWebServerErrorResponse* response = [(ReadiumGCDWebServerErrorResponse*)[self alloc] initWithStatusCode:errorCode underlyingError:underlyingError messageFormat:format arguments:arguments]; va_end(arguments); return response; } @@ -98,7 +98,7 @@ - (instancetype)initWithStatusCode:(NSInteger)statusCode error:(NSError*)error { return self; } -- (instancetype)initWithClientError:(GCDWebServerClientErrorHTTPStatusCode)errorCode message:(NSString*)format, ... { +- (instancetype)initWithClientError:(ReadiumGCDWebServerClientErrorHTTPStatusCode)errorCode message:(NSString*)format, ... { GWS_DCHECK(((NSInteger)errorCode >= 400) && ((NSInteger)errorCode < 500)); va_list arguments; va_start(arguments, format); @@ -107,7 +107,7 @@ - (instancetype)initWithClientError:(GCDWebServerClientErrorHTTPStatusCode)error return self; } -- (instancetype)initWithServerError:(GCDWebServerServerErrorHTTPStatusCode)errorCode message:(NSString*)format, ... { +- (instancetype)initWithServerError:(ReadiumGCDWebServerServerErrorHTTPStatusCode)errorCode message:(NSString*)format, ... { GWS_DCHECK(((NSInteger)errorCode >= 500) && ((NSInteger)errorCode < 600)); va_list arguments; va_start(arguments, format); @@ -116,7 +116,7 @@ - (instancetype)initWithServerError:(GCDWebServerServerErrorHTTPStatusCode)error return self; } -- (instancetype)initWithClientError:(GCDWebServerClientErrorHTTPStatusCode)errorCode underlyingError:(NSError*)underlyingError message:(NSString*)format, ... { +- (instancetype)initWithClientError:(ReadiumGCDWebServerClientErrorHTTPStatusCode)errorCode underlyingError:(NSError*)underlyingError message:(NSString*)format, ... { GWS_DCHECK(((NSInteger)errorCode >= 400) && ((NSInteger)errorCode < 500)); va_list arguments; va_start(arguments, format); @@ -125,7 +125,7 @@ - (instancetype)initWithClientError:(GCDWebServerClientErrorHTTPStatusCode)error return self; } -- (instancetype)initWithServerError:(GCDWebServerServerErrorHTTPStatusCode)errorCode underlyingError:(NSError*)underlyingError message:(NSString*)format, ... { +- (instancetype)initWithServerError:(ReadiumGCDWebServerServerErrorHTTPStatusCode)errorCode underlyingError:(NSError*)underlyingError message:(NSString*)format, ... { GWS_DCHECK(((NSInteger)errorCode >= 500) && ((NSInteger)errorCode < 600)); va_list arguments; va_start(arguments, format); diff --git a/GCDWebServer/Responses/GCDWebServerFileResponse.h b/GCDWebServer/Responses/GCDWebServerFileResponse.h index 78931bc6..f16d2475 100644 --- a/GCDWebServer/Responses/GCDWebServerFileResponse.h +++ b/GCDWebServer/Responses/GCDWebServerFileResponse.h @@ -30,14 +30,14 @@ NS_ASSUME_NONNULL_BEGIN /** - * The GCDWebServerFileResponse subclass of GCDWebServerResponse reads the body + * The ReadiumGCDWebServerFileResponse subclass of ReadiumGCDWebServerResponse reads the body * of the HTTP response from a file on disk. * * It will automatically set the contentType, lastModifiedDate and eTag - * properties of the GCDWebServerResponse according to the file extension and + * properties of the ReadiumGCDWebServerResponse according to the file extension and * metadata. */ -@interface GCDWebServerFileResponse : GCDWebServerResponse +@interface ReadiumGCDWebServerFileResponse : ReadiumGCDWebServerResponse @property(nonatomic, copy) NSString* contentType; // Redeclare as non-null @property(nonatomic) NSDate* lastModifiedDate; // Redeclare as non-null @property(nonatomic, copy) NSString* eTag; // Redeclare as non-null @@ -89,7 +89,7 @@ NS_ASSUME_NONNULL_BEGIN * actual size of the file. * * This argument would typically be set to the value of the byteRange property - * of the current GCDWebServerRequest. + * of the current ReadiumGCDWebServerRequest. */ - (nullable instancetype)initWithFile:(NSString*)path byteRange:(NSRange)range; diff --git a/GCDWebServer/Responses/GCDWebServerFileResponse.m b/GCDWebServer/Responses/GCDWebServerFileResponse.m index e9b6a062..9aebe116 100644 --- a/GCDWebServer/Responses/GCDWebServerFileResponse.m +++ b/GCDWebServer/Responses/GCDWebServerFileResponse.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebServer requires ARC +#error ReadiumGCDWebServer requires ARC #endif #import @@ -39,7 +39,7 @@ #define kFileReadBufferSize (32 * 1024) -@implementation GCDWebServerFileResponse { +@implementation ReadiumGCDWebServerFileResponse { NSString* _path; NSUInteger _offset; NSUInteger _size; @@ -49,19 +49,19 @@ @implementation GCDWebServerFileResponse { @dynamic contentType, lastModifiedDate, eTag; + (instancetype)responseWithFile:(NSString*)path { - return [(GCDWebServerFileResponse*)[[self class] alloc] initWithFile:path]; + return [(ReadiumGCDWebServerFileResponse*)[[self class] alloc] initWithFile:path]; } + (instancetype)responseWithFile:(NSString*)path isAttachment:(BOOL)attachment { - return [(GCDWebServerFileResponse*)[[self class] alloc] initWithFile:path isAttachment:attachment]; + return [(ReadiumGCDWebServerFileResponse*)[[self class] alloc] initWithFile:path isAttachment:attachment]; } + (instancetype)responseWithFile:(NSString*)path byteRange:(NSRange)range { - return [(GCDWebServerFileResponse*)[[self class] alloc] initWithFile:path byteRange:range]; + return [(ReadiumGCDWebServerFileResponse*)[[self class] alloc] initWithFile:path byteRange:range]; } + (instancetype)responseWithFile:(NSString*)path byteRange:(NSRange)range isAttachment:(BOOL)attachment { - return [(GCDWebServerFileResponse*)[[self class] alloc] initWithFile:path byteRange:range isAttachment:attachment mimeTypeOverrides:nil]; + return [(ReadiumGCDWebServerFileResponse*)[[self class] alloc] initWithFile:path byteRange:range isAttachment:attachment mimeTypeOverrides:nil]; } - (instancetype)initWithFile:(NSString*)path { @@ -94,7 +94,7 @@ - (instancetype)initWithFile:(NSString*)path byteRange:(NSRange)range isAttachme #endif NSUInteger fileSize = (NSUInteger)info.st_size; - BOOL hasByteRange = GCDWebServerIsValidByteRange(range); + BOOL hasByteRange = ReadiumGCDWebServerIsValidByteRange(range); if (hasByteRange) { if (range.location != NSUIntegerMax) { range.location = MIN(range.location, fileSize); @@ -126,14 +126,14 @@ - (instancetype)initWithFile:(NSString*)path byteRange:(NSRange)range isAttachme 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)]; + NSString* value = [NSString stringWithFormat:@"attachment; filename=\"%@\"; filename*=UTF-8''%@", lossyFileName, ReadiumGCDWebServerEscapeURLString(fileName)]; [self setValue:value forAdditionalHeader:@"Content-Disposition"]; } else { GWS_DNOT_REACHED(); } } - self.contentType = GCDWebServerGetMimeTypeForExtension([_path pathExtension], overrides); + self.contentType = ReadiumGCDWebServerGetMimeTypeForExtension([_path pathExtension], overrides); self.contentLength = _size; self.lastModifiedDate = _NSDateFromTimeSpec(&info.st_mtimespec); self.eTag = [NSString stringWithFormat:@"%llu/%li/%li", info.st_ino, info.st_mtimespec.tv_sec, info.st_mtimespec.tv_nsec]; @@ -145,13 +145,13 @@ - (BOOL)open:(NSError**)error { _file = open([_path fileSystemRepresentation], O_NOFOLLOW | O_RDONLY); if (_file <= 0) { if (error) { - *error = GCDWebServerMakePosixError(errno); + *error = ReadiumGCDWebServerMakePosixError(errno); } return NO; } if (lseek(_file, _offset, SEEK_SET) != (off_t)_offset) { if (error) { - *error = GCDWebServerMakePosixError(errno); + *error = ReadiumGCDWebServerMakePosixError(errno); } close(_file); return NO; @@ -165,7 +165,7 @@ - (NSData*)readData:(NSError**)error { ssize_t result = read(_file, data.mutableBytes, length); if (result < 0) { if (error) { - *error = GCDWebServerMakePosixError(errno); + *error = ReadiumGCDWebServerMakePosixError(errno); } return nil; } diff --git a/GCDWebServer/Responses/GCDWebServerStreamedResponse.h b/GCDWebServer/Responses/GCDWebServerStreamedResponse.h index 211f6303..7321497e 100644 --- a/GCDWebServer/Responses/GCDWebServerStreamedResponse.h +++ b/GCDWebServer/Responses/GCDWebServerStreamedResponse.h @@ -30,14 +30,14 @@ NS_ASSUME_NONNULL_BEGIN /** - * The GCDWebServerStreamBlock is called to stream the data for the HTTP body. + * The ReadiumGCDWebServerStreamBlock is called to stream the data for the HTTP body. * The block must return either a chunk of data, an empty NSData when done, or * nil on error and set the "error" argument which is guaranteed to be non-NULL. */ -typedef NSData* _Nullable (^GCDWebServerStreamBlock)(NSError** error); +typedef NSData* _Nullable (^ReadiumGCDWebServerStreamBlock)(NSError** error); /** - * The GCDWebServerAsyncStreamBlock works like the GCDWebServerStreamBlock + * The ReadiumGCDWebServerAsyncStreamBlock works like the ReadiumGCDWebServerStreamBlock * except the streamed data can be returned at a later time allowing for * truly asynchronous generation of the data. * @@ -46,34 +46,34 @@ typedef NSData* _Nullable (^GCDWebServerStreamBlock)(NSError** error); * * The block cannot call "completionBlock" more than once per invocation. */ -typedef void (^GCDWebServerAsyncStreamBlock)(GCDWebServerBodyReaderCompletionBlock completionBlock); +typedef void (^ReadiumGCDWebServerAsyncStreamBlock)(ReadiumGCDWebServerBodyReaderCompletionBlock completionBlock); /** - * The GCDWebServerStreamedResponse subclass of GCDWebServerResponse streams + * The ReadiumGCDWebServerStreamedResponse subclass of ReadiumGCDWebServerResponse streams * the body of the HTTP response using a GCD block. */ -@interface GCDWebServerStreamedResponse : GCDWebServerResponse +@interface ReadiumGCDWebServerStreamedResponse : ReadiumGCDWebServerResponse @property(nonatomic, copy) NSString* contentType; // Redeclare as non-null /** * Creates a response with streamed data and a given content type. */ -+ (instancetype)responseWithContentType:(NSString*)type streamBlock:(GCDWebServerStreamBlock)block; ++ (instancetype)responseWithContentType:(NSString*)type streamBlock:(ReadiumGCDWebServerStreamBlock)block; /** * Creates a response with async streamed data and a given content type. */ -+ (instancetype)responseWithContentType:(NSString*)type asyncStreamBlock:(GCDWebServerAsyncStreamBlock)block; ++ (instancetype)responseWithContentType:(NSString*)type asyncStreamBlock:(ReadiumGCDWebServerAsyncStreamBlock)block; /** * Initializes a response with streamed data and a given content type. */ -- (instancetype)initWithContentType:(NSString*)type streamBlock:(GCDWebServerStreamBlock)block; +- (instancetype)initWithContentType:(NSString*)type streamBlock:(ReadiumGCDWebServerStreamBlock)block; /** * This method is the designated initializer for the class. */ -- (instancetype)initWithContentType:(NSString*)type asyncStreamBlock:(GCDWebServerAsyncStreamBlock)block; +- (instancetype)initWithContentType:(NSString*)type asyncStreamBlock:(ReadiumGCDWebServerAsyncStreamBlock)block; @end diff --git a/GCDWebServer/Responses/GCDWebServerStreamedResponse.m b/GCDWebServer/Responses/GCDWebServerStreamedResponse.m index 63264628..c7c39190 100644 --- a/GCDWebServer/Responses/GCDWebServerStreamedResponse.m +++ b/GCDWebServer/Responses/GCDWebServerStreamedResponse.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebServer requires ARC +#error ReadiumGCDWebServer requires ARC #endif #ifdef SWIFT_PACKAGE @@ -35,30 +35,30 @@ #import "GCDWebServerPrivate.h" #endif -@implementation GCDWebServerStreamedResponse { - GCDWebServerAsyncStreamBlock _block; +@implementation ReadiumGCDWebServerStreamedResponse { + ReadiumGCDWebServerAsyncStreamBlock _block; } @dynamic contentType; -+ (instancetype)responseWithContentType:(NSString*)type streamBlock:(GCDWebServerStreamBlock)block { - return [(GCDWebServerStreamedResponse*)[[self class] alloc] initWithContentType:type streamBlock:block]; ++ (instancetype)responseWithContentType:(NSString*)type streamBlock:(ReadiumGCDWebServerStreamBlock)block { + return [(ReadiumGCDWebServerStreamedResponse*)[[self class] alloc] initWithContentType:type streamBlock:block]; } -+ (instancetype)responseWithContentType:(NSString*)type asyncStreamBlock:(GCDWebServerAsyncStreamBlock)block { - return [(GCDWebServerStreamedResponse*)[[self class] alloc] initWithContentType:type asyncStreamBlock:block]; ++ (instancetype)responseWithContentType:(NSString*)type asyncStreamBlock:(ReadiumGCDWebServerAsyncStreamBlock)block { + return [(ReadiumGCDWebServerStreamedResponse*)[[self class] alloc] initWithContentType:type asyncStreamBlock:block]; } -- (instancetype)initWithContentType:(NSString*)type streamBlock:(GCDWebServerStreamBlock)block { +- (instancetype)initWithContentType:(NSString*)type streamBlock:(ReadiumGCDWebServerStreamBlock)block { return [self initWithContentType:type - asyncStreamBlock:^(GCDWebServerBodyReaderCompletionBlock completionBlock) { + asyncStreamBlock:^(ReadiumGCDWebServerBodyReaderCompletionBlock completionBlock) { NSError* error = nil; NSData* data = block(&error); completionBlock(data, error); }]; } -- (instancetype)initWithContentType:(NSString*)type asyncStreamBlock:(GCDWebServerAsyncStreamBlock)block { +- (instancetype)initWithContentType:(NSString*)type asyncStreamBlock:(ReadiumGCDWebServerAsyncStreamBlock)block { if ((self = [super init])) { _block = [block copy]; @@ -67,7 +67,7 @@ - (instancetype)initWithContentType:(NSString*)type asyncStreamBlock:(GCDWebServ return self; } -- (void)asyncReadDataWithCompletion:(GCDWebServerBodyReaderCompletionBlock)block { +- (void)asyncReadDataWithCompletion:(ReadiumGCDWebServerBodyReaderCompletionBlock)block { _block(block); } diff --git a/GCDWebUploader/GCDWebUploader.h b/GCDWebUploader/GCDWebUploader.h index 8fb8948f..e5e9a6f4 100644 --- a/GCDWebUploader/GCDWebUploader.h +++ b/GCDWebUploader/GCDWebUploader.h @@ -29,54 +29,54 @@ NS_ASSUME_NONNULL_BEGIN -@class GCDWebUploader; +@class ReadiumGCDWebUploader; /** - * Delegate methods for GCDWebUploader. + * Delegate methods for ReadiumGCDWebUploader. * * @warning These methods are always called on the main thread in a serialized way. */ -@protocol GCDWebUploaderDelegate +@protocol ReadiumGCDWebUploaderDelegate @optional /** * This method is called whenever a file has been downloaded. */ -- (void)webUploader:(GCDWebUploader*)uploader didDownloadFileAtPath:(NSString*)path; +- (void)webUploader:(ReadiumGCDWebUploader*)uploader didDownloadFileAtPath:(NSString*)path; /** * This method is called whenever a file has been uploaded. */ -- (void)webUploader:(GCDWebUploader*)uploader didUploadFileAtPath:(NSString*)path; +- (void)webUploader:(ReadiumGCDWebUploader*)uploader didUploadFileAtPath:(NSString*)path; /** * This method is called whenever a file or directory has been moved. */ -- (void)webUploader:(GCDWebUploader*)uploader didMoveItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath; +- (void)webUploader:(ReadiumGCDWebUploader*)uploader didMoveItemFromPath:(NSString*)fromPath toPath:(NSString*)toPath; /** * This method is called whenever a file or directory has been deleted. */ -- (void)webUploader:(GCDWebUploader*)uploader didDeleteItemAtPath:(NSString*)path; +- (void)webUploader:(ReadiumGCDWebUploader*)uploader didDeleteItemAtPath:(NSString*)path; /** * This method is called whenever a directory has been created. */ -- (void)webUploader:(GCDWebUploader*)uploader didCreateDirectoryAtPath:(NSString*)path; +- (void)webUploader:(ReadiumGCDWebUploader*)uploader didCreateDirectoryAtPath:(NSString*)path; @end /** - * The GCDWebUploader subclass of GCDWebServer implements an HTML 5 web browser + * The ReadiumGCDWebUploader subclass of ReadiumGCDWebServer implements an HTML 5 web browser * interface for uploading or downloading files, and moving or deleting files * or directories. * - * See the README.md file for more information about the features of GCDWebUploader. + * See the README.md file for more information about the features of ReadiumGCDWebUploader. * - * @warning For GCDWebUploader to work, "GCDWebUploader.bundle" must be added + * @warning For ReadiumGCDWebUploader to work, "ReadiumGCDWebUploader.bundle" must be added * to the resources of the Xcode target. */ -@interface GCDWebUploader : GCDWebServer +@interface ReadiumGCDWebUploader : ReadiumGCDWebServer /** * Returns the upload directory as specified when the uploader was initialized. @@ -86,7 +86,7 @@ NS_ASSUME_NONNULL_BEGIN /** * Sets the delegate for the uploader. */ -@property(nonatomic, weak, nullable) id delegate; +@property(nonatomic, weak, nullable) id delegate; /** * Sets which files are allowed to be operated on depending on their extension. @@ -161,11 +161,11 @@ NS_ASSUME_NONNULL_BEGIN @end /** - * Hooks to customize the behavior of GCDWebUploader. + * Hooks to customize the behavior of ReadiumGCDWebUploader. * * @warning These methods can be called on any GCD thread. */ -@interface GCDWebUploader (Subclassing) +@interface ReadiumGCDWebUploader (Subclassing) /** * This method is called to check if a file upload is allowed to complete. diff --git a/GCDWebUploader/GCDWebUploader.m b/GCDWebUploader/GCDWebUploader.m index 93d0200b..3b8fbb01 100644 --- a/GCDWebUploader/GCDWebUploader.m +++ b/GCDWebUploader/GCDWebUploader.m @@ -26,7 +26,7 @@ */ #if !__has_feature(objc_arc) -#error GCDWebUploader requires ARC +#error ReadiumGCDWebUploader requires ARC #endif #import @@ -49,24 +49,24 @@ NS_ASSUME_NONNULL_BEGIN -@interface GCDWebUploader (Methods) -- (nullable GCDWebServerResponse*)listDirectory:(GCDWebServerRequest*)request; -- (nullable GCDWebServerResponse*)downloadFile:(GCDWebServerRequest*)request; -- (nullable GCDWebServerResponse*)uploadFile:(GCDWebServerMultiPartFormRequest*)request; -- (nullable GCDWebServerResponse*)moveItem:(GCDWebServerURLEncodedFormRequest*)request; -- (nullable GCDWebServerResponse*)deleteItem:(GCDWebServerURLEncodedFormRequest*)request; -- (nullable GCDWebServerResponse*)createDirectory:(GCDWebServerURLEncodedFormRequest*)request; +@interface ReadiumGCDWebUploader (Methods) +- (nullable ReadiumGCDWebServerResponse*)listDirectory:(ReadiumGCDWebServerRequest*)request; +- (nullable ReadiumGCDWebServerResponse*)downloadFile:(ReadiumGCDWebServerRequest*)request; +- (nullable ReadiumGCDWebServerResponse*)uploadFile:(ReadiumGCDWebServerMultiPartFormRequest*)request; +- (nullable ReadiumGCDWebServerResponse*)moveItem:(ReadiumGCDWebServerURLEncodedFormRequest*)request; +- (nullable ReadiumGCDWebServerResponse*)deleteItem:(ReadiumGCDWebServerURLEncodedFormRequest*)request; +- (nullable ReadiumGCDWebServerResponse*)createDirectory:(ReadiumGCDWebServerURLEncodedFormRequest*)request; @end NS_ASSUME_NONNULL_END -@implementation GCDWebUploader +@implementation ReadiumGCDWebUploader @dynamic delegate; - (instancetype)initWithUploadDirectory:(NSString*)path { if ((self = [super init])) { - NSString* bundlePath = [[NSBundle bundleForClass:[GCDWebUploader class]] pathForResource:@"GCDWebUploader" ofType:@"bundle"]; + NSString* bundlePath = [[NSBundle bundleForClass:[ReadiumGCDWebUploader class]] pathForResource:@"ReadiumGCDWebUploader" ofType:@"bundle"]; if (bundlePath == nil) { return nil; } @@ -75,7 +75,7 @@ - (instancetype)initWithUploadDirectory:(NSString*)path { return nil; } _uploadDirectory = [path copy]; - GCDWebUploader* __unsafe_unretained server = self; + ReadiumGCDWebUploader* __unsafe_unretained server = self; // Resource files [self addGETHandlerForBasePath:@"/" directoryPath:(NSString*)[siteBundle resourcePath] indexFilename:nil cacheAge:3600 allowRangeRequests:NO]; @@ -83,8 +83,8 @@ - (instancetype)initWithUploadDirectory:(NSString*)path { // Web page [self addHandlerForMethod:@"GET" path:@"/" - requestClass:[GCDWebServerRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { + requestClass:[ReadiumGCDWebServerRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { #if TARGET_OS_IPHONE NSString* device = [[UIDevice currentDevice] name]; @@ -130,7 +130,7 @@ - (instancetype)initWithUploadDirectory:(NSString*)path { #endif footer = [NSString stringWithFormat:[siteBundle localizedStringForKey:@"FOOTER_FORMAT" value:@"" table:nil], name, version]; } - return [GCDWebServerDataResponse responseWithHTMLTemplate:(NSString*)[siteBundle pathForResource:@"index" ofType:@"html"] + return [ReadiumGCDWebServerDataResponse responseWithHTMLTemplate:(NSString*)[siteBundle pathForResource:@"index" ofType:@"html"] variables:@{ @"device" : device, @"title" : title, @@ -144,49 +144,49 @@ - (instancetype)initWithUploadDirectory:(NSString*)path { // File listing [self addHandlerForMethod:@"GET" path:@"/list" - requestClass:[GCDWebServerRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { + requestClass:[ReadiumGCDWebServerRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { return [server listDirectory:request]; }]; // File download [self addHandlerForMethod:@"GET" path:@"/download" - requestClass:[GCDWebServerRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { + requestClass:[ReadiumGCDWebServerRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { return [server downloadFile:request]; }]; // File upload [self addHandlerForMethod:@"POST" path:@"/upload" - requestClass:[GCDWebServerMultiPartFormRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { - return [server uploadFile:(GCDWebServerMultiPartFormRequest*)request]; + requestClass:[ReadiumGCDWebServerMultiPartFormRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { + return [server uploadFile:(ReadiumGCDWebServerMultiPartFormRequest*)request]; }]; // File and folder moving [self addHandlerForMethod:@"POST" path:@"/move" - requestClass:[GCDWebServerURLEncodedFormRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { - return [server moveItem:(GCDWebServerURLEncodedFormRequest*)request]; + requestClass:[ReadiumGCDWebServerURLEncodedFormRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { + return [server moveItem:(ReadiumGCDWebServerURLEncodedFormRequest*)request]; }]; // File and folder deletion [self addHandlerForMethod:@"POST" path:@"/delete" - requestClass:[GCDWebServerURLEncodedFormRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { - return [server deleteItem:(GCDWebServerURLEncodedFormRequest*)request]; + requestClass:[ReadiumGCDWebServerURLEncodedFormRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { + return [server deleteItem:(ReadiumGCDWebServerURLEncodedFormRequest*)request]; }]; // Directory creation [self addHandlerForMethod:@"POST" path:@"/create" - requestClass:[GCDWebServerURLEncodedFormRequest class] - processBlock:^GCDWebServerResponse*(GCDWebServerRequest* request) { - return [server createDirectory:(GCDWebServerURLEncodedFormRequest*)request]; + requestClass:[ReadiumGCDWebServerURLEncodedFormRequest class] + processBlock:^ReadiumGCDWebServerResponse*(ReadiumGCDWebServerRequest* request) { + return [server createDirectory:(ReadiumGCDWebServerURLEncodedFormRequest*)request]; }]; } return self; @@ -194,7 +194,7 @@ - (instancetype)initWithUploadDirectory:(NSString*)path { @end -@implementation GCDWebUploader (Methods) +@implementation ReadiumGCDWebUploader (Methods) - (BOOL)_checkFileExtension:(NSString*)fileName { if (_allowedFileExtensions && ![_allowedFileExtensions containsObject:[[fileName pathExtension] lowercaseString]]) { @@ -221,26 +221,26 @@ - (NSString*)_uniquePathForPath:(NSString*)path { return path; } -- (GCDWebServerResponse*)listDirectory:(GCDWebServerRequest*)request { +- (ReadiumGCDWebServerResponse*)listDirectory:(ReadiumGCDWebServerRequest*)request { NSString* relativePath = [[request query] objectForKey:@"path"]; - NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(relativePath)]; + NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(relativePath)]; BOOL isDirectory = NO; if (!absolutePath || ![[NSFileManager defaultManager] fileExistsAtPath:absolutePath isDirectory:&isDirectory]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; } if (!isDirectory) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"\"%@\" is not a directory", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"\"%@\" is not a directory", relativePath]; } NSString* directoryName = [absolutePath lastPathComponent]; if (!_allowHiddenItems && [directoryName hasPrefix:@"."]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Listing directory name \"%@\" is not allowed", directoryName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Listing directory name \"%@\" is not allowed", directoryName]; } NSError* error = nil; NSArray* contents = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:absolutePath error:&error] sortedArrayUsingSelector:@selector(localizedStandardCompare:)]; if (contents == nil) { - return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed listing directory \"%@\"", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed listing directory \"%@\"", relativePath]; } NSMutableArray* array = [NSMutableArray array]; @@ -262,23 +262,23 @@ - (GCDWebServerResponse*)listDirectory:(GCDWebServerRequest*)request { } } } - return [GCDWebServerDataResponse responseWithJSONObject:array]; + return [ReadiumGCDWebServerDataResponse responseWithJSONObject:array]; } -- (GCDWebServerResponse*)downloadFile:(GCDWebServerRequest*)request { +- (ReadiumGCDWebServerResponse*)downloadFile:(ReadiumGCDWebServerRequest*)request { NSString* relativePath = [[request query] objectForKey:@"path"]; - NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(relativePath)]; + NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(relativePath)]; BOOL isDirectory = NO; if (![[NSFileManager defaultManager] fileExistsAtPath:absolutePath isDirectory:&isDirectory]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; } if (isDirectory) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"\"%@\" is a directory", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_BadRequest message:@"\"%@\" is a directory", relativePath]; } NSString* fileName = [absolutePath lastPathComponent]; if (([fileName hasPrefix:@"."] && !_allowHiddenItems) || ![self _checkFileExtension:fileName]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Downlading file name \"%@\" is not allowed", fileName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Downlading file name \"%@\" is not allowed", fileName]; } if ([self.delegate respondsToSelector:@selector(webUploader:didDownloadFileAtPath:)]) { @@ -286,27 +286,27 @@ - (GCDWebServerResponse*)downloadFile:(GCDWebServerRequest*)request { [self.delegate webUploader:self didDownloadFileAtPath:absolutePath]; }); } - return [GCDWebServerFileResponse responseWithFile:absolutePath isAttachment:YES]; + return [ReadiumGCDWebServerFileResponse responseWithFile:absolutePath isAttachment:YES]; } -- (GCDWebServerResponse*)uploadFile:(GCDWebServerMultiPartFormRequest*)request { +- (ReadiumGCDWebServerResponse*)uploadFile:(ReadiumGCDWebServerMultiPartFormRequest*)request { NSRange range = [[request.headers objectForKey:@"Accept"] rangeOfString:@"application/json" options:NSCaseInsensitiveSearch]; NSString* contentType = (range.location != NSNotFound ? @"application/json" : @"text/plain; charset=utf-8"); // Required when using iFrame transport (see https://github.com/blueimp/jQuery-File-Upload/wiki/Setup) - GCDWebServerMultiPartFile* file = [request firstFileForControlName:@"files[]"]; + ReadiumGCDWebServerMultiPartFile* file = [request firstFileForControlName:@"files[]"]; if ((!_allowHiddenItems && [file.fileName hasPrefix:@"."]) || ![self _checkFileExtension:file.fileName]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Uploaded file name \"%@\" is not allowed", file.fileName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Uploaded file name \"%@\" is not allowed", file.fileName]; } NSString* relativePath = [[request firstArgumentForControlName:@"path"] string]; - NSString* absolutePath = [self _uniquePathForPath:[[_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(relativePath)] stringByAppendingPathComponent:file.fileName]]; + NSString* absolutePath = [self _uniquePathForPath:[[_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(relativePath)] stringByAppendingPathComponent:file.fileName]]; if (![self shouldUploadFileAtPath:absolutePath withTemporaryFile:file.temporaryPath]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Uploading file \"%@\" to \"%@\" is not permitted", file.fileName, relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Uploading file \"%@\" to \"%@\" is not permitted", file.fileName, relativePath]; } NSError* error = nil; if (![[NSFileManager defaultManager] moveItemAtPath:file.temporaryPath toPath:absolutePath error:&error]) { - return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed moving uploaded file to \"%@\"", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed moving uploaded file to \"%@\"", relativePath]; } if ([self.delegate respondsToSelector:@selector(webUploader:didUploadFileAtPath:)]) { @@ -314,37 +314,37 @@ - (GCDWebServerResponse*)uploadFile:(GCDWebServerMultiPartFormRequest*)request { [self.delegate webUploader:self didUploadFileAtPath:absolutePath]; }); } - return [GCDWebServerDataResponse responseWithJSONObject:@{} contentType:contentType]; + return [ReadiumGCDWebServerDataResponse responseWithJSONObject:@{} contentType:contentType]; } -- (GCDWebServerResponse*)moveItem:(GCDWebServerURLEncodedFormRequest*)request { +- (ReadiumGCDWebServerResponse*)moveItem:(ReadiumGCDWebServerURLEncodedFormRequest*)request { NSString* oldRelativePath = [request.arguments objectForKey:@"oldPath"]; - NSString* oldAbsolutePath = [_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(oldRelativePath)]; + NSString* oldAbsolutePath = [_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(oldRelativePath)]; BOOL isDirectory = NO; if (![[NSFileManager defaultManager] fileExistsAtPath:oldAbsolutePath isDirectory:&isDirectory]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", oldRelativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", oldRelativePath]; } NSString* oldItemName = [oldAbsolutePath lastPathComponent]; if ((!_allowHiddenItems && [oldItemName hasPrefix:@"."]) || (!isDirectory && ![self _checkFileExtension:oldItemName])) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Moving from item name \"%@\" is not allowed", oldItemName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Moving from item name \"%@\" is not allowed", oldItemName]; } NSString* newRelativePath = [request.arguments objectForKey:@"newPath"]; - NSString* newAbsolutePath = [self _uniquePathForPath:[_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(newRelativePath)]]; + NSString* newAbsolutePath = [self _uniquePathForPath:[_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(newRelativePath)]]; NSString* newItemName = [newAbsolutePath lastPathComponent]; if ((!_allowHiddenItems && [newItemName hasPrefix:@"."]) || (!isDirectory && ![self _checkFileExtension:newItemName])) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Moving to item name \"%@\" is not allowed", newItemName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Moving to item name \"%@\" is not allowed", newItemName]; } if (![self shouldMoveItemFromPath:oldAbsolutePath toPath:newAbsolutePath]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Moving \"%@\" to \"%@\" is not permitted", oldRelativePath, newRelativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Moving \"%@\" to \"%@\" is not permitted", oldRelativePath, newRelativePath]; } NSError* error = nil; if (![[NSFileManager defaultManager] moveItemAtPath:oldAbsolutePath toPath:newAbsolutePath error:&error]) { - return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed moving \"%@\" to \"%@\"", oldRelativePath, newRelativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed moving \"%@\" to \"%@\"", oldRelativePath, newRelativePath]; } if ([self.delegate respondsToSelector:@selector(webUploader:didMoveItemFromPath:toPath:)]) { @@ -352,29 +352,29 @@ - (GCDWebServerResponse*)moveItem:(GCDWebServerURLEncodedFormRequest*)request { [self.delegate webUploader:self didMoveItemFromPath:oldAbsolutePath toPath:newAbsolutePath]; }); } - return [GCDWebServerDataResponse responseWithJSONObject:@{}]; + return [ReadiumGCDWebServerDataResponse responseWithJSONObject:@{}]; } -- (GCDWebServerResponse*)deleteItem:(GCDWebServerURLEncodedFormRequest*)request { +- (ReadiumGCDWebServerResponse*)deleteItem:(ReadiumGCDWebServerURLEncodedFormRequest*)request { NSString* relativePath = [request.arguments objectForKey:@"path"]; - NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(relativePath)]; + NSString* absolutePath = [_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(relativePath)]; BOOL isDirectory = NO; if (![[NSFileManager defaultManager] fileExistsAtPath:absolutePath isDirectory:&isDirectory]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_NotFound message:@"\"%@\" does not exist", relativePath]; } NSString* itemName = [absolutePath lastPathComponent]; if (([itemName hasPrefix:@"."] && !_allowHiddenItems) || (!isDirectory && ![self _checkFileExtension:itemName])) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Deleting item name \"%@\" is not allowed", itemName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Deleting item name \"%@\" is not allowed", itemName]; } if (![self shouldDeleteItemAtPath:absolutePath]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Deleting \"%@\" is not permitted", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Deleting \"%@\" is not permitted", relativePath]; } NSError* error = nil; if (![[NSFileManager defaultManager] removeItemAtPath:absolutePath error:&error]) { - return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed deleting \"%@\"", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed deleting \"%@\"", relativePath]; } if ([self.delegate respondsToSelector:@selector(webUploader:didDeleteItemAtPath:)]) { @@ -382,25 +382,25 @@ - (GCDWebServerResponse*)deleteItem:(GCDWebServerURLEncodedFormRequest*)request [self.delegate webUploader:self didDeleteItemAtPath:absolutePath]; }); } - return [GCDWebServerDataResponse responseWithJSONObject:@{}]; + return [ReadiumGCDWebServerDataResponse responseWithJSONObject:@{}]; } -- (GCDWebServerResponse*)createDirectory:(GCDWebServerURLEncodedFormRequest*)request { +- (ReadiumGCDWebServerResponse*)createDirectory:(ReadiumGCDWebServerURLEncodedFormRequest*)request { NSString* relativePath = [request.arguments objectForKey:@"path"]; - NSString* absolutePath = [self _uniquePathForPath:[_uploadDirectory stringByAppendingPathComponent:GCDWebServerNormalizePath(relativePath)]]; + NSString* absolutePath = [self _uniquePathForPath:[_uploadDirectory stringByAppendingPathComponent:ReadiumGCDWebServerNormalizePath(relativePath)]]; NSString* directoryName = [absolutePath lastPathComponent]; if (!_allowHiddenItems && [directoryName hasPrefix:@"."]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Creating directory name \"%@\" is not allowed", directoryName]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Creating directory name \"%@\" is not allowed", directoryName]; } if (![self shouldCreateDirectoryAtPath:absolutePath]) { - return [GCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Creating directory \"%@\" is not permitted", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithClientError:kGCDWebServerHTTPStatusCode_Forbidden message:@"Creating directory \"%@\" is not permitted", relativePath]; } NSError* error = nil; if (![[NSFileManager defaultManager] createDirectoryAtPath:absolutePath withIntermediateDirectories:NO attributes:nil error:&error]) { - return [GCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed creating directory \"%@\"", relativePath]; + return [ReadiumGCDWebServerErrorResponse responseWithServerError:kGCDWebServerHTTPStatusCode_InternalServerError underlyingError:error message:@"Failed creating directory \"%@\"", relativePath]; } if ([self.delegate respondsToSelector:@selector(webUploader:didCreateDirectoryAtPath:)]) { @@ -408,12 +408,12 @@ - (GCDWebServerResponse*)createDirectory:(GCDWebServerURLEncodedFormRequest*)req [self.delegate webUploader:self didCreateDirectoryAtPath:absolutePath]; }); } - return [GCDWebServerDataResponse responseWithJSONObject:@{}]; + return [ReadiumGCDWebServerDataResponse responseWithJSONObject:@{}]; } @end -@implementation GCDWebUploader (Subclassing) +@implementation ReadiumGCDWebUploader (Subclassing) - (BOOL)shouldUploadFileAtPath:(NSString*)path withTemporaryFile:(NSString*)tempPath { return YES; diff --git a/iOS/ViewController.swift b/iOS/ViewController.swift index f5556546..a493610a 100644 --- a/iOS/ViewController.swift +++ b/iOS/ViewController.swift @@ -25,24 +25,24 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -import GCDWebServer +import ReadiumGCDWebServer import UIKit class ViewController: UIViewController { @IBOutlet var label: UILabel? - var webServer: GCDWebUploader! + var webServer: ReadiumGCDWebUploader! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! - webServer = GCDWebUploader(uploadDirectory: documentsPath) + webServer = ReadiumGCDWebUploader(uploadDirectory: documentsPath) webServer.delegate = self webServer.allowHiddenItems = true if webServer.start() { - label?.text = "GCDWebServer running locally on port \(webServer.port)" + label?.text = "ReadiumGCDWebServer running locally on port \(webServer.port)" } else { - label?.text = "GCDWebServer not running!" + label?.text = "ReadiumGCDWebServer not running!" } } @@ -54,24 +54,24 @@ class ViewController: UIViewController { } } -extension ViewController: GCDWebUploaderDelegate { - func webUploader(_: GCDWebUploader, didUploadFileAtPath path: String) { +extension ViewController: ReadiumGCDWebUploaderDelegate { + func webUploader(_: ReadiumGCDWebUploader, didUploadFileAtPath path: String) { print("[UPLOAD] \(path)") } - func webUploader(_: GCDWebUploader, didDownloadFileAtPath path: String) { + func webUploader(_: ReadiumGCDWebUploader, didDownloadFileAtPath path: String) { print("[DOWNLOAD] \(path)") } - func webUploader(_: GCDWebUploader, didMoveItemFromPath fromPath: String, toPath: String) { + func webUploader(_: ReadiumGCDWebUploader, didMoveItemFromPath fromPath: String, toPath: String) { print("[MOVE] \(fromPath) -> \(toPath)") } - func webUploader(_: GCDWebUploader, didCreateDirectoryAtPath path: String) { + func webUploader(_: ReadiumGCDWebUploader, didCreateDirectoryAtPath path: String) { print("[CREATE] \(path)") } - func webUploader(_: GCDWebUploader, didDeleteItemAtPath path: String) { + func webUploader(_: ReadiumGCDWebUploader, didDeleteItemAtPath path: String) { print("[DELETE] \(path)") } }