From 117716da9e5de25f0befef9ffd44a41ad3e32268 Mon Sep 17 00:00:00 2001 From: Kevin Wojniak Date: Thu, 8 Oct 2015 20:41:26 -0700 Subject: [PATCH 1/3] Replace use of Python with built-in web server See issue #637 --- Sparkle.xcodeproj/project.pbxproj | 6 + TestApplication/SUTestApplicationDelegate.m | 20 +- TestApplication/SUTestWebServer.h | 17 ++ TestApplication/SUTestWebServer.m | 247 ++++++++++++++++++++ 4 files changed, 280 insertions(+), 10 deletions(-) create mode 100644 TestApplication/SUTestWebServer.h create mode 100644 TestApplication/SUTestWebServer.m diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 189859cb..356297be 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -190,6 +190,7 @@ 767B61AC1972D488004E0C3C /* SUGuidedPackageInstaller.h in Headers */ = {isa = PBXBuildFile; fileRef = 767B61AA1972D488004E0C3C /* SUGuidedPackageInstaller.h */; }; 767B61AD1972D488004E0C3C /* SUGuidedPackageInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 767B61AB1972D488004E0C3C /* SUGuidedPackageInstaller.m */; }; 767B61AE1972D488004E0C3C /* SUGuidedPackageInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 767B61AB1972D488004E0C3C /* SUGuidedPackageInstaller.m */; }; + A5BF4F1D1BC7668B007A052A /* SUTestWebServer.m in Sources */ = {isa = PBXBuildFile; fileRef = A5BF4F1C1BC7668B007A052A /* SUTestWebServer.m */; settings = {ASSET_TAGS = (); }; }; F8761EB11ADC5068000C9034 /* SUCodeSigningVerifierTest.m in Sources */ = {isa = PBXBuildFile; fileRef = F8761EB01ADC5068000C9034 /* SUCodeSigningVerifierTest.m */; }; F8761EB31ADC50EB000C9034 /* SparkleTestCodeSignApp.zip in Resources */ = {isa = PBXBuildFile; fileRef = F8761EB21ADC50EB000C9034 /* SparkleTestCodeSignApp.zip */; }; F8761EB61ADC5E7A000C9034 /* SUCodeSigningVerifier.m in Sources */ = {isa = PBXBuildFile; fileRef = 61B078CD15A5FB6100600039 /* SUCodeSigningVerifier.m */; }; @@ -590,6 +591,8 @@ 767B61AB1972D488004E0C3C /* SUGuidedPackageInstaller.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUGuidedPackageInstaller.m; sourceTree = ""; }; 8DC2EF5A0486A6940098B216 /* Sparkle-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "Sparkle-Info.plist"; sourceTree = ""; }; 8DC2EF5B0486A6940098B216 /* Sparkle.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Sparkle.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + A5BF4F1B1BC7668B007A052A /* SUTestWebServer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUTestWebServer.h; sourceTree = ""; }; + A5BF4F1C1BC7668B007A052A /* SUTestWebServer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUTestWebServer.m; sourceTree = ""; }; F8761EB01ADC5068000C9034 /* SUCodeSigningVerifierTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUCodeSigningVerifierTest.m; sourceTree = ""; }; F8761EB21ADC50EB000C9034 /* SparkleTestCodeSignApp.zip */ = {isa = PBXFileReference; lastKnownFileType = archive.zip; path = SparkleTestCodeSignApp.zip; sourceTree = ""; }; FA1941CA0D94A70100DD942E /* ConfigFrameworkDebug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = ConfigFrameworkDebug.xcconfig; sourceTree = ""; }; @@ -973,6 +976,8 @@ 72E45CF21B640CDD005C701A /* SUTestApplicationDelegate.m */, 72E45CF41B640DAE005C701A /* SUUpdateSettingsWindowController.h */, 72E45CF51B640DAE005C701A /* SUUpdateSettingsWindowController.m */, + A5BF4F1B1BC7668B007A052A /* SUTestWebServer.h */, + A5BF4F1C1BC7668B007A052A /* SUTestWebServer.m */, 72E45CF61B640DAE005C701A /* SUUpdateSettingsWindowController.xib */, 72E45CFD1B641D0D005C701A /* test_app_only_dsa_priv_dont_ever_do_this_for_real.pem */, 14732BBF1960F0AC00593899 /* test_app_only_dsa_pub.pem */, @@ -1507,6 +1512,7 @@ buildActionMask = 2147483647; files = ( 61B5F93009C4CFDC00B25A18 /* main.m in Sources */, + A5BF4F1D1BC7668B007A052A /* SUTestWebServer.m in Sources */, 72E45CF31B640CDD005C701A /* SUTestApplicationDelegate.m in Sources */, 72E45CF71B640DAE005C701A /* SUUpdateSettingsWindowController.m in Sources */, ); diff --git a/TestApplication/SUTestApplicationDelegate.m b/TestApplication/SUTestApplicationDelegate.m index b46a739a..13ae0d80 100644 --- a/TestApplication/SUTestApplicationDelegate.m +++ b/TestApplication/SUTestApplicationDelegate.m @@ -8,18 +8,19 @@ #import "SUTestApplicationDelegate.h" #import "SUUpdateSettingsWindowController.h" +#import "SUTestWebServer.h" @interface SUTestApplicationDelegate () @property (nonatomic) SUUpdateSettingsWindowController *updateSettingsWindowController; -@property (nonatomic) NSTask *serverTask; +@property (nonatomic) SUTestWebServer *webServer; @end @implementation SUTestApplicationDelegate @synthesize updateSettingsWindowController = _updateSettingsWindowController; -@synthesize serverTask = _serverTask; +@synthesize webServer = _webServer; static NSString * const UPDATED_VERSION = @"2.0"; @@ -176,13 +177,12 @@ static NSString * const UPDATED_VERSION = @"2.0"; } // Finally start the server - NSTask *serverTask = [[NSTask alloc] init]; - serverTask.launchPath = @"/usr/bin/python"; - assert([fileManager fileExistsAtPath:serverTask.launchPath]); - serverTask.arguments = @[@"-m", @"SimpleHTTPServer", @"1337"]; - serverTask.currentDirectoryPath = serverDirectoryPath; - [serverTask launch]; - self.serverTask = serverTask; + SUTestWebServer *webServer = [[SUTestWebServer alloc] initWithPort:1337 workingDirectory:serverDirectoryPath]; + if (!webServer) { + NSLog(@"Failed to create the web server"); + assert(NO); + } + self.webServer = webServer; // Show the Settings window self.updateSettingsWindowController = [[SUUpdateSettingsWindowController alloc] init]; @@ -191,7 +191,7 @@ static NSString * const UPDATED_VERSION = @"2.0"; - (void)applicationWillTerminate:(NSNotification * __unused)notification { - [self.serverTask terminate]; + [self.webServer close]; } @end diff --git a/TestApplication/SUTestWebServer.h b/TestApplication/SUTestWebServer.h new file mode 100644 index 00000000..2c61c565 --- /dev/null +++ b/TestApplication/SUTestWebServer.h @@ -0,0 +1,17 @@ +// +// SUTestWebServer.h +// Sparkle +// +// Created by Kevin Wojniak on 10/8/15. +// Copyright © 2015 Sparkle Project. All rights reserved. +// + +#import + +@interface SUTestWebServer : NSObject + +- (instancetype)initWithPort:(int)port workingDirectory:(NSString*)workingDirectory; + +- (void)close; + +@end diff --git a/TestApplication/SUTestWebServer.m b/TestApplication/SUTestWebServer.m new file mode 100644 index 00000000..f3cd6189 --- /dev/null +++ b/TestApplication/SUTestWebServer.m @@ -0,0 +1,247 @@ +// +// SUTestWebServer.m +// Sparkle +// +// Created by Kevin Wojniak on 10/8/15. +// Copyright © 2015 Sparkle Project. All rights reserved. +// + +#import "SUTestWebServer.h" +#import +#import + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" + +@class SUTestWebServerConnection; + +@protocol SUTestWebServerConnectionDelegate +@required +- (void)connectionDidClose:(SUTestWebServerConnection*)sender; +@end + +@interface SUTestWebServerConnection : NSObject + +@end + +@implementation SUTestWebServerConnection { + NSString *_workingDirectory; + id _delegate; + NSInputStream *_inputStream; + NSOutputStream *_outputStream; + NSData *_dataToWrite; + NSInteger _numBytesToWrite; +} + +- (instancetype)initWithNativeHandle:(CFSocketNativeHandle)handle workingDirectory:(NSString*)workingDirectory delegate:(id)delegate { + self = [super init]; + assert(self != nil); + + _workingDirectory = workingDirectory; + _delegate = delegate; + + CFReadStreamRef readStream = NULL; + CFWriteStreamRef writeStream = NULL; + CFStreamCreatePairWithSocket(NULL, handle, &readStream, &writeStream); + assert(readStream != NULL); + assert(writeStream != NULL); + + _inputStream = (__bridge NSInputStream*)readStream; + assert(_inputStream != nil); + _inputStream.delegate = self; + + _outputStream = (__bridge NSOutputStream*)writeStream; + assert(_outputStream != nil); + _outputStream.delegate = self; + + [_inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + [_outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + [_inputStream open]; + [_outputStream open]; + + return self; +} + +- (void)close { + if (!_inputStream) { + assert(_outputStream == nil); + return; + } + [_inputStream close]; + [_outputStream close]; + [_inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + [_outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + _inputStream = nil; + _outputStream = nil; + [_delegate connectionDidClose:self]; +} + +- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { + if (eventCode == NSStreamEventEndEncountered) { + [self close]; + return; + } + if (aStream == _inputStream && eventCode == NSStreamEventHasBytesAvailable) { + uint8_t buffer[8096]; + const NSInteger numBytes = [_inputStream read:buffer maxLength:sizeof(buffer)]; + if (numBytes > 0) { + NSString *request = [[NSString alloc] initWithBytes:buffer length:(NSUInteger)numBytes encoding:NSUTF8StringEncoding]; + NSArray *lines = [request componentsSeparatedByString:@"\r\n"]; + NSString *requestLine = lines.count >= 3 ? lines[0] : nil; + NSArray *parts = requestLine ? [requestLine componentsSeparatedByString:@" "] : nil; + // Only process GET requests for existing files + if ([parts[0] isEqualToString:@"GET"]) { + // Use NSURL to strip out query parameters + NSString *path = [NSURL URLWithString:parts[1] relativeToURL:nil].path; + NSString *filePath = [_workingDirectory stringByAppendingString:path]; + BOOL isDir = NO; + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDir] || isDir) { + NSLog(@"%@ - 404", requestLine); + [self write404]; + } else { + NSLog(@"%@ - 200", requestLine); + [self write:[NSData dataWithContentsOfFile:filePath] status:YES]; + } + } else { + NSLog(@"%@ - 404", requestLine); + [self write404]; + } + } + } else if (aStream == _outputStream && eventCode == NSStreamEventHasSpaceAvailable && _dataToWrite) { + [self checkIfCanWriteNow]; + } +} + +- (void)write404 { + NSString *body = @"404 Not Found

