url.c 150 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2018, 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 https://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. #ifdef HAVE_SYS_UN_H
  46. #include <sys/un.h>
  47. #endif
  48. #ifndef HAVE_SOCKET
  49. #error "We can't compile without socket() support!"
  50. #endif
  51. #include <limits.h>
  52. #ifdef USE_LIBIDN2
  53. #include <idn2.h>
  54. #elif defined(USE_WIN32_IDN)
  55. /* prototype for curl_win32_idn_to_ascii() */
  56. bool curl_win32_idn_to_ascii(const char *in, char **out);
  57. #endif /* USE_LIBIDN2 */
  58. #include "urldata.h"
  59. #include "netrc.h"
  60. #include "formdata.h"
  61. #include "mime.h"
  62. #include "vtls/vtls.h"
  63. #include "hostip.h"
  64. #include "transfer.h"
  65. #include "sendf.h"
  66. #include "progress.h"
  67. #include "cookie.h"
  68. #include "strcase.h"
  69. #include "strerror.h"
  70. #include "escape.h"
  71. #include "strtok.h"
  72. #include "share.h"
  73. #include "content_encoding.h"
  74. #include "http_digest.h"
  75. #include "http_negotiate.h"
  76. #include "select.h"
  77. #include "multiif.h"
  78. #include "easyif.h"
  79. #include "speedcheck.h"
  80. #include "warnless.h"
  81. #include "non-ascii.h"
  82. #include "inet_pton.h"
  83. #include "getinfo.h"
  84. /* And now for the protocols */
  85. #include "ftp.h"
  86. #include "dict.h"
  87. #include "telnet.h"
  88. #include "tftp.h"
  89. #include "http.h"
  90. #include "http2.h"
  91. #include "file.h"
  92. #include "curl_ldap.h"
  93. #include "ssh.h"
  94. #include "imap.h"
  95. #include "url.h"
  96. #include "connect.h"
  97. #include "inet_ntop.h"
  98. #include "http_ntlm.h"
  99. #include "curl_ntlm_wb.h"
  100. #include "socks.h"
  101. #include "curl_rtmp.h"
  102. #include "gopher.h"
  103. #include "http_proxy.h"
  104. #include "conncache.h"
  105. #include "multihandle.h"
  106. #include "pipeline.h"
  107. #include "dotdot.h"
  108. #include "strdup.h"
  109. #include "setopt.h"
  110. /* The last 3 #include files should be in this order */
  111. #include "curl_printf.h"
  112. #include "curl_memory.h"
  113. #include "memdebug.h"
  114. static void conn_free(struct connectdata *conn);
  115. static void free_fixed_hostname(struct hostname *host);
  116. static CURLcode parse_url_login(struct Curl_easy *data,
  117. struct connectdata *conn,
  118. char **userptr, char **passwdptr,
  119. char **optionsptr);
  120. static unsigned int get_protocol_family(unsigned int protocol);
  121. /* Some parts of the code (e.g. chunked encoding) assume this buffer has at
  122. * more than just a few bytes to play with. Don't let it become too small or
  123. * bad things will happen.
  124. */
  125. #if READBUFFER_SIZE < READBUFFER_MIN
  126. # error READBUFFER_SIZE is too small
  127. #endif
  128. /*
  129. * Protocol table.
  130. */
  131. static const struct Curl_handler * const protocols[] = {
  132. #ifndef CURL_DISABLE_HTTP
  133. &Curl_handler_http,
  134. #endif
  135. #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
  136. &Curl_handler_https,
  137. #endif
  138. #ifndef CURL_DISABLE_FTP
  139. &Curl_handler_ftp,
  140. #endif
  141. #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
  142. &Curl_handler_ftps,
  143. #endif
  144. #ifndef CURL_DISABLE_TELNET
  145. &Curl_handler_telnet,
  146. #endif
  147. #ifndef CURL_DISABLE_DICT
  148. &Curl_handler_dict,
  149. #endif
  150. #ifndef CURL_DISABLE_LDAP
  151. &Curl_handler_ldap,
  152. #if !defined(CURL_DISABLE_LDAPS) && \
  153. ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
  154. (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
  155. &Curl_handler_ldaps,
  156. #endif
  157. #endif
  158. #ifndef CURL_DISABLE_FILE
  159. &Curl_handler_file,
  160. #endif
  161. #ifndef CURL_DISABLE_TFTP
  162. &Curl_handler_tftp,
  163. #endif
  164. #if defined(USE_LIBSSH2) || defined(USE_LIBSSH)
  165. &Curl_handler_scp,
  166. #endif
  167. #if defined(USE_LIBSSH2) || defined(USE_LIBSSH)
  168. &Curl_handler_sftp,
  169. #endif
  170. #ifndef CURL_DISABLE_IMAP
  171. &Curl_handler_imap,
  172. #ifdef USE_SSL
  173. &Curl_handler_imaps,
  174. #endif
  175. #endif
  176. #ifndef CURL_DISABLE_POP3
  177. &Curl_handler_pop3,
  178. #ifdef USE_SSL
  179. &Curl_handler_pop3s,
  180. #endif
  181. #endif
  182. #if !defined(CURL_DISABLE_SMB) && defined(USE_NTLM) && \
  183. (CURL_SIZEOF_CURL_OFF_T > 4) && \
  184. (!defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO))
  185. &Curl_handler_smb,
  186. #ifdef USE_SSL
  187. &Curl_handler_smbs,
  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. ZERO_NULL, /* connection_check */
  231. 0, /* defport */
  232. 0, /* protocol */
  233. PROTOPT_NONE /* flags */
  234. };
  235. void Curl_freeset(struct Curl_easy *data)
  236. {
  237. /* Free all dynamic strings stored in the data->set substructure. */
  238. enum dupstring i;
  239. for(i = (enum dupstring)0; i < STRING_LAST; i++) {
  240. Curl_safefree(data->set.str[i]);
  241. }
  242. if(data->change.referer_alloc) {
  243. Curl_safefree(data->change.referer);
  244. data->change.referer_alloc = FALSE;
  245. }
  246. data->change.referer = NULL;
  247. if(data->change.url_alloc) {
  248. Curl_safefree(data->change.url);
  249. data->change.url_alloc = FALSE;
  250. }
  251. data->change.url = NULL;
  252. Curl_mime_cleanpart(&data->set.mimepost);
  253. }
  254. /*
  255. * This is the internal function curl_easy_cleanup() calls. This should
  256. * cleanup and free all resources associated with this sessionhandle.
  257. *
  258. * NOTE: if we ever add something that attempts to write to a socket or
  259. * similar here, we must ignore SIGPIPE first. It is currently only done
  260. * when curl_easy_perform() is invoked.
  261. */
  262. CURLcode Curl_close(struct Curl_easy *data)
  263. {
  264. struct Curl_multi *m;
  265. if(!data)
  266. return CURLE_OK;
  267. Curl_expire_clear(data); /* shut off timers */
  268. m = data->multi;
  269. if(m)
  270. /* This handle is still part of a multi handle, take care of this first
  271. and detach this handle from there. */
  272. curl_multi_remove_handle(data->multi, data);
  273. if(data->multi_easy)
  274. /* when curl_easy_perform() is used, it creates its own multi handle to
  275. use and this is the one */
  276. curl_multi_cleanup(data->multi_easy);
  277. /* Destroy the timeout list that is held in the easy handle. It is
  278. /normally/ done by curl_multi_remove_handle() but this is "just in
  279. case" */
  280. Curl_llist_destroy(&data->state.timeoutlist, NULL);
  281. data->magic = 0; /* force a clear AFTER the possibly enforced removal from
  282. the multi handle, since that function uses the magic
  283. field! */
  284. if(data->state.rangestringalloc)
  285. free(data->state.range);
  286. /* Free the pathbuffer */
  287. Curl_safefree(data->state.pathbuffer);
  288. data->state.path = NULL;
  289. /* freed here just in case DONE wasn't called */
  290. Curl_free_request_state(data);
  291. /* Close down all open SSL info and sessions */
  292. Curl_ssl_close_all(data);
  293. Curl_safefree(data->state.first_host);
  294. Curl_safefree(data->state.scratch);
  295. Curl_ssl_free_certinfo(data);
  296. /* Cleanup possible redirect junk */
  297. free(data->req.newurl);
  298. data->req.newurl = NULL;
  299. if(data->change.referer_alloc) {
  300. Curl_safefree(data->change.referer);
  301. data->change.referer_alloc = FALSE;
  302. }
  303. data->change.referer = NULL;
  304. if(data->change.url_alloc) {
  305. Curl_safefree(data->change.url);
  306. data->change.url_alloc = FALSE;
  307. }
  308. data->change.url = NULL;
  309. Curl_safefree(data->state.buffer);
  310. Curl_safefree(data->state.headerbuff);
  311. Curl_safefree(data->state.ulbuf);
  312. Curl_flush_cookies(data, 1);
  313. Curl_digest_cleanup(data);
  314. Curl_safefree(data->info.contenttype);
  315. Curl_safefree(data->info.wouldredirect);
  316. /* this destroys the channel and we cannot use it anymore after this */
  317. Curl_resolver_cleanup(data->state.resolver);
  318. Curl_http2_cleanup_dependencies(data);
  319. Curl_convert_close(data);
  320. /* No longer a dirty share, if it exists */
  321. if(data->share) {
  322. Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
  323. data->share->dirty--;
  324. Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
  325. }
  326. /* destruct wildcard structures if it is needed */
  327. Curl_wildcard_dtor(&data->wildcard);
  328. Curl_freeset(data);
  329. free(data);
  330. return CURLE_OK;
  331. }
  332. /*
  333. * Initialize the UserDefined fields within a Curl_easy.
  334. * This may be safely called on a new or existing Curl_easy.
  335. */
  336. CURLcode Curl_init_userdefined(struct Curl_easy *data)
  337. {
  338. struct UserDefined *set = &data->set;
  339. CURLcode result = CURLE_OK;
  340. set->out = stdout; /* default output to stdout */
  341. set->in_set = stdin; /* default input from stdin */
  342. set->err = stderr; /* default stderr to stderr */
  343. /* use fwrite as default function to store output */
  344. set->fwrite_func = (curl_write_callback)fwrite;
  345. /* use fread as default function to read input */
  346. set->fread_func_set = (curl_read_callback)fread;
  347. set->is_fread_set = 0;
  348. set->is_fwrite_set = 0;
  349. set->seek_func = ZERO_NULL;
  350. set->seek_client = ZERO_NULL;
  351. /* conversion callbacks for non-ASCII hosts */
  352. set->convfromnetwork = ZERO_NULL;
  353. set->convtonetwork = ZERO_NULL;
  354. set->convfromutf8 = ZERO_NULL;
  355. set->filesize = -1; /* we don't know the size */
  356. set->postfieldsize = -1; /* unknown size */
  357. set->maxredirs = -1; /* allow any amount by default */
  358. set->httpreq = HTTPREQ_GET; /* Default HTTP request */
  359. set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
  360. set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
  361. set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
  362. set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
  363. set->ftp_filemethod = FTPFILE_MULTICWD;
  364. set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
  365. /* Set the default size of the SSL session ID cache */
  366. set->general_ssl.max_ssl_sessions = 5;
  367. set->proxyport = 0;
  368. set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
  369. set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
  370. set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
  371. /* SOCKS5 proxy auth defaults to username/password + GSS-API */
  372. set->socks5auth = CURLAUTH_BASIC | CURLAUTH_GSSAPI;
  373. /* make libcurl quiet by default: */
  374. set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
  375. Curl_mime_initpart(&set->mimepost, data);
  376. /*
  377. * libcurl 7.10 introduced SSL verification *by default*! This needs to be
  378. * switched off unless wanted.
  379. */
  380. set->ssl.primary.verifypeer = TRUE;
  381. set->ssl.primary.verifyhost = TRUE;
  382. #ifdef USE_TLS_SRP
  383. set->ssl.authtype = CURL_TLSAUTH_NONE;
  384. #endif
  385. set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
  386. type */
  387. set->ssl.primary.sessionid = TRUE; /* session ID caching enabled by
  388. default */
  389. set->proxy_ssl = set->ssl;
  390. set->new_file_perms = 0644; /* Default permissions */
  391. set->new_directory_perms = 0755; /* Default permissions */
  392. /* for the *protocols fields we don't use the CURLPROTO_ALL convenience
  393. define since we internally only use the lower 16 bits for the passed
  394. in bitmask to not conflict with the private bits */
  395. set->allowed_protocols = CURLPROTO_ALL;
  396. set->redir_protocols = CURLPROTO_ALL & /* All except FILE, SCP and SMB */
  397. ~(CURLPROTO_FILE | CURLPROTO_SCP | CURLPROTO_SMB |
  398. CURLPROTO_SMBS);
  399. #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
  400. /*
  401. * disallow unprotected protection negotiation NEC reference implementation
  402. * seem not to follow rfc1961 section 4.3/4.4
  403. */
  404. set->socks5_gssapi_nec = FALSE;
  405. #endif
  406. /* Set the default CA cert bundle/path detected/specified at build time.
  407. *
  408. * If Schannel (WinSSL) is the selected SSL backend then these locations
  409. * are ignored. We allow setting CA location for schannel only when
  410. * explicitly specified by the user via CURLOPT_CAINFO / --cacert.
  411. */
  412. if(Curl_ssl_backend() != CURLSSLBACKEND_SCHANNEL) {
  413. #if defined(CURL_CA_BUNDLE)
  414. result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_ORIG], CURL_CA_BUNDLE);
  415. if(result)
  416. return result;
  417. result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_PROXY],
  418. CURL_CA_BUNDLE);
  419. if(result)
  420. return result;
  421. #endif
  422. #if defined(CURL_CA_PATH)
  423. result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_ORIG], CURL_CA_PATH);
  424. if(result)
  425. return result;
  426. result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_PROXY], CURL_CA_PATH);
  427. if(result)
  428. return result;
  429. #endif
  430. }
  431. set->wildcard_enabled = FALSE;
  432. set->chunk_bgn = ZERO_NULL;
  433. set->chunk_end = ZERO_NULL;
  434. /* tcp keepalives are disabled by default, but provide reasonable values for
  435. * the interval and idle times.
  436. */
  437. set->tcp_keepalive = FALSE;
  438. set->tcp_keepintvl = 60;
  439. set->tcp_keepidle = 60;
  440. set->tcp_fastopen = FALSE;
  441. set->tcp_nodelay = TRUE;
  442. set->ssl_enable_npn = TRUE;
  443. set->ssl_enable_alpn = TRUE;
  444. set->expect_100_timeout = 1000L; /* Wait for a second by default. */
  445. set->sep_headers = TRUE; /* separated header lists by default */
  446. set->buffer_size = READBUFFER_SIZE;
  447. set->upload_buffer_size = UPLOAD_BUFSIZE;
  448. set->happy_eyeballs_timeout = CURL_HET_DEFAULT;
  449. Curl_http2_init_userset(set);
  450. return result;
  451. }
  452. /**
  453. * Curl_open()
  454. *
  455. * @param curl is a pointer to a sessionhandle pointer that gets set by this
  456. * function.
  457. * @return CURLcode
  458. */
  459. CURLcode Curl_open(struct Curl_easy **curl)
  460. {
  461. CURLcode result;
  462. struct Curl_easy *data;
  463. /* Very simple start-up: alloc the struct, init it with zeroes and return */
  464. data = calloc(1, sizeof(struct Curl_easy));
  465. if(!data) {
  466. /* this is a very serious error */
  467. DEBUGF(fprintf(stderr, "Error: calloc of Curl_easy failed\n"));
  468. return CURLE_OUT_OF_MEMORY;
  469. }
  470. data->magic = CURLEASY_MAGIC_NUMBER;
  471. result = Curl_resolver_init(&data->state.resolver);
  472. if(result) {
  473. DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
  474. free(data);
  475. return result;
  476. }
  477. /* We do some initial setup here, all those fields that can't be just 0 */
  478. data->state.buffer = malloc(READBUFFER_SIZE + 1);
  479. if(!data->state.buffer) {
  480. DEBUGF(fprintf(stderr, "Error: malloc of buffer failed\n"));
  481. result = CURLE_OUT_OF_MEMORY;
  482. }
  483. else {
  484. data->state.headerbuff = malloc(HEADERSIZE);
  485. if(!data->state.headerbuff) {
  486. DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
  487. result = CURLE_OUT_OF_MEMORY;
  488. }
  489. else {
  490. result = Curl_init_userdefined(data);
  491. data->state.headersize = HEADERSIZE;
  492. Curl_convert_init(data);
  493. Curl_initinfo(data);
  494. /* most recent connection is not yet defined */
  495. data->state.lastconnect = NULL;
  496. data->progress.flags |= PGRS_HIDE;
  497. data->state.current_speed = -1; /* init to negative == impossible */
  498. data->set.fnmatch = ZERO_NULL;
  499. data->set.maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */
  500. Curl_http2_init_state(&data->state);
  501. }
  502. }
  503. if(result) {
  504. Curl_resolver_cleanup(data->state.resolver);
  505. free(data->state.buffer);
  506. free(data->state.headerbuff);
  507. Curl_freeset(data);
  508. free(data);
  509. data = NULL;
  510. }
  511. else
  512. *curl = data;
  513. return result;
  514. }
  515. #ifdef USE_RECV_BEFORE_SEND_WORKAROUND
  516. static void conn_reset_postponed_data(struct connectdata *conn, int num)
  517. {
  518. struct postponed_data * const psnd = &(conn->postponed[num]);
  519. if(psnd->buffer) {
  520. DEBUGASSERT(psnd->allocated_size > 0);
  521. DEBUGASSERT(psnd->recv_size <= psnd->allocated_size);
  522. DEBUGASSERT(psnd->recv_size ?
  523. (psnd->recv_processed < psnd->recv_size) :
  524. (psnd->recv_processed == 0));
  525. DEBUGASSERT(psnd->bindsock != CURL_SOCKET_BAD);
  526. free(psnd->buffer);
  527. psnd->buffer = NULL;
  528. psnd->allocated_size = 0;
  529. psnd->recv_size = 0;
  530. psnd->recv_processed = 0;
  531. #ifdef DEBUGBUILD
  532. psnd->bindsock = CURL_SOCKET_BAD; /* used only for DEBUGASSERT */
  533. #endif /* DEBUGBUILD */
  534. }
  535. else {
  536. DEBUGASSERT(psnd->allocated_size == 0);
  537. DEBUGASSERT(psnd->recv_size == 0);
  538. DEBUGASSERT(psnd->recv_processed == 0);
  539. DEBUGASSERT(psnd->bindsock == CURL_SOCKET_BAD);
  540. }
  541. }
  542. static void conn_reset_all_postponed_data(struct connectdata *conn)
  543. {
  544. conn_reset_postponed_data(conn, 0);
  545. conn_reset_postponed_data(conn, 1);
  546. }
  547. #else /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
  548. /* Use "do-nothing" macro instead of function when workaround not used */
  549. #define conn_reset_all_postponed_data(c) do {} WHILE_FALSE
  550. #endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
  551. static void conn_free(struct connectdata *conn)
  552. {
  553. if(!conn)
  554. return;
  555. /* possible left-overs from the async name resolvers */
  556. Curl_resolver_cancel(conn);
  557. /* close the SSL stuff before we close any sockets since they will/may
  558. write to the sockets */
  559. Curl_ssl_close(conn, FIRSTSOCKET);
  560. Curl_ssl_close(conn, SECONDARYSOCKET);
  561. /* close possibly still open sockets */
  562. if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
  563. Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
  564. if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
  565. Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
  566. if(CURL_SOCKET_BAD != conn->tempsock[0])
  567. Curl_closesocket(conn, conn->tempsock[0]);
  568. if(CURL_SOCKET_BAD != conn->tempsock[1])
  569. Curl_closesocket(conn, conn->tempsock[1]);
  570. #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
  571. defined(NTLM_WB_ENABLED)
  572. Curl_ntlm_wb_cleanup(conn);
  573. #endif
  574. Curl_safefree(conn->user);
  575. Curl_safefree(conn->passwd);
  576. Curl_safefree(conn->oauth_bearer);
  577. Curl_safefree(conn->options);
  578. Curl_safefree(conn->http_proxy.user);
  579. Curl_safefree(conn->socks_proxy.user);
  580. Curl_safefree(conn->http_proxy.passwd);
  581. Curl_safefree(conn->socks_proxy.passwd);
  582. Curl_safefree(conn->allocptr.proxyuserpwd);
  583. Curl_safefree(conn->allocptr.uagent);
  584. Curl_safefree(conn->allocptr.userpwd);
  585. Curl_safefree(conn->allocptr.accept_encoding);
  586. Curl_safefree(conn->allocptr.te);
  587. Curl_safefree(conn->allocptr.rangeline);
  588. Curl_safefree(conn->allocptr.ref);
  589. Curl_safefree(conn->allocptr.host);
  590. Curl_safefree(conn->allocptr.cookiehost);
  591. Curl_safefree(conn->allocptr.rtsp_transport);
  592. Curl_safefree(conn->trailer);
  593. Curl_safefree(conn->host.rawalloc); /* host name buffer */
  594. Curl_safefree(conn->conn_to_host.rawalloc); /* host name buffer */
  595. Curl_safefree(conn->secondaryhostname);
  596. Curl_safefree(conn->http_proxy.host.rawalloc); /* http proxy name buffer */
  597. Curl_safefree(conn->socks_proxy.host.rawalloc); /* socks proxy name buffer */
  598. Curl_safefree(conn->master_buffer);
  599. Curl_safefree(conn->connect_state);
  600. conn_reset_all_postponed_data(conn);
  601. Curl_llist_destroy(&conn->send_pipe, NULL);
  602. Curl_llist_destroy(&conn->recv_pipe, NULL);
  603. Curl_safefree(conn->localdev);
  604. Curl_free_primary_ssl_config(&conn->ssl_config);
  605. Curl_free_primary_ssl_config(&conn->proxy_ssl_config);
  606. #ifdef USE_UNIX_SOCKETS
  607. Curl_safefree(conn->unix_domain_socket);
  608. #endif
  609. #ifdef USE_SSL
  610. Curl_safefree(conn->ssl_extra);
  611. #endif
  612. free(conn); /* free all the connection oriented data */
  613. }
  614. /*
  615. * Disconnects the given connection. Note the connection may not be the
  616. * primary connection, like when freeing room in the connection cache or
  617. * killing of a dead old connection.
  618. *
  619. * A connection needs an easy handle when closing down. We support this passed
  620. * in separately since the connection to get closed here is often already
  621. * disassociated from an easy handle.
  622. *
  623. * This function MUST NOT reset state in the Curl_easy struct if that
  624. * isn't strictly bound to the life-time of *this* particular connection.
  625. *
  626. */
  627. CURLcode Curl_disconnect(struct Curl_easy *data,
  628. struct connectdata *conn, bool dead_connection)
  629. {
  630. if(!conn)
  631. return CURLE_OK; /* this is closed and fine already */
  632. if(!data) {
  633. DEBUGF(infof(data, "DISCONNECT without easy handle, ignoring\n"));
  634. return CURLE_OK;
  635. }
  636. /*
  637. * If this connection isn't marked to force-close, leave it open if there
  638. * are other users of it
  639. */
  640. if(CONN_INUSE(conn) && !dead_connection) {
  641. DEBUGF(infof(data, "Curl_disconnect when inuse: %zu\n", CONN_INUSE(conn)));
  642. return CURLE_OK;
  643. }
  644. conn->data = data;
  645. if(conn->dns_entry != NULL) {
  646. Curl_resolv_unlock(data, conn->dns_entry);
  647. conn->dns_entry = NULL;
  648. }
  649. Curl_hostcache_prune(data); /* kill old DNS cache entries */
  650. #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM)
  651. /* Cleanup NTLM connection-related data */
  652. Curl_http_ntlm_cleanup(conn);
  653. #endif
  654. if(conn->handler->disconnect)
  655. /* This is set if protocol-specific cleanups should be made */
  656. conn->handler->disconnect(conn, dead_connection);
  657. /* unlink ourselves! */
  658. infof(data, "Closing connection %ld\n", conn->connection_id);
  659. Curl_conncache_remove_conn(conn, TRUE);
  660. free_fixed_hostname(&conn->host);
  661. free_fixed_hostname(&conn->conn_to_host);
  662. free_fixed_hostname(&conn->http_proxy.host);
  663. free_fixed_hostname(&conn->socks_proxy.host);
  664. DEBUGASSERT(conn->data == data);
  665. /* this assumes that the pointer is still there after the connection was
  666. detected from the cache */
  667. Curl_ssl_close(conn, FIRSTSOCKET);
  668. conn_free(conn);
  669. return CURLE_OK;
  670. }
  671. /*
  672. * This function should return TRUE if the socket is to be assumed to
  673. * be dead. Most commonly this happens when the server has closed the
  674. * connection due to inactivity.
  675. */
  676. static bool SocketIsDead(curl_socket_t sock)
  677. {
  678. int sval;
  679. bool ret_val = TRUE;
  680. sval = SOCKET_READABLE(sock, 0);
  681. if(sval == 0)
  682. /* timeout */
  683. ret_val = FALSE;
  684. return ret_val;
  685. }
  686. /*
  687. * IsPipeliningPossible()
  688. *
  689. * Return a bitmask with the available pipelining and multiplexing options for
  690. * the given requested connection.
  691. */
  692. static int IsPipeliningPossible(const struct Curl_easy *handle,
  693. const struct connectdata *conn)
  694. {
  695. int avail = 0;
  696. /* If a HTTP protocol and pipelining is enabled */
  697. if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
  698. (!conn->bits.protoconnstart || !conn->bits.close)) {
  699. if(Curl_pipeline_wanted(handle->multi, CURLPIPE_HTTP1) &&
  700. (handle->set.httpversion != CURL_HTTP_VERSION_1_0) &&
  701. (handle->set.httpreq == HTTPREQ_GET ||
  702. handle->set.httpreq == HTTPREQ_HEAD))
  703. /* didn't ask for HTTP/1.0 and a GET or HEAD */
  704. avail |= CURLPIPE_HTTP1;
  705. if(Curl_pipeline_wanted(handle->multi, CURLPIPE_MULTIPLEX) &&
  706. (handle->set.httpversion >= CURL_HTTP_VERSION_2))
  707. /* allows HTTP/2 */
  708. avail |= CURLPIPE_MULTIPLEX;
  709. }
  710. return avail;
  711. }
  712. /* Returns non-zero if a handle was removed */
  713. int Curl_removeHandleFromPipeline(struct Curl_easy *handle,
  714. struct curl_llist *pipeline)
  715. {
  716. if(pipeline) {
  717. struct curl_llist_element *curr;
  718. curr = pipeline->head;
  719. while(curr) {
  720. if(curr->ptr == handle) {
  721. Curl_llist_remove(pipeline, curr, NULL);
  722. return 1; /* we removed a handle */
  723. }
  724. curr = curr->next;
  725. }
  726. }
  727. return 0;
  728. }
  729. #if 0 /* this code is saved here as it is useful for debugging purposes */
  730. static void Curl_printPipeline(struct curl_llist *pipeline)
  731. {
  732. struct curl_llist_element *curr;
  733. curr = pipeline->head;
  734. while(curr) {
  735. struct Curl_easy *data = (struct Curl_easy *) curr->ptr;
  736. infof(data, "Handle in pipeline: %s\n", data->state.path);
  737. curr = curr->next;
  738. }
  739. }
  740. #endif
  741. static struct Curl_easy* gethandleathead(struct curl_llist *pipeline)
  742. {
  743. struct curl_llist_element *curr = pipeline->head;
  744. #ifdef DEBUGBUILD
  745. {
  746. struct curl_llist_element *p = pipeline->head;
  747. while(p) {
  748. struct Curl_easy *e = p->ptr;
  749. DEBUGASSERT(GOOD_EASY_HANDLE(e));
  750. p = p->next;
  751. }
  752. }
  753. #endif
  754. if(curr) {
  755. return (struct Curl_easy *) curr->ptr;
  756. }
  757. return NULL;
  758. }
  759. /* remove the specified connection from all (possible) pipelines and related
  760. queues */
  761. void Curl_getoff_all_pipelines(struct Curl_easy *data,
  762. struct connectdata *conn)
  763. {
  764. if(!conn->bundle)
  765. return;
  766. if(conn->bundle->multiuse == BUNDLE_PIPELINING) {
  767. bool recv_head = (conn->readchannel_inuse &&
  768. Curl_recvpipe_head(data, conn));
  769. bool send_head = (conn->writechannel_inuse &&
  770. Curl_sendpipe_head(data, conn));
  771. if(Curl_removeHandleFromPipeline(data, &conn->recv_pipe) && recv_head)
  772. Curl_pipeline_leave_read(conn);
  773. if(Curl_removeHandleFromPipeline(data, &conn->send_pipe) && send_head)
  774. Curl_pipeline_leave_write(conn);
  775. }
  776. else {
  777. (void)Curl_removeHandleFromPipeline(data, &conn->recv_pipe);
  778. (void)Curl_removeHandleFromPipeline(data, &conn->send_pipe);
  779. }
  780. }
  781. static bool
  782. proxy_info_matches(const struct proxy_info* data,
  783. const struct proxy_info* needle)
  784. {
  785. if((data->proxytype == needle->proxytype) &&
  786. (data->port == needle->port) &&
  787. Curl_safe_strcasecompare(data->host.name, needle->host.name))
  788. return TRUE;
  789. return FALSE;
  790. }
  791. /*
  792. * This function checks if the given connection is dead and extracts it from
  793. * the connection cache if so.
  794. *
  795. * When this is called as a Curl_conncache_foreach() callback, the connection
  796. * cache lock is held!
  797. *
  798. * Returns TRUE if the connection was dead and extracted.
  799. */
  800. static bool extract_if_dead(struct connectdata *conn,
  801. struct Curl_easy *data)
  802. {
  803. size_t pipeLen = conn->send_pipe.size + conn->recv_pipe.size;
  804. if(!pipeLen && !CONN_INUSE(conn)) {
  805. /* The check for a dead socket makes sense only if there are no
  806. handles in pipeline and the connection isn't already marked in
  807. use */
  808. bool dead;
  809. conn->data = data;
  810. if(conn->handler->connection_check) {
  811. /* The protocol has a special method for checking the state of the
  812. connection. Use it to check if the connection is dead. */
  813. unsigned int state;
  814. state = conn->handler->connection_check(conn, CONNCHECK_ISDEAD);
  815. dead = (state & CONNRESULT_DEAD);
  816. }
  817. else {
  818. /* Use the general method for determining the death of a connection */
  819. dead = SocketIsDead(conn->sock[FIRSTSOCKET]);
  820. }
  821. if(dead) {
  822. infof(data, "Connection %ld seems to be dead!\n", conn->connection_id);
  823. Curl_conncache_remove_conn(conn, FALSE);
  824. conn->data = NULL; /* detach */
  825. return TRUE;
  826. }
  827. }
  828. return FALSE;
  829. }
  830. struct prunedead {
  831. struct Curl_easy *data;
  832. struct connectdata *extracted;
  833. };
  834. /*
  835. * Wrapper to use extract_if_dead() function in Curl_conncache_foreach()
  836. *
  837. */
  838. static int call_extract_if_dead(struct connectdata *conn, void *param)
  839. {
  840. struct prunedead *p = (struct prunedead *)param;
  841. if(extract_if_dead(conn, p->data)) {
  842. /* stop the iteration here, pass back the connection that was extracted */
  843. p->extracted = conn;
  844. return 1;
  845. }
  846. return 0; /* continue iteration */
  847. }
  848. /*
  849. * This function scans the connection cache for half-open/dead connections,
  850. * closes and removes them.
  851. * The cleanup is done at most once per second.
  852. */
  853. static void prune_dead_connections(struct Curl_easy *data)
  854. {
  855. struct curltime now = Curl_now();
  856. time_t elapsed = Curl_timediff(now, data->state.conn_cache->last_cleanup);
  857. if(elapsed >= 1000L) {
  858. struct prunedead prune;
  859. prune.data = data;
  860. prune.extracted = NULL;
  861. while(Curl_conncache_foreach(data, data->state.conn_cache, &prune,
  862. call_extract_if_dead)) {
  863. /* disconnect it */
  864. (void)Curl_disconnect(data, prune.extracted, /* dead_connection */TRUE);
  865. }
  866. data->state.conn_cache->last_cleanup = now;
  867. }
  868. }
  869. static size_t max_pipeline_length(struct Curl_multi *multi)
  870. {
  871. return multi ? multi->max_pipeline_length : 0;
  872. }
  873. /*
  874. * Given one filled in connection struct (named needle), this function should
  875. * detect if there already is one that has all the significant details
  876. * exactly the same and thus should be used instead.
  877. *
  878. * If there is a match, this function returns TRUE - and has marked the
  879. * connection as 'in-use'. It must later be called with ConnectionDone() to
  880. * return back to 'idle' (unused) state.
  881. *
  882. * The force_reuse flag is set if the connection must be used, even if
  883. * the pipelining strategy wants to open a new connection instead of reusing.
  884. */
  885. static bool
  886. ConnectionExists(struct Curl_easy *data,
  887. struct connectdata *needle,
  888. struct connectdata **usethis,
  889. bool *force_reuse,
  890. bool *waitpipe)
  891. {
  892. struct connectdata *check;
  893. struct connectdata *chosen = 0;
  894. bool foundPendingCandidate = FALSE;
  895. int canpipe = IsPipeliningPossible(data, needle);
  896. struct connectbundle *bundle;
  897. #ifdef USE_NTLM
  898. bool wantNTLMhttp = ((data->state.authhost.want &
  899. (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
  900. (needle->handler->protocol & PROTO_FAMILY_HTTP));
  901. bool wantProxyNTLMhttp = (needle->bits.proxy_user_passwd &&
  902. ((data->state.authproxy.want &
  903. (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
  904. (needle->handler->protocol & PROTO_FAMILY_HTTP)));
  905. #endif
  906. *force_reuse = FALSE;
  907. *waitpipe = FALSE;
  908. /* We can't pipeline if the site is blacklisted */
  909. if((canpipe & CURLPIPE_HTTP1) &&
  910. Curl_pipeline_site_blacklisted(data, needle))
  911. canpipe &= ~ CURLPIPE_HTTP1;
  912. /* Look up the bundle with all the connections to this particular host.
  913. Locks the connection cache, beware of early returns! */
  914. bundle = Curl_conncache_find_bundle(needle, data->state.conn_cache);
  915. if(bundle) {
  916. /* Max pipe length is zero (unlimited) for multiplexed connections */
  917. size_t max_pipe_len = (bundle->multiuse != BUNDLE_MULTIPLEX)?
  918. max_pipeline_length(data->multi):0;
  919. size_t best_pipe_len = max_pipe_len;
  920. struct curl_llist_element *curr;
  921. infof(data, "Found bundle for host %s: %p [%s]\n",
  922. (needle->bits.conn_to_host ? needle->conn_to_host.name :
  923. needle->host.name), (void *)bundle,
  924. (bundle->multiuse == BUNDLE_PIPELINING ?
  925. "can pipeline" :
  926. (bundle->multiuse == BUNDLE_MULTIPLEX ?
  927. "can multiplex" : "serially")));
  928. /* We can't pipeline if we don't know anything about the server */
  929. if(canpipe) {
  930. if(bundle->multiuse <= BUNDLE_UNKNOWN) {
  931. if((bundle->multiuse == BUNDLE_UNKNOWN) && data->set.pipewait) {
  932. infof(data, "Server doesn't support multi-use yet, wait\n");
  933. *waitpipe = TRUE;
  934. Curl_conncache_unlock(needle);
  935. return FALSE; /* no re-use */
  936. }
  937. infof(data, "Server doesn't support multi-use (yet)\n");
  938. canpipe = 0;
  939. }
  940. if((bundle->multiuse == BUNDLE_PIPELINING) &&
  941. !Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1)) {
  942. /* not asked for, switch off */
  943. infof(data, "Could pipeline, but not asked to!\n");
  944. canpipe = 0;
  945. }
  946. else if((bundle->multiuse == BUNDLE_MULTIPLEX) &&
  947. !Curl_pipeline_wanted(data->multi, CURLPIPE_MULTIPLEX)) {
  948. infof(data, "Could multiplex, but not asked to!\n");
  949. canpipe = 0;
  950. }
  951. }
  952. curr = bundle->conn_list.head;
  953. while(curr) {
  954. bool match = FALSE;
  955. size_t pipeLen;
  956. /*
  957. * Note that if we use a HTTP proxy in normal mode (no tunneling), we
  958. * check connections to that proxy and not to the actual remote server.
  959. */
  960. check = curr->ptr;
  961. curr = curr->next;
  962. if(extract_if_dead(check, data)) {
  963. /* disconnect it */
  964. (void)Curl_disconnect(data, check, /* dead_connection */TRUE);
  965. continue;
  966. }
  967. pipeLen = check->send_pipe.size + check->recv_pipe.size;
  968. if(canpipe) {
  969. if(check->bits.protoconnstart && check->bits.close)
  970. continue;
  971. if(!check->bits.multiplex) {
  972. /* If not multiplexing, make sure the connection is fine for HTTP/1
  973. pipelining */
  974. struct Curl_easy* sh = gethandleathead(&check->send_pipe);
  975. struct Curl_easy* rh = gethandleathead(&check->recv_pipe);
  976. if(sh) {
  977. if(!(IsPipeliningPossible(sh, check) & CURLPIPE_HTTP1))
  978. continue;
  979. }
  980. else if(rh) {
  981. if(!(IsPipeliningPossible(rh, check) & CURLPIPE_HTTP1))
  982. continue;
  983. }
  984. }
  985. }
  986. else {
  987. if(pipeLen > 0) {
  988. /* can only happen within multi handles, and means that another easy
  989. handle is using this connection */
  990. continue;
  991. }
  992. if(Curl_resolver_asynch()) {
  993. /* ip_addr_str[0] is NUL only if the resolving of the name hasn't
  994. completed yet and until then we don't re-use this connection */
  995. if(!check->ip_addr_str[0]) {
  996. infof(data,
  997. "Connection #%ld is still name resolving, can't reuse\n",
  998. check->connection_id);
  999. continue;
  1000. }
  1001. }
  1002. if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) ||
  1003. check->bits.close) {
  1004. if(!check->bits.close)
  1005. foundPendingCandidate = TRUE;
  1006. /* Don't pick a connection that hasn't connected yet or that is going
  1007. to get closed. */
  1008. infof(data, "Connection #%ld isn't open enough, can't reuse\n",
  1009. check->connection_id);
  1010. #ifdef DEBUGBUILD
  1011. if(check->recv_pipe.size > 0) {
  1012. infof(data,
  1013. "BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
  1014. check->connection_id);
  1015. }
  1016. #endif
  1017. continue;
  1018. }
  1019. }
  1020. #ifdef USE_UNIX_SOCKETS
  1021. if(needle->unix_domain_socket) {
  1022. if(!check->unix_domain_socket)
  1023. continue;
  1024. if(strcmp(needle->unix_domain_socket, check->unix_domain_socket))
  1025. continue;
  1026. if(needle->abstract_unix_socket != check->abstract_unix_socket)
  1027. continue;
  1028. }
  1029. else if(check->unix_domain_socket)
  1030. continue;
  1031. #endif
  1032. if((needle->handler->flags&PROTOPT_SSL) !=
  1033. (check->handler->flags&PROTOPT_SSL))
  1034. /* don't do mixed SSL and non-SSL connections */
  1035. if(get_protocol_family(check->handler->protocol) !=
  1036. needle->handler->protocol || !check->tls_upgraded)
  1037. /* except protocols that have been upgraded via TLS */
  1038. continue;
  1039. if(needle->bits.httpproxy != check->bits.httpproxy ||
  1040. needle->bits.socksproxy != check->bits.socksproxy)
  1041. continue;
  1042. if(needle->bits.socksproxy && !proxy_info_matches(&needle->socks_proxy,
  1043. &check->socks_proxy))
  1044. continue;
  1045. if(needle->bits.conn_to_host != check->bits.conn_to_host)
  1046. /* don't mix connections that use the "connect to host" feature and
  1047. * connections that don't use this feature */
  1048. continue;
  1049. if(needle->bits.conn_to_port != check->bits.conn_to_port)
  1050. /* don't mix connections that use the "connect to port" feature and
  1051. * connections that don't use this feature */
  1052. continue;
  1053. if(needle->bits.httpproxy) {
  1054. if(!proxy_info_matches(&needle->http_proxy, &check->http_proxy))
  1055. continue;
  1056. if(needle->bits.tunnel_proxy != check->bits.tunnel_proxy)
  1057. continue;
  1058. if(needle->http_proxy.proxytype == CURLPROXY_HTTPS) {
  1059. /* use https proxy */
  1060. if(needle->handler->flags&PROTOPT_SSL) {
  1061. /* use double layer ssl */
  1062. if(!Curl_ssl_config_matches(&needle->proxy_ssl_config,
  1063. &check->proxy_ssl_config))
  1064. continue;
  1065. if(check->proxy_ssl[FIRSTSOCKET].state != ssl_connection_complete)
  1066. continue;
  1067. }
  1068. else {
  1069. if(!Curl_ssl_config_matches(&needle->ssl_config,
  1070. &check->ssl_config))
  1071. continue;
  1072. if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete)
  1073. continue;
  1074. }
  1075. }
  1076. }
  1077. if(!canpipe && CONN_INUSE(check))
  1078. /* this request can't be pipelined but the checked connection is
  1079. already in use so we skip it */
  1080. continue;
  1081. if(CONN_INUSE(check) && (check->data->multi != needle->data->multi))
  1082. /* this could be subject for pipeline/multiplex use, but only
  1083. if they belong to the same multi handle */
  1084. continue;
  1085. if(needle->localdev || needle->localport) {
  1086. /* If we are bound to a specific local end (IP+port), we must not
  1087. re-use a random other one, although if we didn't ask for a
  1088. particular one we can reuse one that was bound.
  1089. This comparison is a bit rough and too strict. Since the input
  1090. parameters can be specified in numerous ways and still end up the
  1091. same it would take a lot of processing to make it really accurate.
  1092. Instead, this matching will assume that re-uses of bound connections
  1093. will most likely also re-use the exact same binding parameters and
  1094. missing out a few edge cases shouldn't hurt anyone very much.
  1095. */
  1096. if((check->localport != needle->localport) ||
  1097. (check->localportrange != needle->localportrange) ||
  1098. (needle->localdev &&
  1099. (!check->localdev || strcmp(check->localdev, needle->localdev))))
  1100. continue;
  1101. }
  1102. if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) {
  1103. /* This protocol requires credentials per connection,
  1104. so verify that we're using the same name and password as well */
  1105. if(strcmp(needle->user, check->user) ||
  1106. strcmp(needle->passwd, check->passwd)) {
  1107. /* one of them was different */
  1108. continue;
  1109. }
  1110. }
  1111. if(!needle->bits.httpproxy || (needle->handler->flags&PROTOPT_SSL) ||
  1112. needle->bits.tunnel_proxy) {
  1113. /* The requested connection does not use a HTTP proxy or it uses SSL or
  1114. it is a non-SSL protocol tunneled or it is a non-SSL protocol which
  1115. is allowed to be upgraded via TLS */
  1116. if((strcasecompare(needle->handler->scheme, check->handler->scheme) ||
  1117. (get_protocol_family(check->handler->protocol) ==
  1118. needle->handler->protocol && check->tls_upgraded)) &&
  1119. (!needle->bits.conn_to_host || strcasecompare(
  1120. needle->conn_to_host.name, check->conn_to_host.name)) &&
  1121. (!needle->bits.conn_to_port ||
  1122. needle->conn_to_port == check->conn_to_port) &&
  1123. strcasecompare(needle->host.name, check->host.name) &&
  1124. needle->remote_port == check->remote_port) {
  1125. /* The schemes match or the the protocol family is the same and the
  1126. previous connection was TLS upgraded, and the hostname and host
  1127. port match */
  1128. if(needle->handler->flags & PROTOPT_SSL) {
  1129. /* This is a SSL connection so verify that we're using the same
  1130. SSL options as well */
  1131. if(!Curl_ssl_config_matches(&needle->ssl_config,
  1132. &check->ssl_config)) {
  1133. DEBUGF(infof(data,
  1134. "Connection #%ld has different SSL parameters, "
  1135. "can't reuse\n",
  1136. check->connection_id));
  1137. continue;
  1138. }
  1139. if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
  1140. foundPendingCandidate = TRUE;
  1141. DEBUGF(infof(data,
  1142. "Connection #%ld has not started SSL connect, "
  1143. "can't reuse\n",
  1144. check->connection_id));
  1145. continue;
  1146. }
  1147. }
  1148. match = TRUE;
  1149. }
  1150. }
  1151. else {
  1152. /* The requested connection is using the same HTTP proxy in normal
  1153. mode (no tunneling) */
  1154. match = TRUE;
  1155. }
  1156. if(match) {
  1157. #if defined(USE_NTLM)
  1158. /* If we are looking for an HTTP+NTLM connection, check if this is
  1159. already authenticating with the right credentials. If not, keep
  1160. looking so that we can reuse NTLM connections if
  1161. possible. (Especially we must not reuse the same connection if
  1162. partway through a handshake!) */
  1163. if(wantNTLMhttp) {
  1164. if(strcmp(needle->user, check->user) ||
  1165. strcmp(needle->passwd, check->passwd))
  1166. continue;
  1167. }
  1168. else if(check->ntlm.state != NTLMSTATE_NONE) {
  1169. /* Connection is using NTLM auth but we don't want NTLM */
  1170. continue;
  1171. }
  1172. /* Same for Proxy NTLM authentication */
  1173. if(wantProxyNTLMhttp) {
  1174. /* Both check->http_proxy.user and check->http_proxy.passwd can be
  1175. * NULL */
  1176. if(!check->http_proxy.user || !check->http_proxy.passwd)
  1177. continue;
  1178. if(strcmp(needle->http_proxy.user, check->http_proxy.user) ||
  1179. strcmp(needle->http_proxy.passwd, check->http_proxy.passwd))
  1180. continue;
  1181. }
  1182. else if(check->proxyntlm.state != NTLMSTATE_NONE) {
  1183. /* Proxy connection is using NTLM auth but we don't want NTLM */
  1184. continue;
  1185. }
  1186. if(wantNTLMhttp || wantProxyNTLMhttp) {
  1187. /* Credentials are already checked, we can use this connection */
  1188. chosen = check;
  1189. if((wantNTLMhttp &&
  1190. (check->ntlm.state != NTLMSTATE_NONE)) ||
  1191. (wantProxyNTLMhttp &&
  1192. (check->proxyntlm.state != NTLMSTATE_NONE))) {
  1193. /* We must use this connection, no other */
  1194. *force_reuse = TRUE;
  1195. break;
  1196. }
  1197. /* Continue look up for a better connection */
  1198. continue;
  1199. }
  1200. #endif
  1201. if(canpipe) {
  1202. /* We can pipeline if we want to. Let's continue looking for
  1203. the optimal connection to use, i.e the shortest pipe that is not
  1204. blacklisted. */
  1205. if(pipeLen == 0) {
  1206. /* We have the optimal connection. Let's stop looking. */
  1207. chosen = check;
  1208. break;
  1209. }
  1210. /* We can't use the connection if the pipe is full */
  1211. if(max_pipe_len && (pipeLen >= max_pipe_len)) {
  1212. infof(data, "Pipe is full, skip (%zu)\n", pipeLen);
  1213. continue;
  1214. }
  1215. #ifdef USE_NGHTTP2
  1216. /* If multiplexed, make sure we don't go over concurrency limit */
  1217. if(check->bits.multiplex) {
  1218. /* Multiplexed connections can only be HTTP/2 for now */
  1219. struct http_conn *httpc = &check->proto.httpc;
  1220. if(pipeLen >= httpc->settings.max_concurrent_streams) {
  1221. infof(data, "MAX_CONCURRENT_STREAMS reached, skip (%zu)\n",
  1222. pipeLen);
  1223. continue;
  1224. }
  1225. }
  1226. #endif
  1227. /* We can't use the connection if the pipe is penalized */
  1228. if(Curl_pipeline_penalized(data, check)) {
  1229. infof(data, "Penalized, skip\n");
  1230. continue;
  1231. }
  1232. if(max_pipe_len) {
  1233. if(pipeLen < best_pipe_len) {
  1234. /* This connection has a shorter pipe so far. We'll pick this
  1235. and continue searching */
  1236. chosen = check;
  1237. best_pipe_len = pipeLen;
  1238. continue;
  1239. }
  1240. }
  1241. else {
  1242. /* When not pipelining (== multiplexed), we have a match here! */
  1243. chosen = check;
  1244. infof(data, "Multiplexed connection found!\n");
  1245. break;
  1246. }
  1247. }
  1248. else {
  1249. /* We have found a connection. Let's stop searching. */
  1250. chosen = check;
  1251. break;
  1252. }
  1253. }
  1254. }
  1255. }
  1256. if(chosen) {
  1257. /* mark it as used before releasing the lock */
  1258. chosen->data = data; /* own it! */
  1259. Curl_conncache_unlock(needle);
  1260. *usethis = chosen;
  1261. return TRUE; /* yes, we found one to use! */
  1262. }
  1263. Curl_conncache_unlock(needle);
  1264. if(foundPendingCandidate && data->set.pipewait) {
  1265. infof(data,
  1266. "Found pending candidate for reuse and CURLOPT_PIPEWAIT is set\n");
  1267. *waitpipe = TRUE;
  1268. }
  1269. return FALSE; /* no matching connecting exists */
  1270. }
  1271. /* after a TCP connection to the proxy has been verified, this function does
  1272. the next magic step.
  1273. Note: this function's sub-functions call failf()
  1274. */
  1275. CURLcode Curl_connected_proxy(struct connectdata *conn, int sockindex)
  1276. {
  1277. CURLcode result = CURLE_OK;
  1278. if(conn->bits.socksproxy) {
  1279. #ifndef CURL_DISABLE_PROXY
  1280. /* for the secondary socket (FTP), use the "connect to host"
  1281. * but ignore the "connect to port" (use the secondary port)
  1282. */
  1283. const char * const host = conn->bits.httpproxy ?
  1284. conn->http_proxy.host.name :
  1285. conn->bits.conn_to_host ?
  1286. conn->conn_to_host.name :
  1287. sockindex == SECONDARYSOCKET ?
  1288. conn->secondaryhostname : conn->host.name;
  1289. const int port = conn->bits.httpproxy ? (int)conn->http_proxy.port :
  1290. sockindex == SECONDARYSOCKET ? conn->secondary_port :
  1291. conn->bits.conn_to_port ? conn->conn_to_port :
  1292. conn->remote_port;
  1293. conn->bits.socksproxy_connecting = TRUE;
  1294. switch(conn->socks_proxy.proxytype) {
  1295. case CURLPROXY_SOCKS5:
  1296. case CURLPROXY_SOCKS5_HOSTNAME:
  1297. result = Curl_SOCKS5(conn->socks_proxy.user, conn->socks_proxy.passwd,
  1298. host, port, sockindex, conn);
  1299. break;
  1300. case CURLPROXY_SOCKS4:
  1301. case CURLPROXY_SOCKS4A:
  1302. result = Curl_SOCKS4(conn->socks_proxy.user, host, port, sockindex,
  1303. conn);
  1304. break;
  1305. default:
  1306. failf(conn->data, "unknown proxytype option given");
  1307. result = CURLE_COULDNT_CONNECT;
  1308. } /* switch proxytype */
  1309. conn->bits.socksproxy_connecting = FALSE;
  1310. #else
  1311. (void)sockindex;
  1312. #endif /* CURL_DISABLE_PROXY */
  1313. }
  1314. return result;
  1315. }
  1316. /*
  1317. * verboseconnect() displays verbose information after a connect
  1318. */
  1319. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1320. void Curl_verboseconnect(struct connectdata *conn)
  1321. {
  1322. if(conn->data->set.verbose)
  1323. infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
  1324. conn->bits.socksproxy ? conn->socks_proxy.host.dispname :
  1325. conn->bits.httpproxy ? conn->http_proxy.host.dispname :
  1326. conn->bits.conn_to_host ? conn->conn_to_host.dispname :
  1327. conn->host.dispname,
  1328. conn->ip_addr_str, conn->port, conn->connection_id);
  1329. }
  1330. #endif
  1331. int Curl_protocol_getsock(struct connectdata *conn,
  1332. curl_socket_t *socks,
  1333. int numsocks)
  1334. {
  1335. if(conn->handler->proto_getsock)
  1336. return conn->handler->proto_getsock(conn, socks, numsocks);
  1337. /* Backup getsock logic. Since there is a live socket in use, we must wait
  1338. for it or it will be removed from watching when the multi_socket API is
  1339. used. */
  1340. socks[0] = conn->sock[FIRSTSOCKET];
  1341. return GETSOCK_READSOCK(0) | GETSOCK_WRITESOCK(0);
  1342. }
  1343. int Curl_doing_getsock(struct connectdata *conn,
  1344. curl_socket_t *socks,
  1345. int numsocks)
  1346. {
  1347. if(conn && conn->handler->doing_getsock)
  1348. return conn->handler->doing_getsock(conn, socks, numsocks);
  1349. return GETSOCK_BLANK;
  1350. }
  1351. /*
  1352. * We are doing protocol-specific connecting and this is being called over and
  1353. * over from the multi interface until the connection phase is done on
  1354. * protocol layer.
  1355. */
  1356. CURLcode Curl_protocol_connecting(struct connectdata *conn,
  1357. bool *done)
  1358. {
  1359. CURLcode result = CURLE_OK;
  1360. if(conn && conn->handler->connecting) {
  1361. *done = FALSE;
  1362. result = conn->handler->connecting(conn, done);
  1363. }
  1364. else
  1365. *done = TRUE;
  1366. return result;
  1367. }
  1368. /*
  1369. * We are DOING this is being called over and over from the multi interface
  1370. * until the DOING phase is done on protocol layer.
  1371. */
  1372. CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
  1373. {
  1374. CURLcode result = CURLE_OK;
  1375. if(conn && conn->handler->doing) {
  1376. *done = FALSE;
  1377. result = conn->handler->doing(conn, done);
  1378. }
  1379. else
  1380. *done = TRUE;
  1381. return result;
  1382. }
  1383. /*
  1384. * We have discovered that the TCP connection has been successful, we can now
  1385. * proceed with some action.
  1386. *
  1387. */
  1388. CURLcode Curl_protocol_connect(struct connectdata *conn,
  1389. bool *protocol_done)
  1390. {
  1391. CURLcode result = CURLE_OK;
  1392. *protocol_done = FALSE;
  1393. if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) {
  1394. /* We already are connected, get back. This may happen when the connect
  1395. worked fine in the first call, like when we connect to a local server
  1396. or proxy. Note that we don't know if the protocol is actually done.
  1397. Unless this protocol doesn't have any protocol-connect callback, as
  1398. then we know we're done. */
  1399. if(!conn->handler->connecting)
  1400. *protocol_done = TRUE;
  1401. return CURLE_OK;
  1402. }
  1403. if(!conn->bits.protoconnstart) {
  1404. result = Curl_proxy_connect(conn, FIRSTSOCKET);
  1405. if(result)
  1406. return result;
  1407. if(CONNECT_FIRSTSOCKET_PROXY_SSL())
  1408. /* wait for HTTPS proxy SSL initialization to complete */
  1409. return CURLE_OK;
  1410. if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
  1411. Curl_connect_ongoing(conn))
  1412. /* when using an HTTP tunnel proxy, await complete tunnel establishment
  1413. before proceeding further. Return CURLE_OK so we'll be called again */
  1414. return CURLE_OK;
  1415. if(conn->handler->connect_it) {
  1416. /* is there a protocol-specific connect() procedure? */
  1417. /* Call the protocol-specific connect function */
  1418. result = conn->handler->connect_it(conn, protocol_done);
  1419. }
  1420. else
  1421. *protocol_done = TRUE;
  1422. /* it has started, possibly even completed but that knowledge isn't stored
  1423. in this bit! */
  1424. if(!result)
  1425. conn->bits.protoconnstart = TRUE;
  1426. }
  1427. return result; /* pass back status */
  1428. }
  1429. /*
  1430. * Helpers for IDNA conversions.
  1431. */
  1432. static bool is_ASCII_name(const char *hostname)
  1433. {
  1434. const unsigned char *ch = (const unsigned char *)hostname;
  1435. while(*ch) {
  1436. if(*ch++ & 0x80)
  1437. return FALSE;
  1438. }
  1439. return TRUE;
  1440. }
  1441. /*
  1442. * Perform any necessary IDN conversion of hostname
  1443. */
  1444. static CURLcode fix_hostname(struct connectdata *conn, struct hostname *host)
  1445. {
  1446. size_t len;
  1447. struct Curl_easy *data = conn->data;
  1448. #ifndef USE_LIBIDN2
  1449. (void)data;
  1450. (void)conn;
  1451. #elif defined(CURL_DISABLE_VERBOSE_STRINGS)
  1452. (void)conn;
  1453. #endif
  1454. /* set the name we use to display the host name */
  1455. host->dispname = host->name;
  1456. len = strlen(host->name);
  1457. if(len && (host->name[len-1] == '.'))
  1458. /* strip off a single trailing dot if present, primarily for SNI but
  1459. there's no use for it */
  1460. host->name[len-1] = 0;
  1461. /* Check name for non-ASCII and convert hostname to ACE form if we can */
  1462. if(!is_ASCII_name(host->name)) {
  1463. #ifdef USE_LIBIDN2
  1464. if(idn2_check_version(IDN2_VERSION)) {
  1465. char *ace_hostname = NULL;
  1466. #if IDN2_VERSION_NUMBER >= 0x00140000
  1467. /* IDN2_NFC_INPUT: Normalize input string using normalization form C.
  1468. IDN2_NONTRANSITIONAL: Perform Unicode TR46 non-transitional
  1469. processing. */
  1470. int flags = IDN2_NFC_INPUT | IDN2_NONTRANSITIONAL;
  1471. #else
  1472. int flags = IDN2_NFC_INPUT;
  1473. #endif
  1474. int rc = idn2_lookup_ul((const char *)host->name, &ace_hostname, flags);
  1475. if(rc == IDN2_OK) {
  1476. host->encalloc = (char *)ace_hostname;
  1477. /* change the name pointer to point to the encoded hostname */
  1478. host->name = host->encalloc;
  1479. }
  1480. else {
  1481. failf(data, "Failed to convert %s to ACE; %s\n", host->name,
  1482. idn2_strerror(rc));
  1483. return CURLE_URL_MALFORMAT;
  1484. }
  1485. }
  1486. #elif defined(USE_WIN32_IDN)
  1487. char *ace_hostname = NULL;
  1488. if(curl_win32_idn_to_ascii(host->name, &ace_hostname)) {
  1489. host->encalloc = ace_hostname;
  1490. /* change the name pointer to point to the encoded hostname */
  1491. host->name = host->encalloc;
  1492. }
  1493. else {
  1494. failf(data, "Failed to convert %s to ACE;\n", host->name);
  1495. return CURLE_URL_MALFORMAT;
  1496. }
  1497. #else
  1498. infof(data, "IDN support not present, can't parse Unicode domains\n");
  1499. #endif
  1500. }
  1501. {
  1502. char *hostp;
  1503. for(hostp = host->name; *hostp; hostp++) {
  1504. if(*hostp <= 32) {
  1505. failf(data, "Host name '%s' contains bad letter", host->name);
  1506. return CURLE_URL_MALFORMAT;
  1507. }
  1508. }
  1509. }
  1510. return CURLE_OK;
  1511. }
  1512. /*
  1513. * Frees data allocated by fix_hostname()
  1514. */
  1515. static void free_fixed_hostname(struct hostname *host)
  1516. {
  1517. #if defined(USE_LIBIDN2)
  1518. if(host->encalloc) {
  1519. idn2_free(host->encalloc); /* must be freed with idn2_free() since this was
  1520. allocated by libidn */
  1521. host->encalloc = NULL;
  1522. }
  1523. #elif defined(USE_WIN32_IDN)
  1524. free(host->encalloc); /* must be freed with free() since this was
  1525. allocated by curl_win32_idn_to_ascii */
  1526. host->encalloc = NULL;
  1527. #else
  1528. (void)host;
  1529. #endif
  1530. }
  1531. static void llist_dtor(void *user, void *element)
  1532. {
  1533. (void)user;
  1534. (void)element;
  1535. /* Do nothing */
  1536. }
  1537. /*
  1538. * Allocate and initialize a new connectdata object.
  1539. */
  1540. static struct connectdata *allocate_conn(struct Curl_easy *data)
  1541. {
  1542. struct connectdata *conn = calloc(1, sizeof(struct connectdata));
  1543. if(!conn)
  1544. return NULL;
  1545. #ifdef USE_SSL
  1546. /* The SSL backend-specific data (ssl_backend_data) objects are allocated as
  1547. a separate array to ensure suitable alignment.
  1548. Note that these backend pointers can be swapped by vtls (eg ssl backend
  1549. data becomes proxy backend data). */
  1550. {
  1551. size_t sslsize = Curl_ssl->sizeof_ssl_backend_data;
  1552. char *ssl = calloc(4, sslsize);
  1553. if(!ssl) {
  1554. free(conn);
  1555. return NULL;
  1556. }
  1557. conn->ssl_extra = ssl;
  1558. conn->ssl[0].backend = (void *)ssl;
  1559. conn->ssl[1].backend = (void *)(ssl + sslsize);
  1560. conn->proxy_ssl[0].backend = (void *)(ssl + 2 * sslsize);
  1561. conn->proxy_ssl[1].backend = (void *)(ssl + 3 * sslsize);
  1562. }
  1563. #endif
  1564. conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
  1565. already from start to avoid NULL
  1566. situations and checks */
  1567. /* and we setup a few fields in case we end up actually using this struct */
  1568. conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
  1569. conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
  1570. conn->tempsock[0] = CURL_SOCKET_BAD; /* no file descriptor */
  1571. conn->tempsock[1] = CURL_SOCKET_BAD; /* no file descriptor */
  1572. conn->connection_id = -1; /* no ID */
  1573. conn->port = -1; /* unknown at this point */
  1574. conn->remote_port = -1; /* unknown at this point */
  1575. #if defined(USE_RECV_BEFORE_SEND_WORKAROUND) && defined(DEBUGBUILD)
  1576. conn->postponed[0].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
  1577. conn->postponed[1].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
  1578. #endif /* USE_RECV_BEFORE_SEND_WORKAROUND && DEBUGBUILD */
  1579. /* Default protocol-independent behavior doesn't support persistent
  1580. connections, so we set this to force-close. Protocols that support
  1581. this need to set this to FALSE in their "curl_do" functions. */
  1582. connclose(conn, "Default to force-close");
  1583. /* Store creation time to help future close decision making */
  1584. conn->created = Curl_now();
  1585. conn->data = data; /* Setup the association between this connection
  1586. and the Curl_easy */
  1587. conn->http_proxy.proxytype = data->set.proxytype;
  1588. conn->socks_proxy.proxytype = CURLPROXY_SOCKS4;
  1589. #ifdef CURL_DISABLE_PROXY
  1590. conn->bits.proxy = FALSE;
  1591. conn->bits.httpproxy = FALSE;
  1592. conn->bits.socksproxy = FALSE;
  1593. conn->bits.proxy_user_passwd = FALSE;
  1594. conn->bits.tunnel_proxy = FALSE;
  1595. #else /* CURL_DISABLE_PROXY */
  1596. /* note that these two proxy bits are now just on what looks to be
  1597. requested, they may be altered down the road */
  1598. conn->bits.proxy = (data->set.str[STRING_PROXY] &&
  1599. *data->set.str[STRING_PROXY]) ? TRUE : FALSE;
  1600. conn->bits.httpproxy = (conn->bits.proxy &&
  1601. (conn->http_proxy.proxytype == CURLPROXY_HTTP ||
  1602. conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0 ||
  1603. conn->http_proxy.proxytype == CURLPROXY_HTTPS)) ?
  1604. TRUE : FALSE;
  1605. conn->bits.socksproxy = (conn->bits.proxy &&
  1606. !conn->bits.httpproxy) ? TRUE : FALSE;
  1607. if(data->set.str[STRING_PRE_PROXY] && *data->set.str[STRING_PRE_PROXY]) {
  1608. conn->bits.proxy = TRUE;
  1609. conn->bits.socksproxy = TRUE;
  1610. }
  1611. conn->bits.proxy_user_passwd =
  1612. (data->set.str[STRING_PROXYUSERNAME]) ? TRUE : FALSE;
  1613. conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
  1614. #endif /* CURL_DISABLE_PROXY */
  1615. conn->bits.user_passwd = (data->set.str[STRING_USERNAME]) ? TRUE : FALSE;
  1616. conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
  1617. conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
  1618. conn->ssl_config.verifystatus = data->set.ssl.primary.verifystatus;
  1619. conn->ssl_config.verifypeer = data->set.ssl.primary.verifypeer;
  1620. conn->ssl_config.verifyhost = data->set.ssl.primary.verifyhost;
  1621. conn->proxy_ssl_config.verifystatus =
  1622. data->set.proxy_ssl.primary.verifystatus;
  1623. conn->proxy_ssl_config.verifypeer = data->set.proxy_ssl.primary.verifypeer;
  1624. conn->proxy_ssl_config.verifyhost = data->set.proxy_ssl.primary.verifyhost;
  1625. conn->ip_version = data->set.ipver;
  1626. #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
  1627. defined(NTLM_WB_ENABLED)
  1628. conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
  1629. conn->ntlm_auth_hlpr_pid = 0;
  1630. conn->challenge_header = NULL;
  1631. conn->response_header = NULL;
  1632. #endif
  1633. if(Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1) &&
  1634. !conn->master_buffer) {
  1635. /* Allocate master_buffer to be used for HTTP/1 pipelining */
  1636. conn->master_buffer = calloc(MASTERBUF_SIZE, sizeof(char));
  1637. if(!conn->master_buffer)
  1638. goto error;
  1639. }
  1640. /* Initialize the pipeline lists */
  1641. Curl_llist_init(&conn->send_pipe, (curl_llist_dtor) llist_dtor);
  1642. Curl_llist_init(&conn->recv_pipe, (curl_llist_dtor) llist_dtor);
  1643. #ifdef HAVE_GSSAPI
  1644. conn->data_prot = PROT_CLEAR;
  1645. #endif
  1646. /* Store the local bind parameters that will be used for this connection */
  1647. if(data->set.str[STRING_DEVICE]) {
  1648. conn->localdev = strdup(data->set.str[STRING_DEVICE]);
  1649. if(!conn->localdev)
  1650. goto error;
  1651. }
  1652. conn->localportrange = data->set.localportrange;
  1653. conn->localport = data->set.localport;
  1654. /* the close socket stuff needs to be copied to the connection struct as
  1655. it may live on without (this specific) Curl_easy */
  1656. conn->fclosesocket = data->set.fclosesocket;
  1657. conn->closesocket_client = data->set.closesocket_client;
  1658. return conn;
  1659. error:
  1660. Curl_llist_destroy(&conn->send_pipe, NULL);
  1661. Curl_llist_destroy(&conn->recv_pipe, NULL);
  1662. free(conn->master_buffer);
  1663. free(conn->localdev);
  1664. #ifdef USE_SSL
  1665. free(conn->ssl_extra);
  1666. #endif
  1667. free(conn);
  1668. return NULL;
  1669. }
  1670. static CURLcode findprotocol(struct Curl_easy *data,
  1671. struct connectdata *conn,
  1672. const char *protostr)
  1673. {
  1674. const struct Curl_handler * const *pp;
  1675. const struct Curl_handler *p;
  1676. /* Scan protocol handler table and match against 'protostr' to set a few
  1677. variables based on the URL. Now that the handler may be changed later
  1678. when the protocol specific setup function is called. */
  1679. for(pp = protocols; (p = *pp) != NULL; pp++) {
  1680. if(strcasecompare(p->scheme, protostr)) {
  1681. /* Protocol found in table. Check if allowed */
  1682. if(!(data->set.allowed_protocols & p->protocol))
  1683. /* nope, get out */
  1684. break;
  1685. /* it is allowed for "normal" request, now do an extra check if this is
  1686. the result of a redirect */
  1687. if(data->state.this_is_a_follow &&
  1688. !(data->set.redir_protocols & p->protocol))
  1689. /* nope, get out */
  1690. break;
  1691. /* Perform setup complement if some. */
  1692. conn->handler = conn->given = p;
  1693. /* 'port' and 'remote_port' are set in setup_connection_internals() */
  1694. return CURLE_OK;
  1695. }
  1696. }
  1697. /* The protocol was not found in the table, but we don't have to assign it
  1698. to anything since it is already assigned to a dummy-struct in the
  1699. create_conn() function when the connectdata struct is allocated. */
  1700. failf(data, "Protocol \"%s\" not supported or disabled in " LIBCURL_NAME,
  1701. protostr);
  1702. return CURLE_UNSUPPORTED_PROTOCOL;
  1703. }
  1704. /*
  1705. * Parse URL and fill in the relevant members of the connection struct.
  1706. */
  1707. static CURLcode parseurlandfillconn(struct Curl_easy *data,
  1708. struct connectdata *conn,
  1709. bool *prot_missing,
  1710. char **userp, char **passwdp,
  1711. char **optionsp)
  1712. {
  1713. char *at;
  1714. char *fragment;
  1715. char *path = data->state.path;
  1716. char *query;
  1717. int rc;
  1718. const char *protop = "";
  1719. CURLcode result;
  1720. bool rebuild_url = FALSE;
  1721. bool url_has_scheme = FALSE;
  1722. char protobuf[16];
  1723. *prot_missing = FALSE;
  1724. /* We might pass the entire URL into the request so we need to make sure
  1725. * there are no bad characters in there.*/
  1726. if(strpbrk(data->change.url, "\r\n")) {
  1727. failf(data, "Illegal characters found in URL");
  1728. return CURLE_URL_MALFORMAT;
  1729. }
  1730. /*************************************************************
  1731. * Parse the URL.
  1732. *
  1733. * We need to parse the url even when using the proxy, because we will need
  1734. * the hostname and port in case we are trying to SSL connect through the
  1735. * proxy -- and we don't know if we will need to use SSL until we parse the
  1736. * url ...
  1737. ************************************************************/
  1738. if(data->change.url[0] == ':') {
  1739. failf(data, "Bad URL, colon is first character");
  1740. return CURLE_URL_MALFORMAT;
  1741. }
  1742. /* MSDOS/Windows style drive prefix, eg c: in c:foo */
  1743. #define STARTS_WITH_DRIVE_PREFIX(str) \
  1744. ((('a' <= str[0] && str[0] <= 'z') || \
  1745. ('A' <= str[0] && str[0] <= 'Z')) && \
  1746. (str[1] == ':'))
  1747. /* MSDOS/Windows style drive prefix, optionally with
  1748. * a '|' instead of ':', followed by a slash or NUL */
  1749. #define STARTS_WITH_URL_DRIVE_PREFIX(str) \
  1750. ((('a' <= (str)[0] && (str)[0] <= 'z') || \
  1751. ('A' <= (str)[0] && (str)[0] <= 'Z')) && \
  1752. ((str)[1] == ':' || (str)[1] == '|') && \
  1753. ((str)[2] == '/' || (str)[2] == '\\' || (str)[2] == 0))
  1754. /* Don't mistake a drive letter for a scheme if the default protocol is file.
  1755. curld --proto-default file c:/foo/bar.txt */
  1756. if(STARTS_WITH_DRIVE_PREFIX(data->change.url) &&
  1757. data->set.str[STRING_DEFAULT_PROTOCOL] &&
  1758. strcasecompare(data->set.str[STRING_DEFAULT_PROTOCOL], "file")) {
  1759. ; /* do nothing */
  1760. }
  1761. else { /* check for a scheme */
  1762. int i;
  1763. for(i = 0; i < 16 && data->change.url[i]; ++i) {
  1764. if(data->change.url[i] == '/')
  1765. break;
  1766. if(data->change.url[i] == ':') {
  1767. url_has_scheme = TRUE;
  1768. break;
  1769. }
  1770. }
  1771. }
  1772. /* handle the file: scheme */
  1773. if((url_has_scheme && strncasecompare(data->change.url, "file:", 5)) ||
  1774. (!url_has_scheme && data->set.str[STRING_DEFAULT_PROTOCOL] &&
  1775. strcasecompare(data->set.str[STRING_DEFAULT_PROTOCOL], "file"))) {
  1776. if(url_has_scheme)
  1777. rc = sscanf(data->change.url, "%*15[^\n/:]:%[^\n]", path);
  1778. else
  1779. rc = sscanf(data->change.url, "%[^\n]", path);
  1780. if(rc != 1) {
  1781. failf(data, "Bad URL");
  1782. return CURLE_URL_MALFORMAT;
  1783. }
  1784. /* Extra handling URLs with an authority component (i.e. that start with
  1785. * "file://")
  1786. *
  1787. * We allow omitted hostname (e.g. file:/<path>) -- valid according to
  1788. * RFC 8089, but not the (current) WHAT-WG URL spec.
  1789. */
  1790. if(url_has_scheme && path[0] == '/' && path[1] == '/') {
  1791. /* swallow the two slashes */
  1792. char *ptr = &path[2];
  1793. /*
  1794. * According to RFC 8089, a file: URL can be reliably dereferenced if:
  1795. *
  1796. * o it has no/blank hostname, or
  1797. *
  1798. * o the hostname matches "localhost" (case-insensitively), or
  1799. *
  1800. * o the hostname is a FQDN that resolves to this machine.
  1801. *
  1802. * For brevity, we only consider URLs with empty, "localhost", or
  1803. * "127.0.0.1" hostnames as local.
  1804. *
  1805. * Additionally, there is an exception for URLs with a Windows drive
  1806. * letter in the authority (which was accidentally omitted from RFC 8089
  1807. * Appendix E, but believe me, it was meant to be there. --MK)
  1808. */
  1809. if(ptr[0] != '/' && !STARTS_WITH_URL_DRIVE_PREFIX(ptr)) {
  1810. /* the URL includes a host name, it must match "localhost" or
  1811. "127.0.0.1" to be valid */
  1812. if(!checkprefix("localhost/", ptr) &&
  1813. !checkprefix("127.0.0.1/", ptr)) {
  1814. failf(data, "Invalid file://hostname/, "
  1815. "expected localhost or 127.0.0.1 or none");
  1816. return CURLE_URL_MALFORMAT;
  1817. }
  1818. ptr += 9; /* now points to the slash after the host */
  1819. }
  1820. /* This cannot be done with strcpy, as the memory chunks overlap! */
  1821. memmove(path, ptr, strlen(ptr) + 1);
  1822. }
  1823. #if !defined(MSDOS) && !defined(WIN32) && !defined(__CYGWIN__)
  1824. /* Don't allow Windows drive letters when not in Windows.
  1825. * This catches both "file:/c:" and "file:c:" */
  1826. if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) ||
  1827. STARTS_WITH_URL_DRIVE_PREFIX(path)) {
  1828. failf(data, "File drive letters are only accepted in MSDOS/Windows.");
  1829. return CURLE_URL_MALFORMAT;
  1830. }
  1831. #else
  1832. /* If the path starts with a slash and a drive letter, ditch the slash */
  1833. if('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) {
  1834. /* This cannot be done with strcpy, as the memory chunks overlap! */
  1835. memmove(path, &path[1], strlen(&path[1]) + 1);
  1836. }
  1837. #endif
  1838. protop = "file"; /* protocol string */
  1839. *prot_missing = !url_has_scheme;
  1840. }
  1841. else {
  1842. /* clear path */
  1843. char slashbuf[4];
  1844. path[0] = 0;
  1845. rc = sscanf(data->change.url,
  1846. "%15[^\n/:]:%3[/]%[^\n/?#]%[^\n]",
  1847. protobuf, slashbuf, conn->host.name, path);
  1848. if(2 == rc) {
  1849. failf(data, "Bad URL");
  1850. return CURLE_URL_MALFORMAT;
  1851. }
  1852. if(3 > rc) {
  1853. /*
  1854. * The URL was badly formatted, let's try the browser-style _without_
  1855. * protocol specified like 'http://'.
  1856. */
  1857. rc = sscanf(data->change.url, "%[^\n/?#]%[^\n]", conn->host.name, path);
  1858. if(1 > rc) {
  1859. /*
  1860. * We couldn't even get this format.
  1861. * djgpp 2.04 has a sscanf() bug where 'conn->host.name' is
  1862. * assigned, but the return value is EOF!
  1863. */
  1864. #if defined(__DJGPP__) && (DJGPP_MINOR == 4)
  1865. if(!(rc == -1 && *conn->host.name))
  1866. #endif
  1867. {
  1868. failf(data, "<url> malformed");
  1869. return CURLE_URL_MALFORMAT;
  1870. }
  1871. }
  1872. /*
  1873. * Since there was no protocol part specified in the URL use the
  1874. * user-specified default protocol. If we weren't given a default make a
  1875. * guess by matching some protocols against the host's outermost
  1876. * sub-domain name. Finally if there was no match use HTTP.
  1877. */
  1878. protop = data->set.str[STRING_DEFAULT_PROTOCOL];
  1879. if(!protop) {
  1880. /* Note: if you add a new protocol, please update the list in
  1881. * lib/version.c too! */
  1882. if(checkprefix("FTP.", conn->host.name))
  1883. protop = "ftp";
  1884. else if(checkprefix("DICT.", conn->host.name))
  1885. protop = "DICT";
  1886. else if(checkprefix("LDAP.", conn->host.name))
  1887. protop = "LDAP";
  1888. else if(checkprefix("IMAP.", conn->host.name))
  1889. protop = "IMAP";
  1890. else if(checkprefix("SMTP.", conn->host.name))
  1891. protop = "smtp";
  1892. else if(checkprefix("POP3.", conn->host.name))
  1893. protop = "pop3";
  1894. else
  1895. protop = "http";
  1896. }
  1897. *prot_missing = TRUE; /* not given in URL */
  1898. }
  1899. else {
  1900. size_t s = strlen(slashbuf);
  1901. protop = protobuf;
  1902. if(s != 2) {
  1903. infof(data, "Unwillingly accepted illegal URL using %zu slash%s!\n",
  1904. s, s>1?"es":"");
  1905. if(data->change.url_alloc)
  1906. free(data->change.url);
  1907. /* repair the URL to use two slashes */
  1908. data->change.url = aprintf("%s://%s%s",
  1909. protobuf, conn->host.name, path);
  1910. if(!data->change.url)
  1911. return CURLE_OUT_OF_MEMORY;
  1912. data->change.url_alloc = TRUE;
  1913. }
  1914. }
  1915. }
  1916. /* We search for '?' in the host name (but only on the right side of a
  1917. * @-letter to allow ?-letters in username and password) to handle things
  1918. * like http://example.com?param= (notice the missing '/').
  1919. */
  1920. at = strchr(conn->host.name, '@');
  1921. if(at)
  1922. query = strchr(at + 1, '?');
  1923. else
  1924. query = strchr(conn->host.name, '?');
  1925. if(query) {
  1926. /* We must insert a slash before the '?'-letter in the URL. If the URL had
  1927. a slash after the '?', that is where the path currently begins and the
  1928. '?string' is still part of the host name.
  1929. We must move the trailing part from the host name and put it first in
  1930. the path. And have it all prefixed with a slash.
  1931. */
  1932. size_t hostlen = strlen(query);
  1933. size_t pathlen = strlen(path);
  1934. /* move the existing path plus the zero byte forward, to make room for
  1935. the host-name part */
  1936. memmove(path + hostlen + 1, path, pathlen + 1);
  1937. /* now copy the trailing host part in front of the existing path */
  1938. memcpy(path + 1, query, hostlen);
  1939. path[0]='/'; /* prepend the missing slash */
  1940. rebuild_url = TRUE;
  1941. *query = 0; /* now cut off the hostname at the ? */
  1942. }
  1943. else if(!path[0]) {
  1944. /* if there's no path set, use a single slash */
  1945. strcpy(path, "/");
  1946. rebuild_url = TRUE;
  1947. }
  1948. /* If the URL is malformatted (missing a '/' after hostname before path) we
  1949. * insert a slash here. The only letters except '/' that can start a path is
  1950. * '?' and '#' - as controlled by the two sscanf() patterns above.
  1951. */
  1952. if(path[0] != '/') {
  1953. /* We need this function to deal with overlapping memory areas. We know
  1954. that the memory area 'path' points to is 'urllen' bytes big and that
  1955. is bigger than the path. Use +1 to move the zero byte too. */
  1956. memmove(&path[1], path, strlen(path) + 1);
  1957. path[0] = '/';
  1958. rebuild_url = TRUE;
  1959. }
  1960. else if(!data->set.path_as_is) {
  1961. /* sanitise paths and remove ../ and ./ sequences according to RFC3986 */
  1962. char *newp = Curl_dedotdotify(path);
  1963. if(!newp)
  1964. return CURLE_OUT_OF_MEMORY;
  1965. if(strcmp(newp, path)) {
  1966. rebuild_url = TRUE;
  1967. free(data->state.pathbuffer);
  1968. data->state.pathbuffer = newp;
  1969. data->state.path = newp;
  1970. path = newp;
  1971. }
  1972. else
  1973. free(newp);
  1974. }
  1975. /*
  1976. * "rebuild_url" means that one or more URL components have been modified so
  1977. * we need to generate an updated full version. We need the corrected URL
  1978. * when communicating over HTTP proxy and we don't know at this point if
  1979. * we're using a proxy or not.
  1980. */
  1981. if(rebuild_url) {
  1982. char *reurl;
  1983. size_t plen = strlen(path); /* new path, should be 1 byte longer than
  1984. the original */
  1985. size_t prefixlen = strlen(conn->host.name);
  1986. if(!*prot_missing) {
  1987. size_t protolen = strlen(protop);
  1988. if(curl_strnequal(protop, data->change.url, protolen))
  1989. prefixlen += protolen;
  1990. else {
  1991. failf(data, "<url> malformed");
  1992. return CURLE_URL_MALFORMAT;
  1993. }
  1994. if(curl_strnequal("://", &data->change.url[protolen], 3))
  1995. prefixlen += 3;
  1996. /* only file: is allowed to omit one or both slashes */
  1997. else if(curl_strnequal("file:", data->change.url, 5))
  1998. prefixlen += 1 + (data->change.url[5] == '/');
  1999. else {
  2000. failf(data, "<url> malformed");
  2001. return CURLE_URL_MALFORMAT;
  2002. }
  2003. }
  2004. reurl = malloc(prefixlen + plen + 1);
  2005. if(!reurl)
  2006. return CURLE_OUT_OF_MEMORY;
  2007. /* copy the prefix */
  2008. memcpy(reurl, data->change.url, prefixlen);
  2009. /* append the trailing piece + zerobyte */
  2010. memcpy(&reurl[prefixlen], path, plen + 1);
  2011. /* possible free the old one */
  2012. if(data->change.url_alloc) {
  2013. Curl_safefree(data->change.url);
  2014. data->change.url_alloc = FALSE;
  2015. }
  2016. infof(data, "Rebuilt URL to: %s\n", reurl);
  2017. data->change.url = reurl;
  2018. data->change.url_alloc = TRUE; /* free this later */
  2019. }
  2020. result = findprotocol(data, conn, protop);
  2021. if(result)
  2022. return result;
  2023. /*
  2024. * Parse the login details from the URL and strip them out of
  2025. * the host name
  2026. */
  2027. result = parse_url_login(data, conn, userp, passwdp, optionsp);
  2028. if(result)
  2029. return result;
  2030. if(conn->host.name[0] == '[') {
  2031. /* This looks like an IPv6 address literal. See if there is an address
  2032. scope if there is no location header */
  2033. char *percent = strchr(conn->host.name, '%');
  2034. if(percent) {
  2035. unsigned int identifier_offset = 3;
  2036. char *endp;
  2037. unsigned long scope;
  2038. if(strncmp("%25", percent, 3) != 0) {
  2039. infof(data,
  2040. "Please URL encode %% as %%25, see RFC 6874.\n");
  2041. identifier_offset = 1;
  2042. }
  2043. scope = strtoul(percent + identifier_offset, &endp, 10);
  2044. if(*endp == ']') {
  2045. /* The address scope was well formed. Knock it out of the
  2046. hostname. */
  2047. memmove(percent, endp, strlen(endp) + 1);
  2048. conn->scope_id = (unsigned int)scope;
  2049. }
  2050. else {
  2051. /* Zone identifier is not numeric */
  2052. #if defined(HAVE_NET_IF_H) && defined(IFNAMSIZ) && defined(HAVE_IF_NAMETOINDEX)
  2053. char ifname[IFNAMSIZ + 2];
  2054. char *square_bracket;
  2055. unsigned int scopeidx = 0;
  2056. strncpy(ifname, percent + identifier_offset, IFNAMSIZ + 2);
  2057. /* Ensure nullbyte termination */
  2058. ifname[IFNAMSIZ + 1] = '\0';
  2059. square_bracket = strchr(ifname, ']');
  2060. if(square_bracket) {
  2061. /* Remove ']' */
  2062. *square_bracket = '\0';
  2063. scopeidx = if_nametoindex(ifname);
  2064. if(scopeidx == 0) {
  2065. infof(data, "Invalid network interface: %s; %s\n", ifname,
  2066. strerror(errno));
  2067. }
  2068. }
  2069. if(scopeidx > 0) {
  2070. char *p = percent + identifier_offset + strlen(ifname);
  2071. /* Remove zone identifier from hostname */
  2072. memmove(percent, p, strlen(p) + 1);
  2073. conn->scope_id = scopeidx;
  2074. }
  2075. else
  2076. #endif /* HAVE_NET_IF_H && IFNAMSIZ */
  2077. infof(data, "Invalid IPv6 address format\n");
  2078. }
  2079. }
  2080. }
  2081. if(data->set.scope_id)
  2082. /* Override any scope that was set above. */
  2083. conn->scope_id = data->set.scope_id;
  2084. /* Remove the fragment part of the path. Per RFC 2396, this is always the
  2085. last part of the URI. We are looking for the first '#' so that we deal
  2086. gracefully with non conformant URI such as http://example.com#foo#bar. */
  2087. fragment = strchr(path, '#');
  2088. if(fragment) {
  2089. *fragment = 0;
  2090. /* we know the path part ended with a fragment, so we know the full URL
  2091. string does too and we need to cut it off from there so it isn't used
  2092. over proxy */
  2093. fragment = strchr(data->change.url, '#');
  2094. if(fragment)
  2095. *fragment = 0;
  2096. }
  2097. /*
  2098. * So if the URL was A://B/C#D,
  2099. * protop is A
  2100. * conn->host.name is B
  2101. * data->state.path is /C
  2102. */
  2103. return CURLE_OK;
  2104. }
  2105. /*
  2106. * If we're doing a resumed transfer, we need to setup our stuff
  2107. * properly.
  2108. */
  2109. static CURLcode setup_range(struct Curl_easy *data)
  2110. {
  2111. struct UrlState *s = &data->state;
  2112. s->resume_from = data->set.set_resume_from;
  2113. if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
  2114. if(s->rangestringalloc)
  2115. free(s->range);
  2116. if(s->resume_from)
  2117. s->range = aprintf("%" CURL_FORMAT_CURL_OFF_T "-", s->resume_from);
  2118. else
  2119. s->range = strdup(data->set.str[STRING_SET_RANGE]);
  2120. s->rangestringalloc = (s->range) ? TRUE : FALSE;
  2121. if(!s->range)
  2122. return CURLE_OUT_OF_MEMORY;
  2123. /* tell ourselves to fetch this range */
  2124. s->use_range = TRUE; /* enable range download */
  2125. }
  2126. else
  2127. s->use_range = FALSE; /* disable range download */
  2128. return CURLE_OK;
  2129. }
  2130. /*
  2131. * setup_connection_internals() -
  2132. *
  2133. * Setup connection internals specific to the requested protocol in the
  2134. * Curl_easy. This is inited and setup before the connection is made but
  2135. * is about the particular protocol that is to be used.
  2136. *
  2137. * This MUST get called after proxy magic has been figured out.
  2138. */
  2139. static CURLcode setup_connection_internals(struct connectdata *conn)
  2140. {
  2141. const struct Curl_handler * p;
  2142. CURLcode result;
  2143. conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
  2144. /* Perform setup complement if some. */
  2145. p = conn->handler;
  2146. if(p->setup_connection) {
  2147. result = (*p->setup_connection)(conn);
  2148. if(result)
  2149. return result;
  2150. p = conn->handler; /* May have changed. */
  2151. }
  2152. if(conn->port < 0)
  2153. /* we check for -1 here since if proxy was detected already, this
  2154. was very likely already set to the proxy port */
  2155. conn->port = p->defport;
  2156. return CURLE_OK;
  2157. }
  2158. /*
  2159. * Curl_free_request_state() should free temp data that was allocated in the
  2160. * Curl_easy for this single request.
  2161. */
  2162. void Curl_free_request_state(struct Curl_easy *data)
  2163. {
  2164. Curl_safefree(data->req.protop);
  2165. Curl_safefree(data->req.newurl);
  2166. }
  2167. #ifndef CURL_DISABLE_PROXY
  2168. /****************************************************************
  2169. * Checks if the host is in the noproxy list. returns true if it matches
  2170. * and therefore the proxy should NOT be used.
  2171. ****************************************************************/
  2172. static bool check_noproxy(const char *name, const char *no_proxy)
  2173. {
  2174. /* no_proxy=domain1.dom,host.domain2.dom
  2175. * (a comma-separated list of hosts which should
  2176. * not be proxied, or an asterisk to override
  2177. * all proxy variables)
  2178. */
  2179. if(no_proxy && no_proxy[0]) {
  2180. size_t tok_start;
  2181. size_t tok_end;
  2182. const char *separator = ", ";
  2183. size_t no_proxy_len;
  2184. size_t namelen;
  2185. char *endptr;
  2186. if(strcasecompare("*", no_proxy)) {
  2187. return TRUE;
  2188. }
  2189. /* NO_PROXY was specified and it wasn't just an asterisk */
  2190. no_proxy_len = strlen(no_proxy);
  2191. if(name[0] == '[') {
  2192. /* IPv6 numerical address */
  2193. endptr = strchr(name, ']');
  2194. if(!endptr)
  2195. return FALSE;
  2196. name++;
  2197. }
  2198. else
  2199. endptr = strchr(name, ':');
  2200. if(endptr)
  2201. namelen = endptr - name;
  2202. else
  2203. namelen = strlen(name);
  2204. for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
  2205. while(tok_start < no_proxy_len &&
  2206. strchr(separator, no_proxy[tok_start]) != NULL) {
  2207. /* Look for the beginning of the token. */
  2208. ++tok_start;
  2209. }
  2210. if(tok_start == no_proxy_len)
  2211. break; /* It was all trailing separator chars, no more tokens. */
  2212. for(tok_end = tok_start; tok_end < no_proxy_len &&
  2213. strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
  2214. /* Look for the end of the token. */
  2215. ;
  2216. /* To match previous behaviour, where it was necessary to specify
  2217. * ".local.com" to prevent matching "notlocal.com", we will leave
  2218. * the '.' off.
  2219. */
  2220. if(no_proxy[tok_start] == '.')
  2221. ++tok_start;
  2222. if((tok_end - tok_start) <= namelen) {
  2223. /* Match the last part of the name to the domain we are checking. */
  2224. const char *checkn = name + namelen - (tok_end - tok_start);
  2225. if(strncasecompare(no_proxy + tok_start, checkn,
  2226. tok_end - tok_start)) {
  2227. if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
  2228. /* We either have an exact match, or the previous character is a .
  2229. * so it is within the same domain, so no proxy for this host.
  2230. */
  2231. return TRUE;
  2232. }
  2233. }
  2234. } /* if((tok_end - tok_start) <= namelen) */
  2235. } /* for(tok_start = 0; tok_start < no_proxy_len;
  2236. tok_start = tok_end + 1) */
  2237. } /* NO_PROXY was specified and it wasn't just an asterisk */
  2238. return FALSE;
  2239. }
  2240. #ifndef CURL_DISABLE_HTTP
  2241. /****************************************************************
  2242. * Detect what (if any) proxy to use. Remember that this selects a host
  2243. * name and is not limited to HTTP proxies only.
  2244. * The returned pointer must be freed by the caller (unless NULL)
  2245. ****************************************************************/
  2246. static char *detect_proxy(struct connectdata *conn)
  2247. {
  2248. char *proxy = NULL;
  2249. /* If proxy was not specified, we check for default proxy environment
  2250. * variables, to enable i.e Lynx compliance:
  2251. *
  2252. * http_proxy=http://some.server.dom:port/
  2253. * https_proxy=http://some.server.dom:port/
  2254. * ftp_proxy=http://some.server.dom:port/
  2255. * no_proxy=domain1.dom,host.domain2.dom
  2256. * (a comma-separated list of hosts which should
  2257. * not be proxied, or an asterisk to override
  2258. * all proxy variables)
  2259. * all_proxy=http://some.server.dom:port/
  2260. * (seems to exist for the CERN www lib. Probably
  2261. * the first to check for.)
  2262. *
  2263. * For compatibility, the all-uppercase versions of these variables are
  2264. * checked if the lowercase versions don't exist.
  2265. */
  2266. char proxy_env[128];
  2267. const char *protop = conn->handler->scheme;
  2268. char *envp = proxy_env;
  2269. char *prox;
  2270. /* Now, build <protocol>_proxy and check for such a one to use */
  2271. while(*protop)
  2272. *envp++ = (char)tolower((int)*protop++);
  2273. /* append _proxy */
  2274. strcpy(envp, "_proxy");
  2275. /* read the protocol proxy: */
  2276. prox = curl_getenv(proxy_env);
  2277. /*
  2278. * We don't try the uppercase version of HTTP_PROXY because of
  2279. * security reasons:
  2280. *
  2281. * When curl is used in a webserver application
  2282. * environment (cgi or php), this environment variable can
  2283. * be controlled by the web server user by setting the
  2284. * http header 'Proxy:' to some value.
  2285. *
  2286. * This can cause 'internal' http/ftp requests to be
  2287. * arbitrarily redirected by any external attacker.
  2288. */
  2289. if(!prox && !strcasecompare("http_proxy", proxy_env)) {
  2290. /* There was no lowercase variable, try the uppercase version: */
  2291. Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
  2292. prox = curl_getenv(proxy_env);
  2293. }
  2294. envp = proxy_env;
  2295. if(prox) {
  2296. proxy = prox; /* use this */
  2297. }
  2298. else {
  2299. envp = (char *)"all_proxy";
  2300. proxy = curl_getenv(envp); /* default proxy to use */
  2301. if(!proxy) {
  2302. envp = (char *)"ALL_PROXY";
  2303. proxy = curl_getenv(envp);
  2304. }
  2305. }
  2306. if(proxy)
  2307. infof(conn->data, "Uses proxy env variable %s == '%s'\n", envp, proxy);
  2308. return proxy;
  2309. }
  2310. #endif /* CURL_DISABLE_HTTP */
  2311. /*
  2312. * If this is supposed to use a proxy, we need to figure out the proxy
  2313. * host name, so that we can re-use an existing connection
  2314. * that may exist registered to the same proxy host.
  2315. */
  2316. static CURLcode parse_proxy(struct Curl_easy *data,
  2317. struct connectdata *conn, char *proxy,
  2318. curl_proxytype proxytype)
  2319. {
  2320. char *prox_portno;
  2321. char *endofprot;
  2322. /* We use 'proxyptr' to point to the proxy name from now on... */
  2323. char *proxyptr;
  2324. char *portptr;
  2325. char *atsign;
  2326. long port = -1;
  2327. char *proxyuser = NULL;
  2328. char *proxypasswd = NULL;
  2329. bool sockstype;
  2330. /* We do the proxy host string parsing here. We want the host name and the
  2331. * port name. Accept a protocol:// prefix
  2332. */
  2333. /* Parse the protocol part if present */
  2334. endofprot = strstr(proxy, "://");
  2335. if(endofprot) {
  2336. proxyptr = endofprot + 3;
  2337. if(checkprefix("https", proxy))
  2338. proxytype = CURLPROXY_HTTPS;
  2339. else if(checkprefix("socks5h", proxy))
  2340. proxytype = CURLPROXY_SOCKS5_HOSTNAME;
  2341. else if(checkprefix("socks5", proxy))
  2342. proxytype = CURLPROXY_SOCKS5;
  2343. else if(checkprefix("socks4a", proxy))
  2344. proxytype = CURLPROXY_SOCKS4A;
  2345. else if(checkprefix("socks4", proxy) || checkprefix("socks", proxy))
  2346. proxytype = CURLPROXY_SOCKS4;
  2347. else if(checkprefix("http:", proxy))
  2348. ; /* leave it as HTTP or HTTP/1.0 */
  2349. else {
  2350. /* Any other xxx:// reject! */
  2351. failf(data, "Unsupported proxy scheme for \'%s\'", proxy);
  2352. return CURLE_COULDNT_CONNECT;
  2353. }
  2354. }
  2355. else
  2356. proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
  2357. #ifdef USE_SSL
  2358. if(!(Curl_ssl->supports & SSLSUPP_HTTPS_PROXY))
  2359. #endif
  2360. if(proxytype == CURLPROXY_HTTPS) {
  2361. failf(data, "Unsupported proxy \'%s\', libcurl is built without the "
  2362. "HTTPS-proxy support.", proxy);
  2363. return CURLE_NOT_BUILT_IN;
  2364. }
  2365. sockstype = proxytype == CURLPROXY_SOCKS5_HOSTNAME ||
  2366. proxytype == CURLPROXY_SOCKS5 ||
  2367. proxytype == CURLPROXY_SOCKS4A ||
  2368. proxytype == CURLPROXY_SOCKS4;
  2369. /* Is there a username and password given in this proxy url? */
  2370. atsign = strchr(proxyptr, '@');
  2371. if(atsign) {
  2372. CURLcode result =
  2373. Curl_parse_login_details(proxyptr, atsign - proxyptr,
  2374. &proxyuser, &proxypasswd, NULL);
  2375. if(result)
  2376. return result;
  2377. proxyptr = atsign + 1;
  2378. }
  2379. /* start scanning for port number at this point */
  2380. portptr = proxyptr;
  2381. /* detect and extract RFC6874-style IPv6-addresses */
  2382. if(*proxyptr == '[') {
  2383. char *ptr = ++proxyptr; /* advance beyond the initial bracket */
  2384. while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
  2385. ptr++;
  2386. if(*ptr == '%') {
  2387. /* There might be a zone identifier */
  2388. if(strncmp("%25", ptr, 3))
  2389. infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
  2390. ptr++;
  2391. /* Allow unreserved characters as defined in RFC 3986 */
  2392. while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
  2393. (*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
  2394. ptr++;
  2395. }
  2396. if(*ptr == ']')
  2397. /* yeps, it ended nicely with a bracket as well */
  2398. *ptr++ = 0;
  2399. else
  2400. infof(data, "Invalid IPv6 address format\n");
  2401. portptr = ptr;
  2402. /* Note that if this didn't end with a bracket, we still advanced the
  2403. * proxyptr first, but I can't see anything wrong with that as no host
  2404. * name nor a numeric can legally start with a bracket.
  2405. */
  2406. }
  2407. /* Get port number off proxy.server.com:1080 */
  2408. prox_portno = strchr(portptr, ':');
  2409. if(prox_portno) {
  2410. char *endp = NULL;
  2411. *prox_portno = 0x0; /* cut off number from host name */
  2412. prox_portno ++;
  2413. /* now set the local port number */
  2414. port = strtol(prox_portno, &endp, 10);
  2415. if((endp && *endp && (*endp != '/') && (*endp != ' ')) ||
  2416. (port < 0) || (port > 65535)) {
  2417. /* meant to detect for example invalid IPv6 numerical addresses without
  2418. brackets: "2a00:fac0:a000::7:13". Accept a trailing slash only
  2419. because we then allow "URL style" with the number followed by a
  2420. slash, used in curl test cases already. Space is also an acceptable
  2421. terminating symbol. */
  2422. infof(data, "No valid port number in proxy string (%s)\n",
  2423. prox_portno);
  2424. }
  2425. else
  2426. conn->port = port;
  2427. }
  2428. else {
  2429. if(proxyptr[0]=='/') {
  2430. /* If the first character in the proxy string is a slash, fail
  2431. immediately. The following code will otherwise clear the string which
  2432. will lead to code running as if no proxy was set! */
  2433. Curl_safefree(proxyuser);
  2434. Curl_safefree(proxypasswd);
  2435. return CURLE_COULDNT_RESOLVE_PROXY;
  2436. }
  2437. /* without a port number after the host name, some people seem to use
  2438. a slash so we strip everything from the first slash */
  2439. atsign = strchr(proxyptr, '/');
  2440. if(atsign)
  2441. *atsign = '\0'; /* cut off path part from host name */
  2442. if(data->set.proxyport)
  2443. /* None given in the proxy string, then get the default one if it is
  2444. given */
  2445. port = data->set.proxyport;
  2446. else {
  2447. if(proxytype == CURLPROXY_HTTPS)
  2448. port = CURL_DEFAULT_HTTPS_PROXY_PORT;
  2449. else
  2450. port = CURL_DEFAULT_PROXY_PORT;
  2451. }
  2452. }
  2453. if(*proxyptr) {
  2454. struct proxy_info *proxyinfo =
  2455. sockstype ? &conn->socks_proxy : &conn->http_proxy;
  2456. proxyinfo->proxytype = proxytype;
  2457. if(proxyuser) {
  2458. /* found user and password, rip them out. note that we are unescaping
  2459. them, as there is otherwise no way to have a username or password
  2460. with reserved characters like ':' in them. */
  2461. Curl_safefree(proxyinfo->user);
  2462. proxyinfo->user = curl_easy_unescape(data, proxyuser, 0, NULL);
  2463. Curl_safefree(proxyuser);
  2464. if(!proxyinfo->user) {
  2465. Curl_safefree(proxypasswd);
  2466. return CURLE_OUT_OF_MEMORY;
  2467. }
  2468. Curl_safefree(proxyinfo->passwd);
  2469. if(proxypasswd && strlen(proxypasswd) < MAX_CURL_PASSWORD_LENGTH)
  2470. proxyinfo->passwd = curl_easy_unescape(data, proxypasswd, 0, NULL);
  2471. else
  2472. proxyinfo->passwd = strdup("");
  2473. Curl_safefree(proxypasswd);
  2474. if(!proxyinfo->passwd)
  2475. return CURLE_OUT_OF_MEMORY;
  2476. conn->bits.proxy_user_passwd = TRUE; /* enable it */
  2477. }
  2478. if(port >= 0) {
  2479. proxyinfo->port = port;
  2480. if(conn->port < 0 || sockstype || !conn->socks_proxy.host.rawalloc)
  2481. conn->port = port;
  2482. }
  2483. /* now, clone the cleaned proxy host name */
  2484. Curl_safefree(proxyinfo->host.rawalloc);
  2485. proxyinfo->host.rawalloc = strdup(proxyptr);
  2486. proxyinfo->host.name = proxyinfo->host.rawalloc;
  2487. if(!proxyinfo->host.rawalloc)
  2488. return CURLE_OUT_OF_MEMORY;
  2489. }
  2490. Curl_safefree(proxyuser);
  2491. Curl_safefree(proxypasswd);
  2492. return CURLE_OK;
  2493. }
  2494. /*
  2495. * Extract the user and password from the authentication string
  2496. */
  2497. static CURLcode parse_proxy_auth(struct Curl_easy *data,
  2498. struct connectdata *conn)
  2499. {
  2500. char proxyuser[MAX_CURL_USER_LENGTH]="";
  2501. char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
  2502. CURLcode result;
  2503. if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
  2504. strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
  2505. MAX_CURL_USER_LENGTH);
  2506. proxyuser[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
  2507. }
  2508. if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
  2509. strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
  2510. MAX_CURL_PASSWORD_LENGTH);
  2511. proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
  2512. }
  2513. result = Curl_urldecode(data, proxyuser, 0, &conn->http_proxy.user, NULL,
  2514. FALSE);
  2515. if(!result)
  2516. result = Curl_urldecode(data, proxypasswd, 0, &conn->http_proxy.passwd,
  2517. NULL, FALSE);
  2518. return result;
  2519. }
  2520. /* create_conn helper to parse and init proxy values. to be called after unix
  2521. socket init but before any proxy vars are evaluated. */
  2522. static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
  2523. {
  2524. char *proxy = NULL;
  2525. char *socksproxy = NULL;
  2526. char *no_proxy = NULL;
  2527. CURLcode result = CURLE_OK;
  2528. struct Curl_easy *data = conn->data;
  2529. /*************************************************************
  2530. * Extract the user and password from the authentication string
  2531. *************************************************************/
  2532. if(conn->bits.proxy_user_passwd) {
  2533. result = parse_proxy_auth(data, conn);
  2534. if(result)
  2535. goto out;
  2536. }
  2537. /*************************************************************
  2538. * Detect what (if any) proxy to use
  2539. *************************************************************/
  2540. if(data->set.str[STRING_PROXY]) {
  2541. proxy = strdup(data->set.str[STRING_PROXY]);
  2542. /* if global proxy is set, this is it */
  2543. if(NULL == proxy) {
  2544. failf(data, "memory shortage");
  2545. result = CURLE_OUT_OF_MEMORY;
  2546. goto out;
  2547. }
  2548. }
  2549. if(data->set.str[STRING_PRE_PROXY]) {
  2550. socksproxy = strdup(data->set.str[STRING_PRE_PROXY]);
  2551. /* if global socks proxy is set, this is it */
  2552. if(NULL == socksproxy) {
  2553. failf(data, "memory shortage");
  2554. result = CURLE_OUT_OF_MEMORY;
  2555. goto out;
  2556. }
  2557. }
  2558. if(!data->set.str[STRING_NOPROXY]) {
  2559. const char *p = "no_proxy";
  2560. no_proxy = curl_getenv(p);
  2561. if(!no_proxy) {
  2562. p = "NO_PROXY";
  2563. no_proxy = curl_getenv(p);
  2564. }
  2565. if(no_proxy) {
  2566. infof(conn->data, "Uses proxy env variable %s == '%s'\n", p, no_proxy);
  2567. }
  2568. }
  2569. if(check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY] ?
  2570. data->set.str[STRING_NOPROXY] : no_proxy)) {
  2571. Curl_safefree(proxy);
  2572. Curl_safefree(socksproxy);
  2573. }
  2574. #ifndef CURL_DISABLE_HTTP
  2575. else if(!proxy && !socksproxy)
  2576. /* if the host is not in the noproxy list, detect proxy. */
  2577. proxy = detect_proxy(conn);
  2578. #endif /* CURL_DISABLE_HTTP */
  2579. Curl_safefree(no_proxy);
  2580. #ifdef USE_UNIX_SOCKETS
  2581. /* For the time being do not mix proxy and unix domain sockets. See #1274 */
  2582. if(proxy && conn->unix_domain_socket) {
  2583. free(proxy);
  2584. proxy = NULL;
  2585. }
  2586. #endif
  2587. if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
  2588. free(proxy); /* Don't bother with an empty proxy string or if the
  2589. protocol doesn't work with network */
  2590. proxy = NULL;
  2591. }
  2592. if(socksproxy && (!*socksproxy ||
  2593. (conn->handler->flags & PROTOPT_NONETWORK))) {
  2594. free(socksproxy); /* Don't bother with an empty socks proxy string or if
  2595. the protocol doesn't work with network */
  2596. socksproxy = NULL;
  2597. }
  2598. /***********************************************************************
  2599. * If this is supposed to use a proxy, we need to figure out the proxy host
  2600. * name, proxy type and port number, so that we can re-use an existing
  2601. * connection that may exist registered to the same proxy host.
  2602. ***********************************************************************/
  2603. if(proxy || socksproxy) {
  2604. if(proxy) {
  2605. result = parse_proxy(data, conn, proxy, conn->http_proxy.proxytype);
  2606. Curl_safefree(proxy); /* parse_proxy copies the proxy string */
  2607. if(result)
  2608. goto out;
  2609. }
  2610. if(socksproxy) {
  2611. result = parse_proxy(data, conn, socksproxy,
  2612. conn->socks_proxy.proxytype);
  2613. /* parse_proxy copies the socks proxy string */
  2614. Curl_safefree(socksproxy);
  2615. if(result)
  2616. goto out;
  2617. }
  2618. if(conn->http_proxy.host.rawalloc) {
  2619. #ifdef CURL_DISABLE_HTTP
  2620. /* asking for a HTTP proxy is a bit funny when HTTP is disabled... */
  2621. result = CURLE_UNSUPPORTED_PROTOCOL;
  2622. goto out;
  2623. #else
  2624. /* force this connection's protocol to become HTTP if compatible */
  2625. if(!(conn->handler->protocol & PROTO_FAMILY_HTTP)) {
  2626. if((conn->handler->flags & PROTOPT_PROXY_AS_HTTP) &&
  2627. !conn->bits.tunnel_proxy)
  2628. conn->handler = &Curl_handler_http;
  2629. else
  2630. /* if not converting to HTTP over the proxy, enforce tunneling */
  2631. conn->bits.tunnel_proxy = TRUE;
  2632. }
  2633. conn->bits.httpproxy = TRUE;
  2634. #endif
  2635. }
  2636. else {
  2637. conn->bits.httpproxy = FALSE; /* not a HTTP proxy */
  2638. conn->bits.tunnel_proxy = FALSE; /* no tunneling if not HTTP */
  2639. }
  2640. if(conn->socks_proxy.host.rawalloc) {
  2641. if(!conn->http_proxy.host.rawalloc) {
  2642. /* once a socks proxy */
  2643. if(!conn->socks_proxy.user) {
  2644. conn->socks_proxy.user = conn->http_proxy.user;
  2645. conn->http_proxy.user = NULL;
  2646. Curl_safefree(conn->socks_proxy.passwd);
  2647. conn->socks_proxy.passwd = conn->http_proxy.passwd;
  2648. conn->http_proxy.passwd = NULL;
  2649. }
  2650. }
  2651. conn->bits.socksproxy = TRUE;
  2652. }
  2653. else
  2654. conn->bits.socksproxy = FALSE; /* not a socks proxy */
  2655. }
  2656. else {
  2657. conn->bits.socksproxy = FALSE;
  2658. conn->bits.httpproxy = FALSE;
  2659. }
  2660. conn->bits.proxy = conn->bits.httpproxy || conn->bits.socksproxy;
  2661. if(!conn->bits.proxy) {
  2662. /* we aren't using the proxy after all... */
  2663. conn->bits.proxy = FALSE;
  2664. conn->bits.httpproxy = FALSE;
  2665. conn->bits.socksproxy = FALSE;
  2666. conn->bits.proxy_user_passwd = FALSE;
  2667. conn->bits.tunnel_proxy = FALSE;
  2668. }
  2669. out:
  2670. free(socksproxy);
  2671. free(proxy);
  2672. return result;
  2673. }
  2674. #endif /* CURL_DISABLE_PROXY */
  2675. /*
  2676. * parse_url_login()
  2677. *
  2678. * Parse the login details (user name, password and options) from the URL and
  2679. * strip them out of the host name
  2680. *
  2681. * Inputs: data->set.use_netrc (CURLOPT_NETRC)
  2682. * conn->host.name
  2683. *
  2684. * Outputs: (almost :- all currently undefined)
  2685. * conn->bits.user_passwd - non-zero if non-default passwords exist
  2686. * user - non-zero length if defined
  2687. * passwd - non-zero length if defined
  2688. * options - non-zero length if defined
  2689. * conn->host.name - remove user name and password
  2690. */
  2691. static CURLcode parse_url_login(struct Curl_easy *data,
  2692. struct connectdata *conn,
  2693. char **user, char **passwd, char **options)
  2694. {
  2695. CURLcode result = CURLE_OK;
  2696. char *userp = NULL;
  2697. char *passwdp = NULL;
  2698. char *optionsp = NULL;
  2699. /* At this point, we're hoping all the other special cases have
  2700. * been taken care of, so conn->host.name is at most
  2701. * [user[:password][;options]]@]hostname
  2702. *
  2703. * We need somewhere to put the embedded details, so do that first.
  2704. */
  2705. char *ptr = strchr(conn->host.name, '@');
  2706. char *login = conn->host.name;
  2707. DEBUGASSERT(!**user);
  2708. DEBUGASSERT(!**passwd);
  2709. DEBUGASSERT(!**options);
  2710. DEBUGASSERT(conn->handler);
  2711. if(!ptr)
  2712. goto out;
  2713. /* We will now try to extract the
  2714. * possible login information in a string like:
  2715. * ftp://user:password@ftp.my.site:8021/README */
  2716. conn->host.name = ++ptr;
  2717. /* So the hostname is sane. Only bother interpreting the
  2718. * results if we could care. It could still be wasted
  2719. * work because it might be overtaken by the programmatically
  2720. * set user/passwd, but doing that first adds more cases here :-(
  2721. */
  2722. if(data->set.use_netrc == CURL_NETRC_REQUIRED)
  2723. goto out;
  2724. /* We could use the login information in the URL so extract it. Only parse
  2725. options if the handler says we should. */
  2726. result =
  2727. Curl_parse_login_details(login, ptr - login - 1,
  2728. &userp, &passwdp,
  2729. (conn->handler->flags & PROTOPT_URLOPTIONS)?
  2730. &optionsp:NULL);
  2731. if(result)
  2732. goto out;
  2733. if(userp) {
  2734. char *newname;
  2735. if(data->set.disallow_username_in_url) {
  2736. failf(data, "Option DISALLOW_USERNAME_IN_URL is set "
  2737. "and url contains username.");
  2738. result = CURLE_LOGIN_DENIED;
  2739. goto out;
  2740. }
  2741. /* We have a user in the URL */
  2742. conn->bits.userpwd_in_url = TRUE;
  2743. conn->bits.user_passwd = TRUE; /* enable user+password */
  2744. /* Decode the user */
  2745. result = Curl_urldecode(data, userp, 0, &newname, NULL, FALSE);
  2746. if(result) {
  2747. goto out;
  2748. }
  2749. free(*user);
  2750. *user = newname;
  2751. }
  2752. if(passwdp) {
  2753. /* We have a password in the URL so decode it */
  2754. char *newpasswd;
  2755. result = Curl_urldecode(data, passwdp, 0, &newpasswd, NULL, FALSE);
  2756. if(result) {
  2757. goto out;
  2758. }
  2759. free(*passwd);
  2760. *passwd = newpasswd;
  2761. }
  2762. if(optionsp) {
  2763. /* We have an options list in the URL so decode it */
  2764. char *newoptions;
  2765. result = Curl_urldecode(data, optionsp, 0, &newoptions, NULL, FALSE);
  2766. if(result) {
  2767. goto out;
  2768. }
  2769. free(*options);
  2770. *options = newoptions;
  2771. }
  2772. out:
  2773. free(userp);
  2774. free(passwdp);
  2775. free(optionsp);
  2776. return result;
  2777. }
  2778. /*
  2779. * Curl_parse_login_details()
  2780. *
  2781. * This is used to parse a login string for user name, password and options in
  2782. * the following formats:
  2783. *
  2784. * user
  2785. * user:password
  2786. * user:password;options
  2787. * user;options
  2788. * user;options:password
  2789. * :password
  2790. * :password;options
  2791. * ;options
  2792. * ;options:password
  2793. *
  2794. * Parameters:
  2795. *
  2796. * login [in] - The login string.
  2797. * len [in] - The length of the login string.
  2798. * userp [in/out] - The address where a pointer to newly allocated memory
  2799. * holding the user will be stored upon completion.
  2800. * passdwp [in/out] - The address where a pointer to newly allocated memory
  2801. * holding the password will be stored upon completion.
  2802. * optionsp [in/out] - The address where a pointer to newly allocated memory
  2803. * holding the options will be stored upon completion.
  2804. *
  2805. * Returns CURLE_OK on success.
  2806. */
  2807. CURLcode Curl_parse_login_details(const char *login, const size_t len,
  2808. char **userp, char **passwdp,
  2809. char **optionsp)
  2810. {
  2811. CURLcode result = CURLE_OK;
  2812. char *ubuf = NULL;
  2813. char *pbuf = NULL;
  2814. char *obuf = NULL;
  2815. const char *psep = NULL;
  2816. const char *osep = NULL;
  2817. size_t ulen;
  2818. size_t plen;
  2819. size_t olen;
  2820. /* Attempt to find the password separator */
  2821. if(passwdp) {
  2822. psep = strchr(login, ':');
  2823. /* Within the constraint of the login string */
  2824. if(psep >= login + len)
  2825. psep = NULL;
  2826. }
  2827. /* Attempt to find the options separator */
  2828. if(optionsp) {
  2829. osep = strchr(login, ';');
  2830. /* Within the constraint of the login string */
  2831. if(osep >= login + len)
  2832. osep = NULL;
  2833. }
  2834. /* Calculate the portion lengths */
  2835. ulen = (psep ?
  2836. (size_t)(osep && psep > osep ? osep - login : psep - login) :
  2837. (osep ? (size_t)(osep - login) : len));
  2838. plen = (psep ?
  2839. (osep && osep > psep ? (size_t)(osep - psep) :
  2840. (size_t)(login + len - psep)) - 1 : 0);
  2841. olen = (osep ?
  2842. (psep && psep > osep ? (size_t)(psep - osep) :
  2843. (size_t)(login + len - osep)) - 1 : 0);
  2844. /* Allocate the user portion buffer */
  2845. if(userp && ulen) {
  2846. ubuf = malloc(ulen + 1);
  2847. if(!ubuf)
  2848. result = CURLE_OUT_OF_MEMORY;
  2849. }
  2850. /* Allocate the password portion buffer */
  2851. if(!result && passwdp && plen) {
  2852. pbuf = malloc(plen + 1);
  2853. if(!pbuf) {
  2854. free(ubuf);
  2855. result = CURLE_OUT_OF_MEMORY;
  2856. }
  2857. }
  2858. /* Allocate the options portion buffer */
  2859. if(!result && optionsp && olen) {
  2860. obuf = malloc(olen + 1);
  2861. if(!obuf) {
  2862. free(pbuf);
  2863. free(ubuf);
  2864. result = CURLE_OUT_OF_MEMORY;
  2865. }
  2866. }
  2867. if(!result) {
  2868. /* Store the user portion if necessary */
  2869. if(ubuf) {
  2870. memcpy(ubuf, login, ulen);
  2871. ubuf[ulen] = '\0';
  2872. Curl_safefree(*userp);
  2873. *userp = ubuf;
  2874. }
  2875. /* Store the password portion if necessary */
  2876. if(pbuf) {
  2877. memcpy(pbuf, psep + 1, plen);
  2878. pbuf[plen] = '\0';
  2879. Curl_safefree(*passwdp);
  2880. *passwdp = pbuf;
  2881. }
  2882. /* Store the options portion if necessary */
  2883. if(obuf) {
  2884. memcpy(obuf, osep + 1, olen);
  2885. obuf[olen] = '\0';
  2886. Curl_safefree(*optionsp);
  2887. *optionsp = obuf;
  2888. }
  2889. }
  2890. return result;
  2891. }
  2892. /*************************************************************
  2893. * Figure out the remote port number and fix it in the URL
  2894. *
  2895. * No matter if we use a proxy or not, we have to figure out the remote
  2896. * port number of various reasons.
  2897. *
  2898. * To be able to detect port number flawlessly, we must not confuse them
  2899. * IPv6-specified addresses in the [0::1] style. (RFC2732)
  2900. *
  2901. * The conn->host.name is currently [user:passwd@]host[:port] where host
  2902. * could be a hostname, IPv4 address or IPv6 address.
  2903. *
  2904. * The port number embedded in the URL is replaced, if necessary.
  2905. *************************************************************/
  2906. static CURLcode parse_remote_port(struct Curl_easy *data,
  2907. struct connectdata *conn)
  2908. {
  2909. char *portptr;
  2910. char endbracket;
  2911. /* Note that at this point, the IPv6 address cannot contain any scope
  2912. suffix as that has already been removed in the parseurlandfillconn()
  2913. function */
  2914. if((1 == sscanf(conn->host.name, "[%*45[0123456789abcdefABCDEF:.]%c",
  2915. &endbracket)) &&
  2916. (']' == endbracket)) {
  2917. /* this is a RFC2732-style specified IP-address */
  2918. conn->bits.ipv6_ip = TRUE;
  2919. conn->host.name++; /* skip over the starting bracket */
  2920. portptr = strchr(conn->host.name, ']');
  2921. if(portptr) {
  2922. *portptr++ = '\0'; /* zero terminate, killing the bracket */
  2923. if(*portptr) {
  2924. if (*portptr != ':') {
  2925. failf(data, "IPv6 closing bracket followed by '%c'", *portptr);
  2926. return CURLE_URL_MALFORMAT;
  2927. }
  2928. }
  2929. else
  2930. portptr = NULL; /* no port number available */
  2931. }
  2932. }
  2933. else {
  2934. #ifdef ENABLE_IPV6
  2935. struct in6_addr in6;
  2936. if(Curl_inet_pton(AF_INET6, conn->host.name, &in6) > 0) {
  2937. /* This is a numerical IPv6 address, meaning this is a wrongly formatted
  2938. URL */
  2939. failf(data, "IPv6 numerical address used in URL without brackets");
  2940. return CURLE_URL_MALFORMAT;
  2941. }
  2942. #endif
  2943. portptr = strchr(conn->host.name, ':');
  2944. }
  2945. if(data->set.use_port && data->state.allow_port) {
  2946. /* if set, we use this and ignore the port possibly given in the URL */
  2947. conn->remote_port = (unsigned short)data->set.use_port;
  2948. if(portptr)
  2949. *portptr = '\0'; /* cut off the name there anyway - if there was a port
  2950. number - since the port number is to be ignored! */
  2951. if(conn->bits.httpproxy) {
  2952. /* we need to create new URL with the new port number */
  2953. char *url;
  2954. char type[12]="";
  2955. if(conn->bits.type_set)
  2956. snprintf(type, sizeof(type), ";type=%c",
  2957. data->set.prefer_ascii?'A':
  2958. (data->set.ftp_list_only?'D':'I'));
  2959. /*
  2960. * This synthesized URL isn't always right--suffixes like ;type=A are
  2961. * stripped off. It would be better to work directly from the original
  2962. * URL and simply replace the port part of it.
  2963. */
  2964. url = aprintf("%s://%s%s%s:%d%s%s%s", conn->given->scheme,
  2965. conn->bits.ipv6_ip?"[":"", conn->host.name,
  2966. conn->bits.ipv6_ip?"]":"", conn->remote_port,
  2967. data->state.slash_removed?"/":"", data->state.path,
  2968. type);
  2969. if(!url)
  2970. return CURLE_OUT_OF_MEMORY;
  2971. if(data->change.url_alloc) {
  2972. Curl_safefree(data->change.url);
  2973. data->change.url_alloc = FALSE;
  2974. }
  2975. data->change.url = url;
  2976. data->change.url_alloc = TRUE;
  2977. }
  2978. }
  2979. else if(portptr) {
  2980. /* no CURLOPT_PORT given, extract the one from the URL */
  2981. char *rest;
  2982. long port;
  2983. port = strtol(portptr + 1, &rest, 10); /* Port number must be decimal */
  2984. if((port < 0) || (port > 0xffff)) {
  2985. /* Single unix standard says port numbers are 16 bits long */
  2986. failf(data, "Port number out of range");
  2987. return CURLE_URL_MALFORMAT;
  2988. }
  2989. if(rest[0]) {
  2990. failf(data, "Port number ended with '%c'", rest[0]);
  2991. return CURLE_URL_MALFORMAT;
  2992. }
  2993. if(rest != &portptr[1]) {
  2994. *portptr = '\0'; /* cut off the name there */
  2995. conn->remote_port = curlx_ultous(port);
  2996. }
  2997. else {
  2998. /* Browser behavior adaptation. If there's a colon with no digits after,
  2999. just cut off the name there which makes us ignore the colon and just
  3000. use the default port. Firefox and Chrome both do that. */
  3001. *portptr = '\0';
  3002. }
  3003. }
  3004. /* only if remote_port was not already parsed off the URL we use the
  3005. default port number */
  3006. if(conn->remote_port < 0)
  3007. conn->remote_port = (unsigned short)conn->given->defport;
  3008. return CURLE_OK;
  3009. }
  3010. /*
  3011. * Override the login details from the URL with that in the CURLOPT_USERPWD
  3012. * option or a .netrc file, if applicable.
  3013. */
  3014. static CURLcode override_login(struct Curl_easy *data,
  3015. struct connectdata *conn,
  3016. char **userp, char **passwdp, char **optionsp)
  3017. {
  3018. if(data->set.str[STRING_USERNAME]) {
  3019. free(*userp);
  3020. *userp = strdup(data->set.str[STRING_USERNAME]);
  3021. if(!*userp)
  3022. return CURLE_OUT_OF_MEMORY;
  3023. }
  3024. if(data->set.str[STRING_PASSWORD]) {
  3025. free(*passwdp);
  3026. *passwdp = strdup(data->set.str[STRING_PASSWORD]);
  3027. if(!*passwdp)
  3028. return CURLE_OUT_OF_MEMORY;
  3029. }
  3030. if(data->set.str[STRING_OPTIONS]) {
  3031. free(*optionsp);
  3032. *optionsp = strdup(data->set.str[STRING_OPTIONS]);
  3033. if(!*optionsp)
  3034. return CURLE_OUT_OF_MEMORY;
  3035. }
  3036. conn->bits.netrc = FALSE;
  3037. if(data->set.use_netrc != CURL_NETRC_IGNORED) {
  3038. int ret = Curl_parsenetrc(conn->host.name,
  3039. userp, passwdp,
  3040. data->set.str[STRING_NETRC_FILE]);
  3041. if(ret > 0) {
  3042. infof(data, "Couldn't find host %s in the "
  3043. DOT_CHAR "netrc file; using defaults\n",
  3044. conn->host.name);
  3045. }
  3046. else if(ret < 0) {
  3047. return CURLE_OUT_OF_MEMORY;
  3048. }
  3049. else {
  3050. /* set bits.netrc TRUE to remember that we got the name from a .netrc
  3051. file, so that it is safe to use even if we followed a Location: to a
  3052. different host or similar. */
  3053. conn->bits.netrc = TRUE;
  3054. conn->bits.user_passwd = TRUE; /* enable user+password */
  3055. }
  3056. }
  3057. return CURLE_OK;
  3058. }
  3059. /*
  3060. * Set the login details so they're available in the connection
  3061. */
  3062. static CURLcode set_login(struct connectdata *conn,
  3063. const char *user, const char *passwd,
  3064. const char *options)
  3065. {
  3066. CURLcode result = CURLE_OK;
  3067. /* If our protocol needs a password and we have none, use the defaults */
  3068. if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd) {
  3069. /* Store the default user */
  3070. conn->user = strdup(CURL_DEFAULT_USER);
  3071. /* Store the default password */
  3072. if(conn->user)
  3073. conn->passwd = strdup(CURL_DEFAULT_PASSWORD);
  3074. else
  3075. conn->passwd = NULL;
  3076. /* This is the default password, so DON'T set conn->bits.user_passwd */
  3077. }
  3078. else {
  3079. /* Store the user, zero-length if not set */
  3080. conn->user = strdup(user);
  3081. /* Store the password (only if user is present), zero-length if not set */
  3082. if(conn->user)
  3083. conn->passwd = strdup(passwd);
  3084. else
  3085. conn->passwd = NULL;
  3086. }
  3087. if(!conn->user || !conn->passwd)
  3088. result = CURLE_OUT_OF_MEMORY;
  3089. /* Store the options, null if not set */
  3090. if(!result && options[0]) {
  3091. conn->options = strdup(options);
  3092. if(!conn->options)
  3093. result = CURLE_OUT_OF_MEMORY;
  3094. }
  3095. return result;
  3096. }
  3097. /*
  3098. * Parses a "host:port" string to connect to.
  3099. * The hostname and the port may be empty; in this case, NULL is returned for
  3100. * the hostname and -1 for the port.
  3101. */
  3102. static CURLcode parse_connect_to_host_port(struct Curl_easy *data,
  3103. const char *host,
  3104. char **hostname_result,
  3105. int *port_result)
  3106. {
  3107. char *host_dup;
  3108. char *hostptr;
  3109. char *host_portno;
  3110. char *portptr;
  3111. int port = -1;
  3112. #if defined(CURL_DISABLE_VERBOSE_STRINGS)
  3113. (void) data;
  3114. #endif
  3115. *hostname_result = NULL;
  3116. *port_result = -1;
  3117. if(!host || !*host)
  3118. return CURLE_OK;
  3119. host_dup = strdup(host);
  3120. if(!host_dup)
  3121. return CURLE_OUT_OF_MEMORY;
  3122. hostptr = host_dup;
  3123. /* start scanning for port number at this point */
  3124. portptr = hostptr;
  3125. /* detect and extract RFC6874-style IPv6-addresses */
  3126. if(*hostptr == '[') {
  3127. #ifdef ENABLE_IPV6
  3128. char *ptr = ++hostptr; /* advance beyond the initial bracket */
  3129. while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
  3130. ptr++;
  3131. if(*ptr == '%') {
  3132. /* There might be a zone identifier */
  3133. if(strncmp("%25", ptr, 3))
  3134. infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
  3135. ptr++;
  3136. /* Allow unreserved characters as defined in RFC 3986 */
  3137. while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
  3138. (*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
  3139. ptr++;
  3140. }
  3141. if(*ptr == ']')
  3142. /* yeps, it ended nicely with a bracket as well */
  3143. *ptr++ = '\0';
  3144. else
  3145. infof(data, "Invalid IPv6 address format\n");
  3146. portptr = ptr;
  3147. /* Note that if this didn't end with a bracket, we still advanced the
  3148. * hostptr first, but I can't see anything wrong with that as no host
  3149. * name nor a numeric can legally start with a bracket.
  3150. */
  3151. #else
  3152. failf(data, "Use of IPv6 in *_CONNECT_TO without IPv6 support built-in!");
  3153. free(host_dup);
  3154. return CURLE_NOT_BUILT_IN;
  3155. #endif
  3156. }
  3157. /* Get port number off server.com:1080 */
  3158. host_portno = strchr(portptr, ':');
  3159. if(host_portno) {
  3160. char *endp = NULL;
  3161. *host_portno = '\0'; /* cut off number from host name */
  3162. host_portno++;
  3163. if(*host_portno) {
  3164. long portparse = strtol(host_portno, &endp, 10);
  3165. if((endp && *endp) || (portparse < 0) || (portparse > 65535)) {
  3166. infof(data, "No valid port number in connect to host string (%s)\n",
  3167. host_portno);
  3168. hostptr = NULL;
  3169. port = -1;
  3170. }
  3171. else
  3172. port = (int)portparse; /* we know it will fit */
  3173. }
  3174. }
  3175. /* now, clone the cleaned host name */
  3176. if(hostptr) {
  3177. *hostname_result = strdup(hostptr);
  3178. if(!*hostname_result) {
  3179. free(host_dup);
  3180. return CURLE_OUT_OF_MEMORY;
  3181. }
  3182. }
  3183. *port_result = port;
  3184. free(host_dup);
  3185. return CURLE_OK;
  3186. }
  3187. /*
  3188. * Parses one "connect to" string in the form:
  3189. * "HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT".
  3190. */
  3191. static CURLcode parse_connect_to_string(struct Curl_easy *data,
  3192. struct connectdata *conn,
  3193. const char *conn_to_host,
  3194. char **host_result,
  3195. int *port_result)
  3196. {
  3197. CURLcode result = CURLE_OK;
  3198. const char *ptr = conn_to_host;
  3199. int host_match = FALSE;
  3200. int port_match = FALSE;
  3201. *host_result = NULL;
  3202. *port_result = -1;
  3203. if(*ptr == ':') {
  3204. /* an empty hostname always matches */
  3205. host_match = TRUE;
  3206. ptr++;
  3207. }
  3208. else {
  3209. /* check whether the URL's hostname matches */
  3210. size_t hostname_to_match_len;
  3211. char *hostname_to_match = aprintf("%s%s%s",
  3212. conn->bits.ipv6_ip ? "[" : "",
  3213. conn->host.name,
  3214. conn->bits.ipv6_ip ? "]" : "");
  3215. if(!hostname_to_match)
  3216. return CURLE_OUT_OF_MEMORY;
  3217. hostname_to_match_len = strlen(hostname_to_match);
  3218. host_match = strncasecompare(ptr, hostname_to_match,
  3219. hostname_to_match_len);
  3220. free(hostname_to_match);
  3221. ptr += hostname_to_match_len;
  3222. host_match = host_match && *ptr == ':';
  3223. ptr++;
  3224. }
  3225. if(host_match) {
  3226. if(*ptr == ':') {
  3227. /* an empty port always matches */
  3228. port_match = TRUE;
  3229. ptr++;
  3230. }
  3231. else {
  3232. /* check whether the URL's port matches */
  3233. char *ptr_next = strchr(ptr, ':');
  3234. if(ptr_next) {
  3235. char *endp = NULL;
  3236. long port_to_match = strtol(ptr, &endp, 10);
  3237. if((endp == ptr_next) && (port_to_match == conn->remote_port)) {
  3238. port_match = TRUE;
  3239. ptr = ptr_next + 1;
  3240. }
  3241. }
  3242. }
  3243. }
  3244. if(host_match && port_match) {
  3245. /* parse the hostname and port to connect to */
  3246. result = parse_connect_to_host_port(data, ptr, host_result, port_result);
  3247. }
  3248. return result;
  3249. }
  3250. /*
  3251. * Processes all strings in the "connect to" slist, and uses the "connect
  3252. * to host" and "connect to port" of the first string that matches.
  3253. */
  3254. static CURLcode parse_connect_to_slist(struct Curl_easy *data,
  3255. struct connectdata *conn,
  3256. struct curl_slist *conn_to_host)
  3257. {
  3258. CURLcode result = CURLE_OK;
  3259. char *host = NULL;
  3260. int port = -1;
  3261. while(conn_to_host && !host && port == -1) {
  3262. result = parse_connect_to_string(data, conn, conn_to_host->data,
  3263. &host, &port);
  3264. if(result)
  3265. return result;
  3266. if(host && *host) {
  3267. conn->conn_to_host.rawalloc = host;
  3268. conn->conn_to_host.name = host;
  3269. conn->bits.conn_to_host = TRUE;
  3270. infof(data, "Connecting to hostname: %s\n", host);
  3271. }
  3272. else {
  3273. /* no "connect to host" */
  3274. conn->bits.conn_to_host = FALSE;
  3275. Curl_safefree(host);
  3276. }
  3277. if(port >= 0) {
  3278. conn->conn_to_port = port;
  3279. conn->bits.conn_to_port = TRUE;
  3280. infof(data, "Connecting to port: %d\n", port);
  3281. }
  3282. else {
  3283. /* no "connect to port" */
  3284. conn->bits.conn_to_port = FALSE;
  3285. port = -1;
  3286. }
  3287. conn_to_host = conn_to_host->next;
  3288. }
  3289. return result;
  3290. }
  3291. /*************************************************************
  3292. * Resolve the address of the server or proxy
  3293. *************************************************************/
  3294. static CURLcode resolve_server(struct Curl_easy *data,
  3295. struct connectdata *conn,
  3296. bool *async)
  3297. {
  3298. CURLcode result = CURLE_OK;
  3299. timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
  3300. /*************************************************************
  3301. * Resolve the name of the server or proxy
  3302. *************************************************************/
  3303. if(conn->bits.reuse)
  3304. /* We're reusing the connection - no need to resolve anything, and
  3305. fix_hostname() was called already in create_conn() for the re-use
  3306. case. */
  3307. *async = FALSE;
  3308. else {
  3309. /* this is a fresh connect */
  3310. int rc;
  3311. struct Curl_dns_entry *hostaddr;
  3312. #ifdef USE_UNIX_SOCKETS
  3313. if(conn->unix_domain_socket) {
  3314. /* Unix domain sockets are local. The host gets ignored, just use the
  3315. * specified domain socket address. Do not cache "DNS entries". There is
  3316. * no DNS involved and we already have the filesystem path available */
  3317. const char *path = conn->unix_domain_socket;
  3318. hostaddr = calloc(1, sizeof(struct Curl_dns_entry));
  3319. if(!hostaddr)
  3320. result = CURLE_OUT_OF_MEMORY;
  3321. else {
  3322. bool longpath = FALSE;
  3323. hostaddr->addr = Curl_unix2addr(path, &longpath,
  3324. conn->abstract_unix_socket);
  3325. if(hostaddr->addr)
  3326. hostaddr->inuse++;
  3327. else {
  3328. /* Long paths are not supported for now */
  3329. if(longpath) {
  3330. failf(data, "Unix socket path too long: '%s'", path);
  3331. result = CURLE_COULDNT_RESOLVE_HOST;
  3332. }
  3333. else
  3334. result = CURLE_OUT_OF_MEMORY;
  3335. free(hostaddr);
  3336. hostaddr = NULL;
  3337. }
  3338. }
  3339. }
  3340. else
  3341. #endif
  3342. if(!conn->bits.proxy) {
  3343. struct hostname *connhost;
  3344. if(conn->bits.conn_to_host)
  3345. connhost = &conn->conn_to_host;
  3346. else
  3347. connhost = &conn->host;
  3348. /* If not connecting via a proxy, extract the port from the URL, if it is
  3349. * there, thus overriding any defaults that might have been set above. */
  3350. if(conn->bits.conn_to_port)
  3351. conn->port = conn->conn_to_port;
  3352. else
  3353. conn->port = conn->remote_port;
  3354. /* Resolve target host right on */
  3355. rc = Curl_resolv_timeout(conn, connhost->name, (int)conn->port,
  3356. &hostaddr, timeout_ms);
  3357. if(rc == CURLRESOLV_PENDING)
  3358. *async = TRUE;
  3359. else if(rc == CURLRESOLV_TIMEDOUT)
  3360. result = CURLE_OPERATION_TIMEDOUT;
  3361. else if(!hostaddr) {
  3362. failf(data, "Couldn't resolve host '%s'", connhost->dispname);
  3363. result = CURLE_COULDNT_RESOLVE_HOST;
  3364. /* don't return yet, we need to clean up the timeout first */
  3365. }
  3366. }
  3367. else {
  3368. /* This is a proxy that hasn't been resolved yet. */
  3369. struct hostname * const host = conn->bits.socksproxy ?
  3370. &conn->socks_proxy.host : &conn->http_proxy.host;
  3371. /* resolve proxy */
  3372. rc = Curl_resolv_timeout(conn, host->name, (int)conn->port,
  3373. &hostaddr, timeout_ms);
  3374. if(rc == CURLRESOLV_PENDING)
  3375. *async = TRUE;
  3376. else if(rc == CURLRESOLV_TIMEDOUT)
  3377. result = CURLE_OPERATION_TIMEDOUT;
  3378. else if(!hostaddr) {
  3379. failf(data, "Couldn't resolve proxy '%s'", host->dispname);
  3380. result = CURLE_COULDNT_RESOLVE_PROXY;
  3381. /* don't return yet, we need to clean up the timeout first */
  3382. }
  3383. }
  3384. DEBUGASSERT(conn->dns_entry == NULL);
  3385. conn->dns_entry = hostaddr;
  3386. }
  3387. return result;
  3388. }
  3389. /*
  3390. * Cleanup the connection just allocated before we can move along and use the
  3391. * previously existing one. All relevant data is copied over and old_conn is
  3392. * ready for freeing once this function returns.
  3393. */
  3394. static void reuse_conn(struct connectdata *old_conn,
  3395. struct connectdata *conn)
  3396. {
  3397. free_fixed_hostname(&old_conn->http_proxy.host);
  3398. free_fixed_hostname(&old_conn->socks_proxy.host);
  3399. free(old_conn->http_proxy.host.rawalloc);
  3400. free(old_conn->socks_proxy.host.rawalloc);
  3401. /* free the SSL config struct from this connection struct as this was
  3402. allocated in vain and is targeted for destruction */
  3403. Curl_free_primary_ssl_config(&old_conn->ssl_config);
  3404. Curl_free_primary_ssl_config(&old_conn->proxy_ssl_config);
  3405. conn->data = old_conn->data;
  3406. /* get the user+password information from the old_conn struct since it may
  3407. * be new for this request even when we re-use an existing connection */
  3408. conn->bits.user_passwd = old_conn->bits.user_passwd;
  3409. if(conn->bits.user_passwd) {
  3410. /* use the new user name and password though */
  3411. Curl_safefree(conn->user);
  3412. Curl_safefree(conn->passwd);
  3413. conn->user = old_conn->user;
  3414. conn->passwd = old_conn->passwd;
  3415. old_conn->user = NULL;
  3416. old_conn->passwd = NULL;
  3417. }
  3418. conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
  3419. if(conn->bits.proxy_user_passwd) {
  3420. /* use the new proxy user name and proxy password though */
  3421. Curl_safefree(conn->http_proxy.user);
  3422. Curl_safefree(conn->socks_proxy.user);
  3423. Curl_safefree(conn->http_proxy.passwd);
  3424. Curl_safefree(conn->socks_proxy.passwd);
  3425. conn->http_proxy.user = old_conn->http_proxy.user;
  3426. conn->socks_proxy.user = old_conn->socks_proxy.user;
  3427. conn->http_proxy.passwd = old_conn->http_proxy.passwd;
  3428. conn->socks_proxy.passwd = old_conn->socks_proxy.passwd;
  3429. old_conn->http_proxy.user = NULL;
  3430. old_conn->socks_proxy.user = NULL;
  3431. old_conn->http_proxy.passwd = NULL;
  3432. old_conn->socks_proxy.passwd = NULL;
  3433. }
  3434. /* host can change, when doing keepalive with a proxy or if the case is
  3435. different this time etc */
  3436. free_fixed_hostname(&conn->host);
  3437. free_fixed_hostname(&conn->conn_to_host);
  3438. Curl_safefree(conn->host.rawalloc);
  3439. Curl_safefree(conn->conn_to_host.rawalloc);
  3440. conn->host = old_conn->host;
  3441. conn->conn_to_host = old_conn->conn_to_host;
  3442. conn->conn_to_port = old_conn->conn_to_port;
  3443. conn->remote_port = old_conn->remote_port;
  3444. /* persist connection info in session handle */
  3445. Curl_persistconninfo(conn);
  3446. conn_reset_all_postponed_data(old_conn); /* free buffers */
  3447. /* re-use init */
  3448. conn->bits.reuse = TRUE; /* yes, we're re-using here */
  3449. Curl_safefree(old_conn->user);
  3450. Curl_safefree(old_conn->passwd);
  3451. Curl_safefree(old_conn->options);
  3452. Curl_safefree(old_conn->http_proxy.user);
  3453. Curl_safefree(old_conn->socks_proxy.user);
  3454. Curl_safefree(old_conn->http_proxy.passwd);
  3455. Curl_safefree(old_conn->socks_proxy.passwd);
  3456. Curl_safefree(old_conn->localdev);
  3457. Curl_llist_destroy(&old_conn->send_pipe, NULL);
  3458. Curl_llist_destroy(&old_conn->recv_pipe, NULL);
  3459. Curl_safefree(old_conn->master_buffer);
  3460. #ifdef USE_UNIX_SOCKETS
  3461. Curl_safefree(old_conn->unix_domain_socket);
  3462. #endif
  3463. }
  3464. /**
  3465. * create_conn() sets up a new connectdata struct, or re-uses an already
  3466. * existing one, and resolves host name.
  3467. *
  3468. * if this function returns CURLE_OK and *async is set to TRUE, the resolve
  3469. * response will be coming asynchronously. If *async is FALSE, the name is
  3470. * already resolved.
  3471. *
  3472. * @param data The sessionhandle pointer
  3473. * @param in_connect is set to the next connection data pointer
  3474. * @param async is set TRUE when an async DNS resolution is pending
  3475. * @see Curl_setup_conn()
  3476. *
  3477. * *NOTE* this function assigns the conn->data pointer!
  3478. */
  3479. static CURLcode create_conn(struct Curl_easy *data,
  3480. struct connectdata **in_connect,
  3481. bool *async)
  3482. {
  3483. CURLcode result = CURLE_OK;
  3484. struct connectdata *conn;
  3485. struct connectdata *conn_temp = NULL;
  3486. size_t urllen;
  3487. char *user = NULL;
  3488. char *passwd = NULL;
  3489. char *options = NULL;
  3490. bool reuse;
  3491. bool prot_missing = FALSE;
  3492. bool connections_available = TRUE;
  3493. bool force_reuse = FALSE;
  3494. bool waitpipe = FALSE;
  3495. size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
  3496. size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
  3497. *async = FALSE;
  3498. /*************************************************************
  3499. * Check input data
  3500. *************************************************************/
  3501. if(!data->change.url) {
  3502. result = CURLE_URL_MALFORMAT;
  3503. goto out;
  3504. }
  3505. /* First, split up the current URL in parts so that we can use the
  3506. parts for checking against the already present connections. In order
  3507. to not have to modify everything at once, we allocate a temporary
  3508. connection data struct and fill in for comparison purposes. */
  3509. conn = allocate_conn(data);
  3510. if(!conn) {
  3511. result = CURLE_OUT_OF_MEMORY;
  3512. goto out;
  3513. }
  3514. /* We must set the return variable as soon as possible, so that our
  3515. parent can cleanup any possible allocs we may have done before
  3516. any failure */
  3517. *in_connect = conn;
  3518. /* This initing continues below, see the comment "Continue connectdata
  3519. * initialization here" */
  3520. /***********************************************************
  3521. * We need to allocate memory to store the path in. We get the size of the
  3522. * full URL to be sure, and we need to make it at least 256 bytes since
  3523. * other parts of the code will rely on this fact
  3524. ***********************************************************/
  3525. #define LEAST_PATH_ALLOC 256
  3526. urllen = strlen(data->change.url);
  3527. if(urllen < LEAST_PATH_ALLOC)
  3528. urllen = LEAST_PATH_ALLOC;
  3529. /*
  3530. * We malloc() the buffers below urllen+2 to make room for 2 possibilities:
  3531. * 1 - an extra terminating zero
  3532. * 2 - an extra slash (in case a syntax like "www.host.com?moo" is used)
  3533. */
  3534. Curl_safefree(data->state.pathbuffer);
  3535. data->state.path = NULL;
  3536. data->state.pathbuffer = malloc(urllen + 2);
  3537. if(NULL == data->state.pathbuffer) {
  3538. result = CURLE_OUT_OF_MEMORY; /* really bad error */
  3539. goto out;
  3540. }
  3541. data->state.path = data->state.pathbuffer;
  3542. conn->host.rawalloc = malloc(urllen + 2);
  3543. if(NULL == conn->host.rawalloc) {
  3544. Curl_safefree(data->state.pathbuffer);
  3545. data->state.path = NULL;
  3546. result = CURLE_OUT_OF_MEMORY;
  3547. goto out;
  3548. }
  3549. conn->host.name = conn->host.rawalloc;
  3550. conn->host.name[0] = 0;
  3551. user = strdup("");
  3552. passwd = strdup("");
  3553. options = strdup("");
  3554. if(!user || !passwd || !options) {
  3555. result = CURLE_OUT_OF_MEMORY;
  3556. goto out;
  3557. }
  3558. result = parseurlandfillconn(data, conn, &prot_missing, &user, &passwd,
  3559. &options);
  3560. if(result)
  3561. goto out;
  3562. /*************************************************************
  3563. * No protocol part in URL was used, add it!
  3564. *************************************************************/
  3565. if(prot_missing) {
  3566. /* We're guessing prefixes here and if we're told to use a proxy or if
  3567. we're going to follow a Location: later or... then we need the protocol
  3568. part added so that we have a valid URL. */
  3569. char *reurl;
  3570. char *ch_lower;
  3571. reurl = aprintf("%s://%s", conn->handler->scheme, data->change.url);
  3572. if(!reurl) {
  3573. result = CURLE_OUT_OF_MEMORY;
  3574. goto out;
  3575. }
  3576. /* Change protocol prefix to lower-case */
  3577. for(ch_lower = reurl; *ch_lower != ':'; ch_lower++)
  3578. *ch_lower = (char)TOLOWER(*ch_lower);
  3579. if(data->change.url_alloc) {
  3580. Curl_safefree(data->change.url);
  3581. data->change.url_alloc = FALSE;
  3582. }
  3583. data->change.url = reurl;
  3584. data->change.url_alloc = TRUE; /* free this later */
  3585. }
  3586. /*************************************************************
  3587. * If the protocol can't handle url query strings, then cut
  3588. * off the unhandable part
  3589. *************************************************************/
  3590. if((conn->given->flags&PROTOPT_NOURLQUERY)) {
  3591. char *path_q_sep = strchr(conn->data->state.path, '?');
  3592. if(path_q_sep) {
  3593. /* according to rfc3986, allow the query (?foo=bar)
  3594. also on protocols that can't handle it.
  3595. cut the string-part after '?'
  3596. */
  3597. /* terminate the string */
  3598. path_q_sep[0] = 0;
  3599. }
  3600. }
  3601. if(data->set.str[STRING_BEARER]) {
  3602. conn->oauth_bearer = strdup(data->set.str[STRING_BEARER]);
  3603. if(!conn->oauth_bearer) {
  3604. result = CURLE_OUT_OF_MEMORY;
  3605. goto out;
  3606. }
  3607. }
  3608. #ifdef USE_UNIX_SOCKETS
  3609. if(data->set.str[STRING_UNIX_SOCKET_PATH]) {
  3610. conn->unix_domain_socket = strdup(data->set.str[STRING_UNIX_SOCKET_PATH]);
  3611. if(conn->unix_domain_socket == NULL) {
  3612. result = CURLE_OUT_OF_MEMORY;
  3613. goto out;
  3614. }
  3615. conn->abstract_unix_socket = data->set.abstract_unix_socket;
  3616. }
  3617. #endif
  3618. /* After the unix socket init but before the proxy vars are used, parse and
  3619. initialize the proxy vars */
  3620. #ifndef CURL_DISABLE_PROXY
  3621. result = create_conn_helper_init_proxy(conn);
  3622. if(result)
  3623. goto out;
  3624. #endif
  3625. /*************************************************************
  3626. * If the protocol is using SSL and HTTP proxy is used, we set
  3627. * the tunnel_proxy bit.
  3628. *************************************************************/
  3629. if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
  3630. conn->bits.tunnel_proxy = TRUE;
  3631. /*************************************************************
  3632. * Figure out the remote port number and fix it in the URL
  3633. *************************************************************/
  3634. result = parse_remote_port(data, conn);
  3635. if(result)
  3636. goto out;
  3637. /* Check for overridden login details and set them accordingly so they
  3638. they are known when protocol->setup_connection is called! */
  3639. result = override_login(data, conn, &user, &passwd, &options);
  3640. if(result)
  3641. goto out;
  3642. result = set_login(conn, user, passwd, options);
  3643. if(result)
  3644. goto out;
  3645. /*************************************************************
  3646. * Process the "connect to" linked list of hostname/port mappings.
  3647. * Do this after the remote port number has been fixed in the URL.
  3648. *************************************************************/
  3649. result = parse_connect_to_slist(data, conn, data->set.connect_to);
  3650. if(result)
  3651. goto out;
  3652. /*************************************************************
  3653. * IDN-fix the hostnames
  3654. *************************************************************/
  3655. result = fix_hostname(conn, &conn->host);
  3656. if(result)
  3657. goto out;
  3658. if(conn->bits.conn_to_host) {
  3659. result = fix_hostname(conn, &conn->conn_to_host);
  3660. if(result)
  3661. goto out;
  3662. }
  3663. if(conn->bits.httpproxy) {
  3664. result = fix_hostname(conn, &conn->http_proxy.host);
  3665. if(result)
  3666. goto out;
  3667. }
  3668. if(conn->bits.socksproxy) {
  3669. result = fix_hostname(conn, &conn->socks_proxy.host);
  3670. if(result)
  3671. goto out;
  3672. }
  3673. /*************************************************************
  3674. * Check whether the host and the "connect to host" are equal.
  3675. * Do this after the hostnames have been IDN-fixed.
  3676. *************************************************************/
  3677. if(conn->bits.conn_to_host &&
  3678. strcasecompare(conn->conn_to_host.name, conn->host.name)) {
  3679. conn->bits.conn_to_host = FALSE;
  3680. }
  3681. /*************************************************************
  3682. * Check whether the port and the "connect to port" are equal.
  3683. * Do this after the remote port number has been fixed in the URL.
  3684. *************************************************************/
  3685. if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) {
  3686. conn->bits.conn_to_port = FALSE;
  3687. }
  3688. /*************************************************************
  3689. * If the "connect to" feature is used with an HTTP proxy,
  3690. * we set the tunnel_proxy bit.
  3691. *************************************************************/
  3692. if((conn->bits.conn_to_host || conn->bits.conn_to_port) &&
  3693. conn->bits.httpproxy)
  3694. conn->bits.tunnel_proxy = TRUE;
  3695. /*************************************************************
  3696. * Setup internals depending on protocol. Needs to be done after
  3697. * we figured out what/if proxy to use.
  3698. *************************************************************/
  3699. result = setup_connection_internals(conn);
  3700. if(result)
  3701. goto out;
  3702. conn->recv[FIRSTSOCKET] = Curl_recv_plain;
  3703. conn->send[FIRSTSOCKET] = Curl_send_plain;
  3704. conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
  3705. conn->send[SECONDARYSOCKET] = Curl_send_plain;
  3706. conn->bits.tcp_fastopen = data->set.tcp_fastopen;
  3707. /***********************************************************************
  3708. * file: is a special case in that it doesn't need a network connection
  3709. ***********************************************************************/
  3710. #ifndef CURL_DISABLE_FILE
  3711. if(conn->handler->flags & PROTOPT_NONETWORK) {
  3712. bool done;
  3713. /* this is supposed to be the connect function so we better at least check
  3714. that the file is present here! */
  3715. DEBUGASSERT(conn->handler->connect_it);
  3716. result = conn->handler->connect_it(conn, &done);
  3717. /* Setup a "faked" transfer that'll do nothing */
  3718. if(!result) {
  3719. conn->data = data;
  3720. conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
  3721. result = Curl_conncache_add_conn(data->state.conn_cache, conn);
  3722. if(result)
  3723. goto out;
  3724. /*
  3725. * Setup whatever necessary for a resumed transfer
  3726. */
  3727. result = setup_range(data);
  3728. if(result) {
  3729. DEBUGASSERT(conn->handler->done);
  3730. /* we ignore the return code for the protocol-specific DONE */
  3731. (void)conn->handler->done(conn, result, FALSE);
  3732. goto out;
  3733. }
  3734. Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
  3735. -1, NULL); /* no upload */
  3736. }
  3737. /* since we skip do_init() */
  3738. Curl_init_do(data, conn);
  3739. goto out;
  3740. }
  3741. #endif
  3742. /* Get a cloned copy of the SSL config situation stored in the
  3743. connection struct. But to get this going nicely, we must first make
  3744. sure that the strings in the master copy are pointing to the correct
  3745. strings in the session handle strings array!
  3746. Keep in mind that the pointers in the master copy are pointing to strings
  3747. that will be freed as part of the Curl_easy struct, but all cloned
  3748. copies will be separately allocated.
  3749. */
  3750. data->set.ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_ORIG];
  3751. data->set.proxy_ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_PROXY];
  3752. data->set.ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_ORIG];
  3753. data->set.proxy_ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_PROXY];
  3754. data->set.ssl.primary.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
  3755. data->set.proxy_ssl.primary.random_file =
  3756. data->set.str[STRING_SSL_RANDOM_FILE];
  3757. data->set.ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
  3758. data->set.proxy_ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
  3759. data->set.ssl.primary.cipher_list =
  3760. data->set.str[STRING_SSL_CIPHER_LIST_ORIG];
  3761. data->set.proxy_ssl.primary.cipher_list =
  3762. data->set.str[STRING_SSL_CIPHER_LIST_PROXY];
  3763. data->set.ssl.primary.cipher_list13 =
  3764. data->set.str[STRING_SSL_CIPHER13_LIST_ORIG];
  3765. data->set.proxy_ssl.primary.cipher_list13 =
  3766. data->set.str[STRING_SSL_CIPHER13_LIST_PROXY];
  3767. data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_ORIG];
  3768. data->set.proxy_ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_PROXY];
  3769. data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_ORIG];
  3770. data->set.proxy_ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_PROXY];
  3771. data->set.ssl.cert = data->set.str[STRING_CERT_ORIG];
  3772. data->set.proxy_ssl.cert = data->set.str[STRING_CERT_PROXY];
  3773. data->set.ssl.cert_type = data->set.str[STRING_CERT_TYPE_ORIG];
  3774. data->set.proxy_ssl.cert_type = data->set.str[STRING_CERT_TYPE_PROXY];
  3775. data->set.ssl.key = data->set.str[STRING_KEY_ORIG];
  3776. data->set.proxy_ssl.key = data->set.str[STRING_KEY_PROXY];
  3777. data->set.ssl.key_type = data->set.str[STRING_KEY_TYPE_ORIG];
  3778. data->set.proxy_ssl.key_type = data->set.str[STRING_KEY_TYPE_PROXY];
  3779. data->set.ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_ORIG];
  3780. data->set.proxy_ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_PROXY];
  3781. data->set.ssl.primary.clientcert = data->set.str[STRING_CERT_ORIG];
  3782. data->set.proxy_ssl.primary.clientcert = data->set.str[STRING_CERT_PROXY];
  3783. #ifdef USE_TLS_SRP
  3784. data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_ORIG];
  3785. data->set.proxy_ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_PROXY];
  3786. data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_ORIG];
  3787. data->set.proxy_ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_PROXY];
  3788. #endif
  3789. if(!Curl_clone_primary_ssl_config(&data->set.ssl.primary,
  3790. &conn->ssl_config)) {
  3791. result = CURLE_OUT_OF_MEMORY;
  3792. goto out;
  3793. }
  3794. if(!Curl_clone_primary_ssl_config(&data->set.proxy_ssl.primary,
  3795. &conn->proxy_ssl_config)) {
  3796. result = CURLE_OUT_OF_MEMORY;
  3797. goto out;
  3798. }
  3799. prune_dead_connections(data);
  3800. /*************************************************************
  3801. * Check the current list of connections to see if we can
  3802. * re-use an already existing one or if we have to create a
  3803. * new one.
  3804. *************************************************************/
  3805. /* reuse_fresh is TRUE if we are told to use a new connection by force, but
  3806. we only acknowledge this option if this is not a re-used connection
  3807. already (which happens due to follow-location or during a HTTP
  3808. authentication phase). */
  3809. if(data->set.reuse_fresh && !data->state.this_is_a_follow)
  3810. reuse = FALSE;
  3811. else
  3812. reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse, &waitpipe);
  3813. /* If we found a reusable connection that is now marked as in use, we may
  3814. still want to open a new connection if we are pipelining. */
  3815. if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) {
  3816. size_t pipelen = conn_temp->send_pipe.size + conn_temp->recv_pipe.size;
  3817. if(pipelen > 0) {
  3818. infof(data, "Found connection %ld, with requests in the pipe (%zu)\n",
  3819. conn_temp->connection_id, pipelen);
  3820. if(Curl_conncache_bundle_size(conn_temp) < max_host_connections &&
  3821. Curl_conncache_size(data) < max_total_connections) {
  3822. /* We want a new connection anyway */
  3823. reuse = FALSE;
  3824. infof(data, "We can reuse, but we want a new connection anyway\n");
  3825. Curl_conncache_return_conn(conn_temp);
  3826. }
  3827. }
  3828. }
  3829. if(reuse) {
  3830. /*
  3831. * We already have a connection for this, we got the former connection
  3832. * in the conn_temp variable and thus we need to cleanup the one we
  3833. * just allocated before we can move along and use the previously
  3834. * existing one.
  3835. */
  3836. reuse_conn(conn, conn_temp);
  3837. #ifdef USE_SSL
  3838. free(conn->ssl_extra);
  3839. #endif
  3840. free(conn); /* we don't need this anymore */
  3841. conn = conn_temp;
  3842. *in_connect = conn;
  3843. infof(data, "Re-using existing connection! (#%ld) with %s %s\n",
  3844. conn->connection_id,
  3845. conn->bits.proxy?"proxy":"host",
  3846. conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname :
  3847. conn->http_proxy.host.name ? conn->http_proxy.host.dispname :
  3848. conn->host.dispname);
  3849. }
  3850. else {
  3851. /* We have decided that we want a new connection. However, we may not
  3852. be able to do that if we have reached the limit of how many
  3853. connections we are allowed to open. */
  3854. if(conn->handler->flags & PROTOPT_ALPN_NPN) {
  3855. /* The protocol wants it, so set the bits if enabled in the easy handle
  3856. (default) */
  3857. if(data->set.ssl_enable_alpn)
  3858. conn->bits.tls_enable_alpn = TRUE;
  3859. if(data->set.ssl_enable_npn)
  3860. conn->bits.tls_enable_npn = TRUE;
  3861. }
  3862. if(waitpipe)
  3863. /* There is a connection that *might* become usable for pipelining
  3864. "soon", and we wait for that */
  3865. connections_available = FALSE;
  3866. else {
  3867. /* this gets a lock on the conncache */
  3868. struct connectbundle *bundle =
  3869. Curl_conncache_find_bundle(conn, data->state.conn_cache);
  3870. if(max_host_connections > 0 && bundle &&
  3871. (bundle->num_connections >= max_host_connections)) {
  3872. struct connectdata *conn_candidate;
  3873. /* The bundle is full. Extract the oldest connection. */
  3874. conn_candidate = Curl_conncache_extract_bundle(data, bundle);
  3875. Curl_conncache_unlock(conn);
  3876. if(conn_candidate)
  3877. (void)Curl_disconnect(data, conn_candidate,
  3878. /* dead_connection */ FALSE);
  3879. else {
  3880. infof(data, "No more connections allowed to host: %zu\n",
  3881. max_host_connections);
  3882. connections_available = FALSE;
  3883. }
  3884. }
  3885. else
  3886. Curl_conncache_unlock(conn);
  3887. }
  3888. if(connections_available &&
  3889. (max_total_connections > 0) &&
  3890. (Curl_conncache_size(data) >= max_total_connections)) {
  3891. struct connectdata *conn_candidate;
  3892. /* The cache is full. Let's see if we can kill a connection. */
  3893. conn_candidate = Curl_conncache_extract_oldest(data);
  3894. if(conn_candidate)
  3895. (void)Curl_disconnect(data, conn_candidate,
  3896. /* dead_connection */ FALSE);
  3897. else {
  3898. infof(data, "No connections available in cache\n");
  3899. connections_available = FALSE;
  3900. }
  3901. }
  3902. if(!connections_available) {
  3903. infof(data, "No connections available.\n");
  3904. conn_free(conn);
  3905. *in_connect = NULL;
  3906. result = CURLE_NO_CONNECTION_AVAILABLE;
  3907. goto out;
  3908. }
  3909. else {
  3910. /*
  3911. * This is a brand new connection, so let's store it in the connection
  3912. * cache of ours!
  3913. */
  3914. result = Curl_conncache_add_conn(data->state.conn_cache, conn);
  3915. if(result)
  3916. goto out;
  3917. }
  3918. #if defined(USE_NTLM)
  3919. /* If NTLM is requested in a part of this connection, make sure we don't
  3920. assume the state is fine as this is a fresh connection and NTLM is
  3921. connection based. */
  3922. if((data->state.authhost.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
  3923. data->state.authhost.done) {
  3924. infof(data, "NTLM picked AND auth done set, clear picked!\n");
  3925. data->state.authhost.picked = CURLAUTH_NONE;
  3926. data->state.authhost.done = FALSE;
  3927. }
  3928. if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
  3929. data->state.authproxy.done) {
  3930. infof(data, "NTLM-proxy picked AND auth done set, clear picked!\n");
  3931. data->state.authproxy.picked = CURLAUTH_NONE;
  3932. data->state.authproxy.done = FALSE;
  3933. }
  3934. #endif
  3935. }
  3936. /* Setup and init stuff before DO starts, in preparing for the transfer. */
  3937. Curl_init_do(data, conn);
  3938. /*
  3939. * Setup whatever necessary for a resumed transfer
  3940. */
  3941. result = setup_range(data);
  3942. if(result)
  3943. goto out;
  3944. /* Continue connectdata initialization here. */
  3945. /*
  3946. * Inherit the proper values from the urldata struct AFTER we have arranged
  3947. * the persistent connection stuff
  3948. */
  3949. conn->seek_func = data->set.seek_func;
  3950. conn->seek_client = data->set.seek_client;
  3951. /*************************************************************
  3952. * Resolve the address of the server or proxy
  3953. *************************************************************/
  3954. result = resolve_server(data, conn, async);
  3955. out:
  3956. free(options);
  3957. free(passwd);
  3958. free(user);
  3959. return result;
  3960. }
  3961. /* Curl_setup_conn() is called after the name resolve initiated in
  3962. * create_conn() is all done.
  3963. *
  3964. * Curl_setup_conn() also handles reused connections
  3965. *
  3966. * conn->data MUST already have been setup fine (in create_conn)
  3967. */
  3968. CURLcode Curl_setup_conn(struct connectdata *conn,
  3969. bool *protocol_done)
  3970. {
  3971. CURLcode result = CURLE_OK;
  3972. struct Curl_easy *data = conn->data;
  3973. Curl_pgrsTime(data, TIMER_NAMELOOKUP);
  3974. if(conn->handler->flags & PROTOPT_NONETWORK) {
  3975. /* nothing to setup when not using a network */
  3976. *protocol_done = TRUE;
  3977. return result;
  3978. }
  3979. *protocol_done = FALSE; /* default to not done */
  3980. /* set proxy_connect_closed to false unconditionally already here since it
  3981. is used strictly to provide extra information to a parent function in the
  3982. case of proxy CONNECT failures and we must make sure we don't have it
  3983. lingering set from a previous invoke */
  3984. conn->bits.proxy_connect_closed = FALSE;
  3985. /*
  3986. * Set user-agent. Used for HTTP, but since we can attempt to tunnel
  3987. * basically anything through a http proxy we can't limit this based on
  3988. * protocol.
  3989. */
  3990. if(data->set.str[STRING_USERAGENT]) {
  3991. Curl_safefree(conn->allocptr.uagent);
  3992. conn->allocptr.uagent =
  3993. aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
  3994. if(!conn->allocptr.uagent)
  3995. return CURLE_OUT_OF_MEMORY;
  3996. }
  3997. data->req.headerbytecount = 0;
  3998. #ifdef CURL_DO_LINEEND_CONV
  3999. data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
  4000. #endif /* CURL_DO_LINEEND_CONV */
  4001. /* set start time here for timeout purposes in the connect procedure, it
  4002. is later set again for the progress meter purpose */
  4003. conn->now = Curl_now();
  4004. if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
  4005. conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
  4006. result = Curl_connecthost(conn, conn->dns_entry);
  4007. if(result)
  4008. return result;
  4009. }
  4010. else {
  4011. Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
  4012. Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
  4013. conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
  4014. *protocol_done = TRUE;
  4015. Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
  4016. Curl_verboseconnect(conn);
  4017. }
  4018. conn->now = Curl_now(); /* time this *after* the connect is done, we set
  4019. this here perhaps a second time */
  4020. return result;
  4021. }
  4022. CURLcode Curl_connect(struct Curl_easy *data,
  4023. struct connectdata **in_connect,
  4024. bool *asyncp,
  4025. bool *protocol_done)
  4026. {
  4027. CURLcode result;
  4028. *asyncp = FALSE; /* assume synchronous resolves by default */
  4029. /* init the single-transfer specific data */
  4030. Curl_free_request_state(data);
  4031. memset(&data->req, 0, sizeof(struct SingleRequest));
  4032. data->req.maxdownload = -1;
  4033. /* call the stuff that needs to be called */
  4034. result = create_conn(data, in_connect, asyncp);
  4035. if(!result) {
  4036. if(CONN_INUSE(*in_connect))
  4037. /* pipelining */
  4038. *protocol_done = TRUE;
  4039. else if(!*asyncp) {
  4040. /* DNS resolution is done: that's either because this is a reused
  4041. connection, in which case DNS was unnecessary, or because DNS
  4042. really did finish already (synch resolver/fast async resolve) */
  4043. result = Curl_setup_conn(*in_connect, protocol_done);
  4044. }
  4045. }
  4046. if(result == CURLE_NO_CONNECTION_AVAILABLE) {
  4047. *in_connect = NULL;
  4048. return result;
  4049. }
  4050. else if(result && *in_connect) {
  4051. /* We're not allowed to return failure with memory left allocated in the
  4052. connectdata struct, free those here */
  4053. Curl_disconnect(data, *in_connect, TRUE);
  4054. *in_connect = NULL; /* return a NULL */
  4055. }
  4056. return result;
  4057. }
  4058. /*
  4059. * Curl_init_do() inits the readwrite session. This is inited each time (in
  4060. * the DO function before the protocol-specific DO functions are invoked) for
  4061. * a transfer, sometimes multiple times on the same Curl_easy. Make sure
  4062. * nothing in here depends on stuff that are setup dynamically for the
  4063. * transfer.
  4064. *
  4065. * Allow this function to get called with 'conn' set to NULL.
  4066. */
  4067. CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn)
  4068. {
  4069. struct SingleRequest *k = &data->req;
  4070. if(conn) {
  4071. conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to
  4072. use */
  4073. /* if the protocol used doesn't support wildcards, switch it off */
  4074. if(data->state.wildcardmatch &&
  4075. !(conn->handler->flags & PROTOPT_WILDCARD))
  4076. data->state.wildcardmatch = FALSE;
  4077. }
  4078. data->state.done = FALSE; /* *_done() is not called yet */
  4079. data->state.expect100header = FALSE;
  4080. if(data->set.opt_no_body)
  4081. /* in HTTP lingo, no body means using the HEAD request... */
  4082. data->set.httpreq = HTTPREQ_HEAD;
  4083. else if(HTTPREQ_HEAD == data->set.httpreq)
  4084. /* ... but if unset there really is no perfect method that is the
  4085. "opposite" of HEAD but in reality most people probably think GET
  4086. then. The important thing is that we can't let it remain HEAD if the
  4087. opt_no_body is set FALSE since then we'll behave wrong when getting
  4088. HTTP. */
  4089. data->set.httpreq = HTTPREQ_GET;
  4090. k->start = Curl_now(); /* start time */
  4091. k->now = k->start; /* current time is now */
  4092. k->header = TRUE; /* assume header */
  4093. k->bytecount = 0;
  4094. k->buf = data->state.buffer;
  4095. k->hbufp = data->state.headerbuff;
  4096. k->ignorebody = FALSE;
  4097. Curl_speedinit(data);
  4098. Curl_pgrsSetUploadCounter(data, 0);
  4099. Curl_pgrsSetDownloadCounter(data, 0);
  4100. return CURLE_OK;
  4101. }
  4102. /*
  4103. * get_protocol_family()
  4104. *
  4105. * This is used to return the protocol family for a given protocol.
  4106. *
  4107. * Parameters:
  4108. *
  4109. * protocol [in] - A single bit protocol identifier such as HTTP or HTTPS.
  4110. *
  4111. * Returns the family as a single bit protocol identifier.
  4112. */
  4113. static unsigned int get_protocol_family(unsigned int protocol)
  4114. {
  4115. unsigned int family;
  4116. switch(protocol) {
  4117. case CURLPROTO_HTTP:
  4118. case CURLPROTO_HTTPS:
  4119. family = CURLPROTO_HTTP;
  4120. break;
  4121. case CURLPROTO_FTP:
  4122. case CURLPROTO_FTPS:
  4123. family = CURLPROTO_FTP;
  4124. break;
  4125. case CURLPROTO_SCP:
  4126. family = CURLPROTO_SCP;
  4127. break;
  4128. case CURLPROTO_SFTP:
  4129. family = CURLPROTO_SFTP;
  4130. break;
  4131. case CURLPROTO_TELNET:
  4132. family = CURLPROTO_TELNET;
  4133. break;
  4134. case CURLPROTO_LDAP:
  4135. case CURLPROTO_LDAPS:
  4136. family = CURLPROTO_LDAP;
  4137. break;
  4138. case CURLPROTO_DICT:
  4139. family = CURLPROTO_DICT;
  4140. break;
  4141. case CURLPROTO_FILE:
  4142. family = CURLPROTO_FILE;
  4143. break;
  4144. case CURLPROTO_TFTP:
  4145. family = CURLPROTO_TFTP;
  4146. break;
  4147. case CURLPROTO_IMAP:
  4148. case CURLPROTO_IMAPS:
  4149. family = CURLPROTO_IMAP;
  4150. break;
  4151. case CURLPROTO_POP3:
  4152. case CURLPROTO_POP3S:
  4153. family = CURLPROTO_POP3;
  4154. break;
  4155. case CURLPROTO_SMTP:
  4156. case CURLPROTO_SMTPS:
  4157. family = CURLPROTO_SMTP;
  4158. break;
  4159. case CURLPROTO_RTSP:
  4160. family = CURLPROTO_RTSP;
  4161. break;
  4162. case CURLPROTO_RTMP:
  4163. case CURLPROTO_RTMPS:
  4164. family = CURLPROTO_RTMP;
  4165. break;
  4166. case CURLPROTO_RTMPT:
  4167. case CURLPROTO_RTMPTS:
  4168. family = CURLPROTO_RTMPT;
  4169. break;
  4170. case CURLPROTO_RTMPE:
  4171. family = CURLPROTO_RTMPE;
  4172. break;
  4173. case CURLPROTO_RTMPTE:
  4174. family = CURLPROTO_RTMPTE;
  4175. break;
  4176. case CURLPROTO_GOPHER:
  4177. family = CURLPROTO_GOPHER;
  4178. break;
  4179. case CURLPROTO_SMB:
  4180. case CURLPROTO_SMBS:
  4181. family = CURLPROTO_SMB;
  4182. break;
  4183. default:
  4184. family = 0;
  4185. break;
  4186. }
  4187. return family;
  4188. }