ASIHTTPRequest.m 181 KB

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