url.c 177 KB

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