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.

1989 lines
74 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
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
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 "GTMSessionUploadFetcher.h"
  19. static NSString *const kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey = @"_upChunk";
  20. static NSString *const kGTMSessionIdentifierUploadFileURLMetadataKey = @"_upFileURL";
  21. static NSString *const kGTMSessionIdentifierUploadFileLengthMetadataKey = @"_upFileLen";
  22. static NSString *const kGTMSessionIdentifierUploadLocationURLMetadataKey = @"_upLocURL";
  23. static NSString *const kGTMSessionIdentifierUploadMIMETypeMetadataKey = @"_uploadMIME";
  24. static NSString *const kGTMSessionIdentifierUploadChunkSizeMetadataKey = @"_upChSize";
  25. static NSString *const kGTMSessionIdentifierUploadCurrentOffsetMetadataKey = @"_upOffset";
  26. static NSString *const kGTMSessionIdentifierUploadAllowsCellularAccess = @"_upAllowsCellularAccess";
  27. static NSString *const kGTMSessionHeaderXGoogUploadChunkGranularity = @"X-Goog-Upload-Chunk-Granularity";
  28. static NSString *const kGTMSessionHeaderXGoogUploadCommand = @"X-Goog-Upload-Command";
  29. static NSString *const kGTMSessionHeaderXGoogUploadContentLength = @"X-Goog-Upload-Content-Length";
  30. static NSString *const kGTMSessionHeaderXGoogUploadContentType = @"X-Goog-Upload-Content-Type";
  31. static NSString *const kGTMSessionHeaderXGoogUploadOffset = @"X-Goog-Upload-Offset";
  32. static NSString *const kGTMSessionHeaderXGoogUploadProtocol = @"X-Goog-Upload-Protocol";
  33. static NSString *const kGTMSessionXGoogUploadProtocolResumable = @"resumable";
  34. static NSString *const kGTMSessionHeaderXGoogUploadSizeReceived = @"X-Goog-Upload-Size-Received";
  35. static NSString *const kGTMSessionHeaderXGoogUploadStatus = @"X-Goog-Upload-Status";
  36. static NSString *const kGTMSessionHeaderXGoogUploadURL = @"X-Goog-Upload-URL";
  37. // Property of chunk fetchers identifying the parent upload fetcher. Non-retained NSValue.
  38. static NSString *const kGTMSessionUploadFetcherChunkParentKey = @"_uploadFetcherChunkParent";
  39. int64_t const kGTMSessionUploadFetcherUnknownFileSize = -1;
  40. int64_t const kGTMSessionUploadFetcherStandardChunkSize = (int64_t)LLONG_MAX;
  41. #if TARGET_OS_IPHONE
  42. int64_t const kGTMSessionUploadFetcherMaximumDemandBufferSize = 10 * 1024 * 1024; // 10 MB for iOS, watchOS, tvOS
  43. #else
  44. int64_t const kGTMSessionUploadFetcherMaximumDemandBufferSize = 100 * 1024 * 1024; // 100 MB for macOS
  45. #endif
  46. typedef NS_ENUM(NSUInteger, GTMSessionUploadFetcherStatus) {
  47. kStatusUnknown,
  48. kStatusActive,
  49. kStatusFinal,
  50. kStatusCancelled,
  51. };
  52. NSString *const kGTMSessionFetcherUploadLocationObtainedNotification =
  53. @"kGTMSessionFetcherUploadLocationObtainedNotification";
  54. #if !GTMSESSION_BUILD_COMBINED_SOURCES
  55. @interface GTMSessionFetcher (ProtectedMethods)
  56. // Access to non-public method on the parent fetcher class.
  57. - (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks;
  58. - (void)createSessionIdentifierWithMetadata:(NSDictionary *)metadata;
  59. - (GTMSessionFetcherCompletionHandler)completionHandlerWithTarget:(id)target
  60. didFinishSelector:(SEL)finishedSelector;
  61. - (void)invokeOnCallbackQueue:(dispatch_queue_t)callbackQueue
  62. afterUserStopped:(BOOL)afterStopped
  63. block:(void (^)(void))block;
  64. - (NSTimer *)retryTimer;
  65. - (void)beginFetchForRetry;
  66. @property(readwrite, strong) NSData *downloadedData;
  67. - (void)releaseCallbacks;
  68. - (NSInteger)statusCodeUnsynchronized;
  69. - (BOOL)userStoppedFetching;
  70. @end
  71. #endif // !GTMSESSION_BUILD_COMBINED_SOURCES
  72. @interface GTMSessionUploadFetcher ()
  73. // Changing readonly to readwrite.
  74. @property(atomic, strong, readwrite) NSURLRequest *lastChunkRequest;
  75. @property(atomic, readwrite, assign) int64_t currentOffset;
  76. // Internal properties.
  77. @property(strong, atomic, GTM_NULLABLE) GTMSessionFetcher *fetcherInFlight; // Synchronized on self.
  78. @property(assign, atomic, getter=isSubdataGenerating) BOOL subdataGenerating;
  79. @property(assign, atomic) BOOL shouldInitiateOffsetQuery;
  80. @property(assign, atomic) int64_t uploadGranularity;
  81. @property(assign, atomic) BOOL allowsCellularAccess;
  82. @end
  83. @implementation GTMSessionUploadFetcher {
  84. GTMSessionFetcher *_chunkFetcher;
  85. // We'll call through to the delegate's completion handler.
  86. GTMSessionFetcherCompletionHandler _delegateCompletionHandler;
  87. dispatch_queue_t _delegateCallbackQueue;
  88. // The initial fetch's body length and bytes actually sent are
  89. // needed for calculating progress during subsequent chunk uploads
  90. int64_t _initialBodyLength;
  91. int64_t _initialBodySent;
  92. // The upload server address for the chunks of this upload session.
  93. NSURL *_uploadLocationURL;
  94. // _uploadData, _uploadDataProvider, or _uploadFileHandle may be set, but only one.
  95. NSData *_uploadData;
  96. NSFileHandle *_uploadFileHandle;
  97. GTMSessionUploadFetcherDataProvider _uploadDataProvider;
  98. NSURL *_uploadFileURL;
  99. int64_t _uploadFileLength;
  100. NSString *_uploadMIMEType;
  101. int64_t _chunkSize;
  102. int64_t _uploadGranularity;
  103. BOOL _isPaused;
  104. BOOL _isRestartedUpload;
  105. BOOL _shouldInitiateOffsetQuery;
  106. // Tied to useBackgroundSession property, since this property is applicable to chunk fetchers.
  107. BOOL _useBackgroundSessionOnChunkFetchers;
  108. // We keep the latest offset into the upload data just for progress reporting.
  109. int64_t _currentOffset;
  110. NSDictionary *_recentChunkReponseHeaders;
  111. NSInteger _recentChunkStatusCode;
  112. // For waiting, we need to know the fetcher in flight, if any, and if subdata generation
  113. // is in progress.
  114. GTMSessionFetcher *_fetcherInFlight;
  115. BOOL _isSubdataGenerating;
  116. BOOL _isCancelInFlight;
  117. GTMSessionUploadFetcherCancellationHandler _cancellationHandler;
  118. }
  119. + (void)load {
  120. [self uploadFetchersForBackgroundSessions];
  121. }
  122. + (instancetype)uploadFetcherWithRequest:(NSURLRequest *)request
  123. uploadMIMEType:(NSString *)uploadMIMEType
  124. chunkSize:(int64_t)chunkSize
  125. fetcherService:(GTMSessionFetcherService *)fetcherService {
  126. GTMSessionUploadFetcher *fetcher = [self uploadFetcherWithRequest:request
  127. fetcherService:fetcherService];
  128. [fetcher setLocationURL:nil
  129. uploadMIMEType:uploadMIMEType
  130. chunkSize:chunkSize
  131. allowsCellularAccess:request.allowsCellularAccess];
  132. return fetcher;
  133. }
  134. + (instancetype)uploadFetcherWithLocation:(NSURL *GTM_NULLABLE_TYPE)uploadLocationURL
  135. uploadMIMEType:(NSString *)uploadMIMEType
  136. chunkSize:(int64_t)chunkSize
  137. fetcherService:(GTM_NULLABLE GTMSessionFetcherService *)fetcherServiceOrNil {
  138. return [self uploadFetcherWithLocation:uploadLocationURL
  139. uploadMIMEType:uploadMIMEType
  140. chunkSize:chunkSize
  141. allowsCellularAccess:YES
  142. fetcherService:fetcherServiceOrNil];
  143. }
  144. + (instancetype)uploadFetcherWithLocation:(NSURL *GTM_NULLABLE_TYPE)uploadLocationURL
  145. uploadMIMEType:(NSString *)uploadMIMEType
  146. chunkSize:(int64_t)chunkSize
  147. allowsCellularAccess:(BOOL)allowsCellularAccess
  148. fetcherService:(GTMSessionFetcherService *)fetcherService {
  149. GTMSessionUploadFetcher *fetcher = [self uploadFetcherWithRequest:nil
  150. fetcherService:fetcherService];
  151. [fetcher setLocationURL:uploadLocationURL
  152. uploadMIMEType:uploadMIMEType
  153. chunkSize:chunkSize
  154. allowsCellularAccess:allowsCellularAccess];
  155. return fetcher;
  156. }
  157. + (instancetype)uploadFetcherForSessionIdentifierMetadata:(NSDictionary *)metadata {
  158. GTMSESSION_ASSERT_DEBUG(
  159. [metadata[kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey] boolValue],
  160. @"Session identifier metadata is not for an upload fetcher: %@", metadata);
  161. NSNumber *uploadFileLengthNum = metadata[kGTMSessionIdentifierUploadFileLengthMetadataKey];
  162. GTMSESSION_ASSERT_DEBUG(uploadFileLengthNum != nil,
  163. @"Session metadata missing an UploadFileSize");
  164. if (uploadFileLengthNum == nil) return nil;
  165. int64_t uploadFileLength = [uploadFileLengthNum longLongValue];
  166. GTMSESSION_ASSERT_DEBUG(uploadFileLength >= 0, @"Session metadata UploadFileSize is unknown");
  167. NSString *uploadFileURLString = metadata[kGTMSessionIdentifierUploadFileURLMetadataKey];
  168. GTMSESSION_ASSERT_DEBUG(uploadFileURLString, @"Session metadata missing an UploadFileURL");
  169. if (uploadFileURLString == nil) return nil;
  170. NSURL *uploadFileURL = [NSURL URLWithString:uploadFileURLString];
  171. // There used to be a call here to NSURL checkResourceIsReachableAndReturnError: to check for the
  172. // existence of the file (also tried NSFileManager fileExistsAtPath:). We've determined
  173. // empirically that the check can fail at startup even when the upload file does in fact exist.
  174. // For now, we'll go ahead and restore the background upload fetcher. If the file doesn't exist,
  175. // it will fail later.
  176. NSString *uploadLocationURLString = metadata[kGTMSessionIdentifierUploadLocationURLMetadataKey];
  177. NSURL *uploadLocationURL =
  178. uploadLocationURLString ? [NSURL URLWithString:uploadLocationURLString] : nil;
  179. NSString *uploadMIMEType =
  180. metadata[kGTMSessionIdentifierUploadMIMETypeMetadataKey];
  181. int64_t uploadChunkSize =
  182. [metadata[kGTMSessionIdentifierUploadChunkSizeMetadataKey] longLongValue];
  183. if (uploadChunkSize <= 0) {
  184. uploadChunkSize = kGTMSessionUploadFetcherStandardChunkSize;
  185. }
  186. int64_t currentOffset =
  187. [metadata[kGTMSessionIdentifierUploadCurrentOffsetMetadataKey] longLongValue];
  188. BOOL allowsCellularAccess = YES;
  189. if (metadata[kGTMSessionIdentifierUploadAllowsCellularAccess]) {
  190. allowsCellularAccess = [metadata[kGTMSessionIdentifierUploadAllowsCellularAccess] boolValue];
  191. }
  192. GTMSESSION_ASSERT_DEBUG(currentOffset <= uploadFileLength,
  193. @"CurrentOffset (%lld) exceeds UploadFileSize (%lld)",
  194. currentOffset, uploadFileLength);
  195. if (currentOffset > uploadFileLength) return nil;
  196. GTMSessionUploadFetcher *uploadFetcher = [self uploadFetcherWithLocation:uploadLocationURL
  197. uploadMIMEType:uploadMIMEType
  198. chunkSize:uploadChunkSize
  199. allowsCellularAccess:allowsCellularAccess
  200. fetcherService:nil];
  201. // Set the upload file length before setting the upload file URL tries to determine the length.
  202. [uploadFetcher setUploadFileLength:uploadFileLength];
  203. uploadFetcher.uploadFileURL = uploadFileURL;
  204. uploadFetcher.sessionUserInfo = metadata;
  205. uploadFetcher.useBackgroundSession = YES;
  206. uploadFetcher.currentOffset = currentOffset;
  207. uploadFetcher.delegateCallbackQueue = uploadFetcher.callbackQueue;
  208. uploadFetcher.allowedInsecureSchemes = @[ @"http" ]; // Allowed on restored upload fetcher.
  209. return uploadFetcher;
  210. }
  211. + (instancetype)uploadFetcherWithRequest:(NSURLRequest *)request
  212. fetcherService:(GTMSessionFetcherService *)fetcherService {
  213. // Internal utility method for instantiating fetchers
  214. GTMSessionUploadFetcher *fetcher;
  215. if ([fetcherService isKindOfClass:[GTMSessionFetcherService class]]) {
  216. fetcher = [fetcherService fetcherWithRequest:request
  217. fetcherClass:self];
  218. } else {
  219. fetcher = [self fetcherWithRequest:request];
  220. }
  221. fetcher.useBackgroundSession = YES;
  222. return fetcher;
  223. }
  224. + (NSPointerArray *)uploadFetcherPointerArrayForBackgroundSessions {
  225. static NSPointerArray *gUploadFetcherPointerArrayForBackgroundSessions = nil;
  226. static dispatch_once_t onceToken;
  227. dispatch_once(&onceToken, ^{
  228. gUploadFetcherPointerArrayForBackgroundSessions = [NSPointerArray weakObjectsPointerArray];
  229. });
  230. return gUploadFetcherPointerArrayForBackgroundSessions;
  231. }
  232. + (instancetype)uploadFetcherForSessionIdentifier:(NSString *)sessionIdentifier {
  233. GTMSESSION_ASSERT_DEBUG(sessionIdentifier != nil, @"Invalid session identifier");
  234. NSArray *uploadFetchersForBackgroundSessions = [self uploadFetchersForBackgroundSessions];
  235. for (GTMSessionUploadFetcher *uploadFetcher in uploadFetchersForBackgroundSessions) {
  236. if ([uploadFetcher.chunkFetcher.sessionIdentifier isEqual:sessionIdentifier]) {
  237. return uploadFetcher;
  238. }
  239. }
  240. return nil;
  241. }
  242. + (NSArray *)uploadFetchersForBackgroundSessions {
  243. NSMutableSet *restoredSessionIdentifiers = [[NSMutableSet alloc] init];
  244. NSMutableArray *uploadFetchers = [[NSMutableArray alloc] init];
  245. NSPointerArray *uploadFetcherPointerArray = [self uploadFetcherPointerArrayForBackgroundSessions];
  246. // Collect the background session upload fetchers that are still in memory.
  247. @synchronized(uploadFetcherPointerArray) {
  248. [uploadFetcherPointerArray compact];
  249. for (GTMSessionUploadFetcher *uploadFetcher in uploadFetcherPointerArray) {
  250. NSString *sessionIdentifier = uploadFetcher.chunkFetcher.sessionIdentifier;
  251. if (sessionIdentifier) {
  252. [restoredSessionIdentifiers addObject:sessionIdentifier];
  253. [uploadFetchers addObject:uploadFetcher];
  254. }
  255. }
  256. } // @synchronized(uploadFetcherPointerArray)
  257. // The system may have other ongoing background upload sessions. Restore upload fetchers for those
  258. // too.
  259. NSArray *fetchers = [GTMSessionFetcher fetchersForBackgroundSessions];
  260. for (GTMSessionFetcher *fetcher in fetchers) {
  261. NSString *sessionIdentifier = fetcher.sessionIdentifier;
  262. if (!sessionIdentifier || [restoredSessionIdentifiers containsObject:sessionIdentifier]) {
  263. continue;
  264. }
  265. NSDictionary *sessionIdentifierMetadata = [fetcher sessionIdentifierMetadata];
  266. if (sessionIdentifierMetadata == nil) {
  267. continue;
  268. }
  269. if (![sessionIdentifierMetadata[kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey] boolValue]) {
  270. continue;
  271. }
  272. GTMSessionUploadFetcher *uploadFetcher =
  273. [self uploadFetcherForSessionIdentifierMetadata:sessionIdentifierMetadata];
  274. if (uploadFetcher == nil) {
  275. // Something went wrong with this upload fetcher, so kill the restored chunk fetcher.
  276. [fetcher stopFetching];
  277. continue;
  278. }
  279. [uploadFetchers addObject:uploadFetcher];
  280. uploadFetcher->_chunkFetcher = fetcher;
  281. uploadFetcher->_fetcherInFlight = fetcher;
  282. [uploadFetcher attachSendProgressBlockToChunkFetcher:fetcher];
  283. fetcher.completionHandler =
  284. [fetcher completionHandlerWithTarget:uploadFetcher
  285. didFinishSelector:@selector(chunkFetcher:finishedWithData:error:)];
  286. GTMSESSION_LOG_DEBUG(@"%@ restoring upload fetcher %@ for chunk fetcher %@",
  287. [self class], uploadFetcher, fetcher);
  288. }
  289. return uploadFetchers;
  290. }
  291. - (void)setUploadData:(NSData *)data {
  292. BOOL changed = NO;
  293. @synchronized(self) {
  294. GTMSessionMonitorSynchronized(self);
  295. if (_uploadData != data) {
  296. _uploadData = data;
  297. changed = YES;
  298. }
  299. }
  300. if (changed) {
  301. [self setupRequestHeaders];
  302. }
  303. }
  304. - (NSData *)uploadData {
  305. @synchronized(self) {
  306. GTMSessionMonitorSynchronized(self);
  307. return _uploadData;
  308. }
  309. }
  310. - (void)setUploadFileHandle:(NSFileHandle *)fh {
  311. BOOL changed = NO;
  312. @synchronized(self) {
  313. GTMSessionMonitorSynchronized(self);
  314. if (_uploadFileHandle != fh) {
  315. _uploadFileHandle = fh;
  316. changed = YES;
  317. }
  318. }
  319. if (changed) {
  320. [self setupRequestHeaders];
  321. }
  322. }
  323. - (NSFileHandle *)uploadFileHandle {
  324. @synchronized(self) {
  325. GTMSessionMonitorSynchronized(self);
  326. return _uploadFileHandle;
  327. }
  328. }
  329. - (void)setUploadFileURL:(NSURL *)uploadURL {
  330. BOOL changed = NO;
  331. @synchronized(self) {
  332. GTMSessionMonitorSynchronized(self);
  333. if (_uploadFileURL != uploadURL) {
  334. _uploadFileURL = uploadURL;
  335. changed = YES;
  336. }
  337. }
  338. if (changed) {
  339. [self setupRequestHeaders];
  340. }
  341. }
  342. - (NSURL *)uploadFileURL {
  343. @synchronized(self) {
  344. GTMSessionMonitorSynchronized(self);
  345. return _uploadFileURL;
  346. }
  347. }
  348. - (void)setUploadFileLength:(int64_t)fullLength {
  349. @synchronized(self) {
  350. GTMSessionMonitorSynchronized(self);
  351. if (_uploadFileLength == kGTMSessionUploadFetcherUnknownFileSize &&
  352. fullLength != kGTMSessionUploadFetcherUnknownFileSize) {
  353. _uploadFileLength = fullLength;
  354. }
  355. }
  356. }
  357. - (void)setUploadDataLength:(int64_t)fullLength
  358. provider:(GTMSessionUploadFetcherDataProvider)block {
  359. @synchronized(self) {
  360. GTMSessionMonitorSynchronized(self);
  361. _uploadDataProvider = [block copy];
  362. _uploadFileLength = fullLength;
  363. }
  364. [self setupRequestHeaders];
  365. }
  366. - (GTMSessionUploadFetcherDataProvider)uploadDataProvider {
  367. @synchronized(self) {
  368. GTMSessionMonitorSynchronized(self);
  369. return _uploadDataProvider;
  370. }
  371. }
  372. - (void)setUploadMIMEType:(NSString *)uploadMIMEType {
  373. GTMSESSION_ASSERT_DEBUG(0, @"TODO: disallow setUploadMIMEType by making declaration readonly");
  374. // (and uploadMIMEType, chunksize, currentOffset)
  375. @synchronized(self) {
  376. GTMSessionMonitorSynchronized(self);
  377. _uploadMIMEType = uploadMIMEType;
  378. }
  379. }
  380. - (NSString *)uploadMIMEType {
  381. @synchronized(self) {
  382. GTMSessionMonitorSynchronized(self);
  383. return _uploadMIMEType;
  384. }
  385. }
  386. - (int64_t)chunkSize {
  387. @synchronized(self) {
  388. GTMSessionMonitorSynchronized(self);
  389. return _chunkSize;
  390. }
  391. }
  392. - (void)setupRequestHeaders {
  393. GTMSessionCheckNotSynchronized(self);
  394. #if DEBUG
  395. @synchronized(self) {
  396. GTMSessionMonitorSynchronized(self);
  397. int hasData = (_uploadData != nil) ? 1 : 0;
  398. int hasFileHandle = (_uploadFileHandle != nil) ? 1 : 0;
  399. int hasFileURL = (_uploadFileURL != nil) ? 1 : 0;
  400. int hasUploadDataProvider = (_uploadDataProvider != nil) ? 1 : 0;
  401. int numberOfSources = hasData + hasFileHandle + hasFileURL + hasUploadDataProvider;
  402. #pragma unused(numberOfSources)
  403. GTMSESSION_ASSERT_DEBUG(numberOfSources == 1,
  404. @"Need just one upload source (%d)", numberOfSources);
  405. } // @synchronized(self)
  406. #endif
  407. // Add our custom headers to the initial request indicating the data
  408. // type and total size to be delivered later in the chunk requests.
  409. NSMutableURLRequest *mutableRequest = [self.request mutableCopy];
  410. GTMSESSION_ASSERT_DEBUG((mutableRequest == nil) != (_uploadLocationURL == nil),
  411. @"Request and location are mutually exclusive");
  412. if (!mutableRequest) return;
  413. [mutableRequest setValue:kGTMSessionXGoogUploadProtocolResumable
  414. forHTTPHeaderField:kGTMSessionHeaderXGoogUploadProtocol];
  415. [mutableRequest setValue:@"start"
  416. forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand];
  417. [mutableRequest setValue:_uploadMIMEType
  418. forHTTPHeaderField:kGTMSessionHeaderXGoogUploadContentType];
  419. [mutableRequest setValue:@([self fullUploadLength]).stringValue
  420. forHTTPHeaderField:kGTMSessionHeaderXGoogUploadContentLength];
  421. NSString *method = mutableRequest.HTTPMethod;
  422. if (method == nil || [method caseInsensitiveCompare:@"GET"] == NSOrderedSame) {
  423. [mutableRequest setHTTPMethod:@"POST"];
  424. }
  425. // Ensure the user agent header identifies this to the upload server as a
  426. // GTMSessionUploadFetcher client. The /1 can be incremented in the unlikely circumstance
  427. // we need to make a bug fix in the client that the server can recognize.
  428. NSString *const kUserAgentStub = @"(GTMSUF/1)";
  429. NSString *userAgent = [mutableRequest valueForHTTPHeaderField:@"User-Agent"];
  430. if (userAgent == nil
  431. || [userAgent rangeOfString:kUserAgentStub].location == NSNotFound) {
  432. if (userAgent.length == 0) {
  433. userAgent = GTMFetcherStandardUserAgentString(nil);
  434. }
  435. userAgent = [userAgent stringByAppendingFormat:@" %@", kUserAgentStub];
  436. [mutableRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"];
  437. }
  438. [self setRequest:mutableRequest];
  439. }
  440. - (void)setLocationURL:(NSURL *GTM_NULLABLE_TYPE)location
  441. uploadMIMEType:(NSString *)uploadMIMEType
  442. chunkSize:(int64_t)chunkSize
  443. allowsCellularAccess:(BOOL)allowsCellularAccess {
  444. @synchronized(self) {
  445. GTMSessionMonitorSynchronized(self);
  446. GTMSESSION_ASSERT_DEBUG(chunkSize > 0, @"chunk size is zero");
  447. _allowsCellularAccess = allowsCellularAccess;
  448. // When resuming an upload, set the known upload target URL.
  449. _uploadLocationURL = location;
  450. _uploadMIMEType = uploadMIMEType;
  451. _chunkSize = chunkSize;
  452. // Indicate that we've not yet determined the file handle's length
  453. _uploadFileLength = kGTMSessionUploadFetcherUnknownFileSize;
  454. // Indicate that we've not yet determined the upload fetcher status
  455. _recentChunkStatusCode = -1;
  456. // If this is restarting an upload begun by another fetcher,
  457. // the location is specified but the request is nil
  458. _isRestartedUpload = (location != nil);
  459. } // @synchronized(self)
  460. }
  461. - (int64_t)fullUploadLength {
  462. int64_t result;
  463. @synchronized(self) {
  464. GTMSessionMonitorSynchronized(self);
  465. if (_uploadData) {
  466. result = (int64_t)_uploadData.length;
  467. } else {
  468. if (_uploadFileLength == kGTMSessionUploadFetcherUnknownFileSize) {
  469. if (_uploadFileHandle) {
  470. // First time through, seek to end to determine file length
  471. _uploadFileLength = (int64_t)[_uploadFileHandle seekToEndOfFile];
  472. } else if (_uploadDataProvider) {
  473. // _uploadFileLength is set when the _uploadDataProvider is set.
  474. GTMSESSION_ASSERT_DEBUG(_uploadFileLength >= 0, @"No uploadDataProvider length set");
  475. } else {
  476. NSNumber *filesizeNum;
  477. NSError *valueError;
  478. if ([_uploadFileURL getResourceValue:&filesizeNum
  479. forKey:NSURLFileSizeKey
  480. error:&valueError]) {
  481. _uploadFileLength = filesizeNum.longLongValue;
  482. } else {
  483. GTMSESSION_ASSERT_DEBUG(NO, @"Cannot get file size: %@\n %@",
  484. valueError, _uploadFileURL.path);
  485. _uploadFileLength = 0;
  486. }
  487. }
  488. }
  489. result = _uploadFileLength;
  490. }
  491. } // @synchronized(self)
  492. return result;
  493. }
  494. // Make a subdata of the upload data.
  495. - (void)generateChunkSubdataWithOffset:(int64_t)offset
  496. length:(int64_t)length
  497. response:(GTMSessionUploadFetcherDataProviderResponse)response {
  498. GTMSessionUploadFetcherDataProvider uploadDataProvider = self.uploadDataProvider;
  499. if (uploadDataProvider) {
  500. uploadDataProvider(offset, length, response);
  501. return;
  502. }
  503. NSData *uploadData = self.uploadData;
  504. if (uploadData) {
  505. // NSData provided.
  506. NSData *resultData;
  507. if (offset == 0 && length == (int64_t)uploadData.length) {
  508. resultData = uploadData;
  509. } else {
  510. int64_t dataLength = (int64_t)uploadData.length;
  511. // Ensure our range is valid. b/18007814
  512. if (offset + length > dataLength) {
  513. NSString *errorMessage = [NSString stringWithFormat:
  514. @"Range invalid for upload data. offset: %lld\tlength: %lld\tdataLength: %lld",
  515. offset, length, dataLength];
  516. GTMSESSION_ASSERT_DEBUG(NO, @"%@", errorMessage);
  517. response(nil,
  518. kGTMSessionUploadFetcherUnknownFileSize,
  519. [self uploadChunkUnavailableErrorWithDescription:errorMessage]);
  520. return;
  521. }
  522. NSRange range = NSMakeRange((NSUInteger)offset, (NSUInteger)length);
  523. @try {
  524. resultData = [uploadData subdataWithRange:range];
  525. }
  526. @catch (NSException *exception) {
  527. NSString *errorMessage = exception.description;
  528. GTMSESSION_ASSERT_DEBUG(NO, @"%@", errorMessage);
  529. response(nil,
  530. kGTMSessionUploadFetcherUnknownFileSize,
  531. [self uploadChunkUnavailableErrorWithDescription:errorMessage]);
  532. return;
  533. }
  534. }
  535. response(resultData, kGTMSessionUploadFetcherUnknownFileSize, nil);
  536. return;
  537. }
  538. NSURL *uploadFileURL = self.uploadFileURL;
  539. if (uploadFileURL) {
  540. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  541. [self generateChunkSubdataFromFileURL:uploadFileURL
  542. offset:offset
  543. length:length
  544. response:response];
  545. });
  546. return;
  547. }
  548. GTMSESSION_ASSERT_DEBUG(_uploadFileHandle, @"Unexpectedly missing upload data package");
  549. NSFileHandle *uploadFileHandle = self.uploadFileHandle;
  550. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  551. [self generateChunkSubdataFromFileHandle:uploadFileHandle
  552. offset:offset
  553. length:length
  554. response:response];
  555. });
  556. }
  557. - (void)generateChunkSubdataFromFileHandle:(NSFileHandle *)fileHandle
  558. offset:(int64_t)offset
  559. length:(int64_t)length
  560. response:(GTMSessionUploadFetcherDataProviderResponse)response {
  561. NSData *resultData;
  562. NSError *error;
  563. @try {
  564. [fileHandle seekToFileOffset:(unsigned long long)offset];
  565. resultData = [fileHandle readDataOfLength:(NSUInteger)length];
  566. }
  567. @catch (NSException *exception) {
  568. GTMSESSION_ASSERT_DEBUG(NO, @"uploadFileHandle failed to read, %@", exception);
  569. error = [self uploadChunkUnavailableErrorWithDescription:exception.description];
  570. }
  571. // The response always re-dispatches to the main thread, so we skip doing that here.
  572. response(resultData, kGTMSessionUploadFetcherUnknownFileSize, error);
  573. }
  574. - (void)generateChunkSubdataFromFileURL:(NSURL *)fileURL
  575. offset:(int64_t)offset
  576. length:(int64_t)length
  577. response:(GTMSessionUploadFetcherDataProviderResponse)response {
  578. GTMSessionCheckNotSynchronized(self);
  579. NSData *resultData;
  580. NSError *error;
  581. int64_t fullUploadLength = [self fullUploadLength];
  582. NSData *mappedData =
  583. [NSData dataWithContentsOfURL:fileURL
  584. options:NSDataReadingMappedAlways + NSDataReadingUncached
  585. error:&error];
  586. if (!mappedData) {
  587. // We could not create an NSData by memory-mapping the file.
  588. #if TARGET_IPHONE_SIMULATOR
  589. // NSTemporaryDirectory() can differ in the simulator between app restarts,
  590. // yet the contents for the new path remains unchanged, so try the latest temp path.
  591. if ([error.domain isEqual:NSCocoaErrorDomain] && (error.code == NSFileReadNoSuchFileError)) {
  592. NSString *filename = [fileURL lastPathComponent];
  593. NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:filename];
  594. NSURL *newFileURL = [NSURL fileURLWithPath:filePath];
  595. if (![newFileURL isEqual:fileURL]) {
  596. [self generateChunkSubdataFromFileURL:newFileURL
  597. offset:offset
  598. length:length
  599. response:response];
  600. return;
  601. }
  602. }
  603. #endif
  604. // If the file is just too large to create an NSData for, or if for some other reason we can't
  605. // map it, create an NSFileHandle instead to read a subset into an NSData.
  606. #if DEBUG
  607. NSNumber *fileSizeNum;
  608. BOOL hasFileSize = [fileURL getResourceValue:&fileSizeNum forKey:NSURLFileSizeKey error:NULL];
  609. GTMSESSION_LOG_DEBUG(@"Note: uploadFileURL is falling back to creating upload chunks by reading"
  610. @" an NSFileHandle since uploadFileURL failed to map the upload file,"
  611. @" file size %@, %@",
  612. hasFileSize ? fileSizeNum : @"unknown", error);
  613. #endif
  614. NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingFromURL:fileURL
  615. error:&error];
  616. if (fileHandle != nil) {
  617. [self generateChunkSubdataFromFileHandle:fileHandle
  618. offset:offset
  619. length:length
  620. response:response];
  621. return;
  622. }
  623. GTMSESSION_ASSERT_DEBUG(NO, @"uploadFileURL failed to read, %@", error);
  624. // Fall through with the error.
  625. } else {
  626. // Successfully created an NSData by memory-mapping the file.
  627. if ((NSUInteger)(offset + length) > mappedData.length) {
  628. NSString *errorMessage = [NSString stringWithFormat:
  629. @"Range invalid for upload data. offset: %lld\tlength: %lld\tdataLength: %lld\texpected UploadLength: %lld",
  630. offset, length, (long long)mappedData.length, fullUploadLength];
  631. GTMSESSION_ASSERT_DEBUG(NO, @"%@", errorMessage);
  632. response(nil,
  633. kGTMSessionUploadFetcherUnknownFileSize,
  634. [self uploadChunkUnavailableErrorWithDescription:errorMessage]);
  635. return;
  636. }
  637. if (offset > 0 || length < fullUploadLength) {
  638. NSRange range = NSMakeRange((NSUInteger)offset, (NSUInteger)length);
  639. resultData = [mappedData subdataWithRange:range];
  640. } else {
  641. resultData = mappedData;
  642. }
  643. }
  644. // The response always re-dispatches to the main thread, so we skip re-dispatching here.
  645. response(resultData, kGTMSessionUploadFetcherUnknownFileSize, error);
  646. }
  647. - (NSError *)uploadChunkUnavailableErrorWithDescription:(NSString *)description {
  648. // The description in the userInfo is intended as a clue to programmers, not
  649. // for client code to examine or rely on.
  650. NSDictionary *userInfo = @{ @"description" : description };
  651. return [NSError errorWithDomain:kGTMSessionFetcherErrorDomain
  652. code:GTMSessionFetcherErrorUploadChunkUnavailable
  653. userInfo:userInfo];
  654. }
  655. - (NSError *)prematureFailureErrorWithUserInfo:(NSDictionary *)userInfo {
  656. // An error for if we get an unexpected status from the upload server or
  657. // otherwise cannot continue. This is an issue beyond the upload protocol;
  658. // there's no way the client can do anything useful except give up.
  659. NSError *error = [NSError errorWithDomain:kGTMSessionFetcherStatusDomain
  660. code:501 // Not implemented
  661. userInfo:userInfo];
  662. return error;
  663. }
  664. + (GTMSessionUploadFetcherStatus)uploadStatusFromResponseHeaders:(NSDictionary *)responseHeaders {
  665. NSString *statusString = [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadStatus];
  666. if ([statusString isEqual:@"active"]) {
  667. return kStatusActive;
  668. }
  669. if ([statusString isEqual:@"final"]) {
  670. return kStatusFinal;
  671. }
  672. if ([statusString isEqual:@"cancelled"]) {
  673. return kStatusCancelled;
  674. }
  675. return kStatusUnknown;
  676. }
  677. #pragma mark Method overrides affecting the initial fetch only
  678. - (void)setCompletionHandler:(GTMSessionFetcherCompletionHandler)handler {
  679. @synchronized(self) {
  680. GTMSessionMonitorSynchronized(self);
  681. _delegateCompletionHandler = handler;
  682. }
  683. }
  684. - (void)setDelegateCallbackQueue:(dispatch_queue_t GTM_NULLABLE_TYPE)queue {
  685. @synchronized(self) {
  686. GTMSessionMonitorSynchronized(self);
  687. _delegateCallbackQueue = queue;
  688. }
  689. }
  690. - (dispatch_queue_t GTM_NULLABLE_TYPE)delegateCallbackQueue {
  691. @synchronized(self) {
  692. GTMSessionMonitorSynchronized(self);
  693. return _delegateCallbackQueue;
  694. }
  695. }
  696. - (BOOL)isRestartedUpload {
  697. @synchronized(self) {
  698. GTMSessionMonitorSynchronized(self);
  699. return _isRestartedUpload;
  700. }
  701. }
  702. - (GTMSessionFetcher * GTM_NULLABLE_TYPE)chunkFetcher {
  703. @synchronized(self) {
  704. GTMSessionMonitorSynchronized(self);
  705. return _chunkFetcher;
  706. }
  707. }
  708. - (void)setChunkFetcher:(GTMSessionFetcher * GTM_NULLABLE_TYPE)fetcher {
  709. @synchronized(self) {
  710. GTMSessionMonitorSynchronized(self);
  711. _chunkFetcher = fetcher;
  712. }
  713. }
  714. - (void)setFetcherInFlight:(GTMSessionFetcher * GTM_NULLABLE_TYPE)fetcher {
  715. @synchronized(self) {
  716. GTMSessionMonitorSynchronized(self);
  717. _fetcherInFlight = fetcher;
  718. }
  719. }
  720. - (GTMSessionFetcher * GTM_NULLABLE_TYPE)fetcherInFlight {
  721. @synchronized(self) {
  722. GTMSessionMonitorSynchronized(self);
  723. return _fetcherInFlight;
  724. }
  725. }
  726. - (void)setCancellationHandler:(GTMSessionUploadFetcherCancellationHandler GTM_NULLABLE_TYPE)
  727. cancellationHandler {
  728. @synchronized(self) {
  729. GTMSessionMonitorSynchronized(self);
  730. _cancellationHandler = cancellationHandler;
  731. }
  732. }
  733. - (GTMSessionUploadFetcherCancellationHandler GTM_NULLABLE_TYPE)cancellationHandler {
  734. @synchronized(self) {
  735. GTMSessionMonitorSynchronized(self);
  736. return _cancellationHandler;
  737. }
  738. }
  739. - (void)beginFetchForRetry {
  740. GTMSessionCheckNotSynchronized(self);
  741. // Override the superclass to reset the initial body length and fetcher-in-flight,
  742. // then call the superclass implementation.
  743. [self setInitialBodyLength:[self bodyLength]];
  744. GTMSESSION_ASSERT_DEBUG(self.fetcherInFlight == nil, @"unexpected fetcher in flight: %@",
  745. self.fetcherInFlight);
  746. self.fetcherInFlight = self;
  747. [super beginFetchForRetry];
  748. }
  749. - (void)beginFetchWithCompletionHandler:(GTMSessionFetcherCompletionHandler)handler {
  750. GTMSessionCheckNotSynchronized(self);
  751. [self setInitialBodyLength:[self bodyLength]];
  752. // We'll hold onto the superclass's callback queue so we can invoke the handler
  753. // even after the superclass has released the queue and its callback handler, as
  754. // happens during auth failure.
  755. [self setDelegateCallbackQueue:self.callbackQueue];
  756. self.completionHandler = handler;
  757. if ([self isRestartedUpload]) {
  758. // When restarting an upload, we know the destination location for chunk fetches,
  759. // but we need to query to find the initial offset.
  760. if (![self isPaused]) {
  761. [self sendQueryForUploadOffsetWithFetcherProperties:self.properties];
  762. }
  763. return;
  764. }
  765. // We don't want to call into the client's completion block immediately
  766. // after the finish of the initial connection (the delegate is called only
  767. // when uploading finishes), so we substitute our own completion block to be
  768. // called when the initial connection finishes
  769. GTMSESSION_ASSERT_DEBUG(self.fetcherInFlight == nil, @"unexpected fetcher in flight: %@",
  770. self.fetcherInFlight);
  771. self.fetcherInFlight = self;
  772. [super beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  773. self.fetcherInFlight = nil;
  774. // callback
  775. BOOL hasTestBlock = (self.testBlock != nil);
  776. if (![self isRestartedUpload] && !hasTestBlock) {
  777. if (error == nil) {
  778. [self beginChunkFetches];
  779. } else {
  780. if ([self retryTimer] == nil) {
  781. [self invokeFinalCallbackWithData:nil
  782. error:error
  783. shouldInvalidateLocation:YES];
  784. }
  785. }
  786. } else {
  787. // If there was no initial request, then this fetch is resuming some
  788. // other uploadFetcher's initial request, and the superclass's connection
  789. // is never used, so at this point we call the user's actual completion
  790. // block.
  791. if (!hasTestBlock) {
  792. [self invokeFinalCallbackWithData:data
  793. error:error
  794. shouldInvalidateLocation:YES];
  795. } else {
  796. // There was a test block, so we won't do chunk fetches, but we simulate obtaining
  797. // the data to be uploaded from the upload data provider block or the file handle,
  798. // and then call back.
  799. [self generateChunkSubdataWithOffset:0
  800. length:[self fullUploadLength]
  801. response:^(NSData *generateData, int64_t fullUploadLength, NSError *generateError) {
  802. [self invokeFinalCallbackWithData:data
  803. error:error
  804. shouldInvalidateLocation:YES];
  805. }];
  806. }
  807. }
  808. }];
  809. }
  810. - (void)beginChunkFetches {
  811. GTMSessionCheckNotSynchronized(self);
  812. #if DEBUG
  813. // The initial response of the resumable upload protocol should have an
  814. // empty body
  815. //
  816. // This assert typically happens because the upload create/edit link URL was
  817. // not supplied with the request, and the server is thus expecting a non-
  818. // resumable request/response.
  819. if (self.downloadedData.length > 0) {
  820. NSData *downloadedData = self.downloadedData;
  821. NSString *str = [[NSString alloc] initWithData:downloadedData
  822. encoding:NSUTF8StringEncoding];
  823. #pragma unused(str)
  824. GTMSESSION_ASSERT_DEBUG(NO, @"unexpected response data (uploading to the wrong URL?)\n%@", str);
  825. }
  826. #endif
  827. // We need to get the upload URL from the location header to continue.
  828. NSDictionary *responseHeaders = [self responseHeaders];
  829. [self retrieveUploadChunkGranularityFromResponseHeaders:responseHeaders];
  830. GTMSessionUploadFetcherStatus uploadStatus =
  831. [[self class] uploadStatusFromResponseHeaders:responseHeaders];
  832. GTMSESSION_ASSERT_DEBUG(uploadStatus != kStatusUnknown,
  833. @"beginChunkFetches has unexpected upload status for headers %@", responseHeaders);
  834. BOOL isPrematureStop = (uploadStatus == kStatusFinal) || (uploadStatus == kStatusCancelled);
  835. NSString *uploadLocationURLStr = [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadURL];
  836. BOOL hasUploadLocation = (uploadLocationURLStr.length > 0);
  837. if (isPrematureStop || !hasUploadLocation) {
  838. GTMSESSION_ASSERT_DEBUG(NO, @"Premature failure: upload-status:\"%@\" location:%@",
  839. [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadStatus], uploadLocationURLStr);
  840. // We cannot continue since we do not know the location to use
  841. // as our upload destination.
  842. NSDictionary *userInfo = nil;
  843. NSData *downloadedData = self.downloadedData;
  844. if (downloadedData.length > 0) {
  845. userInfo = @{ kGTMSessionFetcherStatusDataKey : downloadedData };
  846. }
  847. NSError *failureError = [self prematureFailureErrorWithUserInfo:userInfo];
  848. [self invokeFinalCallbackWithData:nil
  849. error:failureError
  850. shouldInvalidateLocation:YES];
  851. return;
  852. }
  853. self.uploadLocationURL = [NSURL URLWithString:uploadLocationURLStr];
  854. NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  855. [nc postNotificationName:kGTMSessionFetcherUploadLocationObtainedNotification
  856. object:self];
  857. // we've now sent all of the initial post body data, so we need to include
  858. // its size in future progress indicator callbacks
  859. [self setInitialBodySent:[self initialBodyLength]];
  860. // just in case the user paused us during the initial fetch...
  861. if (![self isPaused]) {
  862. [self uploadNextChunkWithOffset:0];
  863. }
  864. }
  865. - (void)URLSession:(NSURLSession *)session
  866. task:(NSURLSessionTask *)task
  867. didSendBodyData:(int64_t)bytesSent
  868. totalBytesSent:(int64_t)totalBytesSent
  869. totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
  870. // Overrides the superclass.
  871. [self invokeDelegateWithDidSendBytes:bytesSent
  872. totalBytesSent:totalBytesSent
  873. totalBytesExpectedToSend:totalBytesExpectedToSend + [self fullUploadLength]];
  874. }
  875. - (BOOL)shouldReleaseCallbacksUponCompletion {
  876. // Overrides the superclass.
  877. // We don't want the superclass to release the delegate and callback
  878. // blocks once the initial fetch has finished
  879. //
  880. // This is invoked for only successful completion of the connection;
  881. // an error always will invoke and release the callbacks
  882. return NO;
  883. }
  884. - (void)invokeFinalCallbackWithData:(NSData *)data
  885. error:(NSError *)error
  886. shouldInvalidateLocation:(BOOL)shouldInvalidateLocation {
  887. @synchronized(self) {
  888. GTMSessionMonitorSynchronized(self);
  889. if (shouldInvalidateLocation) {
  890. _uploadLocationURL = nil;
  891. }
  892. dispatch_queue_t queue = _delegateCallbackQueue;
  893. GTMSessionFetcherCompletionHandler handler = _delegateCompletionHandler;
  894. if (queue && handler) {
  895. [self invokeOnCallbackQueue:queue
  896. afterUserStopped:NO
  897. block:^{
  898. handler(data, error);
  899. }];
  900. }
  901. } // @synchronized(self)
  902. [self releaseUploadAndBaseCallbacks:!self.userStoppedFetching];
  903. }
  904. - (void)releaseUploadAndBaseCallbacks:(BOOL)shouldReleaseCancellation {
  905. @synchronized(self) {
  906. GTMSessionMonitorSynchronized(self);
  907. _delegateCallbackQueue = nil;
  908. _delegateCompletionHandler = nil;
  909. _uploadDataProvider = nil;
  910. if (shouldReleaseCancellation) {
  911. _cancellationHandler = nil;
  912. }
  913. }
  914. // Release the base class's callbacks, too, if needed.
  915. [self releaseCallbacks];
  916. }
  917. - (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks {
  918. GTMSessionCheckNotSynchronized(self);
  919. // Clear _fetcherInFlight when stopped. Moved from stopFetching, since that's a public method,
  920. // where this method does the work. Fixes issue clearing value when retryBlock included.
  921. GTMSessionFetcher *fetcherInFlight = self.fetcherInFlight;
  922. if (fetcherInFlight == self) {
  923. self.fetcherInFlight = nil;
  924. }
  925. [super stopFetchReleasingCallbacks:shouldReleaseCallbacks];
  926. if (shouldReleaseCallbacks) {
  927. [self releaseUploadAndBaseCallbacks:NO];
  928. }
  929. }
  930. #pragma mark Chunk fetching methods
  931. - (void)uploadNextChunkWithOffset:(int64_t)offset {
  932. // use the properties in each chunk fetcher
  933. NSDictionary *props = [self properties];
  934. [self uploadNextChunkWithOffset:offset
  935. fetcherProperties:props];
  936. }
  937. - (void)sendQueryForUploadOffsetWithFetcherProperties:(NSDictionary *)props {
  938. GTMSessionFetcher *queryFetcher = [self uploadFetcherWithProperties:props
  939. isQueryFetch:YES];
  940. queryFetcher.bodyData = [NSData data];
  941. NSString *originalComment = self.comment;
  942. [queryFetcher setCommentWithFormat:@"%@ (query offset)",
  943. originalComment ? originalComment : @"upload"];
  944. [queryFetcher setRequestValue:@"query" forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand];
  945. self.fetcherInFlight = queryFetcher;
  946. [queryFetcher beginFetchWithDelegate:self
  947. didFinishSelector:@selector(queryFetcher:finishedWithData:error:)];
  948. }
  949. - (void)queryFetcher:(GTMSessionFetcher *)queryFetcher
  950. finishedWithData:(NSData *)data
  951. error:(NSError *)error {
  952. self.fetcherInFlight = nil;
  953. NSDictionary *responseHeaders = [queryFetcher responseHeaders];
  954. NSString *sizeReceivedHeader;
  955. GTMSessionUploadFetcherStatus uploadStatus =
  956. [[self class] uploadStatusFromResponseHeaders:responseHeaders];
  957. GTMSESSION_ASSERT_DEBUG(uploadStatus != kStatusUnknown || error != nil,
  958. @"query fetcher completion has unexpected upload status for headers %@", responseHeaders);
  959. if (error == nil) {
  960. sizeReceivedHeader = [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadSizeReceived];
  961. if (uploadStatus == kStatusCancelled ||
  962. (uploadStatus == kStatusActive && sizeReceivedHeader == nil)) {
  963. NSDictionary *userInfo = nil;
  964. if (data.length > 0) {
  965. userInfo = @{ kGTMSessionFetcherStatusDataKey : data };
  966. }
  967. error = [self prematureFailureErrorWithUserInfo:userInfo];
  968. }
  969. }
  970. if (error == nil) {
  971. int64_t offset = [sizeReceivedHeader longLongValue];
  972. int64_t fullUploadLength = [self fullUploadLength];
  973. if (uploadStatus == kStatusFinal ||
  974. (offset >= fullUploadLength &&
  975. fullUploadLength != kGTMSessionUploadFetcherUnknownFileSize)) {
  976. // Handle we're done
  977. [self chunkFetcher:queryFetcher finishedWithData:data error:nil];
  978. } else {
  979. [self retrieveUploadChunkGranularityFromResponseHeaders:responseHeaders];
  980. [self uploadNextChunkWithOffset:offset];
  981. }
  982. } else {
  983. // Handle query error
  984. [self chunkFetcher:queryFetcher finishedWithData:data error:error];
  985. }
  986. }
  987. - (void)sendCancelUploadWithFetcherProperties:(NSDictionary *)props {
  988. @synchronized(self) {
  989. _isCancelInFlight = YES;
  990. }
  991. GTMSessionFetcher *cancelFetcher = [self uploadFetcherWithProperties:props
  992. isQueryFetch:YES];
  993. cancelFetcher.bodyData = [NSData data];
  994. NSString *originalComment = self.comment;
  995. [cancelFetcher setCommentWithFormat:@"%@ (cancel)",
  996. originalComment ? originalComment : @"upload"];
  997. [cancelFetcher setRequestValue:@"cancel" forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand];
  998. self.fetcherInFlight = cancelFetcher;
  999. [cancelFetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  1000. self.fetcherInFlight = nil;
  1001. if (![self triggerCancellationHandlerForFetch:cancelFetcher data:data error:error]) {
  1002. if (error) {
  1003. GTMSESSION_LOG_DEBUG(@"cancelFetcher %@", error);
  1004. }
  1005. }
  1006. @synchronized(self) {
  1007. self->_isCancelInFlight = NO;
  1008. }
  1009. }];
  1010. }
  1011. - (void)uploadNextChunkWithOffset:(int64_t)offset
  1012. fetcherProperties:(NSDictionary *)props {
  1013. GTMSessionCheckNotSynchronized(self);
  1014. // Example chunk headers:
  1015. // X-Goog-Upload-Command: upload, finalize
  1016. // X-Goog-Upload-Offset: 0
  1017. // Content-Length: 2000000
  1018. // Content-Type: image/jpeg
  1019. //
  1020. // {bytes 0-1999999}
  1021. // The chunk upload URL requires no authentication header.
  1022. GTMSessionFetcher *chunkFetcher = [self uploadFetcherWithProperties:props
  1023. isQueryFetch:NO];
  1024. [self attachSendProgressBlockToChunkFetcher:chunkFetcher];
  1025. int64_t chunkSize = [self updateChunkFetcher:chunkFetcher
  1026. forChunkAtOffset:offset];
  1027. BOOL isUploadingFileURL = (self.uploadFileURL != nil);
  1028. int64_t fullUploadLength = [self fullUploadLength];
  1029. // The chunk size may have changed, so determine again if we're uploading the full file.
  1030. BOOL isUploadingFullFile = (offset == 0 &&
  1031. fullUploadLength != kGTMSessionUploadFetcherUnknownFileSize &&
  1032. chunkSize >= fullUploadLength);
  1033. if (isUploadingFullFile && isUploadingFileURL) {
  1034. // The data is the full upload file URL.
  1035. chunkFetcher.bodyFileURL = self.uploadFileURL;
  1036. [self beginChunkFetcher:chunkFetcher
  1037. offset:offset];
  1038. } else {
  1039. // Make an NSData for the subset for this upload chunk.
  1040. self.subdataGenerating = YES;
  1041. [self generateChunkSubdataWithOffset:offset
  1042. length:chunkSize
  1043. response:^(NSData *chunkData, int64_t uploadFileLength, NSError *chunkError) {
  1044. // The subdata methods may leave us on a background thread.
  1045. dispatch_async(dispatch_get_main_queue(), ^{
  1046. self.subdataGenerating = NO;
  1047. // dont allow the updating of fileLength for uploads not using a data provider as they
  1048. // should know the file length before the upload starts.
  1049. if (self->_uploadDataProvider != nil && uploadFileLength > 0) {
  1050. [self setUploadFileLength:uploadFileLength];
  1051. // Update the command and content-length headers if this is the last chunk to be sent.
  1052. if (offset + chunkSize >= uploadFileLength) {
  1053. int64_t updatedChunkSize = [self updateChunkFetcher:chunkFetcher
  1054. forChunkAtOffset:offset];
  1055. if (updatedChunkSize == 0) {
  1056. // Calling beginChunkFetcher early when there is no more data to send allows us to
  1057. // properly handle nil chunkData below without having to account for the case where
  1058. // we are just finalizing the file.
  1059. chunkFetcher.bodyData = [[NSData alloc] init];
  1060. [self beginChunkFetcher:chunkFetcher
  1061. offset:offset];
  1062. return;
  1063. }
  1064. }
  1065. }
  1066. if (chunkData == nil) {
  1067. NSError *responseError = chunkError;
  1068. if (!responseError) {
  1069. responseError = [self uploadChunkUnavailableErrorWithDescription:@"chunkData is nil"];
  1070. }
  1071. [self invokeFinalCallbackWithData:nil
  1072. error:responseError
  1073. shouldInvalidateLocation:YES];
  1074. return;
  1075. }
  1076. BOOL didWriteFile = NO;
  1077. if (isUploadingFileURL) {
  1078. // Make a temporary file with the data subset.
  1079. NSString *tempName =
  1080. [NSString stringWithFormat:@"GTMUpload_temp_%@", [[NSUUID UUID] UUIDString]];
  1081. NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:tempName];
  1082. NSError *writeError;
  1083. didWriteFile = [chunkData writeToFile:tempPath
  1084. options:NSDataWritingAtomic
  1085. error:&writeError];
  1086. if (didWriteFile) {
  1087. chunkFetcher.bodyFileURL = [NSURL fileURLWithPath:tempPath];
  1088. } else {
  1089. GTMSESSION_LOG_DEBUG(@"writeToFile failed: %@\n%@", writeError, tempPath);
  1090. }
  1091. }
  1092. if (!didWriteFile) {
  1093. chunkFetcher.bodyData = [chunkData copy];
  1094. }
  1095. [self beginChunkFetcher:chunkFetcher
  1096. offset:offset];
  1097. });
  1098. }];
  1099. }
  1100. }
  1101. - (void)beginChunkFetcher:(GTMSessionFetcher *)chunkFetcher
  1102. offset:(int64_t)offset {
  1103. // Track the current offset for progress reporting
  1104. self.currentOffset = offset;
  1105. // Hang on to the fetcher in case we need to cancel it. We set these before beginning the
  1106. // chunk fetch so the observers notified of chunk fetches can inspect the upload fetcher to
  1107. // match to the chunk.
  1108. self.chunkFetcher = chunkFetcher;
  1109. self.fetcherInFlight = chunkFetcher;
  1110. // Update the last chunk request, including any request headers.
  1111. self.lastChunkRequest = chunkFetcher.request;
  1112. [chunkFetcher beginFetchWithDelegate:self
  1113. didFinishSelector:@selector(chunkFetcher:finishedWithData:error:)];
  1114. }
  1115. - (void)attachSendProgressBlockToChunkFetcher:(GTMSessionFetcher *)chunkFetcher {
  1116. chunkFetcher.sendProgressBlock = ^(int64_t bytesSent, int64_t totalBytesSent,
  1117. int64_t totalBytesExpectedToSend) {
  1118. // The total bytes expected include the initial body and the full chunked
  1119. // data, independent of how big this fetcher's chunk is.
  1120. int64_t initialBodySent = [self bodyLength]; // TODO(grobbins) use [self initialBodySent]
  1121. int64_t totalSent = initialBodySent + self.currentOffset + totalBytesSent;
  1122. int64_t totalExpected = initialBodySent + [self fullUploadLength];
  1123. [self invokeDelegateWithDidSendBytes:bytesSent
  1124. totalBytesSent:totalSent
  1125. totalBytesExpectedToSend:totalExpected];
  1126. };
  1127. }
  1128. - (NSDictionary *)uploadSessionIdentifierMetadata {
  1129. NSMutableDictionary *metadata = [NSMutableDictionary dictionary];
  1130. metadata[kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey] = @YES;
  1131. GTMSESSION_ASSERT_DEBUG(self.uploadFileURL,
  1132. @"Invalid upload fetcher to create session identifier for metadata");
  1133. metadata[kGTMSessionIdentifierUploadFileURLMetadataKey] = [self.uploadFileURL absoluteString];
  1134. metadata[kGTMSessionIdentifierUploadFileLengthMetadataKey] = @([self fullUploadLength]);
  1135. if (self.uploadLocationURL) {
  1136. metadata[kGTMSessionIdentifierUploadLocationURLMetadataKey] =
  1137. [self.uploadLocationURL absoluteString];
  1138. }
  1139. if (self.uploadMIMEType) {
  1140. metadata[kGTMSessionIdentifierUploadMIMETypeMetadataKey] = self.uploadMIMEType;
  1141. }
  1142. metadata[kGTMSessionIdentifierUploadChunkSizeMetadataKey] = @(self.chunkSize);
  1143. metadata[kGTMSessionIdentifierUploadCurrentOffsetMetadataKey] = @(self.currentOffset);
  1144. metadata[kGTMSessionIdentifierUploadAllowsCellularAccess] = @(self.request.allowsCellularAccess);
  1145. return metadata;
  1146. }
  1147. - (GTMSessionFetcher *)uploadFetcherWithProperties:(NSDictionary *)properties
  1148. isQueryFetch:(BOOL)isQueryFetch {
  1149. GTMSessionCheckNotSynchronized(self);
  1150. // Common code to make a request for a query command or for a chunk upload.
  1151. NSURL *uploadLocationURL = self.uploadLocationURL;
  1152. NSMutableURLRequest *chunkRequest = [NSMutableURLRequest requestWithURL:uploadLocationURL];
  1153. [chunkRequest setHTTPMethod:@"PUT"];
  1154. // copy the user-agent from the original connection
  1155. // n.b. that self.request is nil for upload fetchers created with an existing upload location
  1156. // URL.
  1157. NSURLRequest *origRequest = self.request;
  1158. chunkRequest.allowsCellularAccess = origRequest.allowsCellularAccess;
  1159. if (!origRequest) {
  1160. chunkRequest.allowsCellularAccess = _allowsCellularAccess;
  1161. }
  1162. NSString *userAgent = [origRequest valueForHTTPHeaderField:@"User-Agent"];
  1163. if (userAgent.length > 0) {
  1164. [chunkRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"];
  1165. }
  1166. [chunkRequest setValue:kGTMSessionXGoogUploadProtocolResumable
  1167. forHTTPHeaderField:kGTMSessionHeaderXGoogUploadProtocol];
  1168. // To avoid timeouts when debugging, copy the timeout of the initial fetcher.
  1169. NSTimeInterval origTimeout = [origRequest timeoutInterval];
  1170. [chunkRequest setTimeoutInterval:origTimeout];
  1171. //
  1172. // Make a new chunk fetcher.
  1173. //
  1174. GTMSessionFetcher *chunkFetcher = [GTMSessionFetcher fetcherWithRequest:chunkRequest];
  1175. chunkFetcher.callbackQueue = self.callbackQueue;
  1176. chunkFetcher.sessionUserInfo = self.sessionUserInfo;
  1177. chunkFetcher.configurationBlock = self.configurationBlock;
  1178. chunkFetcher.allowedInsecureSchemes = self.allowedInsecureSchemes;
  1179. chunkFetcher.allowLocalhostRequest = self.allowLocalhostRequest;
  1180. chunkFetcher.allowInvalidServerCertificates = self.allowInvalidServerCertificates;
  1181. chunkFetcher.useUploadTask = !isQueryFetch;
  1182. if (self.uploadFileURL && !isQueryFetch && self.useBackgroundSession) {
  1183. [chunkFetcher createSessionIdentifierWithMetadata:[self uploadSessionIdentifierMetadata]];
  1184. }
  1185. // Give the chunk fetcher the same properties as the previous chunk fetcher
  1186. chunkFetcher.properties = [properties mutableCopy];
  1187. [chunkFetcher setProperty:[NSValue valueWithNonretainedObject:self]
  1188. forKey:kGTMSessionUploadFetcherChunkParentKey];
  1189. // copy other fetcher settings to the new fetcher
  1190. chunkFetcher.retryEnabled = self.retryEnabled;
  1191. chunkFetcher.maxRetryInterval = self.maxRetryInterval;
  1192. if ([self isRetryEnabled]) {
  1193. // We interpose our own retry method both so we can change the request to ask the server to
  1194. // tell us where to resume the chunk.
  1195. chunkFetcher.retryBlock = ^(BOOL suggestedWillRetry, NSError *chunkError,
  1196. GTMSessionFetcherRetryResponse response) {
  1197. void (^finish)(BOOL) = ^(BOOL shouldRetry){
  1198. // We'll retry by sending an offset query.
  1199. if (shouldRetry) {
  1200. self.shouldInitiateOffsetQuery = !isQueryFetch;
  1201. // We don't know what our actual offset is anymore, but the server will tell us.
  1202. self.currentOffset = 0;
  1203. }
  1204. // We don't actually want to retry this specific fetcher.
  1205. response(NO);
  1206. };
  1207. GTMSessionFetcherRetryBlock retryBlock = self.retryBlock;
  1208. if (retryBlock) {
  1209. // Ask the client, then call the finish block above.
  1210. retryBlock(suggestedWillRetry, chunkError, finish);
  1211. } else {
  1212. finish(suggestedWillRetry);
  1213. }
  1214. };
  1215. }
  1216. return chunkFetcher;
  1217. }
  1218. - (void)chunkFetcher:(GTMSessionFetcher *)chunkFetcher
  1219. finishedWithData:(NSData *)data
  1220. error:(NSError *)error {
  1221. BOOL hasDestroyedOldChunkFetcher = NO;
  1222. self.fetcherInFlight = nil;
  1223. NSDictionary *responseHeaders = [chunkFetcher responseHeaders];
  1224. GTMSessionUploadFetcherStatus uploadStatus =
  1225. [[self class] uploadStatusFromResponseHeaders:responseHeaders];
  1226. GTMSESSION_ASSERT_DEBUG(uploadStatus != kStatusUnknown
  1227. || error != nil
  1228. || self.wasCreatedFromBackgroundSession,
  1229. @"chunk fetcher completion has kStatusUnknown upload status for headers %@ fetcher %@",
  1230. responseHeaders, self);
  1231. BOOL isUploadStatusStopped = (uploadStatus == kStatusFinal || uploadStatus == kStatusCancelled);
  1232. // Check if the fetcher was actually querying. If it failed, do not retry,
  1233. // as it would enter an infinite retry loop.
  1234. NSString *uploadCommand =
  1235. chunkFetcher.request.allHTTPHeaderFields[kGTMSessionHeaderXGoogUploadCommand];
  1236. BOOL isQueryFetch = [uploadCommand isEqual:@"query"];
  1237. // TODO
  1238. // Maybe here we can check to see if the request had x goog content length set. (the file length one).
  1239. NSString *previousContentLengthValue =
  1240. [chunkFetcher.request valueForHTTPHeaderField:@"Content-Length"];
  1241. // The Content-Length header may not be present if the chunk fetcher was recreated from
  1242. // a background session.
  1243. BOOL hasKnownChunkSize = (previousContentLengthValue != nil);
  1244. int64_t previousContentLength = [previousContentLengthValue longLongValue];
  1245. BOOL needsQuery = (!hasKnownChunkSize && !isUploadStatusStopped);
  1246. if (error || (needsQuery && !isQueryFetch)) {
  1247. NSInteger status = error.code;
  1248. // Status 4xx indicates a bad offset in the Google upload protocol. However, do not retry status
  1249. // 404 per spec, nor if the upload size appears to have been zero (since the server will just
  1250. // keep asking us to retry.)
  1251. if (self.shouldInitiateOffsetQuery ||
  1252. (needsQuery && !isQueryFetch) ||
  1253. ([error.domain isEqual:kGTMSessionFetcherStatusDomain] &&
  1254. status >= 400 && status <= 499 &&
  1255. status != 404 &&
  1256. uploadStatus == kStatusActive &&
  1257. previousContentLength > 0)) {
  1258. self.shouldInitiateOffsetQuery = NO;
  1259. [self destroyChunkFetcher];
  1260. hasDestroyedOldChunkFetcher = YES;
  1261. [self sendQueryForUploadOffsetWithFetcherProperties:chunkFetcher.properties];
  1262. } else {
  1263. // Some unexpected status has occurred; handle it as we would a regular
  1264. // object fetcher failure.
  1265. [self invokeFinalCallbackWithData:data
  1266. error:error
  1267. shouldInvalidateLocation:NO];
  1268. }
  1269. } else {
  1270. // The chunk has uploaded successfully.
  1271. int64_t newOffset = self.currentOffset + previousContentLength;
  1272. #if DEBUG
  1273. // Verify that if we think all of the uploading data has been sent, the server responded with
  1274. // the "final" upload status.
  1275. BOOL hasUploadAllData = (newOffset == [self fullUploadLength]);
  1276. BOOL isFinalStatus = (uploadStatus == kStatusFinal);
  1277. #pragma unused(hasUploadAllData,isFinalStatus)
  1278. GTMSESSION_ASSERT_DEBUG(hasUploadAllData == isFinalStatus || !hasKnownChunkSize,
  1279. @"uploadStatus:%@ newOffset:%lld (%lld + %lld) fullUploadLength:%lld"
  1280. @" chunkFetcher:%@ requestHeaders:%@ responseHeaders:%@",
  1281. [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadStatus],
  1282. newOffset, self.currentOffset, previousContentLength,
  1283. [self fullUploadLength],
  1284. chunkFetcher, chunkFetcher.request.allHTTPHeaderFields,
  1285. responseHeaders);
  1286. #endif
  1287. if (isUploadStatusStopped ||
  1288. (!_uploadData && _uploadFileLength == 0) ||
  1289. (_currentOffset > _uploadFileLength && _uploadFileLength > 0)) {
  1290. // This was the last chunk.
  1291. if (error == nil && uploadStatus == kStatusCancelled) {
  1292. // Report cancelled status as an error.
  1293. NSDictionary *userInfo = nil;
  1294. if (data.length > 0) {
  1295. userInfo = @{ kGTMSessionFetcherStatusDataKey : data };
  1296. }
  1297. data = nil;
  1298. error = [self prematureFailureErrorWithUserInfo:userInfo];
  1299. } else {
  1300. // The upload is in final status.
  1301. //
  1302. // Take the chunk fetcher's data as the superclass data.
  1303. self.downloadedData = data;
  1304. self.statusCode = chunkFetcher.statusCode;
  1305. }
  1306. // we're done
  1307. [self invokeFinalCallbackWithData:data
  1308. error:error
  1309. shouldInvalidateLocation:YES];
  1310. } else {
  1311. // Start the next chunk.
  1312. self.currentOffset = newOffset;
  1313. // We want to destroy this chunk fetcher before creating the next one, but
  1314. // we want to pass on its properties
  1315. NSDictionary *props = [chunkFetcher properties];
  1316. // We no longer need to be able to cancel this chunkFetcher. Destroy it
  1317. // before we create a new chunk fetcher.
  1318. [self destroyChunkFetcher];
  1319. hasDestroyedOldChunkFetcher = YES;
  1320. [self uploadNextChunkWithOffset:newOffset
  1321. fetcherProperties:props];
  1322. }
  1323. }
  1324. if (!hasDestroyedOldChunkFetcher) {
  1325. [self destroyChunkFetcher];
  1326. }
  1327. }
  1328. - (void)destroyChunkFetcher {
  1329. @synchronized(self) {
  1330. GTMSessionMonitorSynchronized(self);
  1331. if (_fetcherInFlight == _chunkFetcher) {
  1332. _fetcherInFlight = nil;
  1333. }
  1334. [_chunkFetcher stopFetching];
  1335. NSURL *chunkFileURL = _chunkFetcher.bodyFileURL;
  1336. BOOL wasTemporaryUploadFile = ![chunkFileURL isEqual:_uploadFileURL];
  1337. if (wasTemporaryUploadFile) {
  1338. NSError *error;
  1339. [[NSFileManager defaultManager] removeItemAtURL:chunkFileURL
  1340. error:&error];
  1341. if (error) {
  1342. GTMSESSION_LOG_DEBUG(@"removingItemAtURL failed: %@\n%@", error, chunkFileURL);
  1343. }
  1344. }
  1345. _recentChunkReponseHeaders = _chunkFetcher.responseHeaders;
  1346. // To avoid retain cycles, remove all properties except the parent identifier.
  1347. _chunkFetcher.properties =
  1348. @{ kGTMSessionUploadFetcherChunkParentKey : [NSValue valueWithNonretainedObject:self] };
  1349. _chunkFetcher.retryBlock = nil;
  1350. _chunkFetcher.sendProgressBlock = nil;
  1351. _chunkFetcher = nil;
  1352. } // @synchronized(self)
  1353. }
  1354. // This method calculates the proper values to pass to the client's send progress block.
  1355. //
  1356. // The actual total bytes sent include the initial body sent, plus the
  1357. // offset into the batched data prior to the current chunk fetcher
  1358. - (void)invokeDelegateWithDidSendBytes:(int64_t)bytesSent
  1359. totalBytesSent:(int64_t)totalBytesSent
  1360. totalBytesExpectedToSend:(int64_t)totalBytesExpected {
  1361. GTMSessionCheckNotSynchronized(self);
  1362. // Ensure the chunk fetcher survives the callback in case the user pauses the upload process.
  1363. __block GTMSessionFetcher *holdFetcher = self.chunkFetcher;
  1364. [self invokeOnCallbackQueue:self.delegateCallbackQueue
  1365. afterUserStopped:NO
  1366. block:^{
  1367. GTMSessionFetcherSendProgressBlock sendProgressBlock = self.sendProgressBlock;
  1368. if (sendProgressBlock) {
  1369. sendProgressBlock(bytesSent, totalBytesSent, totalBytesExpected);
  1370. }
  1371. holdFetcher = nil;
  1372. }];
  1373. }
  1374. - (void)retrieveUploadChunkGranularityFromResponseHeaders:(NSDictionary *)responseHeaders {
  1375. GTMSessionCheckNotSynchronized(self);
  1376. // Standard granularity for Google uploads is 256K.
  1377. NSString *chunkGranularityHeader =
  1378. [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadChunkGranularity];
  1379. self.uploadGranularity = chunkGranularityHeader.longLongValue;
  1380. }
  1381. #pragma mark -
  1382. - (BOOL)isPaused {
  1383. @synchronized(self) {
  1384. GTMSessionMonitorSynchronized(self);
  1385. return _isPaused;
  1386. } // @synchronized(self)
  1387. }
  1388. - (void)pauseFetching {
  1389. @synchronized(self) {
  1390. GTMSessionMonitorSynchronized(self);
  1391. _isPaused = YES;
  1392. } // @synchronized(self)
  1393. // Pausing just means stopping the current chunk from uploading;
  1394. // when we resume, we will send a query request to the server to
  1395. // figure out what bytes to resume sending.
  1396. //
  1397. // We won't try to cancel the initial data upload, but rather will check
  1398. // for being paused in beginChunkFetches.
  1399. [self destroyChunkFetcher];
  1400. }
  1401. - (void)resumeFetching {
  1402. BOOL wasPaused;
  1403. @synchronized(self) {
  1404. GTMSessionMonitorSynchronized(self);
  1405. wasPaused = _isPaused;
  1406. _isPaused = NO;
  1407. } // @synchronized(self)
  1408. if (wasPaused) {
  1409. [self sendQueryForUploadOffsetWithFetcherProperties:self.properties];
  1410. }
  1411. }
  1412. - (void)stopFetching {
  1413. // Overrides the superclass
  1414. [self destroyChunkFetcher];
  1415. // If we think the server is waiting for more data, then tell it there won't be more.
  1416. if (self.uploadLocationURL) {
  1417. [self sendCancelUploadWithFetcherProperties:[self properties]];
  1418. self.uploadLocationURL = nil;
  1419. } else {
  1420. [self invokeOnCallbackQueue:self.callbackQueue
  1421. afterUserStopped:YES
  1422. block:^{
  1423. // Repeated calls to stopFetching may cause this path to be reached despite having sent a real
  1424. // cancel request, check here to ensure that the cancellation handler invocation which fires
  1425. // will definitely be for the real request sent previously.
  1426. @synchronized(self) {
  1427. if (self->_isCancelInFlight) {
  1428. return;
  1429. }
  1430. }
  1431. [self triggerCancellationHandlerForFetch:nil data:nil error:nil];
  1432. }];
  1433. }
  1434. [super stopFetching];
  1435. }
  1436. // Fires the cancellation handler, returning whether there was a handler to be fired.
  1437. - (BOOL)triggerCancellationHandlerForFetch:(GTMSessionFetcher *)fetcher
  1438. data:(NSData *)data
  1439. error:(NSError *)error {
  1440. GTMSessionUploadFetcherCancellationHandler handler = self.cancellationHandler;
  1441. if (handler) {
  1442. handler(fetcher, data, error);
  1443. self.cancellationHandler = nil;
  1444. return YES;
  1445. }
  1446. return NO;
  1447. }
  1448. #pragma mark -
  1449. - (int64_t)updateChunkFetcher:(GTMSessionFetcher *)chunkFetcher
  1450. forChunkAtOffset:(int64_t)offset {
  1451. BOOL isUploadingFileURL = (self.uploadFileURL != nil);
  1452. // Upload another chunk, meeting server-required granularity.
  1453. int64_t chunkSize = self.chunkSize;
  1454. int64_t fullUploadLength = [self fullUploadLength];
  1455. BOOL isFileLengthKnown = fullUploadLength >= 0;
  1456. BOOL isUploadingFullFile = (offset == 0 && isFileLengthKnown && chunkSize >= fullUploadLength);
  1457. if (!isUploadingFileURL || !isUploadingFullFile) {
  1458. // We're not uploading the entire file and given the file URL. Since we'll be
  1459. // allocating a subdata block for a chunk, we need to bound it to something that
  1460. // won't blow the process's memory.
  1461. if (chunkSize > kGTMSessionUploadFetcherMaximumDemandBufferSize) {
  1462. chunkSize = kGTMSessionUploadFetcherMaximumDemandBufferSize;
  1463. }
  1464. }
  1465. int64_t granularity = self.uploadGranularity;
  1466. if (granularity > 0) {
  1467. if (chunkSize < granularity) {
  1468. chunkSize = granularity;
  1469. } else {
  1470. chunkSize = chunkSize - (chunkSize % granularity);
  1471. }
  1472. }
  1473. GTMSESSION_ASSERT_DEBUG(offset < fullUploadLength || fullUploadLength == 0,
  1474. @"offset %lld exceeds data length %lld", offset, fullUploadLength);
  1475. if (granularity > 0) {
  1476. offset = offset - (offset % granularity);
  1477. }
  1478. // If the chunk size is bigger than the remaining data, or else
  1479. // it's close enough in size to the remaining data that we'd rather
  1480. // avoid having a whole extra http fetch for the leftover bit, then make
  1481. // this chunk size exactly match the remaining data size
  1482. NSString *command;
  1483. int64_t thisChunkSize = chunkSize;
  1484. BOOL isChunkTooBig = (thisChunkSize >= (fullUploadLength - offset));
  1485. BOOL isChunkAlmostBigEnough = (fullUploadLength - offset - 2500 < thisChunkSize);
  1486. BOOL isFinalChunk = (isChunkTooBig || isChunkAlmostBigEnough) && isFileLengthKnown;
  1487. if (isFinalChunk) {
  1488. thisChunkSize = fullUploadLength - offset;
  1489. if (thisChunkSize > 0) {
  1490. command = @"upload, finalize";
  1491. } else {
  1492. command = @"finalize";
  1493. }
  1494. } else {
  1495. command = @"upload";
  1496. }
  1497. NSString *lengthStr = @(thisChunkSize).stringValue;
  1498. NSString *offsetStr = @(offset).stringValue;
  1499. [chunkFetcher setRequestValue:command forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand];
  1500. [chunkFetcher setRequestValue:lengthStr forHTTPHeaderField:@"Content-Length"];
  1501. [chunkFetcher setRequestValue:offsetStr forHTTPHeaderField:kGTMSessionHeaderXGoogUploadOffset];
  1502. if (_uploadFileLength != kGTMSessionUploadFetcherUnknownFileSize) {
  1503. [chunkFetcher setRequestValue:@([self fullUploadLength]).stringValue
  1504. forHTTPHeaderField:kGTMSessionHeaderXGoogUploadContentLength];
  1505. }
  1506. // Append the range of bytes in this chunk to the fetcher comment.
  1507. NSString *baseComment = self.comment;
  1508. [chunkFetcher setCommentWithFormat:@"%@ (%lld-%lld)",
  1509. baseComment ? baseComment : @"upload", offset, MAX(0, offset + thisChunkSize - 1)];
  1510. return thisChunkSize;
  1511. }
  1512. // Public properties.
  1513. @synthesize currentOffset = _currentOffset,
  1514. allowsCellularAccess = _allowsCellularAccess,
  1515. delegateCompletionHandler = _delegateCompletionHandler,
  1516. chunkFetcher = _chunkFetcher,
  1517. lastChunkRequest = _lastChunkRequest,
  1518. subdataGenerating = _subdataGenerating,
  1519. shouldInitiateOffsetQuery = _shouldInitiateOffsetQuery,
  1520. uploadGranularity = _uploadGranularity;
  1521. // Internal properties.
  1522. @dynamic fetcherInFlight;
  1523. @dynamic activeFetcher;
  1524. @dynamic statusCode;
  1525. @dynamic delegateCallbackQueue;
  1526. + (void)removePointer:(void *)pointer fromPointerArray:(NSPointerArray *)pointerArray {
  1527. for (NSUInteger index = 0, count = pointerArray.count; index < count; ++index) {
  1528. void *pointerAtIndex = [pointerArray pointerAtIndex:index];
  1529. if (pointerAtIndex == pointer) {
  1530. [pointerArray removePointerAtIndex:index];
  1531. return;
  1532. }
  1533. }
  1534. }
  1535. - (BOOL)useBackgroundSession {
  1536. @synchronized(self) {
  1537. GTMSessionMonitorSynchronized(self);
  1538. return _useBackgroundSessionOnChunkFetchers;
  1539. } // @synchronized(self
  1540. }
  1541. - (void)setUseBackgroundSession:(BOOL)useBackgroundSession {
  1542. @synchronized(self) {
  1543. GTMSessionMonitorSynchronized(self);
  1544. if (_useBackgroundSessionOnChunkFetchers != useBackgroundSession) {
  1545. _useBackgroundSessionOnChunkFetchers = useBackgroundSession;
  1546. NSPointerArray *uploadFetcherPointerArrayForBackgroundSessions =
  1547. [[self class] uploadFetcherPointerArrayForBackgroundSessions];
  1548. @synchronized(uploadFetcherPointerArrayForBackgroundSessions) {
  1549. if (_useBackgroundSessionOnChunkFetchers) {
  1550. [uploadFetcherPointerArrayForBackgroundSessions addPointer:(__bridge void *)self];
  1551. } else {
  1552. [[self class] removePointer:(__bridge void *)self
  1553. fromPointerArray:uploadFetcherPointerArrayForBackgroundSessions];
  1554. }
  1555. } // @synchronized(uploadFetcherPointerArrayForBackgroundSessions)
  1556. }
  1557. } // @synchronized(self)
  1558. }
  1559. - (BOOL)canFetchWithBackgroundSession {
  1560. // The initial upload fetcher is always a foreground session; the
  1561. // useBackgroundSession property will apply only to chunk fetchers,
  1562. // not to queries.
  1563. return NO;
  1564. }
  1565. - (NSDictionary *)responseHeaders {
  1566. GTMSessionCheckNotSynchronized(self);
  1567. // Overrides the superclass
  1568. // If asked for the fetcher's response, use the most recent chunk fetcher's response,
  1569. // since the original request's response lacks useful information like the actual
  1570. // Content-Type.
  1571. NSDictionary *dict = self.chunkFetcher.responseHeaders;
  1572. if (dict) {
  1573. return dict;
  1574. }
  1575. @synchronized(self) {
  1576. GTMSessionMonitorSynchronized(self);
  1577. if (_recentChunkReponseHeaders) {
  1578. return _recentChunkReponseHeaders;
  1579. }
  1580. } // @synchronized(self
  1581. // No chunk fetcher yet completed, so return whatever we have from the initial fetch.
  1582. return [super responseHeaders];
  1583. }
  1584. - (NSInteger)statusCodeUnsynchronized {
  1585. GTMSessionCheckSynchronized(self);
  1586. if (_recentChunkStatusCode != -1) {
  1587. // Overrides the superclass to indicate status appropriate to the initial
  1588. // or latest chunk fetch
  1589. return _recentChunkStatusCode;
  1590. } else {
  1591. return [super statusCodeUnsynchronized];
  1592. }
  1593. }
  1594. - (void)setStatusCode:(NSInteger)val {
  1595. @synchronized(self) {
  1596. GTMSessionMonitorSynchronized(self);
  1597. _recentChunkStatusCode = val;
  1598. }
  1599. }
  1600. - (int64_t)initialBodyLength {
  1601. @synchronized(self) {
  1602. GTMSessionMonitorSynchronized(self);
  1603. return _initialBodyLength;
  1604. }
  1605. }
  1606. - (void)setInitialBodyLength:(int64_t)length {
  1607. @synchronized(self) {
  1608. GTMSessionMonitorSynchronized(self);
  1609. _initialBodyLength = length;
  1610. }
  1611. }
  1612. - (int64_t)initialBodySent {
  1613. @synchronized(self) {
  1614. GTMSessionMonitorSynchronized(self);
  1615. return _initialBodySent;
  1616. }
  1617. }
  1618. - (void)setInitialBodySent:(int64_t)length {
  1619. @synchronized(self) {
  1620. GTMSessionMonitorSynchronized(self);
  1621. _initialBodySent = length;
  1622. }
  1623. }
  1624. - (NSURL *)uploadLocationURL {
  1625. @synchronized(self) {
  1626. GTMSessionMonitorSynchronized(self);
  1627. return _uploadLocationURL;
  1628. }
  1629. }
  1630. - (void)setUploadLocationURL:(NSURL *)locationURL {
  1631. @synchronized(self) {
  1632. GTMSessionMonitorSynchronized(self);
  1633. _uploadLocationURL = locationURL;
  1634. }
  1635. }
  1636. - (GTMSessionFetcher *)activeFetcher {
  1637. GTMSessionFetcher *result = self.fetcherInFlight;
  1638. if (result) return result;
  1639. return self;
  1640. }
  1641. - (BOOL)isFetching {
  1642. // If there is an active chunk fetcher, then the upload fetcher is considered
  1643. // to still be fetching.
  1644. if (self.fetcherInFlight != nil) return YES;
  1645. return [super isFetching];
  1646. }
  1647. - (BOOL)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds {
  1648. NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds];
  1649. while (self.fetcherInFlight || self.subdataGenerating) {
  1650. if ([timeoutDate timeIntervalSinceNow] < 0) return NO;
  1651. if (self.subdataGenerating) {
  1652. // Allow time for subdata generation.
  1653. NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:0.001];
  1654. [[NSRunLoop currentRunLoop] runUntilDate:stopDate];
  1655. } else {
  1656. // Wait for any chunk or query fetchers that still have pending callbacks or
  1657. // notifications.
  1658. BOOL timedOut;
  1659. if (self.fetcherInFlight == self) {
  1660. timedOut = ![super waitForCompletionWithTimeout:timeoutInSeconds];
  1661. } else {
  1662. timedOut = ![self.fetcherInFlight waitForCompletionWithTimeout:timeoutInSeconds];
  1663. }
  1664. if (timedOut) return NO;
  1665. }
  1666. }
  1667. return YES;
  1668. }
  1669. @end
  1670. @implementation GTMSessionFetcher (GTMSessionUploadFetcherMethods)
  1671. - (GTMSessionUploadFetcher *)parentUploadFetcher {
  1672. NSValue *property = [self propertyForKey:kGTMSessionUploadFetcherChunkParentKey];
  1673. if (!property) return nil;
  1674. GTMSessionUploadFetcher *uploadFetcher = property.nonretainedObjectValue;
  1675. GTMSESSION_ASSERT_DEBUG([uploadFetcher isKindOfClass:[GTMSessionUploadFetcher class]],
  1676. @"Unexpected parent upload fetcher class: %@", [uploadFetcher class]);
  1677. return uploadFetcher;
  1678. }
  1679. @end