ASIHTTPRequest.m 180 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125
  1. //
  2. // ASIHTTPRequest.m
  3. //
  4. // Created by Ben Copsey on 04/10/2007.
  5. // Copyright 2007-2011 All-Seeing Interactive. All rights reserved.
  6. //
  7. // A guide to the main features is available at:
  8. // http://allseeing-i.com/ASIHTTPRequest
  9. //
  10. // Portions are based on the ImageClient example from Apple:
  11. // See: http://developer.apple.com/samplecode/ImageClient/listing37.html
  12. #import "ASIHTTPRequest.h"
  13. #if TARGET_OS_IPHONE
  14. #import "Reachability.h"
  15. #import "ASIAuthenticationDialog.h"
  16. #import <MobileCoreServices/MobileCoreServices.h>
  17. #else
  18. #import <SystemConfiguration/SystemConfiguration.h>
  19. #endif
  20. #import "ASIInputStream.h"
  21. #import "ASIDataDecompressor.h"
  22. #import "ASIDataCompressor.h"
  23. // Automatically set on build
  24. NSString *ASIHTTPRequestVersion = @"v1.8.1-61 2011-09-19";
  25. static NSString *defaultUserAgent = nil;
  26. NSString* const NetworkRequestErrorDomain = @"ASIHTTPRequestErrorDomain";
  27. static NSString *ASIHTTPRequestRunLoopMode = @"ASIHTTPRequestRunLoopMode";
  28. static const CFOptionFlags kNetworkEvents = kCFStreamEventHasBytesAvailable | kCFStreamEventEndEncountered | kCFStreamEventErrorOccurred;
  29. // In memory caches of credentials, used on when useSessionPersistence is YES
  30. static NSMutableArray *sessionCredentialsStore = nil;
  31. static NSMutableArray *sessionProxyCredentialsStore = nil;
  32. // This lock mediates access to session credentials
  33. static NSRecursiveLock *sessionCredentialsLock = nil;
  34. // We keep track of cookies we have received here so we can remove them from the sharedHTTPCookieStorage later
  35. static NSMutableArray *sessionCookies = nil;
  36. // The number of times we will allow requests to redirect before we fail with a redirection error
  37. const int RedirectionLimit = 5;
  38. // The default number of seconds to use for a timeout
  39. static NSTimeInterval defaultTimeOutSeconds = 10;
  40. static void ReadStreamClientCallBack(CFReadStreamRef readStream, CFStreamEventType type, void *clientCallBackInfo) {
  41. [((ASIHTTPRequest*)clientCallBackInfo) handleNetworkEvent: type];
  42. }
  43. // This lock prevents the operation from being cancelled while it is trying to update the progress, and vice versa
  44. static NSRecursiveLock *progressLock;
  45. static NSError *ASIRequestCancelledError;
  46. static NSError *ASIRequestTimedOutError;
  47. static NSError *ASIAuthenticationError;
  48. static NSError *ASIUnableToCreateRequestError;
  49. static NSError *ASITooMuchRedirectionError;
  50. static NSMutableArray *bandwidthUsageTracker = nil;
  51. static unsigned long averageBandwidthUsedPerSecond = 0;
  52. // These are used for queuing persistent connections on the same connection
  53. // Incremented every time we specify we want a new connection
  54. static unsigned int nextConnectionNumberToCreate = 0;
  55. // An array of connectionInfo dictionaries.
  56. // When attempting a persistent connection, we look here to try to find an existing connection to the same server that is currently not in use
  57. static NSMutableArray *persistentConnectionsPool = nil;
  58. // Mediates access to the persistent connections pool
  59. static NSRecursiveLock *connectionsLock = nil;
  60. // Each request gets a new id, we store this rather than a ref to the request itself in the connectionInfo dictionary.
  61. // We do this so we don't have to keep the request around while we wait for the connection to expire
  62. static unsigned int nextRequestID = 0;
  63. // Records how much bandwidth all requests combined have used in the last second
  64. static unsigned long bandwidthUsedInLastSecond = 0;
  65. // A date one second in the future from the time it was created
  66. static NSDate *bandwidthMeasurementDate = nil;
  67. // Since throttling variables are shared among all requests, we'll use a lock to mediate access
  68. static NSLock *bandwidthThrottlingLock = nil;
  69. // the maximum number of bytes that can be transmitted in one second
  70. static unsigned long maxBandwidthPerSecond = 0;
  71. // A default figure for throttling bandwidth on mobile devices
  72. unsigned long const ASIWWANBandwidthThrottleAmount = 14800;
  73. #if TARGET_OS_IPHONE
  74. // YES when bandwidth throttling is active
  75. // This flag does not denote whether throttling is turned on - rather whether it is currently in use
  76. // It will be set to NO when throttling was turned on with setShouldThrottleBandwidthForWWAN, but a WI-FI connection is active
  77. static BOOL isBandwidthThrottled = NO;
  78. // When YES, bandwidth will be automatically throttled when using WWAN (3G/Edge/GPRS)
  79. // Wifi will not be throttled
  80. static BOOL shouldThrottleBandwidthForWWANOnly = NO;
  81. #endif
  82. // Mediates access to the session cookies so requests
  83. static NSRecursiveLock *sessionCookiesLock = nil;
  84. // This lock ensures delegates only receive one notification that authentication is required at once
  85. // When using ASIAuthenticationDialogs, it also ensures only one dialog is shown at once
  86. // If a request can't acquire the lock immediately, it means a dialog is being shown or a delegate is handling the authentication challenge
  87. // Once it gets the lock, it will try to look for existing credentials again rather than showing the dialog / notifying the delegate
  88. // This is so it can make use of any credentials supplied for the other request, if they are appropriate
  89. static NSRecursiveLock *delegateAuthenticationLock = nil;
  90. // When throttling bandwidth, Set to a date in future that we will allow all requests to wake up and reschedule their streams
  91. static NSDate *throttleWakeUpTime = nil;
  92. static id <ASICacheDelegate> defaultCache = nil;
  93. // Used for tracking when requests are using the network
  94. static unsigned int runningRequestCount = 0;
  95. // You can use [ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:NO] if you want to manage it yourself
  96. // Alternatively, override showNetworkActivityIndicator / hideNetworkActivityIndicator
  97. // By default this does nothing on Mac OS X, but again override the above methods for a different behaviour
  98. static BOOL shouldUpdateNetworkActivityIndicator = YES;
  99. // The thread all requests will run on
  100. // Hangs around forever, but will be blocked unless there are requests underway
  101. static NSThread *networkThread = nil;
  102. static NSOperationQueue *sharedQueue = nil;
  103. // Private stuff
  104. @interface ASIHTTPRequest ()
  105. - (void)cancelLoad;
  106. - (void)destroyReadStream;
  107. - (void)scheduleReadStream;
  108. - (void)unscheduleReadStream;
  109. - (BOOL)willAskDelegateForCredentials;
  110. - (BOOL)willAskDelegateForProxyCredentials;
  111. - (void)askDelegateForProxyCredentials;
  112. - (void)askDelegateForCredentials;
  113. - (void)failAuthentication;
  114. + (void)measureBandwidthUsage;
  115. + (void)recordBandwidthUsage;
  116. - (void)startRequest;
  117. - (void)updateStatus:(NSTimer *)timer;
  118. - (void)checkRequestStatus;
  119. - (void)reportFailure;
  120. - (void)reportFinished;
  121. - (void)markAsFinished;
  122. - (void)performRedirect;
  123. - (BOOL)shouldTimeOut;
  124. - (BOOL)willRedirect;
  125. - (BOOL)willAskDelegateToConfirmRedirect;
  126. + (void)performInvocation:(NSInvocation *)invocation onTarget:(id *)target releasingObject:(id)objectToRelease;
  127. + (void)hideNetworkActivityIndicatorAfterDelay;
  128. + (void)hideNetworkActivityIndicatorIfNeeeded;
  129. + (void)runRequests;
  130. // Handling Proxy autodetection and PAC file downloads
  131. - (BOOL)configureProxies;
  132. - (void)fetchPACFile;
  133. - (void)finishedDownloadingPACFile:(ASIHTTPRequest *)theRequest;
  134. - (void)runPACScript:(NSString *)script;
  135. - (void)timeOutPACRead;
  136. - (void)useDataFromCache;
  137. // Called to update the size of a partial download when starting a request, or retrying after a timeout
  138. - (void)updatePartialDownloadSize;
  139. #if TARGET_OS_IPHONE
  140. + (void)registerForNetworkReachabilityNotifications;
  141. + (void)unsubscribeFromNetworkReachabilityNotifications;
  142. // Called when the status of the network changes
  143. + (void)reachabilityChanged:(NSNotification *)note;
  144. #endif
  145. #if NS_BLOCKS_AVAILABLE
  146. - (void)performBlockOnMainThread:(ASIBasicBlock)block;
  147. - (void)releaseBlocksOnMainThread;
  148. + (void)releaseBlocks:(NSArray *)blocks;
  149. - (void)callBlock:(ASIBasicBlock)block;
  150. #endif
  151. @property (assign) BOOL complete;
  152. @property (retain) NSArray *responseCookies;
  153. @property (assign) int responseStatusCode;
  154. @property (retain, nonatomic) NSDate *lastActivityTime;
  155. @property (assign) unsigned long long partialDownloadSize;
  156. @property (assign,nonatomic) unsigned long long uploadBufferSize;
  157. @property (retain, nonatomic) NSOutputStream *postBodyWriteStream;
  158. @property (retain, nonatomic) NSInputStream *postBodyReadStream;
  159. @property (assign,nonatomic) unsigned long long lastBytesRead;
  160. @property (assign,nonatomic) unsigned long long lastBytesSent;
  161. @property (retain) NSRecursiveLock *cancelledLock;
  162. @property (retain, nonatomic) NSOutputStream *fileDownloadOutputStream;
  163. @property (retain, nonatomic) NSOutputStream *inflatedFileDownloadOutputStream;
  164. @property (assign) int authenticationRetryCount;
  165. @property (assign) int proxyAuthenticationRetryCount;
  166. @property (assign,nonatomic) BOOL updatedProgress;
  167. @property (assign,nonatomic) BOOL needsRedirect;
  168. @property (assign,nonatomic) int redirectCount;
  169. @property (retain, nonatomic) NSData *compressedPostBody;
  170. @property (retain, nonatomic) NSString *compressedPostBodyFilePath;
  171. @property (retain) NSString *authenticationRealm;
  172. @property (retain) NSString *proxyAuthenticationRealm;
  173. @property (retain) NSString *responseStatusMessage;
  174. @property (assign) BOOL inProgress;
  175. @property (assign) int retryCount;
  176. @property (assign) BOOL willRetryRequest;
  177. @property (assign) BOOL connectionCanBeReused;
  178. @property (retain, nonatomic) NSMutableDictionary *connectionInfo;
  179. @property (retain, nonatomic) NSInputStream *readStream;
  180. @property (assign) ASIAuthenticationState authenticationNeeded;
  181. @property (assign,nonatomic) BOOL readStreamIsScheduled;
  182. @property (assign,nonatomic) BOOL downloadComplete;
  183. @property (retain) NSNumber *requestID;
  184. @property (assign,nonatomic) NSString *runLoopMode;
  185. @property (retain, nonatomic) NSTimer *statusTimer;
  186. @property (assign) BOOL didUseCachedResponse;
  187. @property (retain, nonatomic) NSURL *redirectURL;
  188. @property (assign,nonatomic) BOOL isPACFileRequest;
  189. @property (retain, nonatomic) ASIHTTPRequest *PACFileRequest;
  190. @property (retain, nonatomic) NSInputStream *PACFileReadStream;
  191. @property (retain, nonatomic) NSMutableData *PACFileData;
  192. @property (assign, nonatomic, setter=setSynchronous:) BOOL isSynchronous;
  193. @end
  194. @implementation ASIHTTPRequest
  195. #pragma mark init / dealloc
  196. + (void)initialize
  197. {
  198. if (self == [ASIHTTPRequest class]) {
  199. persistentConnectionsPool = [[NSMutableArray alloc] init];
  200. connectionsLock = [[NSRecursiveLock alloc] init];
  201. progressLock = [[NSRecursiveLock alloc] init];
  202. bandwidthThrottlingLock = [[NSLock alloc] init];
  203. sessionCookiesLock = [[NSRecursiveLock alloc] init];
  204. sessionCredentialsLock = [[NSRecursiveLock alloc] init];
  205. delegateAuthenticationLock = [[NSRecursiveLock alloc] init];
  206. bandwidthUsageTracker = [[NSMutableArray alloc] initWithCapacity:5];
  207. ASIRequestTimedOutError = [[NSError alloc] initWithDomain:NetworkRequestErrorDomain code:ASIRequestTimedOutErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"The request timed out",NSLocalizedDescriptionKey,nil]];
  208. ASIAuthenticationError = [[NSError alloc] initWithDomain:NetworkRequestErrorDomain code:ASIAuthenticationErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Authentication needed",NSLocalizedDescriptionKey,nil]];
  209. ASIRequestCancelledError = [[NSError alloc] initWithDomain:NetworkRequestErrorDomain code:ASIRequestCancelledErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"The request was cancelled",NSLocalizedDescriptionKey,nil]];
  210. ASIUnableToCreateRequestError = [[NSError alloc] initWithDomain:NetworkRequestErrorDomain code:ASIUnableToCreateRequestErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to create request (bad url?)",NSLocalizedDescriptionKey,nil]];
  211. ASITooMuchRedirectionError = [[NSError alloc] initWithDomain:NetworkRequestErrorDomain code:ASITooMuchRedirectionErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"The request failed because it redirected too many times",NSLocalizedDescriptionKey,nil]];
  212. sharedQueue = [[NSOperationQueue alloc] init];
  213. [sharedQueue setMaxConcurrentOperationCount:4];
  214. }
  215. }
  216. - (id)initWithURL:(NSURL *)newURL
  217. {
  218. self = [self init];
  219. [self setRequestMethod:@"GET"];
  220. [self setRunLoopMode:NSDefaultRunLoopMode];
  221. [self setShouldAttemptPersistentConnection:YES];
  222. [self setPersistentConnectionTimeoutSeconds:60.0];
  223. [self setShouldPresentCredentialsBeforeChallenge:YES];
  224. [self setShouldRedirect:YES];
  225. [self setShowAccurateProgress:YES];
  226. [self setShouldResetDownloadProgress:YES];
  227. [self setShouldResetUploadProgress:YES];
  228. [self setAllowCompressedResponse:YES];
  229. [self setShouldWaitToInflateCompressedResponses:YES];
  230. [self setDefaultResponseEncoding:NSISOLatin1StringEncoding];
  231. [self setShouldPresentProxyAuthenticationDialog:YES];
  232. [self setTimeOutSeconds:[ASIHTTPRequest defaultTimeOutSeconds]];
  233. [self setUseSessionPersistence:YES];
  234. [self setUseCookiePersistence:YES];
  235. [self setValidatesSecureCertificate:YES];
  236. [self setRequestCookies:[[[NSMutableArray alloc] init] autorelease]];
  237. [self setDidStartSelector:@selector(requestStarted:)];
  238. [self setDidReceiveResponseHeadersSelector:@selector(request:didReceiveResponseHeaders:)];
  239. [self setWillRedirectSelector:@selector(request:willRedirectToURL:)];
  240. [self setDidFinishSelector:@selector(requestFinished:)];
  241. [self setDidFailSelector:@selector(requestFailed:)];
  242. [self setDidReceiveDataSelector:@selector(request:didReceiveData:)];
  243. [self setURL:newURL];
  244. [self setCancelledLock:[[[NSRecursiveLock alloc] init] autorelease]];
  245. [self setDownloadCache:[[self class] defaultCache]];
  246. return self;
  247. }
  248. + (id)requestWithURL:(NSURL *)newURL
  249. {
  250. return [[[self alloc] initWithURL:newURL] autorelease];
  251. }
  252. + (id)requestWithURL:(NSURL *)newURL usingCache:(id <ASICacheDelegate>)cache
  253. {
  254. return [self requestWithURL:newURL usingCache:cache andCachePolicy:ASIUseDefaultCachePolicy];
  255. }
  256. + (id)requestWithURL:(NSURL *)newURL usingCache:(id <ASICacheDelegate>)cache andCachePolicy:(ASICachePolicy)policy
  257. {
  258. ASIHTTPRequest *request = [[[self alloc] initWithURL:newURL] autorelease];
  259. [request setDownloadCache:cache];
  260. [request setCachePolicy:policy];
  261. return request;
  262. }
  263. - (void)dealloc
  264. {
  265. [self setAuthenticationNeeded:ASINoAuthenticationNeededYet];
  266. if (requestAuthentication) {
  267. CFRelease(requestAuthentication);
  268. }
  269. if (proxyAuthentication) {
  270. CFRelease(proxyAuthentication);
  271. }
  272. if (request) {
  273. CFRelease(request);
  274. }
  275. if (clientCertificateIdentity) {
  276. CFRelease(clientCertificateIdentity);
  277. }
  278. [self cancelLoad];
  279. [redirectURL release];
  280. [statusTimer invalidate];
  281. [statusTimer release];
  282. [queue release];
  283. [userInfo release];
  284. [postBody release];
  285. [compressedPostBody release];
  286. [error release];
  287. [requestHeaders release];
  288. [requestCookies release];
  289. [downloadDestinationPath release];
  290. [temporaryFileDownloadPath release];
  291. [temporaryUncompressedDataDownloadPath release];
  292. [fileDownloadOutputStream release];
  293. [inflatedFileDownloadOutputStream release];
  294. [username release];
  295. [password release];
  296. [domain release];
  297. [authenticationRealm release];
  298. [authenticationScheme release];
  299. [requestCredentials release];
  300. [proxyHost release];
  301. [proxyType release];
  302. [proxyUsername release];
  303. [proxyPassword release];
  304. [proxyDomain release];
  305. [proxyAuthenticationRealm release];
  306. [proxyAuthenticationScheme release];
  307. [proxyCredentials release];
  308. [url release];
  309. [originalURL release];
  310. [lastActivityTime release];
  311. [responseCookies release];
  312. [rawResponseData release];
  313. [responseHeaders release];
  314. [requestMethod release];
  315. [cancelledLock release];
  316. [postBodyFilePath release];
  317. [compressedPostBodyFilePath release];
  318. [postBodyWriteStream release];
  319. [postBodyReadStream release];
  320. [PACurl release];
  321. [clientCertificates release];
  322. [responseStatusMessage release];
  323. [connectionInfo release];
  324. [requestID release];
  325. [dataDecompressor release];
  326. [userAgent release];
  327. #if NS_BLOCKS_AVAILABLE
  328. [self releaseBlocksOnMainThread];
  329. #endif
  330. [super dealloc];
  331. }
  332. #if NS_BLOCKS_AVAILABLE
  333. - (void)releaseBlocksOnMainThread
  334. {
  335. NSMutableArray *blocks = [NSMutableArray array];
  336. if (completionBlock) {
  337. [blocks addObject:completionBlock];
  338. [completionBlock release];
  339. completionBlock = nil;
  340. }
  341. if (failureBlock) {
  342. [blocks addObject:failureBlock];
  343. [failureBlock release];
  344. failureBlock = nil;
  345. }
  346. if (startedBlock) {
  347. [blocks addObject:startedBlock];
  348. [startedBlock release];
  349. startedBlock = nil;
  350. }
  351. if (headersReceivedBlock) {
  352. [blocks addObject:headersReceivedBlock];
  353. [headersReceivedBlock release];
  354. headersReceivedBlock = nil;
  355. }
  356. if (bytesReceivedBlock) {
  357. [blocks addObject:bytesReceivedBlock];
  358. [bytesReceivedBlock release];
  359. bytesReceivedBlock = nil;
  360. }
  361. if (bytesSentBlock) {
  362. [blocks addObject:bytesSentBlock];
  363. [bytesSentBlock release];
  364. bytesSentBlock = nil;
  365. }
  366. if (downloadSizeIncrementedBlock) {
  367. [blocks addObject:downloadSizeIncrementedBlock];
  368. [downloadSizeIncrementedBlock release];
  369. downloadSizeIncrementedBlock = nil;
  370. }
  371. if (uploadSizeIncrementedBlock) {
  372. [blocks addObject:uploadSizeIncrementedBlock];
  373. [uploadSizeIncrementedBlock release];
  374. uploadSizeIncrementedBlock = nil;
  375. }
  376. if (dataReceivedBlock) {
  377. [blocks addObject:dataReceivedBlock];
  378. [dataReceivedBlock release];
  379. dataReceivedBlock = nil;
  380. }
  381. if (proxyAuthenticationNeededBlock) {
  382. [blocks addObject:proxyAuthenticationNeededBlock];
  383. [proxyAuthenticationNeededBlock release];
  384. proxyAuthenticationNeededBlock = nil;
  385. }
  386. if (authenticationNeededBlock) {
  387. [blocks addObject:authenticationNeededBlock];
  388. [authenticationNeededBlock release];
  389. authenticationNeededBlock = nil;
  390. }
  391. [[self class] performSelectorOnMainThread:@selector(releaseBlocks:) withObject:blocks waitUntilDone:[NSThread isMainThread]];
  392. }
  393. // Always called on main thread
  394. + (void)releaseBlocks:(NSArray *)blocks
  395. {
  396. // Blocks will be released when this method exits
  397. }
  398. #endif
  399. #pragma mark setup request
  400. - (void)addRequestHeader:(NSString *)header value:(NSString *)value
  401. {
  402. if (!requestHeaders) {
  403. [self setRequestHeaders:[NSMutableDictionary dictionaryWithCapacity:1]];
  404. }
  405. [requestHeaders setObject:value forKey:header];
  406. }
  407. // This function will be called either just before a request starts, or when postLength is needed, whichever comes first
  408. // postLength must be set by the time this function is complete
  409. - (void)buildPostBody
  410. {
  411. if ([self haveBuiltPostBody]) {
  412. return;
  413. }
  414. // Are we submitting the request body from a file on disk
  415. if ([self postBodyFilePath]) {
  416. // If we were writing to the post body via appendPostData or appendPostDataFromFile, close the write stream
  417. if ([self postBodyWriteStream]) {
  418. [[self postBodyWriteStream] close];
  419. [self setPostBodyWriteStream:nil];
  420. }
  421. NSString *path;
  422. if ([self shouldCompressRequestBody]) {
  423. if (![self compressedPostBodyFilePath]) {
  424. [self setCompressedPostBodyFilePath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]];
  425. NSError *err = nil;
  426. if (![ASIDataCompressor compressDataFromFile:[self postBodyFilePath] toFile:[self compressedPostBodyFilePath] error:&err]) {
  427. [self failWithError:err];
  428. return;
  429. }
  430. }
  431. path = [self compressedPostBodyFilePath];
  432. } else {
  433. path = [self postBodyFilePath];
  434. }
  435. NSError *err = nil;
  436. [self setPostLength:[[[[[NSFileManager alloc] init] autorelease] attributesOfItemAtPath:path error:&err] fileSize]];
  437. if (err) {
  438. [self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to get attributes for file at path '%@'",path],NSLocalizedDescriptionKey,error,NSUnderlyingErrorKey,nil]]];
  439. return;
  440. }
  441. // Otherwise, we have an in-memory request body
  442. } else {
  443. if ([self shouldCompressRequestBody]) {
  444. NSError *err = nil;
  445. NSData *compressedBody = [ASIDataCompressor compressData:[self postBody] error:&err];
  446. if (err) {
  447. [self failWithError:err];
  448. return;
  449. }
  450. [self setCompressedPostBody:compressedBody];
  451. [self setPostLength:[[self compressedPostBody] length]];
  452. } else {
  453. [self setPostLength:[[self postBody] length]];
  454. }
  455. }
  456. if ([self postLength] > 0) {
  457. if ([requestMethod isEqualToString:@"GET"] || [requestMethod isEqualToString:@"DELETE"] || [requestMethod isEqualToString:@"HEAD"]) {
  458. [self setRequestMethod:@"POST"];
  459. }
  460. [self addRequestHeader:@"Content-Length" value:[NSString stringWithFormat:@"%llu",[self postLength]]];
  461. }
  462. [self setHaveBuiltPostBody:YES];
  463. }
  464. // Sets up storage for the post body
  465. - (void)setupPostBody
  466. {
  467. if ([self shouldStreamPostDataFromDisk]) {
  468. if (![self postBodyFilePath]) {
  469. [self setPostBodyFilePath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]];
  470. [self setDidCreateTemporaryPostDataFile:YES];
  471. }
  472. if (![self postBodyWriteStream]) {
  473. [self setPostBodyWriteStream:[[[NSOutputStream alloc] initToFileAtPath:[self postBodyFilePath] append:NO] autorelease]];
  474. [[self postBodyWriteStream] open];
  475. }
  476. } else {
  477. if (![self postBody]) {
  478. [self setPostBody:[[[NSMutableData alloc] init] autorelease]];
  479. }
  480. }
  481. }
  482. - (void)appendPostData:(NSData *)data
  483. {
  484. [self setupPostBody];
  485. if ([data length] == 0) {
  486. return;
  487. }
  488. if ([self shouldStreamPostDataFromDisk]) {
  489. [[self postBodyWriteStream] write:[data bytes] maxLength:[data length]];
  490. } else {
  491. [[self postBody] appendData:data];
  492. }
  493. }
  494. - (void)appendPostDataFromFile:(NSString *)file
  495. {
  496. [self setupPostBody];
  497. NSInputStream *stream = [[[NSInputStream alloc] initWithFileAtPath:file] autorelease];
  498. [stream open];
  499. NSUInteger bytesRead;
  500. while ([stream hasBytesAvailable]) {
  501. unsigned char buffer[1024*256];
  502. bytesRead = [stream read:buffer maxLength:sizeof(buffer)];
  503. if (bytesRead == 0) {
  504. break;
  505. }
  506. if ([self shouldStreamPostDataFromDisk]) {
  507. [[self postBodyWriteStream] write:buffer maxLength:bytesRead];
  508. } else {
  509. [[self postBody] appendData:[NSData dataWithBytes:buffer length:bytesRead]];
  510. }
  511. }
  512. [stream close];
  513. }
  514. - (NSString *)requestMethod
  515. {
  516. [[self cancelledLock] lock];
  517. NSString *m = requestMethod;
  518. [[self cancelledLock] unlock];
  519. return m;
  520. }
  521. - (void)setRequestMethod:(NSString *)newRequestMethod
  522. {
  523. [[self cancelledLock] lock];
  524. if (requestMethod != newRequestMethod) {
  525. [requestMethod release];
  526. requestMethod = [newRequestMethod retain];
  527. if ([requestMethod isEqualToString:@"POST"] || [requestMethod isEqualToString:@"PUT"] || [postBody length] || postBodyFilePath) {
  528. [self setShouldAttemptPersistentConnection:NO];
  529. }
  530. }
  531. [[self cancelledLock] unlock];
  532. }
  533. - (NSURL *)url
  534. {
  535. [[self cancelledLock] lock];
  536. NSURL *u = url;
  537. [[self cancelledLock] unlock];
  538. return u;
  539. }
  540. - (void)setURL:(NSURL *)newURL
  541. {
  542. [[self cancelledLock] lock];
  543. if ([newURL isEqual:[self url]]) {
  544. [[self cancelledLock] unlock];
  545. return;
  546. }
  547. [url release];
  548. url = [newURL retain];
  549. if (requestAuthentication) {
  550. CFRelease(requestAuthentication);
  551. requestAuthentication = NULL;
  552. }
  553. if (proxyAuthentication) {
  554. CFRelease(proxyAuthentication);
  555. proxyAuthentication = NULL;
  556. }
  557. if (request) {
  558. CFRelease(request);
  559. request = NULL;
  560. }
  561. [self setRedirectURL:nil];
  562. [[self cancelledLock] unlock];
  563. }
  564. - (id)delegate
  565. {
  566. [[self cancelledLock] lock];
  567. id d = delegate;
  568. [[self cancelledLock] unlock];
  569. return d;
  570. }
  571. - (void)setDelegate:(id)newDelegate
  572. {
  573. [[self cancelledLock] lock];
  574. delegate = newDelegate;
  575. [[self cancelledLock] unlock];
  576. }
  577. - (id)queue
  578. {
  579. [[self cancelledLock] lock];
  580. id q = queue;
  581. [[self cancelledLock] unlock];
  582. return q;
  583. }
  584. - (void)setQueue:(id)newQueue
  585. {
  586. [[self cancelledLock] lock];
  587. if (newQueue != queue) {
  588. [queue release];
  589. queue = [newQueue retain];
  590. }
  591. [[self cancelledLock] unlock];
  592. }
  593. #pragma mark get information about this request
  594. // cancel the request - this must be run on the same thread as the request is running on
  595. - (void)cancelOnRequestThread
  596. {
  597. #if DEBUG_REQUEST_STATUS
  598. ASI_DEBUG_LOG(@"[STATUS] Request cancelled: %@",self);
  599. #endif
  600. [[self cancelledLock] lock];
  601. if ([self isCancelled] || [self complete]) {
  602. [[self cancelledLock] unlock];
  603. return;
  604. }
  605. [self failWithError:ASIRequestCancelledError];
  606. [self setComplete:YES];
  607. [self cancelLoad];
  608. CFRetain(self);
  609. [self willChangeValueForKey:@"isCancelled"];
  610. cancelled = YES;
  611. [self didChangeValueForKey:@"isCancelled"];
  612. [[self cancelledLock] unlock];
  613. CFRelease(self);
  614. }
  615. - (void)cancel
  616. {
  617. [self performSelector:@selector(cancelOnRequestThread) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
  618. }
  619. - (void)clearDelegatesAndCancel
  620. {
  621. [[self cancelledLock] lock];
  622. // Clear delegates
  623. [self setDelegate:nil];
  624. [self setQueue:nil];
  625. [self setDownloadProgressDelegate:nil];
  626. [self setUploadProgressDelegate:nil];
  627. #if NS_BLOCKS_AVAILABLE
  628. // Clear blocks
  629. [self releaseBlocksOnMainThread];
  630. #endif
  631. [[self cancelledLock] unlock];
  632. [self cancel];
  633. }
  634. - (BOOL)isCancelled
  635. {
  636. BOOL result;
  637. [[self cancelledLock] lock];
  638. result = cancelled;
  639. [[self cancelledLock] unlock];
  640. return result;
  641. }
  642. // Call this method to get the received data as an NSString. Don't use for binary data!
  643. - (NSString *)responseString
  644. {
  645. NSData *data = [self responseData];
  646. if (!data) {
  647. return nil;
  648. }
  649. return [[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:[self responseEncoding]] autorelease];
  650. }
  651. - (BOOL)isResponseCompressed
  652. {
  653. NSString *encoding = [[self responseHeaders] objectForKey:@"Content-Encoding"];
  654. return encoding && [encoding rangeOfString:@"gzip"].location != NSNotFound;
  655. }
  656. - (NSData *)responseData
  657. {
  658. if ([self isResponseCompressed] && [self shouldWaitToInflateCompressedResponses]) {
  659. return [ASIDataDecompressor uncompressData:[self rawResponseData] error:NULL];
  660. } else {
  661. return [self rawResponseData];
  662. }
  663. return nil;
  664. }
  665. #pragma mark running a request
  666. - (void)startSynchronous
  667. {
  668. #if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
  669. ASI_DEBUG_LOG(@"[STATUS] Starting synchronous request %@",self);
  670. #endif
  671. [self setSynchronous:YES];
  672. [self setRunLoopMode:ASIHTTPRequestRunLoopMode];
  673. [self setInProgress:YES];
  674. if (![self isCancelled] && ![self complete]) {
  675. [self main];
  676. while (!complete) {
  677. [[NSRunLoop currentRunLoop] runMode:[self runLoopMode] beforeDate:[NSDate distantFuture]];
  678. }
  679. }
  680. [self setInProgress:NO];
  681. }
  682. - (void)start
  683. {
  684. [self setInProgress:YES];
  685. [self performSelector:@selector(main) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
  686. }
  687. - (void)startAsynchronous
  688. {
  689. #if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
  690. ASI_DEBUG_LOG(@"[STATUS] Starting asynchronous request %@",self);
  691. #endif
  692. [sharedQueue addOperation:self];
  693. }
  694. #pragma mark concurrency
  695. - (BOOL)isConcurrent
  696. {
  697. return YES;
  698. }
  699. - (BOOL)isFinished
  700. {
  701. return finished;
  702. }
  703. - (BOOL)isExecuting {
  704. return [self inProgress];
  705. }
  706. #pragma mark request logic
  707. // Create the request
  708. - (void)main
  709. {
  710. @try {
  711. [[self cancelledLock] lock];
  712. #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
  713. if ([ASIHTTPRequest isMultitaskingSupported] && [self shouldContinueWhenAppEntersBackground]) {
  714. backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
  715. // Synchronize the cleanup call on the main thread in case
  716. // the task actually finishes at around the same time.
  717. dispatch_async(dispatch_get_main_queue(), ^{
  718. if (backgroundTask != UIBackgroundTaskInvalid)
  719. {
  720. [[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
  721. backgroundTask = UIBackgroundTaskInvalid;
  722. [self cancel];
  723. }
  724. });
  725. }];
  726. }
  727. #endif
  728. // A HEAD request generated by an ASINetworkQueue may have set the error already. If so, we should not proceed.
  729. if ([self error]) {
  730. [self setComplete:YES];
  731. [self markAsFinished];
  732. return;
  733. }
  734. [self setComplete:NO];
  735. [self setDidUseCachedResponse:NO];
  736. if (![self url]) {
  737. [self failWithError:ASIUnableToCreateRequestError];
  738. return;
  739. }
  740. // Must call before we create the request so that the request method can be set if needs be
  741. if (![self mainRequest]) {
  742. [self buildPostBody];
  743. }
  744. if (![[self requestMethod] isEqualToString:@"GET"]) {
  745. [self setDownloadCache:nil];
  746. }
  747. // If we're redirecting, we'll already have a CFHTTPMessageRef
  748. if (request) {
  749. CFRelease(request);
  750. }
  751. // Create a new HTTP request.
  752. request = CFHTTPMessageCreateRequest(kCFAllocatorDefault, (CFStringRef)[self requestMethod], (CFURLRef)[self url], [self useHTTPVersionOne] ? kCFHTTPVersion1_0 : kCFHTTPVersion1_1);
  753. if (!request) {
  754. [self failWithError:ASIUnableToCreateRequestError];
  755. return;
  756. }
  757. //If this is a HEAD request generated by an ASINetworkQueue, we need to let the main request generate its headers first so we can use them
  758. if ([self mainRequest]) {
  759. [[self mainRequest] buildRequestHeaders];
  760. }
  761. // Even if this is a HEAD request with a mainRequest, we still need to call to give subclasses a chance to add their own to HEAD requests (ASIS3Request does this)
  762. [self buildRequestHeaders];
  763. if ([self downloadCache]) {
  764. // If this request should use the default policy, set its policy to the download cache's default policy
  765. if (![self cachePolicy]) {
  766. [self setCachePolicy:[[self downloadCache] defaultCachePolicy]];
  767. }
  768. // If have have cached data that is valid for this request, use that and stop
  769. if ([[self downloadCache] canUseCachedDataForRequest:self]) {
  770. [self useDataFromCache];
  771. return;
  772. }
  773. // If cached data is stale, or we have been told to ask the server if it has been modified anyway, we need to add headers for a conditional GET
  774. if ([self cachePolicy] & (ASIAskServerIfModifiedWhenStaleCachePolicy|ASIAskServerIfModifiedCachePolicy)) {
  775. NSDictionary *cachedHeaders = [[self downloadCache] cachedResponseHeadersForURL:[self url]];
  776. if (cachedHeaders) {
  777. NSString *etag = [cachedHeaders objectForKey:@"Etag"];
  778. if (etag) {
  779. [[self requestHeaders] setObject:etag forKey:@"If-None-Match"];
  780. }
  781. NSString *lastModified = [cachedHeaders objectForKey:@"Last-Modified"];
  782. if (lastModified) {
  783. [[self requestHeaders] setObject:lastModified forKey:@"If-Modified-Since"];
  784. }
  785. }
  786. }
  787. }
  788. [self applyAuthorizationHeader];
  789. NSString *header;
  790. for (header in [self requestHeaders]) {
  791. CFHTTPMessageSetHeaderFieldValue(request, (CFStringRef)header, (CFStringRef)[[self requestHeaders] objectForKey:header]);
  792. }
  793. // If we immediately have access to proxy settings, start the request
  794. // Otherwise, we'll start downloading the proxy PAC file, and call startRequest once that process is complete
  795. if ([self configureProxies]) {
  796. [self startRequest];
  797. }
  798. } @catch (NSException *exception) {
  799. NSError *underlyingError = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASIUnhandledExceptionError userInfo:[exception userInfo]];
  800. [self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIUnhandledExceptionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[exception name],NSLocalizedDescriptionKey,[exception reason],NSLocalizedFailureReasonErrorKey,underlyingError,NSUnderlyingErrorKey,nil]]];
  801. } @finally {
  802. [[self cancelledLock] unlock];
  803. }
  804. }
  805. - (void)applyAuthorizationHeader
  806. {
  807. // Do we want to send credentials before we are asked for them?
  808. if (![self shouldPresentCredentialsBeforeChallenge]) {
  809. #if DEBUG_HTTP_AUTHENTICATION
  810. ASI_DEBUG_LOG(@"[AUTH] Request %@ will not send credentials to the server until it asks for them",self);
  811. #endif
  812. return;
  813. }
  814. NSDictionary *credentials = nil;
  815. // Do we already have an auth header?
  816. if (![[self requestHeaders] objectForKey:@"Authorization"]) {
  817. // If we have basic authentication explicitly set and a username and password set on the request, add a basic auth header
  818. if ([self username] && [self password] && [[self authenticationScheme] isEqualToString:(NSString *)kCFHTTPAuthenticationSchemeBasic]) {
  819. [self addBasicAuthenticationHeaderWithUsername:[self username] andPassword:[self password]];
  820. #if DEBUG_HTTP_AUTHENTICATION
  821. ASI_DEBUG_LOG(@"[AUTH] Request %@ has a username and password set, and was manually configured to use BASIC. Will send credentials without waiting for an authentication challenge",self);
  822. #endif
  823. } else {
  824. // See if we have any cached credentials we can use in the session store
  825. if ([self useSessionPersistence]) {
  826. credentials = [self findSessionAuthenticationCredentials];
  827. if (credentials) {
  828. // When the Authentication key is set, the credentials were stored after an authentication challenge, so we can let CFNetwork apply them
  829. // (credentials for Digest and NTLM will always be stored like this)
  830. if ([credentials objectForKey:@"Authentication"]) {
  831. // If we've already talked to this server and have valid credentials, let's apply them to the request
  832. if (CFHTTPMessageApplyCredentialDictionary(request, (CFHTTPAuthenticationRef)[credentials objectForKey:@"Authentication"], (CFDictionaryRef)[credentials objectForKey:@"Credentials"], NULL)) {
  833. [self setAuthenticationScheme:[credentials objectForKey:@"AuthenticationScheme"]];
  834. #if DEBUG_HTTP_AUTHENTICATION
  835. ASI_DEBUG_LOG(@"[AUTH] Request %@ found cached credentials (%@), will reuse without waiting for an authentication challenge",self,[credentials objectForKey:@"AuthenticationScheme"]);
  836. #endif
  837. } else {
  838. [[self class] removeAuthenticationCredentialsFromSessionStore:[credentials objectForKey:@"Credentials"]];
  839. #if DEBUG_HTTP_AUTHENTICATION
  840. ASI_DEBUG_LOG(@"[AUTH] Failed to apply cached credentials to request %@. These will be removed from the session store, and this request will wait for an authentication challenge",self);
  841. #endif
  842. }
  843. // If the Authentication key is not set, these credentials were stored after a username and password set on a previous request passed basic authentication
  844. // When this happens, we'll need to create the Authorization header ourselves
  845. } else {
  846. NSDictionary *usernameAndPassword = [credentials objectForKey:@"Credentials"];
  847. [self addBasicAuthenticationHeaderWithUsername:[usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationUsername] andPassword:[usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationPassword]];
  848. #if DEBUG_HTTP_AUTHENTICATION
  849. ASI_DEBUG_LOG(@"[AUTH] Request %@ found cached BASIC credentials from a previous request. Will send credentials without waiting for an authentication challenge",self);
  850. #endif
  851. }
  852. }
  853. }
  854. }
  855. }
  856. // Apply proxy authentication credentials
  857. if ([self useSessionPersistence]) {
  858. credentials = [self findSessionProxyAuthenticationCredentials];
  859. if (credentials) {
  860. if (!CFHTTPMessageApplyCredentialDictionary(request, (CFHTTPAuthenticationRef)[credentials objectForKey:@"Authentication"], (CFDictionaryRef)[credentials objectForKey:@"Credentials"], NULL)) {
  861. [[self class] removeProxyAuthenticationCredentialsFromSessionStore:[credentials objectForKey:@"Credentials"]];
  862. }
  863. }
  864. }
  865. }
  866. - (void)applyCookieHeader
  867. {
  868. // Add cookies from the persistent (mac os global) store
  869. if ([self useCookiePersistence]) {
  870. NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[[self url] absoluteURL]];
  871. if (cookies) {
  872. [[self requestCookies] addObjectsFromArray:cookies];
  873. }
  874. }
  875. // Apply request cookies
  876. NSArray *cookies;
  877. if ([self mainRequest]) {
  878. cookies = [[self mainRequest] requestCookies];
  879. } else {
  880. cookies = [self requestCookies];
  881. }
  882. if ([cookies count] > 0) {
  883. NSHTTPCookie *cookie;
  884. NSString *cookieHeader = nil;
  885. for (cookie in cookies) {
  886. if (!cookieHeader) {
  887. cookieHeader = [NSString stringWithFormat: @"%@=%@",[cookie name],[cookie value]];
  888. } else {
  889. cookieHeader = [NSString stringWithFormat: @"%@; %@=%@",cookieHeader,[cookie name],[cookie value]];
  890. }
  891. }
  892. if (cookieHeader) {
  893. [self addRequestHeader:@"Cookie" value:cookieHeader];
  894. }
  895. }
  896. }
  897. - (void)buildRequestHeaders
  898. {
  899. if ([self haveBuiltRequestHeaders]) {
  900. return;
  901. }
  902. [self setHaveBuiltRequestHeaders:YES];
  903. if ([self mainRequest]) {
  904. for (NSString *header in [[self mainRequest] requestHeaders]) {
  905. [self addRequestHeader:header value:[[[self mainRequest] requestHeaders] valueForKey:header]];
  906. }
  907. return;
  908. }
  909. [self applyCookieHeader];
  910. // Build and set the user agent string if the request does not already have a custom user agent specified
  911. if (![[self requestHeaders] objectForKey:@"User-Agent"]) {
  912. NSString *userAgentString = [self userAgent];
  913. if (!userAgentString) {
  914. userAgentString = [ASIHTTPRequest defaultUserAgentString];
  915. }
  916. if (userAgentString) {
  917. [self addRequestHeader:@"User-Agent" value:userAgentString];
  918. }
  919. }
  920. // Accept a compressed response
  921. if ([self allowCompressedResponse]) {
  922. [self addRequestHeader:@"Accept-Encoding" value:@"gzip"];
  923. }
  924. // Configure a compressed request body
  925. if ([self shouldCompressRequestBody]) {
  926. [self addRequestHeader:@"Content-Encoding" value:@"gzip"];
  927. }
  928. // Should this request resume an existing download?
  929. [self updatePartialDownloadSize];
  930. if ([self partialDownloadSize]) {
  931. [self addRequestHeader:@"Range" value:[NSString stringWithFormat:@"bytes=%llu-",[self partialDownloadSize]]];
  932. }
  933. }
  934. - (void)updatePartialDownloadSize
  935. {
  936. NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
  937. if ([self allowResumeForFileDownloads] && [self downloadDestinationPath] && [self temporaryFileDownloadPath] && [fileManager fileExistsAtPath:[self temporaryFileDownloadPath]]) {
  938. NSError *err = nil;
  939. [self setPartialDownloadSize:[[fileManager attributesOfItemAtPath:[self temporaryFileDownloadPath] error:&err] fileSize]];
  940. if (err) {
  941. [self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to get attributes for file at path '%@'",[self temporaryFileDownloadPath]],NSLocalizedDescriptionKey,error,NSUnderlyingErrorKey,nil]]];
  942. return;
  943. }
  944. }
  945. }
  946. - (void)startRequest
  947. {
  948. if ([self isCancelled]) {
  949. return;
  950. }
  951. [self performSelectorOnMainThread:@selector(requestStarted) withObject:nil waitUntilDone:[NSThread isMainThread]];
  952. [self setDownloadComplete:NO];
  953. [self setComplete:NO];
  954. [self setTotalBytesRead:0];
  955. [self setLastBytesRead:0];
  956. if ([self redirectCount] == 0) {
  957. [self setOriginalURL:[self url]];
  958. }
  959. // If we're retrying a request, let's remove any progress we made
  960. if ([self lastBytesSent] > 0) {
  961. [self removeUploadProgressSoFar];
  962. }
  963. [self setLastBytesSent:0];
  964. [self setContentLength:0];
  965. [self setResponseHeaders:nil];
  966. if (![self downloadDestinationPath]) {
  967. [self setRawResponseData:[[[NSMutableData alloc] init] autorelease]];
  968. }
  969. //
  970. // Create the stream for the request
  971. //
  972. NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
  973. [self setReadStreamIsScheduled:NO];
  974. // Do we need to stream the request body from disk
  975. if ([self shouldStreamPostDataFromDisk] && [self postBodyFilePath] && [fileManager fileExistsAtPath:[self postBodyFilePath]]) {
  976. // Are we gzipping the request body?
  977. if ([self compressedPostBodyFilePath] && [fileManager fileExistsAtPath:[self compressedPostBodyFilePath]]) {
  978. [self setPostBodyReadStream:[ASIInputStream inputStreamWithFileAtPath:[self compressedPostBodyFilePath] request:self]];
  979. } else {
  980. [self setPostBodyReadStream:[ASIInputStream inputStreamWithFileAtPath:[self postBodyFilePath] request:self]];
  981. }
  982. [self setReadStream:[NSMakeCollectable(CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request,(CFReadStreamRef)[self postBodyReadStream])) autorelease]];
  983. } else {
  984. // If we have a request body, we'll stream it from memory using our custom stream, so that we can measure bandwidth use and it can be bandwidth-throttled if necessary
  985. if ([self postBody] && [[self postBody] length] > 0) {
  986. if ([self shouldCompressRequestBody] && [self compressedPostBody]) {
  987. [self setPostBodyReadStream:[ASIInputStream inputStreamWithData:[self compressedPostBody] request:self]];
  988. } else if ([self postBody]) {
  989. [self setPostBodyReadStream:[ASIInputStream inputStreamWithData:[self postBody] request:self]];
  990. }
  991. [self setReadStream:[NSMakeCollectable(CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request,(CFReadStreamRef)[self postBodyReadStream])) autorelease]];
  992. } else {
  993. [self setReadStream:[NSMakeCollectable(CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request)) autorelease]];
  994. }
  995. }
  996. if (![self readStream]) {
  997. [self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileBuildingRequestType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to create read stream",NSLocalizedDescriptionKey,nil]]];
  998. return;
  999. }
  1000. //
  1001. // Handle SSL certificate settings
  1002. //
  1003. if([[[[self url] scheme] lowercaseString] isEqualToString:@"https"]) {
  1004. // Tell CFNetwork not to validate SSL certificates
  1005. if (![self validatesSecureCertificate]) {
  1006. // see: http://iphonedevelopment.blogspot.com/2010/05/nsstream-tcp-and-ssl.html
  1007. NSDictionary *sslProperties = [[NSDictionary alloc] initWithObjectsAndKeys:
  1008. [NSNumber numberWithBool:YES], kCFStreamSSLPeerName,
  1009. [NSNumber numberWithBool:YES], kCFStreamSSLValidatesCertificateChain,
  1010. [NSNumber numberWithBool:NO], kCFStreamSSLValidatesCertificateChain,
  1011. kCFNull,kCFStreamSSLPeerName,
  1012. nil];
  1013. CFReadStreamSetProperty((CFReadStreamRef)[self readStream],
  1014. kCFStreamPropertySSLSettings,
  1015. (CFTypeRef)sslProperties);
  1016. }
  1017. // Tell CFNetwork to use a client certificate
  1018. if (clientCertificateIdentity) {
  1019. NSMutableDictionary *sslProperties = [NSMutableDictionary dictionaryWithCapacity:1];
  1020. NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[clientCertificates count]+1];
  1021. // The first object in the array is our SecIdentityRef
  1022. [certificates addObject:(id)clientCertificateIdentity];
  1023. // If we've added any additional certificates, add them too
  1024. for (id cert in clientCertificates) {
  1025. [certificates addObject:cert];
  1026. }
  1027. [sslProperties setObject:certificates forKey:(NSString *)kCFStreamSSLCertificates];
  1028. CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertySSLSettings, sslProperties);
  1029. }
  1030. }
  1031. //
  1032. // Handle proxy settings
  1033. //
  1034. if ([self proxyHost] && [self proxyPort]) {
  1035. NSString *hostKey;
  1036. NSString *portKey;
  1037. if (![self proxyType]) {
  1038. [self setProxyType:(NSString *)kCFProxyTypeHTTP];
  1039. }
  1040. if ([[self proxyType] isEqualToString:(NSString *)kCFProxyTypeSOCKS]) {
  1041. hostKey = (NSString *)kCFStreamPropertySOCKSProxyHost;
  1042. portKey = (NSString *)kCFStreamPropertySOCKSProxyPort;
  1043. } else {
  1044. hostKey = (NSString *)kCFStreamPropertyHTTPProxyHost;
  1045. portKey = (NSString *)kCFStreamPropertyHTTPProxyPort;
  1046. if ([[[[self url] scheme] lowercaseString] isEqualToString:@"https"]) {
  1047. hostKey = (NSString *)kCFStreamPropertyHTTPSProxyHost;
  1048. portKey = (NSString *)kCFStreamPropertyHTTPSProxyPort;
  1049. }
  1050. }
  1051. NSMutableDictionary *proxyToUse = [NSMutableDictionary dictionaryWithObjectsAndKeys:[self proxyHost],hostKey,[NSNumber numberWithInt:[self proxyPort]],portKey,nil];
  1052. if ([[self proxyType] isEqualToString:(NSString *)kCFProxyTypeSOCKS]) {
  1053. CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertySOCKSProxy, proxyToUse);
  1054. } else {
  1055. CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPProxy, proxyToUse);
  1056. }
  1057. }
  1058. //
  1059. // Handle persistent connections
  1060. //
  1061. [ASIHTTPRequest expirePersistentConnections];
  1062. [connectionsLock lock];
  1063. if (![[self url] host] || ![[self url] scheme]) {
  1064. [self setConnectionInfo:nil];
  1065. [self setShouldAttemptPersistentConnection:NO];
  1066. }
  1067. // Will store the old stream that was using this connection (if there was one) so we can clean it up once we've opened our own stream
  1068. NSInputStream *oldStream = nil;
  1069. // Use a persistent connection if possible
  1070. if ([self shouldAttemptPersistentConnection]) {
  1071. // If we are redirecting, we will re-use the current connection only if we are connecting to the same server
  1072. if ([self connectionInfo]) {
  1073. if (![[[self connectionInfo] objectForKey:@"host"] isEqualToString:[[self url] host]] || ![[[self connectionInfo] objectForKey:@"scheme"] isEqualToString:[[self url] scheme]] || [(NSNumber *)[[self connectionInfo] objectForKey:@"port"] intValue] != [[[self url] port] intValue]) {
  1074. [self setConnectionInfo:nil];
  1075. // Check if we should have expired this connection
  1076. } else if ([[[self connectionInfo] objectForKey:@"expires"] timeIntervalSinceNow] < 0) {
  1077. #if DEBUG_PERSISTENT_CONNECTIONS
  1078. ASI_DEBUG_LOG(@"[CONNECTION] Not re-using connection #%i because it has expired",[[[self connectionInfo] objectForKey:@"id"] intValue]);
  1079. #endif
  1080. [persistentConnectionsPool removeObject:[self connectionInfo]];
  1081. [self setConnectionInfo:nil];
  1082. } else if ([[self connectionInfo] objectForKey:@"request"] != nil) {
  1083. //Some other request reused this connection already - we'll have to create a new one
  1084. #if DEBUG_PERSISTENT_CONNECTIONS
  1085. ASI_DEBUG_LOG(@"%@ - Not re-using connection #%i for request #%i because it is already used by request #%i",self,[[[self connectionInfo] objectForKey:@"id"] intValue],[[self requestID] intValue],[[[self connectionInfo] objectForKey:@"request"] intValue]);
  1086. #endif
  1087. [self setConnectionInfo:nil];
  1088. }
  1089. }
  1090. if (![self connectionInfo] && [[self url] host] && [[self url] scheme]) { // We must have a proper url with a host and scheme, or this will explode
  1091. // Look for a connection to the same server in the pool
  1092. for (NSMutableDictionary *existingConnection in persistentConnectionsPool) {
  1093. if (![existingConnection objectForKey:@"request"] && [[existingConnection objectForKey:@"host"] isEqualToString:[[self url] host]] && [[existingConnection objectForKey:@"scheme"] isEqualToString:[[self url] scheme]] && [(NSNumber *)[existingConnection objectForKey:@"port"] intValue] == [[[self url] port] intValue]) {
  1094. [self setConnectionInfo:existingConnection];
  1095. }
  1096. }
  1097. }
  1098. if ([[self connectionInfo] objectForKey:@"stream"]) {
  1099. oldStream = [[[self connectionInfo] objectForKey:@"stream"] retain];
  1100. }
  1101. // No free connection was found in the pool matching the server/scheme/port we're connecting to, we'll need to create a new one
  1102. if (![self connectionInfo]) {
  1103. [self setConnectionInfo:[NSMutableDictionary dictionary]];
  1104. nextConnectionNumberToCreate++;
  1105. [[self connectionInfo] setObject:[NSNumber numberWithInt:nextConnectionNumberToCreate] forKey:@"id"];
  1106. [[self connectionInfo] setObject:[[self url] host] forKey:@"host"];
  1107. [[self connectionInfo] setObject:[NSNumber numberWithInt:[[[self url] port] intValue]] forKey:@"port"];
  1108. [[self connectionInfo] setObject:[[self url] scheme] forKey:@"scheme"];
  1109. [persistentConnectionsPool addObject:[self connectionInfo]];
  1110. }
  1111. // If we are retrying this request, it will already have a requestID
  1112. if (![self requestID]) {
  1113. nextRequestID++;
  1114. [self setRequestID:[NSNumber numberWithUnsignedInt:nextRequestID]];
  1115. }
  1116. [[self connectionInfo] setObject:[self requestID] forKey:@"request"];
  1117. [[self connectionInfo] setObject:[self readStream] forKey:@"stream"];
  1118. CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPAttemptPersistentConnection, kCFBooleanTrue);
  1119. #if DEBUG_PERSISTENT_CONNECTIONS
  1120. ASI_DEBUG_LOG(@"[CONNECTION] Request #%@ will use connection #%i",[self requestID],[[[self connectionInfo] objectForKey:@"id"] intValue]);
  1121. #endif
  1122. // Tag the stream with an id that tells it which connection to use behind the scenes
  1123. // See http://lists.apple.com/archives/macnetworkprog/2008/Dec/msg00001.html for details on this approach
  1124. CFReadStreamSetProperty((CFReadStreamRef)[self readStream], CFSTR("ASIStreamID"), [[self connectionInfo] objectForKey:@"id"]);
  1125. } else {
  1126. #if DEBUG_PERSISTENT_CONNECTIONS
  1127. ASI_DEBUG_LOG(@"[CONNECTION] Request %@ will not use a persistent connection",self);
  1128. #endif
  1129. }
  1130. [connectionsLock unlock];
  1131. // Schedule the stream
  1132. if (![self readStreamIsScheduled] && (!throttleWakeUpTime || [throttleWakeUpTime timeIntervalSinceDate:[NSDate date]] < 0)) {
  1133. [self scheduleReadStream];
  1134. }
  1135. BOOL streamSuccessfullyOpened = NO;
  1136. // Start the HTTP connection
  1137. CFStreamClientContext ctxt = {0, self, NULL, NULL, NULL};
  1138. if (CFReadStreamSetClient((CFReadStreamRef)[self readStream], kNetworkEvents, ReadStreamClientCallBack, &ctxt)) {
  1139. if (CFReadStreamOpen((CFReadStreamRef)[self readStream])) {
  1140. streamSuccessfullyOpened = YES;
  1141. }
  1142. }
  1143. // Here, we'll close the stream that was previously using this connection, if there was one
  1144. // We've kept it open until now (when we've just opened a new stream) so that the new stream can make use of the old connection
  1145. // http://lists.apple.com/archives/Macnetworkprog/2006/Mar/msg00119.html
  1146. if (oldStream) {
  1147. [oldStream close];
  1148. [oldStream release];
  1149. oldStream = nil;
  1150. }
  1151. if (!streamSuccessfullyOpened) {
  1152. [self setConnectionCanBeReused:NO];
  1153. [self destroyReadStream];
  1154. [self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileBuildingRequestType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to start HTTP connection",NSLocalizedDescriptionKey,nil]]];
  1155. return;
  1156. }
  1157. if (![self mainRequest]) {
  1158. if ([self shouldResetUploadProgress]) {
  1159. if ([self showAccurateProgress]) {
  1160. [self incrementUploadSizeBy:[self postLength]];
  1161. } else {
  1162. [self incrementUploadSizeBy:1];
  1163. }
  1164. [ASIHTTPRequest updateProgressIndicator:&uploadProgressDelegate withProgress:0 ofTotal:1];
  1165. }
  1166. if ([self shouldResetDownloadProgress] && ![self partialDownloadSize]) {
  1167. [ASIHTTPRequest updateProgressIndicator:&downloadProgressDelegate withProgress:0 ofTotal:1];
  1168. }
  1169. }
  1170. // Record when the request started, so we can timeout if nothing happens
  1171. [self setLastActivityTime:[NSDate date]];
  1172. [self setStatusTimer:[NSTimer timerWithTimeInterval:0.25 target:self selector:@selector(updateStatus:) userInfo:nil repeats:YES]];
  1173. [[NSRunLoop currentRunLoop] addTimer:[self statusTimer] forMode:[self runLoopMode]];
  1174. }
  1175. - (void)setStatusTimer:(NSTimer *)timer
  1176. {
  1177. CFRetain(self);
  1178. // We must invalidate the old timer here, not before we've created and scheduled a new timer
  1179. // This is because the timer may be the only thing retaining an asynchronous request
  1180. if (statusTimer && timer != statusTimer) {
  1181. [statusTimer invalidate];
  1182. [statusTimer release];
  1183. }
  1184. statusTimer = [timer retain];
  1185. CFRelease(self);
  1186. }
  1187. // This gets fired every 1/4 of a second to update the progress and work out if we need to timeout
  1188. - (void)updateStatus:(NSTimer*)timer
  1189. {
  1190. [self checkRequestStatus];
  1191. if (![self inProgress]) {
  1192. [self setStatusTimer:nil];
  1193. }
  1194. }
  1195. - (void)performRedirect
  1196. {
  1197. [self setURL:[self redirectURL]];
  1198. [self setComplete:YES];
  1199. [self setNeedsRedirect:NO];
  1200. [self setRedirectCount:[self redirectCount]+1];
  1201. if ([self redirectCount] > RedirectionLimit) {
  1202. // Some naughty / badly coded website is trying to force us into a redirection loop. This is not cool.
  1203. [self failWithError:ASITooMuchRedirectionError];
  1204. [self setComplete:YES];
  1205. } else {
  1206. // Go all the way back to the beginning and build the request again, so that we can apply any new cookies
  1207. [self main];
  1208. }
  1209. }
  1210. // Called by delegate to resume loading with a new url after the delegate received request:willRedirectToURL:
  1211. - (void)redirectToURL:(NSURL *)newURL
  1212. {
  1213. [self setRedirectURL:newURL];
  1214. [self performSelector:@selector(performRedirect) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
  1215. }
  1216. - (BOOL)shouldTimeOut
  1217. {
  1218. NSTimeInterval secondsSinceLastActivity = [[NSDate date] timeIntervalSinceDate:lastActivityTime];
  1219. // See if we need to timeout
  1220. if ([self readStream] && [self readStreamIsScheduled] && [self lastActivityTime] && [self timeOutSeconds] > 0 && secondsSinceLastActivity > [self timeOutSeconds]) {
  1221. // We have no body, or we've sent more than the upload buffer size,so we can safely time out here
  1222. if ([self postLength] == 0 || ([self uploadBufferSize] > 0 && [self totalBytesSent] > [self uploadBufferSize])) {
  1223. return YES;
  1224. // ***Black magic warning***
  1225. // We have a body, but we've taken longer than timeOutSeconds to upload the first small chunk of data
  1226. // Since there's no reliable way to track upload progress for the first 32KB (iPhone) or 128KB (Mac) with CFNetwork, we'll be slightly more forgiving on the timeout, as there's a strong chance our connection is just very slow.
  1227. } else if (secondsSinceLastActivity > [self timeOutSeconds]*1.5) {
  1228. return YES;
  1229. }
  1230. }
  1231. return NO;
  1232. }
  1233. - (void)checkRequestStatus
  1234. {
  1235. // We won't let the request cancel while we're updating progress / checking for a timeout
  1236. [[self cancelledLock] lock];
  1237. // See if our NSOperationQueue told us to cancel
  1238. if ([self isCancelled] || [self complete]) {
  1239. [[self cancelledLock] unlock];
  1240. return;
  1241. }
  1242. [self performThrottling];
  1243. if ([self shouldTimeOut]) {
  1244. // Do we need to auto-retry this request?
  1245. if ([self numberOfTimesToRetryOnTimeout] > [self retryCount]) {
  1246. // If we are resuming a download, we may need to update the Range header to take account of data we've just downloaded
  1247. [self updatePartialDownloadSize];
  1248. if ([self partialDownloadSize]) {
  1249. CFHTTPMessageSetHeaderFieldValue(request, (CFStringRef)@"Range", (CFStringRef)[NSString stringWithFormat:@"bytes=%llu-",[self partialDownloadSize]]);
  1250. }
  1251. [self setRetryCount:[self retryCount]+1];
  1252. [self unscheduleReadStream];
  1253. [[self cancelledLock] unlock];
  1254. [self startRequest];
  1255. return;
  1256. }
  1257. [self failWithError:ASIRequestTimedOutError];
  1258. [self cancelLoad];
  1259. [self setComplete:YES];
  1260. [[self cancelledLock] unlock];
  1261. return;
  1262. }
  1263. // readStream will be null if we aren't currently running (perhaps we're waiting for a delegate to supply credentials)
  1264. if ([self readStream]) {
  1265. // If we have a post body
  1266. if ([self postLength]) {
  1267. [self setLastBytesSent:totalBytesSent];
  1268. // Find out how much data we've uploaded so far
  1269. [self setTotalBytesSent:[[NSMakeCollectable(CFReadStreamCopyProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPRequestBytesWrittenCount)) autorelease] unsignedLongLongValue]];
  1270. if (totalBytesSent > lastBytesSent) {
  1271. // We've uploaded more data, reset the timeout
  1272. [self setLastActivityTime:[NSDate date]];
  1273. [ASIHTTPRequest incrementBandwidthUsedInLastSecond:(unsigned long)(totalBytesSent-lastBytesSent)];
  1274. #if DEBUG_REQUEST_STATUS
  1275. if ([self totalBytesSent] == [self postLength]) {
  1276. ASI_DEBUG_LOG(@"[STATUS] Request %@ finished uploading data",self);
  1277. }
  1278. #endif
  1279. }
  1280. }
  1281. [self updateProgressIndicators];
  1282. }
  1283. [[self cancelledLock] unlock];
  1284. }
  1285. // Cancel loading and clean up. DO NOT USE THIS TO CANCEL REQUESTS - use [request cancel] instead
  1286. - (void)cancelLoad
  1287. {
  1288. // If we're in the middle of downloading a PAC file, let's stop that first
  1289. if (PACFileReadStream) {
  1290. [PACFileReadStream setDelegate:nil];
  1291. [PACFileReadStream close];
  1292. [self setPACFileReadStream:nil];
  1293. [self setPACFileData:nil];
  1294. } else if (PACFileRequest) {
  1295. [PACFileRequest setDelegate:nil];
  1296. [PACFileRequest cancel];
  1297. [self setPACFileRequest:nil];
  1298. }
  1299. [self destroyReadStream];
  1300. [[self postBodyReadStream] close];
  1301. [self setPostBodyReadStream:nil];
  1302. if ([self rawResponseData]) {
  1303. if (![self complete]) {
  1304. [self setRawResponseData:nil];
  1305. }
  1306. // If we were downloading to a file
  1307. } else if ([self temporaryFileDownloadPath]) {
  1308. [[self fileDownloadOutputStream] close];
  1309. [self setFileDownloadOutputStream:nil];
  1310. [[self inflatedFileDownloadOutputStream] close];
  1311. [self setInflatedFileDownloadOutputStream:nil];
  1312. // If we haven't said we might want to resume, let's remove the temporary file too
  1313. if (![self complete]) {
  1314. if (![self allowResumeForFileDownloads]) {
  1315. [self removeTemporaryDownloadFile];
  1316. }
  1317. [self removeTemporaryUncompressedDownloadFile];
  1318. }
  1319. }
  1320. // Clean up any temporary file used to store request body for streaming
  1321. if (![self authenticationNeeded] && ![self willRetryRequest] && [self didCreateTemporaryPostDataFile]) {
  1322. [self removeTemporaryUploadFile];
  1323. [self removeTemporaryCompressedUploadFile];
  1324. [self setDidCreateTemporaryPostDataFile:NO];
  1325. }
  1326. }
  1327. #pragma mark HEAD request
  1328. // Used by ASINetworkQueue to create a HEAD request appropriate for this request with the same headers (though you can use it yourself)
  1329. - (ASIHTTPRequest *)HEADRequest
  1330. {
  1331. ASIHTTPRequest *headRequest = [[self class] requestWithURL:[self url]];
  1332. // Copy the properties that make sense for a HEAD request
  1333. [headRequest setRequestHeaders:[[[self requestHeaders] mutableCopy] autorelease]];
  1334. [headRequest setRequestCookies:[[[self requestCookies] mutableCopy] autorelease]];
  1335. [headRequest setUseCookiePersistence:[self useCookiePersistence]];
  1336. [headRequest setUseKeychainPersistence:[self useKeychainPersistence]];
  1337. [headRequest setUseSessionPersistence:[self useSessionPersistence]];
  1338. [headRequest setAllowCompressedResponse:[self allowCompressedResponse]];
  1339. [headRequest setUsername:[self username]];
  1340. [headRequest setPassword:[self password]];
  1341. [headRequest setDomain:[self domain]];
  1342. [headRequest setProxyUsername:[self proxyUsername]];
  1343. [headRequest setProxyPassword:[self proxyPassword]];
  1344. [headRequest setProxyDomain:[self proxyDomain]];
  1345. [headRequest setProxyHost:[self proxyHost]];
  1346. [headRequest setProxyPort:[self proxyPort]];
  1347. [headRequest setProxyType:[self proxyType]];
  1348. [headRequest setShouldPresentAuthenticationDialog:[self shouldPresentAuthenticationDialog]];
  1349. [headRequest setShouldPresentProxyAuthenticationDialog:[self shouldPresentProxyAuthenticationDialog]];
  1350. [headRequest setTimeOutSeconds:[self timeOutSeconds]];
  1351. [headRequest setUseHTTPVersionOne:[self useHTTPVersionOne]];
  1352. [headRequest setValidatesSecureCertificate:[self validatesSecureCertificate]];
  1353. [headRequest setClientCertificateIdentity:clientCertificateIdentity];
  1354. [headRequest setClientCertificates:[[clientCertificates copy] autorelease]];
  1355. [headRequest setPACurl:[self PACurl]];
  1356. [headRequest setShouldPresentCredentialsBeforeChallenge:[self shouldPresentCredentialsBeforeChallenge]];
  1357. [headRequest setNumberOfTimesToRetryOnTimeout:[self numberOfTimesToRetryOnTimeout]];
  1358. [headRequest setShouldUseRFC2616RedirectBehaviour:[self shouldUseRFC2616RedirectBehaviour]];
  1359. [headRequest setShouldAttemptPersistentConnection:[self shouldAttemptPersistentConnection]];
  1360. [headRequest setPersistentConnectionTimeoutSeconds:[self persistentConnectionTimeoutSeconds]];
  1361. [headRequest setMainRequest:self];
  1362. [headRequest setRequestMethod:@"HEAD"];
  1363. return headRequest;
  1364. }
  1365. #pragma mark upload/download progress
  1366. - (void)updateProgressIndicators
  1367. {
  1368. //Only update progress if this isn't a HEAD request used to preset the content-length
  1369. if (![self mainRequest]) {
  1370. if ([self showAccurateProgress] || ([self complete] && ![self updatedProgress])) {
  1371. [self updateUploadProgress];
  1372. [self updateDownloadProgress];
  1373. }
  1374. }
  1375. }
  1376. - (id)uploadProgressDelegate
  1377. {
  1378. [[self cancelledLock] lock];
  1379. id d = [[uploadProgressDelegate retain] autorelease];
  1380. [[self cancelledLock] unlock];
  1381. return d;
  1382. }
  1383. - (void)setUploadProgressDelegate:(id)newDelegate
  1384. {
  1385. [[self cancelledLock] lock];
  1386. uploadProgressDelegate = newDelegate;
  1387. #if !TARGET_OS_IPHONE
  1388. // If the uploadProgressDelegate is an NSProgressIndicator, we set its MaxValue to 1.0 so we can update it as if it were a UIProgressView
  1389. double max = 1.0;
  1390. [ASIHTTPRequest performSelector:@selector(setMaxValue:) onTarget:&uploadProgressDelegate withObject:nil amount:&max callerToRetain:nil];
  1391. #endif
  1392. [[self cancelledLock] unlock];
  1393. }
  1394. - (id)downloadProgressDelegate
  1395. {
  1396. [[self cancelledLock] lock];
  1397. id d = [[downloadProgressDelegate retain] autorelease];
  1398. [[self cancelledLock] unlock];
  1399. return d;
  1400. }
  1401. - (void)setDownloadProgressDelegate:(id)newDelegate
  1402. {
  1403. [[self cancelledLock] lock];
  1404. downloadProgressDelegate = newDelegate;
  1405. #if !TARGET_OS_IPHONE
  1406. // If the downloadProgressDelegate is an NSProgressIndicator, we set its MaxValue to 1.0 so we can update it as if it were a UIProgressView
  1407. double max = 1.0;
  1408. [ASIHTTPRequest performSelector:@selector(setMaxValue:) onTarget:&downloadProgressDelegate withObject:nil amount:&max callerToRetain:nil];
  1409. #endif
  1410. [[self cancelledLock] unlock];
  1411. }
  1412. - (void)updateDownloadProgress
  1413. {
  1414. // We won't update download progress until we've examined the headers, since we might need to authenticate
  1415. if (![self responseHeaders] || [self needsRedirect] || !([self contentLength] || [self complete])) {
  1416. return;
  1417. }
  1418. unsigned long long bytesReadSoFar = [self totalBytesRead]+[self partialDownloadSize];
  1419. unsigned long long value = 0;
  1420. if ([self showAccurateProgress] && [self contentLength]) {
  1421. value = bytesReadSoFar-[self lastBytesRead];
  1422. if (value == 0) {
  1423. return;
  1424. }
  1425. } else {
  1426. value = 1;
  1427. [self setUpdatedProgress:YES];
  1428. }
  1429. if (!value) {
  1430. return;
  1431. }
  1432. [ASIHTTPRequest performSelector:@selector(request:didReceiveBytes:) onTarget:&queue withObject:self amount:&value callerToRetain:self];
  1433. [ASIHTTPRequest performSelector:@selector(request:didReceiveBytes:) onTarget:&downloadProgressDelegate withObject:self amount:&value callerToRetain:self];
  1434. [ASIHTTPRequest updateProgressIndicator:&downloadProgressDelegate withProgress:[self totalBytesRead]+[self partialDownloadSize] ofTotal:[self contentLength]+[self partialDownloadSize]];
  1435. #if NS_BLOCKS_AVAILABLE
  1436. if (bytesReceivedBlock) {
  1437. unsigned long long totalSize = [self contentLength] + [self partialDownloadSize];
  1438. [self performBlockOnMainThread:^{ if (bytesReceivedBlock) { bytesReceivedBlock(value, totalSize); }}];
  1439. }
  1440. #endif
  1441. [self setLastBytesRead:bytesReadSoFar];
  1442. }
  1443. - (void)updateUploadProgress
  1444. {
  1445. if ([self isCancelled] || [self totalBytesSent] == 0) {
  1446. return;
  1447. }
  1448. // If this is the first time we've written to the buffer, totalBytesSent will be the size of the buffer (currently seems to be 128KB on both Leopard and iPhone 2.2.1, 32KB on iPhone 3.0)
  1449. // If request body is less than the buffer size, totalBytesSent will be the total size of the request body
  1450. // We will remove this from any progress display, as kCFStreamPropertyHTTPRequestBytesWrittenCount does not tell us how much data has actually be written
  1451. if ([self uploadBufferSize] == 0 && [self totalBytesSent] != [self postLength]) {
  1452. [self setUploadBufferSize:[self totalBytesSent]];
  1453. [self incrementUploadSizeBy:-[self uploadBufferSize]];
  1454. }
  1455. unsigned long long value = 0;
  1456. if ([self showAccurateProgress]) {
  1457. if ([self totalBytesSent] == [self postLength] || [self lastBytesSent] > 0) {
  1458. value = [self totalBytesSent]-[self lastBytesSent];
  1459. } else {
  1460. return;
  1461. }
  1462. } else {
  1463. value = 1;
  1464. [self setUpdatedProgress:YES];
  1465. }
  1466. if (!value) {
  1467. return;
  1468. }
  1469. [ASIHTTPRequest performSelector:@selector(request:didSendBytes:) onTarget:&queue withObject:self amount:&value callerToRetain:self];
  1470. [ASIHTTPRequest performSelector:@selector(request:didSendBytes:) onTarget:&uploadProgressDelegate withObject:self amount:&value callerToRetain:self];
  1471. [ASIHTTPRequest updateProgressIndicator:&uploadProgressDelegate withProgress:[self totalBytesSent]-[self uploadBufferSize] ofTotal:[self postLength]-[self uploadBufferSize]];
  1472. #if NS_BLOCKS_AVAILABLE
  1473. if(bytesSentBlock){
  1474. unsigned long long totalSize = [self postLength];
  1475. [self performBlockOnMainThread:^{ if (bytesSentBlock) { bytesSentBlock(value, totalSize); }}];
  1476. }
  1477. #endif
  1478. }
  1479. - (void)incrementDownloadSizeBy:(long long)length
  1480. {
  1481. [ASIHTTPRequest performSelector:@selector(request:incrementDownloadSizeBy:) onTarget:&queue withObject:self amount:&length callerToRetain:self];
  1482. [ASIHTTPRequest performSelector:@selector(request:incrementDownloadSizeBy:) onTarget:&downloadProgressDelegate withObject:self amount:&length callerToRetain:self];
  1483. #if NS_BLOCKS_AVAILABLE
  1484. if(downloadSizeIncrementedBlock){
  1485. [self performBlockOnMainThread:^{ if (downloadSizeIncrementedBlock) { downloadSizeIncrementedBlock(length); }}];
  1486. }
  1487. #endif
  1488. }
  1489. - (void)incrementUploadSizeBy:(long long)length
  1490. {
  1491. [ASIHTTPRequest performSelector:@selector(request:incrementUploadSizeBy:) onTarget:&queue withObject:self amount:&length callerToRetain:self];
  1492. [ASIHTTPRequest performSelector:@selector(request:incrementUploadSizeBy:) onTarget:&uploadProgressDelegate withObject:self amount:&length callerToRetain:self];
  1493. #if NS_BLOCKS_AVAILABLE
  1494. if(uploadSizeIncrementedBlock) {
  1495. [self performBlockOnMainThread:^{ if (uploadSizeIncrementedBlock) { uploadSizeIncrementedBlock(length); }}];
  1496. }
  1497. #endif
  1498. }
  1499. - (void)removeUploadProgressSoFar
  1500. {
  1501. long long progressToRemove = -[self totalBytesSent];
  1502. [ASIHTTPRequest performSelector:@selector(request:didSendBytes:) onTarget:&queue withObject:self amount:&progressToRemove callerToRetain:self];
  1503. [ASIHTTPRequest performSelector:@selector(request:didSendBytes:) onTarget:&uploadProgressDelegate withObject:self amount:&progressToRemove callerToRetain:self];
  1504. [ASIHTTPRequest updateProgressIndicator:&uploadProgressDelegate withProgress:0 ofTotal:[self postLength]];
  1505. #if NS_BLOCKS_AVAILABLE
  1506. if(bytesSentBlock){
  1507. unsigned long long totalSize = [self postLength];
  1508. [self performBlockOnMainThread:^{ if (bytesSentBlock) { bytesSentBlock(progressToRemove, totalSize); }}];
  1509. }
  1510. #endif
  1511. }
  1512. #if NS_BLOCKS_AVAILABLE
  1513. - (void)performBlockOnMainThread:(ASIBasicBlock)block
  1514. {
  1515. [self performSelectorOnMainThread:@selector(callBlock:) withObject:[[block copy] autorelease] waitUntilDone:[NSThread isMainThread]];
  1516. }
  1517. - (void)callBlock:(ASIBasicBlock)block
  1518. {
  1519. block();
  1520. }
  1521. #endif
  1522. + (void)performSelector:(SEL)selector onTarget:(id *)target withObject:(id)object amount:(void *)amount callerToRetain:(id)callerToRetain
  1523. {
  1524. if ([*target respondsToSelector:selector]) {
  1525. NSMethodSignature *signature = nil;
  1526. signature = [*target methodSignatureForSelector:selector];
  1527. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
  1528. [invocation setSelector:selector];
  1529. int argumentNumber = 2;
  1530. // If we got an object parameter, we pass a pointer to the object pointer
  1531. if (object) {
  1532. [invocation setArgument:&object atIndex:argumentNumber];
  1533. argumentNumber++;
  1534. }
  1535. // For the amount we'll just pass the pointer directly so NSInvocation will call the method using the number itself rather than a pointer to it
  1536. if (amount) {
  1537. [invocation setArgument:amount atIndex:argumentNumber];
  1538. }
  1539. SEL callback = @selector(performInvocation:onTarget:releasingObject:);
  1540. NSMethodSignature *cbSignature = [ASIHTTPRequest methodSignatureForSelector:callback];
  1541. NSInvocation *cbInvocation = [NSInvocation invocationWithMethodSignature:cbSignature];
  1542. [cbInvocation setSelector:callback];
  1543. [cbInvocation setTarget:self];
  1544. [cbInvocation setArgument:&invocation atIndex:2];
  1545. [cbInvocation setArgument:&target atIndex:3];
  1546. if (callerToRetain) {
  1547. [cbInvocation setArgument:&callerToRetain atIndex:4];
  1548. }
  1549. CFRetain(invocation);
  1550. // Used to pass in a request that we must retain until after the call
  1551. // We're using CFRetain rather than [callerToRetain retain] so things to avoid earthquakes when using garbage collection
  1552. if (callerToRetain) {
  1553. CFRetain(callerToRetain);
  1554. }
  1555. [cbInvocation performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:[NSThread isMainThread]];
  1556. }
  1557. }
  1558. + (void)performInvocation:(NSInvocation *)invocation onTarget:(id *)target releasingObject:(id)objectToRelease
  1559. {
  1560. if (*target && [*target respondsToSelector:[invocation selector]]) {
  1561. [invocation invokeWithTarget:*target];
  1562. }
  1563. CFRelease(invocation);
  1564. if (objectToRelease) {
  1565. CFRelease(objectToRelease);
  1566. }
  1567. }
  1568. + (void)updateProgressIndicator:(id *)indicator withProgress:(unsigned long long)progress ofTotal:(unsigned long long)total
  1569. {
  1570. #if TARGET_OS_IPHONE
  1571. // Cocoa Touch: UIProgressView
  1572. SEL selector = @selector(setProgress:);
  1573. float progressAmount = (float)((progress*1.0)/(total*1.0));
  1574. #else
  1575. // Cocoa: NSProgressIndicator
  1576. double progressAmount = progressAmount = (progress*1.0)/(total*1.0);
  1577. SEL selector = @selector(setDoubleValue:);
  1578. #endif
  1579. if (![*indicator respondsToSelector:selector]) {
  1580. return;
  1581. }
  1582. [progressLock lock];
  1583. [ASIHTTPRequest performSelector:selector onTarget:indicator withObject:nil amount:&progressAmount callerToRetain:nil];
  1584. [progressLock unlock];
  1585. }
  1586. #pragma mark talking to delegates / calling blocks
  1587. /* ALWAYS CALLED ON MAIN THREAD! */
  1588. - (void)requestStarted
  1589. {
  1590. if ([self error] || [self mainRequest]) {
  1591. return;
  1592. }
  1593. if (delegate && [delegate respondsToSelector:didStartSelector]) {
  1594. [delegate performSelector:didStartSelector withObject:self];
  1595. }
  1596. #if NS_BLOCKS_AVAILABLE
  1597. if(startedBlock){
  1598. startedBlock();
  1599. }
  1600. #endif
  1601. if (queue && [queue respondsToSelector:@selector(requestStarted:)]) {
  1602. [queue performSelector:@selector(requestStarted:) withObject:self];
  1603. }
  1604. }
  1605. /* ALWAYS CALLED ON MAIN THREAD! */
  1606. - (void)requestRedirected
  1607. {
  1608. if ([self error] || [self mainRequest]) {
  1609. return;
  1610. }
  1611. if([[self delegate] respondsToSelector:@selector(requestRedirected:)]){
  1612. [[self delegate] performSelector:@selector(requestRedirected:) withObject:self];
  1613. }
  1614. #if NS_BLOCKS_AVAILABLE
  1615. if(requestRedirectedBlock){
  1616. requestRedirectedBlock();
  1617. }
  1618. #endif
  1619. }
  1620. /* ALWAYS CALLED ON MAIN THREAD! */
  1621. - (void)requestReceivedResponseHeaders:(NSMutableDictionary *)newResponseHeaders
  1622. {
  1623. if ([self error] || [self mainRequest]) {
  1624. return;
  1625. }
  1626. if (delegate && [delegate respondsToSelector:didReceiveResponseHeadersSelector]) {
  1627. [delegate performSelector:didReceiveResponseHeadersSelector withObject:self withObject:newResponseHeaders];
  1628. }
  1629. #if NS_BLOCKS_AVAILABLE
  1630. if(headersReceivedBlock){
  1631. headersReceivedBlock(newResponseHeaders);
  1632. }
  1633. #endif
  1634. if (queue && [queue respondsToSelector:@selector(request:didReceiveResponseHeaders:)]) {
  1635. [queue performSelector:@selector(request:didReceiveResponseHeaders:) withObject:self withObject:newResponseHeaders];
  1636. }
  1637. }
  1638. /* ALWAYS CALLED ON MAIN THREAD! */
  1639. - (void)requestWillRedirectToURL:(NSURL *)newURL
  1640. {
  1641. if ([self error] || [self mainRequest]) {
  1642. return;
  1643. }
  1644. if (delegate && [delegate respondsToSelector:willRedirectSelector]) {
  1645. [delegate performSelector:willRedirectSelector withObject:self withObject:newURL];
  1646. }
  1647. if (queue && [queue respondsToSelector:@selector(request:willRedirectToURL:)]) {
  1648. [queue performSelector:@selector(request:willRedirectToURL:) withObject:self withObject:newURL];
  1649. }
  1650. }
  1651. // Subclasses might override this method to process the result in the same thread
  1652. // If you do this, don't forget to call [super requestFinished] to let the queue / delegate know we're done
  1653. - (void)requestFinished
  1654. {
  1655. #if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
  1656. ASI_DEBUG_LOG(@"[STATUS] Request finished: %@",self);
  1657. #endif
  1658. if ([self error] || [self mainRequest]) {
  1659. return;
  1660. }
  1661. if ([self isPACFileRequest]) {
  1662. [self reportFinished];
  1663. } else {
  1664. [self performSelectorOnMainThread:@selector(reportFinished) withObject:nil waitUntilDone:[NSThread isMainThread]];
  1665. }
  1666. }
  1667. /* ALWAYS CALLED ON MAIN THREAD! */
  1668. - (void)reportFinished
  1669. {
  1670. if (delegate == nil)
  1671. {
  1672. return;
  1673. }
  1674. if (delegate && [delegate respondsToSelector:didFinishSelector])
  1675. {
  1676. [delegate performSelector:didFinishSelector withObject:self];
  1677. }
  1678. #if NS_BLOCKS_AVAILABLE
  1679. if(completionBlock){
  1680. completionBlock();
  1681. }
  1682. #endif
  1683. if (queue && [queue respondsToSelector:@selector(requestFinished:)]) {
  1684. [queue performSelector:@selector(requestFinished:) withObject:self];
  1685. }
  1686. }
  1687. /* ALWAYS CALLED ON MAIN THREAD! */
  1688. - (void)reportFailure
  1689. {
  1690. if (delegate && [delegate respondsToSelector:didFailSelector]) {
  1691. [delegate performSelector:didFailSelector withObject:self];
  1692. }
  1693. #if NS_BLOCKS_AVAILABLE
  1694. if(failureBlock){
  1695. failureBlock();
  1696. }
  1697. #endif
  1698. if (queue && [queue respondsToSelector:@selector(requestFailed:)]) {
  1699. [queue performSelector:@selector(requestFailed:) withObject:self];
  1700. }
  1701. }
  1702. /* ALWAYS CALLED ON MAIN THREAD! */
  1703. - (void)passOnReceivedData:(NSData *)data
  1704. {
  1705. if (delegate && [delegate respondsToSelector:didReceiveDataSelector]) {
  1706. [delegate performSelector:didReceiveDataSelector withObject:self withObject:data];
  1707. }
  1708. #if NS_BLOCKS_AVAILABLE
  1709. if (dataReceivedBlock) {
  1710. dataReceivedBlock(data);
  1711. }
  1712. #endif
  1713. }
  1714. // Subclasses might override this method to perform error handling in the same thread
  1715. // If you do this, don't forget to call [super failWithError:] to let the queue / delegate know we're done
  1716. - (void)failWithError:(NSError *)theError
  1717. {
  1718. #if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
  1719. ASI_DEBUG_LOG(@"[STATUS] Request %@: %@",self,(theError == ASIRequestCancelledError ? @"Cancelled" : @"Failed"));
  1720. #endif
  1721. [self setComplete:YES];
  1722. // Invalidate the current connection so subsequent requests don't attempt to reuse it
  1723. if (theError && [theError code] != ASIAuthenticationErrorType && [theError code] != ASITooMuchRedirectionErrorType) {
  1724. [connectionsLock lock];
  1725. #if DEBUG_PERSISTENT_CONNECTIONS
  1726. ASI_DEBUG_LOG(@"[CONNECTION] Request #%@ failed and will invalidate connection #%@",[self requestID],[[self connectionInfo] objectForKey:@"id"]);
  1727. #endif
  1728. [[self connectionInfo] removeObjectForKey:@"request"];
  1729. [persistentConnectionsPool removeObject:[self connectionInfo]];
  1730. [connectionsLock unlock];
  1731. [self destroyReadStream];
  1732. }
  1733. if ([self connectionCanBeReused]) {
  1734. [[self connectionInfo] setObject:[NSDate dateWithTimeIntervalSinceNow:[self persistentConnectionTimeoutSeconds]] forKey:@"expires"];
  1735. }
  1736. if ([self isCancelled] || [self error]) {
  1737. return;
  1738. }
  1739. // If we have cached data, use it and ignore the error when using ASIFallbackToCacheIfLoadFailsCachePolicy
  1740. if ([self downloadCache] && ([self cachePolicy] & ASIFallbackToCacheIfLoadFailsCachePolicy)) {
  1741. if ([[self downloadCache] canUseCachedDataForRequest:self]) {
  1742. [self useDataFromCache];
  1743. return;
  1744. }
  1745. }
  1746. [self setError:theError];
  1747. ASIHTTPRequest *failedRequest = self;
  1748. // If this is a HEAD request created by an ASINetworkQueue or compatible queue delegate, make the main request fail
  1749. if ([self mainRequest]) {
  1750. failedRequest = [self mainRequest];
  1751. [failedRequest setError:theError];
  1752. }
  1753. if ([self isPACFileRequest]) {
  1754. [failedRequest reportFailure];
  1755. } else {
  1756. [failedRequest performSelectorOnMainThread:@selector(reportFailure) withObject:nil waitUntilDone:[NSThread isMainThread]];
  1757. }
  1758. if (!inProgress)
  1759. {
  1760. // if we're not in progress, we can't notify the queue we've finished (doing so can cause a crash later on)
  1761. // "markAsFinished" will be at the start of main() when we are started
  1762. return;
  1763. }
  1764. [self markAsFinished];
  1765. }
  1766. #pragma mark parsing HTTP response headers
  1767. - (void)readResponseHeaders
  1768. {
  1769. [self setAuthenticationNeeded:ASINoAuthenticationNeededYet];
  1770. CFHTTPMessageRef message = (CFHTTPMessageRef)CFReadStreamCopyProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPResponseHeader);
  1771. if (!message) {
  1772. return;
  1773. }
  1774. // Make sure we've received all the headers
  1775. if (!CFHTTPMessageIsHeaderComplete(message)) {
  1776. CFRelease(message);
  1777. return;
  1778. }
  1779. #if DEBUG_REQUEST_STATUS
  1780. if ([self totalBytesSent] == [self postLength]) {
  1781. ASI_DEBUG_LOG(@"[STATUS] Request %@ received response headers",self);
  1782. }
  1783. #endif
  1784. [self setResponseHeaders:[NSMakeCollectable(CFHTTPMessageCopyAllHeaderFields(message)) autorelease]];
  1785. [self setResponseStatusCode:(int)CFHTTPMessageGetResponseStatusCode(message)];
  1786. [self setResponseStatusMessage:[NSMakeCollectable(CFHTTPMessageCopyResponseStatusLine(message)) autorelease]];
  1787. if ([self downloadCache] && ([[self downloadCache] canUseCachedDataForRequest:self])) {
  1788. // Update the expiry date
  1789. [[self downloadCache] updateExpiryForRequest:self maxAge:[self secondsToCache]];
  1790. // Read the response from the cache
  1791. [self useDataFromCache];
  1792. CFRelease(message);
  1793. return;
  1794. }
  1795. // Is the server response a challenge for credentials?
  1796. if ([self responseStatusCode] == 401) {
  1797. [self setAuthenticationNeeded:ASIHTTPAuthenticationNeeded];
  1798. } else if ([self responseStatusCode] == 407) {
  1799. [self setAuthenticationNeeded:ASIProxyAuthenticationNeeded];
  1800. } else {
  1801. #if DEBUG_HTTP_AUTHENTICATION
  1802. if ([self authenticationScheme]) {
  1803. ASI_DEBUG_LOG(@"[AUTH] Request %@ has passed %@ authentication",self,[self authenticationScheme]);
  1804. }
  1805. #endif
  1806. }
  1807. // Authentication succeeded, or no authentication was required
  1808. if (![self authenticationNeeded]) {
  1809. // Did we get here without an authentication challenge? (which can happen when shouldPresentCredentialsBeforeChallenge is YES and basic auth was successful)
  1810. if (!requestAuthentication && [[self authenticationScheme] isEqualToString:(NSString *)kCFHTTPAuthenticationSchemeBasic] && [self username] && [self password] && [self useSessionPersistence]) {
  1811. #if DEBUG_HTTP_AUTHENTICATION
  1812. ASI_DEBUG_LOG(@"[AUTH] Request %@ passed BASIC authentication, and will save credentials in the session store for future use",self);
  1813. #endif
  1814. NSMutableDictionary *newCredentials = [NSMutableDictionary dictionaryWithCapacity:2];
  1815. [newCredentials setObject:[self username] forKey:(NSString *)kCFHTTPAuthenticationUsername];
  1816. [newCredentials setObject:[self password] forKey:(NSString *)kCFHTTPAuthenticationPassword];
  1817. // Store the credentials in the session
  1818. NSMutableDictionary *sessionCredentials = [NSMutableDictionary dictionary];
  1819. [sessionCredentials setObject:newCredentials forKey:@"Credentials"];
  1820. [sessionCredentials setObject:[self url] forKey:@"URL"];
  1821. [sessionCredentials setObject:(NSString *)kCFHTTPAuthenticationSchemeBasic forKey:@"AuthenticationScheme"];
  1822. [[self class] storeAuthenticationCredentialsInSessionStore:sessionCredentials];
  1823. }
  1824. }
  1825. // Read response textEncoding
  1826. [self parseStringEncodingFromHeaders];
  1827. // Handle cookies
  1828. NSArray *newCookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[self responseHeaders] forURL:[self url]];
  1829. [self setResponseCookies:newCookies];
  1830. if ([self useCookiePersistence]) {
  1831. // Store cookies in global persistent store
  1832. [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:newCookies forURL:[self url] mainDocumentURL:nil];
  1833. // We also keep any cookies in the sessionCookies array, so that we have a reference to them if we need to remove them later
  1834. NSHTTPCookie *cookie;
  1835. for (cookie in newCookies) {
  1836. [ASIHTTPRequest addSessionCookie:cookie];
  1837. }
  1838. }
  1839. // Do we need to redirect?
  1840. if (![self willRedirect]) {
  1841. // See if we got a Content-length header
  1842. NSString *cLength = [responseHeaders valueForKey:@"Content-Length"];
  1843. ASIHTTPRequest *theRequest = self;
  1844. if ([self mainRequest]) {
  1845. theRequest = [self mainRequest];
  1846. }
  1847. if (cLength) {
  1848. unsigned long long length = strtoull([cLength UTF8String], NULL, 0);
  1849. // Workaround for Apache HEAD requests for dynamically generated content returning the wrong Content-Length when using gzip
  1850. if ([self mainRequest] && [self allowCompressedResponse] && length == 20 && [self showAccurateProgress] && [self shouldResetDownloadProgress]) {
  1851. [[self mainRequest] setShowAccurateProgress:NO];
  1852. [[self mainRequest] incrementDownloadSizeBy:1];
  1853. } else {
  1854. [theRequest setContentLength:length];
  1855. if ([self showAccurateProgress] && [self shouldResetDownloadProgress]) {
  1856. [theRequest incrementDownloadSizeBy:[theRequest contentLength]+[theRequest partialDownloadSize]];
  1857. }
  1858. }
  1859. } else if ([self showAccurateProgress] && [self shouldResetDownloadProgress]) {
  1860. [theRequest setShowAccurateProgress:NO];
  1861. [theRequest incrementDownloadSizeBy:1];
  1862. }
  1863. }
  1864. // Handle connection persistence
  1865. if ([self shouldAttemptPersistentConnection]) {
  1866. NSString *connectionHeader = [[[self responseHeaders] objectForKey:@"Connection"] lowercaseString];
  1867. NSString *httpVersion = [NSMakeCollectable(CFHTTPMessageCopyVersion(message)) autorelease];
  1868. // Don't re-use the connection if the server is HTTP 1.0 and didn't send Connection: Keep-Alive
  1869. if (![httpVersion isEqualToString:(NSString *)kCFHTTPVersion1_0] || [connectionHeader isEqualToString:@"keep-alive"]) {
  1870. // See if server explicitly told us to close the connection
  1871. if (![connectionHeader isEqualToString:@"close"]) {
  1872. NSString *keepAliveHeader = [[self responseHeaders] objectForKey:@"Keep-Alive"];
  1873. // If we got a keep alive header, we'll reuse the connection for as long as the server tells us
  1874. if (keepAliveHeader) {
  1875. int timeout = 0;
  1876. int max = 0;
  1877. NSScanner *scanner = [NSScanner scannerWithString:keepAliveHeader];
  1878. [scanner scanString:@"timeout=" intoString:NULL];
  1879. [scanner scanInt:&timeout];
  1880. [scanner scanUpToString:@"max=" intoString:NULL];
  1881. [scanner scanString:@"max=" intoString:NULL];
  1882. [scanner scanInt:&max];
  1883. if (max > 5) {
  1884. [self setConnectionCanBeReused:YES];
  1885. [self setPersistentConnectionTimeoutSeconds:timeout];
  1886. #if DEBUG_PERSISTENT_CONNECTIONS
  1887. ASI_DEBUG_LOG(@"[CONNECTION] Got a keep-alive header, will keep this connection open for %f seconds", [self persistentConnectionTimeoutSeconds]);
  1888. #endif
  1889. }
  1890. // Otherwise, we'll assume we can keep this connection open
  1891. } else {
  1892. [self setConnectionCanBeReused:YES];
  1893. #if DEBUG_PERSISTENT_CONNECTIONS
  1894. ASI_DEBUG_LOG(@"[CONNECTION] Got no keep-alive header, will keep this connection open for %f seconds", [self persistentConnectionTimeoutSeconds]);
  1895. #endif
  1896. }
  1897. }
  1898. }
  1899. }
  1900. CFRelease(message);
  1901. [self performSelectorOnMainThread:@selector(requestReceivedResponseHeaders:) withObject:[[[self responseHeaders] copy] autorelease] waitUntilDone:[NSThread isMainThread]];
  1902. }
  1903. - (BOOL)willRedirect
  1904. {
  1905. // Do we need to redirect?
  1906. if (![self shouldRedirect] || ![responseHeaders valueForKey:@"Location"]) {
  1907. return NO;
  1908. }
  1909. // Note that ASIHTTPRequest does not currently support 305 Use Proxy
  1910. int responseCode = [self responseStatusCode];
  1911. if (responseCode != 301 && responseCode != 302 && responseCode != 303 && responseCode != 307) {
  1912. return NO;
  1913. }
  1914. [self performSelectorOnMainThread:@selector(requestRedirected) withObject:nil waitUntilDone:[NSThread isMainThread]];
  1915. // By default, we redirect 301 and 302 response codes as GET requests
  1916. // According to RFC 2616 this is wrong, but this is what most browsers do, so it's probably what you're expecting to happen
  1917. // See also:
  1918. // http://allseeing-i.lighthouseapp.com/projects/27881/tickets/27-302-redirection-issue
  1919. if (responseCode != 307 && (![self shouldUseRFC2616RedirectBehaviour] || responseCode == 303)) {
  1920. [self setRequestMethod:@"GET"];
  1921. [self setPostBody:nil];
  1922. [self setPostLength:0];
  1923. // Perhaps there are other headers we should be preserving, but it's hard to know what we need to keep and what to throw away.
  1924. NSString *userAgentHeader = [[self requestHeaders] objectForKey:@"User-Agent"];
  1925. NSString *acceptHeader = [[self requestHeaders] objectForKey:@"Accept"];
  1926. [self setRequestHeaders:nil];
  1927. if (userAgentHeader) {
  1928. [self addRequestHeader:@"User-Agent" value:userAgentHeader];
  1929. }
  1930. if (acceptHeader) {
  1931. [self addRequestHeader:@"Accept" value:acceptHeader];
  1932. }
  1933. [self setHaveBuiltRequestHeaders:NO];
  1934. } else {
  1935. // Force rebuild the cookie header incase we got some new cookies from this request
  1936. // All other request headers will remain as they are for 301 / 302 redirects
  1937. [self applyCookieHeader];
  1938. }
  1939. // Force the redirected request to rebuild the request headers (if not a 303, it will re-use old ones, and add any new ones)
  1940. [self setRedirectURL:[[NSURL URLWithString:[responseHeaders valueForKey:@"Location"] relativeToURL:[self url]] absoluteURL]];
  1941. [self setNeedsRedirect:YES];
  1942. // Clear the request cookies
  1943. // This means manually added cookies will not be added to the redirect request - only those stored in the global persistent store
  1944. // But, this is probably the safest option - we might be redirecting to a different domain
  1945. [self setRequestCookies:[NSMutableArray array]];
  1946. #if DEBUG_REQUEST_STATUS
  1947. ASI_DEBUG_LOG(@"[STATUS] Request will redirect (code: %i): %@",responseCode,self);
  1948. #endif
  1949. return YES;
  1950. }
  1951. - (void)parseStringEncodingFromHeaders
  1952. {
  1953. // Handle response text encoding
  1954. NSStringEncoding charset = 0;
  1955. NSString *mimeType = nil;
  1956. [[self class] parseMimeType:&mimeType andResponseEncoding:&charset fromContentType:[[self responseHeaders] valueForKey:@"Content-Type"]];
  1957. if (charset != 0) {
  1958. [self setResponseEncoding:charset];
  1959. } else {
  1960. [self setResponseEncoding:[self defaultResponseEncoding]];
  1961. }
  1962. }
  1963. #pragma mark http authentication
  1964. - (void)saveProxyCredentialsToKeychain:(NSDictionary *)newCredentials
  1965. {
  1966. NSURLCredential *authenticationCredentials = [NSURLCredential credentialWithUser:[newCredentials objectForKey:(NSString *)kCFHTTPAuthenticationUsername] password:[newCredentials objectForKey:(NSString *)kCFHTTPAuthenticationPassword] persistence:NSURLCredentialPersistencePermanent];
  1967. if (authenticationCredentials) {
  1968. [ASIHTTPRequest saveCredentials:authenticationCredentials forProxy:[self proxyHost] port:[self proxyPort] realm:[self proxyAuthenticationRealm]];
  1969. }
  1970. }
  1971. - (void)saveCredentialsToKeychain:(NSDictionary *)newCredentials
  1972. {
  1973. NSURLCredential *authenticationCredentials = [NSURLCredential credentialWithUser:[newCredentials objectForKey:(NSString *)kCFHTTPAuthenticationUsername] password:[newCredentials objectForKey:(NSString *)kCFHTTPAuthenticationPassword] persistence:NSURLCredentialPersistencePermanent];
  1974. if (authenticationCredentials) {
  1975. [ASIHTTPRequest saveCredentials:authenticationCredentials forHost:[[self url] host] port:[[[self url] port] intValue] protocol:[[self url] scheme] realm:[self authenticationRealm]];
  1976. }
  1977. }
  1978. - (BOOL)applyProxyCredentials:(NSDictionary *)newCredentials
  1979. {
  1980. [self setProxyAuthenticationRetryCount:[self proxyAuthenticationRetryCount]+1];
  1981. if (newCredentials && proxyAuthentication && request) {
  1982. // Apply whatever credentials we've built up to the old request
  1983. if (CFHTTPMessageApplyCredentialDictionary(request, proxyAuthentication, (CFMutableDictionaryRef)newCredentials, NULL)) {
  1984. //If we have credentials and they're ok, let's save them to the keychain
  1985. if (useKeychainPersistence) {
  1986. [self saveProxyCredentialsToKeychain:newCredentials];
  1987. }
  1988. if (useSessionPersistence) {
  1989. NSMutableDictionary *sessionProxyCredentials = [NSMutableDictionary dictionary];
  1990. [sessionProxyCredentials setObject:(id)proxyAuthentication forKey:@"Authentication"];
  1991. [sessionProxyCredentials setObject:newCredentials forKey:@"Credentials"];
  1992. [sessionProxyCredentials setObject:[self proxyHost] forKey:@"Host"];
  1993. [sessionProxyCredentials setObject:[NSNumber numberWithInt:[self proxyPort]] forKey:@"Port"];
  1994. [sessionProxyCredentials setObject:[self proxyAuthenticationScheme] forKey:@"AuthenticationScheme"];
  1995. [[self class] storeProxyAuthenticationCredentialsInSessionStore:sessionProxyCredentials];
  1996. }
  1997. [self setProxyCredentials:newCredentials];
  1998. return YES;
  1999. } else {
  2000. [[self class] removeProxyAuthenticationCredentialsFromSessionStore:newCredentials];
  2001. }
  2002. }
  2003. return NO;
  2004. }
  2005. - (BOOL)applyCredentials:(NSDictionary *)newCredentials
  2006. {
  2007. [self setAuthenticationRetryCount:[self authenticationRetryCount]+1];
  2008. if (newCredentials && requestAuthentication && request) {
  2009. // Apply whatever credentials we've built up to the old request
  2010. if (CFHTTPMessageApplyCredentialDictionary(request, requestAuthentication, (CFMutableDictionaryRef)newCredentials, NULL)) {
  2011. //If we have credentials and they're ok, let's save them to the keychain
  2012. if (useKeychainPersistence) {
  2013. [self saveCredentialsToKeychain:newCredentials];
  2014. }
  2015. if (useSessionPersistence) {
  2016. NSMutableDictionary *sessionCredentials = [NSMutableDictionary dictionary];
  2017. [sessionCredentials setObject:(id)requestAuthentication forKey:@"Authentication"];
  2018. [sessionCredentials setObject:newCredentials forKey:@"Credentials"];
  2019. [sessionCredentials setObject:[self url] forKey:@"URL"];
  2020. [sessionCredentials setObject:[self authenticationScheme] forKey:@"AuthenticationScheme"];
  2021. if ([self authenticationRealm]) {
  2022. [sessionCredentials setObject:[self authenticationRealm] forKey:@"AuthenticationRealm"];
  2023. }
  2024. [[self class] storeAuthenticationCredentialsInSessionStore:sessionCredentials];
  2025. }
  2026. [self setRequestCredentials:newCredentials];
  2027. return YES;
  2028. } else {
  2029. [[self class] removeAuthenticationCredentialsFromSessionStore:newCredentials];
  2030. }
  2031. }
  2032. return NO;
  2033. }
  2034. - (NSMutableDictionary *)findProxyCredentials
  2035. {
  2036. NSMutableDictionary *newCredentials = [[[NSMutableDictionary alloc] init] autorelease];
  2037. NSString *user = nil;
  2038. NSString *pass = nil;
  2039. ASIHTTPRequest *theRequest = [self mainRequest];
  2040. // If this is a HEAD request generated by an ASINetworkQueue, we'll try to use the details from the main request
  2041. if ([theRequest proxyUsername] && [theRequest proxyPassword]) {
  2042. user = [theRequest proxyUsername];
  2043. pass = [theRequest proxyPassword];
  2044. // Let's try to use the ones set in this object
  2045. } else if ([self proxyUsername] && [self proxyPassword]) {
  2046. user = [self proxyUsername];
  2047. pass = [self proxyPassword];
  2048. }
  2049. // When we connect to a website using NTLM via a proxy, we will use the main credentials
  2050. if ((!user || !pass) && [self proxyAuthenticationScheme] == (NSString *)kCFHTTPAuthenticationSchemeNTLM) {
  2051. user = [self username];
  2052. pass = [self password];
  2053. }
  2054. // Ok, that didn't work, let's try the keychain
  2055. // For authenticating proxies, we'll look in the keychain regardless of the value of useKeychainPersistence
  2056. if ((!user || !pass)) {
  2057. NSURLCredential *authenticationCredentials = [ASIHTTPRequest savedCredentialsForProxy:[self proxyHost] port:[self proxyPort] protocol:[[self url] scheme] realm:[self proxyAuthenticationRealm]];
  2058. if (authenticationCredentials) {
  2059. user = [authenticationCredentials user];
  2060. pass = [authenticationCredentials password];
  2061. }
  2062. }
  2063. // Handle NTLM, which requires a domain to be set too
  2064. if (CFHTTPAuthenticationRequiresAccountDomain(proxyAuthentication)) {
  2065. NSString *ntlmDomain = [self proxyDomain];
  2066. // If we have no domain yet
  2067. if (!ntlmDomain || [ntlmDomain length] == 0) {
  2068. // Let's try to extract it from the username
  2069. NSArray* ntlmComponents = [user componentsSeparatedByString:@"\\"];
  2070. if ([ntlmComponents count] == 2) {
  2071. ntlmDomain = [ntlmComponents objectAtIndex:0];
  2072. user = [ntlmComponents objectAtIndex:1];
  2073. // If we are connecting to a website using NTLM, but we are connecting via a proxy, the string we need may be in the domain property
  2074. } else {
  2075. ntlmDomain = [self domain];
  2076. }
  2077. if (!ntlmDomain) {
  2078. ntlmDomain = @"";
  2079. }
  2080. }
  2081. [newCredentials setObject:ntlmDomain forKey:(NSString *)kCFHTTPAuthenticationAccountDomain];
  2082. }
  2083. // If we have a username and password, let's apply them to the request and continue
  2084. if (user && pass) {
  2085. [newCredentials setObject:user forKey:(NSString *)kCFHTTPAuthenticationUsername];
  2086. [newCredentials setObject:pass forKey:(NSString *)kCFHTTPAuthenticationPassword];
  2087. return newCredentials;
  2088. }
  2089. return nil;
  2090. }
  2091. - (NSMutableDictionary *)findCredentials
  2092. {
  2093. NSMutableDictionary *newCredentials = [[[NSMutableDictionary alloc] init] autorelease];
  2094. // First, let's look at the url to see if the username and password were included
  2095. NSString *user = [[self url] user];
  2096. NSString *pass = [[self url] password];
  2097. if (user && pass) {
  2098. #if DEBUG_HTTP_AUTHENTICATION
  2099. ASI_DEBUG_LOG(@"[AUTH] Request %@ will use credentials set on its url",self);
  2100. #endif
  2101. } else {
  2102. // If this is a HEAD request generated by an ASINetworkQueue, we'll try to use the details from the main request
  2103. if ([self mainRequest] && [[self mainRequest] username] && [[self mainRequest] password]) {
  2104. user = [[self mainRequest] username];
  2105. pass = [[self mainRequest] password];
  2106. #if DEBUG_HTTP_AUTHENTICATION
  2107. ASI_DEBUG_LOG(@"[AUTH] Request %@ will use credentials from its parent request",self);
  2108. #endif
  2109. // Let's try to use the ones set in this object
  2110. } else if ([self username] && [self password]) {
  2111. user = [self username];
  2112. pass = [self password];
  2113. #if DEBUG_HTTP_AUTHENTICATION
  2114. ASI_DEBUG_LOG(@"[AUTH] Request %@ will use username and password properties as credentials",self);
  2115. #endif
  2116. }
  2117. }
  2118. // Ok, that didn't work, let's try the keychain
  2119. if ((!user || !pass) && useKeychainPersistence) {
  2120. NSURLCredential *authenticationCredentials = [ASIHTTPRequest savedCredentialsForHost:[[self url] host] port:[[[self url] port] intValue] protocol:[[self url] scheme] realm:[self authenticationRealm]];
  2121. if (authenticationCredentials) {
  2122. user = [authenticationCredentials user];
  2123. pass = [authenticationCredentials password];
  2124. #if DEBUG_HTTP_AUTHENTICATION
  2125. if (user && pass) {
  2126. ASI_DEBUG_LOG(@"[AUTH] Request %@ will use credentials from the keychain",self);
  2127. }
  2128. #endif
  2129. }
  2130. }
  2131. // Handle NTLM, which requires a domain to be set too
  2132. if (CFHTTPAuthenticationRequiresAccountDomain(requestAuthentication)) {
  2133. NSString *ntlmDomain = [self domain];
  2134. // If we have no domain yet, let's try to extract it from the username
  2135. if (!ntlmDomain || [ntlmDomain length] == 0) {
  2136. ntlmDomain = @"";
  2137. NSArray* ntlmComponents = [user componentsSeparatedByString:@"\\"];
  2138. if ([ntlmComponents count] == 2) {
  2139. ntlmDomain = [ntlmComponents objectAtIndex:0];
  2140. user = [ntlmComponents objectAtIndex:1];
  2141. }
  2142. }
  2143. [newCredentials setObject:ntlmDomain forKey:(NSString *)kCFHTTPAuthenticationAccountDomain];
  2144. }
  2145. // If we have a username and password, let's apply them to the request and continue
  2146. if (user && pass) {
  2147. [newCredentials setObject:user forKey:(NSString *)kCFHTTPAuthenticationUsername];
  2148. [newCredentials setObject:pass forKey:(NSString *)kCFHTTPAuthenticationPassword];
  2149. return newCredentials;
  2150. }
  2151. return nil;
  2152. }
  2153. // Called by delegate or authentication dialog to resume loading once authentication info has been populated
  2154. - (void)retryUsingSuppliedCredentials
  2155. {
  2156. #if DEBUG_HTTP_AUTHENTICATION
  2157. ASI_DEBUG_LOG(@"[AUTH] Request %@ received credentials from its delegate or an ASIAuthenticationDialog, will retry",self);
  2158. #endif
  2159. //If the url was changed by the delegate, our CFHTTPMessageRef will be NULL and we'll go back to the start
  2160. if (!request) {
  2161. [self performSelector:@selector(main) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
  2162. return;
  2163. }
  2164. [self performSelector:@selector(attemptToApplyCredentialsAndResume) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
  2165. }
  2166. // Called by delegate or authentication dialog to cancel authentication
  2167. - (void)cancelAuthentication
  2168. {
  2169. #if DEBUG_HTTP_AUTHENTICATION
  2170. ASI_DEBUG_LOG(@"[AUTH] Request %@ had authentication cancelled by its delegate or an ASIAuthenticationDialog",self);
  2171. #endif
  2172. [self performSelector:@selector(failAuthentication) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
  2173. }
  2174. - (void)failAuthentication
  2175. {
  2176. [self failWithError:ASIAuthenticationError];
  2177. }
  2178. - (BOOL)showProxyAuthenticationDialog
  2179. {
  2180. if ([self isSynchronous]) {
  2181. return NO;
  2182. }
  2183. // Mac authentication dialog coming soon!
  2184. #if TARGET_OS_IPHONE
  2185. if ([self shouldPresentProxyAuthenticationDialog]) {
  2186. [ASIAuthenticationDialog performSelectorOnMainThread:@selector(presentAuthenticationDialogForRequest:) withObject:self waitUntilDone:[NSThread isMainThread]];
  2187. return YES;
  2188. }
  2189. return NO;
  2190. #else
  2191. return NO;
  2192. #endif
  2193. }
  2194. - (BOOL)willAskDelegateForProxyCredentials
  2195. {
  2196. if ([self isSynchronous]) {
  2197. return NO;
  2198. }
  2199. // If we have a delegate, we'll see if it can handle proxyAuthenticationNeededForRequest:.
  2200. // Otherwise, we'll try the queue (if this request is part of one) and it will pass the message on to its own delegate
  2201. id authenticationDelegate = [self delegate];
  2202. if (!authenticationDelegate) {
  2203. authenticationDelegate = [self queue];
  2204. }
  2205. BOOL delegateOrBlockWillHandleAuthentication = NO;
  2206. if ([authenticationDelegate respondsToSelector:@selector(proxyAuthenticationNeededForRequest:)]) {
  2207. delegateOrBlockWillHandleAuthentication = YES;
  2208. }
  2209. #if NS_BLOCKS_AVAILABLE
  2210. if(proxyAuthenticationNeededBlock){
  2211. delegateOrBlockWillHandleAuthentication = YES;
  2212. }
  2213. #endif
  2214. if (delegateOrBlockWillHandleAuthentication) {
  2215. [self performSelectorOnMainThread:@selector(askDelegateForProxyCredentials) withObject:nil waitUntilDone:NO];
  2216. }
  2217. return delegateOrBlockWillHandleAuthentication;
  2218. }
  2219. /* ALWAYS CALLED ON MAIN THREAD! */
  2220. - (void)askDelegateForProxyCredentials
  2221. {
  2222. id authenticationDelegate = [self delegate];
  2223. if (!authenticationDelegate) {
  2224. authenticationDelegate = [self queue];
  2225. }
  2226. if ([authenticationDelegate respondsToSelector:@selector(proxyAuthenticationNeededForRequest:)]) {
  2227. [authenticationDelegate performSelector:@selector(proxyAuthenticationNeededForRequest:) withObject:self];
  2228. return;
  2229. }
  2230. #if NS_BLOCKS_AVAILABLE
  2231. if(proxyAuthenticationNeededBlock){
  2232. proxyAuthenticationNeededBlock();
  2233. }
  2234. #endif
  2235. }
  2236. - (BOOL)willAskDelegateForCredentials
  2237. {
  2238. if ([self isSynchronous]) {
  2239. return NO;
  2240. }
  2241. // If we have a delegate, we'll see if it can handle proxyAuthenticationNeededForRequest:.
  2242. // Otherwise, we'll try the queue (if this request is part of one) and it will pass the message on to its own delegate
  2243. id authenticationDelegate = [self delegate];
  2244. if (!authenticationDelegate) {
  2245. authenticationDelegate = [self queue];
  2246. }
  2247. BOOL delegateOrBlockWillHandleAuthentication = NO;
  2248. if ([authenticationDelegate respondsToSelector:@selector(authenticationNeededForRequest:)]) {
  2249. delegateOrBlockWillHandleAuthentication = YES;
  2250. }
  2251. #if NS_BLOCKS_AVAILABLE
  2252. if (authenticationNeededBlock) {
  2253. delegateOrBlockWillHandleAuthentication = YES;
  2254. }
  2255. #endif
  2256. if (delegateOrBlockWillHandleAuthentication) {
  2257. [self performSelectorOnMainThread:@selector(askDelegateForCredentials) withObject:nil waitUntilDone:NO];
  2258. }
  2259. return delegateOrBlockWillHandleAuthentication;
  2260. }
  2261. /* ALWAYS CALLED ON MAIN THREAD! */
  2262. - (void)askDelegateForCredentials
  2263. {
  2264. id authenticationDelegate = [self delegate];
  2265. if (!authenticationDelegate) {
  2266. authenticationDelegate = [self queue];
  2267. }
  2268. if ([authenticationDelegate respondsToSelector:@selector(authenticationNeededForRequest:)]) {
  2269. [authenticationDelegate performSelector:@selector(authenticationNeededForRequest:) withObject:self];
  2270. return;
  2271. }
  2272. #if NS_BLOCKS_AVAILABLE
  2273. if (authenticationNeededBlock) {
  2274. authenticationNeededBlock();
  2275. }
  2276. #endif
  2277. }
  2278. - (void)attemptToApplyProxyCredentialsAndResume
  2279. {
  2280. if ([self error] || [self isCancelled]) {
  2281. return;
  2282. }
  2283. // Read authentication data
  2284. if (!proxyAuthentication) {
  2285. CFHTTPMessageRef responseHeader = (CFHTTPMessageRef) CFReadStreamCopyProperty((CFReadStreamRef)[self readStream],kCFStreamPropertyHTTPResponseHeader);
  2286. proxyAuthentication = CFHTTPAuthenticationCreateFromResponse(NULL, responseHeader);
  2287. CFRelease(responseHeader);
  2288. [self setProxyAuthenticationScheme:[NSMakeCollectable(CFHTTPAuthenticationCopyMethod(proxyAuthentication)) autorelease]];
  2289. }
  2290. // If we haven't got a CFHTTPAuthenticationRef by now, something is badly wrong, so we'll have to give up
  2291. if (!proxyAuthentication) {
  2292. [self cancelLoad];
  2293. [self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to get authentication object from response headers",NSLocalizedDescriptionKey,nil]]];
  2294. return;
  2295. }
  2296. // Get the authentication realm
  2297. [self setProxyAuthenticationRealm:nil];
  2298. if (!CFHTTPAuthenticationRequiresAccountDomain(proxyAuthentication)) {
  2299. [self setProxyAuthenticationRealm:[NSMakeCollectable(CFHTTPAuthenticationCopyRealm(proxyAuthentication)) autorelease]];
  2300. }
  2301. // See if authentication is valid
  2302. CFStreamError err;
  2303. if (!CFHTTPAuthenticationIsValid(proxyAuthentication, &err)) {
  2304. CFRelease(proxyAuthentication);
  2305. proxyAuthentication = NULL;
  2306. // check for bad credentials, so we can give the delegate a chance to replace them
  2307. if (err.domain == kCFStreamErrorDomainHTTP && (err.error == kCFStreamErrorHTTPAuthenticationBadUserName || err.error == kCFStreamErrorHTTPAuthenticationBadPassword)) {
  2308. // Prevent more than one request from asking for credentials at once
  2309. [delegateAuthenticationLock lock];
  2310. // We know the credentials we just presented are bad, we should remove them from the session store too
  2311. [[self class] removeProxyAuthenticationCredentialsFromSessionStore:proxyCredentials];
  2312. [self setProxyCredentials:nil];
  2313. // If the user cancelled authentication via a dialog presented by another request, our queue may have cancelled us
  2314. if ([self error] || [self isCancelled]) {
  2315. [delegateAuthenticationLock unlock];
  2316. return;
  2317. }
  2318. // Now we've acquired the lock, it may be that the session contains credentials we can re-use for this request
  2319. if ([self useSessionPersistence]) {
  2320. NSDictionary *credentials = [self findSessionProxyAuthenticationCredentials];
  2321. if (credentials && [self applyProxyCredentials:[credentials objectForKey:@"Credentials"]]) {
  2322. [delegateAuthenticationLock unlock];
  2323. [self startRequest];
  2324. return;
  2325. }
  2326. }
  2327. [self setLastActivityTime:nil];
  2328. if ([self willAskDelegateForProxyCredentials]) {
  2329. [self attemptToApplyProxyCredentialsAndResume];
  2330. [delegateAuthenticationLock unlock];
  2331. return;
  2332. }
  2333. if ([self showProxyAuthenticationDialog]) {
  2334. [self attemptToApplyProxyCredentialsAndResume];
  2335. [delegateAuthenticationLock unlock];
  2336. return;
  2337. }
  2338. [delegateAuthenticationLock unlock];
  2339. }
  2340. [self cancelLoad];
  2341. [self failWithError:ASIAuthenticationError];
  2342. return;
  2343. }
  2344. [self cancelLoad];
  2345. if (proxyCredentials) {
  2346. // We use startRequest rather than starting all over again in load request because NTLM requires we reuse the request
  2347. if ((([self proxyAuthenticationScheme] != (NSString *)kCFHTTPAuthenticationSchemeNTLM) || [self proxyAuthenticationRetryCount] < 2) && [self applyProxyCredentials:proxyCredentials]) {
  2348. [self startRequest];
  2349. // We've failed NTLM authentication twice, we should assume our credentials are wrong
  2350. } else if ([self proxyAuthenticationScheme] == (NSString *)kCFHTTPAuthenticationSchemeNTLM && [self proxyAuthenticationRetryCount] == 2) {
  2351. [self failWithError:ASIAuthenticationError];
  2352. // Something went wrong, we'll have to give up
  2353. } else {
  2354. [self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to apply proxy credentials to request",NSLocalizedDescriptionKey,nil]]];
  2355. }
  2356. // Are a user name & password needed?
  2357. } else if (CFHTTPAuthenticationRequiresUserNameAndPassword(proxyAuthentication)) {
  2358. // Prevent more than one request from asking for credentials at once
  2359. [delegateAuthenticationLock lock];
  2360. // If the user cancelled authentication via a dialog presented by another request, our queue may have cancelled us
  2361. if ([self error] || [self isCancelled]) {
  2362. [delegateAuthenticationLock unlock];
  2363. return;
  2364. }
  2365. // Now we've acquired the lock, it may be that the session contains credentials we can re-use for this request
  2366. if ([self useSessionPersistence]) {
  2367. NSDictionary *credentials = [self findSessionProxyAuthenticationCredentials];
  2368. if (credentials && [self applyProxyCredentials:[credentials objectForKey:@"Credentials"]]) {
  2369. [delegateAuthenticationLock unlock];
  2370. [self startRequest];
  2371. return;
  2372. }
  2373. }
  2374. NSMutableDictionary *newCredentials = [self findProxyCredentials];
  2375. //If we have some credentials to use let's apply them to the request and continue
  2376. if (newCredentials) {
  2377. if ([self applyProxyCredentials:newCredentials]) {
  2378. [delegateAuthenticationLock unlock];
  2379. [self startRequest];
  2380. } else {
  2381. [delegateAuthenticationLock unlock];
  2382. [self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to apply proxy credentials to request",NSLocalizedDescriptionKey,nil]]];
  2383. }
  2384. return;
  2385. }
  2386. if ([self willAskDelegateForProxyCredentials]) {
  2387. [delegateAuthenticationLock unlock];
  2388. return;
  2389. }
  2390. if ([self showProxyAuthenticationDialog]) {
  2391. [delegateAuthenticationLock unlock];
  2392. return;
  2393. }
  2394. [delegateAuthenticationLock unlock];
  2395. // The delegate isn't interested and we aren't showing the authentication dialog, we'll have to give up
  2396. [self failWithError:ASIAuthenticationError];
  2397. return;
  2398. }
  2399. }
  2400. - (BOOL)showAuthenticationDialog
  2401. {
  2402. if ([self isSynchronous]) {
  2403. return NO;
  2404. }
  2405. // Mac authentication dialog coming soon!
  2406. #if TARGET_OS_IPHONE
  2407. if ([self shouldPresentAuthenticationDialog]) {
  2408. [ASIAuthenticationDialog performSelectorOnMainThread:@selector(presentAuthenticationDialogForRequest:) withObject:self waitUntilDone:[NSThread isMainThread]];
  2409. return YES;
  2410. }
  2411. return NO;
  2412. #else
  2413. return NO;
  2414. #endif
  2415. }
  2416. - (void)attemptToApplyCredentialsAndResume
  2417. {
  2418. if ([self error] || [self isCancelled]) {
  2419. return;
  2420. }
  2421. // Do we actually need to authenticate with a proxy?
  2422. if ([self authenticationNeeded] == ASIProxyAuthenticationNeeded) {
  2423. [self attemptToApplyProxyCredentialsAndResume];
  2424. return;
  2425. }
  2426. // Read authentication data
  2427. if (!requestAuthentication) {
  2428. CFHTTPMessageRef responseHeader = (CFHTTPMessageRef) CFReadStreamCopyProperty((CFReadStreamRef)[self readStream],kCFStreamPropertyHTTPResponseHeader);
  2429. requestAuthentication = CFHTTPAuthenticationCreateFromResponse(NULL, responseHeader);
  2430. CFRelease(responseHeader);
  2431. [self setAuthenticationScheme:[NSMakeCollectable(CFHTTPAuthenticationCopyMethod(requestAuthentication)) autorelease]];
  2432. }
  2433. if (!requestAuthentication) {
  2434. #if DEBUG_HTTP_AUTHENTICATION
  2435. ASI_DEBUG_LOG(@"[AUTH] Request %@ failed to read authentication information from response headers",self);
  2436. #endif
  2437. [self cancelLoad];
  2438. [self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to get authentication object from response headers",NSLocalizedDescriptionKey,nil]]];
  2439. return;
  2440. }
  2441. // Get the authentication realm
  2442. [self setAuthenticationRealm:nil];
  2443. if (!CFHTTPAuthenticationRequiresAccountDomain(requestAuthentication)) {
  2444. [self setAuthenticationRealm:[NSMakeCollectable(CFHTTPAuthenticationCopyRealm(requestAuthentication)) autorelease]];
  2445. }
  2446. #if DEBUG_HTTP_AUTHENTICATION
  2447. NSString *realm = [self authenticationRealm];
  2448. if (realm) {
  2449. realm = [NSString stringWithFormat:@" (Realm: %@)",realm];
  2450. } else {
  2451. realm = @"";
  2452. }
  2453. if ([self authenticationScheme] != (NSString *)kCFHTTPAuthenticationSchemeNTLM || [self authenticationRetryCount] == 0) {
  2454. ASI_DEBUG_LOG(@"[AUTH] Request %@ received 401 challenge and must authenticate using %@%@",self,[self authenticationScheme],realm);
  2455. } else {
  2456. ASI_DEBUG_LOG(@"[AUTH] Request %@ NTLM handshake step %i",self,[self authenticationRetryCount]+1);
  2457. }
  2458. #endif
  2459. // See if authentication is valid
  2460. CFStreamError err;
  2461. if (!CFHTTPAuthenticationIsValid(requestAuthentication, &err)) {
  2462. CFRelease(requestAuthentication);
  2463. requestAuthentication = NULL;
  2464. // check for bad credentials, so we can give the delegate a chance to replace them
  2465. if (err.domain == kCFStreamErrorDomainHTTP && (err.error == kCFStreamErrorHTTPAuthenticationBadUserName || err.error == kCFStreamErrorHTTPAuthenticationBadPassword)) {
  2466. #if DEBUG_HTTP_AUTHENTICATION
  2467. ASI_DEBUG_LOG(@"[AUTH] Request %@ had bad credentials, will remove them from the session store if they are cached",self);
  2468. #endif
  2469. // Prevent more than one request from asking for credentials at once
  2470. [delegateAuthenticationLock lock];
  2471. // We know the credentials we just presented are bad, we should remove them from the session store too
  2472. [[self class] removeAuthenticationCredentialsFromSessionStore:requestCredentials];
  2473. [self setRequestCredentials:nil];
  2474. // If the user cancelled authentication via a dialog presented by another request, our queue may have cancelled us
  2475. if ([self error] || [self isCancelled]) {
  2476. #if DEBUG_HTTP_AUTHENTICATION
  2477. ASI_DEBUG_LOG(@"[AUTH] Request %@ failed or was cancelled while waiting to access credentials",self);
  2478. #endif
  2479. [delegateAuthenticationLock unlock];
  2480. return;
  2481. }
  2482. // Now we've acquired the lock, it may be that the session contains credentials we can re-use for this request
  2483. if ([self useSessionPersistence]) {
  2484. NSDictionary *credentials = [self findSessionAuthenticationCredentials];
  2485. if (credentials && [self applyCredentials:[credentials objectForKey:@"Credentials"]]) {
  2486. #if DEBUG_HTTP_AUTHENTICATION
  2487. ASI_DEBUG_LOG(@"[AUTH] Request %@ will reuse cached credentials from the session (%@)",self,[credentials objectForKey:@"AuthenticationScheme"]);
  2488. #endif
  2489. [delegateAuthenticationLock unlock];
  2490. [self startRequest];
  2491. return;
  2492. }
  2493. }
  2494. [self setLastActivityTime:nil];
  2495. if ([self willAskDelegateForCredentials]) {
  2496. #if DEBUG_HTTP_AUTHENTICATION
  2497. ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask its delegate for credentials to use",self);
  2498. #endif
  2499. [delegateAuthenticationLock unlock];
  2500. return;
  2501. }
  2502. if ([self showAuthenticationDialog]) {
  2503. #if DEBUG_HTTP_AUTHENTICATION
  2504. ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask ASIAuthenticationDialog for credentials",self);
  2505. #endif
  2506. [delegateAuthenticationLock unlock];
  2507. return;
  2508. }
  2509. [delegateAuthenticationLock unlock];
  2510. }
  2511. #if DEBUG_HTTP_AUTHENTICATION
  2512. ASI_DEBUG_LOG(@"[AUTH] Request %@ has no credentials to present and must give up",self);
  2513. #endif
  2514. [self cancelLoad];
  2515. [self failWithError:ASIAuthenticationError];
  2516. return;
  2517. }
  2518. [self cancelLoad];
  2519. if (requestCredentials) {
  2520. if ((([self authenticationScheme] != (NSString *)kCFHTTPAuthenticationSchemeNTLM) || [self authenticationRetryCount] < 2) && [self applyCredentials:requestCredentials]) {
  2521. [self startRequest];
  2522. // We've failed NTLM authentication twice, we should assume our credentials are wrong
  2523. } else if ([self authenticationScheme] == (NSString *)kCFHTTPAuthenticationSchemeNTLM && [self authenticationRetryCount ] == 2) {
  2524. #if DEBUG_HTTP_AUTHENTICATION
  2525. ASI_DEBUG_LOG(@"[AUTH] Request %@ has failed NTLM authentication",self);
  2526. #endif
  2527. [self failWithError:ASIAuthenticationError];
  2528. } else {
  2529. #if DEBUG_HTTP_AUTHENTICATION
  2530. ASI_DEBUG_LOG(@"[AUTH] Request %@ had credentials and they were not marked as bad, but we got a 401 all the same.",self);
  2531. #endif
  2532. [self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to apply credentials to request",NSLocalizedDescriptionKey,nil]]];
  2533. }
  2534. // Are a user name & password needed?
  2535. } else if (CFHTTPAuthenticationRequiresUserNameAndPassword(requestAuthentication)) {
  2536. // Prevent more than one request from asking for credentials at once
  2537. [delegateAuthenticationLock lock];
  2538. // If the user cancelled authentication via a dialog presented by another request, our queue may have cancelled us
  2539. if ([self error] || [self isCancelled]) {
  2540. #if DEBUG_HTTP_AUTHENTICATION
  2541. ASI_DEBUG_LOG(@"[AUTH] Request %@ failed or was cancelled while waiting to access credentials",self);
  2542. #endif
  2543. [delegateAuthenticationLock unlock];
  2544. return;
  2545. }
  2546. // Now we've acquired the lock, it may be that the session contains credentials we can re-use for this request
  2547. if ([self useSessionPersistence]) {
  2548. NSDictionary *credentials = [self findSessionAuthenticationCredentials];
  2549. if (credentials && [self applyCredentials:[credentials objectForKey:@"Credentials"]]) {
  2550. #if DEBUG_HTTP_AUTHENTICATION
  2551. ASI_DEBUG_LOG(@"[AUTH] Request %@ will reuse cached credentials from the session (%@)",self,[credentials objectForKey:@"AuthenticationScheme"]);
  2552. #endif
  2553. [delegateAuthenticationLock unlock];
  2554. [self startRequest];
  2555. return;
  2556. }
  2557. }
  2558. NSMutableDictionary *newCredentials = [self findCredentials];
  2559. //If we have some credentials to use let's apply them to the request and continue
  2560. if (newCredentials) {
  2561. if ([self applyCredentials:newCredentials]) {
  2562. [delegateAuthenticationLock unlock];
  2563. [self startRequest];
  2564. } else {
  2565. #if DEBUG_HTTP_AUTHENTICATION
  2566. ASI_DEBUG_LOG(@"[AUTH] Request %@ failed to apply credentials",self);
  2567. #endif
  2568. [delegateAuthenticationLock unlock];
  2569. [self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to apply credentials to request",NSLocalizedDescriptionKey,nil]]];
  2570. }
  2571. return;
  2572. }
  2573. if ([self willAskDelegateForCredentials]) {
  2574. #if DEBUG_HTTP_AUTHENTICATION
  2575. ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask its delegate for credentials to use",self);
  2576. #endif
  2577. [delegateAuthenticationLock unlock];
  2578. return;
  2579. }
  2580. if ([self showAuthenticationDialog]) {
  2581. #if DEBUG_HTTP_AUTHENTICATION
  2582. ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask ASIAuthenticationDialog for credentials",self);
  2583. #endif
  2584. [delegateAuthenticationLock unlock];
  2585. return;
  2586. }
  2587. #if DEBUG_HTTP_AUTHENTICATION
  2588. ASI_DEBUG_LOG(@"[AUTH] Request %@ has no credentials to present and must give up",self);
  2589. #endif
  2590. [delegateAuthenticationLock unlock];
  2591. [self failWithError:ASIAuthenticationError];
  2592. return;
  2593. }
  2594. }
  2595. - (void)addBasicAuthenticationHeaderWithUsername:(NSString *)theUsername andPassword:(NSString *)thePassword
  2596. {
  2597. [self addRequestHeader:@"Authorization" value:[NSString stringWithFormat:@"Basic %@",[ASIHTTPRequest base64forData:[[NSString stringWithFormat:@"%@:%@",theUsername,thePassword] dataUsingEncoding:NSUTF8StringEncoding]]]];
  2598. [self setAuthenticationScheme:(NSString *)kCFHTTPAuthenticationSchemeBasic];
  2599. }
  2600. #pragma mark stream status handlers
  2601. - (void)handleNetworkEvent:(CFStreamEventType)type
  2602. {
  2603. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  2604. [[self cancelledLock] lock];
  2605. if ([self complete] || [self isCancelled]) {
  2606. [[self cancelledLock] unlock];
  2607. [pool drain];
  2608. return;
  2609. }
  2610. CFRetain(self);
  2611. // Dispatch the stream events.
  2612. switch (type) {
  2613. case kCFStreamEventHasBytesAvailable:
  2614. [self handleBytesAvailable];
  2615. break;
  2616. case kCFStreamEventEndEncountered:
  2617. [self handleStreamComplete];
  2618. break;
  2619. case kCFStreamEventErrorOccurred:
  2620. [self handleStreamError];
  2621. break;
  2622. default:
  2623. break;
  2624. }
  2625. [self performThrottling];
  2626. [[self cancelledLock] unlock];
  2627. if ([self downloadComplete] && [self needsRedirect]) {
  2628. if (![self willAskDelegateToConfirmRedirect]) {
  2629. [self performRedirect];
  2630. }
  2631. } else if ([self downloadComplete] && [self authenticationNeeded]) {
  2632. [self attemptToApplyCredentialsAndResume];
  2633. }
  2634. CFRelease(self);
  2635. [pool drain];
  2636. }
  2637. - (BOOL)willAskDelegateToConfirmRedirect
  2638. {
  2639. // We must lock to ensure delegate / queue aren't changed while we check them
  2640. [[self cancelledLock] lock];
  2641. // Here we perform an initial check to see if either the delegate or the queue wants to be asked about the redirect, because if not we should redirect straight away
  2642. // We will check again on the main thread later
  2643. BOOL needToAskDelegateAboutRedirect = (([self delegate] && [[self delegate] respondsToSelector:[self willRedirectSelector]]) || ([self queue] && [[self queue] respondsToSelector:@selector(request:willRedirectToURL:)]));
  2644. [[self cancelledLock] unlock];
  2645. // Either the delegate or the queue's delegate is interested in being told when we are about to redirect
  2646. if (needToAskDelegateAboutRedirect) {
  2647. NSURL *newURL = [[[self redirectURL] copy] autorelease];
  2648. [self setRedirectURL:nil];
  2649. [self performSelectorOnMainThread:@selector(requestWillRedirectToURL:) withObject:newURL waitUntilDone:[NSThread isMainThread]];
  2650. return true;
  2651. }
  2652. return false;
  2653. }
  2654. - (void)handleBytesAvailable
  2655. {
  2656. if (![self responseHeaders]) {
  2657. [self readResponseHeaders];
  2658. }
  2659. // If we've cancelled the load part way through (for example, after deciding to use a cached version)
  2660. if ([self complete]) {
  2661. return;
  2662. }
  2663. // In certain (presumably very rare) circumstances, handleBytesAvailable seems to be called when there isn't actually any data available
  2664. // We'll check that there is actually data available to prevent blocking on CFReadStreamRead()
  2665. // So far, I've only seen this in the stress tests, so it might never happen in real-world situations.
  2666. if (!CFReadStreamHasBytesAvailable((CFReadStreamRef)[self readStream])) {
  2667. return;
  2668. }
  2669. long long bufferSize = 16384;
  2670. if (contentLength > 262144) {
  2671. bufferSize = 262144;
  2672. } else if (contentLength > 65536) {
  2673. bufferSize = 65536;
  2674. }
  2675. // Reduce the buffer size if we're receiving data too quickly when bandwidth throttling is active
  2676. // This just augments the throttling done in measureBandwidthUsage to reduce the amount we go over the limit
  2677. if ([[self class] isBandwidthThrottled]) {
  2678. [bandwidthThrottlingLock lock];
  2679. if (maxBandwidthPerSecond > 0) {
  2680. long long maxiumumSize = (long long)maxBandwidthPerSecond- (long long)bandwidthUsedInLastSecond;
  2681. if (maxiumumSize < 0) {
  2682. // We aren't supposed to read any more data right now, but we'll read a single byte anyway so the CFNetwork's buffer isn't full
  2683. bufferSize = 1;
  2684. } else if (maxiumumSize/4 < bufferSize) {
  2685. // We were going to fetch more data that we should be allowed, so we'll reduce the size of our read
  2686. bufferSize = maxiumumSize/4;
  2687. }
  2688. }
  2689. if (bufferSize < 1) {
  2690. bufferSize = 1;
  2691. }
  2692. [bandwidthThrottlingLock unlock];
  2693. }
  2694. UInt8 buffer[bufferSize];
  2695. NSInteger bytesRead = [[self readStream] read:buffer maxLength:sizeof(buffer)];
  2696. // Less than zero is an error
  2697. if (bytesRead < 0) {
  2698. [self handleStreamError];
  2699. // If zero bytes were read, wait for the EOF to come.
  2700. } else if (bytesRead) {
  2701. // If we are inflating the response on the fly
  2702. NSData *inflatedData = nil;
  2703. if ([self isResponseCompressed] && ![self shouldWaitToInflateCompressedResponses]) {
  2704. if (![self dataDecompressor]) {
  2705. [self setDataDecompressor:[ASIDataDecompressor decompressor]];
  2706. }
  2707. NSError *err = nil;
  2708. inflatedData = [[self dataDecompressor] uncompressBytes:buffer length:bytesRead error:&err];
  2709. if (err) {
  2710. [self failWithError:err];
  2711. return;
  2712. }
  2713. }
  2714. [self setTotalBytesRead:[self totalBytesRead]+bytesRead];
  2715. [self setLastActivityTime:[NSDate date]];
  2716. // For bandwidth measurement / throttling
  2717. [ASIHTTPRequest incrementBandwidthUsedInLastSecond:bytesRead];
  2718. // If we need to redirect, and have automatic redirect on, and might be resuming a download, let's do nothing with the content
  2719. if ([self needsRedirect] && [self shouldRedirect] && [self allowResumeForFileDownloads]) {
  2720. return;
  2721. }
  2722. BOOL dataWillBeHandledExternally = NO;
  2723. if ([[self delegate] respondsToSelector:[self didReceiveDataSelector]]) {
  2724. dataWillBeHandledExternally = YES;
  2725. }
  2726. #if NS_BLOCKS_AVAILABLE
  2727. if (dataReceivedBlock) {
  2728. dataWillBeHandledExternally = YES;
  2729. }
  2730. #endif
  2731. // Does the delegate want to handle the data manually?
  2732. if (dataWillBeHandledExternally) {
  2733. NSData *data = nil;
  2734. if ([self isResponseCompressed] && ![self shouldWaitToInflateCompressedResponses]) {
  2735. data = inflatedData;
  2736. } else {
  2737. data = [NSData dataWithBytes:buffer length:bytesRead];
  2738. }
  2739. [self performSelectorOnMainThread:@selector(passOnReceivedData:) withObject:data waitUntilDone:[NSThread isMainThread]];
  2740. // Are we downloading to a file?
  2741. } else if ([self downloadDestinationPath]) {
  2742. BOOL append = NO;
  2743. if (![self fileDownloadOutputStream]) {
  2744. if (![self temporaryFileDownloadPath]) {
  2745. [self setTemporaryFileDownloadPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]];
  2746. } else if ([self allowResumeForFileDownloads] && [[self requestHeaders] objectForKey:@"Range"]) {
  2747. if ([[self responseHeaders] objectForKey:@"Content-Range"]) {
  2748. append = YES;
  2749. } else {
  2750. [self incrementDownloadSizeBy:-[self partialDownloadSize]];
  2751. [self setPartialDownloadSize:0];
  2752. }
  2753. }
  2754. [self setFileDownloadOutputStream:[[[NSOutputStream alloc] initToFileAtPath:[self temporaryFileDownloadPath] append:append] autorelease]];
  2755. [[self fileDownloadOutputStream] open];
  2756. }
  2757. [[self fileDownloadOutputStream] write:buffer maxLength:bytesRead];
  2758. if ([self isResponseCompressed] && ![self shouldWaitToInflateCompressedResponses]) {
  2759. if (![self inflatedFileDownloadOutputStream]) {
  2760. if (![self temporaryUncompressedDataDownloadPath]) {
  2761. [self setTemporaryUncompressedDataDownloadPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]];
  2762. }
  2763. [self setInflatedFileDownloadOutputStream:[[[NSOutputStream alloc] initToFileAtPath:[self temporaryUncompressedDataDownloadPath] append:append] autorelease]];
  2764. [[self inflatedFileDownloadOutputStream] open];
  2765. }
  2766. [[self inflatedFileDownloadOutputStream] write:[inflatedData bytes] maxLength:[inflatedData length]];
  2767. }
  2768. //Otherwise, let's add the data to our in-memory store
  2769. } else {
  2770. if ([self isResponseCompressed] && ![self shouldWaitToInflateCompressedResponses]) {
  2771. [rawResponseData appendData:inflatedData];
  2772. } else {
  2773. [rawResponseData appendBytes:buffer length:bytesRead];
  2774. }
  2775. }
  2776. }
  2777. }
  2778. - (void)handleStreamComplete
  2779. {
  2780. #if DEBUG_REQUEST_STATUS
  2781. ASI_DEBUG_LOG(@"[STATUS] Request %@ finished downloading data (%qu bytes)",self, [self totalBytesRead]);
  2782. #endif
  2783. [self setStatusTimer:nil];
  2784. [self setDownloadComplete:YES];
  2785. if (![self responseHeaders]) {
  2786. [self readResponseHeaders];
  2787. }
  2788. [progressLock lock];
  2789. // Find out how much data we've uploaded so far
  2790. [self setLastBytesSent:totalBytesSent];
  2791. [self setTotalBytesSent:[NSMakeCollectable(CFReadStreamCopyProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPRequestBytesWrittenCount)) unsignedLongLongValue]];
  2792. [self setComplete:YES];
  2793. if (![self contentLength]) {
  2794. [self setContentLength:[self totalBytesRead]];
  2795. }
  2796. [self updateProgressIndicators];
  2797. [[self postBodyReadStream] close];
  2798. [self setPostBodyReadStream:nil];
  2799. [self setDataDecompressor:nil];
  2800. NSError *fileError = nil;
  2801. // Delete up the request body temporary file, if it exists
  2802. if ([self didCreateTemporaryPostDataFile] && ![self authenticationNeeded]) {
  2803. [self removeTemporaryUploadFile];
  2804. [self removeTemporaryCompressedUploadFile];
  2805. }
  2806. // Close the output stream as we're done writing to the file
  2807. if ([self temporaryFileDownloadPath]) {
  2808. [[self fileDownloadOutputStream] close];
  2809. [self setFileDownloadOutputStream:nil];
  2810. [[self inflatedFileDownloadOutputStream] close];
  2811. [self setInflatedFileDownloadOutputStream:nil];
  2812. // If we are going to redirect and we are resuming, let's ignore this download
  2813. if ([self shouldRedirect] && [self needsRedirect] && [self allowResumeForFileDownloads]) {
  2814. } else if ([self isResponseCompressed]) {
  2815. // Decompress the file directly to the destination path
  2816. if ([self shouldWaitToInflateCompressedResponses]) {
  2817. [ASIDataDecompressor uncompressDataFromFile:[self temporaryFileDownloadPath] toFile:[self downloadDestinationPath] error:&fileError];
  2818. // Response should already have been inflated, move the temporary file to the destination path
  2819. } else {
  2820. NSError *moveError = nil;
  2821. [[[[NSFileManager alloc] init] autorelease] moveItemAtPath:[self temporaryUncompressedDataDownloadPath] toPath:[self downloadDestinationPath] error:&moveError];
  2822. if (moveError) {
  2823. fileError = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to move file from '%@' to '%@'",[self temporaryFileDownloadPath],[self downloadDestinationPath]],NSLocalizedDescriptionKey,moveError,NSUnderlyingErrorKey,nil]];
  2824. }
  2825. [self setTemporaryUncompressedDataDownloadPath:nil];
  2826. }
  2827. [self removeTemporaryDownloadFile];
  2828. } else {
  2829. //Remove any file at the destination path
  2830. NSError *moveError = nil;
  2831. if (![[self class] removeFileAtPath:[self downloadDestinationPath] error:&moveError]) {
  2832. fileError = moveError;
  2833. }
  2834. //Move the temporary file to the destination path
  2835. if (!fileError) {
  2836. [[[[NSFileManager alloc] init] autorelease] moveItemAtPath:[self temporaryFileDownloadPath] toPath:[self downloadDestinationPath] error:&moveError];
  2837. if (moveError) {
  2838. fileError = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to move file from '%@' to '%@'",[self temporaryFileDownloadPath],[self downloadDestinationPath]],NSLocalizedDescriptionKey,moveError,NSUnderlyingErrorKey,nil]];
  2839. }
  2840. [self setTemporaryFileDownloadPath:nil];
  2841. }
  2842. }
  2843. }
  2844. // Save to the cache
  2845. if ([self downloadCache] && ![self didUseCachedResponse]) {
  2846. [[self downloadCache] storeResponseForRequest:self maxAge:[self secondsToCache]];
  2847. }
  2848. [progressLock unlock];
  2849. [connectionsLock lock];
  2850. if (![self connectionCanBeReused]) {
  2851. [self unscheduleReadStream];
  2852. }
  2853. #if DEBUG_PERSISTENT_CONNECTIONS
  2854. if ([self requestID]) {
  2855. ASI_DEBUG_LOG(@"[CONNECTION] Request #%@ finished using connection #%@",[self requestID], [[self connectionInfo] objectForKey:@"id"]);
  2856. }
  2857. #endif
  2858. [[self connectionInfo] removeObjectForKey:@"request"];
  2859. [[self connectionInfo] setObject:[NSDate dateWithTimeIntervalSinceNow:[self persistentConnectionTimeoutSeconds]] forKey:@"expires"];
  2860. [connectionsLock unlock];
  2861. if (![self authenticationNeeded]) {
  2862. [self destroyReadStream];
  2863. }
  2864. if (![self needsRedirect] && ![self authenticationNeeded] && ![self didUseCachedResponse]) {
  2865. if (fileError) {
  2866. [self failWithError:fileError];
  2867. } else {
  2868. [self requestFinished];
  2869. }
  2870. [self markAsFinished];
  2871. // If request has asked delegate or ASIAuthenticationDialog for credentials
  2872. } else if ([self authenticationNeeded]) {
  2873. CFRunLoopStop(CFRunLoopGetCurrent());
  2874. }
  2875. }
  2876. - (void)markAsFinished
  2877. {
  2878. // Autoreleased requests may well be dealloced here otherwise
  2879. CFRetain(self);
  2880. // dealloc won't be called when running with GC, so we'll clean these up now
  2881. if (request) {
  2882. CFRelease(request);
  2883. request = nil;
  2884. }
  2885. if (requestAuthentication) {
  2886. CFRelease(requestAuthentication);
  2887. requestAuthentication = nil;
  2888. }
  2889. if (proxyAuthentication) {
  2890. CFRelease(proxyAuthentication);
  2891. proxyAuthentication = nil;
  2892. }
  2893. BOOL wasInProgress = inProgress;
  2894. BOOL wasFinished = finished;
  2895. if (!wasFinished)
  2896. [self willChangeValueForKey:@"isFinished"];
  2897. if (wasInProgress)
  2898. [self willChangeValueForKey:@"isExecuting"];
  2899. [self setInProgress:NO];
  2900. finished = YES;
  2901. if (wasInProgress)
  2902. [self didChangeValueForKey:@"isExecuting"];
  2903. if (!wasFinished)
  2904. [self didChangeValueForKey:@"isFinished"];
  2905. CFRunLoopStop(CFRunLoopGetCurrent());
  2906. #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
  2907. if ([ASIHTTPRequest isMultitaskingSupported] && [self shouldContinueWhenAppEntersBackground]) {
  2908. dispatch_async(dispatch_get_main_queue(), ^{
  2909. if (backgroundTask != UIBackgroundTaskInvalid) {
  2910. [[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
  2911. backgroundTask = UIBackgroundTaskInvalid;
  2912. }
  2913. });
  2914. }
  2915. #endif
  2916. CFRelease(self);
  2917. }
  2918. - (void)useDataFromCache
  2919. {
  2920. NSDictionary *headers = [[self downloadCache] cachedResponseHeadersForURL:[self url]];
  2921. NSString *dataPath = [[self downloadCache] pathToCachedResponseDataForURL:[self url]];
  2922. ASIHTTPRequest *theRequest = self;
  2923. if ([self mainRequest]) {
  2924. theRequest = [self mainRequest];
  2925. }
  2926. if (headers && dataPath) {
  2927. [self setResponseStatusCode:[[headers objectForKey:@"X-ASIHTTPRequest-Response-Status-Code"] intValue]];
  2928. [self setDidUseCachedResponse:YES];
  2929. [theRequest setResponseHeaders:headers];
  2930. if ([theRequest downloadDestinationPath]) {
  2931. [theRequest setDownloadDestinationPath:dataPath];
  2932. } else {
  2933. [theRequest setRawResponseData:[NSMutableData dataWithData:[[self downloadCache] cachedResponseDataForURL:[self url]]]];
  2934. }
  2935. [theRequest setContentLength:[[[self responseHeaders] objectForKey:@"Content-Length"] longLongValue]];
  2936. [theRequest setTotalBytesRead:[self contentLength]];
  2937. [theRequest parseStringEncodingFromHeaders];
  2938. [theRequest setResponseCookies:[NSHTTPCookie cookiesWithResponseHeaderFields:headers forURL:[self url]]];
  2939. // See if we need to redirect
  2940. if ([self willRedirect]) {
  2941. if (![self willAskDelegateToConfirmRedirect]) {
  2942. [self performRedirect];
  2943. }
  2944. return;
  2945. }
  2946. }
  2947. [theRequest setComplete:YES];
  2948. [theRequest setDownloadComplete:YES];
  2949. // If we're pulling data from the cache without contacting the server at all, we won't have set originalURL yet
  2950. if ([self redirectCount] == 0) {
  2951. [theRequest setOriginalURL:[theRequest url]];
  2952. }
  2953. [theRequest updateProgressIndicators];
  2954. [theRequest requestFinished];
  2955. [theRequest markAsFinished];
  2956. if ([self mainRequest]) {
  2957. [self markAsFinished];
  2958. }
  2959. }
  2960. - (BOOL)retryUsingNewConnection
  2961. {
  2962. if ([self retryCount] == 0) {
  2963. [self setWillRetryRequest:YES];
  2964. [self cancelLoad];
  2965. [self setWillRetryRequest:NO];
  2966. #if DEBUG_PERSISTENT_CONNECTIONS
  2967. ASI_DEBUG_LOG(@"[CONNECTION] Request attempted to use connection #%@, but it has been closed - will retry with a new connection", [[self connectionInfo] objectForKey:@"id"]);
  2968. #endif
  2969. [connectionsLock lock];
  2970. [[self connectionInfo] removeObjectForKey:@"request"];
  2971. [persistentConnectionsPool removeObject:[self connectionInfo]];
  2972. [self setConnectionInfo:nil];
  2973. [connectionsLock unlock];
  2974. [self setRetryCount:[self retryCount]+1];
  2975. [self startRequest];
  2976. return YES;
  2977. }
  2978. #if DEBUG_PERSISTENT_CONNECTIONS
  2979. ASI_DEBUG_LOG(@"[CONNECTION] Request attempted to use connection #%@, but it has been closed - we have already retried with a new connection, so we must give up", [[self connectionInfo] objectForKey:@"id"]);
  2980. #endif
  2981. return NO;
  2982. }
  2983. - (void)handleStreamError
  2984. {
  2985. NSError *underlyingError = [NSMakeCollectable(CFReadStreamCopyError((CFReadStreamRef)[self readStream])) autorelease];
  2986. if (![self error]) { // We may already have handled this error
  2987. // First, check for a 'socket not connected', 'broken pipe' or 'connection lost' error
  2988. // This may occur when we've attempted to reuse a connection that should have been closed
  2989. // If we get this, we need to retry the request
  2990. // We'll only do this once - if it happens again on retry, we'll give up
  2991. // -1005 = kCFURLErrorNetworkConnectionLost - this doesn't seem to be declared on Mac OS 10.5
  2992. if (([[underlyingError domain] isEqualToString:NSPOSIXErrorDomain] && ([underlyingError code] == ENOTCONN || [underlyingError code] == EPIPE))
  2993. || ([[underlyingError domain] isEqualToString:(NSString *)kCFErrorDomainCFNetwork] && [underlyingError code] == -1005)) {
  2994. if ([self retryUsingNewConnection]) {
  2995. return;
  2996. }
  2997. }
  2998. NSString *reason = @"A connection failure occurred";
  2999. // We'll use a custom error message for SSL errors, but you should always check underlying error if you want more details
  3000. // For some reason SecureTransport.h doesn't seem to be available on iphone, so error codes hard-coded
  3001. // Also, iPhone seems to handle errors differently from Mac OS X - a self-signed certificate returns a different error code on each platform, so we'll just provide a general error
  3002. if ([[underlyingError domain] isEqualToString:NSOSStatusErrorDomain]) {
  3003. if ([underlyingError code] <= -9800 && [underlyingError code] >= -9818) {
  3004. reason = [NSString stringWithFormat:@"%@: SSL problem (Possible causes may include a bad/expired/self-signed certificate, clock set to wrong date)",reason];
  3005. }
  3006. }
  3007. [self cancelLoad];
  3008. [self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIConnectionFailureErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:reason,NSLocalizedDescriptionKey,underlyingError,NSUnderlyingErrorKey,nil]]];
  3009. } else {
  3010. [self cancelLoad];
  3011. }
  3012. [self checkRequestStatus];
  3013. }
  3014. #pragma mark managing the read stream
  3015. - (void)destroyReadStream
  3016. {
  3017. if ([self readStream]) {
  3018. [self unscheduleReadStream];
  3019. if (![self connectionCanBeReused]) {
  3020. [[self readStream] removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:[self runLoopMode]];
  3021. [[self readStream] close];
  3022. }
  3023. [self setReadStream:nil];
  3024. }
  3025. }
  3026. - (void)scheduleReadStream
  3027. {
  3028. if ([self readStream] && ![self readStreamIsScheduled]) {
  3029. [connectionsLock lock];
  3030. runningRequestCount++;
  3031. if (shouldUpdateNetworkActivityIndicator) {
  3032. [[self class] showNetworkActivityIndicator];
  3033. }
  3034. [connectionsLock unlock];
  3035. // Reset the timeout
  3036. [self setLastActivityTime:[NSDate date]];
  3037. CFStreamClientContext ctxt = {0, self, NULL, NULL, NULL};
  3038. CFReadStreamSetClient((CFReadStreamRef)[self readStream], kNetworkEvents, ReadStreamClientCallBack, &ctxt);
  3039. [[self readStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:[self runLoopMode]];
  3040. [self setReadStreamIsScheduled:YES];
  3041. }
  3042. }
  3043. - (void)unscheduleReadStream
  3044. {
  3045. if ([self readStream] && [self readStreamIsScheduled]) {
  3046. [connectionsLock lock];
  3047. runningRequestCount--;
  3048. if (shouldUpdateNetworkActivityIndicator && runningRequestCount == 0) {
  3049. // This call will wait half a second before turning off the indicator
  3050. // This can prevent flicker when you have a single request finish and then immediately start another request
  3051. // We run this on the main thread because we have no guarantee this thread will have a runloop in 0.5 seconds time
  3052. // We don't bother the cancel this call if we start a new request, because we'll check if requests are running before we hide it
  3053. [[self class] performSelectorOnMainThread:@selector(hideNetworkActivityIndicatorAfterDelay) withObject:nil waitUntilDone:[NSThread isMainThread]];
  3054. }
  3055. [connectionsLock unlock];
  3056. CFReadStreamSetClient((CFReadStreamRef)[self readStream], kCFStreamEventNone, NULL, NULL);
  3057. [[self readStream] removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:[self runLoopMode]];
  3058. [self setReadStreamIsScheduled:NO];
  3059. }
  3060. }
  3061. #pragma mark cleanup
  3062. - (BOOL)removeTemporaryDownloadFile
  3063. {
  3064. NSError *err = nil;
  3065. if ([self temporaryFileDownloadPath]) {
  3066. if (![[self class] removeFileAtPath:[self temporaryFileDownloadPath] error:&err]) {
  3067. [self failWithError:err];
  3068. }
  3069. [self setTemporaryFileDownloadPath:nil];
  3070. }
  3071. return (!err);
  3072. }
  3073. - (BOOL)removeTemporaryUncompressedDownloadFile
  3074. {
  3075. NSError *err = nil;
  3076. if ([self temporaryUncompressedDataDownloadPath]) {
  3077. if (![[self class] removeFileAtPath:[self temporaryUncompressedDataDownloadPath] error:&err]) {
  3078. [self failWithError:err];
  3079. }
  3080. [self setTemporaryUncompressedDataDownloadPath:nil];
  3081. }
  3082. return (!err);
  3083. }
  3084. - (BOOL)removeTemporaryUploadFile
  3085. {
  3086. NSError *err = nil;
  3087. if ([self postBodyFilePath]) {
  3088. if (![[self class] removeFileAtPath:[self postBodyFilePath] error:&err]) {
  3089. [self failWithError:err];
  3090. }
  3091. [self setPostBodyFilePath:nil];
  3092. }
  3093. return (!err);
  3094. }
  3095. - (BOOL)removeTemporaryCompressedUploadFile
  3096. {
  3097. NSError *err = nil;
  3098. if ([self compressedPostBodyFilePath]) {
  3099. if (![[self class] removeFileAtPath:[self compressedPostBodyFilePath] error:&err]) {
  3100. [self failWithError:err];
  3101. }
  3102. [self setCompressedPostBodyFilePath:nil];
  3103. }
  3104. return (!err);
  3105. }
  3106. + (BOOL)removeFileAtPath:(NSString *)path error:(NSError **)err
  3107. {
  3108. NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
  3109. if ([fileManager fileExistsAtPath:path]) {
  3110. NSError *removeError = nil;
  3111. [fileManager removeItemAtPath:path error:&removeError];
  3112. if (removeError) {
  3113. if (err) {
  3114. *err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to delete file at path '%@'",path],NSLocalizedDescriptionKey,removeError,NSUnderlyingErrorKey,nil]];
  3115. }
  3116. return NO;
  3117. }
  3118. }
  3119. return YES;
  3120. }
  3121. #pragma mark Proxies
  3122. - (BOOL)configureProxies
  3123. {
  3124. // Have details of the proxy been set on this request
  3125. if (![self isPACFileRequest] && (![self proxyHost] && ![self proxyPort])) {
  3126. // If not, we need to figure out what they'll be
  3127. NSArray *proxies = nil;
  3128. // Have we been given a proxy auto config file?
  3129. if ([self PACurl]) {
  3130. // If yes, we'll need to fetch the PAC file asynchronously, so we stop this request to wait until we have the proxy details.
  3131. [self fetchPACFile];
  3132. return NO;
  3133. // Detect proxy settings and apply them
  3134. } else {
  3135. #if TARGET_OS_IPHONE
  3136. NSDictionary *proxySettings = [NSMakeCollectable(CFNetworkCopySystemProxySettings()) autorelease];
  3137. #else
  3138. NSDictionary *proxySettings = [NSMakeCollectable(SCDynamicStoreCopyProxies(NULL)) autorelease];
  3139. #endif
  3140. proxies = [NSMakeCollectable(CFNetworkCopyProxiesForURL((CFURLRef)[self url], (CFDictionaryRef)proxySettings)) autorelease];
  3141. // Now check to see if the proxy settings contained a PAC url, we need to run the script to get the real list of proxies if so
  3142. NSDictionary *settings = [proxies objectAtIndex:0];
  3143. if ([settings objectForKey:(NSString *)kCFProxyAutoConfigurationURLKey]) {
  3144. [self setPACurl:[settings objectForKey:(NSString *)kCFProxyAutoConfigurationURLKey]];
  3145. [self fetchPACFile];
  3146. return NO;
  3147. }
  3148. }
  3149. if (!proxies) {
  3150. [self setReadStream:nil];
  3151. [self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileBuildingRequestType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to obtain information on proxy servers needed for request",NSLocalizedDescriptionKey,nil]]];
  3152. return NO;
  3153. }
  3154. // I don't really understand why the dictionary returned by CFNetworkCopyProxiesForURL uses different key names from CFNetworkCopySystemProxySettings/SCDynamicStoreCopyProxies
  3155. // and why its key names are documented while those we actually need to use don't seem to be (passing the kCF* keys doesn't seem to work)
  3156. if ([proxies count] > 0) {
  3157. NSDictionary *settings = [proxies objectAtIndex:0];
  3158. [self setProxyHost:[settings objectForKey:(NSString *)kCFProxyHostNameKey]];
  3159. [self setProxyPort:[[settings objectForKey:(NSString *)kCFProxyPortNumberKey] intValue]];
  3160. [self setProxyType:[settings objectForKey:(NSString *)kCFProxyTypeKey]];
  3161. }
  3162. }
  3163. return YES;
  3164. }
  3165. // Attempts to download a PAC (Proxy Auto-Configuration) file
  3166. // PAC files at file://, http:// and https:// addresses are supported
  3167. - (void)fetchPACFile
  3168. {
  3169. // For file:// urls, we'll use an async NSInputStream (ASIHTTPRequest does not support file:// urls)
  3170. if ([[self PACurl] isFileURL]) {
  3171. NSInputStream *stream = [[[NSInputStream alloc] initWithFileAtPath:[[self PACurl] path]] autorelease];
  3172. [self setPACFileReadStream:stream];
  3173. [stream setDelegate:(id)self];
  3174. [stream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:[self runLoopMode]];
  3175. [stream open];
  3176. // If it takes more than timeOutSeconds to read the PAC, we'll just give up and assume no proxies
  3177. // We won't bother to handle cases where the first part of the PAC is read within timeOutSeconds, but the whole thing takes longer
  3178. // Either our PAC file is in easy reach, or it's going to slow things down to the point that it's probably better requests fail
  3179. [self performSelector:@selector(timeOutPACRead) withObject:nil afterDelay:[self timeOutSeconds]];
  3180. return;
  3181. }
  3182. NSString *scheme = [[[self PACurl] scheme] lowercaseString];
  3183. if (![scheme isEqualToString:@"http"] && ![scheme isEqualToString:@"https"]) {
  3184. // Don't know how to read data from this URL, we'll have to give up
  3185. // We'll simply assume no proxies, and start the request as normal
  3186. [self startRequest];
  3187. return;
  3188. }
  3189. // Create an ASIHTTPRequest to fetch the PAC file
  3190. ASIHTTPRequest *PACRequest = [ASIHTTPRequest requestWithURL:[self PACurl]];
  3191. // Will prevent this request attempting to configure proxy settings for itself
  3192. [PACRequest setIsPACFileRequest:YES];
  3193. [PACRequest setTimeOutSeconds:[self timeOutSeconds]];
  3194. // If we're a synchronous request, we'll download the PAC file synchronously
  3195. if ([self isSynchronous]) {
  3196. [PACRequest startSynchronous];
  3197. if (![PACRequest error] && [PACRequest responseString]) {
  3198. [self runPACScript:[PACRequest responseString]];
  3199. }
  3200. [self startRequest];
  3201. return;
  3202. }
  3203. [self setPACFileRequest:PACRequest];
  3204. // Force this request to run before others in the shared queue
  3205. [PACRequest setQueuePriority:NSOperationQueuePriorityHigh];
  3206. // We'll treat failure to download the PAC file the same as success - if we were unable to fetch a PAC file, we proceed as if we have no proxy server and let this request fail itself if necessary
  3207. [PACRequest setDelegate:self];
  3208. [PACRequest setDidFinishSelector:@selector(finishedDownloadingPACFile:)];
  3209. [PACRequest setDidFailSelector:@selector(finishedDownloadingPACFile:)];
  3210. [PACRequest startAsynchronous];
  3211. // Temporarily increase the number of operations in the shared queue to give our request a chance to run
  3212. [connectionsLock lock];
  3213. [sharedQueue setMaxConcurrentOperationCount:[sharedQueue maxConcurrentOperationCount]+1];
  3214. [connectionsLock unlock];
  3215. }
  3216. // Called as we read the PAC file from a file:// url
  3217. - (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
  3218. {
  3219. if (![self PACFileReadStream]) {
  3220. return;
  3221. }
  3222. if (eventCode == NSStreamEventHasBytesAvailable) {
  3223. if (![self PACFileData]) {
  3224. [self setPACFileData:[NSMutableData data]];
  3225. }
  3226. // If your PAC file is larger than 16KB, you're just being cruel.
  3227. uint8_t buf[16384];
  3228. NSInteger len = [(NSInputStream *)stream read:buf maxLength:16384];
  3229. if (len) {
  3230. [[self PACFileData] appendBytes:(const void *)buf length:len];
  3231. }
  3232. } else if (eventCode == NSStreamEventErrorOccurred || eventCode == NSStreamEventEndEncountered) {
  3233. [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeOutPACRead) object:nil];
  3234. [stream close];
  3235. [stream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:[self runLoopMode]];
  3236. [self setPACFileReadStream:nil];
  3237. if (eventCode == NSStreamEventEndEncountered) {
  3238. // It sounds as though we have no idea what encoding a PAC file will use
  3239. static NSStringEncoding encodingsToTry[2] = {NSUTF8StringEncoding,NSISOLatin1StringEncoding};
  3240. NSUInteger i;
  3241. for (i=0; i<2; i++) {
  3242. NSString *pacScript = [[[NSString alloc] initWithBytes:[[self PACFileData] bytes] length:[[self PACFileData] length] encoding:encodingsToTry[i]] autorelease];
  3243. if (pacScript) {
  3244. [self runPACScript:pacScript];
  3245. break;
  3246. }
  3247. }
  3248. }
  3249. [self setPACFileData:nil];
  3250. [self startRequest];
  3251. }
  3252. }
  3253. // Called if it takes longer than timeOutSeconds to read the whole PAC file (when reading from a file:// url)
  3254. - (void)timeOutPACRead
  3255. {
  3256. [self stream:[self PACFileReadStream] handleEvent:NSStreamEventErrorOccurred];
  3257. }
  3258. // Runs the downloaded PAC script
  3259. - (void)runPACScript:(NSString *)script
  3260. {
  3261. if (script) {
  3262. // From: http://developer.apple.com/samplecode/CFProxySupportTool/listing1.html
  3263. // Work around <rdar://problem/5530166>. This dummy call to
  3264. // CFNetworkCopyProxiesForURL initialise some state within CFNetwork
  3265. // that is required by CFNetworkCopyProxiesForAutoConfigurationScript.
  3266. NSDictionary *proxySettings = NSMakeCollectable([(NSDictionary *)CFNetworkCopySystemProxySettings() autorelease]);
  3267. CFRelease(CFNetworkCopyProxiesForURL((CFURLRef)[self url], (CFDictionaryRef)proxySettings));
  3268. // Obtain the list of proxies by running the autoconfiguration script
  3269. CFErrorRef err = NULL;
  3270. NSArray *proxies = [NSMakeCollectable(CFNetworkCopyProxiesForAutoConfigurationScript((CFStringRef)script,(CFURLRef)[self url], &err)) autorelease];
  3271. if (!err && [proxies count] > 0) {
  3272. NSDictionary *settings = [proxies objectAtIndex:0];
  3273. [self setProxyHost:[settings objectForKey:(NSString *)kCFProxyHostNameKey]];
  3274. [self setProxyPort:[[settings objectForKey:(NSString *)kCFProxyPortNumberKey] intValue]];
  3275. [self setProxyType:[settings objectForKey:(NSString *)kCFProxyTypeKey]];
  3276. }
  3277. }
  3278. }
  3279. // Called if we successfully downloaded a PAC file from a webserver
  3280. - (void)finishedDownloadingPACFile:(ASIHTTPRequest *)theRequest
  3281. {
  3282. if (![theRequest error] && [theRequest responseString]) {
  3283. [self runPACScript:[theRequest responseString]];
  3284. }
  3285. // Set the shared queue's maxConcurrentOperationCount back to normal
  3286. [connectionsLock lock];
  3287. [sharedQueue setMaxConcurrentOperationCount:[sharedQueue maxConcurrentOperationCount]-1];
  3288. [connectionsLock unlock];
  3289. // We no longer need our PAC file request
  3290. [self setPACFileRequest:nil];
  3291. // Start the request
  3292. [self startRequest];
  3293. }
  3294. #pragma mark persistent connections
  3295. - (NSNumber *)connectionID
  3296. {
  3297. return [[self connectionInfo] objectForKey:@"id"];
  3298. }
  3299. + (void)expirePersistentConnections
  3300. {
  3301. [connectionsLock lock];
  3302. NSUInteger i;
  3303. for (i=0; i<[persistentConnectionsPool count]; i++) {
  3304. NSDictionary *existingConnection = [persistentConnectionsPool objectAtIndex:i];
  3305. if (![existingConnection objectForKey:@"request"] && [[existingConnection objectForKey:@"expires"] timeIntervalSinceNow] <= 0) {
  3306. #if DEBUG_PERSISTENT_CONNECTIONS
  3307. ASI_DEBUG_LOG(@"[CONNECTION] Closing connection #%i because it has expired",[[existingConnection objectForKey:@"id"] intValue]);
  3308. #endif
  3309. NSInputStream *stream = [existingConnection objectForKey:@"stream"];
  3310. if (stream) {
  3311. [stream close];
  3312. }
  3313. [persistentConnectionsPool removeObject:existingConnection];
  3314. i--;
  3315. }
  3316. }
  3317. [connectionsLock unlock];
  3318. }
  3319. #pragma mark NSCopying
  3320. - (id)copyWithZone:(NSZone *)zone
  3321. {
  3322. // Don't forget - this will return a retained copy!
  3323. ASIHTTPRequest *newRequest = [[[self class] alloc] initWithURL:[self url]];
  3324. [newRequest setDelegate:[self delegate]];
  3325. [newRequest setRequestMethod:[self requestMethod]];
  3326. [newRequest setPostBody:[self postBody]];
  3327. [newRequest setShouldStreamPostDataFromDisk:[self shouldStreamPostDataFromDisk]];
  3328. [newRequest setPostBodyFilePath:[self postBodyFilePath]];
  3329. [newRequest setRequestHeaders:[[[self requestHeaders] mutableCopyWithZone:zone] autorelease]];
  3330. [newRequest setRequestCookies:[[[self requestCookies] mutableCopyWithZone:zone] autorelease]];
  3331. [newRequest setUseCookiePersistence:[self useCookiePersistence]];
  3332. [newRequest setUseKeychainPersistence:[self useKeychainPersistence]];
  3333. [newRequest setUseSessionPersistence:[self useSessionPersistence]];
  3334. [newRequest setAllowCompressedResponse:[self allowCompressedResponse]];
  3335. [newRequest setDownloadDestinationPath:[self downloadDestinationPath]];
  3336. [newRequest setTemporaryFileDownloadPath:[self temporaryFileDownloadPath]];
  3337. [newRequest setUsername:[self username]];
  3338. [newRequest setPassword:[self password]];
  3339. [newRequest setDomain:[self domain]];
  3340. [newRequest setProxyUsername:[self proxyUsername]];
  3341. [newRequest setProxyPassword:[self proxyPassword]];
  3342. [newRequest setProxyDomain:[self proxyDomain]];
  3343. [newRequest setProxyHost:[self proxyHost]];
  3344. [newRequest setProxyPort:[self proxyPort]];
  3345. [newRequest setProxyType:[self proxyType]];
  3346. [newRequest setUploadProgressDelegate:[self uploadProgressDelegate]];
  3347. [newRequest setDownloadProgressDelegate:[self downloadProgressDelegate]];
  3348. [newRequest setShouldPresentAuthenticationDialog:[self shouldPresentAuthenticationDialog]];
  3349. [newRequest setShouldPresentProxyAuthenticationDialog:[self shouldPresentProxyAuthenticationDialog]];
  3350. [newRequest setPostLength:[self postLength]];
  3351. [newRequest setHaveBuiltPostBody:[self haveBuiltPostBody]];
  3352. [newRequest setDidStartSelector:[self didStartSelector]];
  3353. [newRequest setDidFinishSelector:[self didFinishSelector]];
  3354. [newRequest setDidFailSelector:[self didFailSelector]];
  3355. [newRequest setTimeOutSeconds:[self timeOutSeconds]];
  3356. [newRequest setShouldResetDownloadProgress:[self shouldResetDownloadProgress]];
  3357. [newRequest setShouldResetUploadProgress:[self shouldResetUploadProgress]];
  3358. [newRequest setShowAccurateProgress:[self showAccurateProgress]];
  3359. [newRequest setDefaultResponseEncoding:[self defaultResponseEncoding]];
  3360. [newRequest setAllowResumeForFileDownloads:[self allowResumeForFileDownloads]];
  3361. [newRequest setUserInfo:[[[self userInfo] copyWithZone:zone] autorelease]];
  3362. [newRequest setTag:[self tag]];
  3363. [newRequest setUseHTTPVersionOne:[self useHTTPVersionOne]];
  3364. [newRequest setShouldRedirect:[self shouldRedirect]];
  3365. [newRequest setValidatesSecureCertificate:[self validatesSecureCertificate]];
  3366. [newRequest setClientCertificateIdentity:clientCertificateIdentity];
  3367. [newRequest setClientCertificates:[[clientCertificates copy] autorelease]];
  3368. [newRequest setPACurl:[self PACurl]];
  3369. [newRequest setShouldPresentCredentialsBeforeChallenge:[self shouldPresentCredentialsBeforeChallenge]];
  3370. [newRequest setNumberOfTimesToRetryOnTimeout:[self numberOfTimesToRetryOnTimeout]];
  3371. [newRequest setShouldUseRFC2616RedirectBehaviour:[self shouldUseRFC2616RedirectBehaviour]];
  3372. [newRequest setShouldAttemptPersistentConnection:[self shouldAttemptPersistentConnection]];
  3373. [newRequest setPersistentConnectionTimeoutSeconds:[self persistentConnectionTimeoutSeconds]];
  3374. [newRequest setAuthenticationScheme:[self authenticationScheme]];
  3375. return newRequest;
  3376. }
  3377. #pragma mark default time out
  3378. + (NSTimeInterval)defaultTimeOutSeconds
  3379. {
  3380. return defaultTimeOutSeconds;
  3381. }
  3382. + (void)setDefaultTimeOutSeconds:(NSTimeInterval)newTimeOutSeconds
  3383. {
  3384. defaultTimeOutSeconds = newTimeOutSeconds;
  3385. }
  3386. #pragma mark client certificate
  3387. - (void)setClientCertificateIdentity:(SecIdentityRef)anIdentity {
  3388. if(clientCertificateIdentity) {
  3389. CFRelease(clientCertificateIdentity);
  3390. }
  3391. clientCertificateIdentity = anIdentity;
  3392. if (clientCertificateIdentity) {
  3393. CFRetain(clientCertificateIdentity);
  3394. }
  3395. }
  3396. #pragma mark session credentials
  3397. + (NSMutableArray *)sessionProxyCredentialsStore
  3398. {
  3399. [sessionCredentialsLock lock];
  3400. if (!sessionProxyCredentialsStore) {
  3401. sessionProxyCredentialsStore = [[NSMutableArray alloc] init];
  3402. }
  3403. [sessionCredentialsLock unlock];
  3404. return sessionProxyCredentialsStore;
  3405. }
  3406. + (NSMutableArray *)sessionCredentialsStore
  3407. {
  3408. [sessionCredentialsLock lock];
  3409. if (!sessionCredentialsStore) {
  3410. sessionCredentialsStore = [[NSMutableArray alloc] init];
  3411. }
  3412. [sessionCredentialsLock unlock];
  3413. return sessionCredentialsStore;
  3414. }
  3415. + (void)storeProxyAuthenticationCredentialsInSessionStore:(NSDictionary *)credentials
  3416. {
  3417. [sessionCredentialsLock lock];
  3418. [self removeProxyAuthenticationCredentialsFromSessionStore:[credentials objectForKey:@"Credentials"]];
  3419. [[[self class] sessionProxyCredentialsStore] addObject:credentials];
  3420. [sessionCredentialsLock unlock];
  3421. }
  3422. + (void)storeAuthenticationCredentialsInSessionStore:(NSDictionary *)credentials
  3423. {
  3424. [sessionCredentialsLock lock];
  3425. [self removeAuthenticationCredentialsFromSessionStore:[credentials objectForKey:@"Credentials"]];
  3426. [[[self class] sessionCredentialsStore] addObject:credentials];
  3427. [sessionCredentialsLock unlock];
  3428. }
  3429. + (void)removeProxyAuthenticationCredentialsFromSessionStore:(NSDictionary *)credentials
  3430. {
  3431. [sessionCredentialsLock lock];
  3432. NSMutableArray *sessionCredentialsList = [[self class] sessionProxyCredentialsStore];
  3433. NSUInteger i;
  3434. for (i=0; i<[sessionCredentialsList count]; i++) {
  3435. NSDictionary *theCredentials = [sessionCredentialsList objectAtIndex:i];
  3436. if ([theCredentials objectForKey:@"Credentials"] == credentials) {
  3437. [sessionCredentialsList removeObjectAtIndex:i];
  3438. [sessionCredentialsLock unlock];
  3439. return;
  3440. }
  3441. }
  3442. [sessionCredentialsLock unlock];
  3443. }
  3444. + (void)removeAuthenticationCredentialsFromSessionStore:(NSDictionary *)credentials
  3445. {
  3446. [sessionCredentialsLock lock];
  3447. NSMutableArray *sessionCredentialsList = [[self class] sessionCredentialsStore];
  3448. NSUInteger i;
  3449. for (i=0; i<[sessionCredentialsList count]; i++) {
  3450. NSDictionary *theCredentials = [sessionCredentialsList objectAtIndex:i];
  3451. if ([theCredentials objectForKey:@"Credentials"] == credentials) {
  3452. [sessionCredentialsList removeObjectAtIndex:i];
  3453. [sessionCredentialsLock unlock];
  3454. return;
  3455. }
  3456. }
  3457. [sessionCredentialsLock unlock];
  3458. }
  3459. - (NSDictionary *)findSessionProxyAuthenticationCredentials
  3460. {
  3461. [sessionCredentialsLock lock];
  3462. NSMutableArray *sessionCredentialsList = [[self class] sessionProxyCredentialsStore];
  3463. for (NSDictionary *theCredentials in sessionCredentialsList) {
  3464. if ([[theCredentials objectForKey:@"Host"] isEqualToString:[self proxyHost]] && [[theCredentials objectForKey:@"Port"] intValue] == [self proxyPort]) {
  3465. [sessionCredentialsLock unlock];
  3466. return theCredentials;
  3467. }
  3468. }
  3469. [sessionCredentialsLock unlock];
  3470. return nil;
  3471. }
  3472. - (NSDictionary *)findSessionAuthenticationCredentials
  3473. {
  3474. [sessionCredentialsLock lock];
  3475. NSMutableArray *sessionCredentialsList = [[self class] sessionCredentialsStore];
  3476. NSURL *requestURL = [self url];
  3477. BOOL haveFoundExactMatch;
  3478. NSDictionary *closeMatch = nil;
  3479. // Loop through all the cached credentials we have, looking for the best match for this request
  3480. for (NSDictionary *theCredentials in sessionCredentialsList) {
  3481. haveFoundExactMatch = NO;
  3482. NSURL *cachedCredentialsURL = [theCredentials objectForKey:@"URL"];
  3483. // Find an exact match (same url)
  3484. if ([cachedCredentialsURL isEqual:[self url]]) {
  3485. haveFoundExactMatch = YES;
  3486. // This is not an exact match for the url, and we already have a close match we can use
  3487. } else if (closeMatch) {
  3488. continue;
  3489. // Find a close match (same host, scheme and port)
  3490. } else if ([[cachedCredentialsURL host] isEqualToString:[requestURL host]] && ([cachedCredentialsURL port] == [requestURL port] || ([requestURL port] && [[cachedCredentialsURL port] isEqualToNumber:[requestURL port]])) && [[cachedCredentialsURL scheme] isEqualToString:[requestURL scheme]]) {
  3491. } else {
  3492. continue;
  3493. }
  3494. // Just a sanity check to ensure we never choose credentials from a different realm. Can't really do more than that, as either this request or the stored credentials may not have a realm when the other does
  3495. if ([self authenticationRealm] && ([theCredentials objectForKey:@"AuthenticationRealm"] && ![[theCredentials objectForKey:@"AuthenticationRealm"] isEqualToString:[self authenticationRealm]])) {
  3496. continue;
  3497. }
  3498. // If we have a username and password set on the request, check that they are the same as the cached ones
  3499. if ([self username] && [self password]) {
  3500. NSDictionary *usernameAndPassword = [theCredentials objectForKey:@"Credentials"];
  3501. NSString *storedUsername = [usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationUsername];
  3502. NSString *storedPassword = [usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationPassword];
  3503. if (![storedUsername isEqualToString:[self username]] || ![storedPassword isEqualToString:[self password]]) {
  3504. continue;
  3505. }
  3506. }
  3507. // If we have an exact match for the url, use those credentials
  3508. if (haveFoundExactMatch) {
  3509. [sessionCredentialsLock unlock];
  3510. return theCredentials;
  3511. }
  3512. // We have no exact match, let's remember that we have a good match for this server, and we'll use it at the end if we don't find an exact match
  3513. closeMatch = theCredentials;
  3514. }
  3515. [sessionCredentialsLock unlock];
  3516. // Return credentials that matched on host, port and scheme, or nil if we didn't find any
  3517. return closeMatch;
  3518. }
  3519. #pragma mark keychain storage
  3520. + (void)saveCredentials:(NSURLCredential *)credentials forHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm
  3521. {
  3522. NSURLProtectionSpace *protectionSpace = [[[NSURLProtectionSpace alloc] initWithHost:host port:port protocol:protocol realm:realm authenticationMethod:NSURLAuthenticationMethodDefault] autorelease];
  3523. [[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credentials forProtectionSpace:protectionSpace];
  3524. }
  3525. + (void)saveCredentials:(NSURLCredential *)credentials forProxy:(NSString *)host port:(int)port realm:(NSString *)realm
  3526. {
  3527. NSURLProtectionSpace *protectionSpace = [[[NSURLProtectionSpace alloc] initWithProxyHost:host port:port type:NSURLProtectionSpaceHTTPProxy realm:realm authenticationMethod:NSURLAuthenticationMethodDefault] autorelease];
  3528. [[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credentials forProtectionSpace:protectionSpace];
  3529. }
  3530. + (NSURLCredential *)savedCredentialsForHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm
  3531. {
  3532. NSURLProtectionSpace *protectionSpace = [[[NSURLProtectionSpace alloc] initWithHost:host port:port protocol:protocol realm:realm authenticationMethod:NSURLAuthenticationMethodDefault] autorelease];
  3533. return [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:protectionSpace];
  3534. }
  3535. + (NSURLCredential *)savedCredentialsForProxy:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm
  3536. {
  3537. NSURLProtectionSpace *protectionSpace = [[[NSURLProtectionSpace alloc] initWithProxyHost:host port:port type:NSURLProtectionSpaceHTTPProxy realm:realm authenticationMethod:NSURLAuthenticationMethodDefault] autorelease];
  3538. return [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:protectionSpace];
  3539. }
  3540. + (void)removeCredentialsForHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm
  3541. {
  3542. NSURLProtectionSpace *protectionSpace = [[[NSURLProtectionSpace alloc] initWithHost:host port:port protocol:protocol realm:realm authenticationMethod:NSURLAuthenticationMethodDefault] autorelease];
  3543. NSURLCredential *credential = [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:protectionSpace];
  3544. if (credential) {
  3545. [[NSURLCredentialStorage sharedCredentialStorage] removeCredential:credential forProtectionSpace:protectionSpace];
  3546. }
  3547. }
  3548. + (void)removeCredentialsForProxy:(NSString *)host port:(int)port realm:(NSString *)realm
  3549. {
  3550. NSURLProtectionSpace *protectionSpace = [[[NSURLProtectionSpace alloc] initWithProxyHost:host port:port type:NSURLProtectionSpaceHTTPProxy realm:realm authenticationMethod:NSURLAuthenticationMethodDefault] autorelease];
  3551. NSURLCredential *credential = [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:protectionSpace];
  3552. if (credential) {
  3553. [[NSURLCredentialStorage sharedCredentialStorage] removeCredential:credential forProtectionSpace:protectionSpace];
  3554. }
  3555. }
  3556. + (NSMutableArray *)sessionCookies
  3557. {
  3558. [sessionCookiesLock lock];
  3559. if (!sessionCookies) {
  3560. [ASIHTTPRequest setSessionCookies:[NSMutableArray array]];
  3561. }
  3562. NSMutableArray *cookies = [[sessionCookies retain] autorelease];
  3563. [sessionCookiesLock unlock];
  3564. return cookies;
  3565. }
  3566. + (void)setSessionCookies:(NSMutableArray *)newSessionCookies
  3567. {
  3568. [sessionCookiesLock lock];
  3569. // Remove existing cookies from the persistent store
  3570. for (NSHTTPCookie *cookie in sessionCookies) {
  3571. [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
  3572. }
  3573. [sessionCookies release];
  3574. sessionCookies = [newSessionCookies retain];
  3575. [sessionCookiesLock unlock];
  3576. }
  3577. + (void)addSessionCookie:(NSHTTPCookie *)newCookie
  3578. {
  3579. [sessionCookiesLock lock];
  3580. NSHTTPCookie *cookie;
  3581. NSUInteger i;
  3582. NSUInteger max = [[ASIHTTPRequest sessionCookies] count];
  3583. for (i=0; i<max; i++) {
  3584. cookie = [[ASIHTTPRequest sessionCookies] objectAtIndex:i];
  3585. if ([[cookie domain] isEqualToString:[newCookie domain]] && [[cookie path] isEqualToString:[newCookie path]] && [[cookie name] isEqualToString:[newCookie name]]) {
  3586. [[ASIHTTPRequest sessionCookies] removeObjectAtIndex:i];
  3587. break;
  3588. }
  3589. }
  3590. [[ASIHTTPRequest sessionCookies] addObject:newCookie];
  3591. [sessionCookiesLock unlock];
  3592. }
  3593. // Dump all session data (authentication and cookies)
  3594. + (void)clearSession
  3595. {
  3596. [sessionCredentialsLock lock];
  3597. [[[self class] sessionCredentialsStore] removeAllObjects];
  3598. [sessionCredentialsLock unlock];
  3599. [[self class] setSessionCookies:nil];
  3600. [[[self class] defaultCache] clearCachedResponsesForStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy];
  3601. }
  3602. #pragma mark get user agent
  3603. + (NSString *)defaultUserAgentString
  3604. {
  3605. @synchronized (self) {
  3606. if (!defaultUserAgent) {
  3607. NSBundle *bundle = [NSBundle bundleForClass:[self class]];
  3608. // Attempt to find a name for this application
  3609. NSString *appName = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
  3610. if (!appName) {
  3611. appName = [bundle objectForInfoDictionaryKey:@"CFBundleName"];
  3612. }
  3613. NSData *latin1Data = [appName dataUsingEncoding:NSUTF8StringEncoding];
  3614. appName = [[[NSString alloc] initWithData:latin1Data encoding:NSISOLatin1StringEncoding] autorelease];
  3615. // If we couldn't find one, we'll give up (and ASIHTTPRequest will use the standard CFNetwork user agent)
  3616. if (!appName) {
  3617. return nil;
  3618. }
  3619. NSString *appVersion = nil;
  3620. NSString *marketingVersionNumber = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
  3621. NSString *developmentVersionNumber = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"];
  3622. if (marketingVersionNumber && developmentVersionNumber) {
  3623. if ([marketingVersionNumber isEqualToString:developmentVersionNumber]) {
  3624. appVersion = marketingVersionNumber;
  3625. } else {
  3626. appVersion = [NSString stringWithFormat:@"%@ rv:%@",marketingVersionNumber,developmentVersionNumber];
  3627. }
  3628. } else {
  3629. appVersion = (marketingVersionNumber ? marketingVersionNumber : developmentVersionNumber);
  3630. }
  3631. NSString *deviceName;
  3632. NSString *OSName;
  3633. NSString *OSVersion;
  3634. NSString *locale = [[NSLocale currentLocale] localeIdentifier];
  3635. #if TARGET_OS_IPHONE
  3636. UIDevice *device = [UIDevice currentDevice];
  3637. deviceName = [device model];
  3638. OSName = [device systemName];
  3639. OSVersion = [device systemVersion];
  3640. #else
  3641. deviceName = @"Macintosh";
  3642. OSName = @"Mac OS X";
  3643. // From http://www.cocoadev.com/index.pl?DeterminingOSVersion
  3644. // We won't bother to check for systems prior to 10.4, since ASIHTTPRequest only works on 10.5+
  3645. OSErr err;
  3646. SInt32 versionMajor, versionMinor, versionBugFix;
  3647. err = Gestalt(gestaltSystemVersionMajor, &versionMajor);
  3648. if (err != noErr) return nil;
  3649. err = Gestalt(gestaltSystemVersionMinor, &versionMinor);
  3650. if (err != noErr) return nil;
  3651. err = Gestalt(gestaltSystemVersionBugFix, &versionBugFix);
  3652. if (err != noErr) return nil;
  3653. OSVersion = [NSString stringWithFormat:@"%u.%u.%u", versionMajor, versionMinor, versionBugFix];
  3654. #endif
  3655. // Takes the form "My Application 1.0 (Macintosh; Mac OS X 10.5.7; en_GB)"
  3656. [self setDefaultUserAgentString:[NSString stringWithFormat:@"%@ %@ (%@; %@ %@; %@)", appName, appVersion, deviceName, OSName, OSVersion, locale]];
  3657. }
  3658. return [[defaultUserAgent retain] autorelease];
  3659. }
  3660. return nil;
  3661. }
  3662. + (void)setDefaultUserAgentString:(NSString *)agent
  3663. {
  3664. @synchronized (self) {
  3665. if (defaultUserAgent == agent) {
  3666. return;
  3667. }
  3668. [defaultUserAgent release];
  3669. defaultUserAgent = [agent copy];
  3670. }
  3671. }
  3672. #pragma mark mime-type detection
  3673. + (NSString *)mimeTypeForFileAtPath:(NSString *)path
  3674. {
  3675. if (![[[[NSFileManager alloc] init] autorelease] fileExistsAtPath:path]) {
  3676. return nil;
  3677. }
  3678. // Borrowed from http://stackoverflow.com/questions/2439020/wheres-the-iphone-mime-type-database
  3679. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)[path pathExtension], NULL);
  3680. CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  3681. CFRelease(UTI);
  3682. if (!MIMEType) {
  3683. return @"application/octet-stream";
  3684. }
  3685. return [NSMakeCollectable(MIMEType) autorelease];
  3686. }
  3687. #pragma mark bandwidth measurement / throttling
  3688. - (void)performThrottling
  3689. {
  3690. if (![self readStream]) {
  3691. return;
  3692. }
  3693. [ASIHTTPRequest measureBandwidthUsage];
  3694. if ([ASIHTTPRequest isBandwidthThrottled]) {
  3695. [bandwidthThrottlingLock lock];
  3696. // Handle throttling
  3697. if (throttleWakeUpTime) {
  3698. if ([throttleWakeUpTime timeIntervalSinceDate:[NSDate date]] > 0) {
  3699. if ([self readStreamIsScheduled]) {
  3700. [self unscheduleReadStream];
  3701. #if DEBUG_THROTTLING
  3702. ASI_DEBUG_LOG(@"[THROTTLING] Sleeping request %@ until after %@",self,throttleWakeUpTime);
  3703. #endif
  3704. }
  3705. } else {
  3706. if (![self readStreamIsScheduled]) {
  3707. [self scheduleReadStream];
  3708. #if DEBUG_THROTTLING
  3709. ASI_DEBUG_LOG(@"[THROTTLING] Waking up request %@",self);
  3710. #endif
  3711. }
  3712. }
  3713. }
  3714. [bandwidthThrottlingLock unlock];
  3715. // Bandwidth throttling must have been turned off since we last looked, let's re-schedule the stream
  3716. } else if (![self readStreamIsScheduled]) {
  3717. [self scheduleReadStream];
  3718. }
  3719. }
  3720. + (BOOL)isBandwidthThrottled
  3721. {
  3722. #if TARGET_OS_IPHONE
  3723. [bandwidthThrottlingLock lock];
  3724. BOOL throttle = isBandwidthThrottled || (!shouldThrottleBandwidthForWWANOnly && (maxBandwidthPerSecond > 0));
  3725. [bandwidthThrottlingLock unlock];
  3726. return throttle;
  3727. #else
  3728. [bandwidthThrottlingLock lock];
  3729. BOOL throttle = (maxBandwidthPerSecond > 0);
  3730. [bandwidthThrottlingLock unlock];
  3731. return throttle;
  3732. #endif
  3733. }
  3734. + (unsigned long)maxBandwidthPerSecond
  3735. {
  3736. [bandwidthThrottlingLock lock];
  3737. unsigned long amount = maxBandwidthPerSecond;
  3738. [bandwidthThrottlingLock unlock];
  3739. return amount;
  3740. }
  3741. + (void)setMaxBandwidthPerSecond:(unsigned long)bytes
  3742. {
  3743. [bandwidthThrottlingLock lock];
  3744. maxBandwidthPerSecond = bytes;
  3745. [bandwidthThrottlingLock unlock];
  3746. }
  3747. + (void)incrementBandwidthUsedInLastSecond:(unsigned long)bytes
  3748. {
  3749. [bandwidthThrottlingLock lock];
  3750. bandwidthUsedInLastSecond += bytes;
  3751. [bandwidthThrottlingLock unlock];
  3752. }
  3753. + (void)recordBandwidthUsage
  3754. {
  3755. if (bandwidthUsedInLastSecond == 0) {
  3756. [bandwidthUsageTracker removeAllObjects];
  3757. } else {
  3758. NSTimeInterval interval = [bandwidthMeasurementDate timeIntervalSinceNow];
  3759. while ((interval < 0 || [bandwidthUsageTracker count] > 5) && [bandwidthUsageTracker count] > 0) {
  3760. [bandwidthUsageTracker removeObjectAtIndex:0];
  3761. interval++;
  3762. }
  3763. }
  3764. #if DEBUG_THROTTLING
  3765. ASI_DEBUG_LOG(@"[THROTTLING] --------------Used: %u bytes of bandwidth in last measurement period--------------",bandwidthUsedInLastSecond);
  3766. #endif
  3767. [bandwidthUsageTracker addObject:[NSNumber numberWithUnsignedLong:bandwidthUsedInLastSecond]];
  3768. [bandwidthMeasurementDate release];
  3769. bandwidthMeasurementDate = [[NSDate dateWithTimeIntervalSinceNow:1] retain];
  3770. bandwidthUsedInLastSecond = 0;
  3771. NSUInteger measurements = [bandwidthUsageTracker count];
  3772. unsigned long totalBytes = 0;
  3773. for (NSNumber *bytes in bandwidthUsageTracker) {
  3774. totalBytes += [bytes unsignedLongValue];
  3775. }
  3776. averageBandwidthUsedPerSecond = totalBytes/measurements;
  3777. }
  3778. + (unsigned long)averageBandwidthUsedPerSecond
  3779. {
  3780. [bandwidthThrottlingLock lock];
  3781. unsigned long amount = averageBandwidthUsedPerSecond;
  3782. [bandwidthThrottlingLock unlock];
  3783. return amount;
  3784. }
  3785. + (void)measureBandwidthUsage
  3786. {
  3787. // Other requests may have to wait for this lock if we're sleeping, but this is fine, since in that case we already know they shouldn't be sending or receiving data
  3788. [bandwidthThrottlingLock lock];
  3789. if (!bandwidthMeasurementDate || [bandwidthMeasurementDate timeIntervalSinceNow] < -0) {
  3790. [ASIHTTPRequest recordBandwidthUsage];
  3791. }
  3792. // Are we performing bandwidth throttling?
  3793. if (
  3794. #if TARGET_OS_IPHONE
  3795. isBandwidthThrottled || (!shouldThrottleBandwidthForWWANOnly && (maxBandwidthPerSecond))
  3796. #else
  3797. maxBandwidthPerSecond
  3798. #endif
  3799. ) {
  3800. // How much data can we still send or receive this second?
  3801. long long bytesRemaining = (long long)maxBandwidthPerSecond - (long long)bandwidthUsedInLastSecond;
  3802. // Have we used up our allowance?
  3803. if (bytesRemaining < 0) {
  3804. // Yes, put this request to sleep until a second is up, with extra added punishment sleeping time for being very naughty (we have used more bandwidth than we were allowed)
  3805. double extraSleepyTime = (-bytesRemaining/(maxBandwidthPerSecond*1.0));
  3806. [throttleWakeUpTime release];
  3807. throttleWakeUpTime = [[NSDate alloc] initWithTimeInterval:extraSleepyTime sinceDate:bandwidthMeasurementDate];
  3808. }
  3809. }
  3810. [bandwidthThrottlingLock unlock];
  3811. }
  3812. + (unsigned long)maxUploadReadLength
  3813. {
  3814. [bandwidthThrottlingLock lock];
  3815. // We'll split our bandwidth allowance into 4 (which is the default for an ASINetworkQueue's max concurrent operations count) to give all running requests a fighting chance of reading data this cycle
  3816. long long toRead = maxBandwidthPerSecond/4;
  3817. if (maxBandwidthPerSecond > 0 && (bandwidthUsedInLastSecond + toRead > maxBandwidthPerSecond)) {
  3818. toRead = (long long)maxBandwidthPerSecond- (long long)bandwidthUsedInLastSecond;
  3819. if (toRead < 0) {
  3820. toRead = 0;
  3821. }
  3822. }
  3823. if (toRead == 0 || !bandwidthMeasurementDate || [bandwidthMeasurementDate timeIntervalSinceNow] < -0) {
  3824. [throttleWakeUpTime release];
  3825. throttleWakeUpTime = [bandwidthMeasurementDate retain];
  3826. }
  3827. [bandwidthThrottlingLock unlock];
  3828. return (unsigned long)toRead;
  3829. }
  3830. #if TARGET_OS_IPHONE
  3831. + (void)setShouldThrottleBandwidthForWWAN:(BOOL)throttle
  3832. {
  3833. if (throttle) {
  3834. [ASIHTTPRequest throttleBandwidthForWWANUsingLimit:ASIWWANBandwidthThrottleAmount];
  3835. } else {
  3836. [ASIHTTPRequest unsubscribeFromNetworkReachabilityNotifications];
  3837. [ASIHTTPRequest setMaxBandwidthPerSecond:0];
  3838. [bandwidthThrottlingLock lock];
  3839. isBandwidthThrottled = NO;
  3840. shouldThrottleBandwidthForWWANOnly = NO;
  3841. [bandwidthThrottlingLock unlock];
  3842. }
  3843. }
  3844. + (void)throttleBandwidthForWWANUsingLimit:(unsigned long)limit
  3845. {
  3846. [bandwidthThrottlingLock lock];
  3847. shouldThrottleBandwidthForWWANOnly = YES;
  3848. maxBandwidthPerSecond = limit;
  3849. [ASIHTTPRequest registerForNetworkReachabilityNotifications];
  3850. [bandwidthThrottlingLock unlock];
  3851. [ASIHTTPRequest reachabilityChanged:nil];
  3852. }
  3853. #pragma mark reachability
  3854. + (void)registerForNetworkReachabilityNotifications
  3855. {
  3856. [[Reachability reachabilityForInternetConnection] startNotifier];
  3857. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  3858. }
  3859. + (void)unsubscribeFromNetworkReachabilityNotifications
  3860. {
  3861. [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
  3862. }
  3863. + (BOOL)isNetworkReachableViaWWAN
  3864. {
  3865. return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == ReachableViaWWAN);
  3866. }
  3867. + (void)reachabilityChanged:(NSNotification *)note
  3868. {
  3869. [bandwidthThrottlingLock lock];
  3870. isBandwidthThrottled = [ASIHTTPRequest isNetworkReachableViaWWAN];
  3871. [bandwidthThrottlingLock unlock];
  3872. }
  3873. #endif
  3874. #pragma mark queue
  3875. // Returns the shared queue
  3876. + (NSOperationQueue *)sharedQueue
  3877. {
  3878. return [[sharedQueue retain] autorelease];
  3879. }
  3880. #pragma mark cache
  3881. + (void)setDefaultCache:(id <ASICacheDelegate>)cache
  3882. {
  3883. @synchronized (self) {
  3884. [cache retain];
  3885. [defaultCache release];
  3886. defaultCache = cache;
  3887. }
  3888. }
  3889. + (id <ASICacheDelegate>)defaultCache
  3890. {
  3891. @synchronized(self) {
  3892. return [[defaultCache retain] autorelease];
  3893. }
  3894. return nil;
  3895. }
  3896. #pragma mark network activity
  3897. + (BOOL)isNetworkInUse
  3898. {
  3899. [connectionsLock lock];
  3900. BOOL inUse = (runningRequestCount > 0);
  3901. [connectionsLock unlock];
  3902. return inUse;
  3903. }
  3904. + (void)setShouldUpdateNetworkActivityIndicator:(BOOL)shouldUpdate
  3905. {
  3906. [connectionsLock lock];
  3907. shouldUpdateNetworkActivityIndicator = shouldUpdate;
  3908. [connectionsLock unlock];
  3909. }
  3910. + (void)showNetworkActivityIndicator
  3911. {
  3912. #if TARGET_OS_IPHONE
  3913. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  3914. #endif
  3915. }
  3916. + (void)hideNetworkActivityIndicator
  3917. {
  3918. #if TARGET_OS_IPHONE
  3919. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  3920. #endif
  3921. }
  3922. /* Always called on main thread */
  3923. + (void)hideNetworkActivityIndicatorAfterDelay
  3924. {
  3925. [self performSelector:@selector(hideNetworkActivityIndicatorIfNeeeded) withObject:nil afterDelay:0.5];
  3926. }
  3927. + (void)hideNetworkActivityIndicatorIfNeeeded
  3928. {
  3929. [connectionsLock lock];
  3930. if (runningRequestCount == 0) {
  3931. [self hideNetworkActivityIndicator];
  3932. }
  3933. [connectionsLock unlock];
  3934. }
  3935. #pragma mark threading behaviour
  3936. // In the default implementation, all requests run in a single background thread
  3937. // Advanced users only: Override this method in a subclass for a different threading behaviour
  3938. // Eg: return [NSThread mainThread] to run all requests in the main thread
  3939. // Alternatively, you can create a thread on demand, or manage a pool of threads
  3940. // Threads returned by this method will need to run the runloop in default mode (eg CFRunLoopRun())
  3941. // Requests will stop the runloop when they complete
  3942. // If you have multiple requests sharing the thread or you want to re-use the thread, you'll need to restart the runloop
  3943. + (NSThread *)threadForRequest:(ASIHTTPRequest *)request
  3944. {
  3945. if (networkThread == nil) {
  3946. @synchronized(self) {
  3947. if (networkThread == nil) {
  3948. networkThread = [[NSThread alloc] initWithTarget:self selector:@selector(runRequests) object:nil];
  3949. [networkThread start];
  3950. }
  3951. }
  3952. }
  3953. return networkThread;
  3954. }
  3955. + (void)runRequests
  3956. {
  3957. // Should keep the runloop from exiting
  3958. CFRunLoopSourceContext context = {0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
  3959. CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
  3960. CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
  3961. BOOL runAlways = YES; // Introduced to cheat Static Analyzer
  3962. while (runAlways) {
  3963. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  3964. CFRunLoopRun();
  3965. [pool drain];
  3966. }
  3967. // Should never be called, but anyway
  3968. CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
  3969. CFRelease(source);
  3970. }
  3971. #pragma mark miscellany
  3972. #if TARGET_OS_IPHONE
  3973. + (BOOL)isMultitaskingSupported
  3974. {
  3975. BOOL multiTaskingSupported = NO;
  3976. if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  3977. multiTaskingSupported = [(id)[UIDevice currentDevice] isMultitaskingSupported];
  3978. }
  3979. return multiTaskingSupported;
  3980. }
  3981. #endif
  3982. // From: http://www.cocoadev.com/index.pl?BaseSixtyFour
  3983. + (NSString*)base64forData:(NSData*)theData {
  3984. const uint8_t* input = (const uint8_t*)[theData bytes];
  3985. NSInteger length = [theData length];
  3986. static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3987. NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
  3988. uint8_t* output = (uint8_t*)data.mutableBytes;
  3989. NSInteger i,i2;
  3990. for (i=0; i < length; i += 3) {
  3991. NSInteger value = 0;
  3992. for (i2=0; i2<3; i2++) {
  3993. value <<= 8;
  3994. if (i+i2 < length) {
  3995. value |= (0xFF & input[i+i2]);
  3996. }
  3997. }
  3998. NSInteger theIndex = (i / 3) * 4;
  3999. output[theIndex + 0] = table[(value >> 18) & 0x3F];
  4000. output[theIndex + 1] = table[(value >> 12) & 0x3F];
  4001. output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
  4002. output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
  4003. }
  4004. return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
  4005. }
  4006. + (NSDate *)expiryDateForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge
  4007. {
  4008. NSDictionary *responseHeaders = [request responseHeaders];
  4009. // If we weren't given a custom max-age, lets look for one in the response headers
  4010. if (!maxAge) {
  4011. NSString *cacheControl = [[responseHeaders objectForKey:@"Cache-Control"] lowercaseString];
  4012. if (cacheControl) {
  4013. NSScanner *scanner = [NSScanner scannerWithString:cacheControl];
  4014. [scanner scanUpToString:@"max-age" intoString:NULL];
  4015. if ([scanner scanString:@"max-age" intoString:NULL]) {
  4016. [scanner scanString:@"=" intoString:NULL];
  4017. [scanner scanDouble:&maxAge];
  4018. }
  4019. }
  4020. }
  4021. // RFC 2612 says max-age must override any Expires header
  4022. if (maxAge) {
  4023. return [[NSDate date] dateByAddingTimeInterval:maxAge];
  4024. } else {
  4025. NSString *expires = [responseHeaders objectForKey:@"Expires"];
  4026. if (expires) {
  4027. return [ASIHTTPRequest dateFromRFC1123String:expires];
  4028. }
  4029. }
  4030. return nil;
  4031. }
  4032. // Based on hints from http://stackoverflow.com/questions/1850824/parsing-a-rfc-822-date-with-nsdateformatter
  4033. + (NSDate *)dateFromRFC1123String:(NSString *)string
  4034. {
  4035. NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
  4036. [formatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
  4037. // Does the string include a week day?
  4038. NSString *day = @"";
  4039. if ([string rangeOfString:@","].location != NSNotFound) {
  4040. day = @"EEE, ";
  4041. }
  4042. // Does the string include seconds?
  4043. NSString *seconds = @"";
  4044. if ([[string componentsSeparatedByString:@":"] count] == 3) {
  4045. seconds = @":ss";
  4046. }
  4047. [formatter setDateFormat:[NSString stringWithFormat:@"%@dd MMM yyyy HH:mm%@ z",day,seconds]];
  4048. return [formatter dateFromString:string];
  4049. }
  4050. + (void)parseMimeType:(NSString **)mimeType andResponseEncoding:(NSStringEncoding *)stringEncoding fromContentType:(NSString *)contentType
  4051. {
  4052. if (!contentType) {
  4053. return;
  4054. }
  4055. NSScanner *charsetScanner = [NSScanner scannerWithString: contentType];
  4056. if (![charsetScanner scanUpToString:@";" intoString:mimeType] || [charsetScanner scanLocation] == [contentType length]) {
  4057. *mimeType = [contentType stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  4058. return;
  4059. }
  4060. *mimeType = [*mimeType stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  4061. NSString *charsetSeparator = @"charset=";
  4062. NSString *IANAEncoding = nil;
  4063. if ([charsetScanner scanUpToString: charsetSeparator intoString: NULL] && [charsetScanner scanLocation] < [contentType length]) {
  4064. [charsetScanner setScanLocation: [charsetScanner scanLocation] + [charsetSeparator length]];
  4065. [charsetScanner scanUpToString: @";" intoString: &IANAEncoding];
  4066. }
  4067. if (IANAEncoding) {
  4068. CFStringEncoding cfEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)IANAEncoding);
  4069. if (cfEncoding != kCFStringEncodingInvalidId) {
  4070. *stringEncoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding);
  4071. }
  4072. }
  4073. }
  4074. #pragma mark -
  4075. #pragma mark blocks
  4076. #if NS_BLOCKS_AVAILABLE
  4077. - (void)setStartedBlock:(ASIBasicBlock)aStartedBlock
  4078. {
  4079. [startedBlock release];
  4080. startedBlock = [aStartedBlock copy];
  4081. }
  4082. - (void)setHeadersReceivedBlock:(ASIHeadersBlock)aReceivedBlock
  4083. {
  4084. [headersReceivedBlock release];
  4085. headersReceivedBlock = [aReceivedBlock copy];
  4086. }
  4087. - (void)setCompletionBlock:(ASIBasicBlock)aCompletionBlock
  4088. {
  4089. [completionBlock release];
  4090. completionBlock = [aCompletionBlock copy];
  4091. }
  4092. - (void)setFailedBlock:(ASIBasicBlock)aFailedBlock
  4093. {
  4094. [failureBlock release];
  4095. failureBlock = [aFailedBlock copy];
  4096. }
  4097. - (void)setBytesReceivedBlock:(ASIProgressBlock)aBytesReceivedBlock
  4098. {
  4099. [bytesReceivedBlock release];
  4100. bytesReceivedBlock = [aBytesReceivedBlock copy];
  4101. }
  4102. - (void)setBytesSentBlock:(ASIProgressBlock)aBytesSentBlock
  4103. {
  4104. [bytesSentBlock release];
  4105. bytesSentBlock = [aBytesSentBlock copy];
  4106. }
  4107. - (void)setDownloadSizeIncrementedBlock:(ASISizeBlock)aDownloadSizeIncrementedBlock{
  4108. [downloadSizeIncrementedBlock release];
  4109. downloadSizeIncrementedBlock = [aDownloadSizeIncrementedBlock copy];
  4110. }
  4111. - (void)setUploadSizeIncrementedBlock:(ASISizeBlock)anUploadSizeIncrementedBlock
  4112. {
  4113. [uploadSizeIncrementedBlock release];
  4114. uploadSizeIncrementedBlock = [anUploadSizeIncrementedBlock copy];
  4115. }
  4116. - (void)setDataReceivedBlock:(ASIDataBlock)aReceivedBlock
  4117. {
  4118. [dataReceivedBlock release];
  4119. dataReceivedBlock = [aReceivedBlock copy];
  4120. }
  4121. - (void)setAuthenticationNeededBlock:(ASIBasicBlock)anAuthenticationBlock
  4122. {
  4123. [authenticationNeededBlock release];
  4124. authenticationNeededBlock = [anAuthenticationBlock copy];
  4125. }
  4126. - (void)setProxyAuthenticationNeededBlock:(ASIBasicBlock)aProxyAuthenticationBlock
  4127. {
  4128. [proxyAuthenticationNeededBlock release];
  4129. proxyAuthenticationNeededBlock = [aProxyAuthenticationBlock copy];
  4130. }
  4131. - (void)setRequestRedirectedBlock:(ASIBasicBlock)aRedirectBlock
  4132. {
  4133. [requestRedirectedBlock release];
  4134. requestRedirectedBlock = [aRedirectBlock copy];
  4135. }
  4136. #endif
  4137. #pragma mark --------------
  4138. @synthesize username;
  4139. @synthesize password;
  4140. @synthesize userAgent;
  4141. @synthesize domain;
  4142. @synthesize proxyUsername;
  4143. @synthesize proxyPassword;
  4144. @synthesize proxyDomain;
  4145. @synthesize url;
  4146. @synthesize originalURL;
  4147. @synthesize delegate;
  4148. @synthesize queue;
  4149. @synthesize uploadProgressDelegate;
  4150. @synthesize downloadProgressDelegate;
  4151. @synthesize useKeychainPersistence;
  4152. @synthesize useSessionPersistence;
  4153. @synthesize useCookiePersistence;
  4154. @synthesize downloadDestinationPath;
  4155. @synthesize temporaryFileDownloadPath;
  4156. @synthesize temporaryUncompressedDataDownloadPath;
  4157. @synthesize didStartSelector;
  4158. @synthesize didReceiveResponseHeadersSelector;
  4159. @synthesize willRedirectSelector;
  4160. @synthesize didFinishSelector;
  4161. @synthesize didFailSelector;
  4162. @synthesize didReceiveDataSelector;
  4163. @synthesize authenticationRealm;
  4164. @synthesize proxyAuthenticationRealm;
  4165. @synthesize error;
  4166. @synthesize complete;
  4167. @synthesize requestHeaders;
  4168. @synthesize responseHeaders;
  4169. @synthesize responseCookies;
  4170. @synthesize requestCookies;
  4171. @synthesize requestCredentials;
  4172. @synthesize responseStatusCode;
  4173. @synthesize rawResponseData;
  4174. @synthesize lastActivityTime;
  4175. @synthesize timeOutSeconds;
  4176. @synthesize requestMethod;
  4177. @synthesize postBody;
  4178. @synthesize compressedPostBody;
  4179. @synthesize contentLength;
  4180. @synthesize partialDownloadSize;
  4181. @synthesize postLength;
  4182. @synthesize shouldResetDownloadProgress;
  4183. @synthesize shouldResetUploadProgress;
  4184. @synthesize mainRequest;
  4185. @synthesize totalBytesRead;
  4186. @synthesize totalBytesSent;
  4187. @synthesize showAccurateProgress;
  4188. @synthesize uploadBufferSize;
  4189. @synthesize defaultResponseEncoding;
  4190. @synthesize responseEncoding;
  4191. @synthesize allowCompressedResponse;
  4192. @synthesize allowResumeForFileDownloads;
  4193. @synthesize userInfo;
  4194. @synthesize tag;
  4195. @synthesize postBodyFilePath;
  4196. @synthesize compressedPostBodyFilePath;
  4197. @synthesize postBodyWriteStream;
  4198. @synthesize postBodyReadStream;
  4199. @synthesize shouldStreamPostDataFromDisk;
  4200. @synthesize didCreateTemporaryPostDataFile;
  4201. @synthesize useHTTPVersionOne;
  4202. @synthesize lastBytesRead;
  4203. @synthesize lastBytesSent;
  4204. @synthesize cancelledLock;
  4205. @synthesize haveBuiltPostBody;
  4206. @synthesize fileDownloadOutputStream;
  4207. @synthesize inflatedFileDownloadOutputStream;
  4208. @synthesize authenticationRetryCount;
  4209. @synthesize proxyAuthenticationRetryCount;
  4210. @synthesize updatedProgress;
  4211. @synthesize shouldRedirect;
  4212. @synthesize validatesSecureCertificate;
  4213. @synthesize needsRedirect;
  4214. @synthesize redirectCount;
  4215. @synthesize shouldCompressRequestBody;
  4216. @synthesize proxyCredentials;
  4217. @synthesize proxyHost;
  4218. @synthesize proxyPort;
  4219. @synthesize proxyType;
  4220. @synthesize PACurl;
  4221. @synthesize authenticationScheme;
  4222. @synthesize proxyAuthenticationScheme;
  4223. @synthesize shouldPresentAuthenticationDialog;
  4224. @synthesize shouldPresentProxyAuthenticationDialog;
  4225. @synthesize authenticationNeeded;
  4226. @synthesize responseStatusMessage;
  4227. @synthesize shouldPresentCredentialsBeforeChallenge;
  4228. @synthesize haveBuiltRequestHeaders;
  4229. @synthesize inProgress;
  4230. @synthesize numberOfTimesToRetryOnTimeout;
  4231. @synthesize retryCount;
  4232. @synthesize willRetryRequest;
  4233. @synthesize shouldAttemptPersistentConnection;
  4234. @synthesize persistentConnectionTimeoutSeconds;
  4235. @synthesize connectionCanBeReused;
  4236. @synthesize connectionInfo;
  4237. @synthesize readStream;
  4238. @synthesize readStreamIsScheduled;
  4239. @synthesize shouldUseRFC2616RedirectBehaviour;
  4240. @synthesize downloadComplete;
  4241. @synthesize requestID;
  4242. @synthesize runLoopMode;
  4243. @synthesize statusTimer;
  4244. @synthesize downloadCache;
  4245. @synthesize cachePolicy;
  4246. @synthesize cacheStoragePolicy;
  4247. @synthesize didUseCachedResponse;
  4248. @synthesize secondsToCache;
  4249. @synthesize clientCertificates;
  4250. @synthesize redirectURL;
  4251. #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
  4252. @synthesize shouldContinueWhenAppEntersBackground;
  4253. #endif
  4254. @synthesize dataDecompressor;
  4255. @synthesize shouldWaitToInflateCompressedResponses;
  4256. @synthesize isPACFileRequest;
  4257. @synthesize PACFileRequest;
  4258. @synthesize PACFileReadStream;
  4259. @synthesize PACFileData;
  4260. @synthesize isSynchronous;
  4261. @end