diff --git a/Source/NSURLSession.m b/Source/NSURLSession.m index dd47cb6f9..3453458ab 100644 --- a/Source/NSURLSession.m +++ b/Source/NSURLSession.m @@ -1,32 +1,32 @@ /** - NSURLSession.m - - Copyright (C) 2017-2024 Free Software Foundation, Inc. - - Written by: Hugo Melder - Date: May 2024 - Author: Hugo Melder - - This file is part of GNUStep-base - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - If you are interested in a warranty or support for this source code, - contact Scott Christley for more information. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110 USA. -*/ + * NSURLSession.m + * + * Copyright (C) 2017-2024 Free Software Foundation, Inc. + * + * Written by: Hugo Melder + * Date: May 2024 + * Author: Hugo Melder + * + * This file is part of GNUStep-base + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * If you are interested in a warranty or support for this source code, + * contact Scott Christley for more information. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110 USA. + */ #import "NSURLSessionPrivate.h" #import "NSURLSessionTaskPrivate.h" @@ -42,7 +42,7 @@ #import "GSPThread.h" /* For nextSessionIdentifier() */ #import "GSDispatch.h" /* For dispatch compatibility */ -NSString *GS_NSURLSESSION_DEBUG_KEY = @"NSURLSession"; +NSString * GS_NSURLSESSION_DEBUG_KEY = @"NSURLSession"; /* We need a globably unique label for the NSURLSession workQueues. */ @@ -63,15 +63,18 @@ /* CURLMOPT_TIMERFUNCTION: Callback to receive timer requests from libcurl */ static int -timer_callback(CURLM *multi, /* multi handle */ - long timeout_ms, /* timeout in number of ms */ - void *clientp) /* private callback pointer */ +timer_callback(CURLM * multi, /* multi handle */ + long timeout_ms, /* timeout in number of ms */ + void * clientp) /* private callback pointer */ { - NSURLSession *session = (NSURLSession *) clientp; + NSURLSession * session = (NSURLSession *)clientp; - NSDebugLLog(GS_NSURLSESSION_DEBUG_KEY, - @"Timer Callback for Session %@: multi=%p timeout_ms=%ld", - session, multi, timeout_ms); + NSDebugLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"Timer Callback for Session %@: multi=%p timeout_ms=%ld", + session, + multi, + timeout_ms); /* * if timeout_ms is -1, just delete the timer @@ -82,42 +85,46 @@ if (timeout_ms == -1) [session _suspendTimer]; else - [session _setTimer:timeout_ms]; + [session _setTimer: timeout_ms]; return 0; } /* CURLMOPT_SOCKETFUNCTION: libcurl requests socket monitoring using this * callback */ static int -socket_callback(CURL *easy, /* easy handle */ +socket_callback(CURL * easy, /* easy handle */ curl_socket_t s, /* socket */ - int what, /* describes the socket */ - void *clientp, /* private callback pointer */ - void *socketp) /* private socket pointer */ + int what, /* describes the socket */ + void * clientp, /* private callback pointer */ + void * socketp) /* private socket pointer */ { - NSURLSession *session = clientp; - const char *whatstr[] = {"none", "IN", "OUT", "INOUT", "REMOVE"}; + NSURLSession * session = clientp; + const char * whatstr[] = { "none", "IN", "OUT", "INOUT", "REMOVE" }; - NSDebugLLog(GS_NSURLSESSION_DEBUG_KEY, - @"Socket Callback for Session %@: socket=%d easy:%p what=%s", - session, s, easy, whatstr[what]); + NSDebugLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"Socket Callback for Session %@: socket=%d easy:%p what=%s", + session, + s, + easy, + whatstr[what]); if (NULL == socketp) { - return [session _addSocket:s easyHandle:easy what:what]; + return [session _addSocket: s easyHandle: easy what: what]; } else if (CURL_POLL_REMOVE == what) { - [session _removeSocket:(struct SourceInfo *) socketp]; + [session _removeSocket: (struct SourceInfo *)socketp]; return 0; } else { - return [session _setSocket:s - sources:(struct SourceInfo *) socketp - what:what]; + return [session _setSocket: s + sources: (struct SourceInfo *)socketp + what: what]; } -} +} /* socket_callback */ #pragma mark - NSURLSession Implementation @@ -130,7 +137,7 @@ @implementation NSURLSession * Event creation and deletion is driven by the various callbacks * registered during initialisation of the multi handle. */ - CURLM *_multiHandle; + CURLM * _multiHandle; /* A serial work queue for timer and socket sources * created on libcurl's behalf. */ @@ -165,15 +172,15 @@ @implementation NSURLSession /* List of active tasks. Access is synchronised via the _workQueue. */ - NSMutableArray *_tasks; + NSMutableArray * _tasks; /* PEM encoded blob of one or more certificates. * * See GSCACertificateFilePath in NSUserDefaults.h */ - NSData *_certificateBlob; + NSData * _certificateBlob; /* Path to PEM encoded CA certificate file. */ - NSString *_certificatePath; + NSString * _certificatePath; /* The task identifier for the next task */ @@ -183,59 +190,62 @@ @implementation NSURLSession gs_mutex_t _taskLock; } -+ (NSURLSession *)sharedSession ++ (NSURLSession *) sharedSession { - static NSURLSession *session = nil; + static NSURLSession * session = nil; static dispatch_once_t predicate; - dispatch_once(&predicate, ^{ - NSURLSessionConfiguration *configuration = + dispatch_once( + &predicate, + ^{ + NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; - session = [[NSURLSession alloc] initWithConfiguration:configuration - delegate:nil - delegateQueue:nil]; - [session _setSharedSession:YES]; + session = [[NSURLSession alloc] initWithConfiguration: configuration + delegate: nil + delegateQueue: nil]; + [session _setSharedSession: YES]; }); return session; } -+ (NSURLSession *)sessionWithConfiguration: ++ (NSURLSession *) sessionWithConfiguration: (NSURLSessionConfiguration *)configuration { - NSURLSession *session; + NSURLSession * session; - session = [[NSURLSession alloc] initWithConfiguration:configuration - delegate:nil - delegateQueue:nil]; + session = [[NSURLSession alloc] initWithConfiguration: configuration + delegate: nil + delegateQueue: nil]; return AUTORELEASE(session); } -+ (NSURLSession *)sessionWithConfiguration: - (NSURLSessionConfiguration *)configuration - delegate:(id)delegate - delegateQueue:(NSOperationQueue *)queue ++ (NSURLSession *) sessionWithConfiguration: + (NSURLSessionConfiguration *)configuration + delegate: (id)delegate + delegateQueue: (NSOperationQueue *)queue { - NSURLSession *session; + NSURLSession * session; - session = [[NSURLSession alloc] initWithConfiguration:configuration - delegate:delegate - delegateQueue:queue]; + session = [[NSURLSession alloc] initWithConfiguration: configuration + delegate: delegate + delegateQueue: queue]; return AUTORELEASE(session); } -- (instancetype)initWithConfiguration:(NSURLSessionConfiguration *)configuration - delegate:(id)delegate - delegateQueue:(NSOperationQueue *)queue +- (instancetype) initWithConfiguration: (NSURLSessionConfiguration *) + configuration + delegate: (id)delegate + delegateQueue: (NSOperationQueue *)queue { self = [super init]; if (self) { - NSString *queueLabel; - NSString *caPath; + NSString * queueLabel; + NSString * caPath; NSUInteger sessionIdentifier; /* To avoid a retain cycle in blocks referencing this object */ @@ -243,8 +253,8 @@ - (instancetype)initWithConfiguration:(NSURLSessionConfiguration *)configuration sessionIdentifier = nextSessionIdentifier(); queueLabel = [[NSString alloc] - initWithFormat:@"org.gnustep.NSURLSession.WorkQueue%ld", - sessionIdentifier]; + initWithFormat: @"org.gnustep.NSURLSession.WorkQueue%ld", + sessionIdentifier]; ASSIGN(_delegate, delegate); ASSIGNCOPY(_configuration, configuration); @@ -266,17 +276,24 @@ - (instancetype)initWithConfiguration:(NSURLSessionConfiguration *)configuration return nil; } - dispatch_source_set_cancel_handler(_timer, ^{ - dispatch_release(this->_timer); - }); + dispatch_source_set_cancel_handler( + _timer, + ^{ + dispatch_release(this->_timer); + }); // Called after timeout set by libcurl is reached - dispatch_source_set_event_handler(_timer, ^{ - // TODO: Check for return values - curl_multi_socket_action(this->_multiHandle, CURL_SOCKET_TIMEOUT, 0, - &this->_stillRunning); - [this _checkForCompletion]; - }); + dispatch_source_set_event_handler( + _timer, + ^{ + // TODO: Check for return values + curl_multi_socket_action( + this->_multiHandle, + CURL_SOCKET_TIMEOUT, + 0, + &this->_stillRunning); + [this _checkForCompletion]; + }); /* Use the provided delegateQueue if available */ if (queue) @@ -289,7 +306,7 @@ - (instancetype)initWithConfiguration:(NSURLSessionConfiguration *)configuration * delegate callbacks and is orthogonal to the workQueue. */ _delegateQueue = [[NSOperationQueue alloc] init]; - [_delegateQueue setMaxConcurrentOperationCount:1]; + [_delegateQueue setMaxConcurrentOperationCount: 1]; } /* libcurl Configuration */ @@ -304,25 +321,28 @@ - (instancetype)initWithConfiguration:(NSURLSessionConfiguration *)configuration curl_multi_setopt(_multiHandle, CURLMOPT_TIMERDATA, self); // Configure Multi Handle - curl_multi_setopt(_multiHandle, CURLMOPT_MAX_HOST_CONNECTIONS, - [_configuration HTTPMaximumConnectionsPerHost]); + curl_multi_setopt( + _multiHandle, + CURLMOPT_MAX_HOST_CONNECTIONS, + [_configuration HTTPMaximumConnectionsPerHost]); /* Check if GSCACertificateFilePath is set */ caPath = [[NSUserDefaults standardUserDefaults] - objectForKey:GSCACertificateFilePath]; + objectForKey: GSCACertificateFilePath]; if (caPath) { NSDebugMLLog( GS_NSURLSESSION_DEBUG_KEY, @"Found a GSCACertificateFilePath entry in UserDefaults"); - _certificateBlob = [[NSData alloc] initWithContentsOfFile:caPath]; + _certificateBlob = [[NSData alloc] initWithContentsOfFile: caPath]; if (!_certificateBlob) { - NSDebugMLLog(GS_NSURLSESSION_DEBUG_KEY, - @"Could not open file at GSCACertificateFilePath=%@", - caPath); + NSDebugMLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"Could not open file at GSCACertificateFilePath=%@", + caPath); } else { @@ -332,26 +352,26 @@ - (instancetype)initWithConfiguration:(NSURLSessionConfiguration *)configuration } return self; -} +} /* initWithConfiguration */ #pragma mark - Private Methods -- (NSData *)_certificateBlob +- (NSData *) _certificateBlob { return _certificateBlob; } -- (NSString *)_certificatePath +- (NSString *) _certificatePath { return _certificatePath; } -- (void)_setSharedSession:(BOOL)flag +- (void) _setSharedSession: (BOOL)flag { _isSharedSession = flag; } -- (NSInteger)_nextTaskIdentifier +- (NSInteger) _nextTaskIdentifier { NSInteger identifier; @@ -363,36 +383,44 @@ - (NSInteger)_nextTaskIdentifier return identifier; } -- (void)_resumeTask:(NSURLSessionTask *)task +- (void) _resumeTask: (NSURLSessionTask *)task { - dispatch_async(_workQueue, ^{ + dispatch_async( + _workQueue, + ^{ CURLMcode code; - CURLM *multiHandle = _multiHandle; + CURLM * multiHandle = _multiHandle; code = curl_multi_add_handle(multiHandle, [task _easyHandle]); - NSDebugMLLog(GS_NSURLSESSION_DEBUG_KEY, - @"Added task=%@ easy=%p to multi=%p with return value %d", - task, [task _easyHandle], multiHandle, code); + NSDebugMLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"Added task=%@ easy=%p to multi=%p with return value %d", + task, + [task _easyHandle], + multiHandle, + code); }); } -- (void)_addHandle:(CURL *)easy +- (void) _addHandle: (CURL *)easy { curl_multi_add_handle(_multiHandle, easy); } -- (void)_removeHandle:(CURL *)easy +- (void) _removeHandle: (CURL *)easy { curl_multi_remove_handle(_multiHandle, easy); } -- (void)_setTimer:(NSInteger)timeoutMs +- (void) _setTimer: (NSInteger)timeoutMs { - dispatch_source_set_timer(_timer, - dispatch_time(DISPATCH_TIME_NOW, - timeoutMs * NSEC_PER_MSEC), - DISPATCH_TIME_FOREVER, // don't repeat - timeoutMs * 0.05); // 5% leeway + dispatch_source_set_timer( + _timer, + dispatch_time( + DISPATCH_TIME_NOW, + timeoutMs * NSEC_PER_MSEC), + DISPATCH_TIME_FOREVER, // don't repeat + timeoutMs * 0.05); // 5% leeway if (_isTimerSuspended) { @@ -401,7 +429,7 @@ - (void)_setTimer:(NSInteger)timeoutMs } } -- (void)_suspendTimer +- (void) _suspendTimer { if (!_isTimerSuspended) { @@ -410,19 +438,21 @@ - (void)_suspendTimer } } -- (dispatch_queue_t)_workQueue +- (dispatch_queue_t) _workQueue { return _workQueue; } /* This method is called when receiving CURL_POLL_REMOVE in socket_callback. * We cancel all active dispatch sources and release the SourceInfo structure - * previously allocated in _addSocket:easyHandle:what: + * previously allocated in _addSocket: easyHandle: what: */ -- (void)_removeSocket:(struct SourceInfo *)sources +- (void) _removeSocket: (struct SourceInfo *)sources { - NSDebugMLLog(GS_NSURLSESSION_DEBUG_KEY, @"Remove socket with SourceInfo: %p", - sources); + NSDebugMLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"Remove socket with SourceInfo: %p", + sources); if (sources->readSocket) { @@ -442,23 +472,28 @@ - (void)_removeSocket:(struct SourceInfo *)sources * (socketp) in socket_callback is NULL, meaning we first need to * allocate our SourceInfo structure. */ -- (int)_addSocket:(curl_socket_t)socket easyHandle:(CURL *)easy what:(int)what +- (int) _addSocket: (curl_socket_t)socket easyHandle: (CURL *)easy what: (int) + what { - struct SourceInfo *info; + struct SourceInfo * info; - NSDebugMLLog(GS_NSURLSESSION_DEBUG_KEY, @"Add Socket: %d easy: %p", socket, - easy); + NSDebugMLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"Add Socket: %d easy: %p", + socket, + easy); /* Allocate a new SourceInfo structure on the heap */ if (!(info = calloc(1, sizeof(struct SourceInfo)))) { - NSDebugMLLog(GS_NSURLSESSION_DEBUG_KEY, - @"Failed to allocate SourceInfo structure!"); + NSDebugMLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"Failed to allocate SourceInfo structure!"); return -1; } /* We can now configure the dispatch sources */ - if (-1 == [self _setSocket:socket sources:info what:what]) + if (-1 == [self _setSocket: socket sources: info what: what]) { NSDebugMLLog(GS_NSURLSESSION_DEBUG_KEY, @"Failed to setup sockets!"); return -1; @@ -466,11 +501,11 @@ - (int)_addSocket:(curl_socket_t)socket easyHandle:(CURL *)easy what:(int)what /* Assign the SourceInfo for access in subsequent socket_callback calls */ curl_multi_assign(_multiHandle, socket, info); return 0; -} +} /* _addSocket */ -- (int)_setSocket:(curl_socket_t)socket - sources:(struct SourceInfo *)sources - what:(int)what +- (int) _setSocket: (curl_socket_t)socket + sources: (struct SourceInfo *)sources + what: (int)what { /* Create a Reading Dispatch Source that listens on socket */ if (CURL_POLL_IN == what || CURL_POLL_INOUT == what) @@ -486,30 +521,38 @@ - (int)_setSocket:(curl_socket_t)socket NSDebugMLLog( GS_NSURLSESSION_DEBUG_KEY, @"Creating a reading dispatch source: socket=%d sources=%p what=%d", - socket, sources, what); - - sources->readSocket = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, - socket, 0, _workQueue); + socket, + sources, + what); + + sources->readSocket = dispatch_source_create( + DISPATCH_SOURCE_TYPE_READ, + socket, + 0, + _workQueue); if (!sources->readSocket) { - NSDebugMLLog(GS_NSURLSESSION_DEBUG_KEY, - @"Unable to create dispatch source for read socket!"); + NSDebugMLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"Unable to create dispatch source for read socket!"); return -1; } - dispatch_source_set_event_handler(sources->readSocket, ^{ - int action; - - action = CURL_CSELECT_IN; - curl_multi_socket_action(_multiHandle, socket, action, &_stillRunning); - - /* Check if the transfer is complete */ - [self _checkForCompletion]; - /* When _stillRunning reaches zero, all transfers are complete/done */ - if (_stillRunning <= 0) - { - [self _suspendTimer]; - } - }); + dispatch_source_set_event_handler( + sources->readSocket, + ^{ + int action; + + action = CURL_CSELECT_IN; + curl_multi_socket_action(_multiHandle, socket, action, &_stillRunning); + + /* Check if the transfer is complete */ + [self _checkForCompletion]; + /* When _stillRunning reaches zero, all transfers are complete/done */ + if (_stillRunning <= 0) + { + [self _suspendTimer]; + } + }); dispatch_resume(sources->readSocket); } @@ -528,51 +571,59 @@ - (int)_setSocket:(curl_socket_t)socket NSDebugMLLog( GS_NSURLSESSION_DEBUG_KEY, @"Creating a writing dispatch source: socket=%d sources=%p what=%d", - socket, sources, what); - - sources->writeSocket = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, - socket, 0, _workQueue); + socket, + sources, + what); + + sources->writeSocket = dispatch_source_create( + DISPATCH_SOURCE_TYPE_WRITE, + socket, + 0, + _workQueue); if (!sources->writeSocket) { - NSDebugMLLog(GS_NSURLSESSION_DEBUG_KEY, - @"Unable to create dispatch source for write socket!"); + NSDebugMLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"Unable to create dispatch source for write socket!"); return -1; } - dispatch_source_set_event_handler(sources->writeSocket, ^{ - int action; + dispatch_source_set_event_handler( + sources->writeSocket, + ^{ + int action; - action = CURL_CSELECT_OUT; - curl_multi_socket_action(_multiHandle, socket, action, &_stillRunning); + action = CURL_CSELECT_OUT; + curl_multi_socket_action(_multiHandle, socket, action, &_stillRunning); - /* Check if the tranfer is complete */ - [self _checkForCompletion]; + /* Check if the tranfer is complete */ + [self _checkForCompletion]; - /* When _stillRunning reaches zero, all transfers are complete/done */ - if (_stillRunning <= 0) - { - [self _suspendTimer]; - } - }); + /* When _stillRunning reaches zero, all transfers are complete/done */ + if (_stillRunning <= 0) + { + [self _suspendTimer]; + } + }); dispatch_resume(sources->writeSocket); } return 0; -} +} /* _setSocket */ /* Called by a socket event handler or by a firing timer set by timer_callback. * * The socket event handler is executed on the _workQueue. */ -- (void)_checkForCompletion +- (void) _checkForCompletion { - CURLMsg *msg; - int msgs_left; - CURL *easyHandle; - CURLcode res; - char *eff_url = NULL; - NSURLSessionTask *task = nil; + CURLMsg * msg; + int msgs_left; + CURL * easyHandle; + CURLcode res; + char * eff_url = NULL; + NSURLSessionTask * task = nil; /* Ask the multi handle if there are any messages from the individual * transfers. @@ -592,10 +643,11 @@ - (void)_checkForCompletion rc = curl_easy_getinfo(easyHandle, CURLINFO_PRIVATE, &task); if (CURLE_OK != rc) { - NSDebugMLLog(GS_NSURLSESSION_DEBUG_KEY, - @"Failed to retrieve task from easy handle %p using " - @"CURLINFO_PRIVATE", - easyHandle); + NSDebugMLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"Failed to retrieve task from easy handle %p using " + @"CURLINFO_PRIVATE", + easyHandle); } rc = curl_easy_getinfo(easyHandle, CURLINFO_EFFECTIVE_URL, &eff_url); if (CURLE_OK != rc) @@ -607,10 +659,13 @@ - (void)_checkForCompletion easyHandle); } - NSDebugMLLog(GS_NSURLSESSION_DEBUG_KEY, - @"Transfer finished for Task %@ with effective url %s " - @"and CURLcode: %s", - task, eff_url, curl_easy_strerror(res)); + NSDebugMLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"Transfer finished for Task %@ with effective url %s " + @"and CURLcode: %s", + task, + eff_url, + curl_easy_strerror(res)); curl_multi_remove_handle(_multiHandle, easyHandle); @@ -619,296 +674,308 @@ - (void)_checkForCompletion RETAIN(self); RETAIN(task); - [_tasks removeObject:task]; - [task _transferFinishedWithCode:res]; + [_tasks removeObject: task]; + [task _transferFinishedWithCode: res]; RELEASE(task); - /* Send URLSession:didBecomeInvalidWithError: to delegate if this + /* Send URLSession: didBecomeInvalidWithError: to delegate if this * session was invalidated */ if (_invalidated && [_tasks count] == 0 && - [_delegate respondsToSelector:@selector(URLSession: - didBecomeInvalidWithError:)]) + [_delegate respondsToSelector: @selector(URLSession: + didBecomeInvalidWithError + :)]) { [_delegateQueue addOperationWithBlock:^{ - /* We only support explicit Invalidation for now. Error is set - * to nil in this case. */ - [_delegate URLSession:self didBecomeInvalidWithError:nil]; - }]; + /* We only support explicit Invalidation for now. Error is set + * to nil in this case. */ + [_delegate URLSession: self didBecomeInvalidWithError: nil]; + }]; } RELEASE(self); } } -} +} /* _checkForCompletion */ /* Adds task to _tasks and updates the delegate */ -- (void)_didCreateTask:(NSURLSessionTask *)task +- (void) _didCreateTask: (NSURLSessionTask *)task { - dispatch_async(_workQueue, ^{ - [_tasks addObject:task]; + dispatch_async( + _workQueue, + ^{ + [_tasks addObject: task]; }); - if ([_delegate respondsToSelector:@selector(URLSession:didCreateTask:)]) + if ([_delegate respondsToSelector: @selector(URLSession:didCreateTask:)]) { [_delegateQueue addOperationWithBlock:^{ - [(id) _delegate URLSession:self - didCreateTask:task]; - }]; + [(id) _delegate URLSession: self + didCreateTask : task]; + }]; } } #pragma mark - Public API -- (void)finishTasksAndInvalidate +- (void) finishTasksAndInvalidate { if (_isSharedSession) { return; } - dispatch_async(_workQueue, ^{ + dispatch_async( + _workQueue, + ^{ _invalidated = YES; }); } -- (void)invalidateAndCancel +- (void) invalidateAndCancel { if (_isSharedSession) { return; } - dispatch_async(_workQueue, ^{ + dispatch_async( + _workQueue, + ^{ _invalidated = YES; /* Cancel all tasks */ - for (NSURLSessionTask *task in _tasks) - { - [task cancel]; - } + for (NSURLSessionTask * task in _tasks) + { + [task cancel]; + } }); } -- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request +- (NSURLSessionDataTask *) dataTaskWithRequest: (NSURLRequest *)request { - NSURLSessionDataTask *task; - NSInteger identifier; + NSURLSessionDataTask * task; + NSInteger identifier; identifier = [self _nextTaskIdentifier]; - task = [[NSURLSessionDataTask alloc] initWithSession:self - request:request - taskIdentifier:identifier]; + task = [[NSURLSessionDataTask alloc] initWithSession: self + request: request + taskIdentifier: identifier]; /* We use the session delegate by default. NSURLSessionTaskDelegate * is a purely optional protocol. */ - [task setDelegate:(id) _delegate]; + [task setDelegate: (id)_delegate]; - [task _setProperties:GSURLSessionUpdatesDelegate]; + [task _setProperties: GSURLSessionUpdatesDelegate]; - [self _didCreateTask:task]; + [self _didCreateTask: task]; return AUTORELEASE(task); } -- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url +- (NSURLSessionDataTask *) dataTaskWithURL: (NSURL *)url { - NSURLRequest *request; + NSURLRequest * request; - request = [NSURLRequest requestWithURL:url]; - return [self dataTaskWithRequest:request]; + request = [NSURLRequest requestWithURL: url]; + return [self dataTaskWithRequest: request]; } -- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - fromFile:(NSURL *)fileURL +- (NSURLSessionUploadTask *) uploadTaskWithRequest: (NSURLRequest *)request + fromFile: (NSURL *)fileURL { - NSURLSessionUploadTask *task; - NSInputStream *stream; - NSInteger identifier; + NSURLSessionUploadTask * task; + NSInputStream * stream; + NSInteger identifier; identifier = [self _nextTaskIdentifier]; - stream = [NSInputStream inputStreamWithURL:fileURL]; - task = [[NSURLSessionUploadTask alloc] initWithSession:self - request:request - taskIdentifier:identifier]; + stream = [NSInputStream inputStreamWithURL: fileURL]; + task = [[NSURLSessionUploadTask alloc] initWithSession: self + request: request + taskIdentifier: identifier]; /* We use the session delegate by default. NSURLSessionTaskDelegate * is a purely optional protocol. */ - [task setDelegate:(id) _delegate]; + [task setDelegate: (id)_delegate]; [task - _setProperties:GSURLSessionUpdatesDelegate | GSURLSessionHasInputStream]; - [task _setBodyStream:stream]; - [task _enableUploadWithSize:0]; + _setProperties: GSURLSessionUpdatesDelegate | GSURLSessionHasInputStream]; + [task _setBodyStream: stream]; + [task _enableUploadWithSize: 0]; - [self _didCreateTask:task]; + [self _didCreateTask: task]; return AUTORELEASE(task); -} +} /* uploadTaskWithRequest */ -- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - fromData:(NSData *)bodyData +- (NSURLSessionUploadTask *) uploadTaskWithRequest: (NSURLRequest *)request + fromData: (NSData *)bodyData { - NSURLSessionUploadTask *task; - NSInteger identifier; + NSURLSessionUploadTask * task; + NSInteger identifier; identifier = [self _nextTaskIdentifier]; - task = [[NSURLSessionUploadTask alloc] initWithSession:self - request:request - taskIdentifier:identifier]; + task = [[NSURLSessionUploadTask alloc] initWithSession: self + request: request + taskIdentifier: identifier]; /* We use the session delegate by default. NSURLSessionTaskDelegate * is a purely optional protocol. */ - [task setDelegate:(id) _delegate]; - [task _setProperties:GSURLSessionUpdatesDelegate]; - [task _enableUploadWithData:bodyData]; + [task setDelegate: (id)_delegate]; + [task _setProperties: GSURLSessionUpdatesDelegate]; + [task _enableUploadWithData: bodyData]; - [self _didCreateTask:task]; + [self _didCreateTask: task]; return AUTORELEASE(task); } -- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest: +- (NSURLSessionUploadTask *) uploadTaskWithStreamedRequest: (NSURLRequest *)request { - NSURLSessionUploadTask *task; - NSInteger identifier; + NSURLSessionUploadTask * task; + NSInteger identifier; identifier = [self _nextTaskIdentifier]; - task = [[NSURLSessionUploadTask alloc] initWithSession:self - request:request - taskIdentifier:identifier]; + task = [[NSURLSessionUploadTask alloc] initWithSession: self + request: request + taskIdentifier: identifier]; /* We use the session delegate by default. NSURLSessionTaskDelegate * is a purely optional protocol. */ - [task setDelegate:(id) _delegate]; + [task setDelegate: (id)_delegate]; [task - _setProperties:GSURLSessionUpdatesDelegate | GSURLSessionHasInputStream]; - [task _enableUploadWithSize:0]; + _setProperties: GSURLSessionUpdatesDelegate | GSURLSessionHasInputStream]; + [task _enableUploadWithSize: 0]; - [self _didCreateTask:task]; + [self _didCreateTask: task]; return AUTORELEASE(task); } -- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request +- (NSURLSessionDownloadTask *) downloadTaskWithRequest: (NSURLRequest *)request { - NSURLSessionDownloadTask *task; - NSInteger identifier; + NSURLSessionDownloadTask * task; + NSInteger identifier; identifier = [self _nextTaskIdentifier]; - task = [[NSURLSessionDownloadTask alloc] initWithSession:self - request:request - taskIdentifier:identifier]; + task = [[NSURLSessionDownloadTask alloc] initWithSession: self + request: request + taskIdentifier: identifier]; /* We use the session delegate by default. NSURLSessionTaskDelegate * is a purely optional protocol. */ - [task setDelegate:(id) _delegate]; + [task setDelegate: (id)_delegate]; [task - _setProperties:GSURLSessionWritesDataToFile | GSURLSessionUpdatesDelegate]; + _setProperties: GSURLSessionWritesDataToFile | GSURLSessionUpdatesDelegate]; - [self _didCreateTask:task]; + [self _didCreateTask: task]; return AUTORELEASE(task); } -- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url +- (NSURLSessionDownloadTask *) downloadTaskWithURL: (NSURL *)url { - NSURLRequest *request; + NSURLRequest * request; - request = [NSURLRequest requestWithURL:url]; - return [self downloadTaskWithRequest:request]; + request = [NSURLRequest requestWithURL: url]; + return [self downloadTaskWithRequest: request]; } -- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData +- (NSURLSessionDownloadTask *) downloadTaskWithResumeData: (NSData *)resumeData { - return [self notImplemented:_cmd]; + return [self notImplemented: _cmd]; } -- (void)getTasksWithCompletionHandler: - (void (^)(NSArray *dataTasks, - NSArray *uploadTasks, - NSArray *downloadTasks)) - completionHandler +- (void) getTasksWithCompletionHandler: + (void (^)( + NSArray * dataTasks, + NSArray * uploadTasks, + NSArray * downloadTasks)) + completionHandler { - dispatch_async(_workQueue, ^{ - NSMutableArray *dataTasks; - NSMutableArray *uploadTasks; - NSMutableArray *downloadTasks; - NSInteger numberOfTasks; + dispatch_async( + _workQueue, + ^{ + NSMutableArray * dataTasks; + NSMutableArray * uploadTasks; + NSMutableArray * downloadTasks; + NSInteger numberOfTasks; Class dataTaskClass; Class uploadTaskClass; Class downloadTaskClass; numberOfTasks = [_tasks count]; - dataTasks = [NSMutableArray arrayWithCapacity:numberOfTasks / 2]; - uploadTasks = [NSMutableArray arrayWithCapacity:numberOfTasks / 2]; - downloadTasks = [NSMutableArray arrayWithCapacity:numberOfTasks / 2]; + dataTasks = [NSMutableArray arrayWithCapacity: numberOfTasks / 2]; + uploadTasks = [NSMutableArray arrayWithCapacity: numberOfTasks / 2]; + downloadTasks = [NSMutableArray arrayWithCapacity: numberOfTasks / 2]; dataTaskClass = [NSURLSessionDataTask class]; uploadTaskClass = [NSURLSessionUploadTask class]; downloadTaskClass = [NSURLSessionDownloadTask class]; - for (NSURLSessionTask *task in _tasks) + for (NSURLSessionTask * task in _tasks) + { + if ([task isKindOfClass: dataTaskClass]) + { + [dataTasks addObject: (NSURLSessionDataTask *)task]; + } + else if ([task isKindOfClass: uploadTaskClass]) + { + [uploadTasks addObject: (NSURLSessionUploadTask *)task]; + } + else if ([task isKindOfClass: downloadTaskClass]) { - if ([task isKindOfClass:dataTaskClass]) - { - [dataTasks addObject:(NSURLSessionDataTask *) task]; - } - else if ([task isKindOfClass:uploadTaskClass]) - { - [uploadTasks addObject:(NSURLSessionUploadTask *) task]; - } - else if ([task isKindOfClass:downloadTaskClass]) - { - [downloadTasks addObject:(NSURLSessionDownloadTask *) task]; - } + [downloadTasks addObject: (NSURLSessionDownloadTask *)task]; } + } completionHandler(dataTasks, uploadTasks, downloadTasks); }); -} +} /* getTasksWithCompletionHandler */ -- (void)getAllTasksWithCompletionHandler: - (void (^)(NSArray<__kindof NSURLSessionTask *> *tasks))completionHandler +- (void) getAllTasksWithCompletionHandler: + (void (^)(NSArray<__kindof NSURLSessionTask *> * tasks))completionHandler { - dispatch_async(_workQueue, ^{ + dispatch_async( + _workQueue, + ^{ completionHandler(_tasks); }); } #pragma mark - Getter and Setter -- (NSOperationQueue *)delegateQueue +- (NSOperationQueue *) delegateQueue { return _delegateQueue; } -- (id)delegate +- (id) delegate { return _delegate; } -- (NSURLSessionConfiguration *)configuration +- (NSURLSessionConfiguration *) configuration { return AUTORELEASE([_configuration copy]); } -- (NSString *)sessionDescription +- (NSString *) sessionDescription { return _sessionDescription; } -- (void)setSessionDescription:(NSString *)sessionDescription +- (void) setSessionDescription: (NSString *)sessionDescription { ASSIGNCOPY(_sessionDescription, sessionDescription); } -- (void)dealloc +- (void) dealloc { RELEASE(_delegateQueue); RELEASE(_delegate); @@ -919,7 +986,7 @@ - (void)dealloc curl_multi_cleanup(_multiHandle); -#if defined(HAVE_DISPATCH_CANCEL) +#if defined(HAVE_DISPATCH_CANCEL) dispatch_cancel(_timer); #else dispatch_source_cancel(_timer); @@ -935,131 +1002,131 @@ - (void)dealloc NSURLSession (NSURLSessionAsynchronousConvenience) - (NSURLSessionDataTask *) - dataTaskWithRequest:(NSURLRequest *)request - completionHandler:(GSNSURLSessionDataCompletionHandler)completionHandler + dataTaskWithRequest: (NSURLRequest *)request + completionHandler: (GSNSURLSessionDataCompletionHandler)completionHandler { - NSURLSessionDataTask *task; - NSInteger identifier; + NSURLSessionDataTask * task; + NSInteger identifier; identifier = [self _nextTaskIdentifier]; - task = [[NSURLSessionDataTask alloc] initWithSession:self - request:request - taskIdentifier:identifier]; - [task setDelegate:(id) _delegate]; - [task _setCompletionHandler:completionHandler]; - [task _enableAutomaticRedirects:YES]; - [task _setProperties:GSURLSessionStoresDataInMemory | - GSURLSessionHasCompletionHandler]; + task = [[NSURLSessionDataTask alloc] initWithSession: self + request: request + taskIdentifier: identifier]; + [task setDelegate: (id)_delegate]; + [task _setCompletionHandler: completionHandler]; + [task _enableAutomaticRedirects: YES]; + [task _setProperties: GSURLSessionStoresDataInMemory | + GSURLSessionHasCompletionHandler]; - [self _didCreateTask:task]; + [self _didCreateTask: task]; return AUTORELEASE(task); } -- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url - completionHandler: - (GSNSURLSessionDataCompletionHandler)completionHandler +- (NSURLSessionDataTask *) dataTaskWithURL: (NSURL *)url + completionHandler: + (GSNSURLSessionDataCompletionHandler)completionHandler { - NSURLRequest *request = [NSURLRequest requestWithURL:url]; + NSURLRequest * request = [NSURLRequest requestWithURL: url]; - return [self dataTaskWithRequest:request completionHandler:completionHandler]; + return [self dataTaskWithRequest: request completionHandler: completionHandler]; } - (NSURLSessionUploadTask *) - uploadTaskWithRequest:(NSURLRequest *)request - fromFile:(NSURL *)fileURL - completionHandler:(GSNSURLSessionDataCompletionHandler)completionHandler + uploadTaskWithRequest: (NSURLRequest *)request + fromFile: (NSURL *)fileURL + completionHandler: (GSNSURLSessionDataCompletionHandler)completionHandler { - NSURLSessionUploadTask *task; - NSInputStream *stream; - NSInteger identifier; + NSURLSessionUploadTask * task; + NSInputStream * stream; + NSInteger identifier; identifier = [self _nextTaskIdentifier]; - stream = [NSInputStream inputStreamWithURL:fileURL]; - task = [[NSURLSessionUploadTask alloc] initWithSession:self - request:request - taskIdentifier:identifier]; - [task setDelegate:(id) _delegate]; - - [task _setProperties:GSURLSessionStoresDataInMemory - | GSURLSessionHasInputStream | - GSURLSessionHasCompletionHandler]; - [task _setCompletionHandler:completionHandler]; - [task _enableAutomaticRedirects:YES]; - [task _setBodyStream:stream]; - [task _enableUploadWithSize:0]; - - [self _didCreateTask:task]; + stream = [NSInputStream inputStreamWithURL: fileURL]; + task = [[NSURLSessionUploadTask alloc] initWithSession: self + request: request + taskIdentifier: identifier]; + [task setDelegate: (id)_delegate]; + + [task _setProperties: GSURLSessionStoresDataInMemory + | GSURLSessionHasInputStream | + GSURLSessionHasCompletionHandler]; + [task _setCompletionHandler: completionHandler]; + [task _enableAutomaticRedirects: YES]; + [task _setBodyStream: stream]; + [task _enableUploadWithSize: 0]; + + [self _didCreateTask: task]; return AUTORELEASE(task); -} +} /* uploadTaskWithRequest */ - (NSURLSessionUploadTask *) - uploadTaskWithRequest:(NSURLRequest *)request - fromData:(NSData *)bodyData - completionHandler:(GSNSURLSessionDataCompletionHandler)completionHandler + uploadTaskWithRequest: (NSURLRequest *)request + fromData: (NSData *)bodyData + completionHandler: (GSNSURLSessionDataCompletionHandler)completionHandler { - NSURLSessionUploadTask *task; - NSInteger identifier; + NSURLSessionUploadTask * task; + NSInteger identifier; identifier = [self _nextTaskIdentifier]; - task = [[NSURLSessionUploadTask alloc] initWithSession:self - request:request - taskIdentifier:identifier]; - [task setDelegate:(id) _delegate]; + task = [[NSURLSessionUploadTask alloc] initWithSession: self + request: request + taskIdentifier: identifier]; + [task setDelegate: (id)_delegate]; - [task _setProperties:GSURLSessionStoresDataInMemory | - GSURLSessionHasCompletionHandler]; - [task _setCompletionHandler:completionHandler]; - [task _enableAutomaticRedirects:YES]; - [task _enableUploadWithData:bodyData]; + [task _setProperties: GSURLSessionStoresDataInMemory | + GSURLSessionHasCompletionHandler]; + [task _setCompletionHandler: completionHandler]; + [task _enableAutomaticRedirects: YES]; + [task _enableUploadWithData: bodyData]; - [self _didCreateTask:task]; + [self _didCreateTask: task]; return AUTORELEASE(task); } -- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request - completionHandler: - (GSNSURLSessionDownloadCompletionHandler) - completionHandler +- (NSURLSessionDownloadTask *) downloadTaskWithRequest: (NSURLRequest *)request + completionHandler: + (GSNSURLSessionDownloadCompletionHandler) + completionHandler { - NSURLSessionDownloadTask *task; - NSInteger identifier; + NSURLSessionDownloadTask * task; + NSInteger identifier; identifier = [self _nextTaskIdentifier]; - task = [[NSURLSessionDownloadTask alloc] initWithSession:self - request:request - taskIdentifier:identifier]; + task = [[NSURLSessionDownloadTask alloc] initWithSession: self + request: request + taskIdentifier: identifier]; - [task setDelegate:(id) _delegate]; + [task setDelegate: (id)_delegate]; - [task _setProperties:GSURLSessionWritesDataToFile | - GSURLSessionHasCompletionHandler]; - [task _enableAutomaticRedirects:YES]; - [task _setCompletionHandler:completionHandler]; + [task _setProperties: GSURLSessionWritesDataToFile | + GSURLSessionHasCompletionHandler]; + [task _enableAutomaticRedirects: YES]; + [task _setCompletionHandler: completionHandler]; - [self _didCreateTask:task]; + [self _didCreateTask: task]; return AUTORELEASE(task); } - (NSURLSessionDownloadTask *) - downloadTaskWithURL:(NSURL *)url - completionHandler:(GSNSURLSessionDownloadCompletionHandler)completionHandler + downloadTaskWithURL: (NSURL *)url + completionHandler: (GSNSURLSessionDownloadCompletionHandler)completionHandler { - NSURLRequest *request = [NSURLRequest requestWithURL:url]; + NSURLRequest * request = [NSURLRequest requestWithURL: url]; - return [self downloadTaskWithRequest:request - completionHandler:completionHandler]; + return [self downloadTaskWithRequest: request + completionHandler: completionHandler]; } - (NSURLSessionDownloadTask *) - downloadTaskWithResumeData:(NSData *)resumeData - completionHandler: - (GSNSURLSessionDownloadCompletionHandler)completionHandler + downloadTaskWithResumeData: (NSData *)resumeData + completionHandler: + (GSNSURLSessionDownloadCompletionHandler)completionHandler { - return [self notImplemented:_cmd]; + return [self notImplemented: _cmd]; } @end diff --git a/Source/NSURLSessionConfiguration.m b/Source/NSURLSessionConfiguration.m index 49068389b..3de770538 100644 --- a/Source/NSURLSessionConfiguration.m +++ b/Source/NSURLSessionConfiguration.m @@ -1,32 +1,32 @@ /** - NSURLSessionConfiguration.m - - Copyright (C) 2017-2024 Free Software Foundation, Inc. - - Written by: Hugo Melder - Date: May 2024 - Author: Hugo Melder - - This file is part of GNUStep-base - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - If you are interested in a warranty or support for this source code, - contact Scott Christley for more information. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110 USA. -*/ + * NSURLSessionConfiguration.m + * + * Copyright (C) 2017-2024 Free Software Foundation, Inc. + * + * Written by: Hugo Melder + * Date: May 2024 + * Author: Hugo Melder + * + * This file is part of GNUStep-base + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * If you are interested in a warranty or support for this source code, + * contact Scott Christley for more information. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110 USA. + */ #import "Foundation/NSURLSession.h" #import "Foundation/NSHTTPCookie.h" @@ -35,9 +35,9 @@ @implementation NSURLSessionConfiguration -static NSURLSessionConfiguration *def = nil; +static NSURLSessionConfiguration * def = nil; -+ (void)initialize ++ (void) initialize { if (nil == def) { @@ -45,26 +45,27 @@ + (void)initialize } } -+ (NSURLSessionConfiguration *)defaultSessionConfiguration ++ (NSURLSessionConfiguration *) defaultSessionConfiguration { return AUTORELEASE([def copy]); } -+ (NSURLSessionConfiguration *)ephemeralSessionConfiguration ++ (NSURLSessionConfiguration *) ephemeralSessionConfiguration { // return default session since we don't store any data on disk anyway return AUTORELEASE([def copy]); } -+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier: ++ (NSURLSessionConfiguration *) backgroundSessionConfigurationWithIdentifier: (NSString *)identifier { - NSURLSessionConfiguration *configuration = [def copy]; + NSURLSessionConfiguration * configuration = [def copy]; + configuration->_identifier = [identifier copy]; return AUTORELEASE(configuration); } -- (instancetype)init +- (instancetype) init { if (nil != (self = [super init])) { @@ -83,7 +84,7 @@ - (instancetype)init return self; } -- (void)dealloc +- (void) dealloc { DESTROY(_identifier); DESTROY(_HTTPAdditionalHeaders); @@ -94,190 +95,191 @@ - (void)dealloc [super dealloc]; } -- (NSString *)identifier +- (NSString *) identifier { return _identifier; } -- (NSURLCache *)URLCache +- (NSURLCache *) URLCache { return _URLCache; } -- (void)setURLCache:(NSURLCache *)cache +- (void) setURLCache: (NSURLCache *)cache { ASSIGN(_URLCache, cache); } -- (void)setURLCredentialStorage:(NSURLCredentialStorage *)storage +- (void) setURLCredentialStorage: (NSURLCredentialStorage *)storage { ASSIGN(_URLCredentialStorage, storage); } -- (NSURLRequestCachePolicy)requestCachePolicy +- (NSURLRequestCachePolicy) requestCachePolicy { return _requestCachePolicy; } -- (void)setRequestCachePolicy:(NSURLRequestCachePolicy)policy +- (void) setRequestCachePolicy: (NSURLRequestCachePolicy)policy { _requestCachePolicy = policy; } -- (NSArray *)protocolClasses +- (NSArray *) protocolClasses { return _protocolClasses; } -- (NSTimeInterval)timeoutIntervalForRequest +- (NSTimeInterval) timeoutIntervalForRequest { return _timeoutIntervalForRequest; } -- (void)setTimeoutIntervalForRequest:(NSTimeInterval)interval +- (void) setTimeoutIntervalForRequest: (NSTimeInterval)interval { _timeoutIntervalForRequest = interval; } -- (NSTimeInterval)timeoutIntervalForResource +- (NSTimeInterval) timeoutIntervalForResource { return _timeoutIntervalForResource; } -- (void)setTimeoutIntervalForResource:(NSTimeInterval)interval +- (void) setTimeoutIntervalForResource: (NSTimeInterval)interval { _timeoutIntervalForResource = interval; } -- (NSInteger)HTTPMaximumConnectionsPerHost +- (NSInteger) HTTPMaximumConnectionsPerHost { return _HTTPMaximumConnectionsPerHost; } -- (void)setHTTPMaximumConnectionsPerHost:(NSInteger)n +- (void) setHTTPMaximumConnectionsPerHost: (NSInteger)n { _HTTPMaximumConnectionsPerHost = n; } -- (NSInteger)HTTPMaximumConnectionLifetime +- (NSInteger) HTTPMaximumConnectionLifetime { return _HTTPMaximumConnectionLifetime; } -- (void)setHTTPMaximumConnectionLifetime:(NSInteger)n +- (void) setHTTPMaximumConnectionLifetime: (NSInteger)n { _HTTPMaximumConnectionLifetime = n; } -- (BOOL)HTTPShouldUsePipelining +- (BOOL) HTTPShouldUsePipelining { return _HTTPShouldUsePipelining; } -- (void)setHTTPShouldUsePipelining:(BOOL)flag +- (void) setHTTPShouldUsePipelining: (BOOL)flag { _HTTPShouldUsePipelining = flag; } -- (NSHTTPCookieAcceptPolicy)HTTPCookieAcceptPolicy +- (NSHTTPCookieAcceptPolicy) HTTPCookieAcceptPolicy { return _HTTPCookieAcceptPolicy; } -- (void)setHTTPCookieAcceptPolicy:(NSHTTPCookieAcceptPolicy)policy +- (void) setHTTPCookieAcceptPolicy: (NSHTTPCookieAcceptPolicy)policy { _HTTPCookieAcceptPolicy = policy; } -- (NSHTTPCookieStorage *)HTTPCookieStorage +- (NSHTTPCookieStorage *) HTTPCookieStorage { return _HTTPCookieStorage; } -- (void)setHTTPCookieStorage:(NSHTTPCookieStorage *)storage +- (void) setHTTPCookieStorage: (NSHTTPCookieStorage *)storage { ASSIGN(_HTTPCookieStorage, storage); } -- (BOOL)HTTPShouldSetCookies +- (BOOL) HTTPShouldSetCookies { return _HTTPShouldSetCookies; } -- (void)setHTTPShouldSetCookies:(BOOL)flag +- (void) setHTTPShouldSetCookies: (BOOL)flag { _HTTPShouldSetCookies = flag; } -- (NSDictionary *)HTTPAdditionalHeaders +- (NSDictionary *) HTTPAdditionalHeaders { return _HTTPAdditionalHeaders; } -- (void)setHTTPAdditionalHeaders:(NSDictionary *)headers +- (void) setHTTPAdditionalHeaders: (NSDictionary *)headers { ASSIGN(_HTTPAdditionalHeaders, headers); } -- (NSURLRequest *)configureRequest:(NSURLRequest *)request +- (NSURLRequest *) configureRequest: (NSURLRequest *)request { - return [self setCookiesOnRequest:request]; + return [self setCookiesOnRequest: request]; } -- (NSURLRequest *)setCookiesOnRequest:(NSURLRequest *)request +- (NSURLRequest *) setCookiesOnRequest: (NSURLRequest *)request { - NSMutableURLRequest *r = AUTORELEASE([request mutableCopy]); + NSMutableURLRequest * r = AUTORELEASE([request mutableCopy]); if (_HTTPShouldSetCookies) { if (nil != _HTTPCookieStorage && nil != [request URL]) { - NSArray *cookies = [_HTTPCookieStorage cookiesForURL:[request URL]]; + NSArray * cookies = [_HTTPCookieStorage cookiesForURL: [request URL]]; if (nil != cookies && [cookies count] > 0) { - NSDictionary *cookiesHeaderFields; - NSString *cookieValue; + NSDictionary * cookiesHeaderFields; + NSString * cookieValue; cookiesHeaderFields = - [NSHTTPCookie requestHeaderFieldsWithCookies:cookies]; - cookieValue = [cookiesHeaderFields objectForKey:@"Cookie"]; + [NSHTTPCookie requestHeaderFieldsWithCookies: cookies]; + cookieValue = [cookiesHeaderFields objectForKey: @"Cookie"]; if (nil != cookieValue && [cookieValue length] > 0) { - [r setValue:cookieValue forHTTPHeaderField:@"Cookie"]; + [r setValue: cookieValue forHTTPHeaderField: @"Cookie"]; } } } } return AUTORELEASE([r copy]); -} +} /* setCookiesOnRequest */ -- (NSURLCredentialStorage *)URLCredentialStorage +- (NSURLCredentialStorage *) URLCredentialStorage { return _URLCredentialStorage; } -- (id)copyWithZone:(NSZone *)zone +- (id) copyWithZone: (NSZone *)zone { - NSURLSessionConfiguration *copy = [[[self class] alloc] init]; + NSURLSessionConfiguration * copy = [[[self class] alloc] init]; if (copy) { copy->_identifier = [_identifier copy]; copy->_URLCache = [_URLCache copy]; copy->_URLCredentialStorage = [_URLCredentialStorage copy]; - copy->_protocolClasses = [_protocolClasses copyWithZone:zone]; + copy->_protocolClasses = [_protocolClasses copyWithZone: zone]; copy->_HTTPMaximumConnectionsPerHost = _HTTPMaximumConnectionsPerHost; copy->_HTTPShouldUsePipelining = _HTTPShouldUsePipelining; copy->_HTTPCookieAcceptPolicy = _HTTPCookieAcceptPolicy; copy->_HTTPCookieStorage = [_HTTPCookieStorage retain]; copy->_HTTPShouldSetCookies = _HTTPShouldSetCookies; - copy->_HTTPAdditionalHeaders = [_HTTPAdditionalHeaders copyWithZone:zone]; + copy->_HTTPAdditionalHeaders = + [_HTTPAdditionalHeaders copyWithZone: zone]; copy->_timeoutIntervalForRequest = _timeoutIntervalForRequest; copy->_timeoutIntervalForResource = _timeoutIntervalForResource; } return copy; -} +} /* copyWithZone */ @end \ No newline at end of file diff --git a/Source/NSURLSessionPrivate.h b/Source/NSURLSessionPrivate.h index b4beb684a..08c65344a 100644 --- a/Source/NSURLSessionPrivate.h +++ b/Source/NSURLSessionPrivate.h @@ -1,32 +1,32 @@ /** - NSURLSessionPrivate.h - - Copyright (C) 2017-2024 Free Software Foundation, Inc. - - Written by: Hugo Melder - Date: May 2024 - Author: Hugo Melder - - This file is part of GNUStep-base - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - If you are interested in a warranty or support for this source code, - contact Scott Christley for more information. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110 USA. -*/ + * NSURLSessionPrivate.h + * + * Copyright (C) 2017-2024 Free Software Foundation, Inc. + * + * Written by: Hugo Melder + * Date: May 2024 + * Author: Hugo Melder + * + * This file is part of GNUStep-base + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * If you are interested in a warranty or support for this source code, + * contact Scott Christley for more information. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110 USA. + */ #import "common.h" @@ -35,7 +35,7 @@ #import #import -extern NSString *GS_NSURLSESSION_DEBUG_KEY; +extern NSString * GS_NSURLSESSION_DEBUG_KEY; /* libcurl may request a full-duplex socket configuration with * CURL_POLL_INOUT, but libdispatch distinguishes between a read and write @@ -50,7 +50,8 @@ struct SourceInfo dispatch_source_t writeSocket; }; -typedef NS_ENUM(NSInteger, GSURLSessionProperties) { +typedef NS_ENUM(NSInteger, GSURLSessionProperties) +{ GSURLSessionStoresDataInMemory = (1 << 0), GSURLSessionWritesDataToFile = (1 << 1), GSURLSessionUpdatesDelegate = (1 << 2), @@ -59,32 +60,32 @@ typedef NS_ENUM(NSInteger, GSURLSessionProperties) { }; @interface -NSURLSession (Private) + NSURLSession(Private) - (dispatch_queue_t)_workQueue; -- (NSData *)_certificateBlob; -- (NSString *)_certificatePath; +-(NSData *)_certificateBlob; +-(NSString *)_certificatePath; /* Adds the internal easy handle to the multi handle. * Modifications are performed on the workQueue. */ -- (void)_resumeTask:(NSURLSessionTask *)task; +-(void)_resumeTask: (NSURLSessionTask *)task; /* The following methods must only be called from within callbacks dispatched on * the workQueue.*/ -- (void)_setTimer:(NSInteger)timeout; -- (void)_suspendTimer; +-(void)_setTimer: (NSInteger)timeout; +-(void)_suspendTimer; /* Required for manual redirects. */ -- (void)_addHandle:(CURL *)easy; -- (void)_removeHandle:(CURL *)easy; - -- (void)_removeSocket:(struct SourceInfo *)sources; -- (int)_addSocket:(curl_socket_t)socket easyHandle:(CURL *)easy what:(int)what; -- (int)_setSocket:(curl_socket_t)socket - sources:(struct SourceInfo *)sources - what:(int)what; +-(void)_addHandle: (CURL *)easy; +-(void)_removeHandle: (CURL *)easy; + +-(void)_removeSocket: (struct SourceInfo *)sources; +-(int)_addSocket: (curl_socket_t)socket easyHandle: (CURL *)easy what: (int)what; +-(int)_setSocket: (curl_socket_t)socket + sources: (struct SourceInfo *)sources + what: (int)what; @end diff --git a/Source/NSURLSessionTask.m b/Source/NSURLSessionTask.m index 0c5208b7c..7c4dea175 100644 --- a/Source/NSURLSessionTask.m +++ b/Source/NSURLSessionTask.m @@ -1,31 +1,31 @@ /** - NSURLSessionTask.m - - Copyright (C) 2017-2024 Free Software Foundation, Inc. - - Written by: Hugo Melder - Date: May 2024 - - This file is part of GNUStep-base - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - If you are interested in a warranty or support for this source code, - contact Scott Christley for more information. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110 USA. -*/ + * NSURLSessionTask.m + * + * Copyright (C) 2017-2024 Free Software Foundation, Inc. + * + * Written by: Hugo Melder + * Date: May 2024 + * + * This file is part of GNUStep-base + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * If you are interested in a warranty or support for this source code, + * contact Scott Christley for more information. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110 USA. + */ #import "NSURLSessionPrivate.h" #include @@ -68,19 +68,19 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary /* Initialised in +[NSURLSessionTask initialize] */ static Class dataTaskClass; static Class downloadTaskClass; -static SEL didReceiveDataSel; -static SEL didReceiveResponseSel; -static SEL didCompleteWithErrorSel; -static SEL didFinishDownloadingToURLSel; -static SEL didWriteDataSel; -static SEL needNewBodyStreamSel; -static SEL willPerformHTTPRedirectionSel; - -static NSString *taskTransferDataKey = @"transferData"; -static NSString *taskTemporaryFileLocationKey = @"tempFileLocation"; -static NSString *taskTemporaryFileHandleKey = @"tempFileHandle"; -static NSString *taskInputStreamKey = @"inputStream"; -static NSString *taskUploadData = @"uploadData"; +static SEL didReceiveDataSel; +static SEL didReceiveResponseSel; +static SEL didCompleteWithErrorSel; +static SEL didFinishDownloadingToURLSel; +static SEL didWriteDataSel; +static SEL needNewBodyStreamSel; +static SEL willPerformHTTPRedirectionSel; + +static NSString * taskTransferDataKey = @"transferData"; +static NSString * taskTemporaryFileLocationKey = @"tempFileLocation"; +static NSString * taskTemporaryFileHandleKey = @"tempFileHandle"; +static NSString * taskInputStreamKey = @"inputStream"; +static NSString * taskUploadData = @"uploadData"; /* Translate WinSock2 Error Codes */ #ifdef _WIN32 @@ -89,59 +89,61 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary { switch (err) { - case WSAEADDRINUSE: - err = EADDRINUSE; - break; - case WSAEADDRNOTAVAIL: - err = EADDRNOTAVAIL; - break; - case WSAEINPROGRESS: - err = EINPROGRESS; - break; - case WSAECONNRESET: - err = ECONNRESET; - break; - case WSAECONNABORTED: - err = ECONNABORTED; - break; - case WSAECONNREFUSED: - err = ECONNREFUSED; - break; - case WSAEHOSTUNREACH: - err = EHOSTUNREACH; - break; - case WSAENETUNREACH: - err = ENETUNREACH; - break; - case WSAETIMEDOUT: - err = ETIMEDOUT; - break; - default: - break; - } + case WSAEADDRINUSE: + err = EADDRINUSE; + break; + case WSAEADDRNOTAVAIL: + err = EADDRNOTAVAIL; + break; + case WSAEINPROGRESS: + err = EINPROGRESS; + break; + case WSAECONNRESET: + err = ECONNRESET; + break; + case WSAECONNABORTED: + err = ECONNABORTED; + break; + case WSAECONNREFUSED: + err = ECONNREFUSED; + break; + case WSAEHOSTUNREACH: + err = EHOSTUNREACH; + break; + case WSAENETUNREACH: + err = ENETUNREACH; + break; + case WSAETIMEDOUT: + err = ETIMEDOUT; + break; + default: + break; + } /* switch */ return err; -} -#endif +} /* translateWinSockToPOSIXError */ +#endif /* ifdef _WIN32 */ static inline NSError * -errorForCURLcode(CURL *handle, CURLcode code, char errorBuffer[CURL_ERROR_SIZE]) +errorForCURLcode(CURL * handle, CURLcode code, + char errorBuffer[CURL_ERROR_SIZE]) { - NSString *curlErrorString; - NSString *errorString; - NSDictionary *userInfo; - NSError *error; - NSInteger urlError = NSURLErrorUnknown; - NSInteger posixError; - NSInteger osError = 0; + NSString * curlErrorString; + NSString * errorString; + NSDictionary * userInfo; + NSError * error; + NSInteger urlError = NSURLErrorUnknown; + NSInteger posixError; + NSInteger osError = 0; if (NULL == handle || CURLE_OK == code) { return NULL; } - errorString = [[NSString alloc] initWithCString:errorBuffer]; - curlErrorString = [[NSString alloc] initWithCString:curl_easy_strerror(code)]; + errorString = [[NSString alloc] initWithCString: errorBuffer]; + curlErrorString = + [[NSString alloc] initWithCString: curl_easy_strerror(code)]; /* Get errno number from the last connect failure. * @@ -163,71 +165,71 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary /* Translate libcurl to NSURLError codes */ switch (code) { - case CURLE_UNSUPPORTED_PROTOCOL: - urlError = NSURLErrorUnsupportedURL; - break; - case CURLE_URL_MALFORMAT: - urlError = NSURLErrorBadURL; - break; - - /* Connection Errors */ - case CURLE_COULDNT_RESOLVE_PROXY: - case CURLE_COULDNT_RESOLVE_HOST: - urlError = NSURLErrorDNSLookupFailed; - break; - case CURLE_QUIC_CONNECT_ERROR: - case CURLE_COULDNT_CONNECT: - urlError = NSURLErrorCannotConnectToHost; - break; - case CURLE_OPERATION_TIMEDOUT: - urlError = NSURLErrorTimedOut; - break; - case CURLE_FILESIZE_EXCEEDED: - urlError = NSURLErrorDataLengthExceedsMaximum; - break; - case CURLE_LOGIN_DENIED: - urlError = NSURLErrorUserAuthenticationRequired; - break; - - /* Response Errors */ - case CURLE_WEIRD_SERVER_REPLY: - urlError = NSURLErrorBadServerResponse; - break; - case CURLE_REMOTE_ACCESS_DENIED: - urlError = NSURLErrorNoPermissionsToReadFile; - break; - case CURLE_GOT_NOTHING: - urlError = NSURLErrorZeroByteResource; - break; - case CURLE_RECV_ERROR: - urlError = NSURLErrorResourceUnavailable; - break; - - /* Callback Errors */ - case CURLE_ABORTED_BY_CALLBACK: - case CURLE_WRITE_ERROR: - errorString = @"Transfer aborted by user"; - urlError = NSURLErrorCancelled; - break; - - /* SSL Errors */ - case CURLE_SSL_CACERT_BADFILE: - case CURLE_SSL_PINNEDPUBKEYNOTMATCH: - case CURLE_SSL_CONNECT_ERROR: - urlError = NSURLErrorSecureConnectionFailed; - break; - case CURLE_SSL_CERTPROBLEM: - urlError = NSURLErrorClientCertificateRejected; - break; - case CURLE_SSL_INVALIDCERTSTATUS: - case CURLE_SSL_ISSUER_ERROR: - urlError = NSURLErrorServerCertificateUntrusted; - break; - - default: - urlError = NSURLErrorUnknown; - break; - } + case CURLE_UNSUPPORTED_PROTOCOL: + urlError = NSURLErrorUnsupportedURL; + break; + case CURLE_URL_MALFORMAT: + urlError = NSURLErrorBadURL; + break; + + /* Connection Errors */ + case CURLE_COULDNT_RESOLVE_PROXY: + case CURLE_COULDNT_RESOLVE_HOST: + urlError = NSURLErrorDNSLookupFailed; + break; + case CURLE_QUIC_CONNECT_ERROR: + case CURLE_COULDNT_CONNECT: + urlError = NSURLErrorCannotConnectToHost; + break; + case CURLE_OPERATION_TIMEDOUT: + urlError = NSURLErrorTimedOut; + break; + case CURLE_FILESIZE_EXCEEDED: + urlError = NSURLErrorDataLengthExceedsMaximum; + break; + case CURLE_LOGIN_DENIED: + urlError = NSURLErrorUserAuthenticationRequired; + break; + + /* Response Errors */ + case CURLE_WEIRD_SERVER_REPLY: + urlError = NSURLErrorBadServerResponse; + break; + case CURLE_REMOTE_ACCESS_DENIED: + urlError = NSURLErrorNoPermissionsToReadFile; + break; + case CURLE_GOT_NOTHING: + urlError = NSURLErrorZeroByteResource; + break; + case CURLE_RECV_ERROR: + urlError = NSURLErrorResourceUnavailable; + break; + + /* Callback Errors */ + case CURLE_ABORTED_BY_CALLBACK: + case CURLE_WRITE_ERROR: + errorString = @"Transfer aborted by user"; + urlError = NSURLErrorCancelled; + break; + + /* SSL Errors */ + case CURLE_SSL_CACERT_BADFILE: + case CURLE_SSL_PINNEDPUBKEYNOTMATCH: + case CURLE_SSL_CONNECT_ERROR: + urlError = NSURLErrorSecureConnectionFailed; + break; + case CURLE_SSL_CERTPROBLEM: + urlError = NSURLErrorClientCertificateRejected; + break; + case CURLE_SSL_INVALIDCERTSTATUS: + case CURLE_SSL_ISSUER_ERROR: + urlError = NSURLErrorServerCertificateUntrusted; + break; + + default: + urlError = NSURLErrorUnknown; + break; + } /* switch */ /* Adjust error based on underlying OS error if available */ if (code == CURLE_COULDNT_CONNECT || code == CURLE_RECV_ERROR @@ -235,50 +237,50 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary { switch (posixError) { - case EADDRINUSE: - urlError = NSURLErrorCannotConnectToHost; - break; - case EADDRNOTAVAIL: - urlError = NSURLErrorCannotFindHost; - break; - case ECONNREFUSED: - urlError = NSURLErrorCannotConnectToHost; - break; - case ENETUNREACH: - urlError = NSURLErrorDNSLookupFailed; - break; - case ETIMEDOUT: - urlError = NSURLErrorTimedOut; - break; - default: /* Do not alter urlError if we have no match */ - break; + case EADDRINUSE: + urlError = NSURLErrorCannotConnectToHost; + break; + case EADDRNOTAVAIL: + urlError = NSURLErrorCannotFindHost; + break; + case ECONNREFUSED: + urlError = NSURLErrorCannotConnectToHost; + break; + case ENETUNREACH: + urlError = NSURLErrorDNSLookupFailed; + break; + case ETIMEDOUT: + urlError = NSURLErrorTimedOut; + break; + default: /* Do not alter urlError if we have no match */ + break; } } userInfo = @{ - @"_curlErrorCode" : [NSNumber numberWithInteger:code], - @"_curlErrorString" : curlErrorString, + @"_curlErrorCode": [NSNumber numberWithInteger: code], + @"_curlErrorString": curlErrorString, /* This is the raw POSIX error or WinSock2 Error Code depending on OS */ - @"_errno" : [NSNumber numberWithInteger:osError], - NSLocalizedDescriptionKey : errorString + @"_errno": [NSNumber numberWithInteger: osError], + NSLocalizedDescriptionKey: errorString }; - error = [NSError errorWithDomain:NSURLErrorDomain - code:urlError - userInfo:userInfo]; + error = [NSError errorWithDomain: NSURLErrorDomain + code: urlError + userInfo: userInfo]; [curlErrorString release]; [errorString release]; return error; -} +} /* errorForCURLcode */ /* CURLOPT_PROGRESSFUNCTION: progress reports by libcurl */ static int -progress_callback(void *clientp, curl_off_t dltotal, curl_off_t dlnow, +progress_callback(void * clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { - NSURLSessionTask *task = clientp; + NSURLSessionTask * task = clientp; /* Returning -1 from this callback makes libcurl abort the transfer and return * CURLE_ABORTED_BY_CALLBACK. @@ -288,10 +290,10 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary return -1; } - [task _setCountOfBytesReceived:dlnow]; - [task _setCountOfBytesSent:ulnow]; - [task _setCountOfBytesExpectedToSend:ultotal]; - [task _setCountOfBytesExpectedToReceive:dltotal]; + [task _setCountOfBytesReceived: dlnow]; + [task _setCountOfBytesSent: ulnow]; + [task _setCountOfBytesExpectedToSend: ultotal]; + [task _setCountOfBytesExpectedToReceive: dltotal]; return 0; } @@ -304,39 +306,41 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary * libcurl does not unfold HTTP "folded headers" (deprecated since RFC 7230). */ size_t -header_callback(char *ptr, size_t size, size_t nitems, void *userdata) +header_callback(char * ptr, size_t size, size_t nitems, void * userdata) { - NSURLSessionTask *task; - NSMutableDictionary *taskData; - NSMutableDictionary *headerFields; - NSString *headerLine; - NSInteger headerCallbackCount; - NSRange range; - NSCharacterSet *set; + NSURLSessionTask * task; + NSMutableDictionary * taskData; + NSMutableDictionary * headerFields; + NSString * headerLine; + NSInteger headerCallbackCount; + NSRange range; + NSCharacterSet * set; - task = (NSURLSessionTask *) userdata; + task = (NSURLSessionTask *)userdata; taskData = [task _taskData]; - headerFields = [taskData objectForKey:@"headers"]; + headerFields = [taskData objectForKey: @"headers"]; headerCallbackCount = [task _headerCallbackCount] + 1; set = [NSCharacterSet whitespaceAndNewlineCharacterSet]; - [task _setHeaderCallbackCount:headerCallbackCount]; + [task _setHeaderCallbackCount: headerCallbackCount]; if (nil == headerFields) { - NSDebugLLog(GS_NSURLSESSION_DEBUG_KEY, - @"task=%@ Could not find 'headers' key in taskData", task); + NSDebugLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"task=%@ Could not find 'headers' key in taskData", + task); return 0; } - headerLine = [[NSString alloc] initWithBytes:ptr - length:nitems - encoding:NSUTF8StringEncoding]; + headerLine = [[NSString alloc] initWithBytes: ptr + length: nitems + encoding: NSUTF8StringEncoding]; // First line is the HTTP Version if (1 == headerCallbackCount) { - [taskData setObject:headerLine forKey:@"version"]; + [taskData setObject: headerLine forKey: @"version"]; [headerLine release]; return size * nitems; @@ -350,62 +354,63 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary */ if ((ptr[0] == ' ') || (ptr[0] == '\t')) { - NSString *key; + NSString * key; - if (nil != (key = [taskData objectForKey:@"lastHeaderKey"])) + if (nil != (key = [taskData objectForKey: @"lastHeaderKey"])) { - NSString *value; - NSString *trimmedLine; + NSString * value; + NSString * trimmedLine; - value = [headerFields objectForKey:key]; + value = [headerFields objectForKey: key]; if (!value) { - NSError *error; - NSString *errorDescription; + NSError * error; + NSString * errorDescription; errorDescription = [NSString - stringWithFormat:@"Header is line folded but previous header " - @"key '%@' does not have an entry", - key]; + stringWithFormat: + @"Header is line folded but previous header " + @"key '%@' does not have an entry", + key]; error = - [NSError errorWithDomain:NSURLErrorDomain - code:NSURLErrorCancelled - userInfo:@{ - NSLocalizedDescriptionKey : errorDescription - }]; + [NSError errorWithDomain: NSURLErrorDomain + code: NSURLErrorCancelled + userInfo: @{ + NSLocalizedDescriptionKey: errorDescription + }]; - [taskData setObject:error forKey:NSUnderlyingErrorKey]; + [taskData setObject: error forKey: NSUnderlyingErrorKey]; [headerLine release]; return 0; } - trimmedLine = [headerLine stringByTrimmingCharactersInSet:set]; - value = [value stringByAppendingString:trimmedLine]; + trimmedLine = [headerLine stringByTrimmingCharactersInSet: set]; + value = [value stringByAppendingString: trimmedLine]; - [headerFields setObject:value forKey:key]; + [headerFields setObject: value forKey: key]; } [headerLine release]; return size * nitems; } - range = [headerLine rangeOfString:@":"]; + range = [headerLine rangeOfString: @":"]; if (NSNotFound != range.location) { - NSString *key; - NSString *value; + NSString * key; + NSString * value; - key = [headerLine substringToIndex:range.location]; - value = [headerLine substringFromIndex:range.location + 1]; + key = [headerLine substringToIndex: range.location]; + value = [headerLine substringFromIndex: range.location + 1]; /* Remove LWS from key and value */ - key = [key stringByTrimmingCharactersInSet:set]; - value = [value stringByTrimmingCharactersInSet:set]; + key = [key stringByTrimmingCharactersInSet: set]; + value = [value stringByTrimmingCharactersInSet: set]; - [headerFields setObject:value forKey:key]; + [headerFields setObject: value forKey: key]; /* Used for line unfolding */ - [taskData setObject:key forKey:@"lastHeaderKey"]; + [taskData setObject: key forKey: @"lastHeaderKey"]; [headerLine release]; return size * nitems; @@ -420,47 +425,51 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary */ if (nitems > 1 && (ptr[0] == '\r') && (ptr[1] == '\n')) { - NSURLSession *session; - id delegate; - NSHTTPURLResponse *response; - NSString *version; - NSString *urlString; - NSURL *url; - CURL *handle; - char *effURL; - NSInteger numberOfRedirects = 0; - NSInteger statusCode = 0; + NSURLSession * session; + id delegate; + NSHTTPURLResponse * response; + NSString * version; + NSString * urlString; + NSURL * url; + CURL * handle; + char * effURL; + NSInteger numberOfRedirects = 0; + NSInteger statusCode = 0; session = [task _session]; delegate = [task delegate]; handle = [task _easyHandle]; numberOfRedirects = [task _numberOfRedirects] + 1; - [task _setNumberOfRedirects:numberOfRedirects]; - [task _setHeaderCallbackCount:0]; + [task _setNumberOfRedirects: numberOfRedirects]; + [task _setHeaderCallbackCount: 0]; curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &statusCode); curl_easy_getinfo(handle, CURLINFO_EFFECTIVE_URL, &effURL); - if (nil == (version = [taskData objectForKey:@"version"])) + if (nil == (version = [taskData objectForKey: @"version"])) { /* Default to HTTP/1.0 if no data is available */ version = @"HTTP/1.0"; } - NSDebugLLog(GS_NSURLSESSION_DEBUG_KEY, - @"task=%@ version=%@ status=%ld found %ld headers", task, - version, statusCode, [headerFields count]); + NSDebugLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"task=%@ version=%@ status=%ld found %ld headers", + task, + version, + statusCode, + [headerFields count]); - urlString = [[NSString alloc] initWithCString:effURL]; - url = [NSURL URLWithString:urlString]; - response = [[NSHTTPURLResponse alloc] initWithURL:url - statusCode:statusCode - HTTPVersion:version - headerFields:[headerFields copy]]; + urlString = [[NSString alloc] initWithCString: effURL]; + url = [NSURL URLWithString: urlString]; + response = [[NSHTTPURLResponse alloc] initWithURL: url + statusCode: statusCode + HTTPVersion: version + headerFields: [headerFields copy]]; - [task _setCookiesFromHeaders:headerFields]; - [task _setResponse:response]; + [task _setCookiesFromHeaders: headerFields]; + [task _setResponse: response]; /* URL redirection handling for 3xx status codes, if delegate updates are * enabled. @@ -471,7 +480,7 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary if ([task _properties] & GSURLSessionUpdatesDelegate && statusCode >= 300 && statusCode < 400) { - NSString *location; + NSString * location; /* * RFC 7231: 7.1.2 Location [Header] @@ -483,85 +492,96 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary * request URI * ([RFC3986], Section 5). */ - location = [headerFields objectForKey:@"Location"]; + location = [headerFields objectForKey: @"Location"]; if (nil != location) { - NSURL *redirectURL; - NSMutableURLRequest *newRequest; + NSURL * redirectURL; + NSMutableURLRequest * newRequest; /* baseURL is only used, if location is a relative reference */ - redirectURL = [NSURL URLWithString:location relativeToURL:url]; + redirectURL = [NSURL URLWithString: location relativeToURL: url]; newRequest = [[task originalRequest] mutableCopy]; - [newRequest setURL:redirectURL]; + [newRequest setURL: redirectURL]; - NSDebugLLog(GS_NSURLSESSION_DEBUG_KEY, - @"task=%@ status=%ld has Location header. Prepare " - @"for redirection with url=%@", - task, statusCode, redirectURL); + NSDebugLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"task=%@ status=%ld has Location header. Prepare " + @"for redirection with url=%@", + task, + statusCode, + redirectURL); - if ([delegate respondsToSelector:willPerformHTTPRedirectionSel]) + if ([delegate respondsToSelector: willPerformHTTPRedirectionSel]) { - NSDebugLLog(GS_NSURLSESSION_DEBUG_KEY, - @"task=%@ ask delegate for redirection " - @"permission. Pausing handle.", - task); + NSDebugLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"task=%@ ask delegate for redirection " + @"permission. Pausing handle.", + task); curl_easy_pause(handle, CURLPAUSE_ALL); [[session delegateQueue] addOperationWithBlock:^{ - void (^completionHandler)(NSURLRequest *) = ^( - NSURLRequest *userRequest) { - /* Changes are dispatched onto workqueue */ - dispatch_async([session _workQueue], ^{ - if (NULL == userRequest) - { - curl_easy_pause(handle, CURLPAUSE_CONT); - [task _setShouldStopTransfer:YES]; - NSDebugLLog(GS_NSURLSESSION_DEBUG_KEY, - @"task=%@ willPerformHTTPRedirection " - @"completionHandler called with nil " - @"request", - task); - } - else - { - NSString *newURLString; - - newURLString = [[userRequest URL] absoluteString]; - - NSDebugLLog(GS_NSURLSESSION_DEBUG_KEY, - @"task=%@ willPerformHTTPRedirection " - @"delegate completionHandler called " - @"with new URL %@", - task, newURLString); - - /* Remove handle for reconfiguration */ - [session _removeHandle:handle]; - - /* Reset statistics */ - [task _setCountOfBytesReceived:0]; - [task _setCountOfBytesSent:0]; - [task _setCountOfBytesExpectedToReceive:0]; - [task _setCountOfBytesExpectedToSend:0]; - - [task _setCurrentRequest:userRequest]; - - /* Update URL in easy handle */ - curl_easy_setopt(handle, CURLOPT_URL, - [newURLString UTF8String]); - curl_easy_pause(handle, CURLPAUSE_CONT); - - [session _addHandle:handle]; - } - }); - }; - - [delegate URLSession:session - task:task - willPerformHTTPRedirection:response - newRequest:newRequest - completionHandler:completionHandler]; - }]; + void (^completionHandler)(NSURLRequest *) = ^( + NSURLRequest * userRequest) { + /* Changes are dispatched onto workqueue */ + dispatch_async( + [session _workQueue], + ^{ + if (NULL == userRequest) + { + curl_easy_pause(handle, CURLPAUSE_CONT); + [task _setShouldStopTransfer: YES]; + NSDebugLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"task=%@ willPerformHTTPRedirection " + @"completionHandler called with nil " + @"request", + task); + } + else + { + NSString * newURLString; + + newURLString = [[userRequest URL] absoluteString]; + + NSDebugLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"task=%@ willPerformHTTPRedirection " + @"delegate completionHandler called " + @"with new URL %@", + task, + newURLString); + + /* Remove handle for reconfiguration */ + [session _removeHandle: handle]; + + /* Reset statistics */ + [task _setCountOfBytesReceived: 0]; + [task _setCountOfBytesSent: 0]; + [task _setCountOfBytesExpectedToReceive: 0]; + [task _setCountOfBytesExpectedToSend: 0]; + + [task _setCurrentRequest: userRequest]; + + /* Update URL in easy handle */ + curl_easy_setopt( + handle, + CURLOPT_URL, + [newURLString UTF8String]); + curl_easy_pause(handle, CURLPAUSE_CONT); + + [session _addHandle: handle]; + } + }); + }; + + [delegate URLSession: session + task: task + willPerformHTTPRedirection: response + newRequest: newRequest + completionHandler: completionHandler]; + }]; [headerFields removeAllObjects]; return size * nitems; @@ -573,24 +593,28 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary @"task=%@ status=%ld has Location header but " @"delegate does not respond to " @"willPerformHTTPRedirection:. Redirecting to Location %@", - task, statusCode, redirectURL); + task, + statusCode, + redirectURL); /* Remove handle for reconfiguration */ - [session _removeHandle:handle]; + [session _removeHandle: handle]; - curl_easy_setopt(handle, CURLOPT_URL, - [[redirectURL absoluteString] UTF8String]); + curl_easy_setopt( + handle, + CURLOPT_URL, + [[redirectURL absoluteString] UTF8String]); /* Reset statistics */ - [task _setCountOfBytesReceived:0]; - [task _setCountOfBytesSent:0]; - [task _setCountOfBytesExpectedToReceive:0]; - [task _setCountOfBytesExpectedToSend:0]; + [task _setCountOfBytesReceived: 0]; + [task _setCountOfBytesSent: 0]; + [task _setCountOfBytesExpectedToReceive: 0]; + [task _setCountOfBytesExpectedToSend: 0]; - [task _setCurrentRequest:newRequest]; + [task _setCurrentRequest: newRequest]; /* Re-add handle to session */ - [session _addHandle:handle]; + [session _addHandle: handle]; } [headerFields removeAllObjects]; @@ -598,20 +622,22 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary } else { - NSError *error; - NSString *errorString; + NSError * error; + NSString * errorString; errorString = [NSString - stringWithFormat:@"task=%@ status=%ld has no Location header", - task, statusCode]; + stringWithFormat: + @"task=%@ status=%ld has no Location header", + task, statusCode]; error = [NSError - errorWithDomain:NSURLErrorDomain - code:NSURLErrorBadServerResponse - userInfo:@{NSLocalizedDescriptionKey : errorString}]; + errorWithDomain: NSURLErrorDomain + code: NSURLErrorBadServerResponse + userInfo: @{ NSLocalizedDescriptionKey: + errorString }]; NSDebugLLog(GS_NSURLSESSION_DEBUG_KEY, @"%@", errorString); - [taskData setObject:error forKey:NSUnderlyingErrorKey]; + [taskData setObject: error forKey: NSUnderlyingErrorKey]; return 0; } @@ -625,8 +651,8 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary * FIXME: Enforce this and implement a custom redirect system */ if ([task _properties] & GSURLSessionUpdatesDelegate && - [task isKindOfClass:dataTaskClass] && - [delegate respondsToSelector:didReceiveResponseSel]) + [task isKindOfClass: dataTaskClass] && + [delegate respondsToSelector: didReceiveResponseSel]) { dispatch_queue_t queue; @@ -635,23 +661,25 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary curl_easy_pause(handle, CURLPAUSE_ALL); [[session delegateQueue] addOperationWithBlock:^{ - [delegate URLSession:session - dataTask:(NSURLSessionDataTask *) task - didReceiveResponse:response - completionHandler:^( - NSURLSessionResponseDisposition disposition) { - /* FIXME: Implement NSURLSessionResponseBecomeDownload */ - if (disposition == NSURLSessionResponseCancel) - { - [task _setShouldStopTransfer:YES]; - } - - /* Unpause easy handle */ - dispatch_async(queue, ^{ - curl_easy_pause(handle, CURLPAUSE_CONT); - }); - }]; - }]; + [delegate URLSession: session + dataTask: (NSURLSessionDataTask *)task + didReceiveResponse: response + completionHandler:^( + NSURLSessionResponseDisposition disposition) { + /* FIXME: Implement NSURLSessionResponseBecomeDownload */ + if (disposition == NSURLSessionResponseCancel) + { + [task _setShouldStopTransfer: YES]; + } + + /* Unpause easy handle */ + dispatch_async( + queue, + ^{ + curl_easy_pause(handle, CURLPAUSE_CONT); + }); + }]; + }]; } [urlString release]; @@ -659,129 +687,132 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary } return size * nitems; -} +} /* header_callback */ /* CURLOPT_READFUNCTION: read callback for data uploads */ size_t -read_callback(char *buffer, size_t size, size_t nitems, void *userdata) +read_callback(char * buffer, size_t size, size_t nitems, void * userdata) { - NSURLSession *session; - NSURLSessionTask *task; - NSMutableDictionary *taskData; - NSInputStream *stream; - NSInteger bytesWritten; + NSURLSession * session; + NSURLSessionTask * task; + NSMutableDictionary * taskData; + NSInputStream * stream; + NSInteger bytesWritten; - task = (NSURLSessionTask *) userdata; + task = (NSURLSessionTask *)userdata; session = [task _session]; taskData = [task _taskData]; - stream = [taskData objectForKey:taskInputStreamKey]; + stream = [taskData objectForKey: taskInputStreamKey]; if (nil == stream) { id delegate = [task delegate]; - NSDebugLLog(GS_NSURLSESSION_DEBUG_KEY, - @"task=%@ requesting new body stream from delegate", task); + NSDebugLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"task=%@ requesting new body stream from delegate", + task); - if ([delegate respondsToSelector:needNewBodyStreamSel]) + if ([delegate respondsToSelector: needNewBodyStreamSel]) { [[[task _session] delegateQueue] addOperationWithBlock:^{ - [delegate URLSession:session - task:task - needNewBodyStream:^(NSInputStream *bodyStream) { - /* Add input stream to task data */ - [taskData setObject:bodyStream forKey:taskInputStreamKey]; - /* Continue with the transfer */ - curl_easy_pause([task _easyHandle], CURLPAUSE_CONT); - }]; - }]; + [delegate URLSession: session + task: task + needNewBodyStream:^(NSInputStream * bodyStream) { + /* Add input stream to task data */ + [taskData setObject: bodyStream forKey: taskInputStreamKey]; + /* Continue with the transfer */ + curl_easy_pause([task _easyHandle], CURLPAUSE_CONT); + }]; + }]; return CURL_READFUNC_PAUSE; } else { - NSDebugLLog(GS_NSURLSESSION_DEBUG_KEY, - @"task=%@ no input stream was given and delegate does " - @"not respond to URLSession:task:needNewBodyStream:", - task); + NSDebugLLog( + GS_NSURLSESSION_DEBUG_KEY, + @"task=%@ no input stream was given and delegate does " + @"not respond to URLSession:task:needNewBodyStream:", + task); return CURL_READFUNC_ABORT; } } - bytesWritten = [stream read:(uint8_t *) buffer maxLength:(size * nitems)]; + bytesWritten = [stream read: (uint8_t *)buffer maxLength: (size * nitems)]; /* An error occured while reading from the inputStream */ if (bytesWritten < 0) { - NSError *error; + NSError * error; error = [NSError - errorWithDomain:NSURLErrorDomain - code:NSURLErrorCancelled - userInfo:@{ - NSLocalizedDescriptionKey : - @"An error occured while reading from the body stream", - NSUnderlyingErrorKey : [stream streamError] + errorWithDomain: NSURLErrorDomain + code: NSURLErrorCancelled + userInfo: @{ + NSLocalizedDescriptionKey: + @"An error occured while reading from the body stream", + NSUnderlyingErrorKey: [stream streamError] }]; - [taskData setObject:error forKey:NSUnderlyingErrorKey]; + [taskData setObject: error forKey: NSUnderlyingErrorKey]; return CURL_READFUNC_ABORT; } return bytesWritten; -} +} /* read_callback */ /* CURLOPT_WRITEFUNCTION: callback for writing received data from easy handle */ static size_t -write_callback(char *ptr, size_t size, size_t nmemb, void *userdata) +write_callback(char * ptr, size_t size, size_t nmemb, void * userdata) { - NSURLSessionTask *task; - NSURLSession *session; - NSMutableDictionary *taskData; - NSData *dataFragment; - NSInteger properties; + NSURLSessionTask * task; + NSURLSession * session; + NSMutableDictionary * taskData; + NSData * dataFragment; + NSInteger properties; - task = (NSURLSessionTask *) userdata; + task = (NSURLSessionTask *)userdata; session = [task _session]; taskData = [task _taskData]; - dataFragment = [[NSData alloc] initWithBytes:ptr length:(size * nmemb)]; + dataFragment = [[NSData alloc] initWithBytes: ptr length: (size * nmemb)]; properties = [task _properties]; if (properties & GSURLSessionStoresDataInMemory) { - NSMutableData *data; + NSMutableData * data; - data = [taskData objectForKey:taskTransferDataKey]; + data = [taskData objectForKey: taskTransferDataKey]; if (!data) { data = [[NSMutableData alloc] init]; /* Strong reference maintained by taskData */ - [taskData setObject:data forKey:taskTransferDataKey]; + [taskData setObject: data forKey: taskTransferDataKey]; [data release]; } - [data appendData:dataFragment]; + [data appendData: dataFragment]; } else if (properties & GSURLSessionWritesDataToFile) { - NSFileHandle *handle; - NSError *error = NULL; + NSFileHandle * handle; + NSError * error = NULL; // Get a temporary file path and create a file handle - if (nil == (handle = [taskData objectForKey:taskTemporaryFileHandleKey])) + if (nil == (handle = [taskData objectForKey: taskTemporaryFileHandleKey])) { - handle = [task _createTemporaryFileHandleWithError:&error]; + handle = [task _createTemporaryFileHandleWithError: &error]; /* We add the error to taskData as an underlying error */ if (NULL != error) { - [taskData setObject:error forKey:NSUnderlyingErrorKey]; + [taskData setObject: error forKey: NSUnderlyingErrorKey]; [dataFragment release]; return 0; } } - [handle writeData:dataFragment]; + [handle writeData: dataFragment]; } /* Notify delegate */ @@ -789,47 +820,47 @@ @interface _GSMutableInsensitiveDictionary : NSMutableDictionary { id delegate = [task delegate]; - if ([task isKindOfClass:dataTaskClass] && - [delegate respondsToSelector:didReceiveDataSel]) + if ([task isKindOfClass: dataTaskClass] && + [delegate respondsToSelector: didReceiveDataSel]) { [[session delegateQueue] addOperationWithBlock:^{ - [delegate URLSession:session - dataTask:(NSURLSessionDataTask *) task - didReceiveData:dataFragment]; - }]; + [delegate URLSession: session + dataTask: (NSURLSessionDataTask *)task + didReceiveData: dataFragment]; + }]; } /* Notify delegate about the download process */ - if ([task isKindOfClass:downloadTaskClass] && - [delegate respondsToSelector:didWriteDataSel]) + if ([task isKindOfClass: downloadTaskClass] && + [delegate respondsToSelector: didWriteDataSel]) { - NSURLSessionDownloadTask *downloadTask; - int64_t bytesWritten; - int64_t totalBytesWritten; - int64_t totalBytesExpectedToReceive; + NSURLSessionDownloadTask * downloadTask; + int64_t bytesWritten; + int64_t totalBytesWritten; + int64_t totalBytesExpectedToReceive; - downloadTask = (NSURLSessionDownloadTask *) task; + downloadTask = (NSURLSessionDownloadTask *)task; bytesWritten = [dataFragment length]; - [downloadTask _updateCountOfBytesWritten:bytesWritten]; + [downloadTask _updateCountOfBytesWritten: bytesWritten]; totalBytesWritten = [downloadTask _countOfBytesWritten]; totalBytesExpectedToReceive = [downloadTask countOfBytesExpectedToReceive]; [[session delegateQueue] addOperationWithBlock:^{ - [delegate URLSession:session - downloadTask:downloadTask - didWriteData:bytesWritten - totalBytesWritten:totalBytesWritten - totalBytesExpectedToWrite:totalBytesExpectedToReceive]; - }]; + [delegate URLSession: session + downloadTask: downloadTask + didWriteData: bytesWritten + totalBytesWritten: totalBytesWritten + totalBytesExpectedToWrite: totalBytesExpectedToReceive]; + }]; } } [dataFragment release]; return size * nmemb; -} +} /* write_callback */ @implementation NSURLSessionTask { @@ -839,19 +870,19 @@ @implementation NSURLSessionTask NSInteger _properties; /* Internal task data */ - NSMutableDictionary *_taskData; - NSInteger _numberOfRedirects; - NSInteger _headerCallbackCount; - NSUInteger _suspendCount; + NSMutableDictionary * _taskData; + NSInteger _numberOfRedirects; + NSInteger _headerCallbackCount; + NSUInteger _suspendCount; - char _curlErrorBuffer[CURL_ERROR_SIZE]; - struct curl_slist *_headerList; + char _curlErrorBuffer[CURL_ERROR_SIZE]; + struct curl_slist * _headerList; - CURL *_easyHandle; - NSURLSession *_session; + CURL * _easyHandle; + NSURLSession * _session; } -+ (void)initialize ++ (void) initialize { dataTaskClass = [NSURLSessionDataTask class]; downloadTaskClass = [NSURLSessionDownloadTask class]; @@ -863,29 +894,29 @@ + (void)initialize @selector(URLSession:downloadTask:didFinishDownloadingToURL:); didWriteDataSel = @selector (URLSession: - downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:); + downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:); needNewBodyStreamSel = @selector(URLSession:task:needNewBodyStream:); willPerformHTTPRedirectionSel = @selector (URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:); } -- (instancetype)initWithSession:(NSURLSession *)session - request:(NSURLRequest *)request - taskIdentifier:(NSUInteger)identifier +- (instancetype) initWithSession: (NSURLSession *)session + request: (NSURLRequest *)request + taskIdentifier: (NSUInteger)identifier { self = [super init]; if (self) { - NSString *httpMethod; - NSData *certificateBlob; - NSURL *url; - NSDictionary *immConfigHeaders; - NSURLSessionConfiguration *configuration; - NSHTTPCookieStorage *storage; + NSString * httpMethod; + NSData * certificateBlob; + NSURL * url; + NSDictionary * immConfigHeaders; + NSURLSessionConfiguration * configuration; + NSHTTPCookieStorage * storage; - _GSMutableInsensitiveDictionary *requestHeaders = nil; - _GSMutableInsensitiveDictionary *configHeaders = nil; + _GSMutableInsensitiveDictionary * requestHeaders = nil; + _GSMutableInsensitiveDictionary * configHeaders = nil; _taskIdentifier = identifier; _taskData = [[NSMutableDictionary alloc] init]; @@ -913,13 +944,13 @@ - (instancetype)initWithSession:(NSURLSession *)session /* Configure initial task data */ - [_taskData setObject:[NSMutableDictionary new] forKey:@"headers"]; + [_taskData setObject: [NSMutableDictionary new] forKey: @"headers"]; /* Easy Handle Configuration */ _easyHandle = curl_easy_init(); - if ([@"head" isEqualToString:httpMethod]) + if ([@"head" isEqualToString: httpMethod]) { curl_easy_setopt(_easyHandle, CURLOPT_NOBODY, 1L); } @@ -929,18 +960,20 @@ - (instancetype)initWithSession:(NSURLSession *)session */ if (nil != [_originalRequest HTTPBody]) { - NSData *body = [_originalRequest HTTPBody]; + NSData * body = [_originalRequest HTTPBody]; curl_easy_setopt(_easyHandle, CURLOPT_UPLOAD, 1L); - curl_easy_setopt(_easyHandle, CURLOPT_POSTFIELDSIZE_LARGE, - [body length]); + curl_easy_setopt( + _easyHandle, + CURLOPT_POSTFIELDSIZE_LARGE, + [body length]); curl_easy_setopt(_easyHandle, CURLOPT_POSTFIELDS, [body bytes]); } else if (nil != [_originalRequest HTTPBodyStream]) { - NSInputStream *stream = [_originalRequest HTTPBodyStream]; + NSInputStream * stream = [_originalRequest HTTPBodyStream]; - [_taskData setObject:stream forKey:taskInputStreamKey]; + [_taskData setObject: stream forKey: taskInputStreamKey]; curl_easy_setopt(_easyHandle, CURLOPT_READFUNCTION, read_callback); curl_easy_setopt(_easyHandle, CURLOPT_READDATA, self); @@ -950,11 +983,15 @@ - (instancetype)initWithSession:(NSURLSession *)session } /* Configure HTTP method and URL */ - curl_easy_setopt(_easyHandle, CURLOPT_CUSTOMREQUEST, - [[_originalRequest HTTPMethod] UTF8String]); + curl_easy_setopt( + _easyHandle, + CURLOPT_CUSTOMREQUEST, + [[_originalRequest HTTPMethod] UTF8String]); - curl_easy_setopt(_easyHandle, CURLOPT_URL, - [[url absoluteString] UTF8String]); + curl_easy_setopt( + _easyHandle, + CURLOPT_URL, + [[url absoluteString] UTF8String]); /* This callback function gets called by libcurl as soon as there is data * received that needs to be saved. For most transfers, this callback gets @@ -987,8 +1024,10 @@ - (instancetype)initWithSession:(NSURLSession *)session /* Specifiy our own progress function with the user pointer being the * current object */ - curl_easy_setopt(_easyHandle, CURLOPT_XFERINFOFUNCTION, - progress_callback); + curl_easy_setopt( + _easyHandle, + CURLOPT_XFERINFOFUNCTION, + progress_callback); curl_easy_setopt(_easyHandle, CURLOPT_XFERINFODATA, self); /* Do not Follow redirects by default @@ -1000,18 +1039,24 @@ - (instancetype)initWithSession:(NSURLSession *)session curl_easy_setopt(_easyHandle, CURLOPT_FOLLOWLOCATION, 0L); /* Set timeout in connect phase */ - curl_easy_setopt(_easyHandle, CURLOPT_CONNECTTIMEOUT, - (NSInteger)[request timeoutInterval]); + curl_easy_setopt( + _easyHandle, + CURLOPT_CONNECTTIMEOUT, + (NSInteger)[request timeoutInterval]); /* Set overall timeout */ - curl_easy_setopt(_easyHandle, CURLOPT_TIMEOUT, - [configuration timeoutIntervalForResource]); + curl_easy_setopt( + _easyHandle, + CURLOPT_TIMEOUT, + [configuration timeoutIntervalForResource]); /* Set to HTTP/3 if requested */ if ([request assumesHTTP3Capable]) { - curl_easy_setopt(_easyHandle, CURLOPT_HTTP_VERSION, - CURL_HTTP_VERSION_3); + curl_easy_setopt( + _easyHandle, + CURLOPT_HTTP_VERSION, + CURL_HTTP_VERSION_3); } /* Configure the custom CA certificate if available */ @@ -1021,7 +1066,7 @@ - (instancetype)initWithSession:(NSURLSession *)session #if LIBCURL_VERSION_NUM >= 0x074D00 struct curl_blob blob; - blob.data = (void *) [certificateBlob bytes]; + blob.data = (void *)[certificateBlob bytes]; blob.len = [certificateBlob length]; /* Session becomes a strong reference when task is resumed until the * end of transfer. */ @@ -1029,8 +1074,10 @@ - (instancetype)initWithSession:(NSURLSession *)session curl_easy_setopt(_easyHandle, CURLOPT_CAINFO_BLOB, &blob); #else - curl_easy_setopt(_easyHandle, CURLOPT_CAINFO, - [_session _certificatePath]); + curl_easy_setopt( + _easyHandle, + CURLOPT_CAINFO, + [_session _certificatePath]); #endif } @@ -1039,8 +1086,8 @@ - (instancetype)initWithSession:(NSURLSession *)session if (nil != immConfigHeaders) { configHeaders = [[_GSMutableInsensitiveDictionary alloc] - initWithDictionary:immConfigHeaders - copyItems:NO]; + initWithDictionary: immConfigHeaders + copyItems: NO]; /* Merge Headers. * @@ -1049,7 +1096,7 @@ - (instancetype)initWithSession:(NSURLSession *)session * the request object’s value takes precedence. */ [configHeaders - addEntriesFromDictionary:(NSDictionary *) requestHeaders]; + addEntriesFromDictionary: (NSDictionary *)requestHeaders]; requestHeaders = configHeaders; } @@ -1058,8 +1105,8 @@ - (instancetype)initWithSession:(NSURLSession *)session storage = [configuration HTTPCookieStorage]; if (nil != storage && [configuration HTTPShouldSetCookies]) { - NSDictionary *cookieHeaders; - NSArray *cookies; + NSDictionary * cookieHeaders; + NSArray * cookies; /* No headers were set */ if (nil == requestHeaders) @@ -1067,54 +1114,56 @@ - (instancetype)initWithSession:(NSURLSession *)session requestHeaders = [_GSMutableInsensitiveDictionary new]; } - cookies = [storage cookiesForURL:url]; + cookies = [storage cookiesForURL: url]; if ([cookies count] > 0) { cookieHeaders = - [NSHTTPCookie requestHeaderFieldsWithCookies:cookies]; - [requestHeaders addEntriesFromDictionary:cookieHeaders]; + [NSHTTPCookie requestHeaderFieldsWithCookies: cookies]; + [requestHeaders addEntriesFromDictionary: cookieHeaders]; } } /* Append Headers to the libcurl header list */ [requestHeaders - enumerateKeysAndObjectsUsingBlock:^(id key, id object, - BOOL *stop) { - NSString *headerLine; + enumerateKeysAndObjectsUsingBlock:^(id key, id object, + BOOL * stop) { + NSString * headerLine; - headerLine = [NSString stringWithFormat:@"%@: %@", key, object]; + headerLine = [NSString stringWithFormat: @"%@: %@", key, object]; - /* We have removed all reserved headers in NSURLRequest */ - _headerList = curl_slist_append(_headerList, [headerLine UTF8String]); - }]; + /* We have removed all reserved headers in NSURLRequest */ + _headerList = curl_slist_append(_headerList, [headerLine UTF8String]); + }]; curl_easy_setopt(_easyHandle, CURLOPT_HTTPHEADER, _headerList); } return self; -} +} /* initWithSession */ -- (void)_enableAutomaticRedirects:(BOOL)flag +- (void) _enableAutomaticRedirects: (BOOL)flag { curl_easy_setopt(_easyHandle, CURLOPT_FOLLOWLOCATION, flag ? 1L : 0L); } -- (void)_enableUploadWithData:(NSData *)data +- (void) _enableUploadWithData: (NSData *)data { curl_easy_setopt(_easyHandle, CURLOPT_UPLOAD, 1L); /* Retain data */ - [_taskData setObject:data forKey:taskUploadData]; + [_taskData setObject: data forKey: taskUploadData]; curl_easy_setopt(_easyHandle, CURLOPT_POSTFIELDSIZE_LARGE, [data length]); curl_easy_setopt(_easyHandle, CURLOPT_POSTFIELDS, [data bytes]); /* The method is overwritten by CURLOPT_UPLOAD. Change it back. */ - curl_easy_setopt(_easyHandle, CURLOPT_CUSTOMREQUEST, - [[_originalRequest HTTPMethod] UTF8String]); + curl_easy_setopt( + _easyHandle, + CURLOPT_CUSTOMREQUEST, + [[_originalRequest HTTPMethod] UTF8String]); } -- (void)_enableUploadWithSize:(NSInteger)size +- (void) _enableUploadWithSize: (NSInteger)size { curl_easy_setopt(_easyHandle, CURLOPT_UPLOAD, 1L); @@ -1131,156 +1180,164 @@ - (void)_enableUploadWithSize:(NSInteger)size } /* The method is overwritten by CURLOPT_UPLOAD. Change it back. */ - curl_easy_setopt(_easyHandle, CURLOPT_CUSTOMREQUEST, - [[_originalRequest HTTPMethod] UTF8String]); -} + curl_easy_setopt( + _easyHandle, + CURLOPT_CUSTOMREQUEST, + [[_originalRequest HTTPMethod] UTF8String]); +} /* _enableUploadWithSize */ -- (CURL *)_easyHandle +- (CURL *) _easyHandle { return _easyHandle; } -- (void)_setVerbose:(BOOL)flag +- (void) _setVerbose: (BOOL)flag { - dispatch_async([_session _workQueue], ^{ + dispatch_async( + [_session _workQueue], + ^{ curl_easy_setopt(_easyHandle, CURLOPT_VERBOSE, flag ? 1L : 0L); }); } -- (void)_setBodyStream:(NSInputStream *)stream +- (void) _setBodyStream: (NSInputStream *)stream { - [_taskData setObject:stream forKey:taskInputStreamKey]; + [_taskData setObject: stream forKey: taskInputStreamKey]; } -- (void)_setOriginalRequest:(NSURLRequest *)request +- (void) _setOriginalRequest: (NSURLRequest *)request { ASSIGNCOPY(_originalRequest, request); } -- (void)_setCurrentRequest:(NSURLRequest *)request +- (void) _setCurrentRequest: (NSURLRequest *)request { ASSIGNCOPY(_currentRequest, request); } -- (void)_setResponse:(NSURLResponse *)response +- (void) _setResponse: (NSURLResponse *)response { - NSURLResponse *oldResponse = _response; + NSURLResponse * oldResponse = _response; + _response = [response retain]; [oldResponse release]; } -- (void)_setCountOfBytesSent:(int64_t)count +- (void) _setCountOfBytesSent: (int64_t)count { _countOfBytesSent = count; } -- (void)_setCountOfBytesReceived:(int64_t)count +- (void) _setCountOfBytesReceived: (int64_t)count { _countOfBytesReceived = count; } -- (void)_setCountOfBytesExpectedToSend:(int64_t)count +- (void) _setCountOfBytesExpectedToSend: (int64_t)count { _countOfBytesExpectedToSend = count; } -- (void)_setCountOfBytesExpectedToReceive:(int64_t)count +- (void) _setCountOfBytesExpectedToReceive: (int64_t)count { _countOfBytesExpectedToReceive = count; } -- (NSMutableDictionary *)_taskData +- (NSMutableDictionary *) _taskData { return _taskData; } -- (NSInteger)_properties +- (NSInteger) _properties { return _properties; } -- (void)_setProperties:(NSInteger)properties +- (void) _setProperties: (NSInteger)properties { _properties = properties; } -- (NSURLSession *)_session +- (NSURLSession *) _session { return _session; } -- (BOOL)_shouldStopTransfer +- (BOOL) _shouldStopTransfer { return _shouldStopTransfer; } -- (void)_setShouldStopTransfer:(BOOL)flag +- (void) _setShouldStopTransfer: (BOOL)flag { _shouldStopTransfer = flag; } -- (NSInteger)_numberOfRedirects +- (NSInteger) _numberOfRedirects { return _numberOfRedirects; } -- (void)_setNumberOfRedirects:(NSInteger)redirects +- (void) _setNumberOfRedirects: (NSInteger)redirects { _numberOfRedirects = redirects; } -- (NSInteger)_headerCallbackCount +- (NSInteger) _headerCallbackCount { return _headerCallbackCount; } -- (void)_setHeaderCallbackCount:(NSInteger)count +- (void) _setHeaderCallbackCount: (NSInteger)count { _headerCallbackCount = count; } /* Creates a temporary file and opens a file handle for writing */ -- (NSFileHandle *)_createTemporaryFileHandleWithError:(NSError **)error +- (NSFileHandle *) _createTemporaryFileHandleWithError: (NSError **)error { - NSFileManager *mgr; - NSFileHandle *handle; - NSString *path; - NSURL *url; + NSFileManager * mgr; + NSFileHandle * handle; + NSString * path; + NSURL * url; mgr = [NSFileManager defaultManager]; path = NSTemporaryDirectory(); - path = [path stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]]; + path = [path stringByAppendingPathComponent: [[NSUUID UUID] UUIDString]]; - url = [NSURL fileURLWithPath:path]; - [_taskData setObject:url forKey:taskTemporaryFileLocationKey]; + url = [NSURL fileURLWithPath: path]; + [_taskData setObject: url forKey: taskTemporaryFileLocationKey]; - if (![mgr createFileAtPath:path contents:nil attributes:nil]) + if (![mgr createFileAtPath: path contents: nil attributes: nil]) { if (error) { - NSString *errorDescription = [NSString - stringWithFormat:@"Failed to create temporary file at path %@", - path]; + NSString * errorDescription = [NSString + stringWithFormat: + @"Failed to create temporary file at path %@", + path]; *error = [NSError - errorWithDomain:NSCocoaErrorDomain - code:NSURLErrorCannotCreateFile - userInfo:@{NSLocalizedDescriptionKey : errorDescription}]; + errorWithDomain: NSCocoaErrorDomain + code: NSURLErrorCannotCreateFile + userInfo: @{ NSLocalizedDescriptionKey: + errorDescription }]; } return nil; } - handle = [NSFileHandle fileHandleForWritingAtPath:path]; - [_taskData setObject:handle forKey:taskTemporaryFileHandleKey]; + handle = [NSFileHandle fileHandleForWritingAtPath: path]; + [_taskData setObject: handle forKey: taskTemporaryFileHandleKey]; return handle; -} +} /* _createTemporaryFileHandleWithError */ /* Called in _checkForCompletion */ -- (void)_transferFinishedWithCode:(CURLcode)code +- (void) _transferFinishedWithCode: (CURLcode)code { - NSError *error = errorForCURLcode(_easyHandle, code, _curlErrorBuffer); + NSError * error = errorForCURLcode(_easyHandle, code, _curlErrorBuffer); if (_properties & GSURLSessionWritesDataToFile) { - NSFileHandle *handle; + NSFileHandle * handle; - if (nil != (handle = [_taskData objectForKey:taskTemporaryFileHandleKey])) + if (nil != + (handle = [_taskData objectForKey: taskTemporaryFileHandleKey])) { [handle closeFile]; } @@ -1289,25 +1346,25 @@ - (void)_transferFinishedWithCode:(CURLcode)code if (_properties & GSURLSessionUpdatesDelegate) { if (_properties & GSURLSessionWritesDataToFile && - [_delegate respondsToSelector:didFinishDownloadingToURLSel]) + [_delegate respondsToSelector: didFinishDownloadingToURLSel]) { - NSURL *url = [_taskData objectForKey:taskTemporaryFileLocationKey]; + NSURL * url = [_taskData objectForKey: taskTemporaryFileLocationKey]; [[_session delegateQueue] addOperationWithBlock:^{ - [(id) _delegate - URLSession:_session - downloadTask:(NSURLSessionDownloadTask *) self - didFinishDownloadingToURL:url]; - }]; + [(id) _delegate + URLSession: _session + downloadTask: (NSURLSessionDownloadTask *)self + didFinishDownloadingToURL: url]; + }]; } - if ([_delegate respondsToSelector:didCompleteWithErrorSel]) + if ([_delegate respondsToSelector: didCompleteWithErrorSel]) { [[_session delegateQueue] addOperationWithBlock:^{ - [_delegate URLSession:_session - task:self - didCompleteWithError:error]; - }]; + [_delegate URLSession: _session + task: self + didCompleteWithError: error]; + }]; } } @@ -1316,42 +1373,42 @@ - (void)_transferFinishedWithCode:(CURLcode)code */ if ((_properties & GSURLSessionStoresDataInMemory) && (_properties & GSURLSessionHasCompletionHandler) && - [self isKindOfClass:dataTaskClass]) + [self isKindOfClass: dataTaskClass]) { - NSURLSessionDataTask *dataTask; - NSData *data; + NSURLSessionDataTask * dataTask; + NSData * data; - dataTask = (NSURLSessionDataTask *) self; - data = [_taskData objectForKey:taskTransferDataKey]; + dataTask = (NSURLSessionDataTask *)self; + data = [_taskData objectForKey: taskTransferDataKey]; [[_session delegateQueue] addOperationWithBlock:^{ - [dataTask _completionHandler](data, _response, error); - }]; + [dataTask _completionHandler](data, _response, error); + }]; } else if ((_properties & GSURLSessionWritesDataToFile) && (_properties & GSURLSessionHasCompletionHandler) && - [self isKindOfClass:downloadTaskClass]) + [self isKindOfClass: downloadTaskClass]) { - NSURLSessionDownloadTask *downloadTask; - NSURL *tempFile; + NSURLSessionDownloadTask * downloadTask; + NSURL * tempFile; - downloadTask = (NSURLSessionDownloadTask *) self; - tempFile = [_taskData objectForKey:taskTemporaryFileLocationKey]; + downloadTask = (NSURLSessionDownloadTask *)self; + tempFile = [_taskData objectForKey: taskTemporaryFileLocationKey]; [[_session delegateQueue] addOperationWithBlock:^{ - [downloadTask _completionHandler](tempFile, _response, error); - }]; + [downloadTask _completionHandler](tempFile, _response, error); + }]; } RELEASE(_session); -} +} /* _transferFinishedWithCode */ /* Called in header_callback */ -- (void)_setCookiesFromHeaders:(NSDictionary *)headers +- (void) _setCookiesFromHeaders: (NSDictionary *)headers { - NSURL *url; - NSArray *cookies; - NSURLSessionConfiguration *config; + NSURL * url; + NSArray * cookies; + NSURLSessionConfiguration * config; config = [_session configuration]; url = [_currentRequest URL]; @@ -1360,20 +1417,20 @@ - (void)_setCookiesFromHeaders:(NSDictionary *)headers if (NSHTTPCookieAcceptPolicyNever != [config HTTPCookieAcceptPolicy] && nil != [config HTTPCookieStorage]) { - cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:headers - forURL:url]; + cookies = [NSHTTPCookie cookiesWithResponseHeaderFields: headers + forURL: url]; if ([cookies count] > 0) { - [[config HTTPCookieStorage] setCookies:cookies - forURL:url - mainDocumentURL:nil]; + [[config HTTPCookieStorage] setCookies: cookies + forURL: url + mainDocumentURL: nil]; } } -} +} /* _setCookiesFromHeaders */ #pragma mark - Public Methods -- (void)suspend +- (void) suspend { _suspendCount += 1; if (_suspendCount == 1) @@ -1387,7 +1444,7 @@ - (void)suspend _shouldStopTransfer = YES; } } -- (void)resume +- (void) resume { /* Only resume a transfer if the task is not suspended and in suspended state */ @@ -1400,12 +1457,12 @@ - (void)resume RETAIN(_session); _state = NSURLSessionTaskStateRunning; - [_session _resumeTask:self]; + [_session _resumeTask: self]; return; } _suspendCount -= 1; } -- (void)cancel +- (void) cancel { /* Transfer is aborted in the next libcurl progress_callback * @@ -1413,7 +1470,9 @@ - (void)cancel * URLSession:task:didCompleteWithError: is called after receiving * CURLMSG_DONE in -[NSURLSessionTask _checkForCompletion]. */ - dispatch_async([_session _workQueue], ^{ + dispatch_async( + [_session _workQueue], + ^{ /* Unpause the easy handle if previously paused */ curl_easy_pause(_easyHandle, CURLPAUSE_CONT); @@ -1422,29 +1481,29 @@ - (void)cancel }); } -- (float)priority +- (float) priority { return _priority; } -- (void)setPriority:(float)priority +- (void) setPriority: (float)priority { _priority = priority; } -- (id)copyWithZone:(NSZone *)zone +- (id) copyWithZone: (NSZone *)zone { - NSURLSessionTask *copy = [[[self class] alloc] init]; + NSURLSessionTask * copy = [[[self class] alloc] init]; if (copy) { - copy->_originalRequest = [_originalRequest copyWithZone:zone]; - copy->_currentRequest = [_currentRequest copyWithZone:zone]; - copy->_response = [_response copyWithZone:zone]; + copy->_originalRequest = [_originalRequest copyWithZone: zone]; + copy->_currentRequest = [_currentRequest copyWithZone: zone]; + copy->_response = [_response copyWithZone: zone]; /* FIXME: Seems like copyWithZone: is not implemented for NSProgress */ copy->_progress = [_progress copy]; - copy->_earliestBeginDate = [_earliestBeginDate copyWithZone:zone]; - copy->_taskDescription = [_taskDescription copyWithZone:zone]; - copy->_taskData = [_taskData copyWithZone:zone]; + copy->_earliestBeginDate = [_earliestBeginDate copyWithZone: zone]; + copy->_taskDescription = [_taskDescription copyWithZone: zone]; + copy->_taskData = [_taskData copyWithZone: zone]; copy->_easyHandle = curl_easy_duphandle(_easyHandle); } @@ -1453,103 +1512,106 @@ - (id)copyWithZone:(NSZone *)zone #pragma mark - Getter and Setter -- (NSUInteger)taskIdentifier +- (NSUInteger) taskIdentifier { return _taskIdentifier; } -- (NSURLRequest *)originalRequest +- (NSURLRequest *) originalRequest { return AUTORELEASE([_originalRequest copy]); } -- (NSURLRequest *)currentRequest +- (NSURLRequest *) currentRequest { return AUTORELEASE([_currentRequest copy]); } -- (NSURLResponse *)response +- (NSURLResponse *) response { return AUTORELEASE([_response copy]); } -- (NSURLSessionTaskState)state +- (NSURLSessionTaskState) state { return _state; } -- (NSProgress *)progress +- (NSProgress *) progress { return _progress; } -- (NSError *)error +- (NSError *) error { return _error; } -- (id)delegate +- (id) delegate { return _delegate; } -- (void)setDelegate:(id)delegate +- (void) setDelegate: (id)delegate { id oldDelegate = _delegate; + _delegate = RETAIN(delegate); RELEASE(oldDelegate); } -- (NSDate *)earliestBeginDate +- (NSDate *) earliestBeginDate { return _earliestBeginDate; } -- (void)setEarliestBeginDate:(NSDate *)date +- (void) setEarliestBeginDate: (NSDate *)date { - NSDate *oldDate = _earliestBeginDate; + NSDate * oldDate = _earliestBeginDate; + _earliestBeginDate = RETAIN(date); RELEASE(oldDate); } -- (int64_t)countOfBytesClientExpectsToSend +- (int64_t) countOfBytesClientExpectsToSend { return _countOfBytesClientExpectsToSend; } -- (int64_t)countOfBytesClientExpectsToReceive +- (int64_t) countOfBytesClientExpectsToReceive { return _countOfBytesClientExpectsToReceive; } -- (int64_t)countOfBytesSent +- (int64_t) countOfBytesSent { return _countOfBytesSent; } -- (int64_t)countOfBytesReceived +- (int64_t) countOfBytesReceived { return _countOfBytesReceived; } -- (int64_t)countOfBytesExpectedToSend +- (int64_t) countOfBytesExpectedToSend { return _countOfBytesExpectedToSend; } -- (int64_t)countOfBytesExpectedToReceive +- (int64_t) countOfBytesExpectedToReceive { return _countOfBytesExpectedToReceive; } -- (NSString *)taskDescription +- (NSString *) taskDescription { return _taskDescription; } -- (void)setTaskDescription:(NSString *)description +- (void) setTaskDescription: (NSString *)description { - NSString *oldDescription = _taskDescription; + NSString * oldDescription = _taskDescription; + _taskDescription = [description copy]; RELEASE(oldDescription); } -- (void)dealloc +- (void) dealloc { /* The session retains this task until the transfer is complete and the easy * handle removed from the multi handle. @@ -1574,17 +1636,17 @@ - (void)dealloc @implementation NSURLSessionDataTask -- (GSNSURLSessionDataCompletionHandler)_completionHandler +- (GSNSURLSessionDataCompletionHandler) _completionHandler { return _completionHandler; } -- (void)_setCompletionHandler:(GSNSURLSessionDataCompletionHandler)handler +- (void) _setCompletionHandler: (GSNSURLSessionDataCompletionHandler)handler { _completionHandler = _Block_copy(handler); } -- (void)dealloc +- (void) dealloc { _Block_release(_completionHandler); [super dealloc]; @@ -1597,27 +1659,27 @@ @implementation NSURLSessionUploadTask @implementation NSURLSessionDownloadTask -- (GSNSURLSessionDownloadCompletionHandler)_completionHandler +- (GSNSURLSessionDownloadCompletionHandler) _completionHandler { return _completionHandler; } -- (void)_setCompletionHandler:(GSNSURLSessionDownloadCompletionHandler)handler +- (void) _setCompletionHandler: (GSNSURLSessionDownloadCompletionHandler)handler { _completionHandler = _Block_copy(handler); } -- (int64_t)_countOfBytesWritten +- (int64_t) _countOfBytesWritten { return _countOfBytesWritten; }; -- (void)_updateCountOfBytesWritten:(int64_t)count +- (void) _updateCountOfBytesWritten: (int64_t)count { _countOfBytesWritten += count; } -- (void)dealloc +- (void) dealloc { _Block_release(_completionHandler); [super dealloc]; diff --git a/Source/NSURLSessionTaskPrivate.h b/Source/NSURLSessionTaskPrivate.h index 830e3c8a7..c28bdd053 100644 --- a/Source/NSURLSessionTaskPrivate.h +++ b/Source/NSURLSessionTaskPrivate.h @@ -1,32 +1,32 @@ /** - NSURLSessionTaskPrivate.h - - Copyright (C) 2017-2024 Free Software Foundation, Inc. - - Written by: Hugo Melder - Date: May 2024 - Author: Hugo Melder - - This file is part of GNUStep-base - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - If you are interested in a warranty or support for this source code, - contact Scott Christley for more information. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110 USA. -*/ + * NSURLSessionTaskPrivate.h + * + * Copyright (C) 2017-2024 Free Software Foundation, Inc. + * + * Written by: Hugo Melder + * Date: May 2024 + * Author: Hugo Melder + * + * This file is part of GNUStep-base + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * If you are interested in a warranty or support for this source code, + * contact Scott Christley for more information. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110 USA. + */ #import "Foundation/NSDictionary.h" #import "Foundation/NSFileHandle.h" @@ -34,23 +34,23 @@ #import @interface -NSURLSessionTask (Private) + NSURLSessionTask(Private) -- (instancetype)initWithSession:(NSURLSession *)session - request:(NSURLRequest *)request - taskIdentifier:(NSUInteger)identifier; +- (instancetype)initWithSession: (NSURLSession *)session + request: (NSURLRequest *)request + taskIdentifier: (NSUInteger)identifier; -- (CURL *)_easyHandle; +-(CURL *)_easyHandle; /* Enable or disable libcurl verbose output. Disabled by default. */ -- (void)_setVerbose:(BOOL)flag; +-(void)_setVerbose: (BOOL)flag; /* This method is called by -[NSURLSession _checkForCompletion] * * We release the session (previously retained in -[NSURLSessionTask resume]) * here and inform the delegate about the transfer state. */ -- (void)_transferFinishedWithCode:(CURLcode)code; +-(void)_transferFinishedWithCode: (CURLcode)code; /* Explicitly enable data upload with an optional estimated size. Set to 0 if * not available. @@ -58,66 +58,66 @@ NSURLSessionTask (Private) * This may be used when a body stream is passed at a later stage * (see URLSession:task:needNewBodyStream:). */ -- (void)_enableUploadWithSize:(NSInteger)size; -- (void)_setBodyStream:(NSInputStream *)stream; +-(void)_enableUploadWithSize: (NSInteger)size; +-(void)_setBodyStream: (NSInputStream *)stream; -- (void)_enableUploadWithData:(NSData *)data; -- (void)_enableAutomaticRedirects:(BOOL)flag; +-(void)_enableUploadWithData: (NSData *)data; +-(void)_enableAutomaticRedirects: (BOOL)flag; /* Assign with copying */ -- (void)_setOriginalRequest:(NSURLRequest *)request; -- (void)_setCurrentRequest:(NSURLRequest *)request; +-(void)_setOriginalRequest: (NSURLRequest *)request; +-(void)_setCurrentRequest: (NSURLRequest *)request; -- (void)_setResponse:(NSURLResponse *)response; -- (void)_setCookiesFromHeaders:(NSDictionary *)headers; +-(void)_setResponse: (NSURLResponse *)response; +-(void)_setCookiesFromHeaders: (NSDictionary *)headers; -- (void)_setCountOfBytesSent:(int64_t)count; -- (void)_setCountOfBytesReceived:(int64_t)count; -- (void)_setCountOfBytesExpectedToSend:(int64_t)count; -- (void)_setCountOfBytesExpectedToReceive:(int64_t)count; +-(void)_setCountOfBytesSent: (int64_t)count; +-(void)_setCountOfBytesReceived: (int64_t)count; +-(void)_setCountOfBytesExpectedToSend: (int64_t)count; +-(void)_setCountOfBytesExpectedToReceive: (int64_t)count; -- (NSMutableDictionary *)_taskData; +-(NSMutableDictionary *)_taskData; -- (NSURLSession *)_session; +-(NSURLSession *)_session; /* Task specific properties. * * See GSURLSessionProperties in NSURLSessionPrivate.h. */ -- (NSInteger)_properties; -- (void)_setProperties:(NSInteger)properties; +-(NSInteger)_properties; +-(void)_setProperties: (NSInteger)properties; /* This value is periodically checked in progress_callback. * We then abort the transfer in the progress_callback if this flag is set. */ -- (BOOL)_shouldStopTransfer; -- (void)_setShouldStopTransfer:(BOOL)flag; +-(BOOL)_shouldStopTransfer; +-(void)_setShouldStopTransfer: (BOOL)flag; -- (NSInteger)_numberOfRedirects; -- (void)_setNumberOfRedirects:(NSInteger)redirects; +-(NSInteger)_numberOfRedirects; +-(void)_setNumberOfRedirects: (NSInteger)redirects; -- (NSInteger)_headerCallbackCount; -- (void)_setHeaderCallbackCount:(NSInteger)count; +-(NSInteger)_headerCallbackCount; +-(void)_setHeaderCallbackCount: (NSInteger)count; -- (NSFileHandle *)_createTemporaryFileHandleWithError:(NSError **)error; +-(NSFileHandle *)_createTemporaryFileHandleWithError: (NSError **)error; @end @interface -NSURLSessionDataTask (Private) + NSURLSessionDataTask(Private) - (GSNSURLSessionDataCompletionHandler)_completionHandler; -- (void)_setCompletionHandler:(GSNSURLSessionDataCompletionHandler)handler; +-(void)_setCompletionHandler: (GSNSURLSessionDataCompletionHandler)handler; @end @interface -NSURLSessionDownloadTask (Private) + NSURLSessionDownloadTask(Private) - (GSNSURLSessionDownloadCompletionHandler)_completionHandler; -- (int64_t)_countOfBytesWritten; -- (void)_updateCountOfBytesWritten:(int64_t)count; -- (void)_setCompletionHandler:(GSNSURLSessionDownloadCompletionHandler)handler; +-(int64_t)_countOfBytesWritten; +-(void)_updateCountOfBytesWritten: (int64_t)count; +-(void)_setCompletionHandler: (GSNSURLSessionDownloadCompletionHandler)handler; @end \ No newline at end of file