-
Notifications
You must be signed in to change notification settings - Fork 1
/
GTMHTTPFetcher.m
executable file
·1935 lines (1620 loc) · 62.3 KB
/
GTMHTTPFetcher.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
/* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// GTMHTTPFetcher.m
//
#define GTMHTTPFETCHER_DEFINE_GLOBALS 1
#import "GTMHTTPFetcher.h"
#if GTM_BACKGROUND_FETCHING
#import <UIKit/UIKit.h>
#endif
static id <GTMCookieStorageProtocol> gGTMFetcherStaticCookieStorage = nil;
static Class gGTMFetcherConnectionClass = nil;
// The default max retry interview is 10 minutes for uploads (POST/PUT/PATCH),
// 1 minute for downloads.
static const NSTimeInterval kUnsetMaxRetryInterval = -1;
static const NSTimeInterval kDefaultMaxDownloadRetryInterval = 60.0;
static const NSTimeInterval kDefaultMaxUploadRetryInterval = 60.0 * 10.;
// delegateQueue callback parameters
static NSString *const kCallbackData = @"data";
static NSString *const kCallbackError = @"error";
//
// GTMHTTPFetcher
//
@interface GTMHTTPFetcher ()
@property (copy) NSString *temporaryDownloadPath;
@property (retain) id <GTMCookieStorageProtocol> cookieStorage;
@property (readwrite, retain) NSData *downloadedData;
#if NS_BLOCKS_AVAILABLE
@property (copy) void (^completionBlock)(NSData *, NSError *);
#endif
- (BOOL)beginFetchMayDelay:(BOOL)mayDelay
mayAuthorize:(BOOL)mayAuthorize;
- (void)failToBeginFetchWithError:(NSError *)error;
- (void)failToBeginFetchDeferWithError:(NSError *)error;
#if GTM_BACKGROUND_FETCHING
- (void)endBackgroundTask;
- (void)backgroundFetchExpired;
#endif
- (BOOL)authorizeRequest;
- (void)authorizer:(id <GTMFetcherAuthorizationProtocol>)auth
request:(NSMutableURLRequest *)request
finishedWithError:(NSError *)error;
- (NSString *)createTempDownloadFilePathForPath:(NSString *)targetPath;
- (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks;
- (BOOL)shouldReleaseCallbacksUponCompletion;
- (void)addCookiesToRequest:(NSMutableURLRequest *)request;
- (void)handleCookiesForResponse:(NSURLResponse *)response;
- (void)invokeFetchCallbacksWithData:(NSData *)data
error:(NSError *)error;
- (void)invokeFetchCallback:(SEL)sel
target:(id)target
data:(NSData *)data
error:(NSError *)error;
- (void)invokeFetchCallbacksOnDelegateQueueWithData:(NSData *)data
error:(NSError *)error;
- (void)releaseCallbacks;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (BOOL)shouldRetryNowForStatus:(NSInteger)status error:(NSError *)error;
- (void)destroyRetryTimer;
- (void)beginRetryTimer;
- (void)primeRetryTimerWithNewTimeInterval:(NSTimeInterval)secs;
- (void)sendStopNotificationIfNeeded;
- (void)retryFetch;
- (void)retryTimerFired:(NSTimer *)timer;
@end
@interface GTMHTTPFetcher (GTMHTTPFetcherLoggingInternal)
- (void)setupStreamLogging;
- (void)logFetchWithError:(NSError *)error;
@end
@implementation GTMHTTPFetcher
+ (GTMHTTPFetcher *)fetcherWithRequest:(NSURLRequest *)request {
return [[[[self class] alloc] initWithRequest:request] autorelease];
}
+ (GTMHTTPFetcher *)fetcherWithURL:(NSURL *)requestURL {
return [self fetcherWithRequest:[NSURLRequest requestWithURL:requestURL]];
}
+ (GTMHTTPFetcher *)fetcherWithURLString:(NSString *)requestURLString {
return [self fetcherWithURL:[NSURL URLWithString:requestURLString]];
}
+ (void)initialize {
// initialize is guaranteed by the runtime to be called in a
// thread-safe manner
if (!gGTMFetcherStaticCookieStorage) {
Class cookieStorageClass = NSClassFromString(@"GTMCookieStorage");
if (cookieStorageClass) {
gGTMFetcherStaticCookieStorage = [[cookieStorageClass alloc] init];
}
}
}
- (id)init {
return [self initWithRequest:nil];
}
- (id)initWithRequest:(NSURLRequest *)request {
self = [super init];
if (self) {
request_ = [request mutableCopy];
if (gGTMFetcherStaticCookieStorage != nil) {
// The user has compiled with the cookie storage class available;
// default to static cookie storage, so our cookies are independent
// of the cookies of other apps.
[self setCookieStorageMethod:kGTMHTTPFetcherCookieStorageMethodStatic];
} else {
// Default to system default cookie storage
[self setCookieStorageMethod:kGTMHTTPFetcherCookieStorageMethodSystemDefault];
}
}
return self;
}
- (id)copyWithZone:(NSZone *)zone {
// disallow use of fetchers in a copy property
[self doesNotRecognizeSelector:_cmd];
return nil;
}
- (NSString *)description {
return [NSString stringWithFormat:@"%@ %p (%@)",
[self class], self, [self.mutableRequest URL]];
}
#if !GTM_IPHONE
- (void)finalize {
[self stopFetchReleasingCallbacks:YES]; // releases connection_, destroys timers
[super finalize];
}
#endif
- (void)dealloc {
#if DEBUG
NSAssert(!isStopNotificationNeeded_,
@"unbalanced fetcher notification for %@", [request_ URL]);
#endif
// Note: if a connection or a retry timer was pending, then this instance
// would be retained by those so it wouldn't be getting dealloc'd,
// hence we don't need to stopFetch here
[request_ release];
[connection_ release];
[downloadedData_ release];
[downloadPath_ release];
[temporaryDownloadPath_ release];
[downloadFileHandle_ release];
[credential_ release];
[proxyCredential_ release];
[postData_ release];
[postStream_ release];
[loggedStreamData_ release];
[response_ release];
#if NS_BLOCKS_AVAILABLE
[completionBlock_ release];
[receivedDataBlock_ release];
[sentDataBlock_ release];
[retryBlock_ release];
#endif
[userData_ release];
[properties_ release];
[delegateQueue_ release];
[runLoopModes_ release];
[fetchHistory_ release];
[cookieStorage_ release];
[authorizer_ release];
[service_ release];
[serviceHost_ release];
[thread_ release];
[retryTimer_ release];
[comment_ release];
[log_ release];
#if !STRIP_GTM_FETCH_LOGGING
[logRequestBody_ release];
[logResponseBody_ release];
#endif
[super dealloc];
}
#pragma mark -
// Begin fetching the URL (or begin a retry fetch). The delegate is retained
// for the duration of the fetch connection.
- (BOOL)beginFetchWithDelegate:(id)delegate
didFinishSelector:(SEL)finishedSelector {
GTMAssertSelectorNilOrImplementedWithArgs(delegate, finishedSelector, @encode(GTMHTTPFetcher *), @encode(NSData *), @encode(NSError *), 0);
GTMAssertSelectorNilOrImplementedWithArgs(delegate, receivedDataSel_, @encode(GTMHTTPFetcher *), @encode(NSData *), 0);
GTMAssertSelectorNilOrImplementedWithArgs(delegate, retrySel_, @encode(GTMHTTPFetcher *), @encode(BOOL), @encode(NSError *), 0);
// We'll retain the delegate only during the outstanding connection (similar
// to what Cocoa does with performSelectorOnMainThread:) and during
// authorization or delays, since the app would crash
// if the delegate was released before the fetch calls back
[self setDelegate:delegate];
finishedSel_ = finishedSelector;
return [self beginFetchMayDelay:YES
mayAuthorize:YES];
}
- (BOOL)beginFetchMayDelay:(BOOL)mayDelay
mayAuthorize:(BOOL)mayAuthorize {
// This is the internal entry point for re-starting fetches
NSError *error = nil;
if (connection_ != nil) {
NSAssert1(connection_ != nil, @"fetch object %@ being reused; this should never happen", self);
goto CannotBeginFetch;
}
if (request_ == nil || [request_ URL] == nil) {
NSAssert(request_ != nil, @"beginFetchWithDelegate requires a request with a URL");
goto CannotBeginFetch;
}
self.downloadedData = nil;
downloadedLength_ = 0;
if (mayDelay && service_) {
BOOL shouldFetchNow = [service_ fetcherShouldBeginFetching:self];
if (!shouldFetchNow) {
// the fetch is deferred, but will happen later
return YES;
}
}
NSString *effectiveHTTPMethod = [request_ valueForHTTPHeaderField:@"X-HTTP-Method-Override"];
if (effectiveHTTPMethod == nil) {
effectiveHTTPMethod = [request_ HTTPMethod];
}
BOOL isEffectiveHTTPGet = (effectiveHTTPMethod == nil
|| [effectiveHTTPMethod isEqual:@"GET"]);
if (postData_ || postStream_) {
if (isEffectiveHTTPGet) {
[request_ setHTTPMethod:@"POST"];
isEffectiveHTTPGet = NO;
}
if (postData_) {
[request_ setHTTPBody:postData_];
} else {
if ([self respondsToSelector:@selector(setupStreamLogging)]) {
[self performSelector:@selector(setupStreamLogging)];
}
[request_ setHTTPBodyStream:postStream_];
}
}
// We authorize after setting up the http method and body in the request
// because OAuth 1 may need to sign the request body
if (mayAuthorize && authorizer_) {
BOOL isAuthorized = [authorizer_ isAuthorizedRequest:request_];
if (!isAuthorized) {
// authorization needed
return [self authorizeRequest];
}
}
[fetchHistory_ updateRequest:request_ isHTTPGet:isEffectiveHTTPGet];
// set the default upload or download retry interval, if necessary
if (isRetryEnabled_
&& maxRetryInterval_ <= kUnsetMaxRetryInterval) {
if (isEffectiveHTTPGet || [effectiveHTTPMethod isEqual:@"HEAD"]) {
[self setMaxRetryInterval:kDefaultMaxDownloadRetryInterval];
} else {
[self setMaxRetryInterval:kDefaultMaxUploadRetryInterval];
}
}
[self addCookiesToRequest:request_];
if (downloadPath_ != nil) {
// downloading to a path, so create a temporary file and a file handle for
// downloading
NSString *tempPath = [self createTempDownloadFilePathForPath:downloadPath_];
BOOL didCreate = [[NSData data] writeToFile:tempPath
options:0
error:&error];
if (!didCreate) goto CannotBeginFetch;
[self setTemporaryDownloadPath:tempPath];
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:tempPath];
if (fh == nil) goto CannotBeginFetch;
[self setDownloadFileHandle:fh];
}
// finally, start the connection
Class connectionClass = [[self class] connectionClass];
NSOperationQueue *delegateQueue = delegateQueue_;
if (delegateQueue &&
![connectionClass instancesRespondToSelector:@selector(setDelegateQueue:)]) {
// NSURLConnection has no setDelegateQueue: on iOS 4 and Mac OS X 10.5.
delegateQueue = nil;
self.delegateQueue = nil;
}
#if DEBUG && TARGET_OS_IPHONE
BOOL isPreIOS6 = (NSFoundationVersionNumber <= 890.1);
if (isPreIOS6 && delegateQueue) {
NSLog(@"GTMHTTPFetcher delegateQueue not safe in iOS 5");
}
#endif
if ([runLoopModes_ count] == 0 && delegateQueue == nil) {
// No custom callback modes or queue were specified, so start the connection
// on the current run loop in the current mode
connection_ = [[connectionClass connectionWithRequest:request_
delegate:self] retain];
} else {
// Specify callbacks be on an operation queue or on the current run loop
// in the specified modes
connection_ = [[connectionClass alloc] initWithRequest:request_
delegate:self
startImmediately:NO];
if (delegateQueue) {
[connection_ performSelector:@selector(setDelegateQueue:)
withObject:delegateQueue];
} else if (runLoopModes_) {
NSRunLoop *rl = [NSRunLoop currentRunLoop];
for (NSString *mode in runLoopModes_) {
[connection_ scheduleInRunLoop:rl forMode:mode];
}
}
[connection_ start];
}
hasConnectionEnded_ = NO;
if (!connection_) {
NSAssert(connection_ != nil, @"beginFetchWithDelegate could not create a connection");
goto CannotBeginFetch;
}
if (downloadFileHandle_ != nil) {
// downloading to a file, so downloadedData_ remains nil
} else {
self.downloadedData = [NSMutableData data];
}
#if GTM_BACKGROUND_FETCHING
backgroundTaskIdentifer_ = 0; // UIBackgroundTaskInvalid is 0 on iOS 4
if (shouldFetchInBackground_) {
// For iOS 3 compatibility, ensure that UIApp supports backgrounding
UIApplication *app = [UIApplication sharedApplication];
if ([app respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)]) {
// Tell UIApplication that we want to continue even when the app is in the
// background.
NSThread *thread = [NSThread currentThread];
backgroundTaskIdentifer_ = [app beginBackgroundTaskWithExpirationHandler:^{
// Callback - this block is always invoked by UIApplication on the main
// thread, but we want to run the user's callbacks on the thread used
// to start the fetch.
[self performSelector:@selector(backgroundFetchExpired)
onThread:thread
withObject:nil
waitUntilDone:YES];
}];
}
}
#endif
// Once connection_ is non-nil we can send the start notification
isStopNotificationNeeded_ = YES;
NSNotificationCenter *defaultNC = [NSNotificationCenter defaultCenter];
[defaultNC postNotificationName:kGTMHTTPFetcherStartedNotification
object:self];
return YES;
CannotBeginFetch:
[self failToBeginFetchDeferWithError:error];
return NO;
}
- (void)failToBeginFetchDeferWithError:(NSError *)error {
if (delegateQueue_) {
// Deferring will happen by the callback being invoked on the specified
// queue.
[self failToBeginFetchWithError:error];
} else {
// No delegate queue has been specified, so put the callback
// on an appropriate run loop.
NSArray *modes = (runLoopModes_ ? runLoopModes_ :
[NSArray arrayWithObject:NSRunLoopCommonModes]);
[self performSelector:@selector(failToBeginFetchWithError:)
onThread:[NSThread currentThread]
withObject:error
waitUntilDone:NO
modes:modes];
}
}
- (void)failToBeginFetchWithError:(NSError *)error {
if (error == nil) {
error = [NSError errorWithDomain:kGTMHTTPFetcherErrorDomain
code:kGTMHTTPFetcherErrorDownloadFailed
userInfo:nil];
}
[[self retain] autorelease]; // In case the callback releases us
[self invokeFetchCallbacksOnDelegateQueueWithData:nil
error:error];
[self releaseCallbacks];
[service_ fetcherDidStop:self];
self.authorizer = nil;
if (temporaryDownloadPath_) {
[[NSFileManager defaultManager] removeItemAtPath:temporaryDownloadPath_
error:NULL];
self.temporaryDownloadPath = nil;
}
}
#if GTM_BACKGROUND_FETCHING
- (void)backgroundFetchExpired {
// On background expiration, we stop the fetch and invoke the callbacks
NSError *error = [NSError errorWithDomain:kGTMHTTPFetcherErrorDomain
code:kGTMHTTPFetcherErrorBackgroundExpiration
userInfo:nil];
[self invokeFetchCallbacksOnDelegateQueueWithData:nil
error:error];
@synchronized(self) {
// Stopping the fetch here will indirectly call endBackgroundTask
[self stopFetchReleasingCallbacks:NO];
[self releaseCallbacks];
self.authorizer = nil;
}
}
- (void)endBackgroundTask {
@synchronized(self) {
// Whenever the connection stops or background execution expires,
// we need to tell UIApplication we're done
if (backgroundTaskIdentifer_) {
// If backgroundTaskIdentifer_ is non-zero, we know we're on iOS 4
UIApplication *app = [UIApplication sharedApplication];
[app endBackgroundTask:backgroundTaskIdentifer_];
backgroundTaskIdentifer_ = 0;
}
}
}
#endif // GTM_BACKGROUND_FETCHING
- (BOOL)authorizeRequest {
id authorizer = self.authorizer;
SEL asyncAuthSel = @selector(authorizeRequest:delegate:didFinishSelector:);
if ([authorizer respondsToSelector:asyncAuthSel]) {
SEL callbackSel = @selector(authorizer:request:finishedWithError:);
[authorizer authorizeRequest:request_
delegate:self
didFinishSelector:callbackSel];
return YES;
} else {
NSAssert(authorizer == nil, @"invalid authorizer for fetch");
// No authorizing possible, and authorizing happens only after any delay;
// just begin fetching
return [self beginFetchMayDelay:NO
mayAuthorize:NO];
}
}
- (void)authorizer:(id <GTMFetcherAuthorizationProtocol>)auth
request:(NSMutableURLRequest *)request
finishedWithError:(NSError *)error {
if (error != nil) {
// We can't fetch without authorization
[self failToBeginFetchDeferWithError:error];
} else {
[self beginFetchMayDelay:NO
mayAuthorize:NO];
}
}
#if NS_BLOCKS_AVAILABLE
- (BOOL)beginFetchWithCompletionHandler:(void (^)(NSData *data, NSError *error))handler {
self.completionBlock = handler;
// The user may have called setDelegate: earlier if they want to use other
// delegate-style callbacks during the fetch; otherwise, the delegate is nil,
// which is fine.
return [self beginFetchWithDelegate:[self delegate]
didFinishSelector:nil];
}
#endif
- (NSString *)createTempDownloadFilePathForPath:(NSString *)targetPath {
NSString *tempDir = nil;
#if (!TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED >= 1060))
// Find an appropriate directory for the download, ideally on the same disk
// as the final target location so the temporary file won't have to be moved
// to a different disk.
//
// Available in SDKs for 10.6 and iOS 4
//
// Oct 2011: We previously also used URLForDirectory for
// (TARGET_OS_IPHONE && (__IPHONE_OS_VERSION_MAX_ALLOWED >= 40000))
// but that is returning a non-temporary directory for iOS, unfortunately
SEL sel = @selector(URLForDirectory:inDomain:appropriateForURL:create:error:);
if ([NSFileManager instancesRespondToSelector:sel]) {
NSError *error = nil;
NSURL *targetURL = [NSURL fileURLWithPath:targetPath];
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSURL *tempDirURL = [fileMgr URLForDirectory:NSItemReplacementDirectory
inDomain:NSUserDomainMask
appropriateForURL:targetURL
create:YES
error:&error];
tempDir = [tempDirURL path];
}
#endif
if (tempDir == nil) {
tempDir = NSTemporaryDirectory();
}
static unsigned int counter = 0;
NSString *name = [NSString stringWithFormat:@"gtmhttpfetcher_%u_%u",
++counter, (unsigned int) arc4random()];
NSString *result = [tempDir stringByAppendingPathComponent:name];
return result;
}
- (void)addCookiesToRequest:(NSMutableURLRequest *)request {
// Get cookies for this URL from our storage array, if
// we have a storage array
if (cookieStorageMethod_ != kGTMHTTPFetcherCookieStorageMethodSystemDefault
&& cookieStorageMethod_ != kGTMHTTPFetcherCookieStorageMethodNone) {
NSArray *cookies = [cookieStorage_ cookiesForURL:[request URL]];
if ([cookies count] > 0) {
NSDictionary *headerFields = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
NSString *cookieHeader = [headerFields objectForKey:@"Cookie"]; // key used in header dictionary
if (cookieHeader) {
[request addValue:cookieHeader forHTTPHeaderField:@"Cookie"]; // header name
}
}
}
}
// Returns YES if this is in the process of fetching a URL, or waiting to
// retry, or waiting for authorization, or waiting to be issued by the
// service object
- (BOOL)isFetching {
if (connection_ != nil || retryTimer_ != nil) return YES;
BOOL isAuthorizing = [authorizer_ isAuthorizingRequest:request_];
if (isAuthorizing) return YES;
BOOL isDelayed = [service_ isDelayingFetcher:self];
return isDelayed;
}
// Returns the status code set in connection:didReceiveResponse:
- (NSInteger)statusCode {
NSInteger statusCode;
if (response_ != nil
&& [response_ respondsToSelector:@selector(statusCode)]) {
statusCode = [(NSHTTPURLResponse *)response_ statusCode];
} else {
// Default to zero, in hopes of hinting "Unknown" (we can't be
// sure that things are OK enough to use 200).
statusCode = 0;
}
return statusCode;
}
- (NSDictionary *)responseHeaders {
if (response_ != nil
&& [response_ respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *headers = [(NSHTTPURLResponse *)response_ allHeaderFields];
return headers;
}
return nil;
}
- (void)releaseCallbacks {
[delegate_ autorelease];
delegate_ = nil;
[delegateQueue_ autorelease];
delegateQueue_ = nil;
#if NS_BLOCKS_AVAILABLE
self.completionBlock = nil;
self.sentDataBlock = nil;
self.receivedDataBlock = nil;
self.retryBlock = nil;
#endif
}
// Cancel the fetch of the URL that's currently in progress.
- (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks {
id <GTMHTTPFetcherServiceProtocol> service;
// if the connection or the retry timer is all that's retaining the fetcher,
// we want to be sure this instance survives stopping at least long enough for
// the stack to unwind
[[self retain] autorelease];
[self destroyRetryTimer];
@synchronized(self) {
service = [[service_ retain] autorelease];
if (connection_) {
// in case cancelling the connection calls this recursively, we want
// to ensure that we'll only release the connection and delegate once,
// so first set connection_ to nil
NSURLConnection* oldConnection = connection_;
connection_ = nil;
if (!hasConnectionEnded_) {
[oldConnection cancel];
}
// this may be called in a callback from the connection, so use autorelease
[oldConnection autorelease];
}
}
// send the stopped notification
[self sendStopNotificationIfNeeded];
@synchronized(self) {
[authorizer_ stopAuthorizationForRequest:request_];
if (shouldReleaseCallbacks) {
[self releaseCallbacks];
self.authorizer = nil;
}
if (temporaryDownloadPath_) {
[[NSFileManager defaultManager] removeItemAtPath:temporaryDownloadPath_
error:NULL];
self.temporaryDownloadPath = nil;
}
}
[service fetcherDidStop:self];
#if GTM_BACKGROUND_FETCHING
[self endBackgroundTask];
#endif
}
// External stop method
- (void)stopFetching {
[self stopFetchReleasingCallbacks:YES];
}
- (void)sendStopNotificationIfNeeded {
BOOL sendNow = NO;
@synchronized(self) {
if (isStopNotificationNeeded_) {
isStopNotificationNeeded_ = NO;
sendNow = YES;
}
}
if (sendNow) {
NSNotificationCenter *defaultNC = [NSNotificationCenter defaultCenter];
[defaultNC postNotificationName:kGTMHTTPFetcherStoppedNotification
object:self];
}
}
- (void)retryFetch {
[self stopFetchReleasingCallbacks:NO];
[self beginFetchWithDelegate:delegate_
didFinishSelector:finishedSel_];
}
- (void)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds {
NSDate* giveUpDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds];
// Loop until the callbacks have been called and released, and until
// the connection is no longer pending, or until the timeout has expired
BOOL isMainThread = [NSThread isMainThread];
while ((!hasConnectionEnded_
#if NS_BLOCKS_AVAILABLE
|| completionBlock_ != nil
#endif
|| delegate_ != nil)
&& [giveUpDate timeIntervalSinceNow] > 0) {
// Run the current run loop 1/1000 of a second to give the networking
// code a chance to work
if (isMainThread || delegateQueue_ == nil) {
NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:0.001];
[[NSRunLoop currentRunLoop] runUntilDate:stopDate];
} else {
[NSThread sleepForTimeInterval:0.001];
}
}
}
#pragma mark NSURLConnection Delegate Methods
//
// NSURLConnection Delegate Methods
//
// This method just says "follow all redirects", which _should_ be the default behavior,
// According to file:///Developer/ADC%20Reference%20Library/documentation/Cocoa/Conceptual/URLLoadingSystem
// but the redirects were not being followed until I added this method. May be
// a bug in the NSURLConnection code, or the documentation.
//
// In OS X 10.4.8 and earlier, the redirect request doesn't
// get the original's headers and body. This causes POSTs to fail.
// So we construct a new request, a copy of the original, with overrides from the
// redirect.
//
// Docs say that if redirectResponse is nil, just return the redirectRequest.
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)redirectRequest
redirectResponse:(NSURLResponse *)redirectResponse {
@synchronized(self) {
if (redirectRequest && redirectResponse) {
// save cookies from the response
[self handleCookiesForResponse:redirectResponse];
NSMutableURLRequest *newRequest = [[request_ mutableCopy] autorelease];
// copy the URL
NSURL *redirectURL = [redirectRequest URL];
NSURL *url = [newRequest URL];
// disallow scheme changes (say, from https to http)
NSString *redirectScheme = [url scheme];
NSString *newScheme = [redirectURL scheme];
NSString *newResourceSpecifier = [redirectURL resourceSpecifier];
if ([redirectScheme caseInsensitiveCompare:@"http"] == NSOrderedSame
&& newScheme != nil
&& [newScheme caseInsensitiveCompare:@"https"] == NSOrderedSame) {
// allow the change from http to https
redirectScheme = newScheme;
}
NSString *newUrlString = [NSString stringWithFormat:@"%@:%@",
redirectScheme, newResourceSpecifier];
NSURL *newURL = [NSURL URLWithString:newUrlString];
[newRequest setURL:newURL];
// any headers in the redirect override headers in the original.
NSDictionary *redirectHeaders = [redirectRequest allHTTPHeaderFields];
for (NSString *key in redirectHeaders) {
NSString *value = [redirectHeaders objectForKey:key];
[newRequest setValue:value forHTTPHeaderField:key];
}
[self addCookiesToRequest:newRequest];
redirectRequest = newRequest;
// log the response we just received
[self setResponse:redirectResponse];
[self logNowWithError:nil];
// update the request for future logging
NSMutableURLRequest *mutable = [[redirectRequest mutableCopy] autorelease];
[self setMutableRequest:mutable];
}
return redirectRequest;
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
@synchronized(self) {
// This method is called when the server has determined that it
// has enough information to create the NSURLResponse
// it can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
[downloadedData_ setLength:0];
[downloadFileHandle_ truncateFileAtOffset:0];
downloadedLength_ = 0;
[self setResponse:response];
// Save cookies from the response
[self handleCookiesForResponse:response];
}
}
// handleCookiesForResponse: handles storage of cookies for responses passed to
// connection:willSendRequest:redirectResponse: and connection:didReceiveResponse:
- (void)handleCookiesForResponse:(NSURLResponse *)response {
if (cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodSystemDefault
|| cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodNone) {
// do nothing special for NSURLConnection's default storage mechanism
// or when we're ignoring cookies
} else if ([response respondsToSelector:@selector(allHeaderFields)]) {
// grab the cookies from the header as NSHTTPCookies and store them either
// into our static array or into the fetchHistory
NSDictionary *responseHeaderFields = [(NSHTTPURLResponse *)response allHeaderFields];
if (responseHeaderFields) {
NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:responseHeaderFields
forURL:[response URL]];
if ([cookies count] > 0) {
[cookieStorage_ setCookies:cookies];
}
}
}
}
-(void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
@synchronized(self) {
if ([challenge previousFailureCount] <= 2) {
NSURLCredential *credential = credential_;
if ([[challenge protectionSpace] isProxy] && proxyCredential_ != nil) {
credential = proxyCredential_;
}
// Here, if credential is still nil, then we *could* try to get it from
// NSURLCredentialStorage's defaultCredentialForProtectionSpace:.
// We don't, because we're assuming:
//
// - for server credentials, we only want ones supplied by the program
// calling http fetcher
// - for proxy credentials, if one were necessary and available in the
// keychain, it would've been found automatically by NSURLConnection
// and this challenge delegate method never would've been called
// anyway
if (credential) {
// try the credential
[[challenge sender] useCredential:credential
forAuthenticationChallenge:challenge];
return;
}
}
// If we don't have credentials, or we've already failed auth 3x,
// report the error, putting the challenge as a value in the userInfo
// dictionary.
#if DEBUG
NSAssert(!isCancellingChallenge_, @"isCancellingChallenge_ unexpected");
#endif
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:challenge
forKey:kGTMHTTPFetcherErrorChallengeKey];
NSError *error = [NSError errorWithDomain:kGTMHTTPFetcherErrorDomain
code:kGTMHTTPFetcherErrorAuthenticationChallengeFailed
userInfo:userInfo];
// cancelAuthenticationChallenge seems to indirectly call
// connection:didFailWithError: now, though that isn't documented
//
// We'll use an ivar to make the indirect invocation of the
// delegate method do nothing.
isCancellingChallenge_ = YES;
[[challenge sender] cancelAuthenticationChallenge:challenge];
isCancellingChallenge_ = NO;
[self connection:connection didFailWithError:error];
}
}
- (void)invokeFetchCallbacksWithData:(NSData *)data
error:(NSError *)error {
// To avoid deadlocks, this should not be called inside of @synchronized(self)
id target;
SEL sel;
#if NS_BLOCKS_AVAILABLE
void (^block)(NSData *, NSError *);
#endif
@synchronized(self) {
target = delegate_;
sel = finishedSel_;
block = completionBlock_;
}
[[self retain] autorelease]; // In case the callback releases us
[self invokeFetchCallback:sel
target:target
data:data
error:error];
#if NS_BLOCKS_AVAILABLE
if (block) {
block(data, error);
}
#endif
}
- (void)invokeFetchCallback:(SEL)sel
target:(id)target
data:(NSData *)data
error:(NSError *)error {
// This method is available to subclasses which may provide a customized
// target pointer.
if (target && sel) {
NSMethodSignature *sig = [target methodSignatureForSelector:sel];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
[invocation setSelector:sel];
[invocation setTarget:target];
[invocation setArgument:&self atIndex:2];
[invocation setArgument:&data atIndex:3];
[invocation setArgument:&error atIndex:4];
[invocation invoke];
}
}
- (void)invokeFetchCallbacksOnDelegateQueueWithData:(NSData *)data
error:(NSError *)error {
// This is called by methods that are not already on the delegateQueue
// (as NSURLConnection callbacks should already be, but other failures
// are not.)
if (!delegateQueue_) {
[self invokeFetchCallbacksWithData:data error:error];
}
// Values may be nil.
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];
[dict setValue:data forKey:kCallbackData];
[dict setValue:error forKey:kCallbackError];
NSInvocationOperation *op =
[[[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(invokeOnQueueWithDictionary:)
object:dict] autorelease];
[delegateQueue_ addOperation:op];
}
- (void)invokeOnQueueWithDictionary:(NSDictionary *)dict {
NSData *data = [dict objectForKey:kCallbackData];
NSError *error = [dict objectForKey:kCallbackError];
[self invokeFetchCallbacksWithData:data error:error];