Bez popisu

GTMSessionFetcher.m 173KB

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