url.c 180 KB

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