url.c 177 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at http://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "curl_setup.h"
  23. #ifdef HAVE_NETINET_IN_H
  24. #include <netinet/in.h>
  25. #endif
  26. #ifdef HAVE_NETDB_H
  27. #include <netdb.h>
  28. #endif
  29. #ifdef HAVE_ARPA_INET_H
  30. #include <arpa/inet.h>
  31. #endif
  32. #ifdef HAVE_NET_IF_H
  33. #include <net/if.h>
  34. #endif
  35. #ifdef HAVE_SYS_IOCTL_H
  36. #include <sys/ioctl.h>
  37. #endif
  38. #ifdef HAVE_SYS_PARAM_H
  39. #include <sys/param.h>
  40. #endif
  41. #ifdef __VMS
  42. #include <in.h>
  43. #include <inet.h>
  44. #endif
  45. #ifndef HAVE_SOCKET
  46. #error "We can't compile without socket() support!"
  47. #endif
  48. #ifdef HAVE_LIMITS_H
  49. #include <limits.h>
  50. #endif
  51. #ifdef USE_LIBIDN
  52. #include <idna.h>
  53. #include <tld.h>
  54. #include <stringprep.h>
  55. #ifdef HAVE_IDN_FREE_H
  56. #include <idn-free.h>
  57. #else
  58. /* prototype from idn-free.h, not provided by libidn 0.4.5's make install! */
  59. void idn_free (void *ptr);
  60. #endif
  61. #ifndef HAVE_IDN_FREE
  62. /* if idn_free() was not found in this version of libidn use free() instead */
  63. #define idn_free(x) (free)(x)
  64. #endif
  65. #elif defined(USE_WIN32_IDN)
  66. /* prototype for curl_win32_idn_to_ascii() */
  67. int curl_win32_idn_to_ascii(const char *in, char **out);
  68. #endif /* USE_LIBIDN */
  69. #include "urldata.h"
  70. #include "netrc.h"
  71. #include "formdata.h"
  72. #include "vtls/vtls.h"
  73. #include "hostip.h"
  74. #include "transfer.h"
  75. #include "sendf.h"
  76. #include "progress.h"
  77. #include "cookie.h"
  78. #include "strequal.h"
  79. #include "strerror.h"
  80. #include "escape.h"
  81. #include "strtok.h"
  82. #include "share.h"
  83. #include "content_encoding.h"
  84. #include "http_digest.h"
  85. #include "http_negotiate.h"
  86. #include "select.h"
  87. #include "multiif.h"
  88. #include "easyif.h"
  89. #include "speedcheck.h"
  90. #include "rawstr.h"
  91. #include "warnless.h"
  92. #include "non-ascii.h"
  93. #include "inet_pton.h"
  94. /* And now for the protocols */
  95. #include "ftp.h"
  96. #include "dict.h"
  97. #include "telnet.h"
  98. #include "tftp.h"
  99. #include "http.h"
  100. #include "file.h"
  101. #include "curl_ldap.h"
  102. #include "ssh.h"
  103. #include "imap.h"
  104. #include "url.h"
  105. #include "connect.h"
  106. #include "inet_ntop.h"
  107. #include "curl_ntlm.h"
  108. #include "curl_ntlm_wb.h"
  109. #include "socks.h"
  110. #include "curl_rtmp.h"
  111. #include "gopher.h"
  112. #include "http_proxy.h"
  113. #include "bundles.h"
  114. #include "conncache.h"
  115. #include "multihandle.h"
  116. #include "pipeline.h"
  117. #include "dotdot.h"
  118. #define _MPRINTF_REPLACE /* use our functions only */
  119. #include <curl/mprintf.h>
  120. #include "curl_memory.h"
  121. /* The last #include file should be: */
  122. #include "memdebug.h"
  123. /* Local static prototypes */
  124. static struct connectdata *
  125. find_oldest_idle_connection(struct SessionHandle *data);
  126. static struct connectdata *
  127. find_oldest_idle_connection_in_bundle(struct SessionHandle *data,
  128. struct connectbundle *bundle);
  129. static void conn_free(struct connectdata *conn);
  130. static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke);
  131. static CURLcode do_init(struct connectdata *conn);
  132. static CURLcode parse_url_login(struct SessionHandle *data,
  133. struct connectdata *conn,
  134. char **userptr, char **passwdptr,
  135. char **optionsptr);
  136. static CURLcode parse_login_details(const char *login, const size_t len,
  137. char **userptr, char **passwdptr,
  138. char **optionsptr);
  139. /*
  140. * Protocol table.
  141. */
  142. static const struct Curl_handler * const protocols[] = {
  143. #ifndef CURL_DISABLE_HTTP
  144. &Curl_handler_http,
  145. #endif
  146. #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
  147. &Curl_handler_https,
  148. #endif
  149. #ifndef CURL_DISABLE_FTP
  150. &Curl_handler_ftp,
  151. #endif
  152. #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
  153. &Curl_handler_ftps,
  154. #endif
  155. #ifndef CURL_DISABLE_TELNET
  156. &Curl_handler_telnet,
  157. #endif
  158. #ifndef CURL_DISABLE_DICT
  159. &Curl_handler_dict,
  160. #endif
  161. #ifndef CURL_DISABLE_LDAP
  162. &Curl_handler_ldap,
  163. #if !defined(CURL_DISABLE_LDAPS) && \
  164. ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
  165. (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
  166. &Curl_handler_ldaps,
  167. #endif
  168. #endif
  169. #ifndef CURL_DISABLE_FILE
  170. &Curl_handler_file,
  171. #endif
  172. #ifndef CURL_DISABLE_TFTP
  173. &Curl_handler_tftp,
  174. #endif
  175. #ifdef USE_LIBSSH2
  176. &Curl_handler_scp,
  177. &Curl_handler_sftp,
  178. #endif
  179. #ifndef CURL_DISABLE_IMAP
  180. &Curl_handler_imap,
  181. #ifdef USE_SSL
  182. &Curl_handler_imaps,
  183. #endif
  184. #endif
  185. #ifndef CURL_DISABLE_POP3
  186. &Curl_handler_pop3,
  187. #ifdef USE_SSL
  188. &Curl_handler_pop3s,
  189. #endif
  190. #endif
  191. #ifndef CURL_DISABLE_SMTP
  192. &Curl_handler_smtp,
  193. #ifdef USE_SSL
  194. &Curl_handler_smtps,
  195. #endif
  196. #endif
  197. #ifndef CURL_DISABLE_RTSP
  198. &Curl_handler_rtsp,
  199. #endif
  200. #ifndef CURL_DISABLE_GOPHER
  201. &Curl_handler_gopher,
  202. #endif
  203. #ifdef USE_LIBRTMP
  204. &Curl_handler_rtmp,
  205. &Curl_handler_rtmpt,
  206. &Curl_handler_rtmpe,
  207. &Curl_handler_rtmpte,
  208. &Curl_handler_rtmps,
  209. &Curl_handler_rtmpts,
  210. #endif
  211. (struct Curl_handler *) NULL
  212. };
  213. /*
  214. * Dummy handler for undefined protocol schemes.
  215. */
  216. static const struct Curl_handler Curl_handler_dummy = {
  217. "<no protocol>", /* scheme */
  218. ZERO_NULL, /* setup_connection */
  219. ZERO_NULL, /* do_it */
  220. ZERO_NULL, /* done */
  221. ZERO_NULL, /* do_more */
  222. ZERO_NULL, /* connect_it */
  223. ZERO_NULL, /* connecting */
  224. ZERO_NULL, /* doing */
  225. ZERO_NULL, /* proto_getsock */
  226. ZERO_NULL, /* doing_getsock */
  227. ZERO_NULL, /* domore_getsock */
  228. ZERO_NULL, /* perform_getsock */
  229. ZERO_NULL, /* disconnect */
  230. ZERO_NULL, /* readwrite */
  231. 0, /* defport */
  232. 0, /* protocol */
  233. PROTOPT_NONE /* flags */
  234. };
  235. void Curl_freeset(struct SessionHandle *data)
  236. {
  237. /* Free all dynamic strings stored in the data->set substructure. */
  238. enum dupstring i;
  239. for(i=(enum dupstring)0; i < STRING_LAST; i++)
  240. Curl_safefree(data->set.str[i]);
  241. if(data->change.referer_alloc) {
  242. Curl_safefree(data->change.referer);
  243. data->change.referer_alloc = FALSE;
  244. }
  245. data->change.referer = NULL;
  246. }
  247. static CURLcode setstropt(char **charp, char *s)
  248. {
  249. /* Release the previous storage at `charp' and replace by a dynamic storage
  250. copy of `s'. Return CURLE_OK or CURLE_OUT_OF_MEMORY. */
  251. Curl_safefree(*charp);
  252. if(s) {
  253. s = strdup(s);
  254. if(!s)
  255. return CURLE_OUT_OF_MEMORY;
  256. *charp = s;
  257. }
  258. return CURLE_OK;
  259. }
  260. static CURLcode setstropt_userpwd(char *option, char **userp, char **passwdp)
  261. {
  262. CURLcode result = CURLE_OK;
  263. char *user = NULL;
  264. char *passwd = NULL;
  265. /* Parse the login details if specified. It not then we treat NULL as a hint
  266. to clear the existing data */
  267. if(option) {
  268. result = parse_login_details(option, strlen(option),
  269. (userp ? &user : NULL),
  270. (passwdp ? &passwd : NULL),
  271. NULL);
  272. }
  273. if(!result) {
  274. /* Store the username part of option if required */
  275. if(userp) {
  276. if(!user && option && option[0] == ':') {
  277. /* Allocate an empty string instead of returning NULL as user name */
  278. user = strdup("");
  279. if(!user)
  280. result = CURLE_OUT_OF_MEMORY;
  281. }
  282. Curl_safefree(*userp);
  283. *userp = user;
  284. }
  285. /* Store the password part of option if required */
  286. if(passwdp) {
  287. Curl_safefree(*passwdp);
  288. *passwdp = passwd;
  289. }
  290. }
  291. return result;
  292. }
  293. CURLcode Curl_dupset(struct SessionHandle *dst, struct SessionHandle *src)
  294. {
  295. CURLcode r = CURLE_OK;
  296. enum dupstring i;
  297. /* Copy src->set into dst->set first, then deal with the strings
  298. afterwards */
  299. dst->set = src->set;
  300. /* clear all string pointers first */
  301. memset(dst->set.str, 0, STRING_LAST * sizeof(char *));
  302. /* duplicate all strings */
  303. for(i=(enum dupstring)0; i< STRING_LAST; i++) {
  304. r = setstropt(&dst->set.str[i], src->set.str[i]);
  305. if(r != CURLE_OK)
  306. break;
  307. }
  308. /* If a failure occurred, freeing has to be performed externally. */
  309. return r;
  310. }
  311. /*
  312. * This is the internal function curl_easy_cleanup() calls. This should
  313. * cleanup and free all resources associated with this sessionhandle.
  314. *
  315. * NOTE: if we ever add something that attempts to write to a socket or
  316. * similar here, we must ignore SIGPIPE first. It is currently only done
  317. * when curl_easy_perform() is invoked.
  318. */
  319. CURLcode Curl_close(struct SessionHandle *data)
  320. {
  321. struct Curl_multi *m;
  322. if(!data)
  323. return CURLE_OK;
  324. Curl_expire(data, 0); /* shut off timers */
  325. m = data->multi;
  326. if(m)
  327. /* This handle is still part of a multi handle, take care of this first
  328. and detach this handle from there. */
  329. curl_multi_remove_handle(data->multi, data);
  330. if(data->multi_easy)
  331. /* when curl_easy_perform() is used, it creates its own multi handle to
  332. use and this is the one */
  333. curl_multi_cleanup(data->multi_easy);
  334. /* Destroy the timeout list that is held in the easy handle. It is
  335. /normally/ done by curl_multi_remove_handle() but this is "just in
  336. case" */
  337. if(data->state.timeoutlist) {
  338. Curl_llist_destroy(data->state.timeoutlist, NULL);
  339. data->state.timeoutlist = NULL;
  340. }
  341. data->magic = 0; /* force a clear AFTER the possibly enforced removal from
  342. the multi handle, since that function uses the magic
  343. field! */
  344. if(data->state.rangestringalloc)
  345. free(data->state.range);
  346. /* Free the pathbuffer */
  347. Curl_safefree(data->state.pathbuffer);
  348. data->state.path = NULL;
  349. /* freed here just in case DONE wasn't called */
  350. Curl_free_request_state(data);
  351. /* Close down all open SSL info and sessions */
  352. Curl_ssl_close_all(data);
  353. Curl_safefree(data->state.first_host);
  354. Curl_safefree(data->state.scratch);
  355. Curl_ssl_free_certinfo(data);
  356. if(data->change.referer_alloc) {
  357. Curl_safefree(data->change.referer);
  358. data->change.referer_alloc = FALSE;
  359. }
  360. data->change.referer = NULL;
  361. if(data->change.url_alloc) {
  362. Curl_safefree(data->change.url);
  363. data->change.url_alloc = FALSE;
  364. }
  365. data->change.url = NULL;
  366. Curl_safefree(data->state.headerbuff);
  367. Curl_flush_cookies(data, 1);
  368. Curl_digest_cleanup(data);
  369. Curl_safefree(data->info.contenttype);
  370. Curl_safefree(data->info.wouldredirect);
  371. /* this destroys the channel and we cannot use it anymore after this */
  372. Curl_resolver_cleanup(data->state.resolver);
  373. Curl_convert_close(data);
  374. /* No longer a dirty share, if it exists */
  375. if(data->share) {
  376. Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
  377. data->share->dirty--;
  378. Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
  379. }
  380. Curl_freeset(data);
  381. free(data);
  382. return CURLE_OK;
  383. }
  384. /*
  385. * Initialize the UserDefined fields within a SessionHandle.
  386. * This may be safely called on a new or existing SessionHandle.
  387. */
  388. CURLcode Curl_init_userdefined(struct UserDefined *set)
  389. {
  390. CURLcode res = CURLE_OK;
  391. set->out = stdout; /* default output to stdout */
  392. set->in = stdin; /* default input from stdin */
  393. set->err = stderr; /* default stderr to stderr */
  394. /* use fwrite as default function to store output */
  395. set->fwrite_func = (curl_write_callback)fwrite;
  396. /* use fread as default function to read input */
  397. set->fread_func = (curl_read_callback)fread;
  398. set->is_fread_set = 0;
  399. set->is_fwrite_set = 0;
  400. set->seek_func = ZERO_NULL;
  401. set->seek_client = ZERO_NULL;
  402. /* conversion callbacks for non-ASCII hosts */
  403. set->convfromnetwork = ZERO_NULL;
  404. set->convtonetwork = ZERO_NULL;
  405. set->convfromutf8 = ZERO_NULL;
  406. set->infilesize = -1; /* we don't know any size */
  407. set->postfieldsize = -1; /* unknown size */
  408. set->maxredirs = -1; /* allow any amount by default */
  409. set->httpreq = HTTPREQ_GET; /* Default HTTP request */
  410. set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
  411. set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
  412. set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
  413. set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
  414. set->ftp_filemethod = FTPFILE_MULTICWD;
  415. set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
  416. /* Set the default size of the SSL session ID cache */
  417. set->ssl.max_ssl_sessions = 5;
  418. set->proxyport = CURL_DEFAULT_PROXY_PORT; /* from url.h */
  419. set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
  420. set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
  421. set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
  422. /* make libcurl quiet by default: */
  423. set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
  424. /*
  425. * libcurl 7.10 introduced SSL verification *by default*! This needs to be
  426. * switched off unless wanted.
  427. */
  428. set->ssl.verifypeer = TRUE;
  429. set->ssl.verifyhost = TRUE;
  430. #ifdef USE_TLS_SRP
  431. set->ssl.authtype = CURL_TLSAUTH_NONE;
  432. #endif
  433. set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
  434. type */
  435. set->ssl.sessionid = TRUE; /* session ID caching enabled by default */
  436. set->new_file_perms = 0644; /* Default permissions */
  437. set->new_directory_perms = 0755; /* Default permissions */
  438. /* for the *protocols fields we don't use the CURLPROTO_ALL convenience
  439. define since we internally only use the lower 16 bits for the passed
  440. in bitmask to not conflict with the private bits */
  441. set->allowed_protocols = CURLPROTO_ALL;
  442. set->redir_protocols =
  443. CURLPROTO_ALL & ~(CURLPROTO_FILE|CURLPROTO_SCP); /* not FILE or SCP */
  444. #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
  445. /*
  446. * disallow unprotected protection negotiation NEC reference implementation
  447. * seem not to follow rfc1961 section 4.3/4.4
  448. */
  449. set->socks5_gssapi_nec = FALSE;
  450. /* set default gssapi service name */
  451. res = setstropt(&set->str[STRING_SOCKS5_GSSAPI_SERVICE],
  452. (char *) CURL_DEFAULT_SOCKS5_GSSAPI_SERVICE);
  453. if(res != CURLE_OK)
  454. return res;
  455. #endif
  456. /* This is our preferred CA cert bundle/path since install time */
  457. #if defined(CURL_CA_BUNDLE)
  458. res = setstropt(&set->str[STRING_SSL_CAFILE], (char *) CURL_CA_BUNDLE);
  459. #elif defined(CURL_CA_PATH)
  460. res = setstropt(&set->str[STRING_SSL_CAPATH], (char *) CURL_CA_PATH);
  461. #endif
  462. set->wildcardmatch = FALSE;
  463. set->chunk_bgn = ZERO_NULL;
  464. set->chunk_end = ZERO_NULL;
  465. /* tcp keepalives are disabled by default, but provide reasonable values for
  466. * the interval and idle times.
  467. */
  468. set->tcp_keepalive = FALSE;
  469. set->tcp_keepintvl = 60;
  470. set->tcp_keepidle = 60;
  471. set->ssl_enable_npn = TRUE;
  472. set->ssl_enable_alpn = TRUE;
  473. set->expect_100_timeout = 1000L; /* Wait for a second by default. */
  474. return res;
  475. }
  476. /**
  477. * Curl_open()
  478. *
  479. * @param curl is a pointer to a sessionhandle pointer that gets set by this
  480. * function.
  481. * @return CURLcode
  482. */
  483. CURLcode Curl_open(struct SessionHandle **curl)
  484. {
  485. CURLcode res = CURLE_OK;
  486. struct SessionHandle *data;
  487. CURLcode status;
  488. /* Very simple start-up: alloc the struct, init it with zeroes and return */
  489. data = calloc(1, sizeof(struct SessionHandle));
  490. if(!data) {
  491. /* this is a very serious error */
  492. DEBUGF(fprintf(stderr, "Error: calloc of SessionHandle failed\n"));
  493. return CURLE_OUT_OF_MEMORY;
  494. }
  495. data->magic = CURLEASY_MAGIC_NUMBER;
  496. status = Curl_resolver_init(&data->state.resolver);
  497. if(status) {
  498. DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
  499. free(data);
  500. return status;
  501. }
  502. /* We do some initial setup here, all those fields that can't be just 0 */
  503. data->state.headerbuff = malloc(HEADERSIZE);
  504. if(!data->state.headerbuff) {
  505. DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
  506. res = CURLE_OUT_OF_MEMORY;
  507. }
  508. else {
  509. res = Curl_init_userdefined(&data->set);
  510. data->state.headersize=HEADERSIZE;
  511. Curl_convert_init(data);
  512. /* most recent connection is not yet defined */
  513. data->state.lastconnect = NULL;
  514. data->progress.flags |= PGRS_HIDE;
  515. data->state.current_speed = -1; /* init to negative == impossible */
  516. data->wildcard.state = CURLWC_INIT;
  517. data->wildcard.filelist = NULL;
  518. data->set.fnmatch = ZERO_NULL;
  519. data->set.maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */
  520. }
  521. if(res) {
  522. Curl_resolver_cleanup(data->state.resolver);
  523. if(data->state.headerbuff)
  524. free(data->state.headerbuff);
  525. Curl_freeset(data);
  526. free(data);
  527. data = NULL;
  528. }
  529. else
  530. *curl = data;
  531. return res;
  532. }
  533. CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option,
  534. va_list param)
  535. {
  536. char *argptr;
  537. CURLcode result = CURLE_OK;
  538. long arg;
  539. #ifndef CURL_DISABLE_HTTP
  540. curl_off_t bigsize;
  541. #endif
  542. switch(option) {
  543. case CURLOPT_DNS_CACHE_TIMEOUT:
  544. data->set.dns_cache_timeout = va_arg(param, long);
  545. break;
  546. case CURLOPT_DNS_USE_GLOBAL_CACHE:
  547. /* remember we want this enabled */
  548. arg = va_arg(param, long);
  549. data->set.global_dns_cache = (0 != arg)?TRUE:FALSE;
  550. break;
  551. case CURLOPT_SSL_CIPHER_LIST:
  552. /* set a list of cipher we want to use in the SSL connection */
  553. result = setstropt(&data->set.str[STRING_SSL_CIPHER_LIST],
  554. va_arg(param, char *));
  555. break;
  556. case CURLOPT_RANDOM_FILE:
  557. /*
  558. * This is the path name to a file that contains random data to seed
  559. * the random SSL stuff with. The file is only used for reading.
  560. */
  561. result = setstropt(&data->set.str[STRING_SSL_RANDOM_FILE],
  562. va_arg(param, char *));
  563. break;
  564. case CURLOPT_EGDSOCKET:
  565. /*
  566. * The Entropy Gathering Daemon socket pathname
  567. */
  568. result = setstropt(&data->set.str[STRING_SSL_EGDSOCKET],
  569. va_arg(param, char *));
  570. break;
  571. case CURLOPT_MAXCONNECTS:
  572. /*
  573. * Set the absolute number of maximum simultaneous alive connection that
  574. * libcurl is allowed to have.
  575. */
  576. data->set.maxconnects = va_arg(param, long);
  577. break;
  578. case CURLOPT_FORBID_REUSE:
  579. /*
  580. * When this transfer is done, it must not be left to be reused by a
  581. * subsequent transfer but shall be closed immediately.
  582. */
  583. data->set.reuse_forbid = (0 != va_arg(param, long))?TRUE:FALSE;
  584. break;
  585. case CURLOPT_FRESH_CONNECT:
  586. /*
  587. * This transfer shall not use a previously cached connection but
  588. * should be made with a fresh new connect!
  589. */
  590. data->set.reuse_fresh = (0 != va_arg(param, long))?TRUE:FALSE;
  591. break;
  592. case CURLOPT_VERBOSE:
  593. /*
  594. * Verbose means infof() calls that give a lot of information about
  595. * the connection and transfer procedures as well as internal choices.
  596. */
  597. data->set.verbose = (0 != va_arg(param, long))?TRUE:FALSE;
  598. break;
  599. case CURLOPT_HEADER:
  600. /*
  601. * Set to include the header in the general data output stream.
  602. */
  603. data->set.include_header = (0 != va_arg(param, long))?TRUE:FALSE;
  604. break;
  605. case CURLOPT_NOPROGRESS:
  606. /*
  607. * Shut off the internal supported progress meter
  608. */
  609. data->set.hide_progress = (0 != va_arg(param, long))?TRUE:FALSE;
  610. if(data->set.hide_progress)
  611. data->progress.flags |= PGRS_HIDE;
  612. else
  613. data->progress.flags &= ~PGRS_HIDE;
  614. break;
  615. case CURLOPT_NOBODY:
  616. /*
  617. * Do not include the body part in the output data stream.
  618. */
  619. data->set.opt_no_body = (0 != va_arg(param, long))?TRUE:FALSE;
  620. break;
  621. case CURLOPT_FAILONERROR:
  622. /*
  623. * Don't output the >=300 error code HTML-page, but instead only
  624. * return error.
  625. */
  626. data->set.http_fail_on_error = (0 != va_arg(param, long))?TRUE:FALSE;
  627. break;
  628. case CURLOPT_UPLOAD:
  629. case CURLOPT_PUT:
  630. /*
  631. * We want to sent data to the remote host. If this is HTTP, that equals
  632. * using the PUT request.
  633. */
  634. data->set.upload = (0 != va_arg(param, long))?TRUE:FALSE;
  635. if(data->set.upload) {
  636. /* If this is HTTP, PUT is what's needed to "upload" */
  637. data->set.httpreq = HTTPREQ_PUT;
  638. data->set.opt_no_body = FALSE; /* this is implied */
  639. }
  640. else
  641. /* In HTTP, the opposite of upload is GET (unless NOBODY is true as
  642. then this can be changed to HEAD later on) */
  643. data->set.httpreq = HTTPREQ_GET;
  644. break;
  645. case CURLOPT_FILETIME:
  646. /*
  647. * Try to get the file time of the remote document. The time will
  648. * later (possibly) become available using curl_easy_getinfo().
  649. */
  650. data->set.get_filetime = (0 != va_arg(param, long))?TRUE:FALSE;
  651. break;
  652. case CURLOPT_FTP_CREATE_MISSING_DIRS:
  653. /*
  654. * An FTP option that modifies an upload to create missing directories on
  655. * the server.
  656. */
  657. switch(va_arg(param, long)) {
  658. case 0:
  659. data->set.ftp_create_missing_dirs = 0;
  660. break;
  661. case 1:
  662. data->set.ftp_create_missing_dirs = 1;
  663. break;
  664. case 2:
  665. data->set.ftp_create_missing_dirs = 2;
  666. break;
  667. default:
  668. /* reserve other values for future use */
  669. result = CURLE_UNKNOWN_OPTION;
  670. break;
  671. }
  672. break;
  673. case CURLOPT_SERVER_RESPONSE_TIMEOUT:
  674. /*
  675. * Option that specifies how quickly an server response must be obtained
  676. * before it is considered failure. For pingpong protocols.
  677. */
  678. data->set.server_response_timeout = va_arg( param , long ) * 1000;
  679. break;
  680. case CURLOPT_TFTP_BLKSIZE:
  681. /*
  682. * TFTP option that specifies the block size to use for data transmission
  683. */
  684. data->set.tftp_blksize = va_arg(param, long);
  685. break;
  686. case CURLOPT_DIRLISTONLY:
  687. /*
  688. * An option that changes the command to one that asks for a list
  689. * only, no file info details.
  690. */
  691. data->set.ftp_list_only = (0 != va_arg(param, long))?TRUE:FALSE;
  692. break;
  693. case CURLOPT_APPEND:
  694. /*
  695. * We want to upload and append to an existing file.
  696. */
  697. data->set.ftp_append = (0 != va_arg(param, long))?TRUE:FALSE;
  698. break;
  699. case CURLOPT_FTP_FILEMETHOD:
  700. /*
  701. * How do access files over FTP.
  702. */
  703. data->set.ftp_filemethod = (curl_ftpfile)va_arg(param, long);
  704. break;
  705. case CURLOPT_NETRC:
  706. /*
  707. * Parse the $HOME/.netrc file
  708. */
  709. data->set.use_netrc = (enum CURL_NETRC_OPTION)va_arg(param, long);
  710. break;
  711. case CURLOPT_NETRC_FILE:
  712. /*
  713. * Use this file instead of the $HOME/.netrc file
  714. */
  715. result = setstropt(&data->set.str[STRING_NETRC_FILE],
  716. va_arg(param, char *));
  717. break;
  718. case CURLOPT_TRANSFERTEXT:
  719. /*
  720. * This option was previously named 'FTPASCII'. Renamed to work with
  721. * more protocols than merely FTP.
  722. *
  723. * Transfer using ASCII (instead of BINARY).
  724. */
  725. data->set.prefer_ascii = (0 != va_arg(param, long))?TRUE:FALSE;
  726. break;
  727. case CURLOPT_TIMECONDITION:
  728. /*
  729. * Set HTTP time condition. This must be one of the defines in the
  730. * curl/curl.h header file.
  731. */
  732. data->set.timecondition = (curl_TimeCond)va_arg(param, long);
  733. break;
  734. case CURLOPT_TIMEVALUE:
  735. /*
  736. * This is the value to compare with the remote document with the
  737. * method set with CURLOPT_TIMECONDITION
  738. */
  739. data->set.timevalue = (time_t)va_arg(param, long);
  740. break;
  741. case CURLOPT_SSLVERSION:
  742. /*
  743. * Set explicit SSL version to try to connect with, as some SSL
  744. * implementations are lame.
  745. */
  746. data->set.ssl.version = va_arg(param, long);
  747. break;
  748. #ifndef CURL_DISABLE_HTTP
  749. case CURLOPT_AUTOREFERER:
  750. /*
  751. * Switch on automatic referer that gets set if curl follows locations.
  752. */
  753. data->set.http_auto_referer = (0 != va_arg(param, long))?TRUE:FALSE;
  754. break;
  755. case CURLOPT_ACCEPT_ENCODING:
  756. /*
  757. * String to use at the value of Accept-Encoding header.
  758. *
  759. * If the encoding is set to "" we use an Accept-Encoding header that
  760. * encompasses all the encodings we support.
  761. * If the encoding is set to NULL we don't send an Accept-Encoding header
  762. * and ignore an received Content-Encoding header.
  763. *
  764. */
  765. argptr = va_arg(param, char *);
  766. result = setstropt(&data->set.str[STRING_ENCODING],
  767. (argptr && !*argptr)?
  768. (char *) ALL_CONTENT_ENCODINGS: argptr);
  769. break;
  770. case CURLOPT_TRANSFER_ENCODING:
  771. data->set.http_transfer_encoding = (0 != va_arg(param, long))?TRUE:FALSE;
  772. break;
  773. case CURLOPT_FOLLOWLOCATION:
  774. /*
  775. * Follow Location: header hints on a HTTP-server.
  776. */
  777. data->set.http_follow_location = (0 != va_arg(param, long))?TRUE:FALSE;
  778. break;
  779. case CURLOPT_UNRESTRICTED_AUTH:
  780. /*
  781. * Send authentication (user+password) when following locations, even when
  782. * hostname changed.
  783. */
  784. data->set.http_disable_hostname_check_before_authentication =
  785. (0 != va_arg(param, long))?TRUE:FALSE;
  786. break;
  787. case CURLOPT_MAXREDIRS:
  788. /*
  789. * The maximum amount of hops you allow curl to follow Location:
  790. * headers. This should mostly be used to detect never-ending loops.
  791. */
  792. data->set.maxredirs = va_arg(param, long);
  793. break;
  794. case CURLOPT_POSTREDIR:
  795. {
  796. /*
  797. * Set the behaviour of POST when redirecting
  798. * CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302
  799. * CURL_REDIR_POST_301 - POST is kept as POST after 301
  800. * CURL_REDIR_POST_302 - POST is kept as POST after 302
  801. * CURL_REDIR_POST_303 - POST is kept as POST after 303
  802. * CURL_REDIR_POST_ALL - POST is kept as POST after 301, 302 and 303
  803. * other - POST is kept as POST after 301 and 302
  804. */
  805. int postRedir = curlx_sltosi(va_arg(param, long));
  806. data->set.keep_post = postRedir & CURL_REDIR_POST_ALL;
  807. }
  808. break;
  809. case CURLOPT_POST:
  810. /* Does this option serve a purpose anymore? Yes it does, when
  811. CURLOPT_POSTFIELDS isn't used and the POST data is read off the
  812. callback! */
  813. if(va_arg(param, long)) {
  814. data->set.httpreq = HTTPREQ_POST;
  815. data->set.opt_no_body = FALSE; /* this is implied */
  816. }
  817. else
  818. data->set.httpreq = HTTPREQ_GET;
  819. break;
  820. case CURLOPT_COPYPOSTFIELDS:
  821. /*
  822. * A string with POST data. Makes curl HTTP POST. Even if it is NULL.
  823. * If needed, CURLOPT_POSTFIELDSIZE must have been set prior to
  824. * CURLOPT_COPYPOSTFIELDS and not altered later.
  825. */
  826. argptr = va_arg(param, char *);
  827. if(!argptr || data->set.postfieldsize == -1)
  828. result = setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr);
  829. else {
  830. /*
  831. * Check that requested length does not overflow the size_t type.
  832. */
  833. if((data->set.postfieldsize < 0) ||
  834. ((sizeof(curl_off_t) != sizeof(size_t)) &&
  835. (data->set.postfieldsize > (curl_off_t)((size_t)-1))))
  836. result = CURLE_OUT_OF_MEMORY;
  837. else {
  838. char * p;
  839. (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
  840. /* Allocate even when size == 0. This satisfies the need of possible
  841. later address compare to detect the COPYPOSTFIELDS mode, and
  842. to mark that postfields is used rather than read function or
  843. form data.
  844. */
  845. p = malloc((size_t)(data->set.postfieldsize?
  846. data->set.postfieldsize:1));
  847. if(!p)
  848. result = CURLE_OUT_OF_MEMORY;
  849. else {
  850. if(data->set.postfieldsize)
  851. memcpy(p, argptr, (size_t)data->set.postfieldsize);
  852. data->set.str[STRING_COPYPOSTFIELDS] = p;
  853. }
  854. }
  855. }
  856. data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS];
  857. data->set.httpreq = HTTPREQ_POST;
  858. break;
  859. case CURLOPT_POSTFIELDS:
  860. /*
  861. * Like above, but use static data instead of copying it.
  862. */
  863. data->set.postfields = va_arg(param, void *);
  864. /* Release old copied data. */
  865. (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
  866. data->set.httpreq = HTTPREQ_POST;
  867. break;
  868. case CURLOPT_POSTFIELDSIZE:
  869. /*
  870. * The size of the POSTFIELD data to prevent libcurl to do strlen() to
  871. * figure it out. Enables binary posts.
  872. */
  873. bigsize = va_arg(param, long);
  874. if(data->set.postfieldsize < bigsize &&
  875. data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
  876. /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
  877. (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
  878. data->set.postfields = NULL;
  879. }
  880. data->set.postfieldsize = bigsize;
  881. break;
  882. case CURLOPT_POSTFIELDSIZE_LARGE:
  883. /*
  884. * The size of the POSTFIELD data to prevent libcurl to do strlen() to
  885. * figure it out. Enables binary posts.
  886. */
  887. bigsize = va_arg(param, curl_off_t);
  888. if(data->set.postfieldsize < bigsize &&
  889. data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
  890. /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
  891. (void) setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
  892. data->set.postfields = NULL;
  893. }
  894. data->set.postfieldsize = bigsize;
  895. break;
  896. case CURLOPT_HTTPPOST:
  897. /*
  898. * Set to make us do HTTP POST
  899. */
  900. data->set.httppost = va_arg(param, struct curl_httppost *);
  901. data->set.httpreq = HTTPREQ_POST_FORM;
  902. data->set.opt_no_body = FALSE; /* this is implied */
  903. break;
  904. case CURLOPT_REFERER:
  905. /*
  906. * String to set in the HTTP Referer: field.
  907. */
  908. if(data->change.referer_alloc) {
  909. Curl_safefree(data->change.referer);
  910. data->change.referer_alloc = FALSE;
  911. }
  912. result = setstropt(&data->set.str[STRING_SET_REFERER],
  913. va_arg(param, char *));
  914. data->change.referer = data->set.str[STRING_SET_REFERER];
  915. break;
  916. case CURLOPT_USERAGENT:
  917. /*
  918. * String to use in the HTTP User-Agent field
  919. */
  920. result = setstropt(&data->set.str[STRING_USERAGENT],
  921. va_arg(param, char *));
  922. break;
  923. case CURLOPT_HTTPHEADER:
  924. /*
  925. * Set a list with HTTP headers to use (or replace internals with)
  926. */
  927. data->set.headers = va_arg(param, struct curl_slist *);
  928. break;
  929. case CURLOPT_HTTP200ALIASES:
  930. /*
  931. * Set a list of aliases for HTTP 200 in response header
  932. */
  933. data->set.http200aliases = va_arg(param, struct curl_slist *);
  934. break;
  935. #if !defined(CURL_DISABLE_COOKIES)
  936. case CURLOPT_COOKIE:
  937. /*
  938. * Cookie string to send to the remote server in the request.
  939. */
  940. result = setstropt(&data->set.str[STRING_COOKIE],
  941. va_arg(param, char *));
  942. break;
  943. case CURLOPT_COOKIEFILE:
  944. /*
  945. * Set cookie file to read and parse. Can be used multiple times.
  946. */
  947. argptr = (char *)va_arg(param, void *);
  948. if(argptr) {
  949. struct curl_slist *cl;
  950. /* append the cookie file name to the list of file names, and deal with
  951. them later */
  952. cl = curl_slist_append(data->change.cookielist, argptr);
  953. if(!cl) {
  954. curl_slist_free_all(data->change.cookielist);
  955. data->change.cookielist = NULL;
  956. return CURLE_OUT_OF_MEMORY;
  957. }
  958. data->change.cookielist = cl; /* store the list for later use */
  959. }
  960. break;
  961. case CURLOPT_COOKIEJAR:
  962. /*
  963. * Set cookie file name to dump all cookies to when we're done.
  964. */
  965. result = setstropt(&data->set.str[STRING_COOKIEJAR],
  966. va_arg(param, char *));
  967. /*
  968. * Activate the cookie parser. This may or may not already
  969. * have been made.
  970. */
  971. data->cookies = Curl_cookie_init(data, NULL, data->cookies,
  972. data->set.cookiesession);
  973. break;
  974. case CURLOPT_COOKIESESSION:
  975. /*
  976. * Set this option to TRUE to start a new "cookie session". It will
  977. * prevent the forthcoming read-cookies-from-file actions to accept
  978. * cookies that are marked as being session cookies, as they belong to a
  979. * previous session.
  980. *
  981. * In the original Netscape cookie spec, "session cookies" are cookies
  982. * with no expire date set. RFC2109 describes the same action if no
  983. * 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds
  984. * a 'Discard' action that can enforce the discard even for cookies that
  985. * have a Max-Age.
  986. *
  987. * We run mostly with the original cookie spec, as hardly anyone implements
  988. * anything else.
  989. */
  990. data->set.cookiesession = (0 != va_arg(param, long))?TRUE:FALSE;
  991. break;
  992. case CURLOPT_COOKIELIST:
  993. argptr = va_arg(param, char *);
  994. if(argptr == NULL)
  995. break;
  996. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  997. if(Curl_raw_equal(argptr, "ALL")) {
  998. /* clear all cookies */
  999. Curl_cookie_clearall(data->cookies);
  1000. }
  1001. else if(Curl_raw_equal(argptr, "SESS")) {
  1002. /* clear session cookies */
  1003. Curl_cookie_clearsess(data->cookies);
  1004. }
  1005. else if(Curl_raw_equal(argptr, "FLUSH")) {
  1006. /* flush cookies to file */
  1007. Curl_flush_cookies(data, 0);
  1008. }
  1009. else {
  1010. if(!data->cookies)
  1011. /* if cookie engine was not running, activate it */
  1012. data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE);
  1013. argptr = strdup(argptr);
  1014. if(!argptr) {
  1015. result = CURLE_OUT_OF_MEMORY;
  1016. }
  1017. else {
  1018. if(checkprefix("Set-Cookie:", argptr))
  1019. /* HTTP Header format line */
  1020. Curl_cookie_add(data, data->cookies, TRUE, argptr + 11, NULL, NULL);
  1021. else
  1022. /* Netscape format line */
  1023. Curl_cookie_add(data, data->cookies, FALSE, argptr, NULL, NULL);
  1024. free(argptr);
  1025. }
  1026. }
  1027. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  1028. break;
  1029. #endif /* CURL_DISABLE_COOKIES */
  1030. case CURLOPT_HTTPGET:
  1031. /*
  1032. * Set to force us do HTTP GET
  1033. */
  1034. if(va_arg(param, long)) {
  1035. data->set.httpreq = HTTPREQ_GET;
  1036. data->set.upload = FALSE; /* switch off upload */
  1037. data->set.opt_no_body = FALSE; /* this is implied */
  1038. }
  1039. break;
  1040. case CURLOPT_HTTP_VERSION:
  1041. /*
  1042. * This sets a requested HTTP version to be used. The value is one of
  1043. * the listed enums in curl/curl.h.
  1044. */
  1045. arg = va_arg(param, long);
  1046. #ifndef USE_NGHTTP2
  1047. if(arg == CURL_HTTP_VERSION_2_0)
  1048. return CURLE_UNSUPPORTED_PROTOCOL;
  1049. #endif
  1050. data->set.httpversion = arg;
  1051. break;
  1052. case CURLOPT_HTTPAUTH:
  1053. /*
  1054. * Set HTTP Authentication type BITMASK.
  1055. */
  1056. {
  1057. int bitcheck;
  1058. bool authbits;
  1059. unsigned long auth = va_arg(param, unsigned long);
  1060. if(auth == CURLAUTH_NONE) {
  1061. data->set.httpauth = auth;
  1062. break;
  1063. }
  1064. /* the DIGEST_IE bit is only used to set a special marker, for all the
  1065. rest we need to handle it as normal DIGEST */
  1066. data->state.authhost.iestyle = (auth & CURLAUTH_DIGEST_IE)?TRUE:FALSE;
  1067. if(auth & CURLAUTH_DIGEST_IE) {
  1068. auth |= CURLAUTH_DIGEST; /* set standard digest bit */
  1069. auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
  1070. }
  1071. /* switch off bits we can't support */
  1072. #ifndef USE_NTLM
  1073. auth &= ~CURLAUTH_NTLM; /* no NTLM support */
  1074. auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
  1075. #elif !defined(NTLM_WB_ENABLED)
  1076. auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
  1077. #endif
  1078. #ifndef USE_HTTP_NEGOTIATE
  1079. auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI or
  1080. WINDOWS_SSPI */
  1081. #endif
  1082. /* check if any auth bit lower than CURLAUTH_ONLY is still set */
  1083. bitcheck = 0;
  1084. authbits = FALSE;
  1085. while(bitcheck < 31) {
  1086. if(auth & (1UL << bitcheck++)) {
  1087. authbits = TRUE;
  1088. break;
  1089. }
  1090. }
  1091. if(!authbits)
  1092. return CURLE_NOT_BUILT_IN; /* no supported types left! */
  1093. data->set.httpauth = auth;
  1094. }
  1095. break;
  1096. case CURLOPT_EXPECT_100_TIMEOUT_MS:
  1097. /*
  1098. * Time to wait for a response to a HTTP request containing an
  1099. * Expect: 100-continue header before sending the data anyway.
  1100. */
  1101. data->set.expect_100_timeout = va_arg(param, long);
  1102. break;
  1103. #endif /* CURL_DISABLE_HTTP */
  1104. case CURLOPT_CUSTOMREQUEST:
  1105. /*
  1106. * Set a custom string to use as request
  1107. */
  1108. result = setstropt(&data->set.str[STRING_CUSTOMREQUEST],
  1109. va_arg(param, char *));
  1110. /* we don't set
  1111. data->set.httpreq = HTTPREQ_CUSTOM;
  1112. here, we continue as if we were using the already set type
  1113. and this just changes the actual request keyword */
  1114. break;
  1115. #ifndef CURL_DISABLE_PROXY
  1116. case CURLOPT_HTTPPROXYTUNNEL:
  1117. /*
  1118. * Tunnel operations through the proxy instead of normal proxy use
  1119. */
  1120. data->set.tunnel_thru_httpproxy = (0 != va_arg(param, long))?TRUE:FALSE;
  1121. break;
  1122. case CURLOPT_PROXYPORT:
  1123. /*
  1124. * Explicitly set HTTP proxy port number.
  1125. */
  1126. data->set.proxyport = va_arg(param, long);
  1127. break;
  1128. case CURLOPT_PROXYAUTH:
  1129. /*
  1130. * Set HTTP Authentication type BITMASK.
  1131. */
  1132. {
  1133. int bitcheck;
  1134. bool authbits;
  1135. unsigned long auth = va_arg(param, unsigned long);
  1136. if(auth == CURLAUTH_NONE) {
  1137. data->set.proxyauth = auth;
  1138. break;
  1139. }
  1140. /* the DIGEST_IE bit is only used to set a special marker, for all the
  1141. rest we need to handle it as normal DIGEST */
  1142. data->state.authproxy.iestyle = (auth & CURLAUTH_DIGEST_IE)?TRUE:FALSE;
  1143. if(auth & CURLAUTH_DIGEST_IE) {
  1144. auth |= CURLAUTH_DIGEST; /* set standard digest bit */
  1145. auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
  1146. }
  1147. /* switch off bits we can't support */
  1148. #ifndef USE_NTLM
  1149. auth &= ~CURLAUTH_NTLM; /* no NTLM support */
  1150. auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
  1151. #elif !defined(NTLM_WB_ENABLED)
  1152. auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
  1153. #endif
  1154. #ifndef USE_HTTP_NEGOTIATE
  1155. auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI or
  1156. WINDOWS_SSPI */
  1157. #endif
  1158. /* check if any auth bit lower than CURLAUTH_ONLY is still set */
  1159. bitcheck = 0;
  1160. authbits = FALSE;
  1161. while(bitcheck < 31) {
  1162. if(auth & (1UL << bitcheck++)) {
  1163. authbits = TRUE;
  1164. break;
  1165. }
  1166. }
  1167. if(!authbits)
  1168. return CURLE_NOT_BUILT_IN; /* no supported types left! */
  1169. data->set.proxyauth = auth;
  1170. }
  1171. break;
  1172. case CURLOPT_PROXY:
  1173. /*
  1174. * Set proxy server:port to use as HTTP proxy.
  1175. *
  1176. * If the proxy is set to "" we explicitly say that we don't want to use a
  1177. * proxy (even though there might be environment variables saying so).
  1178. *
  1179. * Setting it to NULL, means no proxy but allows the environment variables
  1180. * to decide for us.
  1181. */
  1182. result = setstropt(&data->set.str[STRING_PROXY],
  1183. va_arg(param, char *));
  1184. break;
  1185. case CURLOPT_PROXYTYPE:
  1186. /*
  1187. * Set proxy type. HTTP/HTTP_1_0/SOCKS4/SOCKS4a/SOCKS5/SOCKS5_HOSTNAME
  1188. */
  1189. data->set.proxytype = (curl_proxytype)va_arg(param, long);
  1190. break;
  1191. case CURLOPT_PROXY_TRANSFER_MODE:
  1192. /*
  1193. * set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy
  1194. */
  1195. switch (va_arg(param, long)) {
  1196. case 0:
  1197. data->set.proxy_transfer_mode = FALSE;
  1198. break;
  1199. case 1:
  1200. data->set.proxy_transfer_mode = TRUE;
  1201. break;
  1202. default:
  1203. /* reserve other values for future use */
  1204. result = CURLE_UNKNOWN_OPTION;
  1205. break;
  1206. }
  1207. break;
  1208. #endif /* CURL_DISABLE_PROXY */
  1209. #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
  1210. case CURLOPT_SOCKS5_GSSAPI_SERVICE:
  1211. /*
  1212. * Set gssapi service name
  1213. */
  1214. result = setstropt(&data->set.str[STRING_SOCKS5_GSSAPI_SERVICE],
  1215. va_arg(param, char *));
  1216. break;
  1217. case CURLOPT_SOCKS5_GSSAPI_NEC:
  1218. /*
  1219. * set flag for nec socks5 support
  1220. */
  1221. data->set.socks5_gssapi_nec = (0 != va_arg(param, long))?TRUE:FALSE;
  1222. break;
  1223. #endif
  1224. case CURLOPT_WRITEHEADER:
  1225. /*
  1226. * Custom pointer to pass the header write callback function
  1227. */
  1228. data->set.writeheader = (void *)va_arg(param, void *);
  1229. break;
  1230. case CURLOPT_ERRORBUFFER:
  1231. /*
  1232. * Error buffer provided by the caller to get the human readable
  1233. * error string in.
  1234. */
  1235. data->set.errorbuffer = va_arg(param, char *);
  1236. break;
  1237. case CURLOPT_FILE:
  1238. /*
  1239. * FILE pointer to write to. Or possibly
  1240. * used as argument to the write callback.
  1241. */
  1242. data->set.out = va_arg(param, void *);
  1243. break;
  1244. case CURLOPT_FTPPORT:
  1245. /*
  1246. * Use FTP PORT, this also specifies which IP address to use
  1247. */
  1248. result = setstropt(&data->set.str[STRING_FTPPORT],
  1249. va_arg(param, char *));
  1250. data->set.ftp_use_port = (NULL != data->set.str[STRING_FTPPORT]) ?
  1251. TRUE:FALSE;
  1252. break;
  1253. case CURLOPT_FTP_USE_EPRT:
  1254. data->set.ftp_use_eprt = (0 != va_arg(param, long))?TRUE:FALSE;
  1255. break;
  1256. case CURLOPT_FTP_USE_EPSV:
  1257. data->set.ftp_use_epsv = (0 != va_arg(param, long))?TRUE:FALSE;
  1258. break;
  1259. case CURLOPT_FTP_USE_PRET:
  1260. data->set.ftp_use_pret = (0 != va_arg(param, long))?TRUE:FALSE;
  1261. break;
  1262. case CURLOPT_FTP_SSL_CCC:
  1263. data->set.ftp_ccc = (curl_ftpccc)va_arg(param, long);
  1264. break;
  1265. case CURLOPT_FTP_SKIP_PASV_IP:
  1266. /*
  1267. * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the
  1268. * bypass of the IP address in PASV responses.
  1269. */
  1270. data->set.ftp_skip_ip = (0 != va_arg(param, long))?TRUE:FALSE;
  1271. break;
  1272. case CURLOPT_INFILE:
  1273. /*
  1274. * FILE pointer to read the file to be uploaded from. Or possibly
  1275. * used as argument to the read callback.
  1276. */
  1277. data->set.in = va_arg(param, void *);
  1278. break;
  1279. case CURLOPT_INFILESIZE:
  1280. /*
  1281. * If known, this should inform curl about the file size of the
  1282. * to-be-uploaded file.
  1283. */
  1284. data->set.infilesize = va_arg(param, long);
  1285. break;
  1286. case CURLOPT_INFILESIZE_LARGE:
  1287. /*
  1288. * If known, this should inform curl about the file size of the
  1289. * to-be-uploaded file.
  1290. */
  1291. data->set.infilesize = va_arg(param, curl_off_t);
  1292. break;
  1293. case CURLOPT_LOW_SPEED_LIMIT:
  1294. /*
  1295. * The low speed limit that if transfers are below this for
  1296. * CURLOPT_LOW_SPEED_TIME, the transfer is aborted.
  1297. */
  1298. data->set.low_speed_limit=va_arg(param, long);
  1299. break;
  1300. case CURLOPT_MAX_SEND_SPEED_LARGE:
  1301. /*
  1302. * When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE
  1303. * bytes per second the transfer is throttled..
  1304. */
  1305. data->set.max_send_speed=va_arg(param, curl_off_t);
  1306. break;
  1307. case CURLOPT_MAX_RECV_SPEED_LARGE:
  1308. /*
  1309. * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per
  1310. * second the transfer is throttled..
  1311. */
  1312. data->set.max_recv_speed=va_arg(param, curl_off_t);
  1313. break;
  1314. case CURLOPT_LOW_SPEED_TIME:
  1315. /*
  1316. * The low speed time that if transfers are below the set
  1317. * CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted.
  1318. */
  1319. data->set.low_speed_time=va_arg(param, long);
  1320. break;
  1321. case CURLOPT_URL:
  1322. /*
  1323. * The URL to fetch.
  1324. */
  1325. if(data->change.url_alloc) {
  1326. /* the already set URL is allocated, free it first! */
  1327. Curl_safefree(data->change.url);
  1328. data->change.url_alloc = FALSE;
  1329. }
  1330. result = setstropt(&data->set.str[STRING_SET_URL],
  1331. va_arg(param, char *));
  1332. data->change.url = data->set.str[STRING_SET_URL];
  1333. break;
  1334. case CURLOPT_PORT:
  1335. /*
  1336. * The port number to use when getting the URL
  1337. */
  1338. data->set.use_port = va_arg(param, long);
  1339. break;
  1340. case CURLOPT_TIMEOUT:
  1341. /*
  1342. * The maximum time you allow curl to use for a single transfer
  1343. * operation.
  1344. */
  1345. data->set.timeout = va_arg(param, long) * 1000L;
  1346. break;
  1347. case CURLOPT_TIMEOUT_MS:
  1348. data->set.timeout = va_arg(param, long);
  1349. break;
  1350. case CURLOPT_CONNECTTIMEOUT:
  1351. /*
  1352. * The maximum time you allow curl to use to connect.
  1353. */
  1354. data->set.connecttimeout = va_arg(param, long) * 1000L;
  1355. break;
  1356. case CURLOPT_CONNECTTIMEOUT_MS:
  1357. data->set.connecttimeout = va_arg(param, long);
  1358. break;
  1359. case CURLOPT_ACCEPTTIMEOUT_MS:
  1360. /*
  1361. * The maximum time you allow curl to wait for server connect
  1362. */
  1363. data->set.accepttimeout = va_arg(param, long);
  1364. break;
  1365. case CURLOPT_USERPWD:
  1366. /*
  1367. * user:password to use in the operation
  1368. */
  1369. result = setstropt_userpwd(va_arg(param, char *),
  1370. &data->set.str[STRING_USERNAME],
  1371. &data->set.str[STRING_PASSWORD]);
  1372. break;
  1373. case CURLOPT_USERNAME:
  1374. /*
  1375. * authentication user name to use in the operation
  1376. */
  1377. result = setstropt(&data->set.str[STRING_USERNAME],
  1378. va_arg(param, char *));
  1379. break;
  1380. case CURLOPT_PASSWORD:
  1381. /*
  1382. * authentication password to use in the operation
  1383. */
  1384. result = setstropt(&data->set.str[STRING_PASSWORD],
  1385. va_arg(param, char *));
  1386. break;
  1387. case CURLOPT_LOGIN_OPTIONS:
  1388. /*
  1389. * authentication options to use in the operation
  1390. */
  1391. result = setstropt(&data->set.str[STRING_OPTIONS],
  1392. va_arg(param, char *));
  1393. break;
  1394. case CURLOPT_XOAUTH2_BEARER:
  1395. /*
  1396. * XOAUTH2 bearer token to use in the operation
  1397. */
  1398. result = setstropt(&data->set.str[STRING_BEARER],
  1399. va_arg(param, char *));
  1400. break;
  1401. case CURLOPT_POSTQUOTE:
  1402. /*
  1403. * List of RAW FTP commands to use after a transfer
  1404. */
  1405. data->set.postquote = va_arg(param, struct curl_slist *);
  1406. break;
  1407. case CURLOPT_PREQUOTE:
  1408. /*
  1409. * List of RAW FTP commands to use prior to RETR (Wesley Laxton)
  1410. */
  1411. data->set.prequote = va_arg(param, struct curl_slist *);
  1412. break;
  1413. case CURLOPT_QUOTE:
  1414. /*
  1415. * List of RAW FTP commands to use before a transfer
  1416. */
  1417. data->set.quote = va_arg(param, struct curl_slist *);
  1418. break;
  1419. case CURLOPT_RESOLVE:
  1420. /*
  1421. * List of NAME:[address] names to populate the DNS cache with
  1422. * Prefix the NAME with dash (-) to _remove_ the name from the cache.
  1423. *
  1424. * Names added with this API will remain in the cache until explicitly
  1425. * removed or the handle is cleaned up.
  1426. *
  1427. * This API can remove any name from the DNS cache, but only entries
  1428. * that aren't actually in use right now will be pruned immediately.
  1429. */
  1430. data->set.resolve = va_arg(param, struct curl_slist *);
  1431. data->change.resolve = data->set.resolve;
  1432. break;
  1433. case CURLOPT_PROGRESSFUNCTION:
  1434. /*
  1435. * Progress callback function
  1436. */
  1437. data->set.fprogress = va_arg(param, curl_progress_callback);
  1438. if(data->set.fprogress)
  1439. data->progress.callback = TRUE; /* no longer internal */
  1440. else
  1441. data->progress.callback = FALSE; /* NULL enforces internal */
  1442. break;
  1443. case CURLOPT_XFERINFOFUNCTION:
  1444. /*
  1445. * Transfer info callback function
  1446. */
  1447. data->set.fxferinfo = va_arg(param, curl_xferinfo_callback);
  1448. if(data->set.fxferinfo)
  1449. data->progress.callback = TRUE; /* no longer internal */
  1450. else
  1451. data->progress.callback = FALSE; /* NULL enforces internal */
  1452. break;
  1453. case CURLOPT_PROGRESSDATA:
  1454. /*
  1455. * Custom client data to pass to the progress callback
  1456. */
  1457. data->set.progress_client = va_arg(param, void *);
  1458. break;
  1459. #ifndef CURL_DISABLE_PROXY
  1460. case CURLOPT_PROXYUSERPWD:
  1461. /*
  1462. * user:password needed to use the proxy
  1463. */
  1464. result = setstropt_userpwd(va_arg(param, char *),
  1465. &data->set.str[STRING_PROXYUSERNAME],
  1466. &data->set.str[STRING_PROXYPASSWORD]);
  1467. break;
  1468. case CURLOPT_PROXYUSERNAME:
  1469. /*
  1470. * authentication user name to use in the operation
  1471. */
  1472. result = setstropt(&data->set.str[STRING_PROXYUSERNAME],
  1473. va_arg(param, char *));
  1474. break;
  1475. case CURLOPT_PROXYPASSWORD:
  1476. /*
  1477. * authentication password to use in the operation
  1478. */
  1479. result = setstropt(&data->set.str[STRING_PROXYPASSWORD],
  1480. va_arg(param, char *));
  1481. break;
  1482. case CURLOPT_NOPROXY:
  1483. /*
  1484. * proxy exception list
  1485. */
  1486. result = setstropt(&data->set.str[STRING_NOPROXY],
  1487. va_arg(param, char *));
  1488. break;
  1489. #endif
  1490. case CURLOPT_RANGE:
  1491. /*
  1492. * What range of the file you want to transfer
  1493. */
  1494. result = setstropt(&data->set.str[STRING_SET_RANGE],
  1495. va_arg(param, char *));
  1496. break;
  1497. case CURLOPT_RESUME_FROM:
  1498. /*
  1499. * Resume transfer at the give file position
  1500. */
  1501. data->set.set_resume_from = va_arg(param, long);
  1502. break;
  1503. case CURLOPT_RESUME_FROM_LARGE:
  1504. /*
  1505. * Resume transfer at the give file position
  1506. */
  1507. data->set.set_resume_from = va_arg(param, curl_off_t);
  1508. break;
  1509. case CURLOPT_DEBUGFUNCTION:
  1510. /*
  1511. * stderr write callback.
  1512. */
  1513. data->set.fdebug = va_arg(param, curl_debug_callback);
  1514. /*
  1515. * if the callback provided is NULL, it'll use the default callback
  1516. */
  1517. break;
  1518. case CURLOPT_DEBUGDATA:
  1519. /*
  1520. * Set to a void * that should receive all error writes. This
  1521. * defaults to CURLOPT_STDERR for normal operations.
  1522. */
  1523. data->set.debugdata = va_arg(param, void *);
  1524. break;
  1525. case CURLOPT_STDERR:
  1526. /*
  1527. * Set to a FILE * that should receive all error writes. This
  1528. * defaults to stderr for normal operations.
  1529. */
  1530. data->set.err = va_arg(param, FILE *);
  1531. if(!data->set.err)
  1532. data->set.err = stderr;
  1533. break;
  1534. case CURLOPT_HEADERFUNCTION:
  1535. /*
  1536. * Set header write callback
  1537. */
  1538. data->set.fwrite_header = va_arg(param, curl_write_callback);
  1539. break;
  1540. case CURLOPT_WRITEFUNCTION:
  1541. /*
  1542. * Set data write callback
  1543. */
  1544. data->set.fwrite_func = va_arg(param, curl_write_callback);
  1545. if(!data->set.fwrite_func) {
  1546. data->set.is_fwrite_set = 0;
  1547. /* When set to NULL, reset to our internal default function */
  1548. data->set.fwrite_func = (curl_write_callback)fwrite;
  1549. }
  1550. else
  1551. data->set.is_fwrite_set = 1;
  1552. break;
  1553. case CURLOPT_READFUNCTION:
  1554. /*
  1555. * Read data callback
  1556. */
  1557. data->set.fread_func = va_arg(param, curl_read_callback);
  1558. if(!data->set.fread_func) {
  1559. data->set.is_fread_set = 0;
  1560. /* When set to NULL, reset to our internal default function */
  1561. data->set.fread_func = (curl_read_callback)fread;
  1562. }
  1563. else
  1564. data->set.is_fread_set = 1;
  1565. break;
  1566. case CURLOPT_SEEKFUNCTION:
  1567. /*
  1568. * Seek callback. Might be NULL.
  1569. */
  1570. data->set.seek_func = va_arg(param, curl_seek_callback);
  1571. break;
  1572. case CURLOPT_SEEKDATA:
  1573. /*
  1574. * Seek control callback. Might be NULL.
  1575. */
  1576. data->set.seek_client = va_arg(param, void *);
  1577. break;
  1578. case CURLOPT_CONV_FROM_NETWORK_FUNCTION:
  1579. /*
  1580. * "Convert from network encoding" callback
  1581. */
  1582. data->set.convfromnetwork = va_arg(param, curl_conv_callback);
  1583. break;
  1584. case CURLOPT_CONV_TO_NETWORK_FUNCTION:
  1585. /*
  1586. * "Convert to network encoding" callback
  1587. */
  1588. data->set.convtonetwork = va_arg(param, curl_conv_callback);
  1589. break;
  1590. case CURLOPT_CONV_FROM_UTF8_FUNCTION:
  1591. /*
  1592. * "Convert from UTF-8 encoding" callback
  1593. */
  1594. data->set.convfromutf8 = va_arg(param, curl_conv_callback);
  1595. break;
  1596. case CURLOPT_IOCTLFUNCTION:
  1597. /*
  1598. * I/O control callback. Might be NULL.
  1599. */
  1600. data->set.ioctl_func = va_arg(param, curl_ioctl_callback);
  1601. break;
  1602. case CURLOPT_IOCTLDATA:
  1603. /*
  1604. * I/O control data pointer. Might be NULL.
  1605. */
  1606. data->set.ioctl_client = va_arg(param, void *);
  1607. break;
  1608. case CURLOPT_SSLCERT:
  1609. /*
  1610. * String that holds file name of the SSL certificate to use
  1611. */
  1612. result = setstropt(&data->set.str[STRING_CERT],
  1613. va_arg(param, char *));
  1614. break;
  1615. case CURLOPT_SSLCERTTYPE:
  1616. /*
  1617. * String that holds file type of the SSL certificate to use
  1618. */
  1619. result = setstropt(&data->set.str[STRING_CERT_TYPE],
  1620. va_arg(param, char *));
  1621. break;
  1622. case CURLOPT_SSLKEY:
  1623. /*
  1624. * String that holds file name of the SSL key to use
  1625. */
  1626. result = setstropt(&data->set.str[STRING_KEY],
  1627. va_arg(param, char *));
  1628. break;
  1629. case CURLOPT_SSLKEYTYPE:
  1630. /*
  1631. * String that holds file type of the SSL key to use
  1632. */
  1633. result = setstropt(&data->set.str[STRING_KEY_TYPE],
  1634. va_arg(param, char *));
  1635. break;
  1636. case CURLOPT_KEYPASSWD:
  1637. /*
  1638. * String that holds the SSL or SSH private key password.
  1639. */
  1640. result = setstropt(&data->set.str[STRING_KEY_PASSWD],
  1641. va_arg(param, char *));
  1642. break;
  1643. case CURLOPT_SSLENGINE:
  1644. /*
  1645. * String that holds the SSL crypto engine.
  1646. */
  1647. argptr = va_arg(param, char *);
  1648. if(argptr && argptr[0])
  1649. result = Curl_ssl_set_engine(data, argptr);
  1650. break;
  1651. case CURLOPT_SSLENGINE_DEFAULT:
  1652. /*
  1653. * flag to set engine as default.
  1654. */
  1655. result = Curl_ssl_set_engine_default(data);
  1656. break;
  1657. case CURLOPT_CRLF:
  1658. /*
  1659. * Kludgy option to enable CRLF conversions. Subject for removal.
  1660. */
  1661. data->set.crlf = (0 != va_arg(param, long))?TRUE:FALSE;
  1662. break;
  1663. case CURLOPT_INTERFACE:
  1664. /*
  1665. * Set what interface or address/hostname to bind the socket to when
  1666. * performing an operation and thus what from-IP your connection will use.
  1667. */
  1668. result = setstropt(&data->set.str[STRING_DEVICE],
  1669. va_arg(param, char *));
  1670. break;
  1671. case CURLOPT_LOCALPORT:
  1672. /*
  1673. * Set what local port to bind the socket to when performing an operation.
  1674. */
  1675. data->set.localport = curlx_sltous(va_arg(param, long));
  1676. break;
  1677. case CURLOPT_LOCALPORTRANGE:
  1678. /*
  1679. * Set number of local ports to try, starting with CURLOPT_LOCALPORT.
  1680. */
  1681. data->set.localportrange = curlx_sltosi(va_arg(param, long));
  1682. break;
  1683. case CURLOPT_KRBLEVEL:
  1684. /*
  1685. * A string that defines the kerberos security level.
  1686. */
  1687. result = setstropt(&data->set.str[STRING_KRB_LEVEL],
  1688. va_arg(param, char *));
  1689. data->set.krb = (NULL != data->set.str[STRING_KRB_LEVEL])?TRUE:FALSE;
  1690. break;
  1691. case CURLOPT_GSSAPI_DELEGATION:
  1692. /*
  1693. * GSSAPI credential delegation
  1694. */
  1695. data->set.gssapi_delegation = va_arg(param, long);
  1696. break;
  1697. case CURLOPT_SSL_VERIFYPEER:
  1698. /*
  1699. * Enable peer SSL verifying.
  1700. */
  1701. data->set.ssl.verifypeer = (0 != va_arg(param, long))?TRUE:FALSE;
  1702. break;
  1703. case CURLOPT_SSL_VERIFYHOST:
  1704. /*
  1705. * Enable verification of the host name in the peer certificate
  1706. */
  1707. arg = va_arg(param, long);
  1708. /* Obviously people are not reading documentation and too many thought
  1709. this argument took a boolean when it wasn't and misused it. We thus ban
  1710. 1 as a sensible input and we warn about its use. Then we only have the
  1711. 2 action internally stored as TRUE. */
  1712. if(1 == arg) {
  1713. failf(data, "CURLOPT_SSL_VERIFYHOST no longer supports 1 as value!");
  1714. return CURLE_BAD_FUNCTION_ARGUMENT;
  1715. }
  1716. data->set.ssl.verifyhost = (0 != arg)?TRUE:FALSE;
  1717. break;
  1718. #ifdef USE_SSLEAY
  1719. /* since these two options are only possible to use on an OpenSSL-
  1720. powered libcurl we #ifdef them on this condition so that libcurls
  1721. built against other SSL libs will return a proper error when trying
  1722. to set this option! */
  1723. case CURLOPT_SSL_CTX_FUNCTION:
  1724. /*
  1725. * Set a SSL_CTX callback
  1726. */
  1727. data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback);
  1728. break;
  1729. case CURLOPT_SSL_CTX_DATA:
  1730. /*
  1731. * Set a SSL_CTX callback parameter pointer
  1732. */
  1733. data->set.ssl.fsslctxp = va_arg(param, void *);
  1734. break;
  1735. #endif
  1736. #if defined(USE_SSLEAY) || defined(USE_QSOSSL) || defined(USE_GSKIT) || \
  1737. defined(USE_NSS)
  1738. case CURLOPT_CERTINFO:
  1739. data->set.ssl.certinfo = (0 != va_arg(param, long))?TRUE:FALSE;
  1740. break;
  1741. #endif
  1742. case CURLOPT_CAINFO:
  1743. /*
  1744. * Set CA info for SSL connection. Specify file name of the CA certificate
  1745. */
  1746. result = setstropt(&data->set.str[STRING_SSL_CAFILE],
  1747. va_arg(param, char *));
  1748. break;
  1749. case CURLOPT_CAPATH:
  1750. /*
  1751. * Set CA path info for SSL connection. Specify directory name of the CA
  1752. * certificates which have been prepared using openssl c_rehash utility.
  1753. */
  1754. /* This does not work on windows. */
  1755. result = setstropt(&data->set.str[STRING_SSL_CAPATH],
  1756. va_arg(param, char *));
  1757. break;
  1758. case CURLOPT_CRLFILE:
  1759. /*
  1760. * Set CRL file info for SSL connection. Specify file name of the CRL
  1761. * to check certificates revocation
  1762. */
  1763. result = setstropt(&data->set.str[STRING_SSL_CRLFILE],
  1764. va_arg(param, char *));
  1765. break;
  1766. case CURLOPT_ISSUERCERT:
  1767. /*
  1768. * Set Issuer certificate file
  1769. * to check certificates issuer
  1770. */
  1771. result = setstropt(&data->set.str[STRING_SSL_ISSUERCERT],
  1772. va_arg(param, char *));
  1773. break;
  1774. case CURLOPT_TELNETOPTIONS:
  1775. /*
  1776. * Set a linked list of telnet options
  1777. */
  1778. data->set.telnet_options = va_arg(param, struct curl_slist *);
  1779. break;
  1780. case CURLOPT_BUFFERSIZE:
  1781. /*
  1782. * The application kindly asks for a differently sized receive buffer.
  1783. * If it seems reasonable, we'll use it.
  1784. */
  1785. data->set.buffer_size = va_arg(param, long);
  1786. if((data->set.buffer_size> (BUFSIZE -1 )) ||
  1787. (data->set.buffer_size < 1))
  1788. data->set.buffer_size = 0; /* huge internal default */
  1789. break;
  1790. case CURLOPT_NOSIGNAL:
  1791. /*
  1792. * The application asks not to set any signal() or alarm() handlers,
  1793. * even when using a timeout.
  1794. */
  1795. data->set.no_signal = (0 != va_arg(param, long))?TRUE:FALSE;
  1796. break;
  1797. case CURLOPT_SHARE:
  1798. {
  1799. struct Curl_share *set;
  1800. set = va_arg(param, struct Curl_share *);
  1801. /* disconnect from old share, if any */
  1802. if(data->share) {
  1803. Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
  1804. if(data->dns.hostcachetype == HCACHE_SHARED) {
  1805. data->dns.hostcache = NULL;
  1806. data->dns.hostcachetype = HCACHE_NONE;
  1807. }
  1808. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
  1809. if(data->share->cookies == data->cookies)
  1810. data->cookies = NULL;
  1811. #endif
  1812. if(data->share->sslsession == data->state.session)
  1813. data->state.session = NULL;
  1814. data->share->dirty--;
  1815. Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
  1816. data->share = NULL;
  1817. }
  1818. /* use new share if it set */
  1819. data->share = set;
  1820. if(data->share) {
  1821. Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
  1822. data->share->dirty++;
  1823. if(data->share->hostcache) {
  1824. /* use shared host cache */
  1825. data->dns.hostcache = data->share->hostcache;
  1826. data->dns.hostcachetype = HCACHE_SHARED;
  1827. }
  1828. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
  1829. if(data->share->cookies) {
  1830. /* use shared cookie list, first free own one if any */
  1831. if(data->cookies)
  1832. Curl_cookie_cleanup(data->cookies);
  1833. /* enable cookies since we now use a share that uses cookies! */
  1834. data->cookies = data->share->cookies;
  1835. }
  1836. #endif /* CURL_DISABLE_HTTP */
  1837. if(data->share->sslsession) {
  1838. data->set.ssl.max_ssl_sessions = data->share->max_ssl_sessions;
  1839. data->state.session = data->share->sslsession;
  1840. }
  1841. Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
  1842. }
  1843. /* check for host cache not needed,
  1844. * it will be done by curl_easy_perform */
  1845. }
  1846. break;
  1847. case CURLOPT_PRIVATE:
  1848. /*
  1849. * Set private data pointer.
  1850. */
  1851. data->set.private_data = va_arg(param, void *);
  1852. break;
  1853. case CURLOPT_MAXFILESIZE:
  1854. /*
  1855. * Set the maximum size of a file to download.
  1856. */
  1857. data->set.max_filesize = va_arg(param, long);
  1858. break;
  1859. #ifdef USE_SSL
  1860. case CURLOPT_USE_SSL:
  1861. /*
  1862. * Make transfers attempt to use SSL/TLS.
  1863. */
  1864. data->set.use_ssl = (curl_usessl)va_arg(param, long);
  1865. break;
  1866. case CURLOPT_SSL_OPTIONS:
  1867. arg = va_arg(param, long);
  1868. data->set.ssl_enable_beast = arg&CURLSSLOPT_ALLOW_BEAST?TRUE:FALSE;
  1869. break;
  1870. #endif
  1871. case CURLOPT_FTPSSLAUTH:
  1872. /*
  1873. * Set a specific auth for FTP-SSL transfers.
  1874. */
  1875. data->set.ftpsslauth = (curl_ftpauth)va_arg(param, long);
  1876. break;
  1877. case CURLOPT_IPRESOLVE:
  1878. data->set.ipver = va_arg(param, long);
  1879. break;
  1880. case CURLOPT_MAXFILESIZE_LARGE:
  1881. /*
  1882. * Set the maximum size of a file to download.
  1883. */
  1884. data->set.max_filesize = va_arg(param, curl_off_t);
  1885. break;
  1886. case CURLOPT_TCP_NODELAY:
  1887. /*
  1888. * Enable or disable TCP_NODELAY, which will disable/enable the Nagle
  1889. * algorithm
  1890. */
  1891. data->set.tcp_nodelay = (0 != va_arg(param, long))?TRUE:FALSE;
  1892. break;
  1893. case CURLOPT_FTP_ACCOUNT:
  1894. result = setstropt(&data->set.str[STRING_FTP_ACCOUNT],
  1895. va_arg(param, char *));
  1896. break;
  1897. case CURLOPT_IGNORE_CONTENT_LENGTH:
  1898. data->set.ignorecl = (0 != va_arg(param, long))?TRUE:FALSE;
  1899. break;
  1900. case CURLOPT_CONNECT_ONLY:
  1901. /*
  1902. * No data transfer, set up connection and let application use the socket
  1903. */
  1904. data->set.connect_only = (0 != va_arg(param, long))?TRUE:FALSE;
  1905. break;
  1906. case CURLOPT_FTP_ALTERNATIVE_TO_USER:
  1907. result = setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER],
  1908. va_arg(param, char *));
  1909. break;
  1910. case CURLOPT_SOCKOPTFUNCTION:
  1911. /*
  1912. * socket callback function: called after socket() but before connect()
  1913. */
  1914. data->set.fsockopt = va_arg(param, curl_sockopt_callback);
  1915. break;
  1916. case CURLOPT_SOCKOPTDATA:
  1917. /*
  1918. * socket callback data pointer. Might be NULL.
  1919. */
  1920. data->set.sockopt_client = va_arg(param, void *);
  1921. break;
  1922. case CURLOPT_OPENSOCKETFUNCTION:
  1923. /*
  1924. * open/create socket callback function: called instead of socket(),
  1925. * before connect()
  1926. */
  1927. data->set.fopensocket = va_arg(param, curl_opensocket_callback);
  1928. break;
  1929. case CURLOPT_OPENSOCKETDATA:
  1930. /*
  1931. * socket callback data pointer. Might be NULL.
  1932. */
  1933. data->set.opensocket_client = va_arg(param, void *);
  1934. break;
  1935. case CURLOPT_CLOSESOCKETFUNCTION:
  1936. /*
  1937. * close socket callback function: called instead of close()
  1938. * when shutting down a connection
  1939. */
  1940. data->set.fclosesocket = va_arg(param, curl_closesocket_callback);
  1941. break;
  1942. case CURLOPT_CLOSESOCKETDATA:
  1943. /*
  1944. * socket callback data pointer. Might be NULL.
  1945. */
  1946. data->set.closesocket_client = va_arg(param, void *);
  1947. break;
  1948. case CURLOPT_SSL_SESSIONID_CACHE:
  1949. data->set.ssl.sessionid = (0 != va_arg(param, long))?TRUE:FALSE;
  1950. break;
  1951. #ifdef USE_LIBSSH2
  1952. /* we only include SSH options if explicitly built to support SSH */
  1953. case CURLOPT_SSH_AUTH_TYPES:
  1954. data->set.ssh_auth_types = va_arg(param, long);
  1955. break;
  1956. case CURLOPT_SSH_PUBLIC_KEYFILE:
  1957. /*
  1958. * Use this file instead of the $HOME/.ssh/id_dsa.pub file
  1959. */
  1960. result = setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY],
  1961. va_arg(param, char *));
  1962. break;
  1963. case CURLOPT_SSH_PRIVATE_KEYFILE:
  1964. /*
  1965. * Use this file instead of the $HOME/.ssh/id_dsa file
  1966. */
  1967. result = setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY],
  1968. va_arg(param, char *));
  1969. break;
  1970. case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5:
  1971. /*
  1972. * Option to allow for the MD5 of the host public key to be checked
  1973. * for validation purposes.
  1974. */
  1975. result = setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5],
  1976. va_arg(param, char *));
  1977. break;
  1978. #ifdef HAVE_LIBSSH2_KNOWNHOST_API
  1979. case CURLOPT_SSH_KNOWNHOSTS:
  1980. /*
  1981. * Store the file name to read known hosts from.
  1982. */
  1983. result = setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS],
  1984. va_arg(param, char *));
  1985. break;
  1986. case CURLOPT_SSH_KEYFUNCTION:
  1987. /* setting to NULL is fine since the ssh.c functions themselves will
  1988. then rever to use the internal default */
  1989. data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback);
  1990. break;
  1991. case CURLOPT_SSH_KEYDATA:
  1992. /*
  1993. * Custom client data to pass to the SSH keyfunc callback
  1994. */
  1995. data->set.ssh_keyfunc_userp = va_arg(param, void *);
  1996. break;
  1997. #endif /* HAVE_LIBSSH2_KNOWNHOST_API */
  1998. #endif /* USE_LIBSSH2 */
  1999. case CURLOPT_HTTP_TRANSFER_DECODING:
  2000. /*
  2001. * disable libcurl transfer encoding is used
  2002. */
  2003. data->set.http_te_skip = (0 == va_arg(param, long))?TRUE:FALSE;
  2004. break;
  2005. case CURLOPT_HTTP_CONTENT_DECODING:
  2006. /*
  2007. * raw data passed to the application when content encoding is used
  2008. */
  2009. data->set.http_ce_skip = (0 == va_arg(param, long))?TRUE:FALSE;
  2010. break;
  2011. case CURLOPT_NEW_FILE_PERMS:
  2012. /*
  2013. * Uses these permissions instead of 0644
  2014. */
  2015. data->set.new_file_perms = va_arg(param, long);
  2016. break;
  2017. case CURLOPT_NEW_DIRECTORY_PERMS:
  2018. /*
  2019. * Uses these permissions instead of 0755
  2020. */
  2021. data->set.new_directory_perms = va_arg(param, long);
  2022. break;
  2023. case CURLOPT_ADDRESS_SCOPE:
  2024. /*
  2025. * We always get longs when passed plain numericals, but for this value we
  2026. * know that an unsigned int will always hold the value so we blindly
  2027. * typecast to this type
  2028. */
  2029. data->set.scope = curlx_sltoui(va_arg(param, long));
  2030. break;
  2031. case CURLOPT_PROTOCOLS:
  2032. /* set the bitmask for the protocols that are allowed to be used for the
  2033. transfer, which thus helps the app which takes URLs from users or other
  2034. external inputs and want to restrict what protocol(s) to deal
  2035. with. Defaults to CURLPROTO_ALL. */
  2036. data->set.allowed_protocols = va_arg(param, long);
  2037. break;
  2038. case CURLOPT_REDIR_PROTOCOLS:
  2039. /* set the bitmask for the protocols that libcurl is allowed to follow to,
  2040. as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
  2041. to be set in both bitmasks to be allowed to get redirected to. Defaults
  2042. to all protocols except FILE and SCP. */
  2043. data->set.redir_protocols = va_arg(param, long);
  2044. break;
  2045. case CURLOPT_MAIL_FROM:
  2046. /* Set the SMTP mail originator */
  2047. result = setstropt(&data->set.str[STRING_MAIL_FROM],
  2048. va_arg(param, char *));
  2049. break;
  2050. case CURLOPT_MAIL_AUTH:
  2051. /* Set the SMTP auth originator */
  2052. result = setstropt(&data->set.str[STRING_MAIL_AUTH],
  2053. va_arg(param, char *));
  2054. break;
  2055. case CURLOPT_MAIL_RCPT:
  2056. /* Set the list of mail recipients */
  2057. data->set.mail_rcpt = va_arg(param, struct curl_slist *);
  2058. break;
  2059. case CURLOPT_SASL_IR:
  2060. /* Enable/disable SASL initial response */
  2061. data->set.sasl_ir = (0 != va_arg(param, long)) ? TRUE : FALSE;
  2062. break;
  2063. case CURLOPT_RTSP_REQUEST:
  2064. {
  2065. /*
  2066. * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...)
  2067. * Would this be better if the RTSPREQ_* were just moved into here?
  2068. */
  2069. long curl_rtspreq = va_arg(param, long);
  2070. Curl_RtspReq rtspreq = RTSPREQ_NONE;
  2071. switch(curl_rtspreq) {
  2072. case CURL_RTSPREQ_OPTIONS:
  2073. rtspreq = RTSPREQ_OPTIONS;
  2074. break;
  2075. case CURL_RTSPREQ_DESCRIBE:
  2076. rtspreq = RTSPREQ_DESCRIBE;
  2077. break;
  2078. case CURL_RTSPREQ_ANNOUNCE:
  2079. rtspreq = RTSPREQ_ANNOUNCE;
  2080. break;
  2081. case CURL_RTSPREQ_SETUP:
  2082. rtspreq = RTSPREQ_SETUP;
  2083. break;
  2084. case CURL_RTSPREQ_PLAY:
  2085. rtspreq = RTSPREQ_PLAY;
  2086. break;
  2087. case CURL_RTSPREQ_PAUSE:
  2088. rtspreq = RTSPREQ_PAUSE;
  2089. break;
  2090. case CURL_RTSPREQ_TEARDOWN:
  2091. rtspreq = RTSPREQ_TEARDOWN;
  2092. break;
  2093. case CURL_RTSPREQ_GET_PARAMETER:
  2094. rtspreq = RTSPREQ_GET_PARAMETER;
  2095. break;
  2096. case CURL_RTSPREQ_SET_PARAMETER:
  2097. rtspreq = RTSPREQ_SET_PARAMETER;
  2098. break;
  2099. case CURL_RTSPREQ_RECORD:
  2100. rtspreq = RTSPREQ_RECORD;
  2101. break;
  2102. case CURL_RTSPREQ_RECEIVE:
  2103. rtspreq = RTSPREQ_RECEIVE;
  2104. break;
  2105. default:
  2106. rtspreq = RTSPREQ_NONE;
  2107. }
  2108. data->set.rtspreq = rtspreq;
  2109. break;
  2110. }
  2111. case CURLOPT_RTSP_SESSION_ID:
  2112. /*
  2113. * Set the RTSP Session ID manually. Useful if the application is
  2114. * resuming a previously established RTSP session
  2115. */
  2116. result = setstropt(&data->set.str[STRING_RTSP_SESSION_ID],
  2117. va_arg(param, char *));
  2118. break;
  2119. case CURLOPT_RTSP_STREAM_URI:
  2120. /*
  2121. * Set the Stream URI for the RTSP request. Unless the request is
  2122. * for generic server options, the application will need to set this.
  2123. */
  2124. result = setstropt(&data->set.str[STRING_RTSP_STREAM_URI],
  2125. va_arg(param, char *));
  2126. break;
  2127. case CURLOPT_RTSP_TRANSPORT:
  2128. /*
  2129. * The content of the Transport: header for the RTSP request
  2130. */
  2131. result = setstropt(&data->set.str[STRING_RTSP_TRANSPORT],
  2132. va_arg(param, char *));
  2133. break;
  2134. case CURLOPT_RTSP_CLIENT_CSEQ:
  2135. /*
  2136. * Set the CSEQ number to issue for the next RTSP request. Useful if the
  2137. * application is resuming a previously broken connection. The CSEQ
  2138. * will increment from this new number henceforth.
  2139. */
  2140. data->state.rtsp_next_client_CSeq = va_arg(param, long);
  2141. break;
  2142. case CURLOPT_RTSP_SERVER_CSEQ:
  2143. /* Same as the above, but for server-initiated requests */
  2144. data->state.rtsp_next_client_CSeq = va_arg(param, long);
  2145. break;
  2146. case CURLOPT_INTERLEAVEDATA:
  2147. data->set.rtp_out = va_arg(param, void *);
  2148. break;
  2149. case CURLOPT_INTERLEAVEFUNCTION:
  2150. /* Set the user defined RTP write function */
  2151. data->set.fwrite_rtp = va_arg(param, curl_write_callback);
  2152. break;
  2153. case CURLOPT_WILDCARDMATCH:
  2154. data->set.wildcardmatch = (0 != va_arg(param, long))?TRUE:FALSE;
  2155. break;
  2156. case CURLOPT_CHUNK_BGN_FUNCTION:
  2157. data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback);
  2158. break;
  2159. case CURLOPT_CHUNK_END_FUNCTION:
  2160. data->set.chunk_end = va_arg(param, curl_chunk_end_callback);
  2161. break;
  2162. case CURLOPT_FNMATCH_FUNCTION:
  2163. data->set.fnmatch = va_arg(param, curl_fnmatch_callback);
  2164. break;
  2165. case CURLOPT_CHUNK_DATA:
  2166. data->wildcard.customptr = va_arg(param, void *);
  2167. break;
  2168. case CURLOPT_FNMATCH_DATA:
  2169. data->set.fnmatch_data = va_arg(param, void *);
  2170. break;
  2171. #ifdef USE_TLS_SRP
  2172. case CURLOPT_TLSAUTH_USERNAME:
  2173. result = setstropt(&data->set.str[STRING_TLSAUTH_USERNAME],
  2174. va_arg(param, char *));
  2175. if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype)
  2176. data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
  2177. break;
  2178. case CURLOPT_TLSAUTH_PASSWORD:
  2179. result = setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD],
  2180. va_arg(param, char *));
  2181. if(data->set.str[STRING_TLSAUTH_USERNAME] && !data->set.ssl.authtype)
  2182. data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
  2183. break;
  2184. case CURLOPT_TLSAUTH_TYPE:
  2185. if(strnequal((char *)va_arg(param, char *), "SRP", strlen("SRP")))
  2186. data->set.ssl.authtype = CURL_TLSAUTH_SRP;
  2187. else
  2188. data->set.ssl.authtype = CURL_TLSAUTH_NONE;
  2189. break;
  2190. #endif
  2191. case CURLOPT_DNS_SERVERS:
  2192. result = Curl_set_dns_servers(data, va_arg(param, char *));
  2193. break;
  2194. case CURLOPT_DNS_INTERFACE:
  2195. result = Curl_set_dns_interface(data, va_arg(param, char *));
  2196. break;
  2197. case CURLOPT_DNS_LOCAL_IP4:
  2198. result = Curl_set_dns_local_ip4(data, va_arg(param, char *));
  2199. break;
  2200. case CURLOPT_DNS_LOCAL_IP6:
  2201. result = Curl_set_dns_local_ip6(data, va_arg(param, char *));
  2202. break;
  2203. case CURLOPT_TCP_KEEPALIVE:
  2204. data->set.tcp_keepalive = (0 != va_arg(param, long))?TRUE:FALSE;
  2205. break;
  2206. case CURLOPT_TCP_KEEPIDLE:
  2207. data->set.tcp_keepidle = va_arg(param, long);
  2208. break;
  2209. case CURLOPT_TCP_KEEPINTVL:
  2210. data->set.tcp_keepintvl = va_arg(param, long);
  2211. break;
  2212. case CURLOPT_SSL_ENABLE_NPN:
  2213. data->set.ssl_enable_npn = (0 != va_arg(param, long))?TRUE:FALSE;
  2214. break;
  2215. case CURLOPT_SSL_ENABLE_ALPN:
  2216. data->set.ssl_enable_alpn = (0 != va_arg(param, long))?TRUE:FALSE;
  2217. break;
  2218. default:
  2219. /* unknown tag and its companion, just ignore: */
  2220. result = CURLE_UNKNOWN_OPTION;
  2221. break;
  2222. }
  2223. return result;
  2224. }
  2225. static void conn_free(struct connectdata *conn)
  2226. {
  2227. if(!conn)
  2228. return;
  2229. /* possible left-overs from the async name resolvers */
  2230. Curl_resolver_cancel(conn);
  2231. /* close the SSL stuff before we close any sockets since they will/may
  2232. write to the sockets */
  2233. Curl_ssl_close(conn, FIRSTSOCKET);
  2234. Curl_ssl_close(conn, SECONDARYSOCKET);
  2235. /* close possibly still open sockets */
  2236. if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
  2237. Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
  2238. if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
  2239. Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
  2240. if(CURL_SOCKET_BAD != conn->tempsock[0])
  2241. Curl_closesocket(conn, conn->tempsock[0]);
  2242. if(CURL_SOCKET_BAD != conn->tempsock[1])
  2243. Curl_closesocket(conn, conn->tempsock[1]);
  2244. #if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
  2245. Curl_ntlm_wb_cleanup(conn);
  2246. #endif
  2247. Curl_safefree(conn->user);
  2248. Curl_safefree(conn->passwd);
  2249. Curl_safefree(conn->xoauth2_bearer);
  2250. Curl_safefree(conn->options);
  2251. Curl_safefree(conn->proxyuser);
  2252. Curl_safefree(conn->proxypasswd);
  2253. Curl_safefree(conn->allocptr.proxyuserpwd);
  2254. Curl_safefree(conn->allocptr.uagent);
  2255. Curl_safefree(conn->allocptr.userpwd);
  2256. Curl_safefree(conn->allocptr.accept_encoding);
  2257. Curl_safefree(conn->allocptr.te);
  2258. Curl_safefree(conn->allocptr.rangeline);
  2259. Curl_safefree(conn->allocptr.ref);
  2260. Curl_safefree(conn->allocptr.host);
  2261. Curl_safefree(conn->allocptr.cookiehost);
  2262. Curl_safefree(conn->allocptr.rtsp_transport);
  2263. Curl_safefree(conn->trailer);
  2264. Curl_safefree(conn->host.rawalloc); /* host name buffer */
  2265. Curl_safefree(conn->proxy.rawalloc); /* proxy name buffer */
  2266. Curl_safefree(conn->master_buffer);
  2267. Curl_llist_destroy(conn->send_pipe, NULL);
  2268. Curl_llist_destroy(conn->recv_pipe, NULL);
  2269. conn->send_pipe = NULL;
  2270. conn->recv_pipe = NULL;
  2271. Curl_safefree(conn->localdev);
  2272. Curl_free_ssl_config(&conn->ssl_config);
  2273. free(conn); /* free all the connection oriented data */
  2274. }
  2275. CURLcode Curl_disconnect(struct connectdata *conn, bool dead_connection)
  2276. {
  2277. struct SessionHandle *data;
  2278. if(!conn)
  2279. return CURLE_OK; /* this is closed and fine already */
  2280. data = conn->data;
  2281. if(!data) {
  2282. DEBUGF(fprintf(stderr, "DISCONNECT without easy handle, ignoring\n"));
  2283. return CURLE_OK;
  2284. }
  2285. if(conn->dns_entry != NULL) {
  2286. Curl_resolv_unlock(data, conn->dns_entry);
  2287. conn->dns_entry = NULL;
  2288. }
  2289. Curl_hostcache_prune(data); /* kill old DNS cache entries */
  2290. {
  2291. int has_host_ntlm = (conn->ntlm.state != NTLMSTATE_NONE);
  2292. int has_proxy_ntlm = (conn->proxyntlm.state != NTLMSTATE_NONE);
  2293. /* Authentication data is a mix of connection-related and sessionhandle-
  2294. related stuff. NTLM is connection-related so when we close the shop
  2295. we shall forget. */
  2296. if(has_host_ntlm) {
  2297. data->state.authhost.done = FALSE;
  2298. data->state.authhost.picked =
  2299. data->state.authhost.want;
  2300. }
  2301. if(has_proxy_ntlm) {
  2302. data->state.authproxy.done = FALSE;
  2303. data->state.authproxy.picked =
  2304. data->state.authproxy.want;
  2305. }
  2306. if(has_host_ntlm || has_proxy_ntlm)
  2307. data->state.authproblem = FALSE;
  2308. }
  2309. /* Cleanup NTLM connection-related data */
  2310. Curl_http_ntlm_cleanup(conn);
  2311. /* Cleanup possible redirect junk */
  2312. if(data->req.newurl) {
  2313. free(data->req.newurl);
  2314. data->req.newurl = NULL;
  2315. }
  2316. if(conn->handler->disconnect)
  2317. /* This is set if protocol-specific cleanups should be made */
  2318. conn->handler->disconnect(conn, dead_connection);
  2319. /* unlink ourselves! */
  2320. infof(data, "Closing connection %ld\n", conn->connection_id);
  2321. Curl_conncache_remove_conn(data->state.conn_cache, conn);
  2322. #if defined(USE_LIBIDN)
  2323. if(conn->host.encalloc)
  2324. idn_free(conn->host.encalloc); /* encoded host name buffer, must be freed
  2325. with idn_free() since this was allocated
  2326. by libidn */
  2327. if(conn->proxy.encalloc)
  2328. idn_free(conn->proxy.encalloc); /* encoded proxy name buffer, must be
  2329. freed with idn_free() since this was
  2330. allocated by libidn */
  2331. #elif defined(USE_WIN32_IDN)
  2332. free(conn->host.encalloc); /* encoded host name buffer, must be freed with
  2333. idn_free() since this was allocated by
  2334. curl_win32_idn_to_ascii */
  2335. if(conn->proxy.encalloc)
  2336. free(conn->proxy.encalloc); /* encoded proxy name buffer, must be freed
  2337. with idn_free() since this was allocated by
  2338. curl_win32_idn_to_ascii */
  2339. #endif
  2340. Curl_ssl_close(conn, FIRSTSOCKET);
  2341. /* Indicate to all handles on the pipe that we're dead */
  2342. if(Curl_multi_pipeline_enabled(data->multi)) {
  2343. signalPipeClose(conn->send_pipe, TRUE);
  2344. signalPipeClose(conn->recv_pipe, TRUE);
  2345. }
  2346. conn_free(conn);
  2347. Curl_speedinit(data);
  2348. return CURLE_OK;
  2349. }
  2350. /*
  2351. * This function should return TRUE if the socket is to be assumed to
  2352. * be dead. Most commonly this happens when the server has closed the
  2353. * connection due to inactivity.
  2354. */
  2355. static bool SocketIsDead(curl_socket_t sock)
  2356. {
  2357. int sval;
  2358. bool ret_val = TRUE;
  2359. sval = Curl_socket_ready(sock, CURL_SOCKET_BAD, 0);
  2360. if(sval == 0)
  2361. /* timeout */
  2362. ret_val = FALSE;
  2363. return ret_val;
  2364. }
  2365. static bool IsPipeliningPossible(const struct SessionHandle *handle,
  2366. const struct connectdata *conn)
  2367. {
  2368. if((conn->handler->protocol & CURLPROTO_HTTP) &&
  2369. Curl_multi_pipeline_enabled(handle->multi) &&
  2370. (handle->set.httpreq == HTTPREQ_GET ||
  2371. handle->set.httpreq == HTTPREQ_HEAD) &&
  2372. handle->set.httpversion != CURL_HTTP_VERSION_1_0)
  2373. return TRUE;
  2374. return FALSE;
  2375. }
  2376. bool Curl_isPipeliningEnabled(const struct SessionHandle *handle)
  2377. {
  2378. return Curl_multi_pipeline_enabled(handle->multi);
  2379. }
  2380. CURLcode Curl_addHandleToPipeline(struct SessionHandle *data,
  2381. struct curl_llist *pipeline)
  2382. {
  2383. if(!Curl_llist_insert_next(pipeline, pipeline->tail, data))
  2384. return CURLE_OUT_OF_MEMORY;
  2385. return CURLE_OK;
  2386. }
  2387. int Curl_removeHandleFromPipeline(struct SessionHandle *handle,
  2388. struct curl_llist *pipeline)
  2389. {
  2390. struct curl_llist_element *curr;
  2391. curr = pipeline->head;
  2392. while(curr) {
  2393. if(curr->ptr == handle) {
  2394. Curl_llist_remove(pipeline, curr, NULL);
  2395. return 1; /* we removed a handle */
  2396. }
  2397. curr = curr->next;
  2398. }
  2399. return 0;
  2400. }
  2401. #if 0 /* this code is saved here as it is useful for debugging purposes */
  2402. static void Curl_printPipeline(struct curl_llist *pipeline)
  2403. {
  2404. struct curl_llist_element *curr;
  2405. curr = pipeline->head;
  2406. while(curr) {
  2407. struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
  2408. infof(data, "Handle in pipeline: %s\n", data->state.path);
  2409. curr = curr->next;
  2410. }
  2411. }
  2412. #endif
  2413. static struct SessionHandle* gethandleathead(struct curl_llist *pipeline)
  2414. {
  2415. struct curl_llist_element *curr = pipeline->head;
  2416. if(curr) {
  2417. return (struct SessionHandle *) curr->ptr;
  2418. }
  2419. return NULL;
  2420. }
  2421. /* remove the specified connection from all (possible) pipelines and related
  2422. queues */
  2423. void Curl_getoff_all_pipelines(struct SessionHandle *data,
  2424. struct connectdata *conn)
  2425. {
  2426. bool recv_head = (conn->readchannel_inuse &&
  2427. (gethandleathead(conn->recv_pipe) == data)) ? TRUE : FALSE;
  2428. bool send_head = (conn->writechannel_inuse &&
  2429. (gethandleathead(conn->send_pipe) == data)) ? TRUE : FALSE;
  2430. if(Curl_removeHandleFromPipeline(data, conn->recv_pipe) && recv_head)
  2431. conn->readchannel_inuse = FALSE;
  2432. if(Curl_removeHandleFromPipeline(data, conn->send_pipe) && send_head)
  2433. conn->writechannel_inuse = FALSE;
  2434. }
  2435. static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke)
  2436. {
  2437. struct curl_llist_element *curr;
  2438. if(!pipeline)
  2439. return;
  2440. curr = pipeline->head;
  2441. while(curr) {
  2442. struct curl_llist_element *next = curr->next;
  2443. struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
  2444. #ifdef DEBUGBUILD /* debug-only code */
  2445. if(data->magic != CURLEASY_MAGIC_NUMBER) {
  2446. /* MAJOR BADNESS */
  2447. infof(data, "signalPipeClose() found BAAD easy handle\n");
  2448. }
  2449. #endif
  2450. if(pipe_broke)
  2451. data->state.pipe_broke = TRUE;
  2452. Curl_multi_handlePipeBreak(data);
  2453. Curl_llist_remove(pipeline, curr, NULL);
  2454. curr = next;
  2455. }
  2456. }
  2457. /*
  2458. * This function finds the connection in the connection
  2459. * cache that has been unused for the longest time.
  2460. *
  2461. * Returns the pointer to the oldest idle connection, or NULL if none was
  2462. * found.
  2463. */
  2464. static struct connectdata *
  2465. find_oldest_idle_connection(struct SessionHandle *data)
  2466. {
  2467. struct conncache *bc = data->state.conn_cache;
  2468. struct curl_hash_iterator iter;
  2469. struct curl_llist_element *curr;
  2470. struct curl_hash_element *he;
  2471. long highscore=-1;
  2472. long score;
  2473. struct timeval now;
  2474. struct connectdata *conn_candidate = NULL;
  2475. struct connectbundle *bundle;
  2476. now = Curl_tvnow();
  2477. Curl_hash_start_iterate(bc->hash, &iter);
  2478. he = Curl_hash_next_element(&iter);
  2479. while(he) {
  2480. struct connectdata *conn;
  2481. bundle = he->ptr;
  2482. curr = bundle->conn_list->head;
  2483. while(curr) {
  2484. conn = curr->ptr;
  2485. if(!conn->inuse) {
  2486. /* Set higher score for the age passed since the connection was used */
  2487. score = Curl_tvdiff(now, conn->now);
  2488. if(score > highscore) {
  2489. highscore = score;
  2490. conn_candidate = conn;
  2491. }
  2492. }
  2493. curr = curr->next;
  2494. }
  2495. he = Curl_hash_next_element(&iter);
  2496. }
  2497. return conn_candidate;
  2498. }
  2499. /*
  2500. * This function finds the connection in the connection
  2501. * bundle that has been unused for the longest time.
  2502. *
  2503. * Returns the pointer to the oldest idle connection, or NULL if none was
  2504. * found.
  2505. */
  2506. static struct connectdata *
  2507. find_oldest_idle_connection_in_bundle(struct SessionHandle *data,
  2508. struct connectbundle *bundle)
  2509. {
  2510. struct curl_llist_element *curr;
  2511. long highscore=-1;
  2512. long score;
  2513. struct timeval now;
  2514. struct connectdata *conn_candidate = NULL;
  2515. struct connectdata *conn;
  2516. (void)data;
  2517. now = Curl_tvnow();
  2518. curr = bundle->conn_list->head;
  2519. while(curr) {
  2520. conn = curr->ptr;
  2521. if(!conn->inuse) {
  2522. /* Set higher score for the age passed since the connection was used */
  2523. score = Curl_tvdiff(now, conn->now);
  2524. if(score > highscore) {
  2525. highscore = score;
  2526. conn_candidate = conn;
  2527. }
  2528. }
  2529. curr = curr->next;
  2530. }
  2531. return conn_candidate;
  2532. }
  2533. /*
  2534. * Given one filled in connection struct (named needle), this function should
  2535. * detect if there already is one that has all the significant details
  2536. * exactly the same and thus should be used instead.
  2537. *
  2538. * If there is a match, this function returns TRUE - and has marked the
  2539. * connection as 'in-use'. It must later be called with ConnectionDone() to
  2540. * return back to 'idle' (unused) state.
  2541. *
  2542. * The force_reuse flag is set if the connection must be used, even if
  2543. * the pipelining strategy wants to open a new connection instead of reusing.
  2544. */
  2545. static bool
  2546. ConnectionExists(struct SessionHandle *data,
  2547. struct connectdata *needle,
  2548. struct connectdata **usethis,
  2549. bool *force_reuse)
  2550. {
  2551. struct connectdata *check;
  2552. struct connectdata *chosen = 0;
  2553. bool canPipeline = IsPipeliningPossible(data, needle);
  2554. bool wantNTLMhttp = ((data->state.authhost.want & CURLAUTH_NTLM) ||
  2555. (data->state.authhost.want & CURLAUTH_NTLM_WB)) &&
  2556. (needle->handler->protocol & CURLPROTO_HTTP) ? TRUE : FALSE;
  2557. struct connectbundle *bundle;
  2558. *force_reuse = FALSE;
  2559. /* We can't pipe if the site is blacklisted */
  2560. if(canPipeline && Curl_pipeline_site_blacklisted(data, needle)) {
  2561. canPipeline = FALSE;
  2562. }
  2563. /* Look up the bundle with all the connections to this
  2564. particular host */
  2565. bundle = Curl_conncache_find_bundle(data->state.conn_cache,
  2566. needle->host.name);
  2567. if(bundle) {
  2568. size_t max_pipe_len = Curl_multi_max_pipeline_length(data->multi);
  2569. size_t best_pipe_len = max_pipe_len;
  2570. struct curl_llist_element *curr;
  2571. infof(data, "Found bundle for host %s: %p\n",
  2572. needle->host.name, (void *)bundle);
  2573. /* We can't pipe if we don't know anything about the server */
  2574. if(canPipeline && !bundle->server_supports_pipelining) {
  2575. infof(data, "Server doesn't support pipelining\n");
  2576. canPipeline = FALSE;
  2577. }
  2578. curr = bundle->conn_list->head;
  2579. while(curr) {
  2580. bool match = FALSE;
  2581. bool credentialsMatch = FALSE;
  2582. size_t pipeLen;
  2583. /*
  2584. * Note that if we use a HTTP proxy, we check connections to that
  2585. * proxy and not to the actual remote server.
  2586. */
  2587. check = curr->ptr;
  2588. curr = curr->next;
  2589. pipeLen = check->send_pipe->size + check->recv_pipe->size;
  2590. if(!pipeLen && !check->inuse) {
  2591. /* The check for a dead socket makes sense only if there are no
  2592. handles in pipeline and the connection isn't already marked in
  2593. use */
  2594. bool dead;
  2595. if(check->handler->protocol & CURLPROTO_RTSP)
  2596. /* RTSP is a special case due to RTP interleaving */
  2597. dead = Curl_rtsp_connisdead(check);
  2598. else
  2599. dead = SocketIsDead(check->sock[FIRSTSOCKET]);
  2600. if(dead) {
  2601. check->data = data;
  2602. infof(data, "Connection %ld seems to be dead!\n",
  2603. check->connection_id);
  2604. /* disconnect resources */
  2605. Curl_disconnect(check, /* dead_connection */ TRUE);
  2606. continue;
  2607. }
  2608. }
  2609. if(canPipeline) {
  2610. /* Make sure the pipe has only GET requests */
  2611. struct SessionHandle* sh = gethandleathead(check->send_pipe);
  2612. struct SessionHandle* rh = gethandleathead(check->recv_pipe);
  2613. if(sh) {
  2614. if(!IsPipeliningPossible(sh, check))
  2615. continue;
  2616. }
  2617. else if(rh) {
  2618. if(!IsPipeliningPossible(rh, check))
  2619. continue;
  2620. }
  2621. }
  2622. else {
  2623. if(pipeLen > 0) {
  2624. /* can only happen within multi handles, and means that another easy
  2625. handle is using this connection */
  2626. continue;
  2627. }
  2628. if(Curl_resolver_asynch()) {
  2629. /* ip_addr_str[0] is NUL only if the resolving of the name hasn't
  2630. completed yet and until then we don't re-use this connection */
  2631. if(!check->ip_addr_str[0]) {
  2632. infof(data,
  2633. "Connection #%ld is still name resolving, can't reuse\n",
  2634. check->connection_id);
  2635. continue;
  2636. }
  2637. }
  2638. if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) ||
  2639. check->bits.close) {
  2640. /* Don't pick a connection that hasn't connected yet or that is going
  2641. to get closed. */
  2642. infof(data, "Connection #%ld isn't open enough, can't reuse\n",
  2643. check->connection_id);
  2644. #ifdef DEBUGBUILD
  2645. if(check->recv_pipe->size > 0) {
  2646. infof(data,
  2647. "BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
  2648. check->connection_id);
  2649. }
  2650. #endif
  2651. continue;
  2652. }
  2653. }
  2654. if((needle->handler->flags&PROTOPT_SSL) !=
  2655. (check->handler->flags&PROTOPT_SSL))
  2656. /* don't do mixed SSL and non-SSL connections */
  2657. if(!(needle->handler->protocol & check->handler->protocol))
  2658. /* except protocols that have been upgraded via TLS */
  2659. continue;
  2660. if(needle->handler->flags&PROTOPT_SSL) {
  2661. if((data->set.ssl.verifypeer != check->verifypeer) ||
  2662. (data->set.ssl.verifyhost != check->verifyhost))
  2663. continue;
  2664. }
  2665. if(needle->bits.proxy != check->bits.proxy)
  2666. /* don't do mixed proxy and non-proxy connections */
  2667. continue;
  2668. if(!canPipeline && check->inuse)
  2669. /* this request can't be pipelined but the checked connection is
  2670. already in use so we skip it */
  2671. continue;
  2672. if(needle->localdev || needle->localport) {
  2673. /* If we are bound to a specific local end (IP+port), we must not
  2674. re-use a random other one, although if we didn't ask for a
  2675. particular one we can reuse one that was bound.
  2676. This comparison is a bit rough and too strict. Since the input
  2677. parameters can be specified in numerous ways and still end up the
  2678. same it would take a lot of processing to make it really accurate.
  2679. Instead, this matching will assume that re-uses of bound connections
  2680. will most likely also re-use the exact same binding parameters and
  2681. missing out a few edge cases shouldn't hurt anyone very much.
  2682. */
  2683. if((check->localport != needle->localport) ||
  2684. (check->localportrange != needle->localportrange) ||
  2685. !check->localdev ||
  2686. !needle->localdev ||
  2687. strcmp(check->localdev, needle->localdev))
  2688. continue;
  2689. }
  2690. if((!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) ||
  2691. wantNTLMhttp) {
  2692. /* This protocol requires credentials per connection or is HTTP+NTLM,
  2693. so verify that we're using the same name and password as well */
  2694. if(!strequal(needle->user, check->user) ||
  2695. !strequal(needle->passwd, check->passwd)) {
  2696. /* one of them was different */
  2697. continue;
  2698. }
  2699. credentialsMatch = TRUE;
  2700. }
  2701. if(!needle->bits.httpproxy || needle->handler->flags&PROTOPT_SSL ||
  2702. (needle->bits.httpproxy && check->bits.httpproxy &&
  2703. needle->bits.tunnel_proxy && check->bits.tunnel_proxy &&
  2704. Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
  2705. (needle->port == check->port))) {
  2706. /* The requested connection does not use a HTTP proxy or it uses SSL or
  2707. it is a non-SSL protocol tunneled over the same http proxy name and
  2708. port number or it is a non-SSL protocol which is allowed to be
  2709. upgraded via TLS */
  2710. if((Curl_raw_equal(needle->handler->scheme, check->handler->scheme) ||
  2711. needle->handler->protocol & check->handler->protocol) &&
  2712. Curl_raw_equal(needle->host.name, check->host.name) &&
  2713. needle->remote_port == check->remote_port) {
  2714. if(needle->handler->flags & PROTOPT_SSL) {
  2715. /* This is a SSL connection so verify that we're using the same
  2716. SSL options as well */
  2717. if(!Curl_ssl_config_matches(&needle->ssl_config,
  2718. &check->ssl_config)) {
  2719. DEBUGF(infof(data,
  2720. "Connection #%ld has different SSL parameters, "
  2721. "can't reuse\n",
  2722. check->connection_id));
  2723. continue;
  2724. }
  2725. else if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
  2726. DEBUGF(infof(data,
  2727. "Connection #%ld has not started SSL connect, "
  2728. "can't reuse\n",
  2729. check->connection_id));
  2730. continue;
  2731. }
  2732. }
  2733. match = TRUE;
  2734. }
  2735. }
  2736. else { /* The requested needle connection is using a proxy,
  2737. is the checked one using the same host, port and type? */
  2738. if(check->bits.proxy &&
  2739. (needle->proxytype == check->proxytype) &&
  2740. (needle->bits.tunnel_proxy == check->bits.tunnel_proxy) &&
  2741. Curl_raw_equal(needle->proxy.name, check->proxy.name) &&
  2742. needle->port == check->port) {
  2743. /* This is the same proxy connection, use it! */
  2744. match = TRUE;
  2745. }
  2746. }
  2747. if(match) {
  2748. /* If we are looking for an HTTP+NTLM connection, check if this is
  2749. already authenticating with the right credentials. If not, keep
  2750. looking so that we can reuse NTLM connections if
  2751. possible. (Especially we must not reuse the same connection if
  2752. partway through a handshake!) */
  2753. if(wantNTLMhttp) {
  2754. if(credentialsMatch && check->ntlm.state != NTLMSTATE_NONE) {
  2755. chosen = check;
  2756. /* We must use this connection, no other */
  2757. *force_reuse = TRUE;
  2758. break;
  2759. }
  2760. else if(credentialsMatch)
  2761. /* this is a backup choice */
  2762. chosen = check;
  2763. continue;
  2764. }
  2765. if(canPipeline) {
  2766. /* We can pipeline if we want to. Let's continue looking for
  2767. the optimal connection to use, i.e the shortest pipe that is not
  2768. blacklisted. */
  2769. if(pipeLen == 0) {
  2770. /* We have the optimal connection. Let's stop looking. */
  2771. chosen = check;
  2772. break;
  2773. }
  2774. /* We can't use the connection if the pipe is full */
  2775. if(pipeLen >= max_pipe_len)
  2776. continue;
  2777. /* We can't use the connection if the pipe is penalized */
  2778. if(Curl_pipeline_penalized(data, check))
  2779. continue;
  2780. if(pipeLen < best_pipe_len) {
  2781. /* This connection has a shorter pipe so far. We'll pick this
  2782. and continue searching */
  2783. chosen = check;
  2784. best_pipe_len = pipeLen;
  2785. continue;
  2786. }
  2787. }
  2788. else {
  2789. /* We have found a connection. Let's stop searching. */
  2790. chosen = check;
  2791. break;
  2792. }
  2793. }
  2794. }
  2795. }
  2796. if(chosen) {
  2797. *usethis = chosen;
  2798. return TRUE; /* yes, we found one to use! */
  2799. }
  2800. return FALSE; /* no matching connecting exists */
  2801. }
  2802. /* Mark the connection as 'idle', or close it if the cache is full.
  2803. Returns TRUE if the connection is kept, or FALSE if it was closed. */
  2804. static bool
  2805. ConnectionDone(struct SessionHandle *data, struct connectdata *conn)
  2806. {
  2807. /* data->multi->maxconnects can be negative, deal with it. */
  2808. size_t maxconnects =
  2809. (data->multi->maxconnects < 0) ? data->multi->num_easy * 4:
  2810. data->multi->maxconnects;
  2811. struct connectdata *conn_candidate = NULL;
  2812. /* Mark the current connection as 'unused' */
  2813. conn->inuse = FALSE;
  2814. if(maxconnects > 0 &&
  2815. data->state.conn_cache->num_connections > maxconnects) {
  2816. infof(data, "Connection cache is full, closing the oldest one.\n");
  2817. conn_candidate = find_oldest_idle_connection(data);
  2818. if(conn_candidate) {
  2819. /* Set the connection's owner correctly */
  2820. conn_candidate->data = data;
  2821. /* the winner gets the honour of being disconnected */
  2822. (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
  2823. }
  2824. }
  2825. return (conn_candidate == conn) ? FALSE : TRUE;
  2826. }
  2827. /*
  2828. * The given input connection struct pointer is to be stored in the connection
  2829. * cache. If the cache is already full, least interesting existing connection
  2830. * (if any) gets closed.
  2831. *
  2832. * The given connection should be unique. That must've been checked prior to
  2833. * this call.
  2834. */
  2835. static CURLcode ConnectionStore(struct SessionHandle *data,
  2836. struct connectdata *conn)
  2837. {
  2838. static int connection_id_counter = 0;
  2839. CURLcode result;
  2840. /* Assign a number to the connection for easier tracking in the log
  2841. output */
  2842. conn->connection_id = connection_id_counter++;
  2843. result = Curl_conncache_add_conn(data->state.conn_cache, conn);
  2844. if(result != CURLE_OK)
  2845. conn->connection_id = -1;
  2846. return result;
  2847. }
  2848. /* after a TCP connection to the proxy has been verified, this function does
  2849. the next magic step.
  2850. Note: this function's sub-functions call failf()
  2851. */
  2852. CURLcode Curl_connected_proxy(struct connectdata *conn,
  2853. int sockindex)
  2854. {
  2855. if(!conn->bits.proxy || sockindex)
  2856. /* this magic only works for the primary socket as the secondary is used
  2857. for FTP only and it has FTP specific magic in ftp.c */
  2858. return CURLE_OK;
  2859. switch(conn->proxytype) {
  2860. #ifndef CURL_DISABLE_PROXY
  2861. case CURLPROXY_SOCKS5:
  2862. case CURLPROXY_SOCKS5_HOSTNAME:
  2863. return Curl_SOCKS5(conn->proxyuser, conn->proxypasswd,
  2864. conn->host.name, conn->remote_port,
  2865. FIRSTSOCKET, conn);
  2866. case CURLPROXY_SOCKS4:
  2867. return Curl_SOCKS4(conn->proxyuser, conn->host.name,
  2868. conn->remote_port, FIRSTSOCKET, conn, FALSE);
  2869. case CURLPROXY_SOCKS4A:
  2870. return Curl_SOCKS4(conn->proxyuser, conn->host.name,
  2871. conn->remote_port, FIRSTSOCKET, conn, TRUE);
  2872. #endif /* CURL_DISABLE_PROXY */
  2873. case CURLPROXY_HTTP:
  2874. case CURLPROXY_HTTP_1_0:
  2875. /* do nothing here. handled later. */
  2876. break;
  2877. default:
  2878. break;
  2879. } /* switch proxytype */
  2880. return CURLE_OK;
  2881. }
  2882. /*
  2883. * verboseconnect() displays verbose information after a connect
  2884. */
  2885. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  2886. void Curl_verboseconnect(struct connectdata *conn)
  2887. {
  2888. if(conn->data->set.verbose)
  2889. infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
  2890. conn->bits.proxy ? conn->proxy.dispname : conn->host.dispname,
  2891. conn->ip_addr_str, conn->port, conn->connection_id);
  2892. }
  2893. #endif
  2894. int Curl_protocol_getsock(struct connectdata *conn,
  2895. curl_socket_t *socks,
  2896. int numsocks)
  2897. {
  2898. if(conn->handler->proto_getsock)
  2899. return conn->handler->proto_getsock(conn, socks, numsocks);
  2900. return GETSOCK_BLANK;
  2901. }
  2902. int Curl_doing_getsock(struct connectdata *conn,
  2903. curl_socket_t *socks,
  2904. int numsocks)
  2905. {
  2906. if(conn && conn->handler->doing_getsock)
  2907. return conn->handler->doing_getsock(conn, socks, numsocks);
  2908. return GETSOCK_BLANK;
  2909. }
  2910. /*
  2911. * We are doing protocol-specific connecting and this is being called over and
  2912. * over from the multi interface until the connection phase is done on
  2913. * protocol layer.
  2914. */
  2915. CURLcode Curl_protocol_connecting(struct connectdata *conn,
  2916. bool *done)
  2917. {
  2918. CURLcode result=CURLE_OK;
  2919. if(conn && conn->handler->connecting) {
  2920. *done = FALSE;
  2921. result = conn->handler->connecting(conn, done);
  2922. }
  2923. else
  2924. *done = TRUE;
  2925. return result;
  2926. }
  2927. /*
  2928. * We are DOING this is being called over and over from the multi interface
  2929. * until the DOING phase is done on protocol layer.
  2930. */
  2931. CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
  2932. {
  2933. CURLcode result=CURLE_OK;
  2934. if(conn && conn->handler->doing) {
  2935. *done = FALSE;
  2936. result = conn->handler->doing(conn, done);
  2937. }
  2938. else
  2939. *done = TRUE;
  2940. return result;
  2941. }
  2942. /*
  2943. * We have discovered that the TCP connection has been successful, we can now
  2944. * proceed with some action.
  2945. *
  2946. */
  2947. CURLcode Curl_protocol_connect(struct connectdata *conn,
  2948. bool *protocol_done)
  2949. {
  2950. CURLcode result=CURLE_OK;
  2951. *protocol_done = FALSE;
  2952. if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) {
  2953. /* We already are connected, get back. This may happen when the connect
  2954. worked fine in the first call, like when we connect to a local server
  2955. or proxy. Note that we don't know if the protocol is actually done.
  2956. Unless this protocol doesn't have any protocol-connect callback, as
  2957. then we know we're done. */
  2958. if(!conn->handler->connecting)
  2959. *protocol_done = TRUE;
  2960. return CURLE_OK;
  2961. }
  2962. if(!conn->bits.protoconnstart) {
  2963. result = Curl_proxy_connect(conn);
  2964. if(result)
  2965. return result;
  2966. if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
  2967. (conn->tunnel_state[FIRSTSOCKET] != TUNNEL_COMPLETE))
  2968. /* when using an HTTP tunnel proxy, await complete tunnel establishment
  2969. before proceeding further. Return CURLE_OK so we'll be called again */
  2970. return CURLE_OK;
  2971. if(conn->handler->connect_it) {
  2972. /* is there a protocol-specific connect() procedure? */
  2973. /* Call the protocol-specific connect function */
  2974. result = conn->handler->connect_it(conn, protocol_done);
  2975. }
  2976. else
  2977. *protocol_done = TRUE;
  2978. /* it has started, possibly even completed but that knowledge isn't stored
  2979. in this bit! */
  2980. if(!result)
  2981. conn->bits.protoconnstart = TRUE;
  2982. }
  2983. return result; /* pass back status */
  2984. }
  2985. /*
  2986. * Helpers for IDNA convertions.
  2987. */
  2988. static bool is_ASCII_name(const char *hostname)
  2989. {
  2990. const unsigned char *ch = (const unsigned char*)hostname;
  2991. while(*ch) {
  2992. if(*ch++ & 0x80)
  2993. return FALSE;
  2994. }
  2995. return TRUE;
  2996. }
  2997. #ifdef USE_LIBIDN
  2998. /*
  2999. * Check if characters in hostname is allowed in Top Level Domain.
  3000. */
  3001. static bool tld_check_name(struct SessionHandle *data,
  3002. const char *ace_hostname)
  3003. {
  3004. size_t err_pos;
  3005. char *uc_name = NULL;
  3006. int rc;
  3007. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  3008. const char *tld_errmsg = "<no msg>";
  3009. #else
  3010. (void)data;
  3011. #endif
  3012. /* Convert (and downcase) ACE-name back into locale's character set */
  3013. rc = idna_to_unicode_lzlz(ace_hostname, &uc_name, 0);
  3014. if(rc != IDNA_SUCCESS)
  3015. return FALSE;
  3016. rc = tld_check_lz(uc_name, &err_pos, NULL);
  3017. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  3018. #ifdef HAVE_TLD_STRERROR
  3019. if(rc != TLD_SUCCESS)
  3020. tld_errmsg = tld_strerror((Tld_rc)rc);
  3021. #endif
  3022. if(rc == TLD_INVALID)
  3023. infof(data, "WARNING: %s; pos %u = `%c'/0x%02X\n",
  3024. tld_errmsg, err_pos, uc_name[err_pos],
  3025. uc_name[err_pos] & 255);
  3026. else if(rc != TLD_SUCCESS)
  3027. infof(data, "WARNING: TLD check for %s failed; %s\n",
  3028. uc_name, tld_errmsg);
  3029. #endif /* CURL_DISABLE_VERBOSE_STRINGS */
  3030. if(uc_name)
  3031. idn_free(uc_name);
  3032. if(rc != TLD_SUCCESS)
  3033. return FALSE;
  3034. return TRUE;
  3035. }
  3036. #endif
  3037. /*
  3038. * Perform any necessary IDN conversion of hostname
  3039. */
  3040. static void fix_hostname(struct SessionHandle *data,
  3041. struct connectdata *conn, struct hostname *host)
  3042. {
  3043. #ifndef USE_LIBIDN
  3044. (void)data;
  3045. (void)conn;
  3046. #elif defined(CURL_DISABLE_VERBOSE_STRINGS)
  3047. (void)conn;
  3048. #endif
  3049. /* set the name we use to display the host name */
  3050. host->dispname = host->name;
  3051. if(!is_ASCII_name(host->name)) {
  3052. #ifdef USE_LIBIDN
  3053. /*************************************************************
  3054. * Check name for non-ASCII and convert hostname to ACE form.
  3055. *************************************************************/
  3056. if(stringprep_check_version(LIBIDN_REQUIRED_VERSION)) {
  3057. char *ace_hostname = NULL;
  3058. int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0);
  3059. infof (data, "Input domain encoded as `%s'\n",
  3060. stringprep_locale_charset ());
  3061. if(rc != IDNA_SUCCESS)
  3062. infof(data, "Failed to convert %s to ACE; %s\n",
  3063. host->name, Curl_idn_strerror(conn,rc));
  3064. else {
  3065. /* tld_check_name() displays a warning if the host name contains
  3066. "illegal" characters for this TLD */
  3067. (void)tld_check_name(data, ace_hostname);
  3068. host->encalloc = ace_hostname;
  3069. /* change the name pointer to point to the encoded hostname */
  3070. host->name = host->encalloc;
  3071. }
  3072. }
  3073. #elif defined(USE_WIN32_IDN)
  3074. /*************************************************************
  3075. * Check name for non-ASCII and convert hostname to ACE form.
  3076. *************************************************************/
  3077. char *ace_hostname = NULL;
  3078. int rc = curl_win32_idn_to_ascii(host->name, &ace_hostname);
  3079. if(rc == 0)
  3080. infof(data, "Failed to convert %s to ACE;\n",
  3081. host->name);
  3082. else {
  3083. host->encalloc = ace_hostname;
  3084. /* change the name pointer to point to the encoded hostname */
  3085. host->name = host->encalloc;
  3086. }
  3087. #else
  3088. infof(data, "IDN support not present, can't parse Unicode domains\n");
  3089. #endif
  3090. }
  3091. }
  3092. static void llist_dtor(void *user, void *element)
  3093. {
  3094. (void)user;
  3095. (void)element;
  3096. /* Do nothing */
  3097. }
  3098. /*
  3099. * Allocate and initialize a new connectdata object.
  3100. */
  3101. static struct connectdata *allocate_conn(struct SessionHandle *data)
  3102. {
  3103. struct connectdata *conn = calloc(1, sizeof(struct connectdata));
  3104. if(!conn)
  3105. return NULL;
  3106. conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
  3107. already from start to avoid NULL
  3108. situations and checks */
  3109. /* and we setup a few fields in case we end up actually using this struct */
  3110. conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
  3111. conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
  3112. conn->tempsock[0] = CURL_SOCKET_BAD; /* no file descriptor */
  3113. conn->tempsock[1] = CURL_SOCKET_BAD; /* no file descriptor */
  3114. conn->connection_id = -1; /* no ID */
  3115. conn->port = -1; /* unknown at this point */
  3116. conn->remote_port = -1; /* unknown */
  3117. /* Default protocol-independent behavior doesn't support persistent
  3118. connections, so we set this to force-close. Protocols that support
  3119. this need to set this to FALSE in their "curl_do" functions. */
  3120. conn->bits.close = TRUE;
  3121. /* Store creation time to help future close decision making */
  3122. conn->created = Curl_tvnow();
  3123. conn->data = data; /* Setup the association between this connection
  3124. and the SessionHandle */
  3125. conn->proxytype = data->set.proxytype; /* type */
  3126. #ifdef CURL_DISABLE_PROXY
  3127. conn->bits.proxy = FALSE;
  3128. conn->bits.httpproxy = FALSE;
  3129. conn->bits.proxy_user_passwd = FALSE;
  3130. conn->bits.tunnel_proxy = FALSE;
  3131. #else /* CURL_DISABLE_PROXY */
  3132. /* note that these two proxy bits are now just on what looks to be
  3133. requested, they may be altered down the road */
  3134. conn->bits.proxy = (data->set.str[STRING_PROXY] &&
  3135. *data->set.str[STRING_PROXY])?TRUE:FALSE;
  3136. conn->bits.httpproxy = (conn->bits.proxy &&
  3137. (conn->proxytype == CURLPROXY_HTTP ||
  3138. conn->proxytype == CURLPROXY_HTTP_1_0))?TRUE:FALSE;
  3139. conn->bits.proxy_user_passwd =
  3140. (NULL != data->set.str[STRING_PROXYUSERNAME])?TRUE:FALSE;
  3141. conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
  3142. #endif /* CURL_DISABLE_PROXY */
  3143. conn->bits.user_passwd = (NULL != data->set.str[STRING_USERNAME])?TRUE:FALSE;
  3144. conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
  3145. conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
  3146. conn->verifypeer = data->set.ssl.verifypeer;
  3147. conn->verifyhost = data->set.ssl.verifyhost;
  3148. conn->ip_version = data->set.ipver;
  3149. #if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
  3150. conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
  3151. conn->ntlm_auth_hlpr_pid = 0;
  3152. conn->challenge_header = NULL;
  3153. conn->response_header = NULL;
  3154. #endif
  3155. if(Curl_multi_pipeline_enabled(data->multi) &&
  3156. !conn->master_buffer) {
  3157. /* Allocate master_buffer to be used for pipelining */
  3158. conn->master_buffer = calloc(BUFSIZE, sizeof (char));
  3159. if(!conn->master_buffer)
  3160. goto error;
  3161. }
  3162. /* Initialize the pipeline lists */
  3163. conn->send_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
  3164. conn->recv_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
  3165. if(!conn->send_pipe || !conn->recv_pipe)
  3166. goto error;
  3167. #ifdef HAVE_GSSAPI
  3168. conn->data_prot = PROT_CLEAR;
  3169. #endif
  3170. /* Store the local bind parameters that will be used for this connection */
  3171. if(data->set.str[STRING_DEVICE]) {
  3172. conn->localdev = strdup(data->set.str[STRING_DEVICE]);
  3173. if(!conn->localdev)
  3174. goto error;
  3175. }
  3176. conn->localportrange = data->set.localportrange;
  3177. conn->localport = data->set.localport;
  3178. /* the close socket stuff needs to be copied to the connection struct as
  3179. it may live on without (this specific) SessionHandle */
  3180. conn->fclosesocket = data->set.fclosesocket;
  3181. conn->closesocket_client = data->set.closesocket_client;
  3182. return conn;
  3183. error:
  3184. Curl_llist_destroy(conn->send_pipe, NULL);
  3185. Curl_llist_destroy(conn->recv_pipe, NULL);
  3186. conn->send_pipe = NULL;
  3187. conn->recv_pipe = NULL;
  3188. Curl_safefree(conn->master_buffer);
  3189. Curl_safefree(conn->localdev);
  3190. Curl_safefree(conn);
  3191. return NULL;
  3192. }
  3193. static CURLcode findprotocol(struct SessionHandle *data,
  3194. struct connectdata *conn,
  3195. const char *protostr)
  3196. {
  3197. const struct Curl_handler * const *pp;
  3198. const struct Curl_handler *p;
  3199. /* Scan protocol handler table and match against 'protostr' to set a few
  3200. variables based on the URL. Now that the handler may be changed later
  3201. when the protocol specific setup function is called. */
  3202. for(pp = protocols; (p = *pp) != NULL; pp++) {
  3203. if(Curl_raw_equal(p->scheme, protostr)) {
  3204. /* Protocol found in table. Check if allowed */
  3205. if(!(data->set.allowed_protocols & p->protocol))
  3206. /* nope, get out */
  3207. break;
  3208. /* it is allowed for "normal" request, now do an extra check if this is
  3209. the result of a redirect */
  3210. if(data->state.this_is_a_follow &&
  3211. !(data->set.redir_protocols & p->protocol))
  3212. /* nope, get out */
  3213. break;
  3214. /* Perform setup complement if some. */
  3215. conn->handler = conn->given = p;
  3216. /* 'port' and 'remote_port' are set in setup_connection_internals() */
  3217. return CURLE_OK;
  3218. }
  3219. }
  3220. /* The protocol was not found in the table, but we don't have to assign it
  3221. to anything since it is already assigned to a dummy-struct in the
  3222. create_conn() function when the connectdata struct is allocated. */
  3223. failf(data, "Protocol %s not supported or disabled in " LIBCURL_NAME,
  3224. protostr);
  3225. return CURLE_UNSUPPORTED_PROTOCOL;
  3226. }
  3227. /*
  3228. * Parse URL and fill in the relevant members of the connection struct.
  3229. */
  3230. static CURLcode parseurlandfillconn(struct SessionHandle *data,
  3231. struct connectdata *conn,
  3232. bool *prot_missing,
  3233. char **userp, char **passwdp,
  3234. char **optionsp)
  3235. {
  3236. char *at;
  3237. char *fragment;
  3238. char *path = data->state.path;
  3239. char *query;
  3240. int rc;
  3241. char protobuf[16];
  3242. const char *protop;
  3243. CURLcode result;
  3244. bool rebuild_url = FALSE;
  3245. *prot_missing = FALSE;
  3246. /*************************************************************
  3247. * Parse the URL.
  3248. *
  3249. * We need to parse the url even when using the proxy, because we will need
  3250. * the hostname and port in case we are trying to SSL connect through the
  3251. * proxy -- and we don't know if we will need to use SSL until we parse the
  3252. * url ...
  3253. ************************************************************/
  3254. if((2 == sscanf(data->change.url, "%15[^:]:%[^\n]",
  3255. protobuf, path)) &&
  3256. Curl_raw_equal(protobuf, "file")) {
  3257. if(path[0] == '/' && path[1] == '/') {
  3258. /* Allow omitted hostname (e.g. file:/<path>). This is not strictly
  3259. * speaking a valid file: URL by RFC 1738, but treating file:/<path> as
  3260. * file://localhost/<path> is similar to how other schemes treat missing
  3261. * hostnames. See RFC 1808. */
  3262. /* This cannot be done with strcpy() in a portable manner, since the
  3263. memory areas overlap! */
  3264. memmove(path, path + 2, strlen(path + 2)+1);
  3265. }
  3266. /*
  3267. * we deal with file://<host>/<path> differently since it supports no
  3268. * hostname other than "localhost" and "127.0.0.1", which is unique among
  3269. * the URL protocols specified in RFC 1738
  3270. */
  3271. if(path[0] != '/') {
  3272. /* the URL included a host name, we ignore host names in file:// URLs
  3273. as the standards don't define what to do with them */
  3274. char *ptr=strchr(path, '/');
  3275. if(ptr) {
  3276. /* there was a slash present
  3277. RFC1738 (section 3.1, page 5) says:
  3278. The rest of the locator consists of data specific to the scheme,
  3279. and is known as the "url-path". It supplies the details of how the
  3280. specified resource can be accessed. Note that the "/" between the
  3281. host (or port) and the url-path is NOT part of the url-path.
  3282. As most agents use file://localhost/foo to get '/foo' although the
  3283. slash preceding foo is a separator and not a slash for the path,
  3284. a URL as file://localhost//foo must be valid as well, to refer to
  3285. the same file with an absolute path.
  3286. */
  3287. if(ptr[1] && ('/' == ptr[1]))
  3288. /* if there was two slashes, we skip the first one as that is then
  3289. used truly as a separator */
  3290. ptr++;
  3291. /* This cannot be made with strcpy, as the memory chunks overlap! */
  3292. memmove(path, ptr, strlen(ptr)+1);
  3293. }
  3294. }
  3295. protop = "file"; /* protocol string */
  3296. }
  3297. else {
  3298. /* clear path */
  3299. path[0]=0;
  3300. if(2 > sscanf(data->change.url,
  3301. "%15[^\n:]://%[^\n/?]%[^\n]",
  3302. protobuf,
  3303. conn->host.name, path)) {
  3304. /*
  3305. * The URL was badly formatted, let's try the browser-style _without_
  3306. * protocol specified like 'http://'.
  3307. */
  3308. rc = sscanf(data->change.url, "%[^\n/?]%[^\n]", conn->host.name, path);
  3309. if(1 > rc) {
  3310. /*
  3311. * We couldn't even get this format.
  3312. * djgpp 2.04 has a sscanf() bug where 'conn->host.name' is
  3313. * assigned, but the return value is EOF!
  3314. */
  3315. #if defined(__DJGPP__) && (DJGPP_MINOR == 4)
  3316. if(!(rc == -1 && *conn->host.name))
  3317. #endif
  3318. {
  3319. failf(data, "<url> malformed");
  3320. return CURLE_URL_MALFORMAT;
  3321. }
  3322. }
  3323. /*
  3324. * Since there was no protocol part specified, we guess what protocol it
  3325. * is based on the first letters of the server name.
  3326. */
  3327. /* Note: if you add a new protocol, please update the list in
  3328. * lib/version.c too! */
  3329. if(checkprefix("FTP.", conn->host.name))
  3330. protop = "ftp";
  3331. else if(checkprefix("DICT.", conn->host.name))
  3332. protop = "DICT";
  3333. else if(checkprefix("LDAP.", conn->host.name))
  3334. protop = "LDAP";
  3335. else if(checkprefix("IMAP.", conn->host.name))
  3336. protop = "IMAP";
  3337. else if(checkprefix("SMTP.", conn->host.name))
  3338. protop = "smtp";
  3339. else if(checkprefix("POP3.", conn->host.name))
  3340. protop = "pop3";
  3341. else {
  3342. protop = "http";
  3343. }
  3344. *prot_missing = TRUE; /* not given in URL */
  3345. }
  3346. else
  3347. protop = protobuf;
  3348. }
  3349. /* We search for '?' in the host name (but only on the right side of a
  3350. * @-letter to allow ?-letters in username and password) to handle things
  3351. * like http://example.com?param= (notice the missing '/').
  3352. */
  3353. at = strchr(conn->host.name, '@');
  3354. if(at)
  3355. query = strchr(at+1, '?');
  3356. else
  3357. query = strchr(conn->host.name, '?');
  3358. if(query) {
  3359. /* We must insert a slash before the '?'-letter in the URL. If the URL had
  3360. a slash after the '?', that is where the path currently begins and the
  3361. '?string' is still part of the host name.
  3362. We must move the trailing part from the host name and put it first in
  3363. the path. And have it all prefixed with a slash.
  3364. */
  3365. size_t hostlen = strlen(query);
  3366. size_t pathlen = strlen(path);
  3367. /* move the existing path plus the zero byte forward, to make room for
  3368. the host-name part */
  3369. memmove(path+hostlen+1, path, pathlen+1);
  3370. /* now copy the trailing host part in front of the existing path */
  3371. memcpy(path+1, query, hostlen);
  3372. path[0]='/'; /* prepend the missing slash */
  3373. rebuild_url = TRUE;
  3374. *query=0; /* now cut off the hostname at the ? */
  3375. }
  3376. else if(!path[0]) {
  3377. /* if there's no path set, use a single slash */
  3378. strcpy(path, "/");
  3379. rebuild_url = TRUE;
  3380. }
  3381. /* If the URL is malformatted (missing a '/' after hostname before path) we
  3382. * insert a slash here. The only letter except '/' we accept to start a path
  3383. * is '?'.
  3384. */
  3385. if(path[0] == '?') {
  3386. /* We need this function to deal with overlapping memory areas. We know
  3387. that the memory area 'path' points to is 'urllen' bytes big and that
  3388. is bigger than the path. Use +1 to move the zero byte too. */
  3389. memmove(&path[1], path, strlen(path)+1);
  3390. path[0] = '/';
  3391. rebuild_url = TRUE;
  3392. }
  3393. else {
  3394. /* sanitise paths and remove ../ and ./ sequences according to RFC3986 */
  3395. char *newp = Curl_dedotdotify(path);
  3396. if(!newp)
  3397. return CURLE_OUT_OF_MEMORY;
  3398. if(strcmp(newp, path)) {
  3399. rebuild_url = TRUE;
  3400. free(data->state.pathbuffer);
  3401. data->state.pathbuffer = newp;
  3402. data->state.path = newp;
  3403. path = newp;
  3404. }
  3405. else
  3406. free(newp);
  3407. }
  3408. /*
  3409. * "rebuild_url" means that one or more URL components have been modified so
  3410. * we need to generate an updated full version. We need the corrected URL
  3411. * when communicating over HTTP proxy and we don't know at this point if
  3412. * we're using a proxy or not.
  3413. */
  3414. if(rebuild_url) {
  3415. char *reurl;
  3416. size_t plen = strlen(path); /* new path, should be 1 byte longer than
  3417. the original */
  3418. size_t urllen = strlen(data->change.url); /* original URL length */
  3419. size_t prefixlen = strlen(conn->host.name);
  3420. if(!*prot_missing)
  3421. prefixlen += strlen(protop) + strlen("://");
  3422. reurl = malloc(urllen + 2); /* 2 for zerobyte + slash */
  3423. if(!reurl)
  3424. return CURLE_OUT_OF_MEMORY;
  3425. /* copy the prefix */
  3426. memcpy(reurl, data->change.url, prefixlen);
  3427. /* append the trailing piece + zerobyte */
  3428. memcpy(&reurl[prefixlen], path, plen + 1);
  3429. /* possible free the old one */
  3430. if(data->change.url_alloc) {
  3431. Curl_safefree(data->change.url);
  3432. data->change.url_alloc = FALSE;
  3433. }
  3434. infof(data, "Rebuilt URL to: %s\n", reurl);
  3435. data->change.url = reurl;
  3436. data->change.url_alloc = TRUE; /* free this later */
  3437. }
  3438. /*
  3439. * Parse the login details from the URL and strip them out of
  3440. * the host name
  3441. */
  3442. result = parse_url_login(data, conn, userp, passwdp, optionsp);
  3443. if(result != CURLE_OK)
  3444. return result;
  3445. if(conn->host.name[0] == '[') {
  3446. /* This looks like an IPv6 address literal. See if there is an address
  3447. scope. */
  3448. char *percent = strstr (conn->host.name, "%25");
  3449. if(percent) {
  3450. char *endp;
  3451. unsigned long scope = strtoul (percent + 3, &endp, 10);
  3452. if(*endp == ']') {
  3453. /* The address scope was well formed. Knock it out of the
  3454. hostname. */
  3455. memmove(percent, endp, strlen(endp)+1);
  3456. if(!data->state.this_is_a_follow)
  3457. /* Don't honour a scope given in a Location: header */
  3458. conn->scope = (unsigned int)scope;
  3459. }
  3460. else
  3461. infof(data, "Invalid IPv6 address format\n");
  3462. }
  3463. }
  3464. if(data->set.scope)
  3465. /* Override any scope that was set above. */
  3466. conn->scope = data->set.scope;
  3467. /* Remove the fragment part of the path. Per RFC 2396, this is always the
  3468. last part of the URI. We are looking for the first '#' so that we deal
  3469. gracefully with non conformant URI such as http://example.com#foo#bar. */
  3470. fragment = strchr(path, '#');
  3471. if(fragment) {
  3472. *fragment = 0;
  3473. /* we know the path part ended with a fragment, so we know the full URL
  3474. string does too and we need to cut it off from there so it isn't used
  3475. over proxy */
  3476. fragment = strchr(data->change.url, '#');
  3477. if(fragment)
  3478. *fragment = 0;
  3479. }
  3480. /*
  3481. * So if the URL was A://B/C#D,
  3482. * protop is A
  3483. * conn->host.name is B
  3484. * data->state.path is /C
  3485. */
  3486. return findprotocol(data, conn, protop);
  3487. }
  3488. /*
  3489. * If we're doing a resumed transfer, we need to setup our stuff
  3490. * properly.
  3491. */
  3492. static CURLcode setup_range(struct SessionHandle *data)
  3493. {
  3494. struct UrlState *s = &data->state;
  3495. s->resume_from = data->set.set_resume_from;
  3496. if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
  3497. if(s->rangestringalloc)
  3498. free(s->range);
  3499. if(s->resume_from)
  3500. s->range = aprintf("%" CURL_FORMAT_CURL_OFF_TU "-", s->resume_from);
  3501. else
  3502. s->range = strdup(data->set.str[STRING_SET_RANGE]);
  3503. s->rangestringalloc = (s->range)?TRUE:FALSE;
  3504. if(!s->range)
  3505. return CURLE_OUT_OF_MEMORY;
  3506. /* tell ourselves to fetch this range */
  3507. s->use_range = TRUE; /* enable range download */
  3508. }
  3509. else
  3510. s->use_range = FALSE; /* disable range download */
  3511. return CURLE_OK;
  3512. }
  3513. /*
  3514. * setup_connection_internals() -
  3515. *
  3516. * Setup connection internals specific to the requested protocol in the
  3517. * SessionHandle. This is inited and setup before the connection is made but
  3518. * is about the particular protocol that is to be used.
  3519. *
  3520. * This MUST get called after proxy magic has been figured out.
  3521. */
  3522. static CURLcode setup_connection_internals(struct connectdata *conn)
  3523. {
  3524. const struct Curl_handler * p;
  3525. CURLcode result;
  3526. /* in some case in the multi state-machine, we go back to the CONNECT state
  3527. and then a second (or third or...) call to this function will be made
  3528. without doing a DISCONNECT or DONE in between (since the connection is
  3529. yet in place) and therefore this function needs to first make sure
  3530. there's no lingering previous data allocated. */
  3531. Curl_free_request_state(conn->data);
  3532. memset(&conn->data->req, 0, sizeof(struct SingleRequest));
  3533. conn->data->req.maxdownload = -1;
  3534. conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
  3535. /* Perform setup complement if some. */
  3536. p = conn->handler;
  3537. if(p->setup_connection) {
  3538. result = (*p->setup_connection)(conn);
  3539. if(result != CURLE_OK)
  3540. return result;
  3541. p = conn->handler; /* May have changed. */
  3542. }
  3543. if(conn->port < 0)
  3544. /* we check for -1 here since if proxy was detected already, this
  3545. was very likely already set to the proxy port */
  3546. conn->port = p->defport;
  3547. /* only if remote_port was not already parsed off the URL we use the
  3548. default port number */
  3549. if(conn->remote_port < 0)
  3550. conn->remote_port = (unsigned short)conn->given->defport;
  3551. return CURLE_OK;
  3552. }
  3553. /*
  3554. * Curl_free_request_state() should free temp data that was allocated in the
  3555. * SessionHandle for this single request.
  3556. */
  3557. void Curl_free_request_state(struct SessionHandle *data)
  3558. {
  3559. Curl_safefree(data->req.protop);
  3560. }
  3561. #ifndef CURL_DISABLE_PROXY
  3562. /****************************************************************
  3563. * Checks if the host is in the noproxy list. returns true if it matches
  3564. * and therefore the proxy should NOT be used.
  3565. ****************************************************************/
  3566. static bool check_noproxy(const char* name, const char* no_proxy)
  3567. {
  3568. /* no_proxy=domain1.dom,host.domain2.dom
  3569. * (a comma-separated list of hosts which should
  3570. * not be proxied, or an asterisk to override
  3571. * all proxy variables)
  3572. */
  3573. size_t tok_start;
  3574. size_t tok_end;
  3575. const char* separator = ", ";
  3576. size_t no_proxy_len;
  3577. size_t namelen;
  3578. char *endptr;
  3579. if(no_proxy && no_proxy[0]) {
  3580. if(Curl_raw_equal("*", no_proxy)) {
  3581. return TRUE;
  3582. }
  3583. /* NO_PROXY was specified and it wasn't just an asterisk */
  3584. no_proxy_len = strlen(no_proxy);
  3585. endptr = strchr(name, ':');
  3586. if(endptr)
  3587. namelen = endptr - name;
  3588. else
  3589. namelen = strlen(name);
  3590. for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
  3591. while(tok_start < no_proxy_len &&
  3592. strchr(separator, no_proxy[tok_start]) != NULL) {
  3593. /* Look for the beginning of the token. */
  3594. ++tok_start;
  3595. }
  3596. if(tok_start == no_proxy_len)
  3597. break; /* It was all trailing separator chars, no more tokens. */
  3598. for(tok_end = tok_start; tok_end < no_proxy_len &&
  3599. strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
  3600. /* Look for the end of the token. */
  3601. ;
  3602. /* To match previous behaviour, where it was necessary to specify
  3603. * ".local.com" to prevent matching "notlocal.com", we will leave
  3604. * the '.' off.
  3605. */
  3606. if(no_proxy[tok_start] == '.')
  3607. ++tok_start;
  3608. if((tok_end - tok_start) <= namelen) {
  3609. /* Match the last part of the name to the domain we are checking. */
  3610. const char *checkn = name + namelen - (tok_end - tok_start);
  3611. if(Curl_raw_nequal(no_proxy + tok_start, checkn,
  3612. tok_end - tok_start)) {
  3613. if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
  3614. /* We either have an exact match, or the previous character is a .
  3615. * so it is within the same domain, so no proxy for this host.
  3616. */
  3617. return TRUE;
  3618. }
  3619. }
  3620. } /* if((tok_end - tok_start) <= namelen) */
  3621. } /* for(tok_start = 0; tok_start < no_proxy_len;
  3622. tok_start = tok_end + 1) */
  3623. } /* NO_PROXY was specified and it wasn't just an asterisk */
  3624. return FALSE;
  3625. }
  3626. /****************************************************************
  3627. * Detect what (if any) proxy to use. Remember that this selects a host
  3628. * name and is not limited to HTTP proxies only.
  3629. * The returned pointer must be freed by the caller (unless NULL)
  3630. ****************************************************************/
  3631. static char *detect_proxy(struct connectdata *conn)
  3632. {
  3633. char *proxy = NULL;
  3634. #ifndef CURL_DISABLE_HTTP
  3635. /* If proxy was not specified, we check for default proxy environment
  3636. * variables, to enable i.e Lynx compliance:
  3637. *
  3638. * http_proxy=http://some.server.dom:port/
  3639. * https_proxy=http://some.server.dom:port/
  3640. * ftp_proxy=http://some.server.dom:port/
  3641. * no_proxy=domain1.dom,host.domain2.dom
  3642. * (a comma-separated list of hosts which should
  3643. * not be proxied, or an asterisk to override
  3644. * all proxy variables)
  3645. * all_proxy=http://some.server.dom:port/
  3646. * (seems to exist for the CERN www lib. Probably
  3647. * the first to check for.)
  3648. *
  3649. * For compatibility, the all-uppercase versions of these variables are
  3650. * checked if the lowercase versions don't exist.
  3651. */
  3652. char *no_proxy=NULL;
  3653. char proxy_env[128];
  3654. no_proxy=curl_getenv("no_proxy");
  3655. if(!no_proxy)
  3656. no_proxy=curl_getenv("NO_PROXY");
  3657. if(!check_noproxy(conn->host.name, no_proxy)) {
  3658. /* It was not listed as without proxy */
  3659. const char *protop = conn->handler->scheme;
  3660. char *envp = proxy_env;
  3661. char *prox;
  3662. /* Now, build <protocol>_proxy and check for such a one to use */
  3663. while(*protop)
  3664. *envp++ = (char)tolower((int)*protop++);
  3665. /* append _proxy */
  3666. strcpy(envp, "_proxy");
  3667. /* read the protocol proxy: */
  3668. prox=curl_getenv(proxy_env);
  3669. /*
  3670. * We don't try the uppercase version of HTTP_PROXY because of
  3671. * security reasons:
  3672. *
  3673. * When curl is used in a webserver application
  3674. * environment (cgi or php), this environment variable can
  3675. * be controlled by the web server user by setting the
  3676. * http header 'Proxy:' to some value.
  3677. *
  3678. * This can cause 'internal' http/ftp requests to be
  3679. * arbitrarily redirected by any external attacker.
  3680. */
  3681. if(!prox && !Curl_raw_equal("http_proxy", proxy_env)) {
  3682. /* There was no lowercase variable, try the uppercase version: */
  3683. Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
  3684. prox=curl_getenv(proxy_env);
  3685. }
  3686. if(prox && *prox) { /* don't count "" strings */
  3687. proxy = prox; /* use this */
  3688. }
  3689. else {
  3690. proxy = curl_getenv("all_proxy"); /* default proxy to use */
  3691. if(!proxy)
  3692. proxy=curl_getenv("ALL_PROXY");
  3693. }
  3694. } /* if(!check_noproxy(conn->host.name, no_proxy)) - it wasn't specified
  3695. non-proxy */
  3696. if(no_proxy)
  3697. free(no_proxy);
  3698. #else /* !CURL_DISABLE_HTTP */
  3699. (void)conn;
  3700. #endif /* CURL_DISABLE_HTTP */
  3701. return proxy;
  3702. }
  3703. /*
  3704. * If this is supposed to use a proxy, we need to figure out the proxy
  3705. * host name, so that we can re-use an existing connection
  3706. * that may exist registered to the same proxy host.
  3707. * proxy will be freed before this function returns.
  3708. */
  3709. static CURLcode parse_proxy(struct SessionHandle *data,
  3710. struct connectdata *conn, char *proxy)
  3711. {
  3712. char *prox_portno;
  3713. char *endofprot;
  3714. /* We use 'proxyptr' to point to the proxy name from now on... */
  3715. char *proxyptr;
  3716. char *portptr;
  3717. char *atsign;
  3718. /* We do the proxy host string parsing here. We want the host name and the
  3719. * port name. Accept a protocol:// prefix
  3720. */
  3721. /* Parse the protocol part if present */
  3722. endofprot = strstr(proxy, "://");
  3723. if(endofprot) {
  3724. proxyptr = endofprot+3;
  3725. if(checkprefix("socks5h", proxy))
  3726. conn->proxytype = CURLPROXY_SOCKS5_HOSTNAME;
  3727. else if(checkprefix("socks5", proxy))
  3728. conn->proxytype = CURLPROXY_SOCKS5;
  3729. else if(checkprefix("socks4a", proxy))
  3730. conn->proxytype = CURLPROXY_SOCKS4A;
  3731. else if(checkprefix("socks4", proxy) || checkprefix("socks", proxy))
  3732. conn->proxytype = CURLPROXY_SOCKS4;
  3733. /* Any other xxx:// : change to http proxy */
  3734. }
  3735. else
  3736. proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
  3737. /* Is there a username and password given in this proxy url? */
  3738. atsign = strchr(proxyptr, '@');
  3739. if(atsign) {
  3740. CURLcode res = CURLE_OK;
  3741. char *proxyuser = NULL;
  3742. char *proxypasswd = NULL;
  3743. res = parse_login_details(proxyptr, atsign - proxyptr,
  3744. &proxyuser, &proxypasswd, NULL);
  3745. if(!res) {
  3746. /* found user and password, rip them out. note that we are
  3747. unescaping them, as there is otherwise no way to have a
  3748. username or password with reserved characters like ':' in
  3749. them. */
  3750. Curl_safefree(conn->proxyuser);
  3751. if(proxyuser && strlen(proxyuser) < MAX_CURL_USER_LENGTH)
  3752. conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
  3753. else
  3754. conn->proxyuser = strdup("");
  3755. if(!conn->proxyuser)
  3756. res = CURLE_OUT_OF_MEMORY;
  3757. else {
  3758. Curl_safefree(conn->proxypasswd);
  3759. if(proxypasswd && strlen(proxypasswd) < MAX_CURL_PASSWORD_LENGTH)
  3760. conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
  3761. else
  3762. conn->proxypasswd = strdup("");
  3763. if(!conn->proxypasswd)
  3764. res = CURLE_OUT_OF_MEMORY;
  3765. }
  3766. if(!res) {
  3767. conn->bits.proxy_user_passwd = TRUE; /* enable it */
  3768. atsign++; /* the right side of the @-letter */
  3769. if(atsign)
  3770. proxyptr = atsign; /* now use this instead */
  3771. else
  3772. res = CURLE_OUT_OF_MEMORY;
  3773. }
  3774. }
  3775. Curl_safefree(proxyuser);
  3776. Curl_safefree(proxypasswd);
  3777. if(res)
  3778. return res;
  3779. }
  3780. /* start scanning for port number at this point */
  3781. portptr = proxyptr;
  3782. /* detect and extract RFC2732-style IPv6-addresses */
  3783. if(*proxyptr == '[') {
  3784. char *ptr = ++proxyptr; /* advance beyond the initial bracket */
  3785. while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '%') ||
  3786. (*ptr == '.')))
  3787. ptr++;
  3788. if(*ptr == ']')
  3789. /* yeps, it ended nicely with a bracket as well */
  3790. *ptr++ = 0;
  3791. else
  3792. infof(data, "Invalid IPv6 address format\n");
  3793. portptr = ptr;
  3794. /* Note that if this didn't end with a bracket, we still advanced the
  3795. * proxyptr first, but I can't see anything wrong with that as no host
  3796. * name nor a numeric can legally start with a bracket.
  3797. */
  3798. }
  3799. /* Get port number off proxy.server.com:1080 */
  3800. prox_portno = strchr(portptr, ':');
  3801. if(prox_portno) {
  3802. *prox_portno = 0x0; /* cut off number from host name */
  3803. prox_portno ++;
  3804. /* now set the local port number */
  3805. conn->port = strtol(prox_portno, NULL, 10);
  3806. }
  3807. else {
  3808. if(proxyptr[0]=='/')
  3809. /* If the first character in the proxy string is a slash, fail
  3810. immediately. The following code will otherwise clear the string which
  3811. will lead to code running as if no proxy was set! */
  3812. return CURLE_COULDNT_RESOLVE_PROXY;
  3813. /* without a port number after the host name, some people seem to use
  3814. a slash so we strip everything from the first slash */
  3815. atsign = strchr(proxyptr, '/');
  3816. if(atsign)
  3817. *atsign = 0x0; /* cut off path part from host name */
  3818. if(data->set.proxyport)
  3819. /* None given in the proxy string, then get the default one if it is
  3820. given */
  3821. conn->port = data->set.proxyport;
  3822. }
  3823. /* now, clone the cleaned proxy host name */
  3824. conn->proxy.rawalloc = strdup(proxyptr);
  3825. conn->proxy.name = conn->proxy.rawalloc;
  3826. if(!conn->proxy.rawalloc)
  3827. return CURLE_OUT_OF_MEMORY;
  3828. return CURLE_OK;
  3829. }
  3830. /*
  3831. * Extract the user and password from the authentication string
  3832. */
  3833. static CURLcode parse_proxy_auth(struct SessionHandle *data,
  3834. struct connectdata *conn)
  3835. {
  3836. char proxyuser[MAX_CURL_USER_LENGTH]="";
  3837. char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
  3838. if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
  3839. strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
  3840. MAX_CURL_USER_LENGTH);
  3841. proxyuser[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
  3842. }
  3843. if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
  3844. strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
  3845. MAX_CURL_PASSWORD_LENGTH);
  3846. proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
  3847. }
  3848. conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
  3849. if(!conn->proxyuser)
  3850. return CURLE_OUT_OF_MEMORY;
  3851. conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
  3852. if(!conn->proxypasswd)
  3853. return CURLE_OUT_OF_MEMORY;
  3854. return CURLE_OK;
  3855. }
  3856. #endif /* CURL_DISABLE_PROXY */
  3857. /*
  3858. * parse_url_login()
  3859. *
  3860. * Parse the login details (user name, password and options) from the URL and
  3861. * strip them out of the host name
  3862. *
  3863. * Inputs: data->set.use_netrc (CURLOPT_NETRC)
  3864. * conn->host.name
  3865. *
  3866. * Outputs: (almost :- all currently undefined)
  3867. * conn->bits.user_passwd - non-zero if non-default passwords exist
  3868. * user - non-zero length if defined
  3869. * passwd - non-zero length if defined
  3870. * options - non-zero length if defined
  3871. * conn->host.name - remove user name and password
  3872. */
  3873. static CURLcode parse_url_login(struct SessionHandle *data,
  3874. struct connectdata *conn,
  3875. char **user, char **passwd, char **options)
  3876. {
  3877. CURLcode result = CURLE_OK;
  3878. char *userp = NULL;
  3879. char *passwdp = NULL;
  3880. char *optionsp = NULL;
  3881. /* At this point, we're hoping all the other special cases have
  3882. * been taken care of, so conn->host.name is at most
  3883. * [user[:password][;options]]@]hostname
  3884. *
  3885. * We need somewhere to put the embedded details, so do that first.
  3886. */
  3887. char *ptr = strchr(conn->host.name, '@');
  3888. char *login = conn->host.name;
  3889. DEBUGASSERT(!**user);
  3890. DEBUGASSERT(!**passwd);
  3891. DEBUGASSERT(!**options);
  3892. if(!ptr)
  3893. goto out;
  3894. /* We will now try to extract the
  3895. * possible login information in a string like:
  3896. * ftp://user:password@ftp.my.site:8021/README */
  3897. conn->host.name = ++ptr;
  3898. /* So the hostname is sane. Only bother interpreting the
  3899. * results if we could care. It could still be wasted
  3900. * work because it might be overtaken by the programmatically
  3901. * set user/passwd, but doing that first adds more cases here :-(
  3902. */
  3903. if(data->set.use_netrc == CURL_NETRC_REQUIRED)
  3904. goto out;
  3905. /* We could use the login information in the URL so extract it */
  3906. result = parse_login_details(login, ptr - login - 1,
  3907. &userp, &passwdp, &optionsp);
  3908. if(result != CURLE_OK)
  3909. goto out;
  3910. if(userp) {
  3911. char *newname;
  3912. /* We have a user in the URL */
  3913. conn->bits.userpwd_in_url = TRUE;
  3914. conn->bits.user_passwd = TRUE; /* enable user+password */
  3915. /* Decode the user */
  3916. newname = curl_easy_unescape(data, userp, 0, NULL);
  3917. if(!newname) {
  3918. result = CURLE_OUT_OF_MEMORY;
  3919. goto out;
  3920. }
  3921. free(*user);
  3922. *user = newname;
  3923. }
  3924. if(passwdp) {
  3925. /* We have a password in the URL so decode it */
  3926. char *newpasswd = curl_easy_unescape(data, passwdp, 0, NULL);
  3927. if(!newpasswd) {
  3928. result = CURLE_OUT_OF_MEMORY;
  3929. goto out;
  3930. }
  3931. free(*passwd);
  3932. *passwd = newpasswd;
  3933. }
  3934. if(optionsp) {
  3935. /* We have an options list in the URL so decode it */
  3936. char *newoptions = curl_easy_unescape(data, optionsp, 0, NULL);
  3937. if(!newoptions) {
  3938. result = CURLE_OUT_OF_MEMORY;
  3939. goto out;
  3940. }
  3941. free(*options);
  3942. *options = newoptions;
  3943. }
  3944. out:
  3945. Curl_safefree(userp);
  3946. Curl_safefree(passwdp);
  3947. Curl_safefree(optionsp);
  3948. return result;
  3949. }
  3950. /*
  3951. * parse_login_details()
  3952. *
  3953. * This is used to parse a login string for user name, password and options in
  3954. * the following formats:
  3955. *
  3956. * user
  3957. * user:password
  3958. * user:password;options
  3959. * user;options
  3960. * user;options:password
  3961. * :password
  3962. * :password;options
  3963. * ;options
  3964. * ;options:password
  3965. *
  3966. * Parameters:
  3967. *
  3968. * login [in] - The login string.
  3969. * len [in] - The length of the login string.
  3970. * userp [in/out] - The address where a pointer to newly allocated memory
  3971. * holding the user will be stored upon completion.
  3972. * passdwp [in/out] - The address where a pointer to newly allocated memory
  3973. * holding the password will be stored upon completion.
  3974. * optionsp [in/out] - The address where a pointer to newly allocated memory
  3975. * holding the options will be stored upon completion.
  3976. *
  3977. * Returns CURLE_OK on success.
  3978. */
  3979. static CURLcode parse_login_details(const char *login, const size_t len,
  3980. char **userp, char **passwdp,
  3981. char **optionsp)
  3982. {
  3983. CURLcode result = CURLE_OK;
  3984. char *ubuf = NULL;
  3985. char *pbuf = NULL;
  3986. char *obuf = NULL;
  3987. const char *psep = NULL;
  3988. const char *osep = NULL;
  3989. size_t ulen;
  3990. size_t plen;
  3991. size_t olen;
  3992. /* Attempt to find the password separator */
  3993. if(passwdp) {
  3994. psep = strchr(login, ':');
  3995. /* Within the constraint of the login string */
  3996. if(psep >= login + len)
  3997. psep = NULL;
  3998. }
  3999. /* Attempt to find the options separator */
  4000. if(optionsp) {
  4001. osep = strchr(login, ';');
  4002. /* Within the constraint of the login string */
  4003. if(osep >= login + len)
  4004. osep = NULL;
  4005. }
  4006. /* Calculate the portion lengths */
  4007. ulen = (psep ?
  4008. (size_t)(osep && psep > osep ? osep - login : psep - login) :
  4009. (osep ? (size_t)(osep - login) : len));
  4010. plen = (psep ?
  4011. (osep && osep > psep ? (size_t)(osep - psep) :
  4012. (size_t)(login + len - psep)) - 1 : 0);
  4013. olen = (osep ?
  4014. (psep && psep > osep ? (size_t)(psep - osep) :
  4015. (size_t)(login + len - osep)) - 1 : 0);
  4016. /* Allocate the user portion buffer */
  4017. if(userp && ulen) {
  4018. ubuf = malloc(ulen + 1);
  4019. if(!ubuf)
  4020. result = CURLE_OUT_OF_MEMORY;
  4021. }
  4022. /* Allocate the password portion buffer */
  4023. if(!result && passwdp && plen) {
  4024. pbuf = malloc(plen + 1);
  4025. if(!pbuf) {
  4026. Curl_safefree(ubuf);
  4027. result = CURLE_OUT_OF_MEMORY;
  4028. }
  4029. }
  4030. /* Allocate the options portion buffer */
  4031. if(!result && optionsp && olen) {
  4032. obuf = malloc(olen + 1);
  4033. if(!obuf) {
  4034. Curl_safefree(pbuf);
  4035. Curl_safefree(ubuf);
  4036. result = CURLE_OUT_OF_MEMORY;
  4037. }
  4038. }
  4039. if(!result) {
  4040. /* Store the user portion if necessary */
  4041. if(ubuf) {
  4042. memcpy(ubuf, login, ulen);
  4043. ubuf[ulen] = '\0';
  4044. Curl_safefree(*userp);
  4045. *userp = ubuf;
  4046. }
  4047. /* Store the password portion if necessary */
  4048. if(pbuf) {
  4049. memcpy(pbuf, psep + 1, plen);
  4050. pbuf[plen] = '\0';
  4051. Curl_safefree(*passwdp);
  4052. *passwdp = pbuf;
  4053. }
  4054. /* Store the options portion if necessary */
  4055. if(obuf) {
  4056. memcpy(obuf, osep + 1, olen);
  4057. obuf[olen] = '\0';
  4058. Curl_safefree(*optionsp);
  4059. *optionsp = obuf;
  4060. }
  4061. }
  4062. return result;
  4063. }
  4064. /*************************************************************
  4065. * Figure out the remote port number and fix it in the URL
  4066. *
  4067. * No matter if we use a proxy or not, we have to figure out the remote
  4068. * port number of various reasons.
  4069. *
  4070. * To be able to detect port number flawlessly, we must not confuse them
  4071. * IPv6-specified addresses in the [0::1] style. (RFC2732)
  4072. *
  4073. * The conn->host.name is currently [user:passwd@]host[:port] where host
  4074. * could be a hostname, IPv4 address or IPv6 address.
  4075. *
  4076. * The port number embedded in the URL is replaced, if necessary.
  4077. *************************************************************/
  4078. static CURLcode parse_remote_port(struct SessionHandle *data,
  4079. struct connectdata *conn)
  4080. {
  4081. char *portptr;
  4082. char endbracket;
  4083. /* Note that at this point, the IPv6 address cannot contain any scope
  4084. suffix as that has already been removed in the parseurlandfillconn()
  4085. function */
  4086. if((1 == sscanf(conn->host.name, "[%*45[0123456789abcdefABCDEF:.]%c",
  4087. &endbracket)) &&
  4088. (']' == endbracket)) {
  4089. /* this is a RFC2732-style specified IP-address */
  4090. conn->bits.ipv6_ip = TRUE;
  4091. conn->host.name++; /* skip over the starting bracket */
  4092. portptr = strchr(conn->host.name, ']');
  4093. if(portptr) {
  4094. *portptr++ = '\0'; /* zero terminate, killing the bracket */
  4095. if(':' != *portptr)
  4096. portptr = NULL; /* no port number available */
  4097. }
  4098. }
  4099. else {
  4100. #ifdef ENABLE_IPV6
  4101. struct in6_addr in6;
  4102. if(Curl_inet_pton(AF_INET6, conn->host.name, &in6) > 0) {
  4103. /* This is a numerical IPv6 address, meaning this is a wrongly formatted
  4104. URL */
  4105. failf(data, "IPv6 numerical address used in URL without brackets");
  4106. return CURLE_URL_MALFORMAT;
  4107. }
  4108. #endif
  4109. portptr = strrchr(conn->host.name, ':');
  4110. }
  4111. if(data->set.use_port && data->state.allow_port) {
  4112. /* if set, we use this and ignore the port possibly given in the URL */
  4113. conn->remote_port = (unsigned short)data->set.use_port;
  4114. if(portptr)
  4115. *portptr = '\0'; /* cut off the name there anyway - if there was a port
  4116. number - since the port number is to be ignored! */
  4117. if(conn->bits.httpproxy) {
  4118. /* we need to create new URL with the new port number */
  4119. char *url;
  4120. char type[12]="";
  4121. if(conn->bits.type_set)
  4122. snprintf(type, sizeof(type), ";type=%c",
  4123. data->set.prefer_ascii?'A':
  4124. (data->set.ftp_list_only?'D':'I'));
  4125. /*
  4126. * This synthesized URL isn't always right--suffixes like ;type=A are
  4127. * stripped off. It would be better to work directly from the original
  4128. * URL and simply replace the port part of it.
  4129. */
  4130. url = aprintf("%s://%s%s%s:%hu%s%s%s", conn->given->scheme,
  4131. conn->bits.ipv6_ip?"[":"", conn->host.name,
  4132. conn->bits.ipv6_ip?"]":"", conn->remote_port,
  4133. data->state.slash_removed?"/":"", data->state.path,
  4134. type);
  4135. if(!url)
  4136. return CURLE_OUT_OF_MEMORY;
  4137. if(data->change.url_alloc) {
  4138. Curl_safefree(data->change.url);
  4139. data->change.url_alloc = FALSE;
  4140. }
  4141. data->change.url = url;
  4142. data->change.url_alloc = TRUE;
  4143. }
  4144. }
  4145. else if(portptr) {
  4146. /* no CURLOPT_PORT given, extract the one from the URL */
  4147. char *rest;
  4148. long port;
  4149. port=strtol(portptr+1, &rest, 10); /* Port number must be decimal */
  4150. if((port < 0) || (port > 0xffff)) {
  4151. /* Single unix standard says port numbers are 16 bits long */
  4152. failf(data, "Port number out of range");
  4153. return CURLE_URL_MALFORMAT;
  4154. }
  4155. else if(rest != &portptr[1]) {
  4156. *portptr = '\0'; /* cut off the name there */
  4157. conn->remote_port = curlx_ultous(port);
  4158. }
  4159. else
  4160. /* Browser behavior adaptation. If there's a colon with no digits after,
  4161. just cut off the name there which makes us ignore the colon and just
  4162. use the default port. Firefox and Chrome both do that. */
  4163. *portptr = '\0';
  4164. }
  4165. return CURLE_OK;
  4166. }
  4167. /*
  4168. * Override the login details from the URL with that in the CURLOPT_USERPWD
  4169. * option or a .netrc file, if applicable.
  4170. */
  4171. static CURLcode override_login(struct SessionHandle *data,
  4172. struct connectdata *conn,
  4173. char **userp, char **passwdp, char **optionsp)
  4174. {
  4175. if(data->set.str[STRING_USERNAME]) {
  4176. free(*userp);
  4177. *userp = strdup(data->set.str[STRING_USERNAME]);
  4178. if(!*userp)
  4179. return CURLE_OUT_OF_MEMORY;
  4180. }
  4181. if(data->set.str[STRING_PASSWORD]) {
  4182. free(*passwdp);
  4183. *passwdp = strdup(data->set.str[STRING_PASSWORD]);
  4184. if(!*passwdp)
  4185. return CURLE_OUT_OF_MEMORY;
  4186. }
  4187. if(data->set.str[STRING_OPTIONS]) {
  4188. free(*optionsp);
  4189. *optionsp = strdup(data->set.str[STRING_OPTIONS]);
  4190. if(!*optionsp)
  4191. return CURLE_OUT_OF_MEMORY;
  4192. }
  4193. conn->bits.netrc = FALSE;
  4194. if(data->set.use_netrc != CURL_NETRC_IGNORED) {
  4195. int ret = Curl_parsenetrc(conn->host.name,
  4196. userp, passwdp,
  4197. data->set.str[STRING_NETRC_FILE]);
  4198. if(ret > 0) {
  4199. infof(data, "Couldn't find host %s in the "
  4200. DOT_CHAR "netrc file; using defaults\n",
  4201. conn->host.name);
  4202. }
  4203. else if(ret < 0 ) {
  4204. return CURLE_OUT_OF_MEMORY;
  4205. }
  4206. else {
  4207. /* set bits.netrc TRUE to remember that we got the name from a .netrc
  4208. file, so that it is safe to use even if we followed a Location: to a
  4209. different host or similar. */
  4210. conn->bits.netrc = TRUE;
  4211. conn->bits.user_passwd = TRUE; /* enable user+password */
  4212. }
  4213. }
  4214. return CURLE_OK;
  4215. }
  4216. /*
  4217. * Set the login details so they're available in the connection
  4218. */
  4219. static CURLcode set_login(struct connectdata *conn,
  4220. const char *user, const char *passwd,
  4221. const char *options)
  4222. {
  4223. CURLcode result = CURLE_OK;
  4224. /* If our protocol needs a password and we have none, use the defaults */
  4225. if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd) {
  4226. /* Store the default user */
  4227. conn->user = strdup(CURL_DEFAULT_USER);
  4228. /* Store the default password */
  4229. if(conn->user)
  4230. conn->passwd = strdup(CURL_DEFAULT_PASSWORD);
  4231. else
  4232. conn->passwd = NULL;
  4233. /* This is the default password, so DON'T set conn->bits.user_passwd */
  4234. }
  4235. else {
  4236. /* Store the user, zero-length if not set */
  4237. conn->user = strdup(user);
  4238. /* Store the password (only if user is present), zero-length if not set */
  4239. if(conn->user)
  4240. conn->passwd = strdup(passwd);
  4241. else
  4242. conn->passwd = NULL;
  4243. }
  4244. if(!conn->user || !conn->passwd)
  4245. result = CURLE_OUT_OF_MEMORY;
  4246. /* Store the options, null if not set */
  4247. if(!result && options[0]) {
  4248. conn->options = strdup(options);
  4249. if(!conn->options)
  4250. result = CURLE_OUT_OF_MEMORY;
  4251. }
  4252. return result;
  4253. }
  4254. /*************************************************************
  4255. * Resolve the address of the server or proxy
  4256. *************************************************************/
  4257. static CURLcode resolve_server(struct SessionHandle *data,
  4258. struct connectdata *conn,
  4259. bool *async)
  4260. {
  4261. CURLcode result=CURLE_OK;
  4262. long timeout_ms = Curl_timeleft(data, NULL, TRUE);
  4263. /*************************************************************
  4264. * Resolve the name of the server or proxy
  4265. *************************************************************/
  4266. if(conn->bits.reuse)
  4267. /* We're reusing the connection - no need to resolve anything, and
  4268. fix_hostname() was called already in create_conn() for the re-use
  4269. case. */
  4270. *async = FALSE;
  4271. else {
  4272. /* this is a fresh connect */
  4273. int rc;
  4274. struct Curl_dns_entry *hostaddr;
  4275. /* set a pointer to the hostname we display */
  4276. fix_hostname(data, conn, &conn->host);
  4277. if(!conn->proxy.name || !*conn->proxy.name) {
  4278. /* If not connecting via a proxy, extract the port from the URL, if it is
  4279. * there, thus overriding any defaults that might have been set above. */
  4280. conn->port = conn->remote_port; /* it is the same port */
  4281. /* Resolve target host right on */
  4282. rc = Curl_resolv_timeout(conn, conn->host.name, (int)conn->port,
  4283. &hostaddr, timeout_ms);
  4284. if(rc == CURLRESOLV_PENDING)
  4285. *async = TRUE;
  4286. else if(rc == CURLRESOLV_TIMEDOUT)
  4287. result = CURLE_OPERATION_TIMEDOUT;
  4288. else if(!hostaddr) {
  4289. failf(data, "Couldn't resolve host '%s'", conn->host.dispname);
  4290. result = CURLE_COULDNT_RESOLVE_HOST;
  4291. /* don't return yet, we need to clean up the timeout first */
  4292. }
  4293. }
  4294. else {
  4295. /* This is a proxy that hasn't been resolved yet. */
  4296. /* IDN-fix the proxy name */
  4297. fix_hostname(data, conn, &conn->proxy);
  4298. /* resolve proxy */
  4299. rc = Curl_resolv_timeout(conn, conn->proxy.name, (int)conn->port,
  4300. &hostaddr, timeout_ms);
  4301. if(rc == CURLRESOLV_PENDING)
  4302. *async = TRUE;
  4303. else if(rc == CURLRESOLV_TIMEDOUT)
  4304. result = CURLE_OPERATION_TIMEDOUT;
  4305. else if(!hostaddr) {
  4306. failf(data, "Couldn't resolve proxy '%s'", conn->proxy.dispname);
  4307. result = CURLE_COULDNT_RESOLVE_PROXY;
  4308. /* don't return yet, we need to clean up the timeout first */
  4309. }
  4310. }
  4311. DEBUGASSERT(conn->dns_entry == NULL);
  4312. conn->dns_entry = hostaddr;
  4313. }
  4314. return result;
  4315. }
  4316. /*
  4317. * Cleanup the connection just allocated before we can move along and use the
  4318. * previously existing one. All relevant data is copied over and old_conn is
  4319. * ready for freeing once this function returns.
  4320. */
  4321. static void reuse_conn(struct connectdata *old_conn,
  4322. struct connectdata *conn)
  4323. {
  4324. if(old_conn->proxy.rawalloc)
  4325. free(old_conn->proxy.rawalloc);
  4326. /* free the SSL config struct from this connection struct as this was
  4327. allocated in vain and is targeted for destruction */
  4328. Curl_free_ssl_config(&old_conn->ssl_config);
  4329. conn->data = old_conn->data;
  4330. /* get the user+password information from the old_conn struct since it may
  4331. * be new for this request even when we re-use an existing connection */
  4332. conn->bits.user_passwd = old_conn->bits.user_passwd;
  4333. if(conn->bits.user_passwd) {
  4334. /* use the new user name and password though */
  4335. Curl_safefree(conn->user);
  4336. Curl_safefree(conn->passwd);
  4337. conn->user = old_conn->user;
  4338. conn->passwd = old_conn->passwd;
  4339. old_conn->user = NULL;
  4340. old_conn->passwd = NULL;
  4341. }
  4342. conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
  4343. if(conn->bits.proxy_user_passwd) {
  4344. /* use the new proxy user name and proxy password though */
  4345. Curl_safefree(conn->proxyuser);
  4346. Curl_safefree(conn->proxypasswd);
  4347. conn->proxyuser = old_conn->proxyuser;
  4348. conn->proxypasswd = old_conn->proxypasswd;
  4349. old_conn->proxyuser = NULL;
  4350. old_conn->proxypasswd = NULL;
  4351. }
  4352. /* host can change, when doing keepalive with a proxy or if the case is
  4353. different this time etc */
  4354. Curl_safefree(conn->host.rawalloc);
  4355. conn->host=old_conn->host;
  4356. /* persist connection info in session handle */
  4357. Curl_persistconninfo(conn);
  4358. /* re-use init */
  4359. conn->bits.reuse = TRUE; /* yes, we're re-using here */
  4360. Curl_safefree(old_conn->user);
  4361. Curl_safefree(old_conn->passwd);
  4362. Curl_safefree(old_conn->proxyuser);
  4363. Curl_safefree(old_conn->proxypasswd);
  4364. Curl_safefree(old_conn->localdev);
  4365. Curl_llist_destroy(old_conn->send_pipe, NULL);
  4366. Curl_llist_destroy(old_conn->recv_pipe, NULL);
  4367. old_conn->send_pipe = NULL;
  4368. old_conn->recv_pipe = NULL;
  4369. Curl_safefree(old_conn->master_buffer);
  4370. }
  4371. /**
  4372. * create_conn() sets up a new connectdata struct, or re-uses an already
  4373. * existing one, and resolves host name.
  4374. *
  4375. * if this function returns CURLE_OK and *async is set to TRUE, the resolve
  4376. * response will be coming asynchronously. If *async is FALSE, the name is
  4377. * already resolved.
  4378. *
  4379. * @param data The sessionhandle pointer
  4380. * @param in_connect is set to the next connection data pointer
  4381. * @param async is set TRUE when an async DNS resolution is pending
  4382. * @see Curl_setup_conn()
  4383. *
  4384. * *NOTE* this function assigns the conn->data pointer!
  4385. */
  4386. static CURLcode create_conn(struct SessionHandle *data,
  4387. struct connectdata **in_connect,
  4388. bool *async)
  4389. {
  4390. CURLcode result = CURLE_OK;
  4391. struct connectdata *conn;
  4392. struct connectdata *conn_temp = NULL;
  4393. size_t urllen;
  4394. char *user = NULL;
  4395. char *passwd = NULL;
  4396. char *options = NULL;
  4397. bool reuse;
  4398. char *proxy = NULL;
  4399. bool prot_missing = FALSE;
  4400. bool no_connections_available = FALSE;
  4401. bool force_reuse;
  4402. size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
  4403. size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
  4404. *async = FALSE;
  4405. /*************************************************************
  4406. * Check input data
  4407. *************************************************************/
  4408. if(!data->change.url) {
  4409. result = CURLE_URL_MALFORMAT;
  4410. goto out;
  4411. }
  4412. /* First, split up the current URL in parts so that we can use the
  4413. parts for checking against the already present connections. In order
  4414. to not have to modify everything at once, we allocate a temporary
  4415. connection data struct and fill in for comparison purposes. */
  4416. conn = allocate_conn(data);
  4417. if(!conn) {
  4418. result = CURLE_OUT_OF_MEMORY;
  4419. goto out;
  4420. }
  4421. /* We must set the return variable as soon as possible, so that our
  4422. parent can cleanup any possible allocs we may have done before
  4423. any failure */
  4424. *in_connect = conn;
  4425. /* This initing continues below, see the comment "Continue connectdata
  4426. * initialization here" */
  4427. /***********************************************************
  4428. * We need to allocate memory to store the path in. We get the size of the
  4429. * full URL to be sure, and we need to make it at least 256 bytes since
  4430. * other parts of the code will rely on this fact
  4431. ***********************************************************/
  4432. #define LEAST_PATH_ALLOC 256
  4433. urllen=strlen(data->change.url);
  4434. if(urllen < LEAST_PATH_ALLOC)
  4435. urllen=LEAST_PATH_ALLOC;
  4436. /*
  4437. * We malloc() the buffers below urllen+2 to make room for 2 possibilities:
  4438. * 1 - an extra terminating zero
  4439. * 2 - an extra slash (in case a syntax like "www.host.com?moo" is used)
  4440. */
  4441. Curl_safefree(data->state.pathbuffer);
  4442. data->state.path = NULL;
  4443. data->state.pathbuffer = malloc(urllen+2);
  4444. if(NULL == data->state.pathbuffer) {
  4445. result = CURLE_OUT_OF_MEMORY; /* really bad error */
  4446. goto out;
  4447. }
  4448. data->state.path = data->state.pathbuffer;
  4449. conn->host.rawalloc = malloc(urllen+2);
  4450. if(NULL == conn->host.rawalloc) {
  4451. Curl_safefree(data->state.pathbuffer);
  4452. data->state.path = NULL;
  4453. result = CURLE_OUT_OF_MEMORY;
  4454. goto out;
  4455. }
  4456. conn->host.name = conn->host.rawalloc;
  4457. conn->host.name[0] = 0;
  4458. user = strdup("");
  4459. passwd = strdup("");
  4460. options = strdup("");
  4461. if(!user || !passwd || !options) {
  4462. result = CURLE_OUT_OF_MEMORY;
  4463. goto out;
  4464. }
  4465. result = parseurlandfillconn(data, conn, &prot_missing, &user, &passwd,
  4466. &options);
  4467. if(result != CURLE_OK)
  4468. goto out;
  4469. /*************************************************************
  4470. * No protocol part in URL was used, add it!
  4471. *************************************************************/
  4472. if(prot_missing) {
  4473. /* We're guessing prefixes here and if we're told to use a proxy or if
  4474. we're gonna follow a Location: later or... then we need the protocol
  4475. part added so that we have a valid URL. */
  4476. char *reurl;
  4477. reurl = aprintf("%s://%s", conn->handler->scheme, data->change.url);
  4478. if(!reurl) {
  4479. result = CURLE_OUT_OF_MEMORY;
  4480. goto out;
  4481. }
  4482. if(data->change.url_alloc) {
  4483. Curl_safefree(data->change.url);
  4484. data->change.url_alloc = FALSE;
  4485. }
  4486. data->change.url = reurl;
  4487. data->change.url_alloc = TRUE; /* free this later */
  4488. }
  4489. /*************************************************************
  4490. * If the protocol can't handle url query strings, then cut
  4491. * of the unhandable part
  4492. *************************************************************/
  4493. if((conn->given->flags&PROTOPT_NOURLQUERY)) {
  4494. char *path_q_sep = strchr(conn->data->state.path, '?');
  4495. if(path_q_sep) {
  4496. /* according to rfc3986, allow the query (?foo=bar)
  4497. also on protocols that can't handle it.
  4498. cut the string-part after '?'
  4499. */
  4500. /* terminate the string */
  4501. path_q_sep[0] = 0;
  4502. }
  4503. }
  4504. if(data->set.str[STRING_BEARER]) {
  4505. conn->xoauth2_bearer = strdup(data->set.str[STRING_BEARER]);
  4506. if(!conn->xoauth2_bearer) {
  4507. result = CURLE_OUT_OF_MEMORY;
  4508. goto out;
  4509. }
  4510. }
  4511. #ifndef CURL_DISABLE_PROXY
  4512. /*************************************************************
  4513. * Extract the user and password from the authentication string
  4514. *************************************************************/
  4515. if(conn->bits.proxy_user_passwd) {
  4516. result = parse_proxy_auth(data, conn);
  4517. if(result != CURLE_OK)
  4518. goto out;
  4519. }
  4520. /*************************************************************
  4521. * Detect what (if any) proxy to use
  4522. *************************************************************/
  4523. if(data->set.str[STRING_PROXY]) {
  4524. proxy = strdup(data->set.str[STRING_PROXY]);
  4525. /* if global proxy is set, this is it */
  4526. if(NULL == proxy) {
  4527. failf(data, "memory shortage");
  4528. result = CURLE_OUT_OF_MEMORY;
  4529. goto out;
  4530. }
  4531. }
  4532. if(data->set.str[STRING_NOPROXY] &&
  4533. check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY])) {
  4534. if(proxy) {
  4535. free(proxy); /* proxy is in exception list */
  4536. proxy = NULL;
  4537. }
  4538. }
  4539. else if(!proxy)
  4540. proxy = detect_proxy(conn);
  4541. if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
  4542. free(proxy); /* Don't bother with an empty proxy string or if the
  4543. protocol doesn't work with network */
  4544. proxy = NULL;
  4545. }
  4546. /***********************************************************************
  4547. * If this is supposed to use a proxy, we need to figure out the proxy host
  4548. * name, proxy type and port number, so that we can re-use an existing
  4549. * connection that may exist registered to the same proxy host.
  4550. ***********************************************************************/
  4551. if(proxy) {
  4552. result = parse_proxy(data, conn, proxy);
  4553. Curl_safefree(proxy); /* parse_proxy copies the proxy string */
  4554. if(result)
  4555. goto out;
  4556. if((conn->proxytype == CURLPROXY_HTTP) ||
  4557. (conn->proxytype == CURLPROXY_HTTP_1_0)) {
  4558. #ifdef CURL_DISABLE_HTTP
  4559. /* asking for a HTTP proxy is a bit funny when HTTP is disabled... */
  4560. result = CURLE_UNSUPPORTED_PROTOCOL;
  4561. goto out;
  4562. #else
  4563. /* force this connection's protocol to become HTTP if not already
  4564. compatible - if it isn't tunneling through */
  4565. if(!(conn->handler->protocol & CURLPROTO_HTTP) &&
  4566. !conn->bits.tunnel_proxy)
  4567. conn->handler = &Curl_handler_http;
  4568. conn->bits.httpproxy = TRUE;
  4569. #endif
  4570. }
  4571. else
  4572. conn->bits.httpproxy = FALSE; /* not a HTTP proxy */
  4573. conn->bits.proxy = TRUE;
  4574. }
  4575. else {
  4576. /* we aren't using the proxy after all... */
  4577. conn->bits.proxy = FALSE;
  4578. conn->bits.httpproxy = FALSE;
  4579. conn->bits.proxy_user_passwd = FALSE;
  4580. conn->bits.tunnel_proxy = FALSE;
  4581. }
  4582. #endif /* CURL_DISABLE_PROXY */
  4583. /*************************************************************
  4584. * If the protocol is using SSL and HTTP proxy is used, we set
  4585. * the tunnel_proxy bit.
  4586. *************************************************************/
  4587. if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
  4588. conn->bits.tunnel_proxy = TRUE;
  4589. /*************************************************************
  4590. * Figure out the remote port number and fix it in the URL
  4591. *************************************************************/
  4592. result = parse_remote_port(data, conn);
  4593. if(result != CURLE_OK)
  4594. goto out;
  4595. /* Check for overridden login details and set them accordingly so they
  4596. they are known when protocol->setup_connection is called! */
  4597. result = override_login(data, conn, &user, &passwd, &options);
  4598. if(result != CURLE_OK)
  4599. goto out;
  4600. result = set_login(conn, user, passwd, options);
  4601. if(result != CURLE_OK)
  4602. goto out;
  4603. /*************************************************************
  4604. * Setup internals depending on protocol. Needs to be done after
  4605. * we figured out what/if proxy to use.
  4606. *************************************************************/
  4607. result = setup_connection_internals(conn);
  4608. if(result != CURLE_OK)
  4609. goto out;
  4610. conn->recv[FIRSTSOCKET] = Curl_recv_plain;
  4611. conn->send[FIRSTSOCKET] = Curl_send_plain;
  4612. conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
  4613. conn->send[SECONDARYSOCKET] = Curl_send_plain;
  4614. /***********************************************************************
  4615. * file: is a special case in that it doesn't need a network connection
  4616. ***********************************************************************/
  4617. #ifndef CURL_DISABLE_FILE
  4618. if(conn->handler->flags & PROTOPT_NONETWORK) {
  4619. bool done;
  4620. /* this is supposed to be the connect function so we better at least check
  4621. that the file is present here! */
  4622. DEBUGASSERT(conn->handler->connect_it);
  4623. result = conn->handler->connect_it(conn, &done);
  4624. /* Setup a "faked" transfer that'll do nothing */
  4625. if(CURLE_OK == result) {
  4626. conn->data = data;
  4627. conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
  4628. ConnectionStore(data, conn);
  4629. /*
  4630. * Setup whatever necessary for a resumed transfer
  4631. */
  4632. result = setup_range(data);
  4633. if(result) {
  4634. DEBUGASSERT(conn->handler->done);
  4635. /* we ignore the return code for the protocol-specific DONE */
  4636. (void)conn->handler->done(conn, result, FALSE);
  4637. goto out;
  4638. }
  4639. Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
  4640. -1, NULL); /* no upload */
  4641. }
  4642. /* since we skip do_init() */
  4643. do_init(conn);
  4644. goto out;
  4645. }
  4646. #endif
  4647. /* Get a cloned copy of the SSL config situation stored in the
  4648. connection struct. But to get this going nicely, we must first make
  4649. sure that the strings in the master copy are pointing to the correct
  4650. strings in the session handle strings array!
  4651. Keep in mind that the pointers in the master copy are pointing to strings
  4652. that will be freed as part of the SessionHandle struct, but all cloned
  4653. copies will be separately allocated.
  4654. */
  4655. data->set.ssl.CApath = data->set.str[STRING_SSL_CAPATH];
  4656. data->set.ssl.CAfile = data->set.str[STRING_SSL_CAFILE];
  4657. data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE];
  4658. data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT];
  4659. data->set.ssl.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
  4660. data->set.ssl.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
  4661. data->set.ssl.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST];
  4662. #ifdef USE_TLS_SRP
  4663. data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME];
  4664. data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD];
  4665. #endif
  4666. if(!Curl_clone_ssl_config(&data->set.ssl, &conn->ssl_config)) {
  4667. result = CURLE_OUT_OF_MEMORY;
  4668. goto out;
  4669. }
  4670. /*************************************************************
  4671. * Check the current list of connections to see if we can
  4672. * re-use an already existing one or if we have to create a
  4673. * new one.
  4674. *************************************************************/
  4675. /* reuse_fresh is TRUE if we are told to use a new connection by force, but
  4676. we only acknowledge this option if this is not a re-used connection
  4677. already (which happens due to follow-location or during a HTTP
  4678. authentication phase). */
  4679. if(data->set.reuse_fresh && !data->state.this_is_a_follow)
  4680. reuse = FALSE;
  4681. else
  4682. reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse);
  4683. /* If we found a reusable connection, we may still want to
  4684. open a new connection if we are pipelining. */
  4685. if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) {
  4686. size_t pipelen = conn_temp->send_pipe->size + conn_temp->recv_pipe->size;
  4687. if(pipelen > 0) {
  4688. infof(data, "Found connection %ld, with requests in the pipe (%zu)\n",
  4689. conn_temp->connection_id, pipelen);
  4690. if(conn_temp->bundle->num_connections < max_host_connections &&
  4691. data->state.conn_cache->num_connections < max_total_connections) {
  4692. /* We want a new connection anyway */
  4693. reuse = FALSE;
  4694. infof(data, "We can reuse, but we want a new connection anyway\n");
  4695. }
  4696. }
  4697. }
  4698. if(reuse) {
  4699. /*
  4700. * We already have a connection for this, we got the former connection
  4701. * in the conn_temp variable and thus we need to cleanup the one we
  4702. * just allocated before we can move along and use the previously
  4703. * existing one.
  4704. */
  4705. conn_temp->inuse = TRUE; /* mark this as being in use so that no other
  4706. handle in a multi stack may nick it */
  4707. reuse_conn(conn, conn_temp);
  4708. free(conn); /* we don't need this anymore */
  4709. conn = conn_temp;
  4710. *in_connect = conn;
  4711. /* set a pointer to the hostname we display */
  4712. fix_hostname(data, conn, &conn->host);
  4713. infof(data, "Re-using existing connection! (#%ld) with host %s\n",
  4714. conn->connection_id,
  4715. conn->proxy.name?conn->proxy.dispname:conn->host.dispname);
  4716. }
  4717. else {
  4718. /* We have decided that we want a new connection. However, we may not
  4719. be able to do that if we have reached the limit of how many
  4720. connections we are allowed to open. */
  4721. struct connectbundle *bundle;
  4722. bundle = Curl_conncache_find_bundle(data->state.conn_cache,
  4723. conn->host.name);
  4724. if(max_host_connections > 0 && bundle &&
  4725. (bundle->num_connections >= max_host_connections)) {
  4726. struct connectdata *conn_candidate;
  4727. /* The bundle is full. Let's see if we can kill a connection. */
  4728. conn_candidate = find_oldest_idle_connection_in_bundle(data, bundle);
  4729. if(conn_candidate) {
  4730. /* Set the connection's owner correctly, then kill it */
  4731. conn_candidate->data = data;
  4732. (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
  4733. }
  4734. else
  4735. no_connections_available = TRUE;
  4736. }
  4737. if(max_total_connections > 0 &&
  4738. (data->state.conn_cache->num_connections >= max_total_connections)) {
  4739. struct connectdata *conn_candidate;
  4740. /* The cache is full. Let's see if we can kill a connection. */
  4741. conn_candidate = find_oldest_idle_connection(data);
  4742. if(conn_candidate) {
  4743. /* Set the connection's owner correctly, then kill it */
  4744. conn_candidate->data = data;
  4745. (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
  4746. }
  4747. else
  4748. no_connections_available = TRUE;
  4749. }
  4750. if(no_connections_available) {
  4751. infof(data, "No connections available.\n");
  4752. conn_free(conn);
  4753. *in_connect = NULL;
  4754. result = CURLE_NO_CONNECTION_AVAILABLE;
  4755. goto out;
  4756. }
  4757. else {
  4758. /*
  4759. * This is a brand new connection, so let's store it in the connection
  4760. * cache of ours!
  4761. */
  4762. ConnectionStore(data, conn);
  4763. }
  4764. }
  4765. /* Mark the connection as used */
  4766. conn->inuse = TRUE;
  4767. /* Setup and init stuff before DO starts, in preparing for the transfer. */
  4768. do_init(conn);
  4769. /*
  4770. * Setup whatever necessary for a resumed transfer
  4771. */
  4772. result = setup_range(data);
  4773. if(result)
  4774. goto out;
  4775. /* Continue connectdata initialization here. */
  4776. /*
  4777. * Inherit the proper values from the urldata struct AFTER we have arranged
  4778. * the persistent connection stuff
  4779. */
  4780. conn->fread_func = data->set.fread_func;
  4781. conn->fread_in = data->set.in;
  4782. conn->seek_func = data->set.seek_func;
  4783. conn->seek_client = data->set.seek_client;
  4784. /*************************************************************
  4785. * Resolve the address of the server or proxy
  4786. *************************************************************/
  4787. result = resolve_server(data, conn, async);
  4788. out:
  4789. Curl_safefree(options);
  4790. Curl_safefree(passwd);
  4791. Curl_safefree(user);
  4792. Curl_safefree(proxy);
  4793. return result;
  4794. }
  4795. /* Curl_setup_conn() is called after the name resolve initiated in
  4796. * create_conn() is all done.
  4797. *
  4798. * Curl_setup_conn() also handles reused connections
  4799. *
  4800. * conn->data MUST already have been setup fine (in create_conn)
  4801. */
  4802. CURLcode Curl_setup_conn(struct connectdata *conn,
  4803. bool *protocol_done)
  4804. {
  4805. CURLcode result = CURLE_OK;
  4806. struct SessionHandle *data = conn->data;
  4807. Curl_pgrsTime(data, TIMER_NAMELOOKUP);
  4808. if(conn->handler->flags & PROTOPT_NONETWORK) {
  4809. /* nothing to setup when not using a network */
  4810. *protocol_done = TRUE;
  4811. return result;
  4812. }
  4813. *protocol_done = FALSE; /* default to not done */
  4814. /* set proxy_connect_closed to false unconditionally already here since it
  4815. is used strictly to provide extra information to a parent function in the
  4816. case of proxy CONNECT failures and we must make sure we don't have it
  4817. lingering set from a previous invoke */
  4818. conn->bits.proxy_connect_closed = FALSE;
  4819. /*
  4820. * Set user-agent. Used for HTTP, but since we can attempt to tunnel
  4821. * basically anything through a http proxy we can't limit this based on
  4822. * protocol.
  4823. */
  4824. if(data->set.str[STRING_USERAGENT]) {
  4825. Curl_safefree(conn->allocptr.uagent);
  4826. conn->allocptr.uagent =
  4827. aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
  4828. if(!conn->allocptr.uagent)
  4829. return CURLE_OUT_OF_MEMORY;
  4830. }
  4831. data->req.headerbytecount = 0;
  4832. #ifdef CURL_DO_LINEEND_CONV
  4833. data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
  4834. #endif /* CURL_DO_LINEEND_CONV */
  4835. /* set start time here for timeout purposes in the connect procedure, it
  4836. is later set again for the progress meter purpose */
  4837. conn->now = Curl_tvnow();
  4838. if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
  4839. conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
  4840. result = Curl_connecthost(conn, conn->dns_entry);
  4841. if(result)
  4842. return result;
  4843. }
  4844. else {
  4845. Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
  4846. Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
  4847. conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
  4848. *protocol_done = TRUE;
  4849. Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
  4850. Curl_verboseconnect(conn);
  4851. }
  4852. conn->now = Curl_tvnow(); /* time this *after* the connect is done, we
  4853. set this here perhaps a second time */
  4854. #ifdef __EMX__
  4855. /*
  4856. * This check is quite a hack. We're calling _fsetmode to fix the problem
  4857. * with fwrite converting newline characters (you get mangled text files,
  4858. * and corrupted binary files when you download to stdout and redirect it to
  4859. * a file).
  4860. */
  4861. if((data->set.out)->_handle == NULL) {
  4862. _fsetmode(stdout, "b");
  4863. }
  4864. #endif
  4865. return result;
  4866. }
  4867. CURLcode Curl_connect(struct SessionHandle *data,
  4868. struct connectdata **in_connect,
  4869. bool *asyncp,
  4870. bool *protocol_done)
  4871. {
  4872. CURLcode code;
  4873. *asyncp = FALSE; /* assume synchronous resolves by default */
  4874. /* call the stuff that needs to be called */
  4875. code = create_conn(data, in_connect, asyncp);
  4876. if(CURLE_OK == code) {
  4877. /* no error */
  4878. if((*in_connect)->send_pipe->size || (*in_connect)->recv_pipe->size)
  4879. /* pipelining */
  4880. *protocol_done = TRUE;
  4881. else if(!*asyncp) {
  4882. /* DNS resolution is done: that's either because this is a reused
  4883. connection, in which case DNS was unnecessary, or because DNS
  4884. really did finish already (synch resolver/fast async resolve) */
  4885. code = Curl_setup_conn(*in_connect, protocol_done);
  4886. }
  4887. }
  4888. if(code == CURLE_NO_CONNECTION_AVAILABLE) {
  4889. *in_connect = NULL;
  4890. return code;
  4891. }
  4892. if(code && *in_connect) {
  4893. /* We're not allowed to return failure with memory left allocated
  4894. in the connectdata struct, free those here */
  4895. Curl_disconnect(*in_connect, FALSE); /* close the connection */
  4896. *in_connect = NULL; /* return a NULL */
  4897. }
  4898. return code;
  4899. }
  4900. CURLcode Curl_done(struct connectdata **connp,
  4901. CURLcode status, /* an error if this is called after an
  4902. error was detected */
  4903. bool premature)
  4904. {
  4905. CURLcode result;
  4906. struct connectdata *conn;
  4907. struct SessionHandle *data;
  4908. DEBUGASSERT(*connp);
  4909. conn = *connp;
  4910. data = conn->data;
  4911. if(conn->bits.done)
  4912. /* Stop if Curl_done() has already been called */
  4913. return CURLE_OK;
  4914. Curl_getoff_all_pipelines(data, conn);
  4915. if((conn->send_pipe->size + conn->recv_pipe->size != 0 &&
  4916. !data->set.reuse_forbid &&
  4917. !conn->bits.close))
  4918. /* Stop if pipeline is not empty and we do not have to close
  4919. connection. */
  4920. return CURLE_OK;
  4921. conn->bits.done = TRUE; /* called just now! */
  4922. /* Cleanup possible redirect junk */
  4923. if(data->req.newurl) {
  4924. free(data->req.newurl);
  4925. data->req.newurl = NULL;
  4926. }
  4927. if(data->req.location) {
  4928. free(data->req.location);
  4929. data->req.location = NULL;
  4930. }
  4931. Curl_resolver_cancel(conn);
  4932. if(conn->dns_entry) {
  4933. Curl_resolv_unlock(data, conn->dns_entry); /* done with this */
  4934. conn->dns_entry = NULL;
  4935. }
  4936. switch(status) {
  4937. case CURLE_ABORTED_BY_CALLBACK:
  4938. case CURLE_READ_ERROR:
  4939. case CURLE_WRITE_ERROR:
  4940. /* When we're aborted due to a callback return code it basically have to
  4941. be counted as premature as there is trouble ahead if we don't. We have
  4942. many callbacks and protocols work differently, we could potentially do
  4943. this more fine-grained in the future. */
  4944. premature = TRUE;
  4945. default:
  4946. break;
  4947. }
  4948. /* this calls the protocol-specific function pointer previously set */
  4949. if(conn->handler->done)
  4950. result = conn->handler->done(conn, status, premature);
  4951. else
  4952. result = CURLE_OK;
  4953. if(Curl_pgrsDone(conn) && !result)
  4954. result = CURLE_ABORTED_BY_CALLBACK;
  4955. /* if the transfer was completed in a paused state there can be buffered
  4956. data left to write and then kill */
  4957. if(data->state.tempwrite) {
  4958. free(data->state.tempwrite);
  4959. data->state.tempwrite = NULL;
  4960. }
  4961. /* if data->set.reuse_forbid is TRUE, it means the libcurl client has
  4962. forced us to close this no matter what we think.
  4963. if conn->bits.close is TRUE, it means that the connection should be
  4964. closed in spite of all our efforts to be nice, due to protocol
  4965. restrictions in our or the server's end
  4966. if premature is TRUE, it means this connection was said to be DONE before
  4967. the entire request operation is complete and thus we can't know in what
  4968. state it is for re-using, so we're forced to close it. In a perfect world
  4969. we can add code that keep track of if we really must close it here or not,
  4970. but currently we have no such detail knowledge.
  4971. */
  4972. if(data->set.reuse_forbid || conn->bits.close || premature) {
  4973. CURLcode res2 = Curl_disconnect(conn, premature); /* close connection */
  4974. /* If we had an error already, make sure we return that one. But
  4975. if we got a new error, return that. */
  4976. if(!result && res2)
  4977. result = res2;
  4978. }
  4979. else {
  4980. /* the connection is no longer in use */
  4981. if(ConnectionDone(data, conn)) {
  4982. /* remember the most recently used connection */
  4983. data->state.lastconnect = conn;
  4984. infof(data, "Connection #%ld to host %s left intact\n",
  4985. conn->connection_id,
  4986. conn->bits.httpproxy?conn->proxy.dispname:conn->host.dispname);
  4987. }
  4988. else
  4989. data->state.lastconnect = NULL;
  4990. }
  4991. *connp = NULL; /* to make the caller of this function better detect that
  4992. this was either closed or handed over to the connection
  4993. cache here, and therefore cannot be used from this point on
  4994. */
  4995. Curl_free_request_state(data);
  4996. return result;
  4997. }
  4998. /*
  4999. * do_init() inits the readwrite session. This is inited each time (in the DO
  5000. * function before the protocol-specific DO functions are invoked) for a
  5001. * transfer, sometimes multiple times on the same SessionHandle. Make sure
  5002. * nothing in here depends on stuff that are setup dynamically for the
  5003. * transfer.
  5004. */
  5005. static CURLcode do_init(struct connectdata *conn)
  5006. {
  5007. struct SessionHandle *data = conn->data;
  5008. struct SingleRequest *k = &data->req;
  5009. conn->bits.done = FALSE; /* Curl_done() is not called yet */
  5010. conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to use */
  5011. data->state.expect100header = FALSE;
  5012. if(data->set.opt_no_body)
  5013. /* in HTTP lingo, no body means using the HEAD request... */
  5014. data->set.httpreq = HTTPREQ_HEAD;
  5015. else if(HTTPREQ_HEAD == data->set.httpreq)
  5016. /* ... but if unset there really is no perfect method that is the
  5017. "opposite" of HEAD but in reality most people probably think GET
  5018. then. The important thing is that we can't let it remain HEAD if the
  5019. opt_no_body is set FALSE since then we'll behave wrong when getting
  5020. HTTP. */
  5021. data->set.httpreq = HTTPREQ_GET;
  5022. k->start = Curl_tvnow(); /* start time */
  5023. k->now = k->start; /* current time is now */
  5024. k->header = TRUE; /* assume header */
  5025. k->bytecount = 0;
  5026. k->buf = data->state.buffer;
  5027. k->uploadbuf = data->state.uploadbuffer;
  5028. k->hbufp = data->state.headerbuff;
  5029. k->ignorebody=FALSE;
  5030. Curl_speedinit(data);
  5031. Curl_pgrsSetUploadCounter(data, 0);
  5032. Curl_pgrsSetDownloadCounter(data, 0);
  5033. return CURLE_OK;
  5034. }
  5035. /*
  5036. * do_complete is called when the DO actions are complete.
  5037. *
  5038. * We init chunking and trailer bits to their default values here immediately
  5039. * before receiving any header data for the current request in the pipeline.
  5040. */
  5041. static void do_complete(struct connectdata *conn)
  5042. {
  5043. conn->data->req.chunk=FALSE;
  5044. conn->data->req.maxfd = (conn->sockfd>conn->writesockfd?
  5045. conn->sockfd:conn->writesockfd)+1;
  5046. Curl_pgrsTime(conn->data, TIMER_PRETRANSFER);
  5047. }
  5048. CURLcode Curl_do(struct connectdata **connp, bool *done)
  5049. {
  5050. CURLcode result=CURLE_OK;
  5051. struct connectdata *conn = *connp;
  5052. struct SessionHandle *data = conn->data;
  5053. if(conn->handler->do_it) {
  5054. /* generic protocol-specific function pointer set in curl_connect() */
  5055. result = conn->handler->do_it(conn, done);
  5056. /* This was formerly done in transfer.c, but we better do it here */
  5057. if((CURLE_SEND_ERROR == result) && conn->bits.reuse) {
  5058. /*
  5059. * If the connection is using an easy handle, call reconnect
  5060. * to re-establish the connection. Otherwise, let the multi logic
  5061. * figure out how to re-establish the connection.
  5062. */
  5063. if(!data->multi) {
  5064. result = Curl_reconnect_request(connp);
  5065. if(result == CURLE_OK) {
  5066. /* ... finally back to actually retry the DO phase */
  5067. conn = *connp; /* re-assign conn since Curl_reconnect_request
  5068. creates a new connection */
  5069. result = conn->handler->do_it(conn, done);
  5070. }
  5071. }
  5072. else
  5073. return result;
  5074. }
  5075. if((result == CURLE_OK) && *done)
  5076. /* do_complete must be called after the protocol-specific DO function */
  5077. do_complete(conn);
  5078. }
  5079. return result;
  5080. }
  5081. /*
  5082. * Curl_do_more() is called during the DO_MORE multi state. It is basically a
  5083. * second stage DO state which (wrongly) was introduced to support FTP's
  5084. * second connection.
  5085. *
  5086. * TODO: A future libcurl should be able to work away this state.
  5087. *
  5088. * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to
  5089. * DOING state there's more work to do!
  5090. */
  5091. CURLcode Curl_do_more(struct connectdata *conn, int *complete)
  5092. {
  5093. CURLcode result=CURLE_OK;
  5094. *complete = 0;
  5095. if(conn->handler->do_more)
  5096. result = conn->handler->do_more(conn, complete);
  5097. if(!result && (*complete == 1))
  5098. /* do_complete must be called after the protocol-specific DO function */
  5099. do_complete(conn);
  5100. return result;
  5101. }