Нема описа

GTMSessionFetcher.m 168KB

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