-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSZURLConnection.m
More file actions
626 lines (538 loc) · 19.3 KB
/
SZURLConnection.m
File metadata and controls
626 lines (538 loc) · 19.3 KB
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
//
// SZURLConnection.h
//
// Created by Jon Nall on 10/9/09.
// Copyright 2009-2013 STUNTAZ!!! All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// Neither the name of Jon Nall nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// SZHTTPURLResponse uses code found In the connection framework
// http://opensource.utr-software.com/connection/
// Which is licensed under the BSD license
// Copyright 2009 Karelia Software. All rights reserved.
//
#import "SZURLConnection.h"
NSString* const kszURLProxyHost = @"kszURLProxyHost";
NSString* const kszURLProxyPort = @"kszURLProxyPort";
NSString* const kszURLErrorDomain = @"org.stuntaz.SZURLErrorDomain";
const NSUInteger kszURLCouldNotCreateStream = -1000;
static NSUInteger kszURLBufferSize = 32 * 1024;
@interface SZURLConnection(Private)
-(void)startConnection;
-(void)handleStreamEvent:(CFStreamEventType)eventType
onStream:(CFReadStreamRef)cfStream;
+(NSOperationQueue*)urlQueue;
@end
#pragma mark -
#pragma mark SZHTTPURLResponse Implementation
@implementation SZHTTPURLResponse
-(id)initWithURL:(NSURL*)URL
HTTPMessage:(CFHTTPMessageRef)message
{
_headerFields = NSMakeCollectable(CFHTTPMessageCopyAllHeaderFields(message));
NSString* MIMEType = [_headerFields objectForKey:@"Content-Type"];
NSInteger contentLength = [[_headerFields objectForKey:@"Content-Length"] intValue];
NSString* encoding = [_headerFields objectForKey:@"Content-Encoding"];
if((self = [super initWithURL:URL
MIMEType:MIMEType
expectedContentLength:contentLength
textEncodingName:encoding]))
{
_statusCode = CFHTTPMessageGetResponseStatusCode(message);
}
return self;
}
-(void)dealloc
{
[_headerFields release];
[super dealloc];
}
-(NSDictionary*)allHeaderFields
{
return _headerFields;
}
-(NSInteger)statusCode
{
return _statusCode;
}
-(NSString*)description
{
return [NSString stringWithFormat:@"Status %ld: <%@:0x%p>", [self statusCode], [self class], self];
}
@end
#pragma mark -
#pragma mark Synchronous Request Implementation
@interface SZURLSyncRequestDelegate : NSObject<SZURLConnectionDelegate>
{
NSTimer* timeoutTimer;
NSMutableData* reqData;
NSURLResponse* reqResponse;
NSError* reqError;
NSCondition* condition;
BOOL complete;
BOOL timedOut;
}
@property (retain) NSURLResponse* reqResponse;
@property (retain) NSError* reqError;
-(NSData*)waitForCompletion:(NSURLResponse**)reponse
withTimeout:(const NSTimeInterval)timeout
error:(NSError**)error;
@end
@implementation SZURLSyncRequestDelegate
@synthesize reqResponse;
@synthesize reqError;
-(id)init
{
self = [super init];
if(self != nil)
{
reqData = [[NSMutableData alloc] init];
condition = [[NSCondition alloc] init];
complete = NO;
timedOut = NO;
}
return self;
}
-(void)dealloc
{
[timeoutTimer release];
[reqData release];
[condition release];
[reqError release];
[reqResponse release];
[super dealloc];
}
-(void)timeout:(NSTimer*)timer
{
NSLog(@"%@ TIMEOUT! (%f seconds)", [self class], [[timer userInfo] doubleValue]);
[condition lock];
timedOut = YES;
[condition signal];
[condition unlock];
}
-(NSData*)waitForCompletion:(NSURLResponse**)response
withTimeout:(const NSTimeInterval)timeout
error:(NSError**)error
{
if(timeout != 0)
{
dispatch_queue_t queue = dispatch_queue_create("timerQueue", 0);
dispatch_async(queue, ^{
timeoutTimer = [[NSTimer scheduledTimerWithTimeInterval:timeout
target:self
selector:@selector(timeout:)
userInfo:[NSNumber numberWithDouble:timeout]
repeats:NO] retain];
});
}
[condition lock];
while(complete == NO && timedOut == NO)
{
[condition wait];
}
[condition unlock];
[timeoutTimer invalidate];
NSData* result = reqData;
if(response != nil)
{
*response = self.reqResponse;
}
if(timedOut)
{
if(error != nil)
{
*error = [NSError errorWithDomain:NSCocoaErrorDomain
code:NSURLErrorTimedOut
userInfo:nil];
return nil;
}
}
// On error, set result to nil and set error if it's non-nil
//
if(self.reqError != nil)
{
result = nil;
if(error != nil)
{
*error = self.reqError;
}
}
return result;
}
-(void)szConnection:(SZURLConnection*)connection
didReceiveResponse:(NSURLResponse*)response
{
self.reqResponse = response;
}
-(void)szConnection:(SZURLConnection*)connection
didReceiveData:(NSData*)data
{
[reqData appendData:data];
}
-(void)szConnectionDidFinishLoading:(SZURLConnection*)connection
{
[condition lock];
complete = YES;
[condition signal];
[condition unlock];
}
-(void)szConnection:(SZURLConnection*)connection
didFailWithError:(NSError*)error
{
[condition lock];
self.reqError = error;
complete = YES;
[condition signal];
[condition unlock];
}
@end
#pragma mark -
#pragma mark Stream Callback
static void SZStreamCallback(CFReadStreamRef stream,
CFStreamEventType eventType,
void* context)
{
SZURLConnection* connection = (SZURLConnection*)context;
[connection handleStreamEvent:eventType onStream:stream];
}
#pragma mark -
#pragma mark SZURLConnection Public Methods
@implementation SZURLConnection
@synthesize delegate = _delegate;
@synthesize minimumDataSize = _minimumDataSize;
+(void)initialize
{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* host = @"";
NSNumber* port = [NSNumber numberWithUnsignedInteger:0];
NSDictionary* proxyDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
host, kszURLProxyHost,
port, kszURLProxyPort,
nil];
[defaults registerDefaults:proxyDefaults];
}
+(NSData*)sendSynchronousRequest:(NSURLRequest*)request
returningResponse:(NSURLResponse**)response
error:(NSError**)error
{
return [SZURLConnection sendSynchronousRequest:request
returningResponse:response
withTimeout:30
error:error];
}
+(NSData*)sendSynchronousRequest:(NSURLRequest*)request
returningResponse:(NSURLResponse**)response
withTimeout:(const NSTimeInterval)timeout
error:(NSError**)error
{
SZURLSyncRequestDelegate* syncDelegate = [[SZURLSyncRequestDelegate alloc] init];
SZURLConnection* connection = [[SZURLConnection alloc] initWithRequest:request
delegate:syncDelegate];
(void)connection; // It's started implcitly in the -initWithRequest
NSData* result = [syncDelegate waitForCompletion:response
withTimeout:timeout
error:error];
[connection release];
[syncDelegate release];
return result;
}
-(id)initWithRequest:(NSURLRequest*)request
delegate:(id)delegate
startImmediately:(BOOL)startImmediately
{
self = [super init];
if(self != nil)
{
[self setDelegate:delegate];
_request = [request copy];
_currentData = [[NSMutableData alloc] initWithCapacity:kszURLBufferSize];
_minimumDataSize = 10;
if(startImmediately)
{
[self start];
}
}
return self;
}
-(id)initWithRequest:(NSURLRequest*)request
delegate:(id)delegate
{
self = [self initWithRequest:request
delegate:delegate
startImmediately:YES];
return self;
}
-(void)dealloc
{
if(_cfStream != NULL)
{
CFReadStreamSetClient(_cfStream, kCFStreamEventNone, NULL, NULL);
CFReadStreamUnscheduleFromRunLoop(_cfStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
CFReadStreamClose(_cfStream);
CFRelease(_cfStream);
_cfStream = NULL;
}
[_currentData release];
[_delegate release];
[_request release];
[super dealloc];
}
-(NSURL*)URL
{
return [_request URL];
}
-(void)start
{
NSInvocationOperation* op = [[[NSInvocationOperation alloc]
initWithTarget:self
selector:@selector(startConnection)
object:nil]
autorelease];
[[SZURLConnection urlQueue] addOperation:op];
}
-(void)cancel
{
if(_cfStream != NULL)
{
CFReadStreamSetClient(_cfStream, kCFStreamEventNone, NULL, NULL);
CFReadStreamUnscheduleFromRunLoop(_cfStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
CFReadStreamClose(_cfStream);
CFRelease(_cfStream);
_cfStream = NULL;
}
}
#pragma mark -
#pragma mark Delegate Methods
-(void)szConnection:(SZURLConnection*)connection
didReceiveResponse:(NSURLResponse*)response
{
[self.delegate szConnection:connection didReceiveResponse:response];
}
-(void)szConnection:(SZURLConnection*)connection
didReceiveData:(NSData*)data
{
[self.delegate szConnection:connection didReceiveData:data];
}
-(void)szConnectionDidFinishLoading:(SZURLConnection*)connection
{
[self.delegate szConnectionDidFinishLoading:connection];
}
-(void)szConnection:(SZURLConnection*)connection
didFailWithError:(NSError*)error
{
[self.delegate szConnection:connection didFailWithError:error];
}
@end
#pragma mark -
#pragma mark SZURLConnection Private Methods
@implementation SZURLConnection(Private)
-(void)startConnection
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
_sentResponse = NO;
CFHTTPMessageRef cfRequest =
CFHTTPMessageCreateRequest(kCFAllocatorDefault,
(CFStringRef)[_request HTTPMethod],
(CFURLRef)[_request URL],
kCFHTTPVersion1_1);
CFHTTPMessageSetBody(cfRequest, (CFDataRef)[_request HTTPBody]);
NSDictionary* headers = [_request allHTTPHeaderFields];
for(NSString* header in [headers keyEnumerator])
{
CFHTTPMessageSetHeaderFieldValue(cfRequest,
(CFStringRef)header,
(CFStringRef)[headers objectForKey:header]);
}
_cfStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault,
cfRequest);
NSString* proxyHost = [[NSUserDefaults standardUserDefaults] stringForKey:kszURLProxyHost];
if(proxyHost != nil && [proxyHost length] > 0)
{
NSString* proxyPortStr = [[NSUserDefaults standardUserDefaults] objectForKey:kszURLProxyPort];
NSNumber* proxyPort = [NSNumber numberWithInteger:[proxyPortStr integerValue]];
NSLog(@"Using HTTP proxy: %@:%@", proxyHost, proxyPort);
NSDictionary* proxyDict = [NSDictionary dictionaryWithObjectsAndKeys:
proxyHost, kCFStreamPropertySOCKSProxyHost,
proxyPort, kCFStreamPropertySOCKSProxyPort,
nil];
CFReadStreamSetProperty(_cfStream, kCFStreamPropertySOCKSProxy, proxyDict);
}
if([[self.URL scheme] isEqualToString:@"https"])
{
NSDictionary* sslProps = [NSDictionary dictionaryWithObjectsAndKeys:
(id)kCFNull, kCFStreamSSLPeerName,
nil];
CFReadStreamSetProperty(_cfStream, kCFStreamPropertySSLSettings, sslProps);
}
CFRelease(cfRequest);
CFOptionFlags registeredEvents = kCFStreamEventHasBytesAvailable |
kCFStreamEventErrorOccurred |
kCFStreamEventEndEncountered;
// Version 0
// void* = self
// release, retain, copy callbacks are NULL
CFStreamClientContext context = {0, self, NULL, NULL, NULL};
if(CFReadStreamSetClient(_cfStream, registeredEvents, &SZStreamCallback, &context))
{
CFReadStreamScheduleWithRunLoop(_cfStream, CFRunLoopGetCurrent(),
kCFRunLoopCommonModes);
}
if(CFReadStreamOpen(_cfStream) == TRUE)
{
// CFError and NSError are toll-free bridged
NSError* error = (NSError*)CFReadStreamCopyError(_cfStream);
if(error == nil)
{
// start the run loop
CFRunLoopRun();
}
else
{
NSLog(@"Stream error occurred: %@", error);
[[self delegate] szConnection:self
didFailWithError:error];
[error release];
}
}
else
{
NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
[_request URL], NSURLErrorKey,
nil];
NSError* error = [NSError errorWithDomain:kszURLErrorDomain
code:kszURLCouldNotCreateStream
userInfo:userInfo];
NSLog(@"Could not open stream: %@", error);
[[self delegate] szConnection:self
didFailWithError:error];
}
[pool drain];
}
-(void)handleStreamEvent:(CFStreamEventType)eventType
onStream:(CFReadStreamRef)cfStream
{
switch(eventType)
{
case kCFStreamEventOpenCompleted:
case kCFStreamEventCanAcceptBytes:
case kCFStreamEventNone:
{
// Do nothing
break;
}
case kCFStreamEventErrorOccurred:
{
// Send in any pending data
//
if([_currentData length] > 0)
{
[self szConnection:self didReceiveData:[[_currentData copy] autorelease]];
[_currentData setLength:0];
}
// CFError and NSError are toll-free bridged
NSError* error = (NSError*)CFReadStreamCopyError(cfStream);
if(error != nil)
{
NSLog(@"Stream error occurred: %@", error);
[[self delegate] szConnection:self
didFailWithError:error];
[error release];
}
CFReadStreamUnscheduleFromRunLoop(cfStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
CFReadStreamClose(cfStream);
break;
}
case kCFStreamEventEndEncountered:
{
// Send in any pending data
//
if([_currentData length] > 0)
{
NSLog(@"Sending in last %lu bytes of data before completion", [_currentData length]);
[self szConnection:self didReceiveData:[[_currentData copy] autorelease]];
[_currentData setLength:0];
}
[self szConnectionDidFinishLoading:self];
CFReadStreamUnscheduleFromRunLoop(cfStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
CFReadStreamClose(cfStream);
break;
}
case kCFStreamEventHasBytesAvailable:
{
// Check if header is done
if(_sentResponse == NO)
{
CFHTTPMessageRef cfResponse = (CFHTTPMessageRef)CFReadStreamCopyProperty(cfStream,
kCFStreamPropertyHTTPResponseHeader);
if(cfResponse != NULL && CFHTTPMessageIsHeaderComplete(cfResponse))
{
SZHTTPURLResponse* response = [[[SZHTTPURLResponse alloc] initWithURL:[_request URL]
HTTPMessage:cfResponse]
autorelease];
[self szConnection:self didReceiveResponse:response];
_sentResponse = YES;
}
if(cfResponse != NULL)
{
CFRelease(cfResponse);
}
}
// Now handle data
{
uint8_t buffer[kszURLBufferSize];
CFIndex bytesRead = 0;
bytesRead = CFReadStreamRead(cfStream, buffer, sizeof(buffer));
if(bytesRead == -1)
{
NSLog(@"CFReadStreamRead returned -1 bytesRead");
[self handleStreamEvent:kCFStreamEventErrorOccurred onStream:cfStream];
}
else
{
[_currentData appendBytes:buffer
length:bytesRead];
if([_currentData length] >= self.minimumDataSize)
{
[self szConnection:self didReceiveData:[[_currentData copy] autorelease]];
[_currentData setLength:0];
}
}
}
break;
}
}
}
+(NSOperationQueue*)urlQueue
{
static NSOperationQueue* _queue = nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
_queue = [[NSOperationQueue alloc] init];
});
return _queue;
}
@end