GTMSessionUploadFetcher.m 83 KB

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