You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4670 lines
173 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. /* Copyright 2014 Google Inc. All rights reserved.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. #if !defined(__has_feature) || !__has_feature(objc_arc)
  16. #error "This file requires ARC support."
  17. #endif
  18. #import "GTMSessionFetcher.h"
  19. #if TARGET_OS_OSX && GTMSESSION_RECONNECT_BACKGROUND_SESSIONS_ON_LAUNCH
  20. // To reconnect background sessions on Mac outside +load requires importing and linking
  21. // AppKit to access the NSApplicationDidFinishLaunching symbol.
  22. #import <AppKit/AppKit.h>
  23. #endif
  24. #import <sys/utsname.h>
  25. #ifndef STRIP_GTM_FETCH_LOGGING
  26. #error GTMSessionFetcher headers should have defaulted this if it wasn't already defined.
  27. #endif
  28. GTM_ASSUME_NONNULL_BEGIN
  29. NSString *const kGTMSessionFetcherStartedNotification = @"kGTMSessionFetcherStartedNotification";
  30. NSString *const kGTMSessionFetcherStoppedNotification = @"kGTMSessionFetcherStoppedNotification";
  31. NSString *const kGTMSessionFetcherRetryDelayStartedNotification = @"kGTMSessionFetcherRetryDelayStartedNotification";
  32. NSString *const kGTMSessionFetcherRetryDelayStoppedNotification = @"kGTMSessionFetcherRetryDelayStoppedNotification";
  33. NSString *const kGTMSessionFetcherCompletionInvokedNotification = @"kGTMSessionFetcherCompletionInvokedNotification";
  34. NSString *const kGTMSessionFetcherCompletionDataKey = @"data";
  35. NSString *const kGTMSessionFetcherCompletionErrorKey = @"error";
  36. NSString *const kGTMSessionFetcherErrorDomain = @"com.google.GTMSessionFetcher";
  37. NSString *const kGTMSessionFetcherStatusDomain = @"com.google.HTTPStatus";
  38. NSString *const kGTMSessionFetcherStatusDataKey = @"data"; // data returned with a kGTMSessionFetcherStatusDomain error
  39. NSString *const kGTMSessionFetcherStatusDataContentTypeKey = @"data_content_type";
  40. NSString *const kGTMSessionFetcherNumberOfRetriesDoneKey = @"kGTMSessionFetcherNumberOfRetriesDoneKey";
  41. NSString *const kGTMSessionFetcherElapsedIntervalWithRetriesKey = @"kGTMSessionFetcherElapsedIntervalWithRetriesKey";
  42. static NSString *const kGTMSessionIdentifierPrefix = @"com.google.GTMSessionFetcher";
  43. static NSString *const kGTMSessionIdentifierDestinationFileURLMetadataKey = @"_destURL";
  44. static NSString *const kGTMSessionIdentifierBodyFileURLMetadataKey = @"_bodyURL";
  45. // The default max retry interview is 10 minutes for uploads (POST/PUT/PATCH),
  46. // 1 minute for downloads.
  47. static const NSTimeInterval kUnsetMaxRetryInterval = -1.0;
  48. static const NSTimeInterval kDefaultMaxDownloadRetryInterval = 60.0;
  49. static const NSTimeInterval kDefaultMaxUploadRetryInterval = 60.0 * 10.;
  50. // The maximum data length that can be loaded to the error userInfo
  51. static const int64_t kMaximumDownloadErrorDataLength = 20000;
  52. #ifdef GTMSESSION_PERSISTED_DESTINATION_KEY
  53. // Projects using unique class names should also define a unique persisted destination key.
  54. static NSString * const kGTMSessionFetcherPersistedDestinationKey =
  55. GTMSESSION_PERSISTED_DESTINATION_KEY;
  56. #else
  57. static NSString * const kGTMSessionFetcherPersistedDestinationKey =
  58. @"com.google.GTMSessionFetcher.downloads";
  59. #endif
  60. GTM_ASSUME_NONNULL_END
  61. //
  62. // GTMSessionFetcher
  63. //
  64. #if 0
  65. #define GTM_LOG_BACKGROUND_SESSION(...) GTMSESSION_LOG_DEBUG(__VA_ARGS__)
  66. #else
  67. #define GTM_LOG_BACKGROUND_SESSION(...)
  68. #endif
  69. #ifndef GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY
  70. #if (TARGET_OS_TV \
  71. || TARGET_OS_WATCH \
  72. || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_11) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11) \
  73. || (TARGET_OS_IPHONE && defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0))
  74. #define GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY 1
  75. #endif
  76. #endif
  77. #if ((defined(TARGET_OS_MACCATALYST) && TARGET_OS_MACCATALYST) || \
  78. (TARGET_OS_OSX && defined(__MAC_10_15) && __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_15) || \
  79. (TARGET_OS_IOS && defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_13_0) || \
  80. (TARGET_OS_WATCH && defined(__WATCHOS_6_0) && __WATCHOS_VERSION_MIN_REQUIRED >= __WATCHOS_6_0) || \
  81. (TARGET_OS_TV && defined(__TVOS_13_0) && __TVOS_VERSION_MIN_REQUIRED >= __TVOS_13_0))
  82. #define GTM_SDK_REQUIRES_TLSMINIMUMSUPPORTEDPROTOCOLVERSION 1
  83. #define GTM_SDK_SUPPORTS_TLSMINIMUMSUPPORTEDPROTOCOLVERSION 1
  84. #elif ((TARGET_OS_OSX && defined(__MAC_10_15) && __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_15) || \
  85. (TARGET_OS_IOS && defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0) || \
  86. (TARGET_OS_WATCH && defined(__WATCHOS_6_0) && __WATCHOS_VERSION_MAX_ALLOWED >= __WATCHOS_6_0) || \
  87. (TARGET_OS_TV && defined(__TVOS_13_0) && __TVOS_VERSION_MAX_ALLOWED >= __TVOS_13_0))
  88. #define GTM_SDK_REQUIRES_TLSMINIMUMSUPPORTEDPROTOCOLVERSION 0
  89. #define GTM_SDK_SUPPORTS_TLSMINIMUMSUPPORTEDPROTOCOLVERSION 1
  90. #else
  91. #define GTM_SDK_REQUIRES_TLSMINIMUMSUPPORTEDPROTOCOLVERSION 0
  92. #define GTM_SDK_SUPPORTS_TLSMINIMUMSUPPORTEDPROTOCOLVERSION 0
  93. #endif
  94. #if ((defined(TARGET_OS_MACCATALYST) && TARGET_OS_MACCATALYST) || \
  95. (TARGET_OS_OSX && defined(__MAC_10_15) && __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_15) || \
  96. (TARGET_OS_IOS && defined(__IPHONE_13_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_13_0) || \
  97. (TARGET_OS_WATCH && defined(__WATCHOS_6_0) && __WATCHOS_VERSION_MIN_REQUIRED >= __WATCHOS_6_0) || \
  98. (TARGET_OS_TV && defined(__TVOS_13_0) && __TVOS_VERSION_MIN_REQUIRED >= __TVOS_13_0))
  99. #define GTM_SDK_REQUIRES_SECTRUSTEVALUATEWITHERROR 1
  100. #else
  101. #define GTM_SDK_REQUIRES_SECTRUSTEVALUATEWITHERROR 0
  102. #endif
  103. @interface GTMSessionFetcher ()
  104. @property(atomic, strong, readwrite, GTM_NULLABLE) NSData *downloadedData;
  105. @property(atomic, strong, readwrite, GTM_NULLABLE) NSData *downloadResumeData;
  106. #if GTM_BACKGROUND_TASK_FETCHING
  107. // Should always be accessed within an @synchronized(self).
  108. @property(assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskIdentifier;
  109. #endif
  110. @property(atomic, readwrite, getter=isUsingBackgroundSession) BOOL usingBackgroundSession;
  111. @end
  112. #if !GTMSESSION_BUILD_COMBINED_SOURCES
  113. @interface GTMSessionFetcher (GTMSessionFetcherLoggingInternal)
  114. - (void)logFetchWithError:(NSError *)error;
  115. - (void)logNowWithError:(GTM_NULLABLE NSError *)error;
  116. - (NSInputStream *)loggedInputStreamForInputStream:(NSInputStream *)inputStream;
  117. - (GTMSessionFetcherBodyStreamProvider)loggedStreamProviderForStreamProvider:
  118. (GTMSessionFetcherBodyStreamProvider)streamProvider;
  119. @end
  120. #endif // !GTMSESSION_BUILD_COMBINED_SOURCES
  121. GTM_ASSUME_NONNULL_BEGIN
  122. static NSTimeInterval InitialMinRetryInterval(void) {
  123. return 1.0 + ((double)(arc4random_uniform(0x0FFFF)) / (double) 0x0FFFF);
  124. }
  125. static BOOL IsLocalhost(NSString * GTM_NULLABLE_TYPE host) {
  126. // We check if there's host, and then make the comparisons.
  127. if (host == nil) return NO;
  128. return ([host caseInsensitiveCompare:@"localhost"] == NSOrderedSame
  129. || [host isEqual:@"::1"]
  130. || [host isEqual:@"127.0.0.1"]);
  131. }
  132. static NSDictionary *GTM_NULLABLE_TYPE GTMErrorUserInfoForData(
  133. NSData *GTM_NULLABLE_TYPE data, NSDictionary *GTM_NULLABLE_TYPE responseHeaders) {
  134. NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
  135. if (data.length > 0) {
  136. userInfo[kGTMSessionFetcherStatusDataKey] = data;
  137. NSString *contentType = responseHeaders[@"Content-Type"];
  138. if (contentType) {
  139. userInfo[kGTMSessionFetcherStatusDataContentTypeKey] = contentType;
  140. }
  141. }
  142. return userInfo.count > 0 ? userInfo : nil;
  143. }
  144. static GTMSessionFetcherTestBlock GTM_NULLABLE_TYPE gGlobalTestBlock;
  145. @implementation GTMSessionFetcher {
  146. NSMutableURLRequest *_request; // after beginFetch, changed only in delegate callbacks
  147. BOOL _useUploadTask; // immutable after beginFetch
  148. NSURL *_bodyFileURL; // immutable after beginFetch
  149. GTMSessionFetcherBodyStreamProvider _bodyStreamProvider; // immutable after beginFetch
  150. NSURLSession *_session;
  151. BOOL _shouldInvalidateSession; // immutable after beginFetch
  152. NSURLSession *_sessionNeedingInvalidation;
  153. NSURLSessionConfiguration *_configuration;
  154. NSURLSessionTask *_sessionTask;
  155. NSString *_taskDescription;
  156. float _taskPriority;
  157. NSURLResponse *_response;
  158. NSString *_sessionIdentifier;
  159. BOOL _wasCreatedFromBackgroundSession;
  160. BOOL _didCreateSessionIdentifier;
  161. NSString *_sessionIdentifierUUID;
  162. BOOL _userRequestedBackgroundSession;
  163. BOOL _usingBackgroundSession;
  164. NSMutableData * GTM_NULLABLE_TYPE _downloadedData;
  165. NSError *_downloadFinishedError;
  166. NSData *_downloadResumeData; // immutable after construction
  167. NSData * GTM_NULLABLE_TYPE _downloadTaskErrorData; // Data for when download task fails
  168. NSURL *_destinationFileURL;
  169. int64_t _downloadedLength;
  170. NSURLCredential *_credential; // username & password
  171. NSURLCredential *_proxyCredential; // credential supplied to proxy servers
  172. BOOL _isStopNotificationNeeded; // set when start notification has been sent
  173. BOOL _isUsingTestBlock; // set when a test block was provided (remains set when the block is released)
  174. id _userData; // retained, if set by caller
  175. NSMutableDictionary *_properties; // more data retained for caller
  176. dispatch_queue_t _callbackQueue;
  177. dispatch_group_t _callbackGroup; // read-only after creation
  178. NSOperationQueue *_delegateQueue; // immutable after beginFetch
  179. id<GTMFetcherAuthorizationProtocol> _authorizer; // immutable after beginFetch
  180. // The service object that created and monitors this fetcher, if any.
  181. id<GTMSessionFetcherServiceProtocol> _service; // immutable; set by the fetcher service upon creation
  182. NSString *_serviceHost;
  183. NSInteger _servicePriority; // immutable after beginFetch
  184. BOOL _hasStoppedFetching; // counterpart to _initialBeginFetchDate
  185. BOOL _userStoppedFetching;
  186. BOOL _isRetryEnabled; // user wants auto-retry
  187. NSTimer *_retryTimer;
  188. NSUInteger _retryCount;
  189. NSTimeInterval _maxRetryInterval; // default 60 (download) or 600 (upload) seconds
  190. NSTimeInterval _minRetryInterval; // random between 1 and 2 seconds
  191. NSTimeInterval _retryFactor; // default interval multiplier is 2
  192. NSTimeInterval _lastRetryInterval;
  193. NSDate *_initialBeginFetchDate; // date that beginFetch was first invoked; immutable after initial beginFetch
  194. NSDate *_initialRequestDate; // date of first request to the target server (ignoring auth)
  195. BOOL _hasAttemptedAuthRefresh; // accessed only in shouldRetryNowForStatus:
  196. NSString *_comment; // comment for log
  197. NSString *_log;
  198. #if !STRIP_GTM_FETCH_LOGGING
  199. NSMutableData *_loggedStreamData;
  200. NSURL *_redirectedFromURL;
  201. NSString *_logRequestBody;
  202. NSString *_logResponseBody;
  203. BOOL _hasLoggedError;
  204. BOOL _deferResponseBodyLogging;
  205. #endif
  206. }
  207. #if !GTMSESSION_UNIT_TESTING
  208. + (void)load {
  209. #if GTMSESSION_RECONNECT_BACKGROUND_SESSIONS_ON_LAUNCH && TARGET_OS_IPHONE
  210. NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  211. [nc addObserver:self
  212. selector:@selector(reconnectFetchersForBackgroundSessionsOnAppLaunch:)
  213. name:UIApplicationDidFinishLaunchingNotification
  214. object:nil];
  215. #elif GTMSESSION_RECONNECT_BACKGROUND_SESSIONS_ON_LAUNCH && TARGET_OS_OSX
  216. NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  217. [nc addObserver:self
  218. selector:@selector(reconnectFetchersForBackgroundSessionsOnAppLaunch:)
  219. name:NSApplicationDidFinishLaunchingNotification
  220. object:nil];
  221. #else
  222. [self fetchersForBackgroundSessions];
  223. #endif
  224. }
  225. + (void)reconnectFetchersForBackgroundSessionsOnAppLaunch:(NSNotification *)notification {
  226. // Give all other app-did-launch handlers a chance to complete before
  227. // reconnecting the fetchers. Not doing this may lead to reconnecting
  228. // before the app delegate has a chance to run.
  229. dispatch_async(dispatch_get_main_queue(), ^{
  230. [self fetchersForBackgroundSessions];
  231. });
  232. }
  233. #endif // !GTMSESSION_UNIT_TESTING
  234. + (instancetype)fetcherWithRequest:(GTM_NULLABLE NSURLRequest *)request {
  235. return [[self alloc] initWithRequest:request configuration:nil];
  236. }
  237. + (instancetype)fetcherWithURL:(NSURL *)requestURL {
  238. return [self fetcherWithRequest:[NSURLRequest requestWithURL:requestURL]];
  239. }
  240. + (instancetype)fetcherWithURLString:(NSString *)requestURLString {
  241. return [self fetcherWithURL:(NSURL *)[NSURL URLWithString:requestURLString]];
  242. }
  243. + (instancetype)fetcherWithDownloadResumeData:(NSData *)resumeData {
  244. GTMSessionFetcher *fetcher = [self fetcherWithRequest:nil];
  245. fetcher.comment = @"Resuming download";
  246. fetcher.downloadResumeData = resumeData;
  247. return fetcher;
  248. }
  249. + (GTM_NULLABLE instancetype)fetcherWithSessionIdentifier:(NSString *)sessionIdentifier {
  250. GTMSESSION_ASSERT_DEBUG(sessionIdentifier != nil, @"Invalid session identifier");
  251. NSMapTable *sessionIdentifierToFetcherMap = [self sessionIdentifierToFetcherMap];
  252. GTMSessionFetcher *fetcher = [sessionIdentifierToFetcherMap objectForKey:sessionIdentifier];
  253. if (!fetcher && [sessionIdentifier hasPrefix:kGTMSessionIdentifierPrefix]) {
  254. fetcher = [self fetcherWithRequest:nil];
  255. [fetcher setSessionIdentifier:sessionIdentifier];
  256. [sessionIdentifierToFetcherMap setObject:fetcher forKey:sessionIdentifier];
  257. fetcher->_wasCreatedFromBackgroundSession = YES;
  258. [fetcher setCommentWithFormat:@"Resuming %@",
  259. fetcher && fetcher->_sessionIdentifierUUID ? fetcher->_sessionIdentifierUUID : @"?"];
  260. }
  261. return fetcher;
  262. }
  263. + (NSMapTable *)sessionIdentifierToFetcherMap {
  264. // TODO: What if a service is involved in creating the fetcher? Currently, when re-creating
  265. // fetchers, if a service was involved, it is not re-created. Should the service maintain a map?
  266. static NSMapTable *gSessionIdentifierToFetcherMap = nil;
  267. static dispatch_once_t onceToken;
  268. dispatch_once(&onceToken, ^{
  269. gSessionIdentifierToFetcherMap = [NSMapTable strongToWeakObjectsMapTable];
  270. });
  271. return gSessionIdentifierToFetcherMap;
  272. }
  273. #if !GTM_ALLOW_INSECURE_REQUESTS
  274. + (BOOL)appAllowsInsecureRequests {
  275. // If the main bundle Info.plist key NSAppTransportSecurity is present, and it specifies
  276. // NSAllowsArbitraryLoads, then we need to explicitly enforce secure schemes.
  277. #if GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY
  278. static BOOL allowsInsecureRequests;
  279. static dispatch_once_t onceToken;
  280. dispatch_once(&onceToken, ^{
  281. NSBundle *mainBundle = [NSBundle mainBundle];
  282. NSDictionary *appTransportSecurity =
  283. [mainBundle objectForInfoDictionaryKey:@"NSAppTransportSecurity"];
  284. allowsInsecureRequests =
  285. [[appTransportSecurity objectForKey:@"NSAllowsArbitraryLoads"] boolValue];
  286. });
  287. return allowsInsecureRequests;
  288. #else
  289. // For builds targeting iOS 8 or 10.10 and earlier, we want to require fetcher
  290. // security checks.
  291. return YES;
  292. #endif // GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY
  293. }
  294. #else // GTM_ALLOW_INSECURE_REQUESTS
  295. + (BOOL)appAllowsInsecureRequests {
  296. return YES;
  297. }
  298. #endif // !GTM_ALLOW_INSECURE_REQUESTS
  299. - (instancetype)init {
  300. return [self initWithRequest:nil configuration:nil];
  301. }
  302. - (instancetype)initWithRequest:(NSURLRequest *)request {
  303. return [self initWithRequest:request configuration:nil];
  304. }
  305. - (instancetype)initWithRequest:(GTM_NULLABLE NSURLRequest *)request
  306. configuration:(GTM_NULLABLE NSURLSessionConfiguration *)configuration {
  307. self = [super init];
  308. if (self) {
  309. #if GTM_BACKGROUND_TASK_FETCHING
  310. _backgroundTaskIdentifier = UIBackgroundTaskInvalid;
  311. #endif
  312. _request = [request mutableCopy];
  313. _configuration = configuration;
  314. NSData *bodyData = request.HTTPBody;
  315. if (bodyData) {
  316. _bodyLength = (int64_t)bodyData.length;
  317. } else {
  318. _bodyLength = NSURLSessionTransferSizeUnknown;
  319. }
  320. _callbackQueue = dispatch_get_main_queue();
  321. _callbackGroup = dispatch_group_create();
  322. _delegateQueue = [NSOperationQueue mainQueue];
  323. _minRetryInterval = InitialMinRetryInterval();
  324. _maxRetryInterval = kUnsetMaxRetryInterval;
  325. _taskPriority = -1.0f; // Valid values if set are 0.0...1.0.
  326. _testBlockAccumulateDataChunkCount = 1;
  327. #if !STRIP_GTM_FETCH_LOGGING
  328. // Encourage developers to set the comment property or use
  329. // setCommentWithFormat: by providing a default string.
  330. _comment = @"(No fetcher comment set)";
  331. #endif
  332. }
  333. return self;
  334. }
  335. - (id)copyWithZone:(NSZone *)zone {
  336. // disallow use of fetchers in a copy property
  337. [self doesNotRecognizeSelector:_cmd];
  338. return nil;
  339. }
  340. - (NSString *)description {
  341. NSString *requestStr = self.request.URL.description;
  342. if (requestStr.length == 0) {
  343. if (self.downloadResumeData.length > 0) {
  344. requestStr = @"<download resume data>";
  345. } else if (_wasCreatedFromBackgroundSession) {
  346. requestStr = @"<from bg session>";
  347. } else {
  348. requestStr = @"<no request>";
  349. }
  350. }
  351. return [NSString stringWithFormat:@"%@ %p (%@)", [self class], self, requestStr];
  352. }
  353. - (void)dealloc {
  354. GTMSESSION_ASSERT_DEBUG(!_isStopNotificationNeeded,
  355. @"unbalanced fetcher notification for %@", _request.URL);
  356. [self forgetSessionIdentifierForFetcherWithoutSyncCheck];
  357. // Note: if a session task or a retry timer was pending, then this instance
  358. // would be retained by those so it wouldn't be getting dealloc'd,
  359. // hence we don't need to stopFetch here
  360. }
  361. #pragma mark -
  362. // Begin fetching the URL (or begin a retry fetch). The delegate is retained
  363. // for the duration of the fetch connection.
  364. - (void)beginFetchWithCompletionHandler:(GTM_NULLABLE GTMSessionFetcherCompletionHandler)handler {
  365. GTMSessionCheckNotSynchronized(self);
  366. _completionHandler = [handler copy];
  367. // The user may have called setDelegate: earlier if they want to use other
  368. // delegate-style callbacks during the fetch; otherwise, the delegate is nil,
  369. // which is fine.
  370. [self beginFetchMayDelay:YES mayAuthorize:YES];
  371. }
  372. // Begin fetching the URL for a retry fetch. The delegate and completion handler
  373. // are already provided, and do not need to be copied.
  374. - (void)beginFetchForRetry {
  375. GTMSessionCheckNotSynchronized(self);
  376. [self beginFetchMayDelay:YES mayAuthorize:YES];
  377. }
  378. - (GTMSessionFetcherCompletionHandler)completionHandlerWithTarget:(GTM_NULLABLE_TYPE id)target
  379. didFinishSelector:(GTM_NULLABLE_TYPE SEL)finishedSelector {
  380. GTMSessionFetcherAssertValidSelector(target, finishedSelector, @encode(GTMSessionFetcher *),
  381. @encode(NSData *), @encode(NSError *), 0);
  382. GTMSessionFetcherCompletionHandler completionHandler = ^(NSData *data, NSError *error) {
  383. if (target && finishedSelector) {
  384. id selfArg = self; // Placate ARC.
  385. NSMethodSignature *sig = [target methodSignatureForSelector:finishedSelector];
  386. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
  387. [invocation setSelector:(SEL)finishedSelector];
  388. [invocation setTarget:target];
  389. [invocation setArgument:&selfArg atIndex:2];
  390. [invocation setArgument:&data atIndex:3];
  391. [invocation setArgument:&error atIndex:4];
  392. [invocation invoke];
  393. }
  394. };
  395. return completionHandler;
  396. }
  397. - (void)beginFetchWithDelegate:(GTM_NULLABLE_TYPE id)target
  398. didFinishSelector:(GTM_NULLABLE_TYPE SEL)finishedSelector {
  399. GTMSessionCheckNotSynchronized(self);
  400. GTMSessionFetcherCompletionHandler handler = [self completionHandlerWithTarget:target
  401. didFinishSelector:finishedSelector];
  402. [self beginFetchWithCompletionHandler:handler];
  403. }
  404. - (void)beginFetchMayDelay:(BOOL)mayDelay
  405. mayAuthorize:(BOOL)mayAuthorize {
  406. // This is the internal entry point for re-starting fetches.
  407. GTMSessionCheckNotSynchronized(self);
  408. NSMutableURLRequest *fetchRequest = _request; // The request property is now externally immutable.
  409. NSURL *fetchRequestURL = fetchRequest.URL;
  410. NSString *priorSessionIdentifier = self.sessionIdentifier;
  411. // A utility block for creating error objects when we fail to start the fetch.
  412. NSError *(^beginFailureError)(NSInteger) = ^(NSInteger code){
  413. NSString *urlString = fetchRequestURL.absoluteString;
  414. NSDictionary *userInfo = @{
  415. NSURLErrorFailingURLStringErrorKey : (urlString ? urlString : @"(missing URL)")
  416. };
  417. return [NSError errorWithDomain:kGTMSessionFetcherErrorDomain
  418. code:code
  419. userInfo:userInfo];
  420. };
  421. // Catch delegate queue maxConcurrentOperationCount values other than 1, particularly
  422. // NSOperationQueueDefaultMaxConcurrentOperationCount (-1), to avoid the additional complexity
  423. // of simultaneous or out-of-order delegate callbacks.
  424. GTMSESSION_ASSERT_DEBUG(_delegateQueue.maxConcurrentOperationCount == 1,
  425. @"delegate queue %@ should support one concurrent operation, not %ld",
  426. _delegateQueue.name,
  427. (long)_delegateQueue.maxConcurrentOperationCount);
  428. if (!_initialBeginFetchDate) {
  429. // This ivar is set only here on the initial beginFetch so need not be synchronized.
  430. _initialBeginFetchDate = [[NSDate alloc] init];
  431. }
  432. if (self.sessionTask != nil) {
  433. // If cached fetcher returned through fetcherWithSessionIdentifier:, then it's
  434. // already begun, but don't consider this a failure, since the user need not know this.
  435. if (self.sessionIdentifier != nil) {
  436. return;
  437. }
  438. GTMSESSION_ASSERT_DEBUG(NO, @"Fetch object %@ being reused; this should never happen", self);
  439. [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorDownloadFailed)];
  440. return;
  441. }
  442. if (fetchRequestURL == nil && !_downloadResumeData && !priorSessionIdentifier) {
  443. GTMSESSION_ASSERT_DEBUG(NO, @"Beginning a fetch requires a request with a URL");
  444. [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorDownloadFailed)];
  445. return;
  446. }
  447. // We'll respect the user's request for a background session (unless this is
  448. // an upload fetcher, which does its initial request foreground.)
  449. self.usingBackgroundSession = self.useBackgroundSession && [self canFetchWithBackgroundSession];
  450. NSURL *bodyFileURL = self.bodyFileURL;
  451. if (bodyFileURL) {
  452. NSError *fileCheckError;
  453. if (![bodyFileURL checkResourceIsReachableAndReturnError:&fileCheckError]) {
  454. // This assert fires when the file being uploaded no longer exists once
  455. // the fetcher is ready to start the upload.
  456. GTMSESSION_ASSERT_DEBUG_OR_LOG(0, @"Body file is unreachable: %@\n %@",
  457. bodyFileURL.path, fileCheckError);
  458. [self failToBeginFetchWithError:fileCheckError];
  459. return;
  460. }
  461. }
  462. NSString *requestScheme = fetchRequestURL.scheme;
  463. BOOL isDataRequest = [requestScheme isEqual:@"data"];
  464. if (isDataRequest) {
  465. // NSURLSession does not support data URLs in background sessions.
  466. #if DEBUG
  467. if (priorSessionIdentifier || self.sessionIdentifier) {
  468. GTMSESSION_LOG_DEBUG(@"Converting background to foreground session for %@",
  469. fetchRequest);
  470. }
  471. #endif
  472. // If priorSessionIdentifier is allowed to stay non-nil, a background session can
  473. // still be created.
  474. priorSessionIdentifier = nil;
  475. [self setSessionIdentifierInternal:nil];
  476. self.usingBackgroundSession = NO;
  477. }
  478. #if GTM_ALLOW_INSECURE_REQUESTS
  479. BOOL shouldCheckSecurity = NO;
  480. #else
  481. BOOL shouldCheckSecurity = (fetchRequestURL != nil
  482. && !isDataRequest
  483. && [[self class] appAllowsInsecureRequests]);
  484. #endif
  485. if (shouldCheckSecurity) {
  486. // Allow https only for requests, unless overridden by the client.
  487. //
  488. // Non-https requests may too easily be snooped, so we disallow them by default.
  489. //
  490. // file: and data: schemes are usually safe if they are hardcoded in the client or provided
  491. // by a trusted source, but since it's fairly rare to need them, it's safest to make clients
  492. // explicitly whitelist them.
  493. BOOL isSecure =
  494. requestScheme != nil && [requestScheme caseInsensitiveCompare:@"https"] == NSOrderedSame;
  495. if (!isSecure) {
  496. BOOL allowRequest = NO;
  497. NSString *host = fetchRequestURL.host;
  498. // Check schemes first. A file scheme request may be allowed here, or as a localhost request.
  499. for (NSString *allowedScheme in _allowedInsecureSchemes) {
  500. if (requestScheme != nil &&
  501. [requestScheme caseInsensitiveCompare:allowedScheme] == NSOrderedSame) {
  502. allowRequest = YES;
  503. break;
  504. }
  505. }
  506. if (!allowRequest) {
  507. // Check for localhost requests. Security checks only occur for non-https requests, so
  508. // this check won't happen for an https request to localhost.
  509. BOOL isLocalhostRequest = (host.length == 0 && [fetchRequestURL isFileURL]) || IsLocalhost(host);
  510. if (isLocalhostRequest) {
  511. if (self.allowLocalhostRequest) {
  512. allowRequest = YES;
  513. } else {
  514. GTMSESSION_ASSERT_DEBUG(NO, @"Fetch request for localhost but fetcher"
  515. @" allowLocalhostRequest is not set: %@", fetchRequestURL);
  516. }
  517. } else {
  518. GTMSESSION_ASSERT_DEBUG(NO, @"Insecure fetch request has a scheme (%@)"
  519. @" not found in fetcher allowedInsecureSchemes (%@): %@",
  520. requestScheme, _allowedInsecureSchemes ?: @" @[] ", fetchRequestURL);
  521. }
  522. }
  523. if (!allowRequest) {
  524. #if !DEBUG
  525. NSLog(@"Insecure fetch disallowed for %@", fetchRequestURL.description ?: @"nil request URL");
  526. #endif
  527. [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorInsecureRequest)];
  528. return;
  529. }
  530. } // !isSecure
  531. } // (requestURL != nil) && !isDataRequest
  532. if (self.cookieStorage == nil) {
  533. self.cookieStorage = [[self class] staticCookieStorage];
  534. }
  535. BOOL isRecreatingSession = (self.sessionIdentifier != nil) && (fetchRequest == nil);
  536. self.canShareSession = !isRecreatingSession && !self.usingBackgroundSession;
  537. if (!self.session && self.canShareSession) {
  538. self.session = [_service sessionForFetcherCreation];
  539. // If _session is nil, then the service's session creation semaphore will block
  540. // until this fetcher invokes fetcherDidCreateSession: below, so this *must* invoke
  541. // that method, even if the session fails to be created.
  542. }
  543. if (!self.session) {
  544. // Create a session.
  545. if (!_configuration) {
  546. if (priorSessionIdentifier || self.usingBackgroundSession) {
  547. NSString *sessionIdentifier = priorSessionIdentifier;
  548. if (!sessionIdentifier) {
  549. sessionIdentifier = [self createSessionIdentifierWithMetadata:nil];
  550. }
  551. NSMapTable *sessionIdentifierToFetcherMap = [[self class] sessionIdentifierToFetcherMap];
  552. [sessionIdentifierToFetcherMap setObject:self forKey:self.sessionIdentifier];
  553. if (@available(iOS 8.0, tvOS 9.0, watchOS 2.0, macOS 10.10, *)) {
  554. _configuration =
  555. [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionIdentifier];
  556. } else {
  557. #if ((!TARGET_OS_IPHONE && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_10) \
  558. || (TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0))
  559. // If building with support for iOS 7 or < macOS 10.10, allow using the older
  560. // -backgroundSessionConfiguration: method, otherwise leave it out to avoid deprecated
  561. // API warnings/errors.
  562. _configuration =
  563. [NSURLSessionConfiguration backgroundSessionConfiguration:sessionIdentifier];
  564. #endif
  565. }
  566. self.usingBackgroundSession = YES;
  567. self.canShareSession = NO;
  568. } else {
  569. _configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
  570. }
  571. #if !GTM_ALLOW_INSECURE_REQUESTS
  572. #if GTM_SDK_REQUIRES_TLSMINIMUMSUPPORTEDPROTOCOLVERSION
  573. _configuration.TLSMinimumSupportedProtocolVersion = tls_protocol_version_TLSv12;
  574. #elif GTM_SDK_SUPPORTS_TLSMINIMUMSUPPORTEDPROTOCOLVERSION
  575. if (@available(iOS 13, tvOS 13, watchOS 6, macOS 10.15, *)) {
  576. #if TARGET_OS_IOS
  577. // Early seeds of iOS 13 don't actually support the selector and several
  578. // months later, those seeds are still in use, so validate if the selector
  579. // is supported.
  580. if ([_configuration respondsToSelector:@selector(setTLSMinimumSupportedProtocolVersion:)]) {
  581. _configuration.TLSMinimumSupportedProtocolVersion = tls_protocol_version_TLSv12;
  582. } else {
  583. _configuration.TLSMinimumSupportedProtocol = kTLSProtocol12;
  584. }
  585. #else
  586. _configuration.TLSMinimumSupportedProtocolVersion = tls_protocol_version_TLSv12;
  587. #endif // TARGET_OS_IOS
  588. } else {
  589. _configuration.TLSMinimumSupportedProtocol = kTLSProtocol12;
  590. }
  591. #else
  592. _configuration.TLSMinimumSupportedProtocol = kTLSProtocol12;
  593. #endif // GTM_SDK_REQUIRES_TLSMINIMUMSUPPORTEDPROTOCOLVERSION
  594. #endif
  595. } // !_configuration
  596. _configuration.HTTPCookieStorage = self.cookieStorage;
  597. if (_configurationBlock) {
  598. _configurationBlock(self, _configuration);
  599. }
  600. id<NSURLSessionDelegate> delegate = [_service sessionDelegate];
  601. if (!delegate || !self.canShareSession) {
  602. delegate = self;
  603. }
  604. self.session = [NSURLSession sessionWithConfiguration:_configuration
  605. delegate:delegate
  606. delegateQueue:self.sessionDelegateQueue];
  607. GTMSESSION_ASSERT_DEBUG(self.session, @"Couldn't create session");
  608. // Tell the service about the session created by this fetcher. This also signals the
  609. // service's semaphore to allow other fetchers to request this session.
  610. [_service fetcherDidCreateSession:self];
  611. // If this assertion fires, the client probably tried to use a session identifier that was
  612. // already used. The solution is to make the client use a unique identifier (or better yet let
  613. // the session fetcher assign the identifier).
  614. GTMSESSION_ASSERT_DEBUG(self.session.delegate == delegate, @"Couldn't assign delegate.");
  615. if (self.session) {
  616. BOOL isUsingSharedDelegate = (delegate != self);
  617. if (!isUsingSharedDelegate) {
  618. _shouldInvalidateSession = YES;
  619. }
  620. }
  621. }
  622. if (isRecreatingSession) {
  623. _shouldInvalidateSession = YES;
  624. // Let's make sure there are tasks still running or if not that we get a callback from a
  625. // completed one; otherwise, we assume the tasks failed.
  626. // This is the observed behavior perhaps 25% of the time within the Simulator running 7.0.3 on
  627. // exiting the app after starting an upload and relaunching the app if we manage to relaunch
  628. // after the task has completed, but before the system relaunches us in the background.
  629. [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks,
  630. NSArray *downloadTasks) {
  631. if (dataTasks.count == 0 && uploadTasks.count == 0 && downloadTasks.count == 0) {
  632. double const kDelayInSeconds = 1.0; // We should get progress indication or completion soon
  633. dispatch_time_t checkForFeedbackDelay =
  634. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kDelayInSeconds * NSEC_PER_SEC));
  635. dispatch_after(checkForFeedbackDelay, dispatch_get_main_queue(), ^{
  636. if (!self.sessionTask && !fetchRequest) {
  637. // If our task and/or request haven't been restored, then we assume task feedback lost.
  638. [self removePersistedBackgroundSessionFromDefaults];
  639. NSError *sessionError =
  640. [NSError errorWithDomain:kGTMSessionFetcherErrorDomain
  641. code:GTMSessionFetcherErrorBackgroundFetchFailed
  642. userInfo:nil];
  643. [self failToBeginFetchWithError:sessionError];
  644. }
  645. });
  646. }
  647. }];
  648. return;
  649. }
  650. self.downloadedData = nil;
  651. self.downloadedLength = 0;
  652. if (_servicePriority == NSIntegerMin) {
  653. mayDelay = NO;
  654. }
  655. if (mayDelay && _service) {
  656. BOOL shouldFetchNow = [_service fetcherShouldBeginFetching:self];
  657. if (!shouldFetchNow) {
  658. // The fetch is deferred, but will happen later.
  659. //
  660. // If this session is held by the fetcher service, clear the session now so that we don't
  661. // assume it's still valid after the fetcher is restarted.
  662. if (self.canShareSession) {
  663. self.session = nil;
  664. }
  665. return;
  666. }
  667. }
  668. NSString *effectiveHTTPMethod = [fetchRequest valueForHTTPHeaderField:@"X-HTTP-Method-Override"];
  669. if (effectiveHTTPMethod == nil) {
  670. effectiveHTTPMethod = fetchRequest.HTTPMethod;
  671. }
  672. BOOL isEffectiveHTTPGet = (effectiveHTTPMethod == nil
  673. || [effectiveHTTPMethod isEqual:@"GET"]);
  674. BOOL needsUploadTask = (self.useUploadTask || self.bodyFileURL || self.bodyStreamProvider);
  675. if (_bodyData || self.bodyStreamProvider || fetchRequest.HTTPBodyStream) {
  676. if (isEffectiveHTTPGet) {
  677. fetchRequest.HTTPMethod = @"POST";
  678. isEffectiveHTTPGet = NO;
  679. }
  680. if (_bodyData) {
  681. if (!needsUploadTask) {
  682. fetchRequest.HTTPBody = _bodyData;
  683. }
  684. #if !STRIP_GTM_FETCH_LOGGING
  685. } else if (fetchRequest.HTTPBodyStream) {
  686. if ([self respondsToSelector:@selector(loggedInputStreamForInputStream:)]) {
  687. fetchRequest.HTTPBodyStream =
  688. [self performSelector:@selector(loggedInputStreamForInputStream:)
  689. withObject:fetchRequest.HTTPBodyStream];
  690. }
  691. #endif
  692. }
  693. }
  694. // We authorize after setting up the http method and body in the request
  695. // because OAuth 1 may need to sign the request body
  696. if (mayAuthorize && _authorizer && !isDataRequest) {
  697. BOOL isAuthorized = [_authorizer isAuthorizedRequest:fetchRequest];
  698. if (!isAuthorized) {
  699. // Authorization needed.
  700. //
  701. // If this session is held by the fetcher service, clear the session now so that we don't
  702. // assume it's still valid after authorization completes.
  703. if (self.canShareSession) {
  704. self.session = nil;
  705. }
  706. // Authorizing the request will recursively call this beginFetch:mayDelay:
  707. // or failToBeginFetchWithError:.
  708. [self authorizeRequest];
  709. return;
  710. }
  711. }
  712. // set the default upload or download retry interval, if necessary
  713. if ([self isRetryEnabled] && self.maxRetryInterval <= 0) {
  714. if (isEffectiveHTTPGet || [effectiveHTTPMethod isEqual:@"HEAD"]) {
  715. [self setMaxRetryInterval:kDefaultMaxDownloadRetryInterval];
  716. } else {
  717. [self setMaxRetryInterval:kDefaultMaxUploadRetryInterval];
  718. }
  719. }
  720. // finally, start the connection
  721. NSURLSessionTask *newSessionTask;
  722. BOOL needsDataAccumulator = NO;
  723. if (_downloadResumeData) {
  724. newSessionTask = [_session downloadTaskWithResumeData:_downloadResumeData];
  725. GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask,
  726. @"Failed downloadTaskWithResumeData for %@, resume data %lu bytes",
  727. _session, (unsigned long)_downloadResumeData.length);
  728. } else if (_destinationFileURL && !isDataRequest) {
  729. newSessionTask = [_session downloadTaskWithRequest:fetchRequest];
  730. GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, @"Failed downloadTaskWithRequest for %@, %@",
  731. _session, fetchRequest);
  732. } else if (needsUploadTask) {
  733. if (bodyFileURL) {
  734. newSessionTask = [_session uploadTaskWithRequest:fetchRequest
  735. fromFile:bodyFileURL];
  736. GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask,
  737. @"Failed uploadTaskWithRequest for %@, %@, file %@",
  738. _session, fetchRequest, bodyFileURL.path);
  739. } else if (self.bodyStreamProvider) {
  740. newSessionTask = [_session uploadTaskWithStreamedRequest:fetchRequest];
  741. GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask,
  742. @"Failed uploadTaskWithStreamedRequest for %@, %@",
  743. _session, fetchRequest);
  744. } else {
  745. GTMSESSION_ASSERT_DEBUG_OR_LOG(_bodyData != nil,
  746. @"Upload task needs body data, %@", fetchRequest);
  747. newSessionTask = [_session uploadTaskWithRequest:fetchRequest
  748. fromData:(NSData * GTM_NONNULL_TYPE)_bodyData];
  749. GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask,
  750. @"Failed uploadTaskWithRequest for %@, %@, body data %lu bytes",
  751. _session, fetchRequest, (unsigned long)_bodyData.length);
  752. }
  753. needsDataAccumulator = YES;
  754. } else {
  755. newSessionTask = [_session dataTaskWithRequest:fetchRequest];
  756. needsDataAccumulator = YES;
  757. GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, @"Failed dataTaskWithRequest for %@, %@",
  758. _session, fetchRequest);
  759. }
  760. self.sessionTask = newSessionTask;
  761. if (!newSessionTask) {
  762. // We shouldn't get here; if we're here, an earlier assertion should have fired to explain
  763. // which session task creation failed.
  764. [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorTaskCreationFailed)];
  765. return;
  766. }
  767. if (needsDataAccumulator && _accumulateDataBlock == nil) {
  768. self.downloadedData = [NSMutableData data];
  769. }
  770. if (_taskDescription) {
  771. newSessionTask.taskDescription = _taskDescription;
  772. }
  773. if (_taskPriority >= 0) {
  774. if (@available(iOS 8.0, macOS 10.10, *)) {
  775. newSessionTask.priority = _taskPriority;
  776. }
  777. }
  778. #if GTM_DISABLE_FETCHER_TEST_BLOCK
  779. GTMSESSION_ASSERT_DEBUG(_testBlock == nil && gGlobalTestBlock == nil, @"test blocks disabled");
  780. _testBlock = nil;
  781. #else
  782. if (!_testBlock) {
  783. if (gGlobalTestBlock) {
  784. // Note that the test block may pass nil for all of its response parameters,
  785. // indicating that the fetch should actually proceed. This is useful when the
  786. // global test block has been set, and the app is only testing a specific
  787. // fetcher. The block simulation code will then resume the task.
  788. _testBlock = gGlobalTestBlock;
  789. }
  790. }
  791. _isUsingTestBlock = (_testBlock != nil);
  792. #endif // GTM_DISABLE_FETCHER_TEST_BLOCK
  793. #if GTM_BACKGROUND_TASK_FETCHING
  794. id<GTMUIApplicationProtocol> app = [[self class] fetcherUIApplication];
  795. // Background tasks seem to interfere with out-of-process uploads and downloads.
  796. if (app && !self.skipBackgroundTask && !self.usingBackgroundSession) {
  797. // Tell UIApplication that we want to continue even when the app is in the
  798. // background.
  799. #if DEBUG
  800. NSString *bgTaskName = [NSString stringWithFormat:@"%@-%@",
  801. [self class], fetchRequest.URL.host];
  802. #else
  803. NSString *bgTaskName = @"GTMSessionFetcher";
  804. #endif
  805. __block UIBackgroundTaskIdentifier bgTaskID = [app beginBackgroundTaskWithName:bgTaskName
  806. expirationHandler:^{
  807. // Background task expiration callback - this block is always invoked by
  808. // UIApplication on the main thread.
  809. if (bgTaskID != UIBackgroundTaskInvalid) {
  810. @synchronized(self) {
  811. if (bgTaskID == self.backgroundTaskIdentifier) {
  812. self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
  813. }
  814. }
  815. [app endBackgroundTask:bgTaskID];
  816. }
  817. }];
  818. @synchronized(self) {
  819. self.backgroundTaskIdentifier = bgTaskID;
  820. }
  821. }
  822. #endif
  823. if (!_initialRequestDate) {
  824. _initialRequestDate = [[NSDate alloc] init];
  825. }
  826. // We don't expect to reach here even on retry or auth until a stop notification has been sent
  827. // for the previous task, but we should ensure that we don't unbalance that.
  828. GTMSESSION_ASSERT_DEBUG(!_isStopNotificationNeeded, @"Start notification without a prior stop");
  829. [self sendStopNotificationIfNeeded];
  830. [self addPersistedBackgroundSessionToDefaults];
  831. [self setStopNotificationNeeded:YES];
  832. [self postNotificationOnMainThreadWithName:kGTMSessionFetcherStartedNotification
  833. userInfo:nil
  834. requireAsync:NO];
  835. // The service needs to know our task if it is serving as NSURLSession delegate.
  836. [_service fetcherDidBeginFetching:self];
  837. if (_testBlock) {
  838. #if !GTM_DISABLE_FETCHER_TEST_BLOCK
  839. [self simulateFetchForTestBlock];
  840. #endif
  841. } else {
  842. // We resume the session task after posting the notification since the
  843. // delegate callbacks may happen immediately if the fetch is started off
  844. // the main thread or the session delegate queue is on a background thread,
  845. // and we don't want to post a start notification after a premature finish
  846. // of the session task.
  847. [newSessionTask resume];
  848. }
  849. }
  850. NSData * GTM_NULLABLE_TYPE GTMDataFromInputStream(NSInputStream *inputStream, NSError **outError) {
  851. NSMutableData *data = [NSMutableData data];
  852. [inputStream open];
  853. NSInteger numberOfBytesRead = 0;
  854. while ([inputStream hasBytesAvailable]) {
  855. uint8_t buffer[512];
  856. numberOfBytesRead = [inputStream read:buffer maxLength:sizeof(buffer)];
  857. if (numberOfBytesRead > 0) {
  858. [data appendBytes:buffer length:(NSUInteger)numberOfBytesRead];
  859. } else {
  860. break;
  861. }
  862. }
  863. [inputStream close];
  864. NSError *streamError = inputStream.streamError;
  865. if (streamError) {
  866. data = nil;
  867. }
  868. if (outError) {
  869. *outError = streamError;
  870. }
  871. return data;
  872. }
  873. #if !GTM_DISABLE_FETCHER_TEST_BLOCK
  874. - (void)simulateFetchForTestBlock {
  875. // This is invoked on the same thread as the beginFetch method was.
  876. //
  877. // Callbacks will all occur on the callback queue.
  878. _testBlock(self, ^(NSURLResponse *response, NSData *responseData, NSError *error) {
  879. // Callback from test block.
  880. if (response == nil && responseData == nil && error == nil) {
  881. // Assume the fetcher should execute rather than be tested.
  882. self->_testBlock = nil;
  883. self->_isUsingTestBlock = NO;
  884. [self->_sessionTask resume];
  885. return;
  886. }
  887. GTMSessionFetcherBodyStreamProvider bodyStreamProvider = self.bodyStreamProvider;
  888. if (bodyStreamProvider) {
  889. bodyStreamProvider(^(NSInputStream *bodyStream){
  890. // Read from the input stream into an NSData buffer. We'll drain the stream
  891. // explicitly on a background queue.
  892. [self invokeOnCallbackQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
  893. afterUserStopped:NO
  894. block:^{
  895. NSError *streamError;
  896. NSData *streamedData = GTMDataFromInputStream(bodyStream, &streamError);
  897. dispatch_async(dispatch_get_main_queue(), ^{
  898. // Continue callbacks on the main thread, since serial behavior
  899. // is more reliable for tests.
  900. [self simulateDataCallbacksForTestBlockWithBodyData:streamedData
  901. response:response
  902. responseData:responseData
  903. error:(error ?: streamError)];
  904. });
  905. }];
  906. });
  907. } else {
  908. // No input stream; use the supplied data or file URL.
  909. NSURL *bodyFileURL = self.bodyFileURL;
  910. if (bodyFileURL) {
  911. NSError *readError;
  912. self->_bodyData = [NSData dataWithContentsOfURL:bodyFileURL
  913. options:NSDataReadingMappedIfSafe
  914. error:&readError];
  915. error = readError;
  916. }
  917. // No stream provider.
  918. // In real fetches, nothing happens until the run loop spins, so apps have leeway to
  919. // set callbacks after they call beginFetch. We'll mirror that fetcher behavior by
  920. // delaying callbacks here at least to the next spin of the run loop. That keeps
  921. // immediate, synchronous setting of callback blocks after beginFetch working in tests.
  922. dispatch_async(dispatch_get_main_queue(), ^{
  923. [self simulateDataCallbacksForTestBlockWithBodyData:self->_bodyData
  924. response:response
  925. responseData:responseData
  926. error:error];
  927. });
  928. }
  929. });
  930. }
  931. - (void)simulateByteTransferReportWithDataLength:(int64_t)totalDataLength
  932. block:(GTMSessionFetcherSendProgressBlock)block {
  933. // This utility method simulates transfer progress with up to three callbacks.
  934. // It is used to call back to any of the progress blocks.
  935. int64_t sendReportSize = totalDataLength / 3 + 1;
  936. int64_t totalSent = 0;
  937. while (totalSent < totalDataLength) {
  938. int64_t bytesRemaining = totalDataLength - totalSent;
  939. sendReportSize = MIN(sendReportSize, bytesRemaining);
  940. totalSent += sendReportSize;
  941. [self invokeOnCallbackQueueUnlessStopped:^{
  942. block(sendReportSize, totalSent, totalDataLength);
  943. }];
  944. }
  945. }
  946. - (void)simulateDataCallbacksForTestBlockWithBodyData:(NSData * GTM_NULLABLE_TYPE)bodyData
  947. response:(NSURLResponse *)response
  948. responseData:(NSData *)suppliedData
  949. error:(NSError *)suppliedError {
  950. __block NSData *responseData = suppliedData;
  951. __block NSError *responseError = suppliedError;
  952. // This method does the test simulation of callbacks once the upload
  953. // and download data are known.
  954. @synchronized(self) {
  955. GTMSessionMonitorSynchronized(self);
  956. // Get copies of ivars we'll access in async invocations. This simulation assumes
  957. // they won't change during fetcher execution.
  958. NSURL *destinationFileURL = _destinationFileURL;
  959. GTMSessionFetcherWillRedirectBlock willRedirectBlock = _willRedirectBlock;
  960. GTMSessionFetcherDidReceiveResponseBlock didReceiveResponseBlock = _didReceiveResponseBlock;
  961. GTMSessionFetcherSendProgressBlock sendProgressBlock = _sendProgressBlock;
  962. GTMSessionFetcherDownloadProgressBlock downloadProgressBlock = _downloadProgressBlock;
  963. GTMSessionFetcherAccumulateDataBlock accumulateDataBlock = _accumulateDataBlock;
  964. GTMSessionFetcherReceivedProgressBlock receivedProgressBlock = _receivedProgressBlock;
  965. GTMSessionFetcherWillCacheURLResponseBlock willCacheURLResponseBlock =
  966. _willCacheURLResponseBlock;
  967. GTMSessionFetcherChallengeBlock challengeBlock = _challengeBlock;
  968. // Simulate receipt of redirection.
  969. if (willRedirectBlock) {
  970. [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES
  971. block:^{
  972. willRedirectBlock((NSHTTPURLResponse *)response, self->_request,
  973. ^(NSURLRequest *redirectRequest) {
  974. // For simulation, we'll assume the app will just continue.
  975. });
  976. }];
  977. }
  978. // If the fetcher has a challenge block, simulate a challenge.
  979. //
  980. // It might be nice to eventually let the user determine which testBlock
  981. // fetches get challenged rather than always executing the supplied
  982. // challenge block.
  983. if (challengeBlock) {
  984. [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES
  985. block:^{
  986. NSURL *requestURL = self->_request.URL;
  987. NSString *host = requestURL.host;
  988. NSURLProtectionSpace *pspace =
  989. [[NSURLProtectionSpace alloc] initWithHost:host
  990. port:requestURL.port.integerValue
  991. protocol:requestURL.scheme
  992. realm:nil
  993. authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
  994. id<NSURLAuthenticationChallengeSender> unusedSender =
  995. (id<NSURLAuthenticationChallengeSender>)[NSNull null];
  996. NSURLAuthenticationChallenge *challenge =
  997. [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:pspace
  998. proposedCredential:nil
  999. previousFailureCount:0
  1000. failureResponse:nil
  1001. error:nil
  1002. sender:unusedSender];
  1003. challengeBlock(self, challenge, ^(NSURLSessionAuthChallengeDisposition disposition,
  1004. NSURLCredential * GTM_NULLABLE_TYPE credential){
  1005. // We could change the responseData and responseError based on the disposition,
  1006. // but it's easier for apps to just supply the expected data and error
  1007. // directly to the test block. So this simulation ignores the disposition.
  1008. });
  1009. }];
  1010. }
  1011. // Simulate receipt of an initial response.
  1012. if (response && didReceiveResponseBlock) {
  1013. [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES
  1014. block:^{
  1015. didReceiveResponseBlock(response, ^(NSURLSessionResponseDisposition desiredDisposition) {
  1016. // For simulation, we'll assume the disposition is to continue.
  1017. });
  1018. }];
  1019. }
  1020. // Simulate reporting send progress.
  1021. if (sendProgressBlock) {
  1022. [self simulateByteTransferReportWithDataLength:(int64_t)bodyData.length
  1023. block:^(int64_t bytesSent,
  1024. int64_t totalBytesSent,
  1025. int64_t totalBytesExpectedToSend) {
  1026. // This is invoked on the callback queue unless stopped.
  1027. sendProgressBlock(bytesSent, totalBytesSent, totalBytesExpectedToSend);
  1028. }];
  1029. }
  1030. if (destinationFileURL) {
  1031. // Simulate download to file progress.
  1032. if (downloadProgressBlock) {
  1033. [self simulateByteTransferReportWithDataLength:(int64_t)responseData.length
  1034. block:^(int64_t bytesDownloaded,
  1035. int64_t totalBytesDownloaded,
  1036. int64_t totalBytesExpectedToDownload) {
  1037. // This is invoked on the callback queue unless stopped.
  1038. downloadProgressBlock(bytesDownloaded, totalBytesDownloaded,
  1039. totalBytesExpectedToDownload);
  1040. }];
  1041. }
  1042. NSError *writeError;
  1043. [responseData writeToURL:destinationFileURL
  1044. options:NSDataWritingAtomic
  1045. error:&writeError];
  1046. if (writeError) {
  1047. // Tell the test code that writing failed.
  1048. responseError = writeError;
  1049. }
  1050. } else {
  1051. // Simulate download to NSData progress.
  1052. if ((accumulateDataBlock || receivedProgressBlock) && responseData) {
  1053. [self simulateByteTransferWithData:responseData
  1054. block:^(NSData *data,
  1055. int64_t bytesReceived,
  1056. int64_t totalBytesReceived,
  1057. int64_t totalBytesExpectedToReceive) {
  1058. // This is invoked on the callback queue unless stopped.
  1059. if (accumulateDataBlock) {
  1060. accumulateDataBlock(data);
  1061. }
  1062. if (receivedProgressBlock) {
  1063. receivedProgressBlock(bytesReceived, totalBytesReceived);
  1064. }
  1065. }];
  1066. }
  1067. if (!accumulateDataBlock) {
  1068. _downloadedData = [responseData mutableCopy];
  1069. }
  1070. if (willCacheURLResponseBlock) {
  1071. // Simulate letting the client inspect and alter the cached response.
  1072. NSData *cachedData = responseData ?: [[NSData alloc] init]; // Always have non-nil data.
  1073. NSCachedURLResponse *cachedResponse =
  1074. [[NSCachedURLResponse alloc] initWithResponse:response
  1075. data:cachedData];
  1076. [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES
  1077. block:^{
  1078. willCacheURLResponseBlock(cachedResponse, ^(NSCachedURLResponse *responseToCache){
  1079. // The app may provide an alternative response, or nil to defeat caching.
  1080. });
  1081. }];
  1082. }
  1083. }
  1084. _response = response;
  1085. } // @synchronized(self)
  1086. NSOperationQueue *queue = self.sessionDelegateQueue;
  1087. [queue addOperationWithBlock:^{
  1088. // Rather than invoke failToBeginFetchWithError: we want to simulate completion of
  1089. // a connection that started and ended, so we'll call down to finishWithError:
  1090. NSInteger status = responseError ? responseError.code : 200;
  1091. if (status >= 200 && status <= 399) {
  1092. [self finishWithError:nil shouldRetry:NO];
  1093. } else {
  1094. [self shouldRetryNowForStatus:status
  1095. error:responseError
  1096. forceAssumeRetry:NO
  1097. response:^(BOOL shouldRetry) {
  1098. [self finishWithError:responseError shouldRetry:shouldRetry];
  1099. }];
  1100. }
  1101. }];
  1102. }
  1103. - (void)simulateByteTransferWithData:(NSData *)responseData
  1104. block:(GTMSessionFetcherSimulateByteTransferBlock)transferBlock {
  1105. // This utility method simulates transfering data to the client. It divides the data into at most
  1106. // "chunkCount" chunks and then passes each chunk along with a progress update to transferBlock.
  1107. // This function can be used with accumulateDataBlock or receivedProgressBlock.
  1108. NSUInteger chunkCount = MAX(self.testBlockAccumulateDataChunkCount, (NSUInteger) 1);
  1109. NSUInteger totalDataLength = responseData.length;
  1110. NSUInteger sendDataSize = totalDataLength / chunkCount + 1;
  1111. NSUInteger totalSent = 0;
  1112. while (totalSent < totalDataLength) {
  1113. NSUInteger bytesRemaining = totalDataLength - totalSent;
  1114. sendDataSize = MIN(sendDataSize, bytesRemaining);
  1115. NSData *chunkData = [responseData subdataWithRange:NSMakeRange(totalSent, sendDataSize)];
  1116. totalSent += sendDataSize;
  1117. [self invokeOnCallbackQueueUnlessStopped:^{
  1118. transferBlock(chunkData,
  1119. (int64_t)sendDataSize,
  1120. (int64_t)totalSent,
  1121. (int64_t)totalDataLength);
  1122. }];
  1123. }
  1124. }
  1125. #endif // !GTM_DISABLE_FETCHER_TEST_BLOCK
  1126. - (void)setSessionTask:(NSURLSessionTask *)sessionTask {
  1127. @synchronized(self) {
  1128. GTMSessionMonitorSynchronized(self);
  1129. if (_sessionTask != sessionTask) {
  1130. _sessionTask = sessionTask;
  1131. if (_sessionTask) {
  1132. // Request could be nil on restoring this fetcher from a background session.
  1133. if (!_request) {
  1134. _request = [_sessionTask.originalRequest mutableCopy];
  1135. }
  1136. }
  1137. }
  1138. } // @synchronized(self)
  1139. }
  1140. - (NSURLSessionTask * GTM_NULLABLE_TYPE)sessionTask {
  1141. @synchronized(self) {
  1142. GTMSessionMonitorSynchronized(self);
  1143. return _sessionTask;
  1144. } // @synchronized(self)
  1145. }
  1146. + (NSUserDefaults *)fetcherUserDefaults {
  1147. static NSUserDefaults *gFetcherUserDefaults = nil;
  1148. static dispatch_once_t onceToken;
  1149. dispatch_once(&onceToken, ^{
  1150. Class fetcherUserDefaultsClass = NSClassFromString(@"GTMSessionFetcherUserDefaultsFactory");
  1151. if (fetcherUserDefaultsClass) {
  1152. gFetcherUserDefaults = [fetcherUserDefaultsClass fetcherUserDefaults];
  1153. } else {
  1154. gFetcherUserDefaults = [NSUserDefaults standardUserDefaults];
  1155. }
  1156. });
  1157. return gFetcherUserDefaults;
  1158. }
  1159. - (void)addPersistedBackgroundSessionToDefaults {
  1160. NSString *sessionIdentifier = self.sessionIdentifier;
  1161. if (!sessionIdentifier) {
  1162. return;
  1163. }
  1164. NSArray *oldBackgroundSessions = [[self class] activePersistedBackgroundSessions];
  1165. if ([oldBackgroundSessions containsObject:_sessionIdentifier]) {
  1166. return;
  1167. }
  1168. NSMutableArray *newBackgroundSessions =
  1169. [NSMutableArray arrayWithArray:oldBackgroundSessions];
  1170. [newBackgroundSessions addObject:sessionIdentifier];
  1171. GTM_LOG_BACKGROUND_SESSION(@"Add to background sessions: %@", newBackgroundSessions);
  1172. NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults];
  1173. [userDefaults setObject:newBackgroundSessions
  1174. forKey:kGTMSessionFetcherPersistedDestinationKey];
  1175. [userDefaults synchronize];
  1176. }
  1177. - (void)removePersistedBackgroundSessionFromDefaults {
  1178. NSString *sessionIdentifier = self.sessionIdentifier;
  1179. if (!sessionIdentifier) return;
  1180. NSArray *oldBackgroundSessions = [[self class] activePersistedBackgroundSessions];
  1181. if (!oldBackgroundSessions) {
  1182. return;
  1183. }
  1184. NSMutableArray *newBackgroundSessions =
  1185. [NSMutableArray arrayWithArray:oldBackgroundSessions];
  1186. NSUInteger sessionIndex = [newBackgroundSessions indexOfObject:sessionIdentifier];
  1187. if (sessionIndex == NSNotFound) {
  1188. return;
  1189. }
  1190. [newBackgroundSessions removeObjectAtIndex:sessionIndex];
  1191. GTM_LOG_BACKGROUND_SESSION(@"Remove from background sessions: %@", newBackgroundSessions);
  1192. NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults];
  1193. if (newBackgroundSessions.count == 0) {
  1194. [userDefaults removeObjectForKey:kGTMSessionFetcherPersistedDestinationKey];
  1195. } else {
  1196. [userDefaults setObject:newBackgroundSessions
  1197. forKey:kGTMSessionFetcherPersistedDestinationKey];
  1198. }
  1199. [userDefaults synchronize];
  1200. }
  1201. + (GTM_NULLABLE NSArray *)activePersistedBackgroundSessions {
  1202. NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults];
  1203. NSArray *oldBackgroundSessions =
  1204. [userDefaults arrayForKey:kGTMSessionFetcherPersistedDestinationKey];
  1205. if (oldBackgroundSessions.count == 0) {
  1206. return nil;
  1207. }
  1208. NSMutableArray *activeBackgroundSessions = nil;
  1209. NSMapTable *sessionIdentifierToFetcherMap = [self sessionIdentifierToFetcherMap];
  1210. for (NSString *sessionIdentifier in oldBackgroundSessions) {
  1211. GTMSessionFetcher *fetcher = [sessionIdentifierToFetcherMap objectForKey:sessionIdentifier];
  1212. if (fetcher) {
  1213. if (!activeBackgroundSessions) {
  1214. activeBackgroundSessions = [[NSMutableArray alloc] init];
  1215. }
  1216. [activeBackgroundSessions addObject:sessionIdentifier];
  1217. }
  1218. }
  1219. return activeBackgroundSessions;
  1220. }
  1221. + (NSArray *)fetchersForBackgroundSessions {
  1222. NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults];
  1223. NSArray *backgroundSessions =
  1224. [userDefaults arrayForKey:kGTMSessionFetcherPersistedDestinationKey];
  1225. NSMapTable *sessionIdentifierToFetcherMap = [self sessionIdentifierToFetcherMap];
  1226. NSMutableArray *fetchers = [NSMutableArray array];
  1227. for (NSString *sessionIdentifier in backgroundSessions) {
  1228. GTMSessionFetcher *fetcher = [sessionIdentifierToFetcherMap objectForKey:sessionIdentifier];
  1229. if (!fetcher) {
  1230. fetcher = [self fetcherWithSessionIdentifier:sessionIdentifier];
  1231. GTMSESSION_ASSERT_DEBUG(fetcher != nil,
  1232. @"Unexpected invalid session identifier: %@", sessionIdentifier);
  1233. [fetcher beginFetchWithCompletionHandler:nil];
  1234. }
  1235. GTM_LOG_BACKGROUND_SESSION(@"%@ restoring session %@ by creating fetcher %@ %p",
  1236. [self class], sessionIdentifier, fetcher, fetcher);
  1237. if (fetcher != nil) {
  1238. [fetchers addObject:fetcher];
  1239. }
  1240. }
  1241. return fetchers;
  1242. }
  1243. #if TARGET_OS_IPHONE && !TARGET_OS_WATCH
  1244. + (void)application:(UIApplication *)application
  1245. handleEventsForBackgroundURLSession:(NSString *)identifier
  1246. completionHandler:(GTMSessionFetcherSystemCompletionHandler)completionHandler {
  1247. GTMSessionFetcher *fetcher = [self fetcherWithSessionIdentifier:identifier];
  1248. if (fetcher != nil) {
  1249. fetcher.systemCompletionHandler = completionHandler;
  1250. } else {
  1251. GTM_LOG_BACKGROUND_SESSION(@"%@ did not create background session identifier: %@",
  1252. [self class], identifier);
  1253. }
  1254. }
  1255. #endif
  1256. - (NSString * GTM_NULLABLE_TYPE)sessionIdentifier {
  1257. @synchronized(self) {
  1258. GTMSessionMonitorSynchronized(self);
  1259. return _sessionIdentifier;
  1260. } // @synchronized(self)
  1261. }
  1262. - (void)setSessionIdentifier:(NSString *)sessionIdentifier {
  1263. GTMSESSION_ASSERT_DEBUG(sessionIdentifier != nil, @"Invalid session identifier");
  1264. @synchronized(self) {
  1265. GTMSessionMonitorSynchronized(self);
  1266. GTMSESSION_ASSERT_DEBUG(!_session, @"Unable to set session identifier after session created");
  1267. _sessionIdentifier = [sessionIdentifier copy];
  1268. _usingBackgroundSession = YES;
  1269. _canShareSession = NO;
  1270. [self restoreDefaultStateForSessionIdentifierMetadata];
  1271. } // @synchronized(self)
  1272. }
  1273. - (void)setSessionIdentifierInternal:(GTM_NULLABLE NSString *)sessionIdentifier {
  1274. // This internal method only does a synchronized set of the session identifier.
  1275. // It does not have side effects on the background session, shared session, or
  1276. // session identifier metadata.
  1277. @synchronized(self) {
  1278. GTMSessionMonitorSynchronized(self);
  1279. _sessionIdentifier = [sessionIdentifier copy];
  1280. } // @synchronized(self)
  1281. }
  1282. - (NSDictionary * GTM_NULLABLE_TYPE)sessionUserInfo {
  1283. @synchronized(self) {
  1284. GTMSessionMonitorSynchronized(self);
  1285. if (_sessionUserInfo == nil) {
  1286. // We'll return the metadata dictionary with internal keys removed. This avoids the user
  1287. // re-using the userInfo dictionary later and accidentally including the internal keys.
  1288. NSMutableDictionary *metadata = [[self sessionIdentifierMetadataUnsynchronized] mutableCopy];
  1289. NSSet *keysToRemove = [metadata keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) {
  1290. return [key hasPrefix:@"_"];
  1291. }];
  1292. [metadata removeObjectsForKeys:[keysToRemove allObjects]];
  1293. if (metadata.count > 0) {
  1294. _sessionUserInfo = metadata;
  1295. }
  1296. }
  1297. return _sessionUserInfo;
  1298. } // @synchronized(self)
  1299. }
  1300. - (void)setSessionUserInfo:(NSDictionary * GTM_NULLABLE_TYPE)dictionary {
  1301. @synchronized(self) {
  1302. GTMSessionMonitorSynchronized(self);
  1303. GTMSESSION_ASSERT_DEBUG(_sessionIdentifier == nil, @"Too late to assign userInfo");
  1304. _sessionUserInfo = dictionary;
  1305. } // @synchronized(self)
  1306. }
  1307. - (GTM_NULLABLE NSDictionary *)sessionIdentifierDefaultMetadata {
  1308. GTMSessionCheckSynchronized(self);
  1309. NSMutableDictionary *defaultUserInfo = [[NSMutableDictionary alloc] init];
  1310. if (_destinationFileURL) {
  1311. defaultUserInfo[kGTMSessionIdentifierDestinationFileURLMetadataKey] =
  1312. [_destinationFileURL absoluteString];
  1313. }
  1314. if (_bodyFileURL) {
  1315. defaultUserInfo[kGTMSessionIdentifierBodyFileURLMetadataKey] = [_bodyFileURL absoluteString];
  1316. }
  1317. return (defaultUserInfo.count > 0) ? defaultUserInfo : nil;
  1318. }
  1319. - (void)restoreDefaultStateForSessionIdentifierMetadata {
  1320. GTMSessionCheckSynchronized(self);
  1321. NSDictionary *metadata = [self sessionIdentifierMetadataUnsynchronized];
  1322. NSString *destinationFileURLString = metadata[kGTMSessionIdentifierDestinationFileURLMetadataKey];
  1323. if (destinationFileURLString) {
  1324. _destinationFileURL = [NSURL URLWithString:destinationFileURLString];
  1325. GTM_LOG_BACKGROUND_SESSION(@"Restoring destination file URL: %@", _destinationFileURL);
  1326. }
  1327. NSString *bodyFileURLString = metadata[kGTMSessionIdentifierBodyFileURLMetadataKey];
  1328. if (bodyFileURLString) {
  1329. _bodyFileURL = [NSURL URLWithString:bodyFileURLString];
  1330. GTM_LOG_BACKGROUND_SESSION(@"Restoring body file URL: %@", _bodyFileURL);
  1331. }
  1332. }
  1333. - (NSDictionary * GTM_NULLABLE_TYPE)sessionIdentifierMetadata {
  1334. @synchronized(self) {
  1335. GTMSessionMonitorSynchronized(self);
  1336. return [self sessionIdentifierMetadataUnsynchronized];
  1337. }
  1338. }
  1339. - (NSDictionary * GTM_NULLABLE_TYPE)sessionIdentifierMetadataUnsynchronized {
  1340. GTMSessionCheckSynchronized(self);
  1341. // Session Identifier format: "com.google.<ClassName>_<UUID>_<Metadata in JSON format>
  1342. if (!_sessionIdentifier) {
  1343. return nil;
  1344. }
  1345. NSScanner *metadataScanner = [NSScanner scannerWithString:_sessionIdentifier];
  1346. [metadataScanner setCharactersToBeSkipped:nil];
  1347. NSString *metadataString;
  1348. NSString *uuid;
  1349. if ([metadataScanner scanUpToString:@"_" intoString:NULL] &&
  1350. [metadataScanner scanString:@"_" intoString:NULL] &&
  1351. [metadataScanner scanUpToString:@"_" intoString:&uuid] &&
  1352. [metadataScanner scanString:@"_" intoString:NULL] &&
  1353. [metadataScanner scanUpToString:@"\n" intoString:&metadataString]) {
  1354. _sessionIdentifierUUID = uuid;
  1355. NSData *metadataData = [metadataString dataUsingEncoding:NSUTF8StringEncoding];
  1356. NSError *error;
  1357. NSDictionary *metadataDict =
  1358. [NSJSONSerialization JSONObjectWithData:metadataData
  1359. options:0
  1360. error:&error];
  1361. GTM_LOG_BACKGROUND_SESSION(@"User Info from session identifier: %@ %@",
  1362. metadataDict, error ? error : @"");
  1363. return metadataDict;
  1364. }
  1365. return nil;
  1366. }
  1367. - (NSString *)createSessionIdentifierWithMetadata:(NSDictionary * GTM_NULLABLE_TYPE)metadataToInclude {
  1368. NSString *result;
  1369. @synchronized(self) {
  1370. GTMSessionMonitorSynchronized(self);
  1371. // Session Identifier format: "com.google.<ClassName>_<UUID>_<Metadata in JSON format>
  1372. GTMSESSION_ASSERT_DEBUG(!_sessionIdentifier, @"Session identifier already created");
  1373. _sessionIdentifierUUID = [[NSUUID UUID] UUIDString];
  1374. _sessionIdentifier =
  1375. [NSString stringWithFormat:@"%@_%@", kGTMSessionIdentifierPrefix, _sessionIdentifierUUID];
  1376. // Start with user-supplied keys so they cannot accidentally override the fetcher's keys.
  1377. NSMutableDictionary *metadataDict =
  1378. [NSMutableDictionary dictionaryWithDictionary:(NSDictionary * GTM_NONNULL_TYPE)_sessionUserInfo];
  1379. if (metadataToInclude) {
  1380. [metadataDict addEntriesFromDictionary:(NSDictionary *)metadataToInclude];
  1381. }
  1382. NSDictionary *defaultMetadataDict = [self sessionIdentifierDefaultMetadata];
  1383. if (defaultMetadataDict) {
  1384. [metadataDict addEntriesFromDictionary:defaultMetadataDict];
  1385. }
  1386. if (metadataDict.count > 0) {
  1387. NSData *metadataData = [NSJSONSerialization dataWithJSONObject:metadataDict
  1388. options:0
  1389. error:NULL];
  1390. GTMSESSION_ASSERT_DEBUG(metadataData != nil,
  1391. @"Session identifier user info failed to convert to JSON");
  1392. if (metadataData.length > 0) {
  1393. NSString *metadataString = [[NSString alloc] initWithData:metadataData
  1394. encoding:NSUTF8StringEncoding];
  1395. _sessionIdentifier =
  1396. [_sessionIdentifier stringByAppendingFormat:@"_%@", metadataString];
  1397. }
  1398. }
  1399. _didCreateSessionIdentifier = YES;
  1400. result = _sessionIdentifier;
  1401. } // @synchronized(self)
  1402. return result;
  1403. }
  1404. - (void)failToBeginFetchWithError:(NSError *)error {
  1405. @synchronized(self) {
  1406. GTMSessionMonitorSynchronized(self);
  1407. _hasStoppedFetching = YES;
  1408. }
  1409. if (error == nil) {
  1410. error = [NSError errorWithDomain:kGTMSessionFetcherErrorDomain
  1411. code:GTMSessionFetcherErrorDownloadFailed
  1412. userInfo:nil];
  1413. }
  1414. [self invokeFetchCallbacksOnCallbackQueueWithData:nil
  1415. error:error];
  1416. [self releaseCallbacks];
  1417. [_service fetcherDidStop:self];
  1418. self.authorizer = nil;
  1419. }
  1420. + (GTMSessionCookieStorage *)staticCookieStorage {
  1421. static GTMSessionCookieStorage *gCookieStorage = nil;
  1422. static dispatch_once_t onceToken;
  1423. dispatch_once(&onceToken, ^{
  1424. gCookieStorage = [[GTMSessionCookieStorage alloc] init];
  1425. });
  1426. return gCookieStorage;
  1427. }
  1428. #if GTM_BACKGROUND_TASK_FETCHING
  1429. - (void)endBackgroundTask {
  1430. // Whenever the connection stops or background execution expires,
  1431. // we need to tell UIApplication we're done.
  1432. UIBackgroundTaskIdentifier bgTaskID;
  1433. @synchronized(self) {
  1434. bgTaskID = self.backgroundTaskIdentifier;
  1435. if (bgTaskID != UIBackgroundTaskInvalid) {
  1436. self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
  1437. }
  1438. }
  1439. if (bgTaskID != UIBackgroundTaskInvalid) {
  1440. id<GTMUIApplicationProtocol> app = [[self class] fetcherUIApplication];
  1441. [app endBackgroundTask:bgTaskID];
  1442. }
  1443. }
  1444. #endif // GTM_BACKGROUND_TASK_FETCHING
  1445. - (void)authorizeRequest {
  1446. GTMSessionCheckNotSynchronized(self);
  1447. id authorizer = self.authorizer;
  1448. SEL asyncAuthSel = @selector(authorizeRequest:delegate:didFinishSelector:);
  1449. if ([authorizer respondsToSelector:asyncAuthSel]) {
  1450. SEL callbackSel = @selector(authorizer:request:finishedWithError:);
  1451. NSMutableURLRequest *mutableRequest = [self.request mutableCopy];
  1452. [authorizer authorizeRequest:mutableRequest
  1453. delegate:self
  1454. didFinishSelector:callbackSel];
  1455. } else {
  1456. GTMSESSION_ASSERT_DEBUG(authorizer == nil, @"invalid authorizer for fetch");
  1457. // No authorizing possible, and authorizing happens only after any delay;
  1458. // just begin fetching
  1459. [self beginFetchMayDelay:NO
  1460. mayAuthorize:NO];
  1461. }
  1462. }
  1463. - (void)authorizer:(id<GTMFetcherAuthorizationProtocol>)auth
  1464. request:(NSMutableURLRequest *)authorizedRequest
  1465. finishedWithError:(NSError *)error {
  1466. GTMSessionCheckNotSynchronized(self);
  1467. if (error != nil) {
  1468. // We can't fetch without authorization
  1469. [self failToBeginFetchWithError:error];
  1470. } else {
  1471. @synchronized(self) {
  1472. _request = authorizedRequest;
  1473. }
  1474. [self beginFetchMayDelay:NO
  1475. mayAuthorize:NO];
  1476. }
  1477. }
  1478. - (BOOL)canFetchWithBackgroundSession {
  1479. // Subclasses may override.
  1480. return YES;
  1481. }
  1482. // Returns YES if the fetcher has been started and has not yet stopped.
  1483. //
  1484. // Fetching includes waiting for authorization or for retry, waiting to be allowed by the
  1485. // service object to start the request, and actually fetching the request.
  1486. - (BOOL)isFetching {
  1487. @synchronized(self) {
  1488. GTMSessionMonitorSynchronized(self);
  1489. return [self isFetchingUnsynchronized];
  1490. }
  1491. }
  1492. - (BOOL)isFetchingUnsynchronized {
  1493. GTMSessionCheckSynchronized(self);
  1494. BOOL hasBegun = (_initialBeginFetchDate != nil);
  1495. return hasBegun && !_hasStoppedFetching;
  1496. }
  1497. - (NSURLResponse * GTM_NULLABLE_TYPE)response {
  1498. @synchronized(self) {
  1499. GTMSessionMonitorSynchronized(self);
  1500. NSURLResponse *response = [self responseUnsynchronized];
  1501. return response;
  1502. } // @synchronized(self)
  1503. }
  1504. - (NSURLResponse * GTM_NULLABLE_TYPE)responseUnsynchronized {
  1505. GTMSessionCheckSynchronized(self);
  1506. NSURLResponse *response = _sessionTask.response;
  1507. if (!response) response = _response;
  1508. return response;
  1509. }
  1510. - (NSInteger)statusCode {
  1511. @synchronized(self) {
  1512. GTMSessionMonitorSynchronized(self);
  1513. NSInteger statusCode = [self statusCodeUnsynchronized];
  1514. return statusCode;
  1515. } // @synchronized(self)
  1516. }
  1517. - (NSInteger)statusCodeUnsynchronized {
  1518. GTMSessionCheckSynchronized(self);
  1519. NSURLResponse *response = [self responseUnsynchronized];
  1520. NSInteger statusCode;
  1521. if ([response respondsToSelector:@selector(statusCode)]) {
  1522. statusCode = [(NSHTTPURLResponse *)response statusCode];
  1523. } else {
  1524. // Default to zero, in hopes of hinting "Unknown" (we can't be
  1525. // sure that things are OK enough to use 200).
  1526. statusCode = 0;
  1527. }
  1528. return statusCode;
  1529. }
  1530. - (NSDictionary * GTM_NULLABLE_TYPE)responseHeaders {
  1531. GTMSessionCheckNotSynchronized(self);
  1532. NSURLResponse *response = self.response;
  1533. if ([response respondsToSelector:@selector(allHeaderFields)]) {
  1534. NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields];
  1535. return headers;
  1536. }
  1537. return nil;
  1538. }
  1539. - (NSDictionary * GTM_NULLABLE_TYPE)responseHeadersUnsynchronized {
  1540. GTMSessionCheckSynchronized(self);
  1541. NSURLResponse *response = [self responseUnsynchronized];
  1542. if ([response respondsToSelector:@selector(allHeaderFields)]) {
  1543. NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields];
  1544. return headers;
  1545. }
  1546. return nil;
  1547. }
  1548. - (void)releaseCallbacks {
  1549. // Avoid releasing blocks in the sync section since objects dealloc'd by
  1550. // the blocks being released may call back into the fetcher or fetcher
  1551. // service.
  1552. dispatch_queue_t NS_VALID_UNTIL_END_OF_SCOPE holdCallbackQueue;
  1553. GTMSessionFetcherCompletionHandler NS_VALID_UNTIL_END_OF_SCOPE holdCompletionHandler;
  1554. @synchronized(self) {
  1555. GTMSessionMonitorSynchronized(self);
  1556. holdCallbackQueue = _callbackQueue;
  1557. holdCompletionHandler = _completionHandler;
  1558. _callbackQueue = nil;
  1559. _completionHandler = nil; // Setter overridden in upload. Setter assumed to be used externally.
  1560. }
  1561. // Set local callback pointers to nil here rather than let them release at the end of the scope
  1562. // to make any problems due to the blocks being released be a bit more obvious in a stack trace.
  1563. holdCallbackQueue = nil;
  1564. holdCompletionHandler = nil;
  1565. self.configurationBlock = nil;
  1566. self.didReceiveResponseBlock = nil;
  1567. self.challengeBlock = nil;
  1568. self.willRedirectBlock = nil;
  1569. self.sendProgressBlock = nil;
  1570. self.receivedProgressBlock = nil;
  1571. self.downloadProgressBlock = nil;
  1572. self.accumulateDataBlock = nil;
  1573. self.willCacheURLResponseBlock = nil;
  1574. self.retryBlock = nil;
  1575. self.testBlock = nil;
  1576. self.resumeDataBlock = nil;
  1577. if (@available(iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *)) {
  1578. self.metricsCollectionBlock = nil;
  1579. }
  1580. }
  1581. - (void)forgetSessionIdentifierForFetcher {
  1582. GTMSessionCheckSynchronized(self);
  1583. [self forgetSessionIdentifierForFetcherWithoutSyncCheck];
  1584. }
  1585. - (void)forgetSessionIdentifierForFetcherWithoutSyncCheck {
  1586. // This should be called inside a @synchronized block (except during dealloc.)
  1587. if (_sessionIdentifier) {
  1588. NSMapTable *sessionIdentifierToFetcherMap = [[self class] sessionIdentifierToFetcherMap];
  1589. [sessionIdentifierToFetcherMap removeObjectForKey:_sessionIdentifier];
  1590. _sessionIdentifier = nil;
  1591. _didCreateSessionIdentifier = NO;
  1592. }
  1593. }
  1594. // External stop method
  1595. - (void)stopFetching {
  1596. @synchronized(self) {
  1597. GTMSessionMonitorSynchronized(self);
  1598. // Prevent enqueued callbacks from executing.
  1599. _userStoppedFetching = YES;
  1600. } // @synchronized(self)
  1601. [self stopFetchReleasingCallbacks:YES];
  1602. }
  1603. // Cancel the fetch of the URL that's currently in progress.
  1604. //
  1605. // If shouldReleaseCallbacks is NO then the fetch will be retried so the callbacks
  1606. // need to still be retained.
  1607. - (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks {
  1608. [self removePersistedBackgroundSessionFromDefaults];
  1609. id<GTMSessionFetcherServiceProtocol> service;
  1610. NSMutableURLRequest *request;
  1611. // If the task or the retry timer is all that's retaining the fetcher,
  1612. // we want to be sure this instance survives stopping at least long enough for
  1613. // the stack to unwind.
  1614. __autoreleasing GTMSessionFetcher *holdSelf = self;
  1615. BOOL hasCanceledTask = NO;
  1616. [holdSelf destroyRetryTimer];
  1617. @synchronized(self) {
  1618. GTMSessionMonitorSynchronized(self);
  1619. _hasStoppedFetching = YES;
  1620. service = _service;
  1621. request = _request;
  1622. if (_sessionTask) {
  1623. // In case cancelling the task or session calls this recursively, we want
  1624. // to ensure that we'll only release the task and delegate once,
  1625. // so first set _sessionTask to nil
  1626. //
  1627. // This may be called in a callback from the task, so use autorelease to avoid
  1628. // releasing the task in its own callback.
  1629. __autoreleasing NSURLSessionTask *oldTask = _sessionTask;
  1630. if (!_isUsingTestBlock) {
  1631. _response = _sessionTask.response;
  1632. }
  1633. _sessionTask = nil;
  1634. if ([oldTask state] != NSURLSessionTaskStateCompleted) {
  1635. // For download tasks, when the fetch is stopped, we may provide resume data that can
  1636. // be used to create a new session.
  1637. BOOL mayResume = (_resumeDataBlock
  1638. && [oldTask respondsToSelector:@selector(cancelByProducingResumeData:)]);
  1639. if (!mayResume) {
  1640. [oldTask cancel];
  1641. // A side effect of stopping the task is that URLSession:task:didCompleteWithError:
  1642. // will be invoked asynchronously on the delegate queue.
  1643. } else {
  1644. void (^resumeBlock)(NSData *) = _resumeDataBlock;
  1645. _resumeDataBlock = nil;
  1646. // Save callbackQueue since releaseCallbacks clears it.
  1647. dispatch_queue_t callbackQueue = _callbackQueue;
  1648. dispatch_group_enter(_callbackGroup);
  1649. [(NSURLSessionDownloadTask *)oldTask cancelByProducingResumeData:^(NSData *resumeData) {
  1650. [self invokeOnCallbackQueue:callbackQueue
  1651. afterUserStopped:YES
  1652. block:^{
  1653. resumeBlock(resumeData);
  1654. dispatch_group_leave(self->_callbackGroup);
  1655. }];
  1656. }];
  1657. }
  1658. hasCanceledTask = YES;
  1659. }
  1660. }
  1661. // If the task was canceled, wait until the URLSession:task:didCompleteWithError: to call
  1662. // finishTasksAndInvalidate, since calling it immediately tends to crash, see radar 18471901.
  1663. if (_session) {
  1664. BOOL shouldInvalidate = _shouldInvalidateSession;
  1665. #if TARGET_OS_IPHONE
  1666. // Don't invalidate if we've got a systemCompletionHandler, since
  1667. // URLSessionDidFinishEventsForBackgroundURLSession: won't be called if invalidated.
  1668. shouldInvalidate = shouldInvalidate && !self.systemCompletionHandler;
  1669. #endif
  1670. if (shouldInvalidate) {
  1671. __autoreleasing NSURLSession *oldSession = _session;
  1672. _session = nil;
  1673. if (!hasCanceledTask) {
  1674. [oldSession finishTasksAndInvalidate];
  1675. } else {
  1676. _sessionNeedingInvalidation = oldSession;
  1677. }
  1678. }
  1679. }
  1680. } // @synchronized(self)
  1681. // send the stopped notification
  1682. [self sendStopNotificationIfNeeded];
  1683. [_authorizer stopAuthorizationForRequest:request];
  1684. if (shouldReleaseCallbacks) {
  1685. [self releaseCallbacks];
  1686. self.authorizer = nil;
  1687. }
  1688. [service fetcherDidStop:self];
  1689. #if GTM_BACKGROUND_TASK_FETCHING
  1690. [self endBackgroundTask];
  1691. #endif
  1692. }
  1693. - (void)setStopNotificationNeeded:(BOOL)flag {
  1694. @synchronized(self) {
  1695. GTMSessionMonitorSynchronized(self);
  1696. _isStopNotificationNeeded = flag;
  1697. } // @synchronized(self)
  1698. }
  1699. - (void)sendStopNotificationIfNeeded {
  1700. BOOL sendNow = NO;
  1701. @synchronized(self) {
  1702. GTMSessionMonitorSynchronized(self);
  1703. if (_isStopNotificationNeeded) {
  1704. _isStopNotificationNeeded = NO;
  1705. sendNow = YES;
  1706. }
  1707. } // @synchronized(self)
  1708. if (sendNow) {
  1709. [self postNotificationOnMainThreadWithName:kGTMSessionFetcherStoppedNotification
  1710. userInfo:nil
  1711. requireAsync:NO];
  1712. }
  1713. }
  1714. - (void)retryFetch {
  1715. [self stopFetchReleasingCallbacks:NO];
  1716. // A retry will need a configuration with a fresh session identifier.
  1717. @synchronized(self) {
  1718. GTMSessionMonitorSynchronized(self);
  1719. if (_sessionIdentifier && _didCreateSessionIdentifier) {
  1720. [self forgetSessionIdentifierForFetcher];
  1721. _configuration = nil;
  1722. }
  1723. if (_canShareSession) {
  1724. // Force a grab of the current session from the fetcher service in case
  1725. // the service's old one has become invalid.
  1726. _session = nil;
  1727. }
  1728. } // @synchronized(self)
  1729. [self beginFetchForRetry];
  1730. }
  1731. - (BOOL)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds {
  1732. // Uncovered in upload fetcher testing, because the chunk fetcher is being waited on, and gets
  1733. // released by the upload code. The uploader just holds onto it with an ivar, and that gets
  1734. // nilled in the chunk fetcher callback.
  1735. // Used once in while loop just to avoid unused variable compiler warning.
  1736. __autoreleasing GTMSessionFetcher *holdSelf = self;
  1737. NSDate *giveUpDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds];
  1738. BOOL shouldSpinRunLoop = ([NSThread isMainThread] &&
  1739. (!self.callbackQueue
  1740. || self.callbackQueue == dispatch_get_main_queue()));
  1741. BOOL expired = NO;
  1742. // Loop until the callbacks have been called and released, and until
  1743. // the connection is no longer pending, until there are no callback dispatches
  1744. // in flight, or until the timeout has expired.
  1745. int64_t delta = (int64_t)(100 * NSEC_PER_MSEC); // 100 ms
  1746. while (1) {
  1747. BOOL isTaskInProgress = (holdSelf->_sessionTask
  1748. && [_sessionTask state] != NSURLSessionTaskStateCompleted);
  1749. BOOL needsToCallCompletion = (_completionHandler != nil);
  1750. BOOL isCallbackInProgress = (_callbackGroup
  1751. && dispatch_group_wait(_callbackGroup, dispatch_time(DISPATCH_TIME_NOW, delta)));
  1752. if (!isTaskInProgress && !needsToCallCompletion && !isCallbackInProgress) break;
  1753. expired = ([giveUpDate timeIntervalSinceNow] < 0);
  1754. if (expired) {
  1755. GTMSESSION_LOG_DEBUG(@"GTMSessionFetcher waitForCompletionWithTimeout:%0.1f expired -- "
  1756. @"%@%@%@", timeoutInSeconds,
  1757. isTaskInProgress ? @"taskInProgress " : @"",
  1758. needsToCallCompletion ? @"needsToCallCompletion " : @"",
  1759. isCallbackInProgress ? @"isCallbackInProgress" : @"");
  1760. break;
  1761. }
  1762. // Run the current run loop 1/1000 of a second to give the networking
  1763. // code a chance to work
  1764. const NSTimeInterval kSpinInterval = 0.001;
  1765. if (shouldSpinRunLoop) {
  1766. NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:kSpinInterval];
  1767. [[NSRunLoop currentRunLoop] runUntilDate:stopDate];
  1768. } else {
  1769. [NSThread sleepForTimeInterval:kSpinInterval];
  1770. }
  1771. }
  1772. return !expired;
  1773. }
  1774. + (void)setGlobalTestBlock:(GTMSessionFetcherTestBlock GTM_NULLABLE_TYPE)block {
  1775. #if GTM_DISABLE_FETCHER_TEST_BLOCK
  1776. GTMSESSION_ASSERT_DEBUG(block == nil, @"test blocks disabled");
  1777. #endif
  1778. gGlobalTestBlock = [block copy];
  1779. }
  1780. #if GTM_BACKGROUND_TASK_FETCHING
  1781. static GTM_NULLABLE_TYPE id<GTMUIApplicationProtocol> gSubstituteUIApp;
  1782. + (void)setSubstituteUIApplication:(nullable id<GTMUIApplicationProtocol>)app {
  1783. gSubstituteUIApp = app;
  1784. }
  1785. + (nullable id<GTMUIApplicationProtocol>)substituteUIApplication {
  1786. return gSubstituteUIApp;
  1787. }
  1788. + (nullable id<GTMUIApplicationProtocol>)fetcherUIApplication {
  1789. id<GTMUIApplicationProtocol> app = gSubstituteUIApp;
  1790. if (app) return app;
  1791. // iOS App extensions should not call [UIApplication sharedApplication], even
  1792. // if UIApplication responds to it.
  1793. static Class applicationClass = nil;
  1794. static dispatch_once_t onceToken;
  1795. dispatch_once(&onceToken, ^{
  1796. BOOL isAppExtension = [[[NSBundle mainBundle] bundlePath] hasSuffix:@".appex"];
  1797. if (!isAppExtension) {
  1798. Class cls = NSClassFromString(@"UIApplication");
  1799. if (cls && [cls respondsToSelector:NSSelectorFromString(@"sharedApplication")]) {
  1800. applicationClass = cls;
  1801. }
  1802. }
  1803. });
  1804. if (applicationClass) {
  1805. app = (id<GTMUIApplicationProtocol>)[applicationClass sharedApplication];
  1806. }
  1807. return app;
  1808. }
  1809. #endif // GTM_BACKGROUND_TASK_FETCHING
  1810. #pragma mark NSURLSession Delegate Methods
  1811. // NSURLSession documentation indicates that redirectRequest can be passed to the handler
  1812. // but empirically redirectRequest lacks the HTTP body, so passing it will break POSTs.
  1813. // Instead, we construct a new request, a copy of the original, with overrides from the
  1814. // redirect.
  1815. - (void)URLSession:(NSURLSession *)session
  1816. task:(NSURLSessionTask *)task
  1817. willPerformHTTPRedirection:(NSHTTPURLResponse *)redirectResponse
  1818. newRequest:(NSURLRequest *)redirectRequest
  1819. completionHandler:(void (^)(NSURLRequest * GTM_NULLABLE_TYPE))handler {
  1820. [self setSessionTask:task];
  1821. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ willPerformHTTPRedirection:%@ newRequest:%@",
  1822. [self class], self, session, task, redirectResponse, redirectRequest);
  1823. if ([self userStoppedFetching]) {
  1824. handler(nil);
  1825. return;
  1826. }
  1827. if (redirectRequest && redirectResponse) {
  1828. // Copy the original request, including the body.
  1829. NSURLRequest *originalRequest = self.request;
  1830. NSMutableURLRequest *newRequest = [originalRequest mutableCopy];
  1831. // The new requests's URL overrides the original's URL.
  1832. [newRequest setURL:[GTMSessionFetcher redirectURLWithOriginalRequestURL:originalRequest.URL
  1833. redirectRequestURL:redirectRequest.URL]];
  1834. // Any headers in the redirect override headers in the original.
  1835. NSDictionary *redirectHeaders = redirectRequest.allHTTPHeaderFields;
  1836. for (NSString *key in redirectHeaders) {
  1837. NSString *value = [redirectHeaders objectForKey:key];
  1838. [newRequest setValue:value forHTTPHeaderField:key];
  1839. }
  1840. redirectRequest = newRequest;
  1841. // Log the response we just received
  1842. [self setResponse:redirectResponse];
  1843. [self logNowWithError:nil];
  1844. GTMSessionFetcherWillRedirectBlock willRedirectBlock = self.willRedirectBlock;
  1845. if (willRedirectBlock) {
  1846. @synchronized(self) {
  1847. GTMSessionMonitorSynchronized(self);
  1848. [self invokeOnCallbackQueueAfterUserStopped:YES
  1849. block:^{
  1850. willRedirectBlock(redirectResponse, redirectRequest, ^(NSURLRequest *clientRequest) {
  1851. // Update the request for future logging.
  1852. [self updateMutableRequest:[clientRequest mutableCopy]];
  1853. handler(clientRequest);
  1854. });
  1855. }];
  1856. } // @synchronized(self)
  1857. return;
  1858. }
  1859. // Continues here if the client did not provide a redirect block.
  1860. // Update the request for future logging.
  1861. [self updateMutableRequest:[redirectRequest mutableCopy]];
  1862. }
  1863. handler(redirectRequest);
  1864. }
  1865. - (void)URLSession:(NSURLSession *)session
  1866. dataTask:(NSURLSessionDataTask *)dataTask
  1867. didReceiveResponse:(NSURLResponse *)response
  1868. completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))handler {
  1869. [self setSessionTask:dataTask];
  1870. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ didReceiveResponse:%@",
  1871. [self class], self, session, dataTask, response);
  1872. void (^accumulateAndFinish)(NSURLSessionResponseDisposition) =
  1873. ^(NSURLSessionResponseDisposition dispositionValue) {
  1874. // This method is called when the server has determined that it
  1875. // has enough information to create the NSURLResponse
  1876. // it can be called multiple times, for example in the case of a
  1877. // redirect, so each time we reset the data.
  1878. @synchronized(self) {
  1879. GTMSessionMonitorSynchronized(self);
  1880. BOOL hadPreviousData = self->_downloadedLength > 0;
  1881. [self->_downloadedData setLength:0];
  1882. self->_downloadedLength = 0;
  1883. if (hadPreviousData && (dispositionValue != NSURLSessionResponseCancel)) {
  1884. // Tell the accumulate block to discard prior data.
  1885. GTMSessionFetcherAccumulateDataBlock accumulateBlock = self->_accumulateDataBlock;
  1886. if (accumulateBlock) {
  1887. [self invokeOnCallbackQueueUnlessStopped:^{
  1888. accumulateBlock(nil);
  1889. }];
  1890. }
  1891. }
  1892. } // @synchronized(self)
  1893. handler(dispositionValue);
  1894. };
  1895. GTMSessionFetcherDidReceiveResponseBlock receivedResponseBlock;
  1896. @synchronized(self) {
  1897. GTMSessionMonitorSynchronized(self);
  1898. receivedResponseBlock = _didReceiveResponseBlock;
  1899. if (receivedResponseBlock) {
  1900. // We will ultimately need to call back to NSURLSession's handler with the disposition value
  1901. // for this delegate method even if the user has stopped the fetcher.
  1902. [self invokeOnCallbackQueueAfterUserStopped:YES
  1903. block:^{
  1904. receivedResponseBlock(response, ^(NSURLSessionResponseDisposition desiredDisposition) {
  1905. accumulateAndFinish(desiredDisposition);
  1906. });
  1907. }];
  1908. }
  1909. } // @synchronized(self)
  1910. if (receivedResponseBlock == nil) {
  1911. accumulateAndFinish(NSURLSessionResponseAllow);
  1912. }
  1913. }
  1914. - (void)URLSession:(NSURLSession *)session
  1915. dataTask:(NSURLSessionDataTask *)dataTask
  1916. didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask {
  1917. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ didBecomeDownloadTask:%@",
  1918. [self class], self, session, dataTask, downloadTask);
  1919. [self setSessionTask:downloadTask];
  1920. }
  1921. - (void)URLSession:(NSURLSession *)session
  1922. task:(NSURLSessionTask *)task
  1923. didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
  1924. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,
  1925. NSURLCredential * GTM_NULLABLE_TYPE credential))handler {
  1926. [self setSessionTask:task];
  1927. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ didReceiveChallenge:%@",
  1928. [self class], self, session, task, challenge);
  1929. GTMSessionFetcherChallengeBlock challengeBlock = self.challengeBlock;
  1930. if (challengeBlock) {
  1931. // The fetcher user has provided custom challenge handling.
  1932. //
  1933. // We will ultimately need to call back to NSURLSession's handler with the disposition value
  1934. // for this delegate method even if the user has stopped the fetcher.
  1935. @synchronized(self) {
  1936. GTMSessionMonitorSynchronized(self);
  1937. [self invokeOnCallbackQueueAfterUserStopped:YES
  1938. block:^{
  1939. challengeBlock(self, challenge, handler);
  1940. }];
  1941. }
  1942. } else {
  1943. // No challenge block was provided by the client.
  1944. [self respondToChallenge:challenge
  1945. completionHandler:handler];
  1946. }
  1947. }
  1948. - (void)respondToChallenge:(NSURLAuthenticationChallenge *)challenge
  1949. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,
  1950. NSURLCredential * GTM_NULLABLE_TYPE credential))handler {
  1951. @synchronized(self) {
  1952. GTMSessionMonitorSynchronized(self);
  1953. NSInteger previousFailureCount = [challenge previousFailureCount];
  1954. if (previousFailureCount <= 2) {
  1955. NSURLProtectionSpace *protectionSpace = [challenge protectionSpace];
  1956. NSString *authenticationMethod = [protectionSpace authenticationMethod];
  1957. if ([authenticationMethod isEqual:NSURLAuthenticationMethodServerTrust]) {
  1958. // SSL.
  1959. //
  1960. // Background sessions seem to require an explicit check of the server trust object
  1961. // rather than default handling.
  1962. SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
  1963. if (serverTrust == NULL) {
  1964. // No server trust information is available.
  1965. handler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  1966. } else {
  1967. // Server trust information is available.
  1968. void (^callback)(SecTrustRef, BOOL) = ^(SecTrustRef trustRef, BOOL allow){
  1969. if (allow) {
  1970. NSURLCredential *trustCredential = [NSURLCredential credentialForTrust:trustRef];
  1971. handler(NSURLSessionAuthChallengeUseCredential, trustCredential);
  1972. } else {
  1973. GTMSESSION_LOG_DEBUG(@"Cancelling authentication challenge for %@", self->_request.URL);
  1974. handler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
  1975. }
  1976. };
  1977. if (_allowInvalidServerCertificates) {
  1978. callback(serverTrust, YES);
  1979. } else {
  1980. [[self class] evaluateServerTrust:serverTrust
  1981. forRequest:_request
  1982. completionHandler:callback];
  1983. }
  1984. }
  1985. return;
  1986. }
  1987. NSURLCredential *credential = _credential;
  1988. if ([[challenge protectionSpace] isProxy] && _proxyCredential != nil) {
  1989. credential = _proxyCredential;
  1990. }
  1991. if (credential) {
  1992. handler(NSURLSessionAuthChallengeUseCredential, credential);
  1993. } else {
  1994. // The credential is still nil; tell the OS to use the default handling. This is needed
  1995. // for things that can come out of the keychain (proxies, client certificates, etc.).
  1996. //
  1997. // Note: Looking up a credential with NSURLCredentialStorage's
  1998. // defaultCredentialForProtectionSpace: is *not* the same invoking the handler with
  1999. // NSURLSessionAuthChallengePerformDefaultHandling. In the case of
  2000. // NSURLAuthenticationMethodClientCertificate, you can get nil back from
  2001. // NSURLCredentialStorage, while using this code path instead works.
  2002. handler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  2003. }
  2004. } else {
  2005. // We've failed auth 3 times. The completion handler will be called with code
  2006. // NSURLErrorCancelled.
  2007. handler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
  2008. }
  2009. } // @synchronized(self)
  2010. }
  2011. // Return redirect URL based on the original request URL and redirect request URL.
  2012. //
  2013. // Method disallows any scheme changes between the original request URL and redirect request URL
  2014. // aside from "http" to "https". If a change in scheme is detected the redirect URL inherits the
  2015. // scheme from the original request URL.
  2016. + (GTM_NULLABLE NSURL *)redirectURLWithOriginalRequestURL:(GTM_NULLABLE NSURL *)originalRequestURL
  2017. redirectRequestURL:(GTM_NULLABLE NSURL *)redirectRequestURL {
  2018. // In the case of an NSURLSession redirect, neither URL should ever be nil; as a sanity check
  2019. // if either is nil return the other URL.
  2020. if (!redirectRequestURL) return originalRequestURL;
  2021. if (!originalRequestURL) return redirectRequestURL;
  2022. NSString *originalScheme = originalRequestURL.scheme;
  2023. NSString *redirectScheme = redirectRequestURL.scheme;
  2024. BOOL insecureToSecureRedirect =
  2025. (originalScheme != nil && [originalScheme caseInsensitiveCompare:@"http"] == NSOrderedSame &&
  2026. redirectScheme != nil && [redirectScheme caseInsensitiveCompare:@"https"] == NSOrderedSame);
  2027. // This can't really be nil for the inputs, but to keep the analyzer happy
  2028. // for the -caseInsensitiveCompare: call below, give it a value if it were.
  2029. if (!originalScheme) originalScheme = @"https";
  2030. // Check for changes to the scheme and disallow any changes except for http to https.
  2031. if (!insecureToSecureRedirect &&
  2032. (redirectScheme.length != originalScheme.length ||
  2033. [redirectScheme caseInsensitiveCompare:originalScheme] != NSOrderedSame)) {
  2034. NSURLComponents *components =
  2035. [NSURLComponents componentsWithURL:(NSURL * _Nonnull)redirectRequestURL
  2036. resolvingAgainstBaseURL:NO];
  2037. components.scheme = originalScheme;
  2038. return components.URL;
  2039. }
  2040. return redirectRequestURL;
  2041. }
  2042. // Validate the certificate chain.
  2043. //
  2044. // This may become a public method if it appears to be useful to users.
  2045. + (void)evaluateServerTrust:(SecTrustRef)serverTrust
  2046. forRequest:(NSURLRequest *)request
  2047. completionHandler:(void (^)(SecTrustRef trustRef, BOOL allow))handler {
  2048. // Retain the trust object to avoid a SecTrustEvaluate() crash on iOS 7.
  2049. CFRetain(serverTrust);
  2050. // Evaluate the certificate chain.
  2051. //
  2052. // The delegate queue may be the main thread. Trust evaluation could cause some
  2053. // blocking network activity, so we must evaluate async, as documented at
  2054. // https://developer.apple.com/library/ios/technotes/tn2232/
  2055. //
  2056. // We must also avoid multiple uses of the trust object, per docs:
  2057. // "It is not safe to call this function concurrently with any other function that uses
  2058. // the same trust management object, or to re-enter this function for the same trust
  2059. // management object."
  2060. //
  2061. // SecTrustEvaluateAsync both does sync execution of Evaluate and calls back on the
  2062. // queue passed to it, according to at sources in
  2063. // http://www.opensource.apple.com/source/libsecurity_keychain/libsecurity_keychain-55050.9/lib/SecTrust.cpp
  2064. // It would require a global serial queue to ensure the evaluate happens only on a
  2065. // single thread at a time, so we'll stick with using SecTrustEvaluate on a background
  2066. // thread.
  2067. dispatch_queue_t evaluateBackgroundQueue =
  2068. dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  2069. dispatch_async(evaluateBackgroundQueue, ^{
  2070. // It looks like the implementation of SecTrustEvaluate() on Mac grabs a global lock,
  2071. // so it may be redundant for us to also lock, but it's easy to synchronize here
  2072. // anyway.
  2073. BOOL shouldAllow;
  2074. #if GTM_SDK_REQUIRES_SECTRUSTEVALUATEWITHERROR
  2075. CFErrorRef errorRef = NULL;
  2076. @synchronized ([GTMSessionFetcher class]) {
  2077. GTMSessionMonitorSynchronized([GTMSessionFetcher class]);
  2078. // SecTrustEvaluateWithError handles both the "proceed" and "unspecified" cases,
  2079. // so it is not necessary to check the trust result the evaluation returns true.
  2080. shouldAllow = SecTrustEvaluateWithError(serverTrust, &errorRef);
  2081. }
  2082. if (errorRef) {
  2083. GTMSESSION_LOG_DEBUG(@"Error %d evaluating trust for %@",
  2084. (int)CFErrorGetCode(errorRef), request);
  2085. CFRelease(errorRef);
  2086. }
  2087. #else
  2088. SecTrustResultType trustEval = kSecTrustResultInvalid;
  2089. OSStatus trustError;
  2090. @synchronized([GTMSessionFetcher class]) {
  2091. GTMSessionMonitorSynchronized([GTMSessionFetcher class]);
  2092. trustError = SecTrustEvaluate(serverTrust, &trustEval);
  2093. }
  2094. if (trustError != errSecSuccess) {
  2095. GTMSESSION_LOG_DEBUG(@"Error %d evaluating trust for %@",
  2096. (int)trustError, request);
  2097. shouldAllow = NO;
  2098. } else {
  2099. // Having a trust level "unspecified" by the user is the usual result, described at
  2100. // https://developer.apple.com/library/mac/qa/qa1360
  2101. if (trustEval == kSecTrustResultUnspecified
  2102. || trustEval == kSecTrustResultProceed) {
  2103. shouldAllow = YES;
  2104. } else {
  2105. shouldAllow = NO;
  2106. GTMSESSION_LOG_DEBUG(@"Challenge SecTrustResultType %u for %@, properties: %@",
  2107. trustEval, request.URL.host,
  2108. CFBridgingRelease(SecTrustCopyProperties(serverTrust)));
  2109. }
  2110. }
  2111. #endif // GTM_SDK_REQUIRES_SECTRUSTEVALUATEWITHERROR
  2112. handler(serverTrust, shouldAllow);
  2113. CFRelease(serverTrust);
  2114. });
  2115. }
  2116. - (void)invokeOnCallbackQueueUnlessStopped:(void (^)(void))block {
  2117. [self invokeOnCallbackQueueAfterUserStopped:NO
  2118. block:block];
  2119. }
  2120. - (void)invokeOnCallbackQueueAfterUserStopped:(BOOL)afterStopped
  2121. block:(void (^)(void))block {
  2122. GTMSessionCheckSynchronized(self);
  2123. [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:afterStopped
  2124. block:block];
  2125. }
  2126. - (void)invokeOnCallbackUnsynchronizedQueueAfterUserStopped:(BOOL)afterStopped
  2127. block:(void (^)(void))block {
  2128. // testBlock simulation code may not be synchronizing when this is invoked.
  2129. [self invokeOnCallbackQueue:_callbackQueue
  2130. afterUserStopped:afterStopped
  2131. block:block];
  2132. }
  2133. - (void)invokeOnCallbackQueue:(dispatch_queue_t)callbackQueue
  2134. afterUserStopped:(BOOL)afterStopped
  2135. block:(void (^)(void))block {
  2136. if (callbackQueue) {
  2137. dispatch_group_async(_callbackGroup, callbackQueue, ^{
  2138. if (!afterStopped) {
  2139. NSDate *serviceStoppedAllDate = [self->_service stoppedAllFetchersDate];
  2140. @synchronized(self) {
  2141. GTMSessionMonitorSynchronized(self);
  2142. // Avoid a race between stopFetching and the callback.
  2143. if (self->_userStoppedFetching) {
  2144. return;
  2145. }
  2146. // Also avoid calling back if the service has stopped all fetchers
  2147. // since this one was created. The fetcher may have stopped before
  2148. // stopAllFetchers was invoked, so _userStoppedFetching wasn't set,
  2149. // but the app still won't expect the callback to fire after
  2150. // the service's stopAllFetchers was invoked.
  2151. if (serviceStoppedAllDate
  2152. && [self->_initialBeginFetchDate compare:serviceStoppedAllDate] != NSOrderedDescending) {
  2153. // stopAllFetchers was called after this fetcher began.
  2154. return;
  2155. }
  2156. } // @synchronized(self)
  2157. }
  2158. block();
  2159. });
  2160. }
  2161. }
  2162. - (void)invokeFetchCallbacksOnCallbackQueueWithData:(GTM_NULLABLE NSData *)data
  2163. error:(GTM_NULLABLE NSError *)error {
  2164. // Callbacks will be released in the method stopFetchReleasingCallbacks:
  2165. GTMSessionFetcherCompletionHandler handler;
  2166. @synchronized(self) {
  2167. GTMSessionMonitorSynchronized(self);
  2168. handler = _completionHandler;
  2169. if (handler) {
  2170. [self invokeOnCallbackQueueUnlessStopped:^{
  2171. handler(data, error);
  2172. // Post a notification, primarily to allow code to collect responses for
  2173. // testing.
  2174. //
  2175. // The observing code is not likely on the fetcher's callback
  2176. // queue, so this posts explicitly to the main queue.
  2177. NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
  2178. if (data) {
  2179. userInfo[kGTMSessionFetcherCompletionDataKey] = data;
  2180. }
  2181. if (error) {
  2182. userInfo[kGTMSessionFetcherCompletionErrorKey] = error;
  2183. }
  2184. [self postNotificationOnMainThreadWithName:kGTMSessionFetcherCompletionInvokedNotification
  2185. userInfo:userInfo
  2186. requireAsync:NO];
  2187. }];
  2188. }
  2189. } // @synchronized(self)
  2190. }
  2191. - (void)postNotificationOnMainThreadWithName:(NSString *)noteName
  2192. userInfo:(GTM_NULLABLE NSDictionary *)userInfo
  2193. requireAsync:(BOOL)requireAsync {
  2194. dispatch_block_t postBlock = ^{
  2195. [[NSNotificationCenter defaultCenter] postNotificationName:noteName
  2196. object:self
  2197. userInfo:userInfo];
  2198. };
  2199. if ([NSThread isMainThread] && !requireAsync) {
  2200. // Post synchronously for compatibility with older code using the fetcher.
  2201. // Avoid calling out to other code from inside a sync block to avoid risk
  2202. // of a deadlock or of recursive sync.
  2203. GTMSessionCheckNotSynchronized(self);
  2204. postBlock();
  2205. } else {
  2206. dispatch_async(dispatch_get_main_queue(), postBlock);
  2207. }
  2208. }
  2209. - (void)URLSession:(NSURLSession *)session
  2210. task:(NSURLSessionTask *)uploadTask
  2211. needNewBodyStream:(void (^)(NSInputStream * GTM_NULLABLE_TYPE bodyStream))completionHandler {
  2212. [self setSessionTask:uploadTask];
  2213. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ needNewBodyStream:",
  2214. [self class], self, session, uploadTask);
  2215. @synchronized(self) {
  2216. GTMSessionMonitorSynchronized(self);
  2217. GTMSessionFetcherBodyStreamProvider provider = _bodyStreamProvider;
  2218. #if !STRIP_GTM_FETCH_LOGGING
  2219. if ([self respondsToSelector:@selector(loggedStreamProviderForStreamProvider:)]) {
  2220. provider = [self performSelector:@selector(loggedStreamProviderForStreamProvider:)
  2221. withObject:provider];
  2222. }
  2223. #endif
  2224. if (provider) {
  2225. [self invokeOnCallbackQueueUnlessStopped:^{
  2226. provider(completionHandler);
  2227. }];
  2228. } else {
  2229. GTMSESSION_ASSERT_DEBUG(NO, @"NSURLSession expects a stream provider");
  2230. completionHandler(nil);
  2231. }
  2232. } // @synchronized(self)
  2233. }
  2234. - (void)URLSession:(NSURLSession *)session
  2235. task:(NSURLSessionTask *)task
  2236. didSendBodyData:(int64_t)bytesSent
  2237. totalBytesSent:(int64_t)totalBytesSent
  2238. totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
  2239. [self setSessionTask:task];
  2240. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ didSendBodyData:%lld"
  2241. @" totalBytesSent:%lld totalBytesExpectedToSend:%lld",
  2242. [self class], self, session, task, bytesSent, totalBytesSent,
  2243. totalBytesExpectedToSend);
  2244. @synchronized(self) {
  2245. GTMSessionMonitorSynchronized(self);
  2246. if (!_sendProgressBlock) {
  2247. return;
  2248. }
  2249. // We won't hold on to send progress block; it's ok to not send it if the upload finishes.
  2250. [self invokeOnCallbackQueueUnlessStopped:^{
  2251. GTMSessionFetcherSendProgressBlock progressBlock;
  2252. @synchronized(self) {
  2253. GTMSessionMonitorSynchronized(self);
  2254. progressBlock = self->_sendProgressBlock;
  2255. }
  2256. if (progressBlock) {
  2257. progressBlock(bytesSent, totalBytesSent, totalBytesExpectedToSend);
  2258. }
  2259. }];
  2260. } // @synchronized(self)
  2261. }
  2262. - (void)URLSession:(NSURLSession *)session
  2263. dataTask:(NSURLSessionDataTask *)dataTask
  2264. didReceiveData:(NSData *)data {
  2265. [self setSessionTask:dataTask];
  2266. NSUInteger bufferLength = data.length;
  2267. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ didReceiveData:%p (%llu bytes)",
  2268. [self class], self, session, dataTask, data,
  2269. (unsigned long long)bufferLength);
  2270. if (bufferLength == 0) {
  2271. // Observed on completing an out-of-process upload.
  2272. return;
  2273. }
  2274. @synchronized(self) {
  2275. GTMSessionMonitorSynchronized(self);
  2276. GTMSessionFetcherAccumulateDataBlock accumulateBlock = _accumulateDataBlock;
  2277. if (accumulateBlock) {
  2278. // Let the client accumulate the data.
  2279. _downloadedLength += bufferLength;
  2280. [self invokeOnCallbackQueueUnlessStopped:^{
  2281. accumulateBlock(data);
  2282. }];
  2283. } else if (!_userStoppedFetching) {
  2284. // Append to the mutable data buffer unless the fetch has been cancelled.
  2285. // Resumed upload tasks may not yet have a data buffer.
  2286. if (_downloadedData == nil) {
  2287. // Using NSClassFromString for iOS 6 compatibility.
  2288. GTMSESSION_ASSERT_DEBUG(
  2289. ![dataTask isKindOfClass:NSClassFromString(@"NSURLSessionDownloadTask")],
  2290. @"Resumed download tasks should not receive data bytes");
  2291. _downloadedData = [[NSMutableData alloc] init];
  2292. }
  2293. [_downloadedData appendData:data];
  2294. _downloadedLength = (int64_t)_downloadedData.length;
  2295. // We won't hold on to receivedProgressBlock here; it's ok to not send
  2296. // it if the transfer finishes.
  2297. if (_receivedProgressBlock) {
  2298. [self invokeOnCallbackQueueUnlessStopped:^{
  2299. GTMSessionFetcherReceivedProgressBlock progressBlock;
  2300. @synchronized(self) {
  2301. GTMSessionMonitorSynchronized(self);
  2302. progressBlock = self->_receivedProgressBlock;
  2303. }
  2304. if (progressBlock) {
  2305. progressBlock((int64_t)bufferLength, self->_downloadedLength);
  2306. }
  2307. }];
  2308. }
  2309. }
  2310. } // @synchronized(self)
  2311. }
  2312. - (void)URLSession:(NSURLSession *)session
  2313. dataTask:(NSURLSessionDataTask *)dataTask
  2314. willCacheResponse:(NSCachedURLResponse *)proposedResponse
  2315. completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler {
  2316. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ willCacheResponse:%@ %@",
  2317. [self class], self, session, dataTask,
  2318. proposedResponse, proposedResponse.response);
  2319. GTMSessionFetcherWillCacheURLResponseBlock callback;
  2320. @synchronized(self) {
  2321. GTMSessionMonitorSynchronized(self);
  2322. callback = _willCacheURLResponseBlock;
  2323. if (callback) {
  2324. [self invokeOnCallbackQueueAfterUserStopped:YES
  2325. block:^{
  2326. callback(proposedResponse, completionHandler);
  2327. }];
  2328. }
  2329. } // @synchronized(self)
  2330. if (!callback) {
  2331. completionHandler(proposedResponse);
  2332. }
  2333. }
  2334. - (void)URLSession:(NSURLSession *)session
  2335. downloadTask:(NSURLSessionDownloadTask *)downloadTask
  2336. didWriteData:(int64_t)bytesWritten
  2337. totalBytesWritten:(int64_t)totalBytesWritten
  2338. totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
  2339. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ downloadTask:%@ didWriteData:%lld"
  2340. @" bytesWritten:%lld totalBytesExpectedToWrite:%lld",
  2341. [self class], self, session, downloadTask, bytesWritten,
  2342. totalBytesWritten, totalBytesExpectedToWrite);
  2343. [self setSessionTask:downloadTask];
  2344. @synchronized(self) {
  2345. GTMSessionMonitorSynchronized(self);
  2346. if ((totalBytesExpectedToWrite != NSURLSessionTransferSizeUnknown) &&
  2347. (totalBytesExpectedToWrite < totalBytesWritten)) {
  2348. // Have observed cases were bytesWritten == totalBytesExpectedToWrite,
  2349. // but totalBytesWritten > totalBytesExpectedToWrite, so setting to unkown in these cases.
  2350. totalBytesExpectedToWrite = NSURLSessionTransferSizeUnknown;
  2351. }
  2352. GTMSessionFetcherDownloadProgressBlock progressBlock;
  2353. progressBlock = self->_downloadProgressBlock;
  2354. if (progressBlock) {
  2355. [self invokeOnCallbackQueueUnlessStopped:^{
  2356. progressBlock(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  2357. }];
  2358. }
  2359. } // @synchronized(self)
  2360. }
  2361. - (void)URLSession:(NSURLSession *)session
  2362. downloadTask:(NSURLSessionDownloadTask *)downloadTask
  2363. didResumeAtOffset:(int64_t)fileOffset
  2364. expectedTotalBytes:(int64_t)expectedTotalBytes {
  2365. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ downloadTask:%@ didResumeAtOffset:%lld"
  2366. @" expectedTotalBytes:%lld",
  2367. [self class], self, session, downloadTask, fileOffset,
  2368. expectedTotalBytes);
  2369. [self setSessionTask:downloadTask];
  2370. }
  2371. - (void)URLSession:(NSURLSession *)session
  2372. downloadTask:(NSURLSessionDownloadTask *)downloadTask
  2373. didFinishDownloadingToURL:(NSURL *)downloadLocationURL {
  2374. // Download may have relaunched app, so update _sessionTask.
  2375. [self setSessionTask:downloadTask];
  2376. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ downloadTask:%@ didFinishDownloadingToURL:%@",
  2377. [self class], self, session, downloadTask, downloadLocationURL);
  2378. NSNumber *fileSizeNum;
  2379. [downloadLocationURL getResourceValue:&fileSizeNum
  2380. forKey:NSURLFileSizeKey
  2381. error:NULL];
  2382. @synchronized(self) {
  2383. GTMSessionMonitorSynchronized(self);
  2384. NSURL *destinationURL = _destinationFileURL;
  2385. _downloadedLength = fileSizeNum.longLongValue;
  2386. // Overwrite any previous file at the destination URL.
  2387. NSFileManager *fileMgr = [NSFileManager defaultManager];
  2388. NSError *removeError;
  2389. if (![fileMgr removeItemAtURL:destinationURL error:&removeError]
  2390. && removeError.code != NSFileNoSuchFileError) {
  2391. GTMSESSION_LOG_DEBUG(@"Could not remove previous file at %@ due to %@",
  2392. downloadLocationURL.path, removeError);
  2393. }
  2394. NSInteger statusCode = [self statusCodeUnsynchronized];
  2395. if (statusCode < 200 || statusCode > 399) {
  2396. // In OS X 10.11, the response body is written to a file even on a server
  2397. // status error. For convenience of the fetcher client, we'll skip saving the
  2398. // downloaded body to the destination URL so that clients do not need to know
  2399. // to delete the file following fetch errors.
  2400. GTMSESSION_LOG_DEBUG(@"Abandoning download due to status %ld, file %@",
  2401. (long)statusCode, downloadLocationURL.path);
  2402. // On error code, add the contents of the temporary file to _downloadTaskErrorData
  2403. // This way fetcher clients have access to error details possibly passed by the server.
  2404. if (_downloadedLength > 0 && _downloadedLength <= kMaximumDownloadErrorDataLength) {
  2405. _downloadTaskErrorData = [NSData dataWithContentsOfURL:downloadLocationURL];
  2406. } else if (_downloadedLength > kMaximumDownloadErrorDataLength) {
  2407. GTMSESSION_LOG_DEBUG(@"Download error data for file %@ not passed to userInfo due to size "
  2408. @"%lld", downloadLocationURL.path, _downloadedLength);
  2409. }
  2410. } else {
  2411. NSError *moveError;
  2412. NSURL *destinationFolderURL = [destinationURL URLByDeletingLastPathComponent];
  2413. BOOL didMoveDownload = NO;
  2414. if ([fileMgr createDirectoryAtURL:destinationFolderURL
  2415. withIntermediateDirectories:YES
  2416. attributes:nil
  2417. error:&moveError]) {
  2418. didMoveDownload = [fileMgr moveItemAtURL:downloadLocationURL
  2419. toURL:destinationURL
  2420. error:&moveError];
  2421. }
  2422. if (!didMoveDownload) {
  2423. _downloadFinishedError = moveError;
  2424. }
  2425. GTM_LOG_BACKGROUND_SESSION(@"%@ %p Moved download from \"%@\" to \"%@\" %@",
  2426. [self class], self,
  2427. downloadLocationURL.path, destinationURL.path,
  2428. error ? error : @"");
  2429. }
  2430. } // @synchronized(self)
  2431. }
  2432. /* Sent as the last message related to a specific task. Error may be
  2433. * nil, which implies that no error occurred and this task is complete.
  2434. */
  2435. - (void)URLSession:(NSURLSession *)session
  2436. task:(NSURLSessionTask *)task
  2437. didCompleteWithError:(NSError *)error {
  2438. [self setSessionTask:task];
  2439. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ didCompleteWithError:%@",
  2440. [self class], self, session, task, error);
  2441. NSInteger status = self.statusCode;
  2442. BOOL forceAssumeRetry = NO;
  2443. BOOL succeeded = NO;
  2444. @synchronized(self) {
  2445. GTMSessionMonitorSynchronized(self);
  2446. #if !GTM_DISABLE_FETCHER_TEST_BLOCK
  2447. // The task is never resumed when a testBlock is used. When the session is destroyed,
  2448. // we should ignore the callback, since the testBlock support code itself invokes
  2449. // shouldRetryNowForStatus: and finishWithError:shouldRetry:
  2450. if (_isUsingTestBlock) return;
  2451. #endif
  2452. if (error == nil) {
  2453. error = _downloadFinishedError;
  2454. }
  2455. succeeded = (error == nil && status >= 0 && status < 300);
  2456. if (succeeded) {
  2457. // Succeeded.
  2458. _bodyLength = task.countOfBytesSent;
  2459. }
  2460. } // @synchronized(self)
  2461. if (succeeded) {
  2462. [self finishWithError:nil shouldRetry:NO];
  2463. return;
  2464. }
  2465. // For background redirects, no delegate method is called, so we cannot restore a stripped
  2466. // Authorization header, so if a 403 ("Forbidden") was generated due to a missing OAuth 2 header,
  2467. // set the current request's URL to the redirected URL, so we in effect restore the Authorization
  2468. // header.
  2469. if ((status == 403) && self.usingBackgroundSession) {
  2470. NSURL *redirectURL = self.response.URL;
  2471. NSURLRequest *request = self.request;
  2472. if (![request.URL isEqual:redirectURL]) {
  2473. NSString *authorizationHeader = [request.allHTTPHeaderFields objectForKey:@"Authorization"];
  2474. if (authorizationHeader != nil) {
  2475. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  2476. mutableRequest.URL = redirectURL;
  2477. [self updateMutableRequest:mutableRequest];
  2478. // Avoid assuming the session is still valid.
  2479. self.session = nil;
  2480. forceAssumeRetry = YES;
  2481. }
  2482. }
  2483. }
  2484. // If invalidating the session was deferred in stopFetchReleasingCallbacks: then do it now.
  2485. NSURLSession *oldSession = self.sessionNeedingInvalidation;
  2486. if (oldSession) {
  2487. [self setSessionNeedingInvalidation:NULL];
  2488. [oldSession finishTasksAndInvalidate];
  2489. }
  2490. // Failed.
  2491. [self shouldRetryNowForStatus:status
  2492. error:error
  2493. forceAssumeRetry:forceAssumeRetry
  2494. response:^(BOOL shouldRetry) {
  2495. [self finishWithError:error shouldRetry:shouldRetry];
  2496. }];
  2497. }
  2498. - (void)URLSession:(NSURLSession *)session
  2499. task:(NSURLSessionTask *)task
  2500. didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics
  2501. API_AVAILABLE(ios(10.0), macosx(10.12), tvos(10.0), watchos(3.0)) {
  2502. @synchronized(self) {
  2503. GTMSessionMonitorSynchronized(self);
  2504. GTMSessionFetcherMetricsCollectionBlock metricsCollectionBlock = _metricsCollectionBlock;
  2505. if (metricsCollectionBlock) {
  2506. [self invokeOnCallbackQueueUnlessStopped:^{
  2507. metricsCollectionBlock(metrics);
  2508. }];
  2509. }
  2510. }
  2511. }
  2512. #if TARGET_OS_IPHONE
  2513. - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
  2514. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSessionDidFinishEventsForBackgroundURLSession:%@",
  2515. [self class], self, session);
  2516. [self removePersistedBackgroundSessionFromDefaults];
  2517. GTMSessionFetcherSystemCompletionHandler handler;
  2518. @synchronized(self) {
  2519. GTMSessionMonitorSynchronized(self);
  2520. handler = self.systemCompletionHandler;
  2521. self.systemCompletionHandler = nil;
  2522. } // @synchronized(self)
  2523. if (handler) {
  2524. GTM_LOG_BACKGROUND_SESSION(@"%@ %p Calling system completionHandler", [self class], self);
  2525. handler();
  2526. @synchronized(self) {
  2527. GTMSessionMonitorSynchronized(self);
  2528. NSURLSession *oldSession = _session;
  2529. _session = nil;
  2530. if (_shouldInvalidateSession) {
  2531. [oldSession finishTasksAndInvalidate];
  2532. }
  2533. } // @synchronized(self)
  2534. }
  2535. }
  2536. #endif
  2537. - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(GTM_NULLABLE NSError *)error {
  2538. // This may happen repeatedly for retries. On authentication callbacks, the retry
  2539. // may begin before the prior session sends the didBecomeInvalid delegate message.
  2540. GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ didBecomeInvalidWithError:%@",
  2541. [self class], self, session, error);
  2542. if (session == (NSURLSession *)self.session) {
  2543. GTM_LOG_SESSION_DELEGATE(@" Unexpected retained invalid session: %@", session);
  2544. self.session = nil;
  2545. }
  2546. }
  2547. - (void)finishWithError:(GTM_NULLABLE NSError *)error shouldRetry:(BOOL)shouldRetry {
  2548. [self removePersistedBackgroundSessionFromDefaults];
  2549. BOOL shouldStopFetching = YES;
  2550. NSData *downloadedData = nil;
  2551. #if !STRIP_GTM_FETCH_LOGGING
  2552. BOOL shouldDeferLogging = NO;
  2553. #endif
  2554. BOOL shouldBeginRetryTimer = NO;
  2555. NSInteger status = [self statusCode];
  2556. NSURL *destinationURL = self.destinationFileURL;
  2557. BOOL fetchSucceeded = (error == nil && status >= 0 && status < 300);
  2558. #if !STRIP_GTM_FETCH_LOGGING
  2559. if (!fetchSucceeded) {
  2560. if (!shouldDeferLogging && !self.hasLoggedError) {
  2561. [self logNowWithError:error];
  2562. self.hasLoggedError = YES;
  2563. }
  2564. }
  2565. #endif // !STRIP_GTM_FETCH_LOGGING
  2566. @synchronized(self) {
  2567. GTMSessionMonitorSynchronized(self);
  2568. #if !STRIP_GTM_FETCH_LOGGING
  2569. shouldDeferLogging = _deferResponseBodyLogging;
  2570. #endif
  2571. if (fetchSucceeded) {
  2572. // Success
  2573. if ((_downloadedData.length > 0) && (destinationURL != nil)) {
  2574. // Overwrite any previous file at the destination URL.
  2575. NSFileManager *fileMgr = [NSFileManager defaultManager];
  2576. [fileMgr removeItemAtURL:destinationURL
  2577. error:NULL];
  2578. NSURL *destinationFolderURL = [destinationURL URLByDeletingLastPathComponent];
  2579. BOOL didMoveDownload = NO;
  2580. if ([fileMgr createDirectoryAtURL:destinationFolderURL
  2581. withIntermediateDirectories:YES
  2582. attributes:nil
  2583. error:&error]) {
  2584. didMoveDownload = [_downloadedData writeToURL:destinationURL
  2585. options:NSDataWritingAtomic
  2586. error:&error];
  2587. }
  2588. if (didMoveDownload) {
  2589. _downloadedData = nil;
  2590. } else {
  2591. _downloadFinishedError = error;
  2592. }
  2593. }
  2594. downloadedData = _downloadedData;
  2595. } else {
  2596. // Unsuccessful with error or status over 300. Retry or notify the delegate of failure
  2597. if (shouldRetry) {
  2598. // Retrying.
  2599. shouldBeginRetryTimer = YES;
  2600. shouldStopFetching = NO;
  2601. } else {
  2602. if (error == nil) {
  2603. // Create an error.
  2604. NSDictionary *userInfo = GTMErrorUserInfoForData(
  2605. _downloadedData.length > 0 ? _downloadedData : _downloadTaskErrorData,
  2606. [self responseHeadersUnsynchronized]);
  2607. error = [NSError errorWithDomain:kGTMSessionFetcherStatusDomain
  2608. code:status
  2609. userInfo:userInfo];
  2610. } else {
  2611. // If the error had resume data, and the client supplied a resume block, pass the
  2612. // data to the client.
  2613. void (^resumeBlock)(NSData *) = _resumeDataBlock;
  2614. _resumeDataBlock = nil;
  2615. if (resumeBlock) {
  2616. NSData *resumeData = [error.userInfo objectForKey:NSURLSessionDownloadTaskResumeData];
  2617. if (resumeData) {
  2618. [self invokeOnCallbackQueueAfterUserStopped:YES block:^{
  2619. resumeBlock(resumeData);
  2620. }];
  2621. }
  2622. }
  2623. }
  2624. if (_downloadedData.length > 0) {
  2625. downloadedData = _downloadedData;
  2626. }
  2627. // If the error occurred after retries, report the number and duration of the
  2628. // retries. This provides a clue to a developer looking at the error description
  2629. // that the fetcher did retry before failing with this error.
  2630. if (_retryCount > 0) {
  2631. NSMutableDictionary *userInfoWithRetries =
  2632. [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)error.userInfo];
  2633. NSTimeInterval timeSinceInitialRequest = -[_initialRequestDate timeIntervalSinceNow];
  2634. [userInfoWithRetries setObject:@(timeSinceInitialRequest)
  2635. forKey:kGTMSessionFetcherElapsedIntervalWithRetriesKey];
  2636. [userInfoWithRetries setObject:@(_retryCount)
  2637. forKey:kGTMSessionFetcherNumberOfRetriesDoneKey];
  2638. error = [NSError errorWithDomain:(NSString *)error.domain
  2639. code:error.code
  2640. userInfo:userInfoWithRetries];
  2641. }
  2642. }
  2643. }
  2644. } // @synchronized(self)
  2645. if (shouldBeginRetryTimer) {
  2646. [self beginRetryTimer];
  2647. }
  2648. // We want to send the stop notification before calling the delegate's
  2649. // callback selector, since the callback selector may release all of
  2650. // the fetcher properties that the client is using to track the fetches.
  2651. //
  2652. // We'll also stop now so that, to any observers watching the notifications,
  2653. // it doesn't look like our wait for a retry (which may be long,
  2654. // 30 seconds or more) is part of the network activity.
  2655. [self sendStopNotificationIfNeeded];
  2656. if (shouldStopFetching) {
  2657. [self invokeFetchCallbacksOnCallbackQueueWithData:downloadedData
  2658. error:error];
  2659. // The upload subclass doesn't want to release callbacks until upload chunks have completed.
  2660. BOOL shouldRelease = [self shouldReleaseCallbacksUponCompletion];
  2661. [self stopFetchReleasingCallbacks:shouldRelease];
  2662. }
  2663. #if !STRIP_GTM_FETCH_LOGGING
  2664. // _hasLoggedError is only set by this method
  2665. if (!shouldDeferLogging && !_hasLoggedError) {
  2666. [self logNowWithError:error];
  2667. }
  2668. #endif
  2669. }
  2670. - (BOOL)shouldReleaseCallbacksUponCompletion {
  2671. // A subclass can override this to keep callbacks around after the
  2672. // connection has finished successfully
  2673. return YES;
  2674. }
  2675. - (void)logNowWithError:(GTM_NULLABLE NSError *)error {
  2676. GTMSessionCheckNotSynchronized(self);
  2677. // If the logging category is available, then log the current request,
  2678. // response, data, and error
  2679. if ([self respondsToSelector:@selector(logFetchWithError:)]) {
  2680. [self performSelector:@selector(logFetchWithError:) withObject:error];
  2681. }
  2682. }
  2683. #pragma mark Retries
  2684. - (BOOL)isRetryError:(NSError *)error {
  2685. struct RetryRecord {
  2686. __unsafe_unretained NSString *const domain;
  2687. NSInteger code;
  2688. };
  2689. struct RetryRecord retries[] = {
  2690. { kGTMSessionFetcherStatusDomain, 408 }, // request timeout
  2691. { kGTMSessionFetcherStatusDomain, 502 }, // failure gatewaying to another server
  2692. { kGTMSessionFetcherStatusDomain, 503 }, // service unavailable
  2693. { kGTMSessionFetcherStatusDomain, 504 }, // request timeout
  2694. { NSURLErrorDomain, NSURLErrorTimedOut },
  2695. { NSURLErrorDomain, NSURLErrorNetworkConnectionLost },
  2696. { nil, 0 }
  2697. };
  2698. // NSError's isEqual always returns false for equal but distinct instances
  2699. // of NSError, so we have to compare the domain and code values explicitly
  2700. NSString *domain = error.domain;
  2701. NSInteger code = error.code;
  2702. for (int idx = 0; retries[idx].domain != nil; idx++) {
  2703. if (code == retries[idx].code && [domain isEqual:retries[idx].domain]) {
  2704. return YES;
  2705. }
  2706. }
  2707. return NO;
  2708. }
  2709. // shouldRetryNowForStatus:error: responds with YES if the user has enabled retries
  2710. // and the status or error is one that is suitable for retrying. "Suitable"
  2711. // means either the isRetryError:'s list contains the status or error, or the
  2712. // user's retry block is present and returns YES when called, or the
  2713. // authorizer may be able to fix.
  2714. - (void)shouldRetryNowForStatus:(NSInteger)status
  2715. error:(NSError *)error
  2716. forceAssumeRetry:(BOOL)forceAssumeRetry
  2717. response:(GTMSessionFetcherRetryResponse)response {
  2718. // Determine if a refreshed authorizer may avoid an authorization error
  2719. BOOL willRetry = NO;
  2720. // We assume _authorizer is immutable after beginFetch, and _hasAttemptedAuthRefresh is modified
  2721. // only in this method, and this method is invoked on the serial delegate queue.
  2722. //
  2723. // We want to avoid calling the authorizer from inside a sync block.
  2724. BOOL isFirstAuthError = (_authorizer != nil
  2725. && !_hasAttemptedAuthRefresh
  2726. && status == GTMSessionFetcherStatusUnauthorized); // 401
  2727. BOOL hasPrimed = NO;
  2728. if (isFirstAuthError) {
  2729. if ([_authorizer respondsToSelector:@selector(primeForRefresh)]) {
  2730. hasPrimed = [_authorizer primeForRefresh];
  2731. }
  2732. }
  2733. BOOL shouldRetryForAuthRefresh = NO;
  2734. if (hasPrimed) {
  2735. shouldRetryForAuthRefresh = YES;
  2736. _hasAttemptedAuthRefresh = YES;
  2737. [self updateRequestValue:nil forHTTPHeaderField:@"Authorization"];
  2738. }
  2739. @synchronized(self) {
  2740. GTMSessionMonitorSynchronized(self);
  2741. BOOL shouldDoRetry = [self isRetryEnabledUnsynchronized];
  2742. if (shouldDoRetry && ![self hasRetryAfterInterval]) {
  2743. // Determine if we're doing exponential backoff retries
  2744. shouldDoRetry = [self nextRetryIntervalUnsynchronized] < _maxRetryInterval;
  2745. if (shouldDoRetry) {
  2746. // If an explicit max retry interval was set, we expect repeated backoffs to take
  2747. // up to roughly twice that for repeated fast failures. If the initial attempt is
  2748. // already more than 3 times the max retry interval, then failures have taken a long time
  2749. // (such as from network timeouts) so don't retry again to avoid the app becoming
  2750. // unexpectedly unresponsive.
  2751. if (_maxRetryInterval > 0) {
  2752. NSTimeInterval maxAllowedIntervalBeforeRetry = _maxRetryInterval * 3;
  2753. NSTimeInterval timeSinceInitialRequest = -[_initialRequestDate timeIntervalSinceNow];
  2754. if (timeSinceInitialRequest > maxAllowedIntervalBeforeRetry) {
  2755. shouldDoRetry = NO;
  2756. }
  2757. }
  2758. }
  2759. }
  2760. BOOL canRetry = shouldRetryForAuthRefresh || forceAssumeRetry || shouldDoRetry;
  2761. if (canRetry) {
  2762. NSDictionary *userInfo =
  2763. GTMErrorUserInfoForData(_downloadedData, [self responseHeadersUnsynchronized]);
  2764. NSError *statusError = [NSError errorWithDomain:kGTMSessionFetcherStatusDomain
  2765. code:status
  2766. userInfo:userInfo];
  2767. if (error == nil) {
  2768. error = statusError;
  2769. }
  2770. willRetry = shouldRetryForAuthRefresh ||
  2771. forceAssumeRetry ||
  2772. [self isRetryError:error] ||
  2773. ((error != statusError) && [self isRetryError:statusError]);
  2774. // If the user has installed a retry callback, consult that.
  2775. GTMSessionFetcherRetryBlock retryBlock = _retryBlock;
  2776. if (retryBlock) {
  2777. [self invokeOnCallbackQueueUnlessStopped:^{
  2778. retryBlock(willRetry, error, response);
  2779. }];
  2780. return;
  2781. }
  2782. }
  2783. } // @synchronized(self)
  2784. response(willRetry);
  2785. }
  2786. - (BOOL)hasRetryAfterInterval {
  2787. GTMSessionCheckSynchronized(self);
  2788. NSDictionary *responseHeaders = [self responseHeadersUnsynchronized];
  2789. NSString *retryAfterValue = [responseHeaders valueForKey:@"Retry-After"];
  2790. return (retryAfterValue != nil);
  2791. }
  2792. - (NSTimeInterval)retryAfterInterval {
  2793. GTMSessionCheckSynchronized(self);
  2794. NSDictionary *responseHeaders = [self responseHeadersUnsynchronized];
  2795. NSString *retryAfterValue = [responseHeaders valueForKey:@"Retry-After"];
  2796. if (retryAfterValue == nil) {
  2797. return 0;
  2798. }
  2799. // Retry-After formatted as HTTP-date | delta-seconds
  2800. // Reference: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  2801. NSDateFormatter *rfc1123DateFormatter = [[NSDateFormatter alloc] init];
  2802. rfc1123DateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
  2803. rfc1123DateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
  2804. rfc1123DateFormatter.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss z";
  2805. NSDate *retryAfterDate = [rfc1123DateFormatter dateFromString:retryAfterValue];
  2806. NSTimeInterval retryAfterInterval = (retryAfterDate != nil) ?
  2807. retryAfterDate.timeIntervalSinceNow : retryAfterValue.intValue;
  2808. retryAfterInterval = MAX(0, retryAfterInterval);
  2809. return retryAfterInterval;
  2810. }
  2811. - (void)beginRetryTimer {
  2812. if (![NSThread isMainThread]) {
  2813. // Defer creating and starting the timer until we're on the main thread to ensure it has
  2814. // a run loop.
  2815. dispatch_group_async(_callbackGroup, dispatch_get_main_queue(), ^{
  2816. [self beginRetryTimer];
  2817. });
  2818. return;
  2819. }
  2820. [self destroyRetryTimer];
  2821. #if GTM_BACKGROUND_TASK_FETCHING
  2822. // Don't keep a background task active while awaiting retry, which can lead to the
  2823. // app exceeding the allotted time for keeping the background task open, causing the
  2824. // system to terminate the app. When the retry starts, a new background task will
  2825. // be created.
  2826. [self endBackgroundTask];
  2827. #endif // GTM_BACKGROUND_TASK_FETCHING
  2828. @synchronized(self) {
  2829. GTMSessionMonitorSynchronized(self);
  2830. NSTimeInterval nextInterval = [self nextRetryIntervalUnsynchronized];
  2831. NSTimeInterval maxInterval = _maxRetryInterval;
  2832. NSTimeInterval newInterval = MIN(nextInterval, (maxInterval > 0 ? maxInterval : DBL_MAX));
  2833. NSTimeInterval newIntervalTolerance = (newInterval / 10) > 1.0 ?: 1.0;
  2834. _lastRetryInterval = newInterval;
  2835. _retryTimer = [NSTimer timerWithTimeInterval:newInterval
  2836. target:self
  2837. selector:@selector(retryTimerFired:)
  2838. userInfo:nil
  2839. repeats:NO];
  2840. _retryTimer.tolerance = newIntervalTolerance;
  2841. [[NSRunLoop mainRunLoop] addTimer:_retryTimer
  2842. forMode:NSDefaultRunLoopMode];
  2843. } // @synchronized(self)
  2844. [self postNotificationOnMainThreadWithName:kGTMSessionFetcherRetryDelayStartedNotification
  2845. userInfo:nil
  2846. requireAsync:NO];
  2847. }
  2848. - (void)retryTimerFired:(NSTimer *)timer {
  2849. [self destroyRetryTimer];
  2850. @synchronized(self) {
  2851. GTMSessionMonitorSynchronized(self);
  2852. _retryCount++;
  2853. } // @synchronized(self)
  2854. NSOperationQueue *queue = self.sessionDelegateQueue;
  2855. [queue addOperationWithBlock:^{
  2856. [self retryFetch];
  2857. }];
  2858. }
  2859. - (void)destroyRetryTimer {
  2860. BOOL shouldNotify = NO;
  2861. @synchronized(self) {
  2862. GTMSessionMonitorSynchronized(self);
  2863. if (_retryTimer) {
  2864. [_retryTimer invalidate];
  2865. _retryTimer = nil;
  2866. shouldNotify = YES;
  2867. }
  2868. }
  2869. if (shouldNotify) {
  2870. [self postNotificationOnMainThreadWithName:kGTMSessionFetcherRetryDelayStoppedNotification
  2871. userInfo:nil
  2872. requireAsync:NO];
  2873. }
  2874. }
  2875. - (NSUInteger)retryCount {
  2876. @synchronized(self) {
  2877. GTMSessionMonitorSynchronized(self);
  2878. return _retryCount;
  2879. } // @synchronized(self)
  2880. }
  2881. - (NSTimeInterval)nextRetryInterval {
  2882. @synchronized(self) {
  2883. GTMSessionMonitorSynchronized(self);
  2884. NSTimeInterval interval = [self nextRetryIntervalUnsynchronized];
  2885. return interval;
  2886. } // @synchronized(self)
  2887. }
  2888. - (NSTimeInterval)nextRetryIntervalUnsynchronized {
  2889. GTMSessionCheckSynchronized(self);
  2890. NSInteger statusCode = [self statusCodeUnsynchronized];
  2891. if ((statusCode == 503) && [self hasRetryAfterInterval]) {
  2892. NSTimeInterval secs = [self retryAfterInterval];
  2893. return secs;
  2894. }
  2895. // The next wait interval is the factor (2.0) times the last interval,
  2896. // but never less than the minimum interval.
  2897. NSTimeInterval secs = _lastRetryInterval * _retryFactor;
  2898. if (_maxRetryInterval > 0) {
  2899. secs = MIN(secs, _maxRetryInterval);
  2900. }
  2901. secs = MAX(secs, _minRetryInterval);
  2902. return secs;
  2903. }
  2904. - (NSTimer *)retryTimer {
  2905. @synchronized(self) {
  2906. GTMSessionMonitorSynchronized(self);
  2907. return _retryTimer;
  2908. } // @synchronized(self)
  2909. }
  2910. - (BOOL)isRetryEnabled {
  2911. @synchronized(self) {
  2912. GTMSessionMonitorSynchronized(self);
  2913. return _isRetryEnabled;
  2914. } // @synchronized(self)
  2915. }
  2916. - (BOOL)isRetryEnabledUnsynchronized {
  2917. GTMSessionCheckSynchronized(self);
  2918. return _isRetryEnabled;
  2919. }
  2920. - (void)setRetryEnabled:(BOOL)flag {
  2921. @synchronized(self) {
  2922. GTMSessionMonitorSynchronized(self);
  2923. if (flag && !_isRetryEnabled) {
  2924. // We defer initializing these until the user calls setRetryEnabled
  2925. // to avoid using the random number generator if it's not needed.
  2926. // However, this means min and max intervals for this fetcher are reset
  2927. // as a side effect of calling setRetryEnabled.
  2928. //
  2929. // Make an initial retry interval random between 1.0 and 2.0 seconds
  2930. _minRetryInterval = InitialMinRetryInterval();
  2931. _maxRetryInterval = kUnsetMaxRetryInterval;
  2932. _retryFactor = 2.0;
  2933. _lastRetryInterval = 0.0;
  2934. }
  2935. _isRetryEnabled = flag;
  2936. } // @synchronized(self)
  2937. };
  2938. - (NSTimeInterval)maxRetryInterval {
  2939. @synchronized(self) {
  2940. GTMSessionMonitorSynchronized(self);
  2941. return _maxRetryInterval;
  2942. } // @synchronized(self)
  2943. }
  2944. - (void)setMaxRetryInterval:(NSTimeInterval)secs {
  2945. @synchronized(self) {
  2946. GTMSessionMonitorSynchronized(self);
  2947. if (secs > 0) {
  2948. _maxRetryInterval = secs;
  2949. } else {
  2950. _maxRetryInterval = kUnsetMaxRetryInterval;
  2951. }
  2952. } // @synchronized(self)
  2953. }
  2954. - (double)minRetryInterval {
  2955. @synchronized(self) {
  2956. GTMSessionMonitorSynchronized(self);
  2957. return _minRetryInterval;
  2958. } // @synchronized(self)
  2959. }
  2960. - (void)setMinRetryInterval:(NSTimeInterval)secs {
  2961. @synchronized(self) {
  2962. GTMSessionMonitorSynchronized(self);
  2963. if (secs > 0) {
  2964. _minRetryInterval = secs;
  2965. } else {
  2966. // Set min interval to a random value between 1.0 and 2.0 seconds
  2967. // so that if multiple clients start retrying at the same time, they'll
  2968. // repeat at different times and avoid overloading the server
  2969. _minRetryInterval = InitialMinRetryInterval();
  2970. }
  2971. } // @synchronized(self)
  2972. }
  2973. #pragma mark iOS System Completion Handlers
  2974. #if TARGET_OS_IPHONE
  2975. static NSMutableDictionary *gSystemCompletionHandlers = nil;
  2976. - (GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandler {
  2977. return [[self class] systemCompletionHandlerForSessionIdentifier:_sessionIdentifier];
  2978. }
  2979. - (void)setSystemCompletionHandler:(GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandler {
  2980. [[self class] setSystemCompletionHandler:systemCompletionHandler
  2981. forSessionIdentifier:_sessionIdentifier];
  2982. }
  2983. + (void)setSystemCompletionHandler:(GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandler
  2984. forSessionIdentifier:(NSString *)sessionIdentifier {
  2985. if (!sessionIdentifier) {
  2986. NSLog(@"%s with nil identifier", __PRETTY_FUNCTION__);
  2987. return;
  2988. }
  2989. @synchronized([GTMSessionFetcher class]) {
  2990. if (gSystemCompletionHandlers == nil && systemCompletionHandler != nil) {
  2991. gSystemCompletionHandlers = [[NSMutableDictionary alloc] init];
  2992. }
  2993. // Use setValue: to remove the object if completionHandler is nil.
  2994. [gSystemCompletionHandlers setValue:systemCompletionHandler
  2995. forKey:sessionIdentifier];
  2996. }
  2997. }
  2998. + (GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandlerForSessionIdentifier:(NSString *)sessionIdentifier {
  2999. if (!sessionIdentifier) {
  3000. return nil;
  3001. }
  3002. @synchronized([GTMSessionFetcher class]) {
  3003. return [gSystemCompletionHandlers objectForKey:sessionIdentifier];
  3004. }
  3005. }
  3006. #endif // TARGET_OS_IPHONE
  3007. #pragma mark Getters and Setters
  3008. @synthesize downloadResumeData = _downloadResumeData,
  3009. configuration = _configuration,
  3010. configurationBlock = _configurationBlock,
  3011. sessionTask = _sessionTask,
  3012. wasCreatedFromBackgroundSession = _wasCreatedFromBackgroundSession,
  3013. sessionUserInfo = _sessionUserInfo,
  3014. taskDescription = _taskDescription,
  3015. taskPriority = _taskPriority,
  3016. usingBackgroundSession = _usingBackgroundSession,
  3017. canShareSession = _canShareSession,
  3018. completionHandler = _completionHandler,
  3019. credential = _credential,
  3020. proxyCredential = _proxyCredential,
  3021. bodyData = _bodyData,
  3022. bodyLength = _bodyLength,
  3023. service = _service,
  3024. serviceHost = _serviceHost,
  3025. accumulateDataBlock = _accumulateDataBlock,
  3026. receivedProgressBlock = _receivedProgressBlock,
  3027. downloadProgressBlock = _downloadProgressBlock,
  3028. resumeDataBlock = _resumeDataBlock,
  3029. didReceiveResponseBlock = _didReceiveResponseBlock,
  3030. challengeBlock = _challengeBlock,
  3031. willRedirectBlock = _willRedirectBlock,
  3032. sendProgressBlock = _sendProgressBlock,
  3033. willCacheURLResponseBlock = _willCacheURLResponseBlock,
  3034. retryBlock = _retryBlock,
  3035. metricsCollectionBlock = _metricsCollectionBlock,
  3036. retryFactor = _retryFactor,
  3037. allowedInsecureSchemes = _allowedInsecureSchemes,
  3038. allowLocalhostRequest = _allowLocalhostRequest,
  3039. allowInvalidServerCertificates = _allowInvalidServerCertificates,
  3040. cookieStorage = _cookieStorage,
  3041. callbackQueue = _callbackQueue,
  3042. initialBeginFetchDate = _initialBeginFetchDate,
  3043. testBlock = _testBlock,
  3044. testBlockAccumulateDataChunkCount = _testBlockAccumulateDataChunkCount,
  3045. comment = _comment,
  3046. log = _log;
  3047. #if !STRIP_GTM_FETCH_LOGGING
  3048. @synthesize redirectedFromURL = _redirectedFromURL,
  3049. logRequestBody = _logRequestBody,
  3050. logResponseBody = _logResponseBody,
  3051. hasLoggedError = _hasLoggedError;
  3052. #endif
  3053. #if GTM_BACKGROUND_TASK_FETCHING
  3054. @synthesize backgroundTaskIdentifier = _backgroundTaskIdentifier,
  3055. skipBackgroundTask = _skipBackgroundTask;
  3056. #endif
  3057. - (GTM_NULLABLE NSURLRequest *)request {
  3058. @synchronized(self) {
  3059. GTMSessionMonitorSynchronized(self);
  3060. return [_request copy];
  3061. } // @synchronized(self)
  3062. }
  3063. - (void)setRequest:(GTM_NULLABLE NSURLRequest *)request {
  3064. @synchronized(self) {
  3065. GTMSessionMonitorSynchronized(self);
  3066. if (![self isFetchingUnsynchronized]) {
  3067. _request = [request mutableCopy];
  3068. } else {
  3069. GTMSESSION_ASSERT_DEBUG(0, @"request may not be set after beginFetch has been invoked");
  3070. }
  3071. } // @synchronized(self)
  3072. }
  3073. - (GTM_NULLABLE NSMutableURLRequest *)mutableRequestForTesting {
  3074. // Allow tests only to modify the request, useful during retries.
  3075. return _request;
  3076. }
  3077. // Internal method for updating the request property such as on redirects.
  3078. - (void)updateMutableRequest:(GTM_NULLABLE NSMutableURLRequest *)request {
  3079. @synchronized(self) {
  3080. GTMSessionMonitorSynchronized(self);
  3081. _request = request;
  3082. } // @synchronized(self)
  3083. }
  3084. // Set a header field value on the request. Header field value changes will not
  3085. // affect a fetch after the fetch has begun.
  3086. - (void)setRequestValue:(GTM_NULLABLE NSString *)value forHTTPHeaderField:(NSString *)field {
  3087. if (![self isFetching]) {
  3088. [self updateRequestValue:value forHTTPHeaderField:field];
  3089. } else {
  3090. GTMSESSION_ASSERT_DEBUG(0, @"request may not be set after beginFetch has been invoked");
  3091. }
  3092. }
  3093. // Internal method for updating request headers.
  3094. - (void)updateRequestValue:(GTM_NULLABLE NSString *)value forHTTPHeaderField:(NSString *)field {
  3095. @synchronized(self) {
  3096. GTMSessionMonitorSynchronized(self);
  3097. [_request setValue:value forHTTPHeaderField:field];
  3098. } // @synchronized(self)
  3099. }
  3100. - (void)setResponse:(GTM_NULLABLE NSURLResponse *)response {
  3101. @synchronized(self) {
  3102. GTMSessionMonitorSynchronized(self);
  3103. _response = response;
  3104. } // @synchronized(self)
  3105. }
  3106. - (int64_t)bodyLength {
  3107. @synchronized(self) {
  3108. GTMSessionMonitorSynchronized(self);
  3109. if (_bodyLength == NSURLSessionTransferSizeUnknown) {
  3110. if (_bodyData) {
  3111. _bodyLength = (int64_t)_bodyData.length;
  3112. } else if (_bodyFileURL) {
  3113. NSNumber *fileSizeNum = nil;
  3114. NSError *fileSizeError = nil;
  3115. if ([_bodyFileURL getResourceValue:&fileSizeNum
  3116. forKey:NSURLFileSizeKey
  3117. error:&fileSizeError]) {
  3118. _bodyLength = [fileSizeNum longLongValue];
  3119. }
  3120. }
  3121. }
  3122. return _bodyLength;
  3123. } // @synchronized(self)
  3124. }
  3125. - (BOOL)useUploadTask {
  3126. @synchronized(self) {
  3127. GTMSessionMonitorSynchronized(self);
  3128. return _useUploadTask;
  3129. } // @synchronized(self)
  3130. }
  3131. - (void)setUseUploadTask:(BOOL)flag {
  3132. @synchronized(self) {
  3133. GTMSessionMonitorSynchronized(self);
  3134. if (flag != _useUploadTask) {
  3135. GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized],
  3136. @"useUploadTask should not change after beginFetch has been invoked");
  3137. _useUploadTask = flag;
  3138. }
  3139. } // @synchronized(self)
  3140. }
  3141. - (GTM_NULLABLE NSURL *)bodyFileURL {
  3142. @synchronized(self) {
  3143. GTMSessionMonitorSynchronized(self);
  3144. return _bodyFileURL;
  3145. } // @synchronized(self)
  3146. }
  3147. - (void)setBodyFileURL:(GTM_NULLABLE NSURL *)fileURL {
  3148. @synchronized(self) {
  3149. GTMSessionMonitorSynchronized(self);
  3150. // The comparison here is a trivial optimization and forgiveness for any client that
  3151. // repeatedly sets the property, so it just uses pointer comparison rather than isEqual:.
  3152. if (fileURL != _bodyFileURL) {
  3153. GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized],
  3154. @"fileURL should not change after beginFetch has been invoked");
  3155. _bodyFileURL = fileURL;
  3156. }
  3157. } // @synchronized(self)
  3158. }
  3159. - (GTM_NULLABLE GTMSessionFetcherBodyStreamProvider)bodyStreamProvider {
  3160. @synchronized(self) {
  3161. GTMSessionMonitorSynchronized(self);
  3162. return _bodyStreamProvider;
  3163. } // @synchronized(self)
  3164. }
  3165. - (void)setBodyStreamProvider:(GTM_NULLABLE GTMSessionFetcherBodyStreamProvider)block {
  3166. @synchronized(self) {
  3167. GTMSessionMonitorSynchronized(self);
  3168. GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized],
  3169. @"stream provider should not change after beginFetch has been invoked");
  3170. _bodyStreamProvider = [block copy];
  3171. } // @synchronized(self)
  3172. }
  3173. - (GTM_NULLABLE id<GTMFetcherAuthorizationProtocol>)authorizer {
  3174. @synchronized(self) {
  3175. GTMSessionMonitorSynchronized(self);
  3176. return _authorizer;
  3177. } // @synchronized(self)
  3178. }
  3179. - (void)setAuthorizer:(GTM_NULLABLE id<GTMFetcherAuthorizationProtocol>)authorizer {
  3180. @synchronized(self) {
  3181. GTMSessionMonitorSynchronized(self);
  3182. if (authorizer != _authorizer) {
  3183. if ([self isFetchingUnsynchronized]) {
  3184. GTMSESSION_ASSERT_DEBUG(0, @"authorizer should not change after beginFetch has been invoked");
  3185. } else {
  3186. _authorizer = authorizer;
  3187. }
  3188. }
  3189. } // @synchronized(self)
  3190. }
  3191. - (GTM_NULLABLE NSData *)downloadedData {
  3192. @synchronized(self) {
  3193. GTMSessionMonitorSynchronized(self);
  3194. return _downloadedData;
  3195. } // @synchronized(self)
  3196. }
  3197. - (void)setDownloadedData:(GTM_NULLABLE NSData *)data {
  3198. @synchronized(self) {
  3199. GTMSessionMonitorSynchronized(self);
  3200. _downloadedData = [data mutableCopy];
  3201. } // @synchronized(self)
  3202. }
  3203. - (int64_t)downloadedLength {
  3204. @synchronized(self) {
  3205. GTMSessionMonitorSynchronized(self);
  3206. return _downloadedLength;
  3207. } // @synchronized(self)
  3208. }
  3209. - (void)setDownloadedLength:(int64_t)length {
  3210. @synchronized(self) {
  3211. GTMSessionMonitorSynchronized(self);
  3212. _downloadedLength = length;
  3213. } // @synchronized(self)
  3214. }
  3215. - (dispatch_queue_t GTM_NONNULL_TYPE)callbackQueue {
  3216. @synchronized(self) {
  3217. GTMSessionMonitorSynchronized(self);
  3218. return _callbackQueue;
  3219. } // @synchronized(self)
  3220. }
  3221. - (void)setCallbackQueue:(dispatch_queue_t GTM_NULLABLE_TYPE)queue {
  3222. @synchronized(self) {
  3223. GTMSessionMonitorSynchronized(self);
  3224. _callbackQueue = queue ?: dispatch_get_main_queue();
  3225. } // @synchronized(self)
  3226. }
  3227. - (GTM_NULLABLE NSURLSession *)session {
  3228. @synchronized(self) {
  3229. GTMSessionMonitorSynchronized(self);
  3230. return _session;
  3231. } // @synchronized(self)
  3232. }
  3233. - (NSInteger)servicePriority {
  3234. @synchronized(self) {
  3235. GTMSessionMonitorSynchronized(self);
  3236. return _servicePriority;
  3237. } // @synchronized(self)
  3238. }
  3239. - (void)setServicePriority:(NSInteger)value {
  3240. @synchronized(self) {
  3241. GTMSessionMonitorSynchronized(self);
  3242. if (value != _servicePriority) {
  3243. GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized],
  3244. @"servicePriority should not change after beginFetch has been invoked");
  3245. _servicePriority = value;
  3246. }
  3247. } // @synchronized(self)
  3248. }
  3249. - (void)setSession:(GTM_NULLABLE NSURLSession *)session {
  3250. @synchronized(self) {
  3251. GTMSessionMonitorSynchronized(self);
  3252. _session = session;
  3253. } // @synchronized(self)
  3254. }
  3255. - (BOOL)canShareSession {
  3256. @synchronized(self) {
  3257. GTMSessionMonitorSynchronized(self);
  3258. return _canShareSession;
  3259. } // @synchronized(self)
  3260. }
  3261. - (void)setCanShareSession:(BOOL)flag {
  3262. @synchronized(self) {
  3263. GTMSessionMonitorSynchronized(self);
  3264. _canShareSession = flag;
  3265. } // @synchronized(self)
  3266. }
  3267. - (BOOL)useBackgroundSession {
  3268. // This reflects if the user requested a background session, not necessarily
  3269. // if one was created. That is tracked with _usingBackgroundSession.
  3270. @synchronized(self) {
  3271. GTMSessionMonitorSynchronized(self);
  3272. return _userRequestedBackgroundSession;
  3273. } // @synchronized(self)
  3274. }
  3275. - (void)setUseBackgroundSession:(BOOL)flag {
  3276. @synchronized(self) {
  3277. GTMSessionMonitorSynchronized(self);
  3278. if (flag != _userRequestedBackgroundSession) {
  3279. GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized],
  3280. @"useBackgroundSession should not change after beginFetch has been invoked");
  3281. _userRequestedBackgroundSession = flag;
  3282. }
  3283. } // @synchronized(self)
  3284. }
  3285. - (BOOL)isUsingBackgroundSession {
  3286. @synchronized(self) {
  3287. GTMSessionMonitorSynchronized(self);
  3288. return _usingBackgroundSession;
  3289. } // @synchronized(self)
  3290. }
  3291. - (void)setUsingBackgroundSession:(BOOL)flag {
  3292. @synchronized(self) {
  3293. GTMSessionMonitorSynchronized(self);
  3294. _usingBackgroundSession = flag;
  3295. } // @synchronized(self)
  3296. }
  3297. - (GTM_NULLABLE NSURLSession *)sessionNeedingInvalidation {
  3298. @synchronized(self) {
  3299. GTMSessionMonitorSynchronized(self);
  3300. return _sessionNeedingInvalidation;
  3301. } // @synchronized(self)
  3302. }
  3303. - (void)setSessionNeedingInvalidation:(GTM_NULLABLE NSURLSession *)session {
  3304. @synchronized(self) {
  3305. GTMSessionMonitorSynchronized(self);
  3306. _sessionNeedingInvalidation = session;
  3307. } // @synchronized(self)
  3308. }
  3309. - (NSOperationQueue * GTM_NONNULL_TYPE)sessionDelegateQueue {
  3310. @synchronized(self) {
  3311. GTMSessionMonitorSynchronized(self);
  3312. return _delegateQueue;
  3313. } // @synchronized(self)
  3314. }
  3315. - (void)setSessionDelegateQueue:(NSOperationQueue * GTM_NULLABLE_TYPE)queue {
  3316. @synchronized(self) {
  3317. GTMSessionMonitorSynchronized(self);
  3318. if (queue != _delegateQueue) {
  3319. if ([self isFetchingUnsynchronized]) {
  3320. GTMSESSION_ASSERT_DEBUG(0, @"sessionDelegateQueue should not change after fetch begins");
  3321. } else {
  3322. _delegateQueue = queue ?: [NSOperationQueue mainQueue];
  3323. }
  3324. }
  3325. } // @synchronized(self)
  3326. }
  3327. - (BOOL)userStoppedFetching {
  3328. @synchronized(self) {
  3329. GTMSessionMonitorSynchronized(self);
  3330. return _userStoppedFetching;
  3331. } // @synchronized(self)
  3332. }
  3333. - (GTM_NULLABLE id)userData {
  3334. @synchronized(self) {
  3335. GTMSessionMonitorSynchronized(self);
  3336. return _userData;
  3337. } // @synchronized(self)
  3338. }
  3339. - (void)setUserData:(GTM_NULLABLE id)theObj {
  3340. @synchronized(self) {
  3341. GTMSessionMonitorSynchronized(self);
  3342. _userData = theObj;
  3343. } // @synchronized(self)
  3344. }
  3345. - (GTM_NULLABLE NSURL *)destinationFileURL {
  3346. @synchronized(self) {
  3347. GTMSessionMonitorSynchronized(self);
  3348. return _destinationFileURL;
  3349. } // @synchronized(self)
  3350. }
  3351. - (void)setDestinationFileURL:(GTM_NULLABLE NSURL *)destinationFileURL {
  3352. @synchronized(self) {
  3353. GTMSessionMonitorSynchronized(self);
  3354. if (((_destinationFileURL == nil) && (destinationFileURL == nil)) ||
  3355. [_destinationFileURL isEqual:destinationFileURL]) {
  3356. return;
  3357. }
  3358. if (_sessionIdentifier) {
  3359. // This is something we don't expect to happen in production.
  3360. // However if it ever happen, leave a system log.
  3361. NSLog(@"%@: Destination File URL changed from (%@) to (%@) after session identifier has "
  3362. @"been created.",
  3363. [self class], _destinationFileURL, destinationFileURL);
  3364. #if DEBUG
  3365. // On both the simulator and devices, the path can change to the download file, but the name
  3366. // shouldn't change. Technically, this isn't supported in the fetcher, but the change of
  3367. // URL is expected to happen only across development runs through Xcode.
  3368. NSString *oldFilename = [_destinationFileURL lastPathComponent];
  3369. NSString *newFilename = [destinationFileURL lastPathComponent];
  3370. #pragma unused(oldFilename)
  3371. #pragma unused(newFilename)
  3372. GTMSESSION_ASSERT_DEBUG([oldFilename isEqualToString:newFilename],
  3373. @"Destination File URL cannot be changed after session identifier has been created");
  3374. #endif
  3375. }
  3376. _destinationFileURL = destinationFileURL;
  3377. } // @synchronized(self)
  3378. }
  3379. - (void)setProperties:(GTM_NULLABLE NSDictionary *)dict {
  3380. @synchronized(self) {
  3381. GTMSessionMonitorSynchronized(self);
  3382. _properties = [dict mutableCopy];
  3383. } // @synchronized(self)
  3384. }
  3385. - (GTM_NULLABLE NSDictionary *)properties {
  3386. @synchronized(self) {
  3387. GTMSessionMonitorSynchronized(self);
  3388. return _properties;
  3389. } // @synchronized(self)
  3390. }
  3391. - (void)setProperty:(GTM_NULLABLE id)obj forKey:(NSString *)key {
  3392. @synchronized(self) {
  3393. GTMSessionMonitorSynchronized(self);
  3394. if (_properties == nil && obj != nil) {
  3395. _properties = [[NSMutableDictionary alloc] init];
  3396. }
  3397. [_properties setValue:obj forKey:key];
  3398. } // @synchronized(self)
  3399. }
  3400. - (GTM_NULLABLE id)propertyForKey:(NSString *)key {
  3401. @synchronized(self) {
  3402. GTMSessionMonitorSynchronized(self);
  3403. return [_properties objectForKey:key];
  3404. } // @synchronized(self)
  3405. }
  3406. - (void)addPropertiesFromDictionary:(NSDictionary *)dict {
  3407. @synchronized(self) {
  3408. GTMSessionMonitorSynchronized(self);
  3409. if (_properties == nil && dict != nil) {
  3410. [self setProperties:[dict mutableCopy]];
  3411. } else {
  3412. [_properties addEntriesFromDictionary:dict];
  3413. }
  3414. } // @synchronized(self)
  3415. }
  3416. - (void)setCommentWithFormat:(id)format, ... {
  3417. #if !STRIP_GTM_FETCH_LOGGING
  3418. NSString *result = format;
  3419. if (format) {
  3420. va_list argList;
  3421. va_start(argList, format);
  3422. result = [[NSString alloc] initWithFormat:format
  3423. arguments:argList];
  3424. va_end(argList);
  3425. }
  3426. [self setComment:result];
  3427. #endif
  3428. }
  3429. #if !STRIP_GTM_FETCH_LOGGING
  3430. - (NSData *)loggedStreamData {
  3431. return _loggedStreamData;
  3432. }
  3433. - (void)appendLoggedStreamData:dataToAdd {
  3434. if (!_loggedStreamData) {
  3435. _loggedStreamData = [NSMutableData data];
  3436. }
  3437. [_loggedStreamData appendData:dataToAdd];
  3438. }
  3439. - (void)clearLoggedStreamData {
  3440. _loggedStreamData = nil;
  3441. }
  3442. - (void)setDeferResponseBodyLogging:(BOOL)deferResponseBodyLogging {
  3443. @synchronized(self) {
  3444. GTMSessionMonitorSynchronized(self);
  3445. if (deferResponseBodyLogging != _deferResponseBodyLogging) {
  3446. _deferResponseBodyLogging = deferResponseBodyLogging;
  3447. if (!deferResponseBodyLogging && !self.hasLoggedError) {
  3448. [_delegateQueue addOperationWithBlock:^{
  3449. [self logNowWithError:nil];
  3450. }];
  3451. }
  3452. }
  3453. } // @synchronized(self)
  3454. }
  3455. - (BOOL)deferResponseBodyLogging {
  3456. @synchronized(self) {
  3457. GTMSessionMonitorSynchronized(self);
  3458. return _deferResponseBodyLogging;
  3459. } // @synchronized(self)
  3460. }
  3461. #else
  3462. + (void)setLoggingEnabled:(BOOL)flag {
  3463. }
  3464. + (BOOL)isLoggingEnabled {
  3465. return NO;
  3466. }
  3467. #endif // STRIP_GTM_FETCH_LOGGING
  3468. @end
  3469. @implementation GTMSessionFetcher (BackwardsCompatibilityOnly)
  3470. - (void)setCookieStorageMethod:(NSInteger)method {
  3471. // For backwards compatibility with the old fetcher, we'll support the old constants.
  3472. //
  3473. // Clients using the GTMSessionFetcher class should set the cookie storage explicitly
  3474. // themselves.
  3475. NSHTTPCookieStorage *storage = nil;
  3476. switch(method) {
  3477. case 0: // kGTMHTTPFetcherCookieStorageMethodStatic
  3478. // nil storage will use [[self class] staticCookieStorage] when the fetch begins.
  3479. break;
  3480. case 1: // kGTMHTTPFetcherCookieStorageMethodFetchHistory
  3481. // Do nothing; use whatever was set by the fetcher service.
  3482. return;
  3483. case 2: // kGTMHTTPFetcherCookieStorageMethodSystemDefault
  3484. storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  3485. break;
  3486. case 3: // kGTMHTTPFetcherCookieStorageMethodNone
  3487. // Create temporary storage for this fetcher only.
  3488. storage = [[GTMSessionCookieStorage alloc] init];
  3489. break;
  3490. default:
  3491. GTMSESSION_ASSERT_DEBUG(0, @"Invalid cookie storage method: %d", (int)method);
  3492. }
  3493. self.cookieStorage = storage;
  3494. }
  3495. @end
  3496. @implementation GTMSessionCookieStorage {
  3497. NSMutableArray *_cookies;
  3498. NSHTTPCookieAcceptPolicy _policy;
  3499. }
  3500. - (id)init {
  3501. self = [super init];
  3502. if (self != nil) {
  3503. _cookies = [[NSMutableArray alloc] init];
  3504. }
  3505. return self;
  3506. }
  3507. - (GTM_NULLABLE NSArray *)cookies {
  3508. @synchronized(self) {
  3509. GTMSessionMonitorSynchronized(self);
  3510. return [_cookies copy];
  3511. } // @synchronized(self)
  3512. }
  3513. - (void)setCookie:(NSHTTPCookie *)cookie {
  3514. if (!cookie) return;
  3515. if (_policy == NSHTTPCookieAcceptPolicyNever) return;
  3516. @synchronized(self) {
  3517. GTMSessionMonitorSynchronized(self);
  3518. [self internalSetCookie:cookie];
  3519. } // @synchronized(self)
  3520. }
  3521. // Note: this should only be called from inside a @synchronized(self) block.
  3522. - (void)internalSetCookie:(NSHTTPCookie *)newCookie {
  3523. GTMSessionCheckSynchronized(self);
  3524. if (_policy == NSHTTPCookieAcceptPolicyNever) return;
  3525. BOOL isValidCookie = (newCookie.name.length > 0
  3526. && newCookie.domain.length > 0
  3527. && newCookie.path.length > 0);
  3528. GTMSESSION_ASSERT_DEBUG(isValidCookie, @"invalid cookie: %@", newCookie);
  3529. if (isValidCookie) {
  3530. // Remove the cookie if it's currently in the array.
  3531. NSHTTPCookie *oldCookie = [self cookieMatchingCookie:newCookie];
  3532. if (oldCookie) {
  3533. [_cookies removeObjectIdenticalTo:oldCookie];
  3534. }
  3535. if (![[self class] hasCookieExpired:newCookie]) {
  3536. [_cookies addObject:newCookie];
  3537. }
  3538. }
  3539. }
  3540. // Add all cookies in the new cookie array to the storage,
  3541. // replacing stored cookies as appropriate.
  3542. //
  3543. // Side effect: removes expired cookies from the storage array.
  3544. - (void)setCookies:(GTM_NULLABLE NSArray *)newCookies {
  3545. @synchronized(self) {
  3546. GTMSessionMonitorSynchronized(self);
  3547. [self removeExpiredCookies];
  3548. for (NSHTTPCookie *newCookie in newCookies) {
  3549. [self internalSetCookie:newCookie];
  3550. }
  3551. } // @synchronized(self)
  3552. }
  3553. - (void)setCookies:(NSArray *)cookies forURL:(GTM_NULLABLE NSURL *)URL mainDocumentURL:(GTM_NULLABLE NSURL *)mainDocumentURL {
  3554. @synchronized(self) {
  3555. GTMSessionMonitorSynchronized(self);
  3556. if (_policy == NSHTTPCookieAcceptPolicyNever) {
  3557. return;
  3558. }
  3559. if (_policy == NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain) {
  3560. NSString *mainHost = mainDocumentURL.host;
  3561. NSString *associatedHost = URL.host;
  3562. if (!mainHost || ![associatedHost hasSuffix:mainHost]) {
  3563. return;
  3564. }
  3565. }
  3566. } // @synchronized(self)
  3567. [self setCookies:cookies];
  3568. }
  3569. - (void)deleteCookie:(NSHTTPCookie *)cookie {
  3570. if (!cookie) return;
  3571. @synchronized(self) {
  3572. GTMSessionMonitorSynchronized(self);
  3573. NSHTTPCookie *foundCookie = [self cookieMatchingCookie:cookie];
  3574. if (foundCookie) {
  3575. [_cookies removeObjectIdenticalTo:foundCookie];
  3576. }
  3577. } // @synchronized(self)
  3578. }
  3579. // Retrieve all cookies appropriate for the given URL, considering
  3580. // domain, path, cookie name, expiration, security setting.
  3581. // Side effect: removed expired cookies from the storage array.
  3582. - (GTM_NULLABLE NSArray *)cookiesForURL:(NSURL *)theURL {
  3583. NSMutableArray *foundCookies = nil;
  3584. @synchronized(self) {
  3585. GTMSessionMonitorSynchronized(self);
  3586. [self removeExpiredCookies];
  3587. // We'll prepend "." to the desired domain, since we want the
  3588. // actual domain "nytimes.com" to still match the cookie domain
  3589. // ".nytimes.com" when we check it below with hasSuffix.
  3590. NSString *host = theURL.host.lowercaseString;
  3591. NSString *path = theURL.path;
  3592. NSString *scheme = [theURL scheme];
  3593. NSString *requestingDomain = nil;
  3594. BOOL isLocalhostRetrieval = NO;
  3595. if (IsLocalhost(host)) {
  3596. isLocalhostRetrieval = YES;
  3597. } else {
  3598. if (host.length > 0) {
  3599. requestingDomain = [@"." stringByAppendingString:host];
  3600. }
  3601. }
  3602. for (NSHTTPCookie *storedCookie in _cookies) {
  3603. NSString *cookieDomain = storedCookie.domain.lowercaseString;
  3604. NSString *cookiePath = storedCookie.path;
  3605. BOOL cookieIsSecure = [storedCookie isSecure];
  3606. BOOL isDomainOK;
  3607. if (isLocalhostRetrieval) {
  3608. // Prior to 10.5.6, the domain stored into NSHTTPCookies for localhost
  3609. // is "localhost.local"
  3610. isDomainOK = (IsLocalhost(cookieDomain)
  3611. || [cookieDomain isEqual:@"localhost.local"]);
  3612. } else {
  3613. // Ensure we're matching exact domain names. We prepended a dot to the
  3614. // requesting domain, so we can also prepend one here if needed before
  3615. // checking if the request contains the cookie domain.
  3616. if (![cookieDomain hasPrefix:@"."]) {
  3617. cookieDomain = [@"." stringByAppendingString:cookieDomain];
  3618. }
  3619. isDomainOK = [requestingDomain hasSuffix:cookieDomain];
  3620. }
  3621. BOOL isPathOK = [cookiePath isEqual:@"/"] || [path hasPrefix:cookiePath];
  3622. BOOL isSecureOK = (!cookieIsSecure
  3623. || [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame);
  3624. if (isDomainOK && isPathOK && isSecureOK) {
  3625. if (foundCookies == nil) {
  3626. foundCookies = [NSMutableArray array];
  3627. }
  3628. [foundCookies addObject:storedCookie];
  3629. }
  3630. }
  3631. } // @synchronized(self)
  3632. return foundCookies;
  3633. }
  3634. // Override methods from the NSHTTPCookieStorage (NSURLSessionTaskAdditions) category.
  3635. - (void)storeCookies:(NSArray *)cookies forTask:(NSURLSessionTask *)task {
  3636. NSURLRequest *currentRequest = task.currentRequest;
  3637. [self setCookies:cookies forURL:currentRequest.URL mainDocumentURL:nil];
  3638. }
  3639. - (void)getCookiesForTask:(NSURLSessionTask *)task
  3640. completionHandler:(void (^)(GTM_NSArrayOf(NSHTTPCookie *) *))completionHandler {
  3641. if (completionHandler) {
  3642. NSURLRequest *currentRequest = task.currentRequest;
  3643. NSURL *currentRequestURL = currentRequest.URL;
  3644. NSArray *cookies = [self cookiesForURL:currentRequestURL];
  3645. completionHandler(cookies);
  3646. }
  3647. }
  3648. // Return a cookie from the array with the same name, domain, and path as the
  3649. // given cookie, or else return nil if none found.
  3650. //
  3651. // Both the cookie being tested and all cookies in the storage array should
  3652. // be valid (non-nil name, domains, paths).
  3653. //
  3654. // Note: this should only be called from inside a @synchronized(self) block
  3655. - (GTM_NULLABLE NSHTTPCookie *)cookieMatchingCookie:(NSHTTPCookie *)cookie {
  3656. GTMSessionCheckSynchronized(self);
  3657. NSString *name = cookie.name;
  3658. NSString *domain = cookie.domain;
  3659. NSString *path = cookie.path;
  3660. GTMSESSION_ASSERT_DEBUG(name && domain && path,
  3661. @"Invalid stored cookie (name:%@ domain:%@ path:%@)", name, domain, path);
  3662. for (NSHTTPCookie *storedCookie in _cookies) {
  3663. if ([storedCookie.name isEqual:name]
  3664. && [storedCookie.domain isEqual:domain]
  3665. && [storedCookie.path isEqual:path]) {
  3666. return storedCookie;
  3667. }
  3668. }
  3669. return nil;
  3670. }
  3671. // Internal routine to remove any expired cookies from the array, excluding
  3672. // cookies with nil expirations.
  3673. //
  3674. // Note: this should only be called from inside a @synchronized(self) block
  3675. - (void)removeExpiredCookies {
  3676. GTMSessionCheckSynchronized(self);
  3677. // Count backwards since we're deleting items from the array
  3678. for (NSInteger idx = (NSInteger)_cookies.count - 1; idx >= 0; idx--) {
  3679. NSHTTPCookie *storedCookie = [_cookies objectAtIndex:(NSUInteger)idx];
  3680. if ([[self class] hasCookieExpired:storedCookie]) {
  3681. [_cookies removeObjectAtIndex:(NSUInteger)idx];
  3682. }
  3683. }
  3684. }
  3685. + (BOOL)hasCookieExpired:(NSHTTPCookie *)cookie {
  3686. NSDate *expiresDate = [cookie expiresDate];
  3687. if (expiresDate == nil) {
  3688. // Cookies seem to have a Expires property even when the expiresDate method returns nil.
  3689. id expiresVal = [[cookie properties] objectForKey:NSHTTPCookieExpires];
  3690. if ([expiresVal isKindOfClass:[NSDate class]]) {
  3691. expiresDate = expiresVal;
  3692. }
  3693. }
  3694. BOOL hasExpired = (expiresDate != nil && [expiresDate timeIntervalSinceNow] < 0);
  3695. return hasExpired;
  3696. }
  3697. - (void)removeAllCookies {
  3698. @synchronized(self) {
  3699. GTMSessionMonitorSynchronized(self);
  3700. [_cookies removeAllObjects];
  3701. } // @synchronized(self)
  3702. }
  3703. - (NSHTTPCookieAcceptPolicy)cookieAcceptPolicy {
  3704. @synchronized(self) {
  3705. GTMSessionMonitorSynchronized(self);
  3706. return _policy;
  3707. } // @synchronized(self)
  3708. }
  3709. - (void)setCookieAcceptPolicy:(NSHTTPCookieAcceptPolicy)cookieAcceptPolicy {
  3710. @synchronized(self) {
  3711. GTMSessionMonitorSynchronized(self);
  3712. _policy = cookieAcceptPolicy;
  3713. } // @synchronized(self)
  3714. }
  3715. @end
  3716. void GTMSessionFetcherAssertValidSelector(id GTM_NULLABLE_TYPE obj, SEL GTM_NULLABLE_TYPE sel, ...) {
  3717. // Verify that the object's selector is implemented with the proper
  3718. // number and type of arguments
  3719. #if DEBUG
  3720. va_list argList;
  3721. va_start(argList, sel);
  3722. if (obj && sel) {
  3723. // Check that the selector is implemented
  3724. if (![obj respondsToSelector:sel]) {
  3725. NSLog(@"\"%@\" selector \"%@\" is unimplemented or misnamed",
  3726. NSStringFromClass([(id)obj class]),
  3727. NSStringFromSelector((SEL)sel));
  3728. NSCAssert(0, @"callback selector unimplemented or misnamed");
  3729. } else {
  3730. const char *expectedArgType;
  3731. unsigned int argCount = 2; // skip self and _cmd
  3732. NSMethodSignature *sig = [obj methodSignatureForSelector:sel];
  3733. // Check that each expected argument is present and of the correct type
  3734. while ((expectedArgType = va_arg(argList, const char*)) != 0) {
  3735. if ([sig numberOfArguments] > argCount) {
  3736. const char *foundArgType = [sig getArgumentTypeAtIndex:argCount];
  3737. if (0 != strncmp(foundArgType, expectedArgType, strlen(expectedArgType))) {
  3738. NSLog(@"\"%@\" selector \"%@\" argument %d should be type %s",
  3739. NSStringFromClass([(id)obj class]),
  3740. NSStringFromSelector((SEL)sel), (argCount - 2), expectedArgType);
  3741. NSCAssert(0, @"callback selector argument type mistake");
  3742. }
  3743. }
  3744. argCount++;
  3745. }
  3746. // Check that the proper number of arguments are present in the selector
  3747. if (argCount != [sig numberOfArguments]) {
  3748. NSLog(@"\"%@\" selector \"%@\" should have %d arguments",
  3749. NSStringFromClass([(id)obj class]),
  3750. NSStringFromSelector((SEL)sel), (argCount - 2));
  3751. NSCAssert(0, @"callback selector arguments incorrect");
  3752. }
  3753. }
  3754. }
  3755. va_end(argList);
  3756. #endif
  3757. }
  3758. NSString *GTMFetcherCleanedUserAgentString(NSString *str) {
  3759. // Reference http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html
  3760. // and http://www-archive.mozilla.org/build/user-agent-strings.html
  3761. if (str == nil) return @"";
  3762. NSMutableString *result = [NSMutableString stringWithString:str];
  3763. // Replace spaces and commas with underscores
  3764. [result replaceOccurrencesOfString:@" "
  3765. withString:@"_"
  3766. options:0
  3767. range:NSMakeRange(0, result.length)];
  3768. [result replaceOccurrencesOfString:@","
  3769. withString:@"_"
  3770. options:0
  3771. range:NSMakeRange(0, result.length)];
  3772. // Delete http token separators and remaining whitespace
  3773. static NSCharacterSet *charsToDelete = nil;
  3774. if (charsToDelete == nil) {
  3775. // Make a set of unwanted characters
  3776. NSString *const kSeparators = @"()<>@;:\\\"/[]?={}";
  3777. NSMutableCharacterSet *mutableChars =
  3778. [[NSCharacterSet whitespaceAndNewlineCharacterSet] mutableCopy];
  3779. [mutableChars addCharactersInString:kSeparators];
  3780. charsToDelete = [mutableChars copy]; // hang on to an immutable copy
  3781. }
  3782. while (1) {
  3783. NSRange separatorRange = [result rangeOfCharacterFromSet:charsToDelete];
  3784. if (separatorRange.location == NSNotFound) break;
  3785. [result deleteCharactersInRange:separatorRange];
  3786. };
  3787. return result;
  3788. }
  3789. NSString *GTMFetcherSystemVersionString(void) {
  3790. static NSString *sSavedSystemString;
  3791. static dispatch_once_t onceToken;
  3792. dispatch_once(&onceToken, ^{
  3793. // The Xcode 8 SDKs finally cleaned up this mess by providing TARGET_OS_OSX
  3794. // and TARGET_OS_IOS, but to build with older SDKs, those don't exist and
  3795. // instead one has to rely on TARGET_OS_MAC (which is true for iOS, watchOS,
  3796. // and tvOS) and TARGET_OS_IPHONE (which is true for iOS, watchOS, tvOS). So
  3797. // one has to order these carefully so you pick off the specific things
  3798. // first.
  3799. // If the code can ever assume Xcode 8 or higher (even when building for
  3800. // older OSes), then
  3801. // TARGET_OS_MAC -> TARGET_OS_OSX
  3802. // TARGET_OS_IPHONE -> TARGET_OS_IOS
  3803. // TARGET_IPHONE_SIMULATOR -> TARGET_OS_SIMULATOR
  3804. #if TARGET_OS_WATCH
  3805. // watchOS - WKInterfaceDevice
  3806. WKInterfaceDevice *currentDevice = [WKInterfaceDevice currentDevice];
  3807. NSString *rawModel = [currentDevice model];
  3808. NSString *model = GTMFetcherCleanedUserAgentString(rawModel);
  3809. NSString *systemVersion = [currentDevice systemVersion];
  3810. #if TARGET_OS_SIMULATOR
  3811. NSString *hardwareModel = @"sim";
  3812. #else
  3813. NSString *hardwareModel;
  3814. struct utsname unameRecord;
  3815. if (uname(&unameRecord) == 0) {
  3816. NSString *machineName = @(unameRecord.machine);
  3817. hardwareModel = GTMFetcherCleanedUserAgentString(machineName);
  3818. }
  3819. if (hardwareModel.length == 0) {
  3820. hardwareModel = @"unk";
  3821. }
  3822. #endif
  3823. sSavedSystemString = [[NSString alloc] initWithFormat:@"%@/%@ hw/%@",
  3824. model, systemVersion, hardwareModel];
  3825. // Example: Apple_Watch/3.0 hw/Watch1_2
  3826. #elif TARGET_OS_TV || TARGET_OS_IPHONE
  3827. // iOS and tvOS have UIDevice, use that.
  3828. UIDevice *currentDevice = [UIDevice currentDevice];
  3829. NSString *rawModel = [currentDevice model];
  3830. NSString *model = GTMFetcherCleanedUserAgentString(rawModel);
  3831. NSString *systemVersion = [currentDevice systemVersion];
  3832. #if TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR
  3833. NSString *hardwareModel = @"sim";
  3834. #else
  3835. NSString *hardwareModel;
  3836. struct utsname unameRecord;
  3837. if (uname(&unameRecord) == 0) {
  3838. NSString *machineName = @(unameRecord.machine);
  3839. hardwareModel = GTMFetcherCleanedUserAgentString(machineName);
  3840. }
  3841. if (hardwareModel.length == 0) {
  3842. hardwareModel = @"unk";
  3843. }
  3844. #endif
  3845. sSavedSystemString = [[NSString alloc] initWithFormat:@"%@/%@ hw/%@",
  3846. model, systemVersion, hardwareModel];
  3847. // Example: iPod_Touch/2.2 hw/iPod1_1
  3848. // Example: Apple_TV/9.2 hw/AppleTV5,3
  3849. #elif TARGET_OS_MAC
  3850. // Mac build
  3851. NSProcessInfo *procInfo = [NSProcessInfo processInfo];
  3852. #if !defined(MAC_OS_X_VERSION_10_10)
  3853. BOOL hasOperatingSystemVersion = NO;
  3854. #elif MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_10
  3855. BOOL hasOperatingSystemVersion =
  3856. [procInfo respondsToSelector:@selector(operatingSystemVersion)];
  3857. #else
  3858. BOOL hasOperatingSystemVersion = YES;
  3859. #endif
  3860. NSString *versString;
  3861. if (hasOperatingSystemVersion) {
  3862. #if defined(MAC_OS_X_VERSION_10_10)
  3863. // A reference to NSOperatingSystemVersion requires the 10.10 SDK.
  3864. #pragma clang diagnostic push
  3865. #pragma clang diagnostic ignored "-Wunguarded-availability"
  3866. // Disable unguarded availability warning as we can't use the @availability macro until we require
  3867. // all clients to build with Xcode 9 or above.
  3868. NSOperatingSystemVersion version = procInfo.operatingSystemVersion;
  3869. #pragma clang diagnostic pop
  3870. versString = [NSString stringWithFormat:@"%ld.%ld.%ld",
  3871. (long)version.majorVersion, (long)version.minorVersion,
  3872. (long)version.patchVersion];
  3873. #else
  3874. #pragma unused(procInfo)
  3875. #endif
  3876. } else {
  3877. // With Gestalt inexplicably deprecated in 10.8, we're reduced to reading
  3878. // the system plist file.
  3879. NSString *const kPath = @"/System/Library/CoreServices/SystemVersion.plist";
  3880. NSDictionary *plist = [NSDictionary dictionaryWithContentsOfFile:kPath];
  3881. versString = [plist objectForKey:@"ProductVersion"];
  3882. if (versString.length == 0) {
  3883. versString = @"10.?.?";
  3884. }
  3885. }
  3886. sSavedSystemString = [[NSString alloc] initWithFormat:@"MacOSX/%@", versString];
  3887. #elif defined(_SYS_UTSNAME_H)
  3888. // Foundation-only build
  3889. struct utsname unameRecord;
  3890. uname(&unameRecord);
  3891. sSavedSystemString = [NSString stringWithFormat:@"%s/%s",
  3892. unameRecord.sysname, unameRecord.release]; // "Darwin/8.11.1"
  3893. #else
  3894. #error No branch taken for a default user agent
  3895. #endif
  3896. });
  3897. return sSavedSystemString;
  3898. }
  3899. NSString *GTMFetcherStandardUserAgentString(NSBundle * GTM_NULLABLE_TYPE bundle) {
  3900. NSString *result = [NSString stringWithFormat:@"%@ %@",
  3901. GTMFetcherApplicationIdentifier(bundle),
  3902. GTMFetcherSystemVersionString()];
  3903. return result;
  3904. }
  3905. NSString *GTMFetcherApplicationIdentifier(NSBundle * GTM_NULLABLE_TYPE bundle) {
  3906. @synchronized([GTMSessionFetcher class]) {
  3907. static NSMutableDictionary *sAppIDMap = nil;
  3908. // If there's a bundle ID, use that; otherwise, use the process name
  3909. if (bundle == nil) {
  3910. bundle = [NSBundle mainBundle];
  3911. }
  3912. NSString *bundleID = [bundle bundleIdentifier];
  3913. if (bundleID == nil) {
  3914. bundleID = @"";
  3915. }
  3916. NSString *identifier = [sAppIDMap objectForKey:bundleID];
  3917. if (identifier) return identifier;
  3918. // Apps may add a string to the info.plist to uniquely identify different builds.
  3919. identifier = [bundle objectForInfoDictionaryKey:@"GTMUserAgentID"];
  3920. if (identifier.length == 0) {
  3921. if (bundleID.length > 0) {
  3922. identifier = bundleID;
  3923. } else {
  3924. // Fall back on the procname, prefixed by "proc" to flag that it's
  3925. // autogenerated and perhaps unreliable
  3926. NSString *procName = [[NSProcessInfo processInfo] processName];
  3927. identifier = [NSString stringWithFormat:@"proc_%@", procName];
  3928. }
  3929. }
  3930. // Clean up whitespace and special characters
  3931. identifier = GTMFetcherCleanedUserAgentString(identifier);
  3932. // If there's a version number, append that
  3933. NSString *version = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
  3934. if (version.length == 0) {
  3935. version = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"];
  3936. }
  3937. // Clean up whitespace and special characters
  3938. version = GTMFetcherCleanedUserAgentString(version);
  3939. // Glue the two together (cleanup done above or else cleanup would strip the
  3940. // slash)
  3941. if (version.length > 0) {
  3942. identifier = [identifier stringByAppendingFormat:@"/%@", version];
  3943. }
  3944. if (sAppIDMap == nil) {
  3945. sAppIDMap = [[NSMutableDictionary alloc] init];
  3946. }
  3947. [sAppIDMap setObject:identifier forKey:bundleID];
  3948. return identifier;
  3949. }
  3950. }
  3951. #if DEBUG && (!defined(NS_BLOCK_ASSERTIONS) || GTMSESSION_ASSERT_AS_LOG)
  3952. @implementation GTMSessionSyncMonitorInternal {
  3953. NSValue *_objectKey; // The synchronize target object.
  3954. const char *_functionName; // The function containing the monitored sync block.
  3955. }
  3956. - (instancetype)initWithSynchronizationObject:(id)object
  3957. allowRecursive:(BOOL)allowRecursive
  3958. functionName:(const char *)functionName {
  3959. self = [super init];
  3960. if (self) {
  3961. Class threadKey = [GTMSessionSyncMonitorInternal class];
  3962. _objectKey = [NSValue valueWithNonretainedObject:object];
  3963. _functionName = functionName;
  3964. NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary;
  3965. NSMutableDictionary *counters = threadDict[threadKey];
  3966. if (counters == nil) {
  3967. counters = [NSMutableDictionary dictionary];
  3968. threadDict[(id)threadKey] = counters;
  3969. }
  3970. NSCountedSet *functionNamesCounter = counters[_objectKey];
  3971. NSUInteger numberOfSyncingFunctions = functionNamesCounter.count;
  3972. if (!allowRecursive) {
  3973. BOOL isTopLevelSyncScope = (numberOfSyncingFunctions == 0);
  3974. NSArray *stack = [NSThread callStackSymbols];
  3975. GTMSESSION_ASSERT_DEBUG(isTopLevelSyncScope,
  3976. @"*** Recursive sync on %@ at %s; previous sync at %@\n%@",
  3977. [object class], functionName, functionNamesCounter.allObjects,
  3978. [stack subarrayWithRange:NSMakeRange(1, stack.count - 1)]);
  3979. }
  3980. if (!functionNamesCounter) {
  3981. functionNamesCounter = [NSCountedSet set];
  3982. counters[_objectKey] = functionNamesCounter;
  3983. }
  3984. [functionNamesCounter addObject:(id _Nonnull)@(functionName)];
  3985. }
  3986. return self;
  3987. }
  3988. - (void)dealloc {
  3989. Class threadKey = [GTMSessionSyncMonitorInternal class];
  3990. NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary;
  3991. NSMutableDictionary *counters = threadDict[threadKey];
  3992. NSCountedSet *functionNamesCounter = counters[_objectKey];
  3993. NSString *functionNameStr = @(_functionName);
  3994. NSUInteger numberOfSyncsByThisFunction = [functionNamesCounter countForObject:functionNameStr];
  3995. NSArray *stack = [NSThread callStackSymbols];
  3996. GTMSESSION_ASSERT_DEBUG(numberOfSyncsByThisFunction > 0, @"Sync not found on %@ at %s\n%@",
  3997. [_objectKey.nonretainedObjectValue class], _functionName,
  3998. [stack subarrayWithRange:NSMakeRange(1, stack.count - 1)]);
  3999. [functionNamesCounter removeObject:functionNameStr];
  4000. if (functionNamesCounter.count == 0) {
  4001. [counters removeObjectForKey:_objectKey];
  4002. }
  4003. }
  4004. + (NSArray *)functionsHoldingSynchronizationOnObject:(id)object {
  4005. Class threadKey = [GTMSessionSyncMonitorInternal class];
  4006. NSValue *localObjectKey = [NSValue valueWithNonretainedObject:object];
  4007. NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary;
  4008. NSMutableDictionary *counters = threadDict[threadKey];
  4009. NSCountedSet *functionNamesCounter = counters[localObjectKey];
  4010. return functionNamesCounter.count > 0 ? functionNamesCounter.allObjects : nil;
  4011. }
  4012. @end
  4013. #endif // DEBUG && (!defined(NS_BLOCK_ASSERTIONS) || GTMSESSION_ASSERT_AS_LOG)
  4014. GTM_ASSUME_NONNULL_END