Not Found

"; + [self write:[body dataUsingEncoding:NSUTF8StringEncoding] status:NO]; +} + +- (void)write:(NSData*)body status:(BOOL)status { + NSString *state = status ? @"200 OK" : @"404 Not Found"; + NSString *header = [NSString stringWithFormat:@"HTTP/1.0 %@\r\nContent-Length: %lu\r\n\r\n", state, body.length]; + NSMutableData *response = [[header dataUsingEncoding:NSUTF8StringEncoding] mutableCopy]; + [response appendData:body]; + [self queueWrite:response]; +} + +- (void)queueWrite:(NSData*)data { + assert(_dataToWrite == nil); + assert(data != nil); + assert(data.length > 0); + _dataToWrite = data; + _numBytesToWrite = (NSInteger)data.length; + [self checkIfCanWriteNow]; +} + +- (void)checkIfCanWriteNow { + assert(_dataToWrite != nil); + if (_numBytesToWrite == 0) { + // nothing more to write, we're done. + _dataToWrite = 0; + _numBytesToWrite = -1; + } else if (_outputStream.hasSpaceAvailable) { + [self writeNow]; + } + // otherwise wait for space available event +} + +- (void)writeNow { + assert(_outputStream != nil); + assert(_outputStream.hasSpaceAvailable); + assert(_dataToWrite != nil); + const uint8_t *bytesOffset = (const uint8_t*)_dataToWrite.bytes + ((NSInteger)_dataToWrite.length - _numBytesToWrite); + const NSInteger bytesWritten = [_outputStream write:bytesOffset maxLength:(NSUInteger)_numBytesToWrite]; + if (bytesWritten > 0) { + _numBytesToWrite -= bytesWritten; + assert(_numBytesToWrite >= 0); + // wait for next space available event to write more + } else { + NSLog(@"Error: bytes written = %ld (%@)", bytesWritten, [NSString stringWithUTF8String:strerror(errno)]); + } +} + +@end + +@interface SUTestWebServer () { + NSMutableArray *_connections; + NSString* _workingDirectory; + CFSocketRef _socket; +} + +- (void)accept:(CFSocketNativeHandle)address; + +@end + +static void connectCallback(CFSocketRef __unused s, CFSocketCallBackType type, CFDataRef __unused address, const void *data, void *info) { + if (type == kCFSocketAcceptCallBack) { + SUTestWebServer *server = (__bridge SUTestWebServer*)info; + [server accept:*(const CFSocketNativeHandle*)data]; + } +} + +@implementation SUTestWebServer + +- (instancetype)initWithPort:(int)port workingDirectory:(NSString*)workingDirectory { + self = [super init]; + assert(self != nil); + + CFSocketContext ctx; + memset(&ctx, 0, sizeof(ctx)); + ctx.info = (__bridge void*)self; + _socket = CFSocketCreate(NULL, 0, 0, 0, kCFSocketAcceptCallBack, connectCallback, &ctx); + assert(_socket != NULL); + + struct sockaddr_in address; + memset(&address, 0, sizeof(address)); + address.sin_len = sizeof(address); + address.sin_family = AF_INET; + address.sin_port = htons(port); + address.sin_addr.s_addr = INADDR_ANY; + + // will fail if port is in use. + CFSocketError socketErr = CFSocketSetAddress(_socket, (CFDataRef)[NSData dataWithBytes:&address length:sizeof(address)]); + if (socketErr != kCFSocketSuccess) { + NSLog(@"Socket error: %@", [NSString stringWithUTF8String:strerror(errno)]); + return nil; + } + + _connections = [[NSMutableArray alloc] init]; + _workingDirectory = workingDirectory; + + CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(NULL, _socket, 0); + assert(source != NULL); + CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode); + CFRelease(source); + + return self; +} + +- (void)connectionDidClose:(SUTestWebServerConnection *)sender { + assert(_connections != nil); + assert([_connections containsObject:sender]); + [_connections removeObject:sender]; +} + +- (void)accept:(CFSocketNativeHandle)address { + SUTestWebServerConnection *conn = [[SUTestWebServerConnection alloc] initWithNativeHandle:address workingDirectory:_workingDirectory delegate:self]; + assert(conn != nil); + if (conn) { + [_connections addObject:conn]; + } +} + +- (void)close { + for (SUTestWebServerConnection *conn in _connections) { + [conn close]; + } + if (_socket) { + CFSocketInvalidate(_socket); + CFRelease(_socket); + _socket = NULL; + } +} + +@end + +#pragma clang diagnostic pop From ff342f1e5b908cc14abc567c75243503466defd1 Mon Sep 17 00:00:00 2001 From: Kevin Wojniak Date: Fri, 9 Oct 2015 09:22:20 -0700 Subject: [PATCH 2/3] Use nil instead of 0. Fix pointer style. --- TestApplication/SUTestWebServer.m | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/TestApplication/SUTestWebServer.m b/TestApplication/SUTestWebServer.m index f3cd6189..ac08a930 100644 --- a/TestApplication/SUTestWebServer.m +++ b/TestApplication/SUTestWebServer.m @@ -138,7 +138,7 @@ assert(_dataToWrite != nil); if (_numBytesToWrite == 0) { // nothing more to write, we're done. - _dataToWrite = 0; + _dataToWrite = nil; _numBytesToWrite = -1; } else if (_outputStream.hasSpaceAvailable) { [self writeNow]; @@ -165,7 +165,7 @@ @interface SUTestWebServer () { NSMutableArray *_connections; - NSString* _workingDirectory; + NSString *_workingDirectory; CFSocketRef _socket; } From 948eccb1694d27fb62801e668ad90a02186ae0e8 Mon Sep 17 00:00:00 2001 From: Kevin Wojniak Date: Fri, 9 Oct 2015 09:37:25 -0700 Subject: [PATCH 3/3] Use properties to avoid having to disable warning for entire file --- TestApplication/SUTestWebServer.m | 114 +++++++++++++++++------------- 1 file changed, 65 insertions(+), 49 deletions(-) diff --git a/TestApplication/SUTestWebServer.m b/TestApplication/SUTestWebServer.m index ac08a930..d8093272 100644 --- a/TestApplication/SUTestWebServer.m +++ b/TestApplication/SUTestWebServer.m @@ -10,9 +10,6 @@ #import #import -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdirect-ivar-access" - @class SUTestWebServerConnection; @protocol SUTestWebServerConnectionDelegate @@ -22,16 +19,23 @@ @interface SUTestWebServerConnection : NSObject +@property (nonatomic) NSString* workingDirectory; +@property (nonatomic, weak) id delegate; +@property (nonatomic) NSInputStream *inputStream; +@property (nonatomic) NSOutputStream *outputStream; +@property (nonatomic) NSData *dataToWrite; +@property (nonatomic) NSInteger numBytesToWrite; + @end -@implementation SUTestWebServerConnection { - NSString *_workingDirectory; - id _delegate; - NSInputStream *_inputStream; - NSOutputStream *_outputStream; - NSData *_dataToWrite; - NSInteger _numBytesToWrite; -} +@implementation SUTestWebServerConnection + +@synthesize workingDirectory = _workingDirectory; +@synthesize delegate = _delegate; +@synthesize inputStream = _inputStream; +@synthesize outputStream = _outputStream; +@synthesize dataToWrite = _dataToWrite; +@synthesize numBytesToWrite = _numBytesToWrite; - (instancetype)initWithNativeHandle:(CFSocketNativeHandle)handle workingDirectory:(NSString*)workingDirectory delegate:(id)delegate { self = [super init]; @@ -63,17 +67,19 @@ } - (void)close { - if (!_inputStream) { - assert(_outputStream == nil); + NSInputStream *inputStream = self.inputStream; + NSOutputStream *outputStream = self.outputStream; + if (inputStream == nil) { + assert(outputStream == nil); return; } - [_inputStream close]; - [_outputStream close]; - [_inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; - [_outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; - _inputStream = nil; - _outputStream = nil; - [_delegate connectionDidClose:self]; + [inputStream close]; + [outputStream close]; + [inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + [outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + self.inputStream = nil; + self.outputStream = nil; + [self.delegate connectionDidClose:self]; } - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { @@ -81,9 +87,9 @@ [self close]; return; } - if (aStream == _inputStream && eventCode == NSStreamEventHasBytesAvailable) { + if (aStream == self.inputStream && eventCode == NSStreamEventHasBytesAvailable) { uint8_t buffer[8096]; - const NSInteger numBytes = [_inputStream read:buffer maxLength:sizeof(buffer)]; + const NSInteger numBytes = [self.inputStream read:buffer maxLength:sizeof(buffer)]; if (numBytes > 0) { NSString *request = [[NSString alloc] initWithBytes:buffer length:(NSUInteger)numBytes encoding:NSUTF8StringEncoding]; NSArray *lines = [request componentsSeparatedByString:@"\r\n"]; @@ -93,7 +99,7 @@ if ([parts[0] isEqualToString:@"GET"]) { // Use NSURL to strip out query parameters NSString *path = [NSURL URLWithString:parts[1] relativeToURL:nil].path; - NSString *filePath = [_workingDirectory stringByAppendingString:path]; + NSString *filePath = [self.workingDirectory stringByAppendingString:path]; BOOL isDir = NO; if (![[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDir] || isDir) { NSLog(@"%@ - 404", requestLine); @@ -107,7 +113,7 @@ [self write404]; } } - } else if (aStream == _outputStream && eventCode == NSStreamEventHasSpaceAvailable && _dataToWrite) { + } else if (aStream == self.outputStream && eventCode == NSStreamEventHasSpaceAvailable && self.dataToWrite != nil) { [self checkIfCanWriteNow]; } } @@ -126,35 +132,36 @@ } - (void)queueWrite:(NSData*)data { - assert(_dataToWrite == nil); + assert(self.dataToWrite == nil); assert(data != nil); assert(data.length > 0); - _dataToWrite = data; - _numBytesToWrite = (NSInteger)data.length; + self.dataToWrite = data; + self.numBytesToWrite = (NSInteger)data.length; [self checkIfCanWriteNow]; } - (void)checkIfCanWriteNow { - assert(_dataToWrite != nil); - if (_numBytesToWrite == 0) { + assert(self.dataToWrite != nil); + if (self.numBytesToWrite == 0) { // nothing more to write, we're done. - _dataToWrite = nil; - _numBytesToWrite = -1; - } else if (_outputStream.hasSpaceAvailable) { + self.dataToWrite = nil; + self.numBytesToWrite = -1; + } else if (self.outputStream.hasSpaceAvailable) { [self writeNow]; } // otherwise wait for space available event } - (void)writeNow { - assert(_outputStream != nil); - assert(_outputStream.hasSpaceAvailable); - assert(_dataToWrite != nil); - const uint8_t *bytesOffset = (const uint8_t*)_dataToWrite.bytes + ((NSInteger)_dataToWrite.length - _numBytesToWrite); - const NSInteger bytesWritten = [_outputStream write:bytesOffset maxLength:(NSUInteger)_numBytesToWrite]; + assert(self.outputStream != nil); + assert(self.outputStream.hasSpaceAvailable); + assert(self.dataToWrite != nil); + NSData *dataToWrite = self.dataToWrite; + const uint8_t *bytesOffset = (const uint8_t*)dataToWrite.bytes + ((NSInteger)dataToWrite.length - self.numBytesToWrite); + const NSInteger bytesWritten = [self.outputStream write:bytesOffset maxLength:(NSUInteger)self.numBytesToWrite]; if (bytesWritten > 0) { - _numBytesToWrite -= bytesWritten; - assert(_numBytesToWrite >= 0); + self.numBytesToWrite = self.numBytesToWrite - bytesWritten; + assert(self.numBytesToWrite >= 0); // wait for next space available event to write more } else { NSLog(@"Error: bytes written = %ld (%@)", bytesWritten, [NSString stringWithUTF8String:strerror(errno)]); @@ -164,24 +171,31 @@ @end @interface SUTestWebServer () { - NSMutableArray *_connections; - NSString *_workingDirectory; CFSocketRef _socket; } +@property (nonatomic) NSMutableArray *connections; +@property (nonatomic) NSString *workingDirectory; + - (void)accept:(CFSocketNativeHandle)address; @end static void connectCallback(CFSocketRef __unused s, CFSocketCallBackType type, CFDataRef __unused address, const void *data, void *info) { if (type == kCFSocketAcceptCallBack) { + assert(data != NULL); + assert(info != NULL); SUTestWebServer *server = (__bridge SUTestWebServer*)info; + assert(server != nil); [server accept:*(const CFSocketNativeHandle*)data]; } } @implementation SUTestWebServer +@synthesize connections = _connections; +@synthesize workingDirectory = _workingDirectory; + - (instancetype)initWithPort:(int)port workingDirectory:(NSString*)workingDirectory { self = [super init]; assert(self != nil); @@ -218,30 +232,32 @@ static void connectCallback(CFSocketRef __unused s, CFSocketCallBackType type, C } - (void)connectionDidClose:(SUTestWebServerConnection *)sender { - assert(_connections != nil); - assert([_connections containsObject:sender]); - [_connections removeObject:sender]; + assert(self.connections != nil); + assert([self.connections containsObject:sender]); + [self.connections removeObject:sender]; } - (void)accept:(CFSocketNativeHandle)address { - SUTestWebServerConnection *conn = [[SUTestWebServerConnection alloc] initWithNativeHandle:address workingDirectory:_workingDirectory delegate:self]; + SUTestWebServerConnection *conn = [[SUTestWebServerConnection alloc] initWithNativeHandle:address workingDirectory:self.workingDirectory delegate:self]; assert(conn != nil); if (conn) { - [_connections addObject:conn]; + assert(self.connections != nil); + [self.connections addObject:conn]; } } - (void)close { - for (SUTestWebServerConnection *conn in _connections) { + for (SUTestWebServerConnection *conn in self.connections) { [conn close]; } +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdirect-ivar-access" if (_socket) { CFSocketInvalidate(_socket); CFRelease(_socket); _socket = NULL; } +#pragma clang diagnostic pop } @end - -#pragma clang diagnostic pop