// // MBIMHTTPConnection.m // CocoaHTTPServer // // Created by James Magahern on 11/16/18. // Copyright © 2018 James Magahern. All rights reserved. // #import "MBIMHTTPConnection.h" #import "MBIMBridge.h" #import "MBIMBridge_Private.h" #import "MBIMBridgeOperation.h" #import @implementation MBIMHTTPConnection { NSMutableData *_bodyData; MBIMBridgeOperation *_currentOperation; } - (BOOL)isSecureServer { return [[MBIMBridge sharedInstance] usesSSL]; } - (NSArray *)sslIdentityAndCertificates { return [[MBIMBridge sharedInstance] sslCertificateAndIdentity]; } - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path { if ([method isEqualToString:@"GET"] || [method isEqualToString:@"POST"]) { return YES; } return NO; } - (NSObject *)httpResponseForMethod:(NSString *)method URI:(NSString *)path { __block NSObject *response = nil; dispatch_semaphore_t sema = dispatch_semaphore_create(0); MBIMBridgeOperationCompletionBlock completion = ^(NSObject *incomingResponse) { response = incomingResponse; dispatch_semaphore_signal(sema); }; NSURL *url = [NSURL URLWithString:path]; NSString *endpointName = [url lastPathComponent]; BOOL requestTimedOut = NO; Class operationClass = [MBIMBridgeOperation operationClassForEndpointName:endpointName]; if (operationClass != nil) { _currentOperation = [[operationClass alloc] initWithRequestURL:url completion:completion]; _currentOperation.requestBodyData = _bodyData; [[[MBIMBridge sharedInstance] operationQueue] addOperation:_currentOperation]; long status = dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60.0 * NSEC_PER_SEC))); if (status != 0) { requestTimedOut = YES; } } else { response = [[HTTPErrorResponse alloc] initWithErrorCode:404]; } if (requestTimedOut) { response = [_currentOperation cancelAndReturnTimeoutResponse]; } return response; } - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path { if ([method isEqualToString:@"POST"]) { return YES; } return NO; } - (void)prepareForBodyWithSize:(UInt64)contentLength { _bodyData = [[NSMutableData alloc] initWithCapacity:contentLength]; } - (void)processBodyData:(NSData *)postDataChunk { [_bodyData appendData:postDataChunk]; } - (void)die { [_currentOperation cancel]; [super die]; } @end