/
GDataHTTPFetcher.m
executable file
·2046 lines (1619 loc) · 60.5 KB
/
GDataHTTPFetcher.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) 2007 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.
*/
//
// GDataHTTPFetcher.m
//
#define GDATAHTTPFETCHER_DEFINE_GLOBALS 1
#import "GDataHTTPFetcher.h"
#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
@interface NSURLConnection (LeopardMethodsOnTigerBuilds)
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;
- (void)start;
- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
@end
#endif
static NSString* const kGDataLastModifiedHeader = @"Last-Modified";
static NSString* const kGDataIfModifiedSinceHeader = @"If-Modified-Since";
SEL const kUnifiedFailureCallback = (SEL) (void *) -1;
static GDataCookieStorage* gGDataFetcherStaticCookieStorage = nil;
static Class gGDataFetcherConnectionClass = nil;
static NSArray *gGDataFetcherDefaultRunLoopModes = nil;
const NSTimeInterval kDefaultMaxRetryInterval = 60. * 10.; // 10 minutes
const NSTimeInterval kCachedURLReservationInterval = 60.; // 1 minute
//
// internal classes
//
@interface GDataCookieStorage : NSObject {
// The cookie storage object manages an array holding cookies, but the array
// is allocated externally (it may be in a fetcher object or the static
// fetcher cookie array.) See the fetcher's setCookieStorageMethod:
// for allocation of this object and assignment of its cookies array.
NSMutableArray *cookies_;
}
// add all NSHTTPCookies in the supplied array to the storage array,
// replacing cookies in the storage array as appropriate
// Side effect: removes expired cookies from the storage array
- (void)setCookies:(NSArray *)newCookies;
// retrieve all cookies appropriate for the given URL, considering
// domain, path, cookie name, expiration, security setting.
// Side effect: removes expired cookies from the storage array
- (NSArray *)cookiesForURL:(NSURL *)theURL;
// return a cookie with the same name, domain, and path as the
// given cookie, or else return nil if none found
//
// Both the cookie being tested and all stored cookies should
// be valid (non-nil name, domains, paths)
- (NSHTTPCookie *)cookieMatchingCookie:(NSHTTPCookie *)cookie;
// remove any expired cookies, excluding cookies with nil expirations
- (void)removeExpiredCookies;
- (void)removeAllCookies;
@end
// GDataURLCache and GDataCachedURLResponse have interfaces similar to their
// NSURLCache counterparts, in hopes that someday the NSURLCache versions
// can be used. But in 10.5.8, those are not reliable enough except when
// used with +setSharedURLCache. Our goal here is just to cache
// responses for handling if-modified-since requests that return
// "304 Not Modified" responses, not for replacing the general URL caches.
@interface GDataCachedURLResponse : NSObject {
NSURLResponse *response_;
NSData *data_;
NSDate *useDate_; // date this response was last saved or used
NSDate *reservationDate_; // date this response's last modified date was used
}
- (id)initWithResponse:(NSURLResponse *)response data:(NSData *)data;
- (NSURLResponse *)response;
- (NSData *)data;
// date the response was saved or last accessed
- (NSDate *)useDate;
- (void)setUseDate:(NSDate *)date;
// date the response's last-modified header was last used for a fetch request
- (NSDate *)reservationDate;
- (void)setReservationDate:(NSDate *)date;
@end
@interface GDataURLCache : NSObject {
NSMutableDictionary *responses_; // maps request URL to GDataCachedURLResponse
NSUInteger memoryCapacity_; // capacity of NSDatas in the responses
NSUInteger totalDataSize_; // sum of sizes of NSDatas of all responses
NSTimeInterval reservationInterval_; // reservation expiration interval
}
- (id)initWithMemoryCapacity:(NSUInteger)totalBytes;
- (GDataCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request;
- (void)storeCachedResponse:(GDataCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request;
- (void)removeCachedResponseForRequest:(NSURLRequest *)request;
- (void)removeAllCachedResponses;
- (NSUInteger)memoryCapacity;
- (void)setMemoryCapacity:(NSUInteger)totalBytes;
// for unit testing
- (void)setReservationInterval:(NSTimeInterval)secs;
- (NSDictionary *)responses;
- (NSUInteger)totalDataSize;
@end
@interface GDataHTTPFetchHistory (InternalMethods)
- (NSString *)cachedLastModifiedStringForRequest:(NSURLRequest *)request;
- (NSData *)cachedDataForRequest:(NSURLRequest *)request;
- (void)removeCachedDataForRequest:(NSURLRequest *)request;
- (void)updateFetchHistoryWithRequest:(NSURLRequest *)request
response:(NSURLResponse *)response
downloadedData:(NSData *)downloadedData;
@end
//
// GDataHTTPFetcher
//
@interface GDataHTTPFetcher (PrivateMethods)
- (void)stopFetchReleasingBlocks:(BOOL)shouldReleaseBlocks;
- (void)handleCookiesForResponse:(NSURLResponse *)response;
- (void)setCookieStorage:(GDataCookieStorage *)obj;
- (void)logNowWithError:(NSError *)error;
- (BOOL)shouldRetryNowForStatus:(NSInteger)status error:(NSError *)error;
- (void)destroyRetryTimer;
- (void)beginRetryTimer;
- (void)primeRetryTimerWithNewTimeInterval:(NSTimeInterval)secs;
- (void)sendStopNotificationIfNeeded;
- (void)retryFetch;
@end
@implementation GDataHTTPFetcher
+ (GDataHTTPFetcher *)httpFetcherWithRequest:(NSURLRequest *)request {
return [[[[self class] alloc] initWithRequest:request] autorelease];
}
+ (void)initialize {
// note that initialize is guaranteed by the runtime to be called in a
// thread-safe manner
if (!gGDataFetcherStaticCookieStorage) {
gGDataFetcherStaticCookieStorage = [[GDataCookieStorage alloc] init];
}
}
- (id)init {
return [self initWithRequest:nil];
}
- (id)initWithRequest:(NSURLRequest *)request {
if ((self = [super init]) != nil) {
request_ = [request mutableCopy];
// default to static cookie storage
[self setCookieStorageMethod:kGDataHTTPFetcherCookieStorageMethodStatic];
}
return self;
}
- (id)copyWithZone:(NSZone *)zone {
// disallow use of fetchers in a copy property
[self doesNotRecognizeSelector:_cmd];
return nil;
}
#if !GDATA_IPHONE
- (void)finalize {
[self stopFetchReleasingBlocks:YES]; // releases connection_, destroys timers
[super finalize];
}
#endif
- (void)dealloc {
// 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];
[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];
[runLoopModes_ release];
[fetchHistory_ release];
[cookieStorage_ release];
[retryTimer_ invalidate];
[retryTimer_ release];
[super dealloc];
}
#pragma mark -
// Updated fetched API
//
// Begin fetching the URL. The delegate is retained for the duration of
// the fetch connection.
//
// The delegate must provide and implement the finished and failed selectors.
//
// finishedSEL has a signature like:
// - (void)fetcher:(GDataHTTPFetcher *)fetcher finishedWithData:(NSData *)data
// failedSEL has a signature like:
// - (void)fetcher:(GDataHTTPFetcher *)fetcher failedWithError:(NSError *)error
//
// Server errors (status >= 300) are reported as the code of the error object.
- (BOOL)beginFetchWithDelegate:(id)delegate
didFinishSelector:(SEL)finishedSEL
didFailSelector:(SEL)failedSEL {
return [self beginFetchWithDelegate:delegate
didFinishSelector:finishedSEL
didFailWithStatusSelector:kUnifiedFailureCallback
didFailWithErrorSelector:failedSEL];
}
#if NS_BLOCKS_AVAILABLE
- (BOOL)beginFetchWithCompletionHandler:(void (^)(NSData *data, NSError *error))handler {
completionBlock_ = [handler copy];
// 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
didFailWithStatusSelector:kUnifiedFailureCallback
didFailWithErrorSelector:nil];
}
#endif
// Original fetcher API
//
// Begin fetching the URL. The delegate is retained for the duration of
// the fetch connection.
//
// The delegate must provide and implement the finished and failed selectors.
//
// finishedSEL has a signature like:
// - (void)fetcher:(GDataHTTPFetcher *)fetcher finishedWithData:(NSData *)data
// statusFailedSEL has a signature like:
// - (void)fetcher:(GDataHTTPFetcher *)fetcher failedWithStatus:(NSInteger)status data:(NSData *)data
// failedSEL has a signature like:
// - (void)fetcher:(GDataHTTPFetcher *)fetcher failedWithError:(NSError *)error
- (BOOL)beginFetchWithDelegate:(id)delegate
didFinishSelector:(SEL)finishedSEL
didFailWithStatusSelector:(SEL)statusFailedSEL
didFailWithErrorSelector:(SEL)networkFailedSEL {
AssertSelectorNilOrImplementedWithArguments(delegate, finishedSEL, @encode(GDataHTTPFetcher *), @encode(NSData *), 0);
AssertSelectorNilOrImplementedWithArguments(delegate, networkFailedSEL, @encode(GDataHTTPFetcher *), @encode(NSError *), 0);
AssertSelectorNilOrImplementedWithArguments(delegate, receivedDataSEL_, @encode(GDataHTTPFetcher *), @encode(NSData *), 0);
AssertSelectorNilOrImplementedWithArguments(delegate, retrySEL_, @encode(GDataHTTPFetcher *), @encode(BOOL), @encode(NSError *), 0);
if (statusFailedSEL != kUnifiedFailureCallback) {
AssertSelectorNilOrImplementedWithArguments(delegate, statusFailedSEL, @encode(GDataHTTPFetcher *), @encode(NSInteger), @encode(NSData *), 0);
}
if (connection_ != nil) {
NSAssert1(connection_ != nil, @"fetch object %@ being reused; this should never happen", self);
goto CannotBeginFetch;
}
if (request_ == nil) {
NSAssert(request_ != nil, @"beginFetchWithDelegate requires a request");
goto CannotBeginFetch;
}
[downloadedData_ release];
downloadedData_ = nil;
[self setDelegate:delegate];
finishedSEL_ = finishedSEL;
networkFailedSEL_ = networkFailedSEL;
statusFailedSEL_ = statusFailedSEL;
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_];
}
}
if (fetchHistory_) {
// If this URL is in the history, set the Last-Modified header field
// if we have a history, we're tracking across fetches, so we don't
// want to pull results from any other cache
[request_ setCachePolicy:NSURLRequestReloadIgnoringCacheData];
if (isEffectiveHTTPGet) {
// servers don't want if-modified-since on anything but GETs
// we'll only add an If-Modified-Since header if there's no ETag
// specified, since the ETag is a more important overall criteria
NSString *etag = [request_ valueForHTTPHeaderField:@"If-None-Match"];
if (etag == nil) {
// no Etag: extract the last-modified date for this request from the
// fetch history, and add it to the request
NSString *lastModifiedStr = [fetchHistory_ cachedLastModifiedStringForRequest:request_];
if (lastModifiedStr != nil) {
[request_ addValue:lastModifiedStr forHTTPHeaderField:kGDataIfModifiedSinceHeader];
}
} else {
// has an ETag: remove any stored response in the fetch history
// for this request, as the If-None-Match header could lead to
// a 304 Not Modified, and we want that error delivered to the user
// since they explicitly specified the ETag
[fetchHistory_ removeCachedDataForRequest:request_];
}
}
}
// get cookies for this URL from our storage array, if
// we have a storage array
if (cookieStorageMethod_ != kGDataHTTPFetcherCookieStorageMethodSystemDefault
&& cookieStorageMethod_ != kGDataHTTPFetcherCookieStorageMethodNone) {
NSArray *cookies = [cookieStorage_ cookiesForURL:[request_ URL]];
if ([cookies count]) {
NSDictionary *headerFields = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
NSString *cookieHeader = [headerFields objectForKey:@"Cookie"]; // key used in header dictionary
if (cookieHeader) {
[request_ addValue:cookieHeader forHTTPHeaderField:@"Cookie"]; // header name
}
}
}
// finally, start the connection
Class connectionClass = [[self class] connectionClass];
NSArray *runLoopModes = nil;
if ([[self class] doesSupportRunLoopModes]) {
// use the connection-specific run loop modes, if they were provided,
// or else use the GDataHTTPFetcher default run loop modes, if any
if (runLoopModes_) {
runLoopModes = runLoopModes_;
} else {
runLoopModes = gGDataFetcherDefaultRunLoopModes;
}
}
if ([runLoopModes count] == 0) {
// if no run loop modes were specified, then we'll start the connection
// on the current run loop in the current mode
connection_ = [[connectionClass connectionWithRequest:request_
delegate:self] retain];
} else {
// schedule on current run loop in the specified modes
connection_ = [[connectionClass alloc] initWithRequest:request_
delegate:self
startImmediately:NO];
NSEnumerator *modeEnumerator = [runLoopModes objectEnumerator];
NSString *mode;
while ((mode = [modeEnumerator nextObject]) != nil) {
[connection_ scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:mode];
}
[connection_ start];
}
if (!connection_) {
NSAssert(connection_ != nil, @"beginFetchWithDelegate could not create a connection");
goto CannotBeginFetch;
}
// once connection_ is non-nil we can send the start notification
NSNotificationCenter *defaultNC = [NSNotificationCenter defaultCenter];
[defaultNC postNotificationName:kGDataHTTPFetcherStartedNotification
object:self];
isStopNotificationNeeded_ = YES;
// we'll retain the delegate only during the outstanding connection (similar
// to what Cocoa does with performSelectorOnMainThread:) since we'd crash
// if the delegate was released in the interim. We don't retain the selector
// at other times, to avoid vicious retain loops. This retain is balanced in
// the -stopFetch method.
[delegate_ retain];
downloadedData_ = [[NSMutableData alloc] init];
return YES;
CannotBeginFetch:
if (networkFailedSEL) {
NSError *error = [NSError errorWithDomain:kGDataHTTPFetcherErrorDomain
code:kGDataHTTPFetcherErrorDownloadFailed
userInfo:nil];
[[self retain] autorelease]; // in case the callback releases us
[delegate performSelector:networkFailedSEL
withObject:self
withObject:error];
}
return NO;
}
// Returns YES if this is in the process of fetching a URL, or waiting to
// retry
- (BOOL)isFetching {
return (connection_ != nil || retryTimer_ != nil);
}
// 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;
}
// Cancel the fetch of the URL that's currently in progress.
- (void)stopFetchReleasingBlocks:(BOOL)shouldReleaseBlocks {
// 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];
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;
// this may be called in a callback from the connection, so use autorelease
[oldConnection cancel];
[oldConnection autorelease];
// send the stopped notification
[self sendStopNotificationIfNeeded];
// balance the retain done when the connection was opened
[delegate_ release];
}
#if NS_BLOCKS_AVAILABLE
// avoid a retain loop in case the blocks are referencing
// the fetcher instance
if (shouldReleaseBlocks) {
[completionBlock_ autorelease];
completionBlock_ = nil;
[self setSentDataBlock:nil];
[self setReceivedDataBlock:nil];
[self setRetryBlock:nil];
}
#endif
}
// external stop method
- (void)stopFetching {
[self stopFetchReleasingBlocks:YES];
}
- (void)sendStopNotificationIfNeeded {
if (isStopNotificationNeeded_) {
isStopNotificationNeeded_ = NO;
NSNotificationCenter *defaultNC = [NSNotificationCenter defaultCenter];
[defaultNC postNotificationName:kGDataHTTPFetcherStoppedNotification
object:self];
}
}
- (void)retryFetch {
id holdDelegate = [[delegate_ retain] autorelease];
[self stopFetchReleasingBlocks:NO];
[self beginFetchWithDelegate:holdDelegate
didFinishSelector:finishedSEL_
didFailWithStatusSelector:statusFailedSEL_
didFailWithErrorSelector:networkFailedSEL_];
}
#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 {
if (redirectRequest && 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];
if (redirectHeaders) {
NSEnumerator *enumerator = [redirectHeaders keyEnumerator];
NSString *key;
while (nil != (key = [enumerator nextObject])) {
NSString *value = [redirectHeaders objectForKey:key];
[newRequest setValue:value forHTTPHeaderField:key];
}
}
redirectRequest = newRequest;
// save cookies from the response
[self handleCookiesForResponse:redirectResponse];
// log the response we just received
[self setResponse:redirectResponse];
[self logNowWithError:nil];
// update the request for future logging
[self setRequest:redirectRequest];
}
return redirectRequest;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// 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];
[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_ == kGDataHTTPFetcherCookieStorageMethodSystemDefault
|| cookieStorageMethod_ == kGDataHTTPFetcherCookieStorageMethodNone) {
// 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 {
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:kGDataHTTPFetcherErrorChallengeKey];
NSError *error = [NSError errorWithDomain:kGDataHTTPFetcherErrorDomain
code:kGDataHTTPFetcherErrorAuthenticationChallengeFailed
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)invokeSentDataCallback:(SEL)sel
target:(id)target
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
NSMethodSignature *sig = [target methodSignatureForSelector:sel];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
[invocation setSelector:sel];
[invocation setTarget:target];
[invocation setArgument:&self atIndex:2];
[invocation setArgument:&bytesWritten atIndex:3];
[invocation setArgument:&totalBytesWritten atIndex:4];
[invocation setArgument:&totalBytesExpectedToWrite atIndex:5];
[invocation invoke];
}
- (void)invokeStatusCallback:(SEL)sel
target:(id)target
status:(NSInteger)status
data:(NSData *)data {
NSMethodSignature *signature = [delegate_ methodSignatureForSelector:sel];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:statusFailedSEL_];
[invocation setTarget:target];
[invocation setArgument:&self atIndex:2];
[invocation setArgument:&status atIndex:3];
[invocation setArgument:&downloadedData_ atIndex:4];
[invocation invoke];
}
- (BOOL)invokeRetryCallback:(SEL)sel
target:(id)target
willRetry:(BOOL)willRetry
error:(NSError *)error {
NSMethodSignature *sig = [target methodSignatureForSelector:sel];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
[invocation setSelector:sel];
[invocation setTarget:target];
[invocation setArgument:&self atIndex:2];
[invocation setArgument:&willRetry atIndex:3];
[invocation setArgument:&error atIndex:4];
[invocation invoke];
[invocation getReturnValue:&willRetry];
return willRetry;
}
- (void)connection:(NSURLConnection *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
SEL sel = [self sentDataSelector];
if (delegate_ && sel) {
[self invokeSentDataCallback:sel
target:delegate_
didSendBodyData:bytesWritten
totalBytesWritten:totalBytesWritten
totalBytesExpectedToWrite:totalBytesExpectedToWrite];
}
#if NS_BLOCKS_AVAILABLE
if (sentDataBlock_) {
sentDataBlock_(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
#endif
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[downloadedData_ appendData:data];
if (receivedDataSEL_) {
[delegate_ performSelector:receivedDataSEL_
withObject:self
withObject:downloadedData_];
}
#if NS_BLOCKS_AVAILABLE
if (receivedDataBlock_) {
receivedDataBlock_(downloadedData_);
}
#endif
}
// for error 304's ("Not Modified") where we've cached the data, return status
// 200 ("OK") to the caller (but leave the fetcher status as 304)
// and copy the cached data to downloadedData_.
// For other errors or if there's no cached data, just return the actual status.
- (NSInteger)statusAfterHandlingNotModifiedError {
NSInteger status = [self statusCode];
if (status == kGDataHTTPFetcherStatusNotModified
&& [fetchHistory_ shouldCacheDatedData]) {
NSData *cachedData = [fetchHistory_ cachedDataForRequest:request_];
if (cachedData) {
// copy our stored data, and forge the status to pass on to the delegate
[downloadedData_ setData:cachedData];
status = 200;
}
}
return status;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[fetchHistory_ updateFetchHistoryWithRequest:request_
response:response_
downloadedData:downloadedData_];
[[self retain] autorelease]; // in case the callback releases us
[self logNowWithError:nil];
NSInteger status = [self statusAfterHandlingNotModifiedError];
// we want to send the stop notification before calling the delegate's
// callback selector, since the callback selector may release all of
// the fetcher properties that the client is using to track the fetches
//
// We'll also stop now so that, to any observers watching the notifications,
// it doesn't look like our wait for a retry (which may be long,
// 30 seconds or more) is part of the network activity
[self sendStopNotificationIfNeeded];
BOOL shouldStopFetching = YES;
// if there's an error status, retry or notify the client
if (status >= 300) {
if ([self shouldRetryNowForStatus:status error:nil]) {
// retrying
[self beginRetryTimer];
shouldStopFetching = NO;
} else if (statusFailedSEL_ == kUnifiedFailureCallback) {
// not retrying, and no separate status callback, so call the
// sole failure selector or the completion block
NSDictionary *userInfo =
[NSDictionary dictionaryWithObject:downloadedData_
forKey:kGDataHTTPFetcherStatusDataKey];
NSError *error = [NSError errorWithDomain:kGDataHTTPFetcherStatusDomain
code:status
userInfo:userInfo];
if (networkFailedSEL_) {
[delegate_ performSelector:networkFailedSEL_
withObject:self
withObject:error];
}
#if NS_BLOCKS_AVAILABLE
if (completionBlock_) {
completionBlock_(nil, error);
}
#endif
} else if (statusFailedSEL_) {
// not retrying, call status failure callback
[self invokeStatusCallback:statusFailedSEL_
target:delegate_
status:status
data:downloadedData_];
}
} else {
// successful http status (under 300)
if (finishedSEL_) {
[delegate_ performSelector:finishedSEL_
withObject:self
withObject:downloadedData_];
}
#if NS_BLOCKS_AVAILABLE
if (completionBlock_) {
completionBlock_(downloadedData_, nil);
}
#endif
}
if (shouldStopFetching) {
[self stopFetching];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// prevent the failure callback from being called twice, since the stopFetch
// call below (either the explicit one at the end of this method, or the
// implicit one when the retry occurs) will release the delegate
if (connection_ == nil) return;
// if this method was invoked indirectly by cancellation of an authentication
// challenge, defer this until it is called again with the proper error object
if (isCancellingChallenge_) return;
[self logNowWithError:error];
// see comment about sendStopNotificationIfNeeded
// in connectionDidFinishLoading:
[self sendStopNotificationIfNeeded];
if ([self shouldRetryNowForStatus:0 error:error]) {
[self beginRetryTimer];
} else {
[[self retain] autorelease]; // in case the callback releases us
if (networkFailedSEL_) {
[delegate_ performSelector:networkFailedSEL_
withObject:self
withObject:error];
}
#if NS_BLOCKS_AVAILABLE
if (completionBlock_) {
completionBlock_(nil, error);
}
#endif
[self stopFetchReleasingBlocks:YES];
}
}
- (void)logNowWithError:(NSError *)error {
// if the logging category is available, then log the current request,
// response, data, and error
if ([self respondsToSelector:@selector(logFetchWithError:)]) {
[self performSelector:@selector(logFetchWithError:) withObject:error];
}
}
#pragma mark Retries
- (BOOL)isRetryError:(NSError *)error {
struct retryRecord {
NSString *const domain;
int code;
};
// Previously we also retried for
// { NSURLErrorDomain, NSURLErrorNetworkConnectionLost }
// but at least on 10.4, once that happened, retries would keep failing
// with the same error.
struct retryRecord retries[] = {
{ kGDataHTTPFetcherStatusDomain, 408 }, // request timeout
{ kGDataHTTPFetcherStatusDomain, 503 }, // service unavailable
{ kGDataHTTPFetcherStatusDomain, 504 }, // request timeout
{ NSURLErrorDomain, NSURLErrorTimedOut },
{ nil, 0 }
};
// NSError's isEqual always returns false for equal but distinct instances