GTMSessionFetcher.m 186 KB

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