forked from this-sam/myFlock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathASIHTTPRequest.m
3251 lines (2667 loc) · 117 KB
/
ASIHTTPRequest.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
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ASIHTTPRequest.m
//
// Created by Ben Copsey on 04/10/2007.
// Copyright 2007-2009 All-Seeing Interactive. All rights reserved.
//
// A guide to the main features is available at:
// http://allseeing-i.com/ASIHTTPRequest
//
// Portions are based on the ImageClient example from Apple:
// See: http://developer.apple.com/samplecode/ImageClient/listing37.html
#import "ASIHTTPRequest.h"
#import <zlib.h>
#if TARGET_OS_IPHONE
#import "Reachability.h"
#import "ASIAuthenticationDialog.h"
#else
#import <SystemConfiguration/SystemConfiguration.h>
#endif
#import "ASIInputStream.h"
// Automatically set on build
NSString *ASIHTTPRequestVersion = @"v1.2-24 2009-12-18";
// We use our own custom run loop mode as CoreAnimation seems to want to hijack our threads otherwise
static CFStringRef ASIHTTPRequestRunMode = CFSTR("ASIHTTPRequest");
NSString* const NetworkRequestErrorDomain = @"ASIHTTPRequestErrorDomain";
static const CFOptionFlags kNetworkEvents = kCFStreamEventOpenCompleted | kCFStreamEventHasBytesAvailable | kCFStreamEventEndEncountered | kCFStreamEventErrorOccurred;
// In memory caches of credentials, used on when useSessionPersistance is YES
static NSMutableArray *sessionCredentialsStore = nil;
static NSMutableArray *sessionProxyCredentialsStore = nil;
// This lock mediates access to session credentials
static NSRecursiveLock *sessionCredentialsLock = nil;
// We keep track of cookies we have received here so we can remove them from the sharedHTTPCookieStorage later
static NSMutableArray *sessionCookies = nil;
// The number of times we will allow requests to redirect before we fail with a redirection error
const int RedirectionLimit = 5;
static void ReadStreamClientCallBack(CFReadStreamRef readStream, CFStreamEventType type, void *clientCallBackInfo) {
[((ASIHTTPRequest*)clientCallBackInfo) handleNetworkEvent: type];
}
// This lock prevents the operation from being cancelled while it is trying to update the progress, and vice versa
static NSRecursiveLock *progressLock;
static NSError *ASIRequestCancelledError;
static NSError *ASIRequestTimedOutError;
static NSError *ASIAuthenticationError;
static NSError *ASIUnableToCreateRequestError;
static NSError *ASITooMuchRedirectionError;
static NSMutableArray *bandwidthUsageTracker = nil;
static unsigned long averageBandwidthUsedPerSecond = 0;
// Records how much bandwidth all requests combined have used in the last second
static unsigned long bandwidthUsedInLastSecond = 0;
// A date one second in the future from the time it was created
static NSDate *bandwidthMeasurementDate = nil;
// Since throttling variables are shared among all requests, we'll use a lock to mediate access
static NSLock *bandwidthThrottlingLock = nil;
// the maximum number of bytes that can be transmitted in one second
static unsigned long maxBandwidthPerSecond = 0;
// A default figure for throttling bandwidth on mobile devices
unsigned long const ASIWWANBandwidthThrottleAmount = 14800;
#if TARGET_OS_IPHONE
// YES when bandwidth throttling is active
// This flag does not denote whether throttling is turned on - rather whether it is currently in use
// It will be set to NO when throttling was turned on with setShouldThrottleBandwidthForWWAN, but a WI-FI connection is active
static BOOL isBandwidthThrottled = NO;
// When YES, bandwidth will be automatically throttled when using WWAN (3G/Edge/GPRS)
// Wifi will not be throttled
static BOOL shouldThrottleBandwithForWWANOnly = NO;
#endif
// Mediates access to the session cookies so requests
static NSRecursiveLock *sessionCookiesLock = nil;
// This lock ensures delegates only receive one notification that authentication is required at once
// When using ASIAuthenticationDialogs, it also ensures only one dialog is shown at once
// If a request can't aquire the lock immediately, it means a dialog is being shown or a delegate is handling the authentication challenge
// Once it gets the lock, it will try to look for existing credentials again rather than showing the dialog / notifying the delegate
// This is so it can make use of any credentials supplied for the other request, if they are appropriate
static NSRecursiveLock *delegateAuthenticationLock = nil;
static NSOperationQueue *sharedRequestQueue = nil;
static BOOL isiPhoneOS2;
// Private stuff
@interface ASIHTTPRequest ()
- (void)cancelLoad;
- (BOOL)askDelegateForCredentials;
- (BOOL)askDelegateForProxyCredentials;
+ (void)measureBandwidthUsage;
+ (void)recordBandwidthUsage;
#if TARGET_OS_IPHONE
+ (void)registerForNetworkReachabilityNotifications;
+ (void)unsubscribeFromNetworkReachabilityNotifications;
// Called when the status of the network changes
+ (void)reachabilityChanged:(NSNotification *)note;
#endif
@property (assign) BOOL complete;
@property (retain) NSDictionary *responseHeaders;
@property (retain) NSArray *responseCookies;
@property (assign) int responseStatusCode;
@property (retain) NSMutableData *rawResponseData;
@property (retain, nonatomic) NSDate *lastActivityTime;
@property (assign) unsigned long long contentLength;
@property (assign) unsigned long long partialDownloadSize;
@property (assign, nonatomic) unsigned long long uploadBufferSize;
@property (assign) NSStringEncoding responseEncoding;
@property (retain, nonatomic) NSOutputStream *postBodyWriteStream;
@property (retain, nonatomic) NSInputStream *postBodyReadStream;
@property (assign) unsigned long long totalBytesRead;
@property (assign) unsigned long long totalBytesSent;
@property (assign, nonatomic) unsigned long long lastBytesRead;
@property (assign, nonatomic) unsigned long long lastBytesSent;
@property (retain) NSRecursiveLock *cancelledLock;
@property (retain, nonatomic) NSOutputStream *fileDownloadOutputStream;
@property (assign) int authenticationRetryCount;
@property (assign) int proxyAuthenticationRetryCount;
@property (assign, nonatomic) BOOL updatedProgress;
@property (assign, nonatomic) BOOL needsRedirect;
@property (assign, nonatomic) int redirectCount;
@property (retain, nonatomic) NSData *compressedPostBody;
@property (retain, nonatomic) NSString *compressedPostBodyFilePath;
@property (retain) NSConditionLock *authenticationLock;
@property (retain) NSString *authenticationRealm;
@property (retain) NSString *proxyAuthenticationRealm;
@property (retain) NSString *responseStatusMessage;
@end
@implementation ASIHTTPRequest
#pragma mark init / dealloc
+ (void)initialize
{
if (self == [ASIHTTPRequest class]) {
progressLock = [[NSRecursiveLock alloc] init];
bandwidthThrottlingLock = [[NSLock alloc] init];
sessionCookiesLock = [[NSRecursiveLock alloc] init];
sessionCredentialsLock = [[NSRecursiveLock alloc] init];
delegateAuthenticationLock = [[NSRecursiveLock alloc] init];
bandwidthUsageTracker = [[NSMutableArray alloc] initWithCapacity:5];
ASIRequestTimedOutError = [[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIRequestTimedOutErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"The request timed out",NSLocalizedDescriptionKey,nil]] retain];
ASIAuthenticationError = [[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIAuthenticationErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Authentication needed",NSLocalizedDescriptionKey,nil]] retain];
ASIRequestCancelledError = [[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIRequestCancelledErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"The request was cancelled",NSLocalizedDescriptionKey,nil]] retain];
ASIUnableToCreateRequestError = [[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIUnableToCreateRequestErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to create request (bad url?)",NSLocalizedDescriptionKey,nil]] retain];
ASITooMuchRedirectionError = [[NSError errorWithDomain:NetworkRequestErrorDomain code:ASITooMuchRedirectionErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"The request failed because it redirected too many times",NSLocalizedDescriptionKey,nil]] retain];
#if TARGET_OS_IPHONE
isiPhoneOS2 = ((floorf([[[UIDevice currentDevice] systemVersion] floatValue]) == 2.0) ? YES : NO);
#else
isiPhoneOS2 = NO;
#endif
}
[super initialize];
}
- (id)initWithURL:(NSURL *)newURL
{
self = [super init];
[self setRequestMethod:@"GET"];
[self setShouldPresentCredentialsBeforeChallenge:YES];
[self setShouldRedirect:YES];
[self setShowAccurateProgress:YES];
[self setShouldResetProgressIndicators:YES];
[self setAllowCompressedResponse:YES];
[self setDefaultResponseEncoding:NSISOLatin1StringEncoding];
[self setShouldPresentProxyAuthenticationDialog:YES];
[self setTimeOutSeconds:10];
[self setUseSessionPersistance:YES];
[self setUseCookiePersistance:YES];
[self setValidatesSecureCertificate:YES];
[self setRequestCookies:[[[NSMutableArray alloc] init] autorelease]];
[self setDidStartSelector:@selector(requestStarted:)];
[self setDidFinishSelector:@selector(requestFinished:)];
[self setDidFailSelector:@selector(requestFailed:)];
[self setURL:newURL];
[self setCancelledLock:[[[NSRecursiveLock alloc] init] autorelease]];
return self;
}
+ (id)requestWithURL:(NSURL *)newURL
{
return [[[self alloc] initWithURL:newURL] autorelease];
}
- (void)dealloc
{
[self setAuthenticationChallengeInProgress:NO];
if (requestAuthentication) {
CFRelease(requestAuthentication);
}
if (proxyAuthentication) {
CFRelease(proxyAuthentication);
}
if (request) {
CFRelease(request);
}
[self cancelLoad];
[userInfo release];
[mainRequest release];
[postBody release];
[compressedPostBody release];
[error release];
[requestHeaders release];
[requestCookies release];
[downloadDestinationPath release];
[temporaryFileDownloadPath release];
[fileDownloadOutputStream release];
[username release];
[password release];
[domain release];
[authenticationRealm release];
[authenticationScheme release];
[requestCredentials release];
[proxyHost release];
[proxyUsername release];
[proxyPassword release];
[proxyDomain release];
[proxyAuthenticationRealm release];
[proxyAuthenticationScheme release];
[proxyCredentials release];
[url release];
[authenticationLock release];
[lastActivityTime release];
[responseCookies release];
[rawResponseData release];
[responseHeaders release];
[requestMethod release];
[cancelledLock release];
[postBodyFilePath release];
[compressedPostBodyFilePath release];
[postBodyWriteStream release];
[postBodyReadStream release];
[PACurl release];
[responseStatusMessage release];
[super dealloc];
}
#pragma mark setup request
- (void)addRequestHeader:(NSString *)header value:(NSString *)value
{
if (!requestHeaders) {
[self setRequestHeaders:[NSMutableDictionary dictionaryWithCapacity:1]];
}
[requestHeaders setObject:value forKey:header];
}
// This function will be called either just before a request starts, or when postLength is needed, whichever comes first
// postLength must be set by the time this function is complete
- (void)buildPostBody
{
if ([self haveBuiltPostBody]) {
return;
}
// Are we submitting the request body from a file on disk
if ([self postBodyFilePath]) {
// If we were writing to the post body via appendPostData or appendPostDataFromFile, close the write stream
if ([self postBodyWriteStream]) {
[[self postBodyWriteStream] close];
[self setPostBodyWriteStream:nil];
}
NSError *err = nil;
NSString *path;
if ([self shouldCompressRequestBody]) {
[self setCompressedPostBodyFilePath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]];
[ASIHTTPRequest compressDataFromFile:[self postBodyFilePath] toFile:[self compressedPostBodyFilePath]];
path = [self compressedPostBodyFilePath];
} else {
path = [self postBodyFilePath];
}
[self setPostLength:[[[NSFileManager defaultManager] attributesOfItemAtPath:path error:&err] fileSize]];
if (err) {
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to get attributes for file at path '@%'",path],NSLocalizedDescriptionKey,error,NSUnderlyingErrorKey,nil]]];
return;
}
// Otherwise, we have an in-memory request body
} else {
if ([self shouldCompressRequestBody]) {
[self setCompressedPostBody:[ASIHTTPRequest compressData:[self postBody]]];
[self setPostLength:[[self compressedPostBody] length]];
} else {
[self setPostLength:[[self postBody] length]];
}
}
if ([self postLength] > 0) {
if ([requestMethod isEqualToString:@"GET"] || [requestMethod isEqualToString:@"DELETE"] || [requestMethod isEqualToString:@"HEAD"]) {
[self setRequestMethod:@"POST"];
}
[self addRequestHeader:@"Content-Length" value:[NSString stringWithFormat:@"%llu",[self postLength]]];
}
[self setHaveBuiltPostBody:YES];
}
// Sets up storage for the post body
- (void)setupPostBody
{
if ([self shouldStreamPostDataFromDisk]) {
if (![self postBodyFilePath]) {
[self setPostBodyFilePath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]];
[self setDidCreateTemporaryPostDataFile:YES];
}
if (![self postBodyWriteStream]) {
[self setPostBodyWriteStream:[[[NSOutputStream alloc] initToFileAtPath:[self postBodyFilePath] append:NO] autorelease]];
[[self postBodyWriteStream] open];
}
} else {
if (![self postBody]) {
[self setPostBody:[[[NSMutableData alloc] init] autorelease]];
}
}
}
- (void)appendPostData:(NSData *)data
{
[self setupPostBody];
if ([data length] == 0) {
return;
}
if ([self shouldStreamPostDataFromDisk]) {
[[self postBodyWriteStream] write:[data bytes] maxLength:[data length]];
} else {
[[self postBody] appendData:data];
}
}
- (void)appendPostDataFromFile:(NSString *)file
{
[self setupPostBody];
NSInputStream *stream = [[[NSInputStream alloc] initWithFileAtPath:file] autorelease];
[stream open];
int bytesRead;
while ([stream hasBytesAvailable]) {
unsigned char buffer[1024*256];
bytesRead = [stream read:buffer maxLength:sizeof(buffer)];
if (bytesRead == 0) {
break;
}
if ([self shouldStreamPostDataFromDisk]) {
[[self postBodyWriteStream] write:buffer maxLength:bytesRead];
} else {
[[self postBody] appendData:[NSData dataWithBytes:buffer length:bytesRead]];
}
}
[stream close];
}
- (void)setDelegate:(id)newDelegate
{
[[self cancelledLock] lock];
delegate = newDelegate;
[[self cancelledLock] unlock];
}
- (void)setQueue:(id)newQueue
{
[[self cancelledLock] lock];
queue = newQueue;
[[self cancelledLock] unlock];
}
#pragma mark get information about this request
- (BOOL)isFinished
{
return [self complete];
}
- (void)cancel
{
[[self cancelledLock] lock];
if ([self isCancelled] || [self complete]) {
[[self cancelledLock] unlock];
return;
}
[self failWithError:ASIRequestCancelledError];
[self setComplete:YES];
[self cancelLoad];
[[self cancelledLock] unlock];
// Must tell the operation to cancel after we unlock, as this request might be dealloced and then NSLock will log an error
[super cancel];
}
// Call this method to get the received data as an NSString. Don't use for binary data!
- (NSString *)responseString
{
NSData *data = [self responseData];
if (!data) {
return nil;
}
return [[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:[self responseEncoding]] autorelease];
}
- (BOOL)isResponseCompressed
{
NSString *encoding = [[self responseHeaders] objectForKey:@"Content-Encoding"];
return encoding && [encoding rangeOfString:@"gzip"].location != NSNotFound;
}
- (NSData *)responseData
{
if ([self isResponseCompressed]) {
return [ASIHTTPRequest uncompressZippedData:[self rawResponseData]];
} else {
return [self rawResponseData];
}
}
#pragma mark running a request
// Run a request asynchronously by adding it to the global queue
// (Use [request start] for a synchronous request)
- (void)startAsynchronous
{
[[ASIHTTPRequest sharedRequestQueue] addOperation:self];
}
#pragma mark request logic
// Create the request
- (void)main
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
@try {
// A HEAD request generated by an ASINetworkQueue may have set the error already. If so, we should not proceed.
if ([self error]) {
[self failWithError:nil];
[pool release];
return;
}
[self setComplete:NO];
if (![self url]) {
[self failWithError:ASIUnableToCreateRequestError];
[pool release];
return;
}
// Must call before we create the request so that the request method can be set if needs be
if (![self mainRequest]) {
[self buildPostBody];
}
// If we're redirecting, we'll already have a CFHTTPMessageRef
if (request) {
CFRelease(request);
}
// Create a new HTTP request.
request = CFHTTPMessageCreateRequest(kCFAllocatorDefault, (CFStringRef)[self requestMethod], (CFURLRef)[self url], [self useHTTPVersionOne] ? kCFHTTPVersion1_0 : kCFHTTPVersion1_1);
if (!request) {
[self failWithError:ASIUnableToCreateRequestError];
[pool release];
return;
}
//If this is a HEAD request generated by an ASINetworkQueue, we need to let the main request generate its headers first so we can use them
if ([self mainRequest]) {
[[self mainRequest] buildRequestHeaders];
}
// Even if this is a HEAD request with a mainRequest, we still need to call to give subclasses a chance to add their own to HEAD requests (ASIS3Request does this)
[self buildRequestHeaders];
[self applyAuthorizationHeader];
NSString *header;
for (header in [self requestHeaders]) {
CFHTTPMessageSetHeaderFieldValue(request, (CFStringRef)header, (CFStringRef)[[self requestHeaders] objectForKey:header]);
}
[self loadRequest];
} @catch (NSException *exception) {
NSError *underlyingError = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASIUnhandledExceptionError userInfo:[exception userInfo]];
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIUnhandledExceptionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[exception name],NSLocalizedDescriptionKey,[exception reason],NSLocalizedFailureReasonErrorKey,underlyingError,NSUnderlyingErrorKey,nil]]];
}
[pool release];
}
- (void)applyAuthorizationHeader
{
// Do we want to send credentials before we are asked for them?
if ([self shouldPresentCredentialsBeforeChallenge]) {
// First, see if we have any credentials we can use in the session store
NSDictionary *credentials = nil;
if ([self useSessionPersistance]) {
credentials = [self findSessionAuthenticationCredentials];
}
// Are any credentials set on this request that might be used for basic authentication?
if ([self username] && [self password] && ![self domain]) {
// If we have stored credentials, is this server asking for basic authentication? If we don't have credentials, we'll assume basic
if (!credentials || (CFStringRef)[credentials objectForKey:@"AuthenticationScheme"] == kCFHTTPAuthenticationSchemeBasic) {
[self addBasicAuthenticationHeaderWithUsername:[self username] andPassword:[self password]];
}
}
if (credentials && ![[self requestHeaders] objectForKey:@"Authorization"]) {
// When the Authentication key is set, the credentials were stored after an authentication challenge, so we can let CFNetwork apply them
// (credentials for Digest and NTLM will always be stored like this)
if ([credentials objectForKey:@"Authentication"]) {
// If we've already talked to this server and have valid credentials, let's apply them to the request
if (!CFHTTPMessageApplyCredentialDictionary(request, (CFHTTPAuthenticationRef)[credentials objectForKey:@"Authentication"], (CFDictionaryRef)[credentials objectForKey:@"Credentials"], NULL)) {
[[self class] removeAuthenticationCredentialsFromSessionStore:[credentials objectForKey:@"Credentials"]];
}
// If the Authentication key is not set, these credentials were stored after a username and password set on a previous request passed basic authentication
// When this happens, we'll need to create the Authorization header ourselves
} else {
NSDictionary *usernameAndPassword = [credentials objectForKey:@"Credentials"];
[self addBasicAuthenticationHeaderWithUsername:[usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationUsername] andPassword:[usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationPassword]];
}
}
if ([self useSessionPersistance]) {
credentials = [self findSessionProxyAuthenticationCredentials];
if (credentials) {
if (!CFHTTPMessageApplyCredentialDictionary(request, (CFHTTPAuthenticationRef)[credentials objectForKey:@"Authentication"], (CFDictionaryRef)[credentials objectForKey:@"Credentials"], NULL)) {
[[self class] removeProxyAuthenticationCredentialsFromSessionStore:[credentials objectForKey:@"Credentials"]];
}
}
}
}
}
- (void)buildRequestHeaders
{
if ([self haveBuiltRequestHeaders]) {
return;
}
[self setHaveBuiltRequestHeaders:YES];
if ([self mainRequest]) {
for (NSString *header in [[self mainRequest] requestHeaders]) {
[self addRequestHeader:header value:[[[self mainRequest] requestHeaders] valueForKey:header]];
}
return;
}
// Add cookies from the persistant (mac os global) store
if ([self useCookiePersistance] ) {
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[self url]];
if (cookies) {
[[self requestCookies] addObjectsFromArray:cookies];
}
}
// Apply request cookies
NSArray *cookies;
if ([self mainRequest]) {
cookies = [[self mainRequest] requestCookies];
} else {
cookies = [self requestCookies];
}
if ([cookies count] > 0) {
NSHTTPCookie *cookie;
NSString *cookieHeader = nil;
for (cookie in cookies) {
if (!cookieHeader) {
cookieHeader = [NSString stringWithFormat: @"%@=%@",[cookie name],[cookie value]];
} else {
cookieHeader = [NSString stringWithFormat: @"%@; %@=%@",cookieHeader,[cookie name],[cookie value]];
}
}
if (cookieHeader) {
[self addRequestHeader:@"Cookie" value:cookieHeader];
}
}
// Build and set the user agent string if the request does not already have a custom user agent specified
if (![[self requestHeaders] objectForKey:@"User-Agent"]) {
NSString *userAgentString = [ASIHTTPRequest defaultUserAgentString];
if (userAgentString) {
[self addRequestHeader:@"User-Agent" value:userAgentString];
}
}
// Accept a compressed response
if ([self allowCompressedResponse]) {
[self addRequestHeader:@"Accept-Encoding" value:@"gzip"];
}
// Configure a compressed request body
if ([self shouldCompressRequestBody]) {
[self addRequestHeader:@"Content-Encoding" value:@"gzip"];
}
// Should this request resume an existing download?
if ([self allowResumeForFileDownloads] && [self downloadDestinationPath] && [self temporaryFileDownloadPath] && [[NSFileManager defaultManager] fileExistsAtPath:[self temporaryFileDownloadPath]]) {
NSError *err = nil;
[self setPartialDownloadSize:[[[NSFileManager defaultManager] attributesOfItemAtPath:[self temporaryFileDownloadPath] error:&err] fileSize]];
if (err) {
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to get attributes for file at path '@%'",[self temporaryFileDownloadPath]],NSLocalizedDescriptionKey,error,NSUnderlyingErrorKey,nil]]];
return;
}
[self addRequestHeader:@"Range" value:[NSString stringWithFormat:@"bytes=%llu-",[self partialDownloadSize]]];
}
}
- (void)startRequest
{
[[self cancelledLock] lock];
if ([self isCancelled]) {
[[self cancelledLock] unlock];
return;
}
[self requestStarted];
[self setAuthenticationLock:[[[NSConditionLock alloc] initWithCondition:1] autorelease]];
[self setComplete:NO];
[self setTotalBytesRead:0];
[self setLastBytesRead:0];
// If we're retrying a request after an authentication failure, let's remove any progress we made
if ([self lastBytesSent] > 0) {
[self removeUploadProgressSoFar];
}
[self setLastBytesSent:0];
if ([self shouldResetProgressIndicators]) {
[self setContentLength:0];
[self resetDownloadProgress:0];
}
[self setResponseHeaders:nil];
if (![self downloadDestinationPath]) {
[self setRawResponseData:[[[NSMutableData alloc] init] autorelease]];
}
// Create the stream for the request
// Do we need to stream the request body from disk
if ([self shouldStreamPostDataFromDisk] && [self postBodyFilePath] && [[NSFileManager defaultManager] fileExistsAtPath:[self postBodyFilePath]]) {
// Are we gzipping the request body?
if ([self compressedPostBodyFilePath] && [[NSFileManager defaultManager] fileExistsAtPath:[self compressedPostBodyFilePath]]) {
[self setPostBodyReadStream:[ASIInputStream inputStreamWithFileAtPath:[self compressedPostBodyFilePath]]];
} else {
[self setPostBodyReadStream:[ASIInputStream inputStreamWithFileAtPath:[self postBodyFilePath]]];
}
readStream = CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request,(CFReadStreamRef)[self postBodyReadStream]);
} else {
// If we have a request body, we'll stream it from memory using our custom stream, so that we can measure bandwidth use and it can be bandwidth-throttled if nescessary
if ([self postBody] && [[self postBody] length] > 0) {
if ([self shouldCompressRequestBody] && [self compressedPostBody]) {
[self setPostBodyReadStream:[ASIInputStream inputStreamWithData:[self compressedPostBody]]];
} else if ([self postBody]) {
[self setPostBodyReadStream:[ASIInputStream inputStreamWithData:[self postBody]]];
}
readStream = CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request,(CFReadStreamRef)[self postBodyReadStream]);
} else {
readStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request);
}
}
if (!readStream) {
[[self cancelledLock] unlock];
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileBuildingRequestType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to create read stream",NSLocalizedDescriptionKey,nil]]];
return;
}
// Tell CFNetwork not to validate SSL certificates
if (!validatesSecureCertificate) {
CFReadStreamSetProperty(readStream, kCFStreamPropertySSLSettings, [NSMutableDictionary dictionaryWithObject:(NSString *)kCFBooleanFalse forKey:(NSString *)kCFStreamSSLValidatesCertificateChain]);
}
// Handle proxy settings
// Have details of the proxy been set on this request
if (![self proxyHost] && ![self proxyPort]) {
// If not, we need to figure out what they'll be
NSArray *proxies = nil;
// Have we been given a proxy auto config file?
if ([self PACurl]) {
proxies = [ASIHTTPRequest proxiesForURL:[self url] fromPAC:[self PACurl]];
// Detect proxy settings and apply them
} else {
#if TARGET_OS_IPHONE
#if TARGET_IPHONE_SIMULATOR && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_0
// Can't detect proxies in 2.2.1 Simulator
NSDictionary *proxySettings = [NSMutableDictionary dictionary];
#else
NSDictionary *proxySettings = [(NSDictionary *)CFNetworkCopySystemProxySettings() autorelease];
#endif
#else
NSDictionary *proxySettings = [(NSDictionary *)SCDynamicStoreCopyProxies(NULL) autorelease];
#endif
proxies = [(NSArray *)CFNetworkCopyProxiesForURL((CFURLRef)[self url], (CFDictionaryRef)proxySettings) autorelease];
// Now check to see if the proxy settings contained a PAC url, we need to run the script to get the real list of proxies if so
NSDictionary *settings = [proxies objectAtIndex:0];
if ([settings objectForKey:(NSString *)kCFProxyAutoConfigurationURLKey]) {
proxies = [ASIHTTPRequest proxiesForURL:[self url] fromPAC:[settings objectForKey:(NSString *)kCFProxyAutoConfigurationURLKey]];
}
}
if (!proxies) {
CFRelease(readStream);
readStream = NULL;
[[self cancelledLock] unlock];
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileBuildingRequestType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to obtain information on proxy servers needed for request",NSLocalizedDescriptionKey,nil]]];
return;
}
// I don't really understand why the dictionary returned by CFNetworkCopyProxiesForURL uses different key names from CFNetworkCopySystemProxySettings/SCDynamicStoreCopyProxies
// and why its key names are documented while those we actually need to use don't seem to be (passing the kCF* keys doesn't seem to work)
if ([proxies count] > 0) {
NSDictionary *settings = [proxies objectAtIndex:0];
[self setProxyHost:[settings objectForKey:(NSString *)kCFProxyHostNameKey]];
[self setProxyPort:[[settings objectForKey:(NSString *)kCFProxyPortNumberKey] intValue]];
}
}
if ([self proxyHost] && [self proxyPort]) {
NSMutableDictionary *proxyToUse = [NSMutableDictionary dictionaryWithObjectsAndKeys:[self proxyHost],kCFStreamPropertyHTTPProxyHost,[NSNumber numberWithInt:[self proxyPort]],kCFStreamPropertyHTTPProxyPort,nil];
CFReadStreamSetProperty(readStream, kCFStreamPropertyHTTPProxy, proxyToUse);
}
// Set the client
CFStreamClientContext ctxt = {0, self, NULL, NULL, NULL};
if (!CFReadStreamSetClient(readStream, kNetworkEvents, ReadStreamClientCallBack, &ctxt)) {
CFRelease(readStream);
readStream = NULL;
[[self cancelledLock] unlock];
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileBuildingRequestType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to setup read stream",NSLocalizedDescriptionKey,nil]]];
return;
}
// Schedule the stream
CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), ASIHTTPRequestRunMode);
// Start the HTTP connection
if (!CFReadStreamOpen(readStream)) {
CFReadStreamSetClient(readStream, 0, NULL, NULL);
CFReadStreamUnscheduleFromRunLoop(readStream, CFRunLoopGetCurrent(), ASIHTTPRequestRunMode);
CFRelease(readStream);
readStream = NULL;
[[self cancelledLock] unlock];
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileBuildingRequestType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to start HTTP connection",NSLocalizedDescriptionKey,nil]]];
return;
}
[[self cancelledLock] unlock];
if (shouldResetProgressIndicators) {
double amount = 1;
if (showAccurateProgress) {
//Workaround for an issue with converting a long to a double on iPhone OS 2.2.1 with a base SDK >= 3.0
if ([ASIHTTPRequest isiPhoneOS2]) {
amount = [[NSNumber numberWithUnsignedLongLong:postLength] doubleValue];
} else {
amount = (double)postLength;
}
}
[self resetUploadProgress:amount];
}
// Record when the request started, so we can timeout if nothing happens
[self setLastActivityTime:[NSDate date]];
}
// This is the 'main loop' for the request. Basically, it runs the runloop that our network stuff is attached to, and checks to see if we should cancel or timeout
- (void)loadRequest
{
[self startRequest];
// Wait for the request to finish
while (!complete) {
// We won't let the request cancel until we're done with this cycle of the loop
[[self cancelledLock] lock];
// See if our NSOperationQueue told us to cancel
if ([self isCancelled] || [self complete]) {
[[self cancelledLock] unlock];
break;
}
// This may take a while, so we'll create a new pool each cycle to stop a giant backlog of autoreleased objects building up
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDate *now = [NSDate date];
// See if we need to timeout
if (lastActivityTime && timeOutSeconds > 0 && [now timeIntervalSinceDate:lastActivityTime] > timeOutSeconds) {
// Prevent timeouts before 128KB* has been sent when the size of data to upload is greater than 128KB* (*32KB on iPhone 3.0 SDK)
// This is to workaround the fact that kCFStreamPropertyHTTPRequestBytesWrittenCount is the amount written to the buffer, not the amount actually sent
// This workaround prevents erroneous timeouts in low bandwidth situations (eg iPhone)
if (totalBytesSent || postLength <= uploadBufferSize || (uploadBufferSize > 0 && totalBytesSent > uploadBufferSize)) {
[self failWithError:ASIRequestTimedOutError];
[self cancelLoad];
[self setComplete:YES];
[[self cancelledLock] unlock];
[pool release];
break;
}
}
// Do we need to redirect?
if ([self needsRedirect]) {
[self cancelLoad];
[self setNeedsRedirect:NO];
[self setRedirectCount:[self redirectCount]+1];
if ([self redirectCount] > RedirectionLimit) {
// Some naughty / badly coded website is trying to force us into a redirection loop. This is not cool.
[self failWithError:ASITooMuchRedirectionError];
[self setComplete:YES];
[[self cancelledLock] unlock];
} else {
[[self cancelledLock] unlock];
// Go all the way back to the beginning and build the request again, so that we can apply any new cookies
[self main];
}
[pool release];
break;
}
// Find out if we've sent any more data than last time, and reset the timeout if so
if (totalBytesSent > lastBytesSent) {
[self setLastActivityTime:[NSDate date]];
[self setLastBytesSent:totalBytesSent];
}
// Find out how much data we've uploaded so far
[self setTotalBytesSent:[[(NSNumber *)CFReadStreamCopyProperty(readStream, kCFStreamPropertyHTTPRequestBytesWrittenCount) autorelease] unsignedLongLongValue]];
[self updateProgressIndicators];
// Measure bandwidth used, and throttle if nescessary
[ASIHTTPRequest measureBandwidthUsage];
// This thread should wait for 1/4 second for the stream to do something. We'll stop early if it does.
CFRunLoopRunInMode(ASIHTTPRequestRunMode,0.25,YES);
[[self cancelledLock] unlock];
[pool release];
}
}
// Cancel loading and clean up. DO NOT USE THIS TO CANCEL REQUESTS - use [request cancel] instead
- (void)cancelLoad
{
if (readStream) {
CFReadStreamSetClient(readStream, kCFStreamEventNone, NULL, NULL);
CFReadStreamUnscheduleFromRunLoop(readStream, CFRunLoopGetCurrent(), ASIHTTPRequestRunMode);
CFReadStreamClose(readStream);
CFRelease(readStream);
readStream = NULL;
}
[[self postBodyReadStream] close];
if ([self rawResponseData]) {
[self setRawResponseData:nil];
// If we were downloading to a file
} else if ([self temporaryFileDownloadPath]) {
[[self fileDownloadOutputStream] close];
// If we haven't said we might want to resume, let's remove the temporary file too
if (![self allowResumeForFileDownloads]) {
[self removeTemporaryDownloadFile];
}
}
// Clean up any temporary file used to store request body for streaming
if (![self authenticationChallengeInProgress] && [self didCreateTemporaryPostDataFile]) {
[self removePostDataFile];
[self setDidCreateTemporaryPostDataFile:NO];
}
[self setResponseHeaders:nil];
}
- (void)removeTemporaryDownloadFile
{
if ([self temporaryFileDownloadPath]) {
if ([[NSFileManager defaultManager] fileExistsAtPath:[self temporaryFileDownloadPath]]) {
NSError *removeError = nil;
[[NSFileManager defaultManager] removeItemAtPath:[self temporaryFileDownloadPath] error:&removeError];
if (removeError) {
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to delete file at path '%@'",[self temporaryFileDownloadPath]],NSLocalizedDescriptionKey,removeError,NSUnderlyingErrorKey,nil]]];
}
}
[self setTemporaryFileDownloadPath:nil];
}
}
- (void)removePostDataFile
{
if ([self postBodyFilePath]) {
NSError *removeError = nil;
[[NSFileManager defaultManager] removeItemAtPath:[self postBodyFilePath] error:&removeError];
if (removeError) {
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to delete file at path '%@'",[self postBodyFilePath]],NSLocalizedDescriptionKey,removeError,NSUnderlyingErrorKey,nil]]];
}
[self setPostBodyFilePath:nil];
}
if ([self compressedPostBodyFilePath]) {
NSError *removeError = nil;
[[NSFileManager defaultManager] removeItemAtPath:[self compressedPostBodyFilePath] error:&removeError];
if (removeError) {
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to delete file at path '%@'",[self compressedPostBodyFilePath]],NSLocalizedDescriptionKey,removeError,NSUnderlyingErrorKey,nil]]];
}
[self setCompressedPostBodyFilePath:nil];
}
}
#pragma mark HEAD request
// Used by ASINetworkQueue to create a HEAD request appropriate for this request with the same headers (though you can use it yourself)
- (ASIHTTPRequest *)HEADRequest
{
ASIHTTPRequest *headRequest = [[self class] requestWithURL:[self url]];
[headRequest setMainRequest:self];
[headRequest setRequestMethod:@"HEAD"];
return headRequest;
}
#pragma mark upload/download progress
- (void)updateProgressIndicators