설명 없음

GTMSessionFetcher.m 169KB

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