forked from gnustep/libs-base
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GSMultiHandle.m
517 lines (431 loc) · 13.8 KB
/
GSMultiHandle.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
#import "GSMultiHandle.h"
#import "GSTimeoutSource.h"
#import "GSEasyHandle.h"
#import "Foundation/NSArray.h"
#import "Foundation/NSDictionary.h"
#import "Foundation/NSError.h"
#import "Foundation/NSException.h"
#import "Foundation/NSURLError.h"
#import "Foundation/NSURLSession.h"
#import "Foundation/NSValue.h"
@interface GSMultiHandle ()
- (void) readAndWriteAvailableDataOnSocket: (curl_socket_t)socket;
- (void) readMessages;
- (void) completedTransferForEasyHandle: (CURL*)rawEasyHandle
easyCode: (CURLcode)easyCode;
- (void) performAction: (int) action
forSocket: (curl_socket_t) socket;
- (int) socketCallback: (CURL *) easy
socket: (curl_socket_t) socket
what: (int) what
socketp: (void *)socketp;
- (int) timerCallback: (CURLM *)multi
timeout_ms: (long)timeout_ms;
@end
/*
* Read and write libdispatch sources for a specific socket.
*
* A simple helper that combines two sources -- both being optional.
*
* This info is stored into the socket using `curl_multi_assign()`.
*
* - SeeAlso: GSSocketRegisterAction
*/
@interface GSSocketSources : NSObject
- (instancetype) initWithSocket: (curl_socket_t)socket
readReadyBlock: (dispatch_block_t)readReadyBlock
writeReadyBlock: (dispatch_block_t)writeReadyBlock
queue: (dispatch_queue_t)queue;
- (void) setReadable: (BOOL)readable
andWritable: (BOOL)writable;
@end
static void handleEasyCode(int code)
{
if (CURLE_OK != code)
{
NSString *reason;
NSException *e;
reason = [NSString stringWithFormat: @"An error occurred, CURLcode is %d",
code];
e = [NSException exceptionWithName: @"libcurl.easy"
reason: reason
userInfo: nil];
[e raise];
}
}
static void handleMultiCode(int code)
{
if (CURLM_OK != code)
{
NSString *reason;
NSException *e;
reason = [NSString stringWithFormat: @"An error occurred, CURLcode is %d", code];
e = [NSException exceptionWithName: @"libcurl.multi"
reason: reason
userInfo: nil];
[e raise];
}
}
static int curl_socket_function(CURL *easy, curl_socket_t socket, int what, void *clientp, void *socketp)
{
GSMultiHandle *handle = (GSMultiHandle *)clientp;
return [handle socketCallback: easy
socket: socket
what: what
socketp: socketp];
}
static int curl_timer_function(CURLM *multi, long timeout_ms, void *clientp)
{
GSMultiHandle *handle = (GSMultiHandle *)clientp;
return [handle timerCallback: multi
timeout_ms: timeout_ms];
}
@implementation GSMultiHandle
{
NSMutableArray *_easyHandles;
dispatch_queue_t _sourcesQueue;
dispatch_queue_t _queue;
GSTimeoutSource *_timeoutSource;
int _runningHandlesCount;
}
- (CURLM*) rawHandle
{
return _rawHandle;
}
- (instancetype) initWithConfiguration: (NSURLSessionConfiguration*)conf
workQueue: (dispatch_queue_t)aQueue
{
if (nil != (self = [super init]))
{
_rawHandle = curl_multi_init();
_easyHandles = [[NSMutableArray alloc] init];
_sourcesQueue = dispatch_queue_create("GSMultiHandle.sourcesqueue", DISPATCH_QUEUE_SERIAL);
#if HAVE_DISPATCH_QUEUE_CREATE_WITH_TARGET
_queue = dispatch_queue_create_with_target("GSMultiHandle.isolation",
DISPATCH_QUEUE_SERIAL, aQueue);
#else
_queue = dispatch_queue_create("GSMultiHandle.isolation",
DISPATCH_QUEUE_SERIAL);
dispatch_set_target_queue(_queue, aQueue);
#endif
[self setupCallbacks];
[self configureWithConfiguration: conf];
}
return self;
}
- (void) dealloc
{
NSEnumerator *e;
GSEasyHandle *handle;
[_timeoutSource cancel];
DESTROY(_timeoutSource);
dispatch_release(_sourcesQueue);
dispatch_release(_queue);
e = [_easyHandles objectEnumerator];
while (nil != (handle = [e nextObject]))
{
curl_multi_remove_handle([handle rawHandle], _rawHandle);
}
DESTROY(_easyHandles);
curl_multi_cleanup(_rawHandle);
[super dealloc];
}
- (void) configureWithConfiguration: (NSURLSessionConfiguration*)configuration
{
handleEasyCode(curl_multi_setopt(_rawHandle, CURLMOPT_MAX_HOST_CONNECTIONS, [configuration HTTPMaximumConnectionsPerHost]));
handleEasyCode(curl_multi_setopt(_rawHandle, CURLMOPT_PIPELINING, [configuration HTTPShouldUsePipelining] ? CURLPIPE_MULTIPLEX : CURLPIPE_NOTHING));
}
- (void)setupCallbacks
{
handleEasyCode(curl_multi_setopt(_rawHandle, CURLMOPT_SOCKETDATA, (void*)self));
handleEasyCode(curl_multi_setopt(_rawHandle, CURLMOPT_SOCKETFUNCTION, curl_socket_function));
handleEasyCode(curl_multi_setopt(_rawHandle, CURLMOPT_TIMERDATA, (__bridge void *)self));
handleEasyCode(curl_multi_setopt(_rawHandle, CURLMOPT_TIMERFUNCTION, curl_timer_function));
}
- (void) addHandle: (GSEasyHandle*)easyHandle
{
// If this is the first handle being added, we need to `kick` the
// underlying multi handle by calling `timeoutTimerFired` as
// described in
// <https://curl.haxx.se/libcurl/c/curl_multi_socket_action.html>.
// That will initiate the registration for timeout timer and socket
// readiness.
BOOL needsTimeout = false;
if ([_easyHandles count] == 0)
{
needsTimeout = YES;
}
[_easyHandles addObject: easyHandle];
handleMultiCode(curl_multi_add_handle(_rawHandle, [easyHandle rawHandle]));
if (needsTimeout)
{
[self timeoutTimerFired];
}
}
- (void) removeHandle: (GSEasyHandle*)easyHandle
{
NSEnumerator *e;
int idx = 0;
BOOL found = NO;
GSEasyHandle *h;
e = [_easyHandles objectEnumerator];
while (nil != (h = [e nextObject]))
{
if ([h rawHandle] == [easyHandle rawHandle])
{
found = YES;
break;
}
idx++;
}
NSAssert(found, @"Handle not in list.");
handleMultiCode(curl_multi_remove_handle(_rawHandle, [easyHandle rawHandle]));
[_easyHandles removeObjectAtIndex: idx];
}
- (void) timeoutTimerFired
{
[self readAndWriteAvailableDataOnSocket: CURL_SOCKET_TIMEOUT];
}
- (void) readAndWriteAvailableDataOnSocket: (curl_socket_t)socket
{
do
{
handleMultiCode(curl_multi_perform(_rawHandle, &_runningHandlesCount));
if (_runningHandlesCount)
{
handleMultiCode(curl_multi_poll(_rawHandle, NULL, 0, 10000, NULL));
}
}
while (_runningHandlesCount);
handleMultiCode(curl_multi_socket_action(_rawHandle, socket, 0, &_runningHandlesCount));
[self readMessages];
}
/// Check the status of all individual transfers.
///
/// libcurl refers to this as “read multi stack informationals”.
/// Check for transfers that completed.
- (void) readMessages
{
while (true)
{
int count = 0;
CURLMsg *msg;
CURL *easyHandle;
int code;
msg = curl_multi_info_read(_rawHandle, &count);
if (NULL == msg || CURLMSG_DONE != msg->msg || !msg->easy_handle) break;
easyHandle = msg->easy_handle;
code = msg->data.result;
[self completedTransferForEasyHandle: easyHandle easyCode: code];
}
}
- (void) completedTransferForEasyHandle: (CURL*)rawEasyHandle
easyCode: (CURLcode)easyCode
{
NSEnumerator *e;
GSEasyHandle *h;
GSEasyHandle *handle = nil;
NSError *err = nil;
int errCode;
e = [_easyHandles objectEnumerator];
while (nil != (h = [e nextObject]))
{
if ([h rawHandle] == rawEasyHandle)
{
handle = h;
break;
}
}
NSAssert(nil != handle, @"Transfer completed for easy handle"
@", but it is not in the list of added handles.");
errCode = [handle urlErrorCodeWithEasyCode: easyCode];
if (0 != errCode)
{
NSString *d = nil;
if ([handle errorBuffer][0] == 0)
{
const char *description = curl_easy_strerror(errCode);
d = [[NSString alloc] initWithCString: description
encoding: NSUTF8StringEncoding];
}
else
{
d = [[NSString alloc] initWithCString: [handle errorBuffer]
encoding: NSUTF8StringEncoding];
}
err = [NSError errorWithDomain: NSURLErrorDomain
code: errCode
userInfo: @{NSLocalizedDescriptionKey : d, NSUnderlyingErrorKey: [NSNumber numberWithInt:easyCode]}];
RELEASE(d);
}
[handle transferCompletedWithError: err];
}
- (void) performAction: (int)action
forSocket: (curl_socket_t)socket
{
dispatch_async(_queue,
^{
curl_multi_socket_action(_rawHandle, socket, action, &_runningHandlesCount);
[self readMessages];
});
}
- (int) socketCallback: (CURL *)easy
socket: (curl_socket_t)socket
what: (int)what
socketp: (void *)socketp
{
GSSocketSources *sources = (GSSocketSources *)socketp;
switch(what)
{
case CURL_POLL_IN:
case CURL_POLL_OUT:
case CURL_POLL_INOUT:
if (!sources)
{
sources = [[GSSocketSources alloc] initWithSocket: socket
readReadyBlock: ^{
[self performAction: CURL_CSELECT_IN forSocket: socket];
}
writeReadyBlock: ^{
[self performAction: CURL_CSELECT_OUT forSocket: socket];
}
queue: _sourcesQueue];
curl_multi_assign(_rawHandle, socket, (void *)sources);
}
[sources setReadable: (what != CURL_POLL_OUT)
andWritable: (what != CURL_POLL_IN)];
break;
case CURL_POLL_REMOVE:
curl_multi_assign(_rawHandle, socket, NULL);
DESTROY(sources);
break;
default:
{
NSDictionary *userInfo = @{ @"NSURLSession.CURL_POLL": @(what) };
NSException *exception = [NSException exceptionWithName: @"NSURLSession.libcurl"
reason: @"Invalid CURL_POLL value"
userInfo: userInfo];
[exception raise];
return -1;
}
}
return 0;
}
- (int) timerCallback: (CURLM *)multi
timeout_ms: (long)timeout_ms
{
// A timeout_ms value of -1 passed to this callback means you should delete
// the timer. All other values are valid expire times in number
// of milliseconds.
if (-1 == timeout_ms)
{
[_timeoutSource suspend];
}
else
{
if (!_timeoutSource)
{
_timeoutSource = [[GSTimeoutSource alloc] initWithQueue: _queue
handler: ^{
[self timeoutTimerFired];
}];
}
[_timeoutSource setTimeout: timeout_ms];
}
}
@end
@implementation GSSocketSources
{
curl_socket_t _socket;
dispatch_block_t _readReadyBlock;
dispatch_block_t _writeReadyBlock;
dispatch_queue_t _queue;
dispatch_source_t _readSource;
dispatch_source_t _writeSource;
}
- (instancetype) initWithSocket: (curl_socket_t)socket
readReadyBlock: (dispatch_block_t)readReadyBlock
writeReadyBlock: (dispatch_block_t)writeReadyBlock
queue: (dispatch_queue_t)queue
{
if ((self = [super init]))
{
_socket = socket;
_readReadyBlock = [readReadyBlock copy];
_writeReadyBlock = [writeReadyBlock copy];
_queue = queue;
}
return self;
}
- (void) setReadable: (BOOL)readable
andWritable: (BOOL)writable
{
if (_readSource && !readable)
{
dispatch_source_cancel(_readSource);
dispatch_release(_readSource);
_readSource = NULL;
}
else if (readable && !_readSource)
{
_readSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, _socket, 0, _queue);
dispatch_source_set_event_handler(_readSource, _readReadyBlock);
dispatch_resume(_readSource);
}
if (_writeSource && !writable)
{
dispatch_source_cancel(_writeSource);
dispatch_release(_writeSource);
_writeSource = NULL;
}
else if (writable && !_writeSource)
{
_writeSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, _socket, 0, _queue);
dispatch_source_set_event_handler(_writeSource, _writeReadyBlock);
dispatch_resume(_writeSource);
}
}
- (void) dealloc
{
dispatch_group_t group;
group = dispatch_group_create();
if (_readSource)
{
dispatch_group_enter(group);
dispatch_source_set_cancel_handler(
_readSource,
^{
dispatch_group_leave(group);
});
dispatch_source_cancel(_readSource);
}
if (_writeSource)
{
dispatch_group_enter(group);
dispatch_source_set_cancel_handler(
_writeSource,
^{
dispatch_group_leave(group);
});
dispatch_source_cancel(_writeSource);
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
dispatch_release(group);
group = nil;
if (_readSource)
{
dispatch_release(_readSource);
_readSource = NULL;
}
if (_writeSource)
{
dispatch_release(_writeSource);
_writeSource = NULL;
}
_socket = 0;
DESTROY(_readReadyBlock);
DESTROY(_writeReadyBlock);
_queue = nil;
[super dealloc];
}
@end