GTMSessionFetcher.m 182 KB

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