This repository has been archived by the owner on Jun 17, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ASIHTTPRequest.m
4779 lines (3970 loc) · 168 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-2010 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"
#if TARGET_OS_IPHONE
#import "Reachability.h"
#import "ASIAuthenticationDialog.h"
#import <MobileCoreServices/MobileCoreServices.h>
#else
#import <SystemConfiguration/SystemConfiguration.h>
#endif
#import "ASIInputStream.h"
#import "ASIDataDecompressor.h"
#import "ASIDataCompressor.h"
// Automatically set on build
NSString *ASIHTTPRequestVersion = @"v1.8-56 2011-02-06";
NSString* const NetworkRequestErrorDomain = @"ASIHTTPRequestErrorDomain";
static NSString *ASIHTTPRequestRunLoopMode = @"ASIHTTPRequestRunLoopMode";
static const CFOptionFlags kNetworkEvents = kCFStreamEventHasBytesAvailable | kCFStreamEventEndEncountered | kCFStreamEventErrorOccurred;
// In memory caches of credentials, used on when useSessionPersistence 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;
// The default number of seconds to use for a timeout
static NSTimeInterval defaultTimeOutSeconds = 10;
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;
// These are used for queuing persistent connections on the same connection
// Incremented every time we specify we want a new connection
static unsigned int nextConnectionNumberToCreate = 0;
// An array of connectionInfo dictionaries.
// When attempting a persistent connection, we look here to try to find an existing connection to the same server that is currently not in use
static NSMutableArray *persistentConnectionsPool = nil;
// Mediates access to the persistent connections pool
static NSRecursiveLock *connectionsLock = nil;
// Each request gets a new id, we store this rather than a ref to the request itself in the connectionInfo dictionary.
// We do this so we don't have to keep the request around while we wait for the connection to expire
static unsigned int nextRequestID = 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 acquire 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;
// When throttling bandwidth, Set to a date in future that we will allow all requests to wake up and reschedule their streams
static NSDate *throttleWakeUpTime = nil;
static id <ASICacheDelegate> defaultCache = nil;
// Used for tracking when requests are using the network
static unsigned int runningRequestCount = 0;
// You can use [ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:NO] if you want to manage it yourself
// Alternatively, override showNetworkActivityIndicator / hideNetworkActivityIndicator
// By default this does nothing on Mac OS X, but again override the above methods for a different behaviour
static BOOL shouldUpdateNetworkActivityIndicator = YES;
//**Queue stuff**/
// The thread all requests will run on
// Hangs around forever, but will be blocked unless there are requests underway
static NSThread *networkThread = nil;
static NSOperationQueue *sharedQueue = nil;
// Private stuff
@interface ASIHTTPRequest ()
- (void)cancelLoad;
- (void)destroyReadStream;
- (void)scheduleReadStream;
- (void)unscheduleReadStream;
- (BOOL)willAskDelegateForCredentials;
- (BOOL)willAskDelegateForProxyCredentials;
- (void)askDelegateForProxyCredentials;
- (void)askDelegateForCredentials;
- (void)failAuthentication;
+ (void)measureBandwidthUsage;
+ (void)recordBandwidthUsage;
- (void)startRequest;
- (void)updateStatus:(NSTimer *)timer;
- (void)checkRequestStatus;
- (void)reportFailure;
- (void)reportFinished;
- (void)markAsFinished;
- (void)performRedirect;
- (BOOL)shouldTimeOut;
+ (void)performInvocation:(NSInvocation *)invocation onTarget:(id *)target releasingObject:(id)objectToRelease;
+ (void)hideNetworkActivityIndicatorAfterDelay;
+ (void)hideNetworkActivityIndicatorIfNeeeded;
+ (void)runRequests;
// Handling Proxy autodetection and PAC file downloads
- (BOOL)configureProxies;
- (void)fetchPACFile;
- (void)finishedDownloadingPACFile:(ASIHTTPRequest *)theRequest;
- (void)runPACScript:(NSString *)script;
- (void)timeOutPACRead;
- (void)useDataFromCache;
// Called to update the size of a partial download when starting a request, or retrying after a timeout
- (void)updatePartialDownloadSize;
#if TARGET_OS_IPHONE
+ (void)registerForNetworkReachabilityNotifications;
+ (void)unsubscribeFromNetworkReachabilityNotifications;
// Called when the status of the network changes
+ (void)reachabilityChanged:(NSNotification *)note;
#endif
#if NS_BLOCKS_AVAILABLE
- (void)performBlockOnMainThread:(ASIBasicBlock)block;
- (void)releaseBlocksOnMainThread;
+ (void)releaseBlocks:(NSArray *)blocks;
- (void)callBlock:(ASIBasicBlock)block;
#endif
@property (assign) BOOL complete;
@property (retain) NSArray *responseCookies;
@property (assign) int responseStatusCode;
@property (retain, nonatomic) NSDate *lastActivityTime;
@property (assign) unsigned long long partialDownloadSize;
@property (assign, nonatomic) unsigned long long uploadBufferSize;
@property (retain, nonatomic) NSOutputStream *postBodyWriteStream;
@property (retain, nonatomic) NSInputStream *postBodyReadStream;
@property (assign, nonatomic) unsigned long long lastBytesRead;
@property (assign, nonatomic) unsigned long long lastBytesSent;
@property (retain) NSRecursiveLock *cancelledLock;
@property (retain, nonatomic) NSOutputStream *fileDownloadOutputStream;
@property (retain, nonatomic) NSOutputStream *inflatedFileDownloadOutputStream;
@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) NSString *authenticationRealm;
@property (retain) NSString *proxyAuthenticationRealm;
@property (retain) NSString *responseStatusMessage;
@property (assign) BOOL inProgress;
@property (assign) int retryCount;
@property (assign) BOOL connectionCanBeReused;
@property (retain, nonatomic) NSMutableDictionary *connectionInfo;
@property (retain, nonatomic) NSInputStream *readStream;
@property (assign) ASIAuthenticationState authenticationNeeded;
@property (assign, nonatomic) BOOL readStreamIsScheduled;
@property (assign, nonatomic) BOOL downloadComplete;
@property (retain) NSNumber *requestID;
@property (assign, nonatomic) NSString *runLoopMode;
@property (retain, nonatomic) NSTimer *statusTimer;
@property (assign) BOOL didUseCachedResponse;
@property (retain, nonatomic) NSURL *redirectURL;
@property (assign, nonatomic) BOOL isPACFileRequest;
@property (retain, nonatomic) ASIHTTPRequest *PACFileRequest;
@property (retain, nonatomic) NSInputStream *PACFileReadStream;
@property (retain, nonatomic) NSMutableData *PACFileData;
@property (assign, nonatomic, setter=setSynchronous:) BOOL isSynchronous;
@end
@implementation ASIHTTPRequest
#pragma mark init / dealloc
+ (void)initialize
{
if (self == [ASIHTTPRequest class]) {
persistentConnectionsPool = [[NSMutableArray alloc] init];
connectionsLock = [[NSRecursiveLock alloc] init];
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 alloc] initWithDomain:NetworkRequestErrorDomain code:ASIRequestTimedOutErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"The request timed out",NSLocalizedDescriptionKey,nil]];
ASIAuthenticationError = [[NSError alloc] initWithDomain:NetworkRequestErrorDomain code:ASIAuthenticationErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Authentication needed",NSLocalizedDescriptionKey,nil]];
ASIRequestCancelledError = [[NSError alloc] initWithDomain:NetworkRequestErrorDomain code:ASIRequestCancelledErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"The request was cancelled",NSLocalizedDescriptionKey,nil]];
ASIUnableToCreateRequestError = [[NSError alloc] initWithDomain:NetworkRequestErrorDomain code:ASIUnableToCreateRequestErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to create request (bad url?)",NSLocalizedDescriptionKey,nil]];
ASITooMuchRedirectionError = [[NSError alloc] initWithDomain:NetworkRequestErrorDomain code:ASITooMuchRedirectionErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"The request failed because it redirected too many times",NSLocalizedDescriptionKey,nil]];
sharedQueue = [[NSOperationQueue alloc] init];
[sharedQueue setMaxConcurrentOperationCount:4];
}
}
- (id)initWithURL:(NSURL *)newURL
{
self = [self init];
[self setRequestMethod:@"GET"];
[self setRunLoopMode:NSDefaultRunLoopMode];
[self setShouldAttemptPersistentConnection:YES];
[self setPersistentConnectionTimeoutSeconds:60.0];
[self setShouldPresentCredentialsBeforeChallenge:YES];
[self setShouldRedirect:YES];
[self setShowAccurateProgress:YES];
[self setShouldResetDownloadProgress:YES];
[self setShouldResetUploadProgress:YES];
[self setAllowCompressedResponse:YES];
[self setShouldWaitToInflateCompressedResponses:YES];
[self setDefaultResponseEncoding:NSISOLatin1StringEncoding];
[self setShouldPresentProxyAuthenticationDialog:YES];
[self setTimeOutSeconds:[ASIHTTPRequest defaultTimeOutSeconds]];
[self setUseSessionPersistence:YES];
[self setUseCookiePersistence:YES];
[self setValidatesSecureCertificate:YES];
[self setRequestCookies:[[[NSMutableArray alloc] init] autorelease]];
[self setDidStartSelector:@selector(requestStarted:)];
[self setDidReceiveResponseHeadersSelector:@selector(request:didReceiveResponseHeaders:)];
[self setWillRedirectSelector:@selector(request:willRedirectToURL:)];
[self setDidFinishSelector:@selector(requestFinished:)];
[self setDidFailSelector:@selector(requestFailed:)];
[self setDidReceiveDataSelector:@selector(request:didReceiveData:)];
[self setURL:newURL];
[self setCancelledLock:[[[NSRecursiveLock alloc] init] autorelease]];
[self setDownloadCache:[[self class] defaultCache]];
return self;
}
+ (id)requestWithURL:(NSURL *)newURL
{
return [[[self alloc] initWithURL:newURL] autorelease];
}
+ (id)requestWithURL:(NSURL *)newURL usingCache:(id <ASICacheDelegate>)cache
{
return [self requestWithURL:newURL usingCache:cache andCachePolicy:ASIUseDefaultCachePolicy];
}
+ (id)requestWithURL:(NSURL *)newURL usingCache:(id <ASICacheDelegate>)cache andCachePolicy:(ASICachePolicy)policy
{
ASIHTTPRequest *request = [[[self alloc] initWithURL:newURL] autorelease];
[request setDownloadCache:cache];
[request setCachePolicy:policy];
return request;
}
- (void)dealloc
{
[self setAuthenticationNeeded:ASINoAuthenticationNeededYet];
if (requestAuthentication) {
CFRelease(requestAuthentication);
}
if (proxyAuthentication) {
CFRelease(proxyAuthentication);
}
if (request) {
CFRelease(request);
}
if (clientCertificateIdentity) {
CFRelease(clientCertificateIdentity);
}
[self cancelLoad];
[redirectURL release];
[statusTimer invalidate];
[statusTimer release];
[queue release];
[userInfo release];
[postBody release];
[compressedPostBody release];
[error release];
[requestHeaders release];
[requestCookies release];
[downloadDestinationPath release];
[temporaryFileDownloadPath release];
[temporaryUncompressedDataDownloadPath release];
[fileDownloadOutputStream release];
[inflatedFileDownloadOutputStream release];
[username release];
[password release];
[domain release];
[authenticationRealm release];
[authenticationScheme release];
[requestCredentials release];
[proxyHost release];
[proxyType release];
[proxyUsername release];
[proxyPassword release];
[proxyDomain release];
[proxyAuthenticationRealm release];
[proxyAuthenticationScheme release];
[proxyCredentials release];
[url release];
[originalURL release];
[lastActivityTime release];
[responseCookies release];
[rawResponseData release];
[responseHeaders release];
[requestMethod release];
[cancelledLock release];
[postBodyFilePath release];
[compressedPostBodyFilePath release];
[postBodyWriteStream release];
[postBodyReadStream release];
[PACurl release];
[clientCertificates release];
[responseStatusMessage release];
[connectionInfo release];
[requestID release];
[dataDecompressor release];
#if NS_BLOCKS_AVAILABLE
[self releaseBlocksOnMainThread];
#endif
[super dealloc];
}
#if NS_BLOCKS_AVAILABLE
- (void)releaseBlocksOnMainThread
{
NSMutableArray *blocks = [NSMutableArray array];
if (completionBlock) {
[blocks addObject:completionBlock];
[completionBlock release];
completionBlock = nil;
}
if (failureBlock) {
[blocks addObject:failureBlock];
[failureBlock release];
failureBlock = nil;
}
if (startedBlock) {
[blocks addObject:startedBlock];
[startedBlock release];
startedBlock = nil;
}
if (headersReceivedBlock) {
[blocks addObject:headersReceivedBlock];
[headersReceivedBlock release];
headersReceivedBlock = nil;
}
if (bytesReceivedBlock) {
[blocks addObject:bytesReceivedBlock];
[bytesReceivedBlock release];
bytesReceivedBlock = nil;
}
if (bytesSentBlock) {
[blocks addObject:bytesSentBlock];
[bytesSentBlock release];
bytesSentBlock = nil;
}
if (downloadSizeIncrementedBlock) {
[blocks addObject:downloadSizeIncrementedBlock];
[downloadSizeIncrementedBlock release];
downloadSizeIncrementedBlock = nil;
}
if (uploadSizeIncrementedBlock) {
[blocks addObject:uploadSizeIncrementedBlock];
[uploadSizeIncrementedBlock release];
uploadSizeIncrementedBlock = nil;
}
if (dataReceivedBlock) {
[blocks addObject:dataReceivedBlock];
[dataReceivedBlock release];
dataReceivedBlock = nil;
}
if (proxyAuthenticationNeededBlock) {
[blocks addObject:proxyAuthenticationNeededBlock];
[proxyAuthenticationNeededBlock release];
proxyAuthenticationNeededBlock = nil;
}
if (authenticationNeededBlock) {
[blocks addObject:authenticationNeededBlock];
[authenticationNeededBlock release];
authenticationNeededBlock = nil;
}
[[self class] performSelectorOnMainThread:@selector(releaseBlocks:) withObject:blocks waitUntilDone:[NSThread isMainThread]];
}
// Always called on main thread
+ (void)releaseBlocks:(NSArray *)blocks
{
// Blocks will be released when this method exits
}
#endif
#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];
}
NSString *path;
if ([self shouldCompressRequestBody]) {
if (![self compressedPostBodyFilePath]) {
[self setCompressedPostBodyFilePath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]];
NSError *err = nil;
if (![ASIDataCompressor compressDataFromFile:[self postBodyFilePath] toFile:[self compressedPostBodyFilePath] error:&err]) {
[self failWithError:err];
return;
}
}
path = [self compressedPostBodyFilePath];
} else {
path = [self postBodyFilePath];
}
NSError *err = nil;
[self setPostLength:[[[[[NSFileManager alloc] init] autorelease] 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]) {
NSError *err = nil;
NSData *compressedBody = [ASIDataCompressor compressData:[self postBody] error:&err];
if (err) {
[self failWithError:err];
return;
}
[self setCompressedPostBody:compressedBody];
[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];
NSUInteger 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];
}
- (NSURL *)url
{
[[self cancelledLock] lock];
NSURL *u = url;
[[self cancelledLock] unlock];
return u;
}
- (void)setURL:(NSURL *)newURL
{
[[self cancelledLock] lock];
if ([newURL isEqual:[self url]]) {
[[self cancelledLock] unlock];
return;
}
[url release];
url = [newURL retain];
if (requestAuthentication) {
CFRelease(requestAuthentication);
requestAuthentication = NULL;
}
if (proxyAuthentication) {
CFRelease(proxyAuthentication);
proxyAuthentication = NULL;
}
if (request) {
CFRelease(request);
request = NULL;
}
[self setRedirectURL:nil];
[[self cancelledLock] unlock];
}
- (id)delegate
{
[[self cancelledLock] lock];
id d = delegate;
[[self cancelledLock] unlock];
return d;
}
- (void)setDelegate:(id)newDelegate
{
[[self cancelledLock] lock];
delegate = newDelegate;
[[self cancelledLock] unlock];
}
- (id)queue
{
[[self cancelledLock] lock];
id q = queue;
[[self cancelledLock] unlock];
return q;
}
- (void)setQueue:(id)newQueue
{
[[self cancelledLock] lock];
if (newQueue != queue) {
[queue release];
queue = [newQueue retain];
}
[[self cancelledLock] unlock];
}
#pragma mark get information about this request
// cancel the request - this must be run on the same thread as the request is running on
- (void)cancelOnRequestThread
{
#if DEBUG_REQUEST_STATUS
NSLog(@"Request cancelled: %@",self);
#endif
[[self cancelledLock] lock];
if ([self isCancelled] || [self complete]) {
[[self cancelledLock] unlock];
return;
}
[self failWithError:ASIRequestCancelledError];
[self setComplete:YES];
[self cancelLoad];
CFRetain(self);
[self willChangeValueForKey:@"isCancelled"];
cancelled = YES;
[self didChangeValueForKey:@"isCancelled"];
[[self cancelledLock] unlock];
CFRelease(self);
}
- (void)cancel
{
[self performSelector:@selector(cancelOnRequestThread) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
}
- (void)clearDelegatesAndCancel
{
[[self cancelledLock] lock];
// Clear delegates
[self setDelegate:nil];
[self setQueue:nil];
[self setDownloadProgressDelegate:nil];
[self setUploadProgressDelegate:nil];
#if NS_BLOCKS_AVAILABLE
// Clear blocks
[self releaseBlocksOnMainThread];
#endif
[[self cancelledLock] unlock];
[self cancel];
}
- (BOOL)isCancelled
{
BOOL result;
[[self cancelledLock] lock];
result = cancelled;
[[self cancelledLock] unlock];
return result;
}
// 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] && [self shouldWaitToInflateCompressedResponses]) {
return [ASIDataDecompressor uncompressData:[self rawResponseData] error:NULL];
} else {
return [self rawResponseData];
}
return nil;
}
#pragma mark running a request
- (void)startSynchronous
{
#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
NSLog(@"Starting synchronous request %@",self);
#endif
[self setSynchronous:YES];
[self setRunLoopMode:ASIHTTPRequestRunLoopMode];
[self setInProgress:YES];
if (![self isCancelled] && ![self complete]) {
[self main];
while (!complete) {
[[NSRunLoop currentRunLoop] runMode:[self runLoopMode] beforeDate:[NSDate distantFuture]];
}
}
[self setInProgress:NO];
}
- (void)start
{
[self setInProgress:YES];
[self performSelector:@selector(main) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
}
- (void)startAsynchronous
{
#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
NSLog(@"Starting asynchronous request %@",self);
#endif
[sharedQueue addOperation:self];
}
#pragma mark concurrency
- (BOOL)isConcurrent
{
return YES;
}
- (BOOL)isFinished
{
return finished;
}
- (BOOL)isExecuting {
return [self inProgress];
}
#pragma mark request logic
// Create the request
- (void)main
{
@try {
[[self cancelledLock] lock];
#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
if ([ASIHTTPRequest isMultitaskingSupported] && [self shouldContinueWhenAppEntersBackground]) {
backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
// Synchronize the cleanup call on the main thread in case
// the task actually finishes at around the same time.
dispatch_async(dispatch_get_main_queue(), ^{
if (backgroundTask != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
[self cancel];
}
});
}];
}
#endif
// A HEAD request generated by an ASINetworkQueue may have set the error already. If so, we should not proceed.
if ([self error]) {
[self setComplete:YES];
[self markAsFinished];
return;
}
[self setComplete:NO];
[self setDidUseCachedResponse:NO];
if (![self url]) {
[self failWithError:ASIUnableToCreateRequestError];
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 (![[self requestMethod] isEqualToString:@"GET"]) {
[self setDownloadCache:nil];
}
// 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];
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];
if ([self downloadCache]) {
// If this request should use the default policy, set its policy to the download cache's default policy
if (![self cachePolicy]) {
[self setCachePolicy:[[self downloadCache] defaultCachePolicy]];
}
// If have have cached data that is valid for this request, use that and stop
if ([[self downloadCache] canUseCachedDataForRequest:self]) {
[self useDataFromCache];
return;
}
// If cached data is stale, or we have been told to ask the server if it has been modified anyway, we need to add headers for a conditional GET
if ([self cachePolicy] & (ASIAskServerIfModifiedWhenStaleCachePolicy|ASIAskServerIfModifiedCachePolicy)) {
NSDictionary *cachedHeaders = [[self downloadCache] cachedResponseHeadersForURL:[self url]];
if (cachedHeaders) {
NSString *etag = [cachedHeaders objectForKey:@"Etag"];
if (etag) {
[[self requestHeaders] setObject:etag forKey:@"If-None-Match"];
}
NSString *lastModified = [cachedHeaders objectForKey:@"Last-Modified"];
if (lastModified) {
[[self requestHeaders] setObject:lastModified forKey:@"If-Modified-Since"];
}
}
}
}
[self applyAuthorizationHeader];
NSString *header;
for (header in [self requestHeaders]) {
CFHTTPMessageSetHeaderFieldValue(request, (CFStringRef)header, (CFStringRef)[[self requestHeaders] objectForKey:header]);
}
// If we immediately have access to proxy settings, start the request
// Otherwise, we'll start downloading the proxy PAC file, and call startRequest once that process is complete
if ([self configureProxies]) {
[self startRequest];
}
} @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]]];
} @finally {
[[self cancelledLock] unlock];
}
}
- (void)applyAuthorizationHeader
{
// Do we want to send credentials before we are asked for them?
if (![self shouldPresentCredentialsBeforeChallenge]) {
return;
}
// First, see if we have any credentials we can use in the session store
NSDictionary *credentials = nil;
if ([self useSessionPersistence]) {
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 know this request should use Basic auth, we'll add an Authorization header with basic credentials
if ([[self authenticationScheme] isEqualToString:(NSString *)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 useSessionPersistence]) {
credentials = [self findSessionProxyAuthenticationCredentials];
if (credentials) {
if (!CFHTTPMessageApplyCredentialDictionary(request, (CFHTTPAuthenticationRef)[credentials objectForKey:@"Authentication"], (CFDictionaryRef)[credentials objectForKey:@"Credentials"], NULL)) {
[[self class] removeProxyAuthenticationCredentialsFromSessionStore:[credentials objectForKey:@"Credentials"]];
}
}
}
}
- (void)applyCookieHeader
{
// Add cookies from the persistent (mac os global) store
if ([self useCookiePersistence]) {
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[[self url] absoluteURL]];
if (cookies) {
[[self requestCookies] addObjectsFromArray:cookies];
}
}
// Apply request cookies