GTMSessionFetcher.m 182 KB

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