url.c 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 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.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. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #ifdef HAVE_NETINET_IN_H
  26. #include <netinet/in.h>
  27. #endif
  28. #ifdef HAVE_NETDB_H
  29. #include <netdb.h>
  30. #endif
  31. #ifdef HAVE_ARPA_INET_H
  32. #include <arpa/inet.h>
  33. #endif
  34. #ifdef HAVE_NET_IF_H
  35. #include <net/if.h>
  36. #endif
  37. #ifdef HAVE_IPHLPAPI_H
  38. #include <Iphlpapi.h>
  39. #endif
  40. #ifdef HAVE_SYS_IOCTL_H
  41. #include <sys/ioctl.h>
  42. #endif
  43. #ifdef HAVE_SYS_PARAM_H
  44. #include <sys/param.h>
  45. #endif
  46. #ifdef __VMS
  47. #include <in.h>
  48. #include <inet.h>
  49. #endif
  50. #ifdef HAVE_SYS_UN_H
  51. #include <sys/un.h>
  52. #endif
  53. #ifndef HAVE_SOCKET
  54. #error "We can't compile without socket() support!"
  55. #endif
  56. #include <limits.h>
  57. #include "doh.h"
  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 "getinfo.h"
  82. #include "urlapi-int.h"
  83. #include "system_win32.h"
  84. #include "hsts.h"
  85. #include "noproxy.h"
  86. #include "cfilters.h"
  87. #include "idn.h"
  88. /* And now for the protocols */
  89. #include "ftp.h"
  90. #include "dict.h"
  91. #include "telnet.h"
  92. #include "tftp.h"
  93. #include "http.h"
  94. #include "http2.h"
  95. #include "file.h"
  96. #include "curl_ldap.h"
  97. #include "vssh/ssh.h"
  98. #include "imap.h"
  99. #include "url.h"
  100. #include "connect.h"
  101. #include "inet_ntop.h"
  102. #include "http_ntlm.h"
  103. #include "curl_rtmp.h"
  104. #include "gopher.h"
  105. #include "mqtt.h"
  106. #include "http_proxy.h"
  107. #include "conncache.h"
  108. #include "multihandle.h"
  109. #include "strdup.h"
  110. #include "setopt.h"
  111. #include "altsvc.h"
  112. #include "dynbuf.h"
  113. #include "headers.h"
  114. /* The last 3 #include files should be in this order */
  115. #include "curl_printf.h"
  116. #include "curl_memory.h"
  117. #include "memdebug.h"
  118. #ifndef ARRAYSIZE
  119. #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0]))
  120. #endif
  121. #ifdef USE_NGHTTP2
  122. static void data_priority_cleanup(struct Curl_easy *data);
  123. #else
  124. #define data_priority_cleanup(x)
  125. #endif
  126. /* Some parts of the code (e.g. chunked encoding) assume this buffer has at
  127. * more than just a few bytes to play with. Don't let it become too small or
  128. * bad things will happen.
  129. */
  130. #if READBUFFER_SIZE < READBUFFER_MIN
  131. # error READBUFFER_SIZE is too small
  132. #endif
  133. #ifdef USE_UNIX_SOCKETS
  134. #define UNIX_SOCKET_PREFIX "localhost"
  135. #endif
  136. /* Reject URLs exceeding this length */
  137. #define MAX_URL_LEN 0xffff
  138. /*
  139. * get_protocol_family()
  140. *
  141. * This is used to return the protocol family for a given protocol.
  142. *
  143. * Parameters:
  144. *
  145. * 'h' [in] - struct Curl_handler pointer.
  146. *
  147. * Returns the family as a single bit protocol identifier.
  148. */
  149. static curl_prot_t get_protocol_family(const struct Curl_handler *h)
  150. {
  151. DEBUGASSERT(h);
  152. DEBUGASSERT(h->family);
  153. return h->family;
  154. }
  155. void Curl_freeset(struct Curl_easy *data)
  156. {
  157. /* Free all dynamic strings stored in the data->set substructure. */
  158. enum dupstring i;
  159. enum dupblob j;
  160. for(i = (enum dupstring)0; i < STRING_LAST; i++) {
  161. Curl_safefree(data->set.str[i]);
  162. }
  163. for(j = (enum dupblob)0; j < BLOB_LAST; j++) {
  164. Curl_safefree(data->set.blobs[j]);
  165. }
  166. if(data->state.referer_alloc) {
  167. Curl_safefree(data->state.referer);
  168. data->state.referer_alloc = FALSE;
  169. }
  170. data->state.referer = NULL;
  171. if(data->state.url_alloc) {
  172. Curl_safefree(data->state.url);
  173. data->state.url_alloc = FALSE;
  174. }
  175. data->state.url = NULL;
  176. Curl_mime_cleanpart(&data->set.mimepost);
  177. #ifndef CURL_DISABLE_COOKIES
  178. curl_slist_free_all(data->state.cookielist);
  179. data->state.cookielist = NULL;
  180. #endif
  181. }
  182. /* free the URL pieces */
  183. static void up_free(struct Curl_easy *data)
  184. {
  185. struct urlpieces *up = &data->state.up;
  186. Curl_safefree(up->scheme);
  187. Curl_safefree(up->hostname);
  188. Curl_safefree(up->port);
  189. Curl_safefree(up->user);
  190. Curl_safefree(up->password);
  191. Curl_safefree(up->options);
  192. Curl_safefree(up->path);
  193. Curl_safefree(up->query);
  194. curl_url_cleanup(data->state.uh);
  195. data->state.uh = NULL;
  196. }
  197. /*
  198. * This is the internal function curl_easy_cleanup() calls. This should
  199. * cleanup and free all resources associated with this sessionhandle.
  200. *
  201. * We ignore SIGPIPE when this is called from curl_easy_cleanup.
  202. */
  203. CURLcode Curl_close(struct Curl_easy **datap)
  204. {
  205. struct Curl_easy *data;
  206. if(!datap || !*datap)
  207. return CURLE_OK;
  208. data = *datap;
  209. *datap = NULL;
  210. Curl_expire_clear(data); /* shut off timers */
  211. /* Detach connection if any is left. This should not be normal, but can be
  212. the case for example with CONNECT_ONLY + recv/send (test 556) */
  213. Curl_detach_connection(data);
  214. if(!data->state.internal) {
  215. if(data->multi)
  216. /* This handle is still part of a multi handle, take care of this first
  217. and detach this handle from there. */
  218. curl_multi_remove_handle(data->multi, data);
  219. if(data->multi_easy) {
  220. /* when curl_easy_perform() is used, it creates its own multi handle to
  221. use and this is the one */
  222. curl_multi_cleanup(data->multi_easy);
  223. data->multi_easy = NULL;
  224. }
  225. }
  226. data->magic = 0; /* force a clear AFTER the possibly enforced removal from
  227. the multi handle, since that function uses the magic
  228. field! */
  229. if(data->state.rangestringalloc)
  230. free(data->state.range);
  231. /* freed here just in case DONE wasn't called */
  232. Curl_free_request_state(data);
  233. /* Close down all open SSL info and sessions */
  234. Curl_ssl_close_all(data);
  235. Curl_safefree(data->state.first_host);
  236. Curl_safefree(data->state.scratch);
  237. Curl_ssl_free_certinfo(data);
  238. /* Cleanup possible redirect junk */
  239. free(data->req.newurl);
  240. data->req.newurl = NULL;
  241. if(data->state.referer_alloc) {
  242. Curl_safefree(data->state.referer);
  243. data->state.referer_alloc = FALSE;
  244. }
  245. data->state.referer = NULL;
  246. up_free(data);
  247. Curl_safefree(data->state.buffer);
  248. Curl_dyn_free(&data->state.headerb);
  249. Curl_safefree(data->state.ulbuf);
  250. Curl_flush_cookies(data, TRUE);
  251. Curl_altsvc_save(data, data->asi, data->set.str[STRING_ALTSVC]);
  252. Curl_altsvc_cleanup(&data->asi);
  253. Curl_hsts_save(data, data->hsts, data->set.str[STRING_HSTS]);
  254. #ifndef CURL_DISABLE_HSTS
  255. if(!data->share || !data->share->hsts)
  256. Curl_hsts_cleanup(&data->hsts);
  257. curl_slist_free_all(data->state.hstslist); /* clean up list */
  258. #endif
  259. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_DIGEST_AUTH)
  260. Curl_http_auth_cleanup_digest(data);
  261. #endif
  262. Curl_safefree(data->info.contenttype);
  263. Curl_safefree(data->info.wouldredirect);
  264. data_priority_cleanup(data);
  265. /* No longer a dirty share, if it exists */
  266. if(data->share) {
  267. Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
  268. data->share->dirty--;
  269. Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
  270. }
  271. Curl_safefree(data->state.aptr.proxyuserpwd);
  272. Curl_safefree(data->state.aptr.uagent);
  273. Curl_safefree(data->state.aptr.userpwd);
  274. Curl_safefree(data->state.aptr.accept_encoding);
  275. Curl_safefree(data->state.aptr.te);
  276. Curl_safefree(data->state.aptr.rangeline);
  277. Curl_safefree(data->state.aptr.ref);
  278. Curl_safefree(data->state.aptr.host);
  279. Curl_safefree(data->state.aptr.cookiehost);
  280. Curl_safefree(data->state.aptr.rtsp_transport);
  281. Curl_safefree(data->state.aptr.user);
  282. Curl_safefree(data->state.aptr.passwd);
  283. Curl_safefree(data->state.aptr.proxyuser);
  284. Curl_safefree(data->state.aptr.proxypasswd);
  285. #ifndef CURL_DISABLE_DOH
  286. if(data->req.doh) {
  287. Curl_dyn_free(&data->req.doh->probe[0].serverdoh);
  288. Curl_dyn_free(&data->req.doh->probe[1].serverdoh);
  289. curl_slist_free_all(data->req.doh->headers);
  290. Curl_safefree(data->req.doh);
  291. }
  292. #endif
  293. #ifndef CURL_DISABLE_HTTP
  294. Curl_mime_cleanpart(data->state.formp);
  295. Curl_safefree(data->state.formp);
  296. #endif
  297. /* destruct wildcard structures if it is needed */
  298. Curl_wildcard_dtor(&data->wildcard);
  299. Curl_freeset(data);
  300. Curl_headers_cleanup(data);
  301. free(data);
  302. return CURLE_OK;
  303. }
  304. /*
  305. * Initialize the UserDefined fields within a Curl_easy.
  306. * This may be safely called on a new or existing Curl_easy.
  307. */
  308. CURLcode Curl_init_userdefined(struct Curl_easy *data)
  309. {
  310. struct UserDefined *set = &data->set;
  311. CURLcode result = CURLE_OK;
  312. set->out = stdout; /* default output to stdout */
  313. set->in_set = stdin; /* default input from stdin */
  314. set->err = stderr; /* default stderr to stderr */
  315. /* use fwrite as default function to store output */
  316. set->fwrite_func = (curl_write_callback)fwrite;
  317. /* use fread as default function to read input */
  318. set->fread_func_set = (curl_read_callback)fread;
  319. set->is_fread_set = 0;
  320. set->seek_func = ZERO_NULL;
  321. set->seek_client = ZERO_NULL;
  322. set->filesize = -1; /* we don't know the size */
  323. set->postfieldsize = -1; /* unknown size */
  324. set->maxredirs = 30; /* sensible default */
  325. set->method = HTTPREQ_GET; /* Default HTTP request */
  326. #ifndef CURL_DISABLE_RTSP
  327. set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
  328. #endif
  329. #ifndef CURL_DISABLE_FTP
  330. set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
  331. set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
  332. set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
  333. set->ftp_filemethod = FTPFILE_MULTICWD;
  334. set->ftp_skip_ip = TRUE; /* skip PASV IP by default */
  335. #endif
  336. set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
  337. /* Set the default size of the SSL session ID cache */
  338. set->general_ssl.max_ssl_sessions = 5;
  339. /* Timeout every 24 hours by default */
  340. set->general_ssl.ca_cache_timeout = 24 * 60 * 60;
  341. set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
  342. #ifndef CURL_DISABLE_PROXY
  343. set->proxyport = 0;
  344. set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
  345. set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
  346. /* SOCKS5 proxy auth defaults to username/password + GSS-API */
  347. set->socks5auth = CURLAUTH_BASIC | CURLAUTH_GSSAPI;
  348. #endif
  349. /* make libcurl quiet by default: */
  350. set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
  351. Curl_mime_initpart(&set->mimepost);
  352. Curl_ssl_easy_config_init(data);
  353. #ifndef CURL_DISABLE_DOH
  354. set->doh_verifyhost = TRUE;
  355. set->doh_verifypeer = TRUE;
  356. #endif
  357. #ifdef USE_SSH
  358. /* defaults to any auth type */
  359. set->ssh_auth_types = CURLSSH_AUTH_DEFAULT;
  360. set->new_directory_perms = 0755; /* Default permissions */
  361. #endif
  362. set->new_file_perms = 0644; /* Default permissions */
  363. set->allowed_protocols = (curl_prot_t) CURLPROTO_ALL;
  364. set->redir_protocols = CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_FTP |
  365. CURLPROTO_FTPS;
  366. #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
  367. /*
  368. * disallow unprotected protection negotiation NEC reference implementation
  369. * seem not to follow rfc1961 section 4.3/4.4
  370. */
  371. set->socks5_gssapi_nec = FALSE;
  372. #endif
  373. /* Set the default CA cert bundle/path detected/specified at build time.
  374. *
  375. * If Schannel is the selected SSL backend then these locations are
  376. * ignored. We allow setting CA location for schannel only when explicitly
  377. * specified by the user via CURLOPT_CAINFO / --cacert.
  378. */
  379. if(Curl_ssl_backend() != CURLSSLBACKEND_SCHANNEL) {
  380. #if defined(CURL_CA_BUNDLE)
  381. result = Curl_setstropt(&set->str[STRING_SSL_CAFILE], CURL_CA_BUNDLE);
  382. if(result)
  383. return result;
  384. result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_PROXY],
  385. CURL_CA_BUNDLE);
  386. if(result)
  387. return result;
  388. #endif
  389. #if defined(CURL_CA_PATH)
  390. result = Curl_setstropt(&set->str[STRING_SSL_CAPATH], CURL_CA_PATH);
  391. if(result)
  392. return result;
  393. result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_PROXY], CURL_CA_PATH);
  394. if(result)
  395. return result;
  396. #endif
  397. }
  398. #ifndef CURL_DISABLE_FTP
  399. set->wildcard_enabled = FALSE;
  400. set->chunk_bgn = ZERO_NULL;
  401. set->chunk_end = ZERO_NULL;
  402. set->fnmatch = ZERO_NULL;
  403. #endif
  404. set->tcp_keepalive = FALSE;
  405. set->tcp_keepintvl = 60;
  406. set->tcp_keepidle = 60;
  407. set->tcp_fastopen = FALSE;
  408. set->tcp_nodelay = TRUE;
  409. set->ssl_enable_alpn = TRUE;
  410. set->expect_100_timeout = 1000L; /* Wait for a second by default. */
  411. set->sep_headers = TRUE; /* separated header lists by default */
  412. set->buffer_size = READBUFFER_SIZE;
  413. set->upload_buffer_size = UPLOADBUFFER_DEFAULT;
  414. set->happy_eyeballs_timeout = CURL_HET_DEFAULT;
  415. set->upkeep_interval_ms = CURL_UPKEEP_INTERVAL_DEFAULT;
  416. set->maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */
  417. set->maxage_conn = 118;
  418. set->maxlifetime_conn = 0;
  419. set->http09_allowed = FALSE;
  420. #ifdef USE_HTTP2
  421. set->httpwant = CURL_HTTP_VERSION_2TLS
  422. #else
  423. set->httpwant = CURL_HTTP_VERSION_1_1
  424. #endif
  425. ;
  426. #if defined(USE_HTTP2) || defined(USE_HTTP3)
  427. memset(&set->priority, 0, sizeof(set->priority));
  428. #endif
  429. set->quick_exit = 0L;
  430. return result;
  431. }
  432. /**
  433. * Curl_open()
  434. *
  435. * @param curl is a pointer to a sessionhandle pointer that gets set by this
  436. * function.
  437. * @return CURLcode
  438. */
  439. CURLcode Curl_open(struct Curl_easy **curl)
  440. {
  441. CURLcode result;
  442. struct Curl_easy *data;
  443. /* Very simple start-up: alloc the struct, init it with zeroes and return */
  444. data = calloc(1, sizeof(struct Curl_easy));
  445. if(!data) {
  446. /* this is a very serious error */
  447. DEBUGF(fprintf(stderr, "Error: calloc of Curl_easy failed\n"));
  448. return CURLE_OUT_OF_MEMORY;
  449. }
  450. data->magic = CURLEASY_MAGIC_NUMBER;
  451. result = Curl_init_userdefined(data);
  452. if(!result) {
  453. Curl_dyn_init(&data->state.headerb, CURL_MAX_HTTP_HEADER);
  454. Curl_initinfo(data);
  455. /* most recent connection is not yet defined */
  456. data->state.lastconnect_id = -1;
  457. data->state.recent_conn_id = -1;
  458. /* and not assigned an id yet */
  459. data->id = -1;
  460. data->progress.flags |= PGRS_HIDE;
  461. data->state.current_speed = -1; /* init to negative == impossible */
  462. }
  463. if(result) {
  464. Curl_dyn_free(&data->state.headerb);
  465. Curl_freeset(data);
  466. free(data);
  467. data = NULL;
  468. }
  469. else
  470. *curl = data;
  471. return result;
  472. }
  473. static void conn_shutdown(struct Curl_easy *data)
  474. {
  475. DEBUGASSERT(data);
  476. infof(data, "Closing connection");
  477. /* possible left-overs from the async name resolvers */
  478. Curl_resolver_cancel(data);
  479. Curl_conn_close(data, SECONDARYSOCKET);
  480. Curl_conn_close(data, FIRSTSOCKET);
  481. }
  482. static void conn_free(struct Curl_easy *data, struct connectdata *conn)
  483. {
  484. size_t i;
  485. DEBUGASSERT(conn);
  486. for(i = 0; i < ARRAYSIZE(conn->cfilter); ++i) {
  487. Curl_conn_cf_discard_all(data, conn, (int)i);
  488. }
  489. Curl_resolver_cleanup(conn->resolve_async.resolver);
  490. Curl_free_idnconverted_hostname(&conn->host);
  491. Curl_free_idnconverted_hostname(&conn->conn_to_host);
  492. #ifndef CURL_DISABLE_PROXY
  493. Curl_free_idnconverted_hostname(&conn->http_proxy.host);
  494. Curl_free_idnconverted_hostname(&conn->socks_proxy.host);
  495. Curl_safefree(conn->http_proxy.user);
  496. Curl_safefree(conn->socks_proxy.user);
  497. Curl_safefree(conn->http_proxy.passwd);
  498. Curl_safefree(conn->socks_proxy.passwd);
  499. Curl_safefree(conn->http_proxy.host.rawalloc); /* http proxy name buffer */
  500. Curl_safefree(conn->socks_proxy.host.rawalloc); /* socks proxy name buffer */
  501. #endif
  502. Curl_safefree(conn->user);
  503. Curl_safefree(conn->passwd);
  504. Curl_safefree(conn->sasl_authzid);
  505. Curl_safefree(conn->options);
  506. Curl_safefree(conn->oauth_bearer);
  507. #ifndef CURL_DISABLE_HTTP
  508. Curl_dyn_free(&conn->trailer);
  509. #endif
  510. Curl_safefree(conn->host.rawalloc); /* host name buffer */
  511. Curl_safefree(conn->conn_to_host.rawalloc); /* host name buffer */
  512. Curl_safefree(conn->hostname_resolve);
  513. Curl_safefree(conn->secondaryhostname);
  514. Curl_safefree(conn->localdev);
  515. Curl_ssl_conn_config_cleanup(conn);
  516. #ifdef USE_UNIX_SOCKETS
  517. Curl_safefree(conn->unix_domain_socket);
  518. #endif
  519. free(conn); /* free all the connection oriented data */
  520. }
  521. /*
  522. * Disconnects the given connection. Note the connection may not be the
  523. * primary connection, like when freeing room in the connection cache or
  524. * killing of a dead old connection.
  525. *
  526. * A connection needs an easy handle when closing down. We support this passed
  527. * in separately since the connection to get closed here is often already
  528. * disassociated from an easy handle.
  529. *
  530. * This function MUST NOT reset state in the Curl_easy struct if that
  531. * isn't strictly bound to the life-time of *this* particular connection.
  532. *
  533. */
  534. void Curl_disconnect(struct Curl_easy *data,
  535. struct connectdata *conn, bool dead_connection)
  536. {
  537. /* there must be a connection to close */
  538. DEBUGASSERT(conn);
  539. /* it must be removed from the connection cache */
  540. DEBUGASSERT(!conn->bundle);
  541. /* there must be an associated transfer */
  542. DEBUGASSERT(data);
  543. /* the transfer must be detached from the connection */
  544. DEBUGASSERT(!data->conn);
  545. DEBUGF(infof(data, "Curl_disconnect(conn #%"
  546. CURL_FORMAT_CURL_OFF_T ", dead=%d)",
  547. conn->connection_id, dead_connection));
  548. /*
  549. * If this connection isn't marked to force-close, leave it open if there
  550. * are other users of it
  551. */
  552. if(CONN_INUSE(conn) && !dead_connection) {
  553. DEBUGF(infof(data, "Curl_disconnect when inuse: %zu", CONN_INUSE(conn)));
  554. return;
  555. }
  556. if(conn->dns_entry) {
  557. Curl_resolv_unlock(data, conn->dns_entry);
  558. conn->dns_entry = NULL;
  559. }
  560. /* Cleanup NTLM connection-related data */
  561. Curl_http_auth_cleanup_ntlm(conn);
  562. /* Cleanup NEGOTIATE connection-related data */
  563. Curl_http_auth_cleanup_negotiate(conn);
  564. if(conn->connect_only)
  565. /* treat the connection as dead in CONNECT_ONLY situations */
  566. dead_connection = TRUE;
  567. /* temporarily attach the connection to this transfer handle for the
  568. disconnect and shutdown */
  569. Curl_attach_connection(data, conn);
  570. if(conn->handler && conn->handler->disconnect)
  571. /* This is set if protocol-specific cleanups should be made */
  572. conn->handler->disconnect(data, conn, dead_connection);
  573. conn_shutdown(data);
  574. Curl_resolver_cancel(data);
  575. /* detach it again */
  576. Curl_detach_connection(data);
  577. conn_free(data, conn);
  578. }
  579. /*
  580. * IsMultiplexingPossible()
  581. *
  582. * Return a bitmask with the available multiplexing options for the given
  583. * requested connection.
  584. */
  585. static int IsMultiplexingPossible(const struct Curl_easy *handle,
  586. const struct connectdata *conn)
  587. {
  588. int avail = 0;
  589. /* If an HTTP protocol and multiplexing is enabled */
  590. if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
  591. (!conn->bits.protoconnstart || !conn->bits.close)) {
  592. if(Curl_multiplex_wanted(handle->multi) &&
  593. (handle->state.httpwant >= CURL_HTTP_VERSION_2))
  594. /* allows HTTP/2 */
  595. avail |= CURLPIPE_MULTIPLEX;
  596. }
  597. return avail;
  598. }
  599. #ifndef CURL_DISABLE_PROXY
  600. static bool
  601. proxy_info_matches(const struct proxy_info *data,
  602. const struct proxy_info *needle)
  603. {
  604. if((data->proxytype == needle->proxytype) &&
  605. (data->port == needle->port) &&
  606. strcasecompare(data->host.name, needle->host.name))
  607. return TRUE;
  608. return FALSE;
  609. }
  610. static bool
  611. socks_proxy_info_matches(const struct proxy_info *data,
  612. const struct proxy_info *needle)
  613. {
  614. if(!proxy_info_matches(data, needle))
  615. return FALSE;
  616. /* the user information is case-sensitive
  617. or at least it is not defined as case-insensitive
  618. see https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.1 */
  619. /* curl_strequal does a case insensitive comparison,
  620. so do not use it here! */
  621. if(Curl_timestrcmp(data->user, needle->user) ||
  622. Curl_timestrcmp(data->passwd, needle->passwd))
  623. return FALSE;
  624. return TRUE;
  625. }
  626. #else
  627. /* disabled, won't get called */
  628. #define proxy_info_matches(x,y) FALSE
  629. #define socks_proxy_info_matches(x,y) FALSE
  630. #endif
  631. /* A connection has to have been idle for a shorter time than 'maxage_conn'
  632. (the success rate is just too low after this), or created less than
  633. 'maxlifetime_conn' ago, to be subject for reuse. */
  634. static bool conn_maxage(struct Curl_easy *data,
  635. struct connectdata *conn,
  636. struct curltime now)
  637. {
  638. timediff_t idletime, lifetime;
  639. idletime = Curl_timediff(now, conn->lastused);
  640. idletime /= 1000; /* integer seconds is fine */
  641. if(idletime > data->set.maxage_conn) {
  642. infof(data, "Too old connection (%" CURL_FORMAT_TIMEDIFF_T
  643. " seconds idle), disconnect it", idletime);
  644. return TRUE;
  645. }
  646. lifetime = Curl_timediff(now, conn->created);
  647. lifetime /= 1000; /* integer seconds is fine */
  648. if(data->set.maxlifetime_conn && lifetime > data->set.maxlifetime_conn) {
  649. infof(data,
  650. "Too old connection (%" CURL_FORMAT_TIMEDIFF_T
  651. " seconds since creation), disconnect it", lifetime);
  652. return TRUE;
  653. }
  654. return FALSE;
  655. }
  656. /*
  657. * This function checks if the given connection is dead and extracts it from
  658. * the connection cache if so.
  659. *
  660. * When this is called as a Curl_conncache_foreach() callback, the connection
  661. * cache lock is held!
  662. *
  663. * Returns TRUE if the connection was dead and extracted.
  664. */
  665. static bool extract_if_dead(struct connectdata *conn,
  666. struct Curl_easy *data)
  667. {
  668. if(!CONN_INUSE(conn)) {
  669. /* The check for a dead socket makes sense only if the connection isn't in
  670. use */
  671. bool dead;
  672. struct curltime now = Curl_now();
  673. if(conn_maxage(data, conn, now)) {
  674. /* avoid check if already too old */
  675. dead = TRUE;
  676. }
  677. else if(conn->handler->connection_check) {
  678. /* The protocol has a special method for checking the state of the
  679. connection. Use it to check if the connection is dead. */
  680. unsigned int state;
  681. /* briefly attach the connection to this transfer for the purpose of
  682. checking it */
  683. Curl_attach_connection(data, conn);
  684. state = conn->handler->connection_check(data, conn, CONNCHECK_ISDEAD);
  685. dead = (state & CONNRESULT_DEAD);
  686. /* detach the connection again */
  687. Curl_detach_connection(data);
  688. }
  689. else {
  690. bool input_pending;
  691. Curl_attach_connection(data, conn);
  692. dead = !Curl_conn_is_alive(data, conn, &input_pending);
  693. if(input_pending) {
  694. /* For reuse, we want a "clean" connection state. The includes
  695. * that we expect - in general - no waiting input data. Input
  696. * waiting might be a TLS Notify Close, for example. We reject
  697. * that.
  698. * For protocols where data from other end may arrive at
  699. * any time (HTTP/2 PING for example), the protocol handler needs
  700. * to install its own `connection_check` callback.
  701. */
  702. dead = TRUE;
  703. }
  704. Curl_detach_connection(data);
  705. }
  706. if(dead) {
  707. infof(data, "Connection %" CURL_FORMAT_CURL_OFF_T " seems to be dead",
  708. conn->connection_id);
  709. Curl_conncache_remove_conn(data, conn, FALSE);
  710. return TRUE;
  711. }
  712. }
  713. return FALSE;
  714. }
  715. struct prunedead {
  716. struct Curl_easy *data;
  717. struct connectdata *extracted;
  718. };
  719. /*
  720. * Wrapper to use extract_if_dead() function in Curl_conncache_foreach()
  721. *
  722. */
  723. static int call_extract_if_dead(struct Curl_easy *data,
  724. struct connectdata *conn, void *param)
  725. {
  726. struct prunedead *p = (struct prunedead *)param;
  727. if(extract_if_dead(conn, data)) {
  728. /* stop the iteration here, pass back the connection that was extracted */
  729. p->extracted = conn;
  730. return 1;
  731. }
  732. return 0; /* continue iteration */
  733. }
  734. /*
  735. * This function scans the connection cache for half-open/dead connections,
  736. * closes and removes them. The cleanup is done at most once per second.
  737. *
  738. * When called, this transfer has no connection attached.
  739. */
  740. static void prune_dead_connections(struct Curl_easy *data)
  741. {
  742. struct curltime now = Curl_now();
  743. timediff_t elapsed;
  744. DEBUGASSERT(!data->conn); /* no connection */
  745. CONNCACHE_LOCK(data);
  746. elapsed =
  747. Curl_timediff(now, data->state.conn_cache->last_cleanup);
  748. CONNCACHE_UNLOCK(data);
  749. if(elapsed >= 1000L) {
  750. struct prunedead prune;
  751. prune.data = data;
  752. prune.extracted = NULL;
  753. while(Curl_conncache_foreach(data, data->state.conn_cache, &prune,
  754. call_extract_if_dead)) {
  755. /* unlocked */
  756. /* remove connection from cache */
  757. Curl_conncache_remove_conn(data, prune.extracted, TRUE);
  758. /* disconnect it */
  759. Curl_disconnect(data, prune.extracted, TRUE);
  760. }
  761. CONNCACHE_LOCK(data);
  762. data->state.conn_cache->last_cleanup = now;
  763. CONNCACHE_UNLOCK(data);
  764. }
  765. }
  766. #ifdef USE_SSH
  767. static bool ssh_config_matches(struct connectdata *one,
  768. struct connectdata *two)
  769. {
  770. return (Curl_safecmp(one->proto.sshc.rsa, two->proto.sshc.rsa) &&
  771. Curl_safecmp(one->proto.sshc.rsa_pub, two->proto.sshc.rsa_pub));
  772. }
  773. #else
  774. #define ssh_config_matches(x,y) FALSE
  775. #endif
  776. /*
  777. * Given one filled in connection struct (named needle), this function should
  778. * detect if there already is one that has all the significant details
  779. * exactly the same and thus should be used instead.
  780. *
  781. * If there is a match, this function returns TRUE - and has marked the
  782. * connection as 'in-use'. It must later be called with ConnectionDone() to
  783. * return back to 'idle' (unused) state.
  784. *
  785. * The force_reuse flag is set if the connection must be used.
  786. */
  787. static bool
  788. ConnectionExists(struct Curl_easy *data,
  789. struct connectdata *needle,
  790. struct connectdata **usethis,
  791. bool *force_reuse,
  792. bool *waitpipe)
  793. {
  794. struct connectdata *chosen = NULL;
  795. bool foundPendingCandidate = FALSE;
  796. bool canmultiplex = FALSE;
  797. struct connectbundle *bundle;
  798. struct Curl_llist_element *curr;
  799. #ifdef USE_NTLM
  800. bool wantNTLMhttp = ((data->state.authhost.want &
  801. (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
  802. (needle->handler->protocol & PROTO_FAMILY_HTTP));
  803. #ifndef CURL_DISABLE_PROXY
  804. bool wantProxyNTLMhttp = (needle->bits.proxy_user_passwd &&
  805. ((data->state.authproxy.want &
  806. (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
  807. (needle->handler->protocol & PROTO_FAMILY_HTTP)));
  808. #else
  809. bool wantProxyNTLMhttp = FALSE;
  810. #endif
  811. #endif
  812. /* plain HTTP with upgrade */
  813. bool h2upgrade = (data->state.httpwant == CURL_HTTP_VERSION_2_0) &&
  814. (needle->handler->protocol & CURLPROTO_HTTP);
  815. *usethis = NULL;
  816. *force_reuse = FALSE;
  817. *waitpipe = FALSE;
  818. /* Look up the bundle with all the connections to this particular host.
  819. Locks the connection cache, beware of early returns! */
  820. bundle = Curl_conncache_find_bundle(data, needle, data->state.conn_cache);
  821. if(!bundle) {
  822. CONNCACHE_UNLOCK(data);
  823. return FALSE;
  824. }
  825. infof(data, "Found bundle for host: %p [%s]",
  826. (void *)bundle, (bundle->multiuse == BUNDLE_MULTIPLEX ?
  827. "can multiplex" : "serially"));
  828. /* We can only multiplex iff the transfer allows it AND we know
  829. * that the server we want to talk to supports it as well. */
  830. canmultiplex = FALSE;
  831. if(IsMultiplexingPossible(data, needle)) {
  832. if(bundle->multiuse == BUNDLE_UNKNOWN) {
  833. if(data->set.pipewait) {
  834. infof(data, "Server doesn't support multiplex yet, wait");
  835. *waitpipe = TRUE;
  836. CONNCACHE_UNLOCK(data);
  837. return FALSE; /* no reuse */
  838. }
  839. infof(data, "Server doesn't support multiplex (yet)");
  840. }
  841. else if(bundle->multiuse == BUNDLE_MULTIPLEX) {
  842. if(Curl_multiplex_wanted(data->multi))
  843. canmultiplex = TRUE;
  844. else
  845. infof(data, "Could multiplex, but not asked to");
  846. }
  847. else if(bundle->multiuse == BUNDLE_NO_MULTIUSE) {
  848. infof(data, "Can not multiplex, even if we wanted to");
  849. }
  850. }
  851. curr = bundle->conn_list.head;
  852. while(curr) {
  853. struct connectdata *check = curr->ptr;
  854. /* Get next node now. We might remove a dead `check` connection which
  855. * would invalidate `curr` as well. */
  856. curr = curr->next;
  857. /* Note that if we use an HTTP proxy in normal mode (no tunneling), we
  858. * check connections to that proxy and not to the actual remote server.
  859. */
  860. if(check->connect_only || check->bits.close)
  861. /* connect-only or to-be-closed connections will not be reused */
  862. continue;
  863. if(data->set.ipver != CURL_IPRESOLVE_WHATEVER
  864. && data->set.ipver != check->ip_version) {
  865. /* skip because the connection is not via the requested IP version */
  866. continue;
  867. }
  868. if(!canmultiplex) {
  869. if(Curl_resolver_asynch() &&
  870. /* primary_ip[0] is NUL only if the resolving of the name hasn't
  871. completed yet and until then we don't reuse this connection */
  872. !check->primary_ip[0])
  873. continue;
  874. }
  875. if(CONN_INUSE(check)) {
  876. if(!canmultiplex) {
  877. /* transfer can't be multiplexed and check is in use */
  878. continue;
  879. }
  880. else {
  881. /* Could multiplex, but not when check belongs to another multi */
  882. struct Curl_llist_element *e = check->easyq.head;
  883. struct Curl_easy *entry = e->ptr;
  884. if(entry->multi != data->multi)
  885. continue;
  886. }
  887. }
  888. if(!Curl_conn_is_connected(check, FIRSTSOCKET)) {
  889. foundPendingCandidate = TRUE;
  890. /* Don't pick a connection that hasn't connected yet */
  891. infof(data, "Connection #%" CURL_FORMAT_CURL_OFF_T
  892. " isn't open enough, can't reuse", check->connection_id);
  893. continue;
  894. }
  895. /* `check` is connected. if it is in use and does not support multiplex,
  896. * we cannot use it. */
  897. if(!check->bits.multiplex && CONN_INUSE(check))
  898. continue;
  899. #ifdef USE_UNIX_SOCKETS
  900. if(needle->unix_domain_socket) {
  901. if(!check->unix_domain_socket)
  902. continue;
  903. if(strcmp(needle->unix_domain_socket, check->unix_domain_socket))
  904. continue;
  905. if(needle->bits.abstract_unix_socket !=
  906. check->bits.abstract_unix_socket)
  907. continue;
  908. }
  909. else if(check->unix_domain_socket)
  910. continue;
  911. #endif
  912. if((needle->handler->flags&PROTOPT_SSL) !=
  913. (check->handler->flags&PROTOPT_SSL))
  914. /* don't do mixed SSL and non-SSL connections */
  915. if(get_protocol_family(check->handler) !=
  916. needle->handler->protocol || !check->bits.tls_upgraded)
  917. /* except protocols that have been upgraded via TLS */
  918. continue;
  919. if(needle->bits.conn_to_host != check->bits.conn_to_host)
  920. /* don't mix connections that use the "connect to host" feature and
  921. * connections that don't use this feature */
  922. continue;
  923. if(needle->bits.conn_to_port != check->bits.conn_to_port)
  924. /* don't mix connections that use the "connect to port" feature and
  925. * connections that don't use this feature */
  926. continue;
  927. #ifndef CURL_DISABLE_PROXY
  928. if(needle->bits.httpproxy != check->bits.httpproxy ||
  929. needle->bits.socksproxy != check->bits.socksproxy)
  930. continue;
  931. if(needle->bits.socksproxy &&
  932. !socks_proxy_info_matches(&needle->socks_proxy,
  933. &check->socks_proxy))
  934. continue;
  935. if(needle->bits.httpproxy) {
  936. if(needle->bits.tunnel_proxy != check->bits.tunnel_proxy)
  937. continue;
  938. if(!proxy_info_matches(&needle->http_proxy, &check->http_proxy))
  939. continue;
  940. if(IS_HTTPS_PROXY(needle->http_proxy.proxytype)) {
  941. /* https proxies come in different types, http/1.1, h2, ... */
  942. if(needle->http_proxy.proxytype != check->http_proxy.proxytype)
  943. continue;
  944. /* match SSL config to proxy */
  945. if(!Curl_ssl_conn_config_match(data, check, TRUE)) {
  946. DEBUGF(infof(data,
  947. "Connection #%" CURL_FORMAT_CURL_OFF_T
  948. " has different SSL proxy parameters, can't reuse",
  949. check->connection_id));
  950. continue;
  951. }
  952. /* the SSL config to the server, which may apply here is checked
  953. * further below */
  954. }
  955. }
  956. #endif
  957. if(h2upgrade && !check->httpversion && canmultiplex) {
  958. if(data->set.pipewait) {
  959. infof(data, "Server upgrade doesn't support multiplex yet, wait");
  960. *waitpipe = TRUE;
  961. CONNCACHE_UNLOCK(data);
  962. return FALSE; /* no reuse */
  963. }
  964. infof(data, "Server upgrade cannot be used");
  965. continue; /* can't be used atm */
  966. }
  967. if(needle->localdev || needle->localport) {
  968. /* If we are bound to a specific local end (IP+port), we must not
  969. reuse a random other one, although if we didn't ask for a
  970. particular one we can reuse one that was bound.
  971. This comparison is a bit rough and too strict. Since the input
  972. parameters can be specified in numerous ways and still end up the
  973. same it would take a lot of processing to make it really accurate.
  974. Instead, this matching will assume that reuses of bound connections
  975. will most likely also reuse the exact same binding parameters and
  976. missing out a few edge cases shouldn't hurt anyone very much.
  977. */
  978. if((check->localport != needle->localport) ||
  979. (check->localportrange != needle->localportrange) ||
  980. (needle->localdev &&
  981. (!check->localdev || strcmp(check->localdev, needle->localdev))))
  982. continue;
  983. }
  984. if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) {
  985. /* This protocol requires credentials per connection,
  986. so verify that we're using the same name and password as well */
  987. if(Curl_timestrcmp(needle->user, check->user) ||
  988. Curl_timestrcmp(needle->passwd, check->passwd) ||
  989. Curl_timestrcmp(needle->sasl_authzid, check->sasl_authzid) ||
  990. Curl_timestrcmp(needle->oauth_bearer, check->oauth_bearer)) {
  991. /* one of them was different */
  992. continue;
  993. }
  994. }
  995. /* GSS delegation differences do not actually affect every connection
  996. and auth method, but this check takes precaution before efficiency */
  997. if(needle->gssapi_delegation != check->gssapi_delegation)
  998. continue;
  999. /* If looking for HTTP and the HTTP version we want is less
  1000. * than the HTTP version of the check connection, continue looking */
  1001. if((needle->handler->protocol & PROTO_FAMILY_HTTP) &&
  1002. (((check->httpversion >= 20) &&
  1003. (data->state.httpwant < CURL_HTTP_VERSION_2_0))
  1004. || ((check->httpversion >= 30) &&
  1005. (data->state.httpwant < CURL_HTTP_VERSION_3))))
  1006. continue;
  1007. #ifdef USE_SSH
  1008. else if(get_protocol_family(needle->handler) & PROTO_FAMILY_SSH) {
  1009. if(!ssh_config_matches(needle, check))
  1010. continue;
  1011. }
  1012. #endif
  1013. #ifndef CURL_DISABLE_FTP
  1014. else if(get_protocol_family(needle->handler) & PROTO_FAMILY_FTP) {
  1015. /* Also match ACCOUNT, ALTERNATIVE-TO-USER, USE_SSL and CCC options */
  1016. if(Curl_timestrcmp(needle->proto.ftpc.account,
  1017. check->proto.ftpc.account) ||
  1018. Curl_timestrcmp(needle->proto.ftpc.alternative_to_user,
  1019. check->proto.ftpc.alternative_to_user) ||
  1020. (needle->proto.ftpc.use_ssl != check->proto.ftpc.use_ssl) ||
  1021. (needle->proto.ftpc.ccc != check->proto.ftpc.ccc))
  1022. continue;
  1023. }
  1024. #endif
  1025. /* Additional match requirements if talking TLS OR
  1026. * not talking to a HTTP proxy OR using a tunnel through a proxy */
  1027. if((needle->handler->flags&PROTOPT_SSL)
  1028. #ifndef CURL_DISABLE_PROXY
  1029. || !needle->bits.httpproxy || needle->bits.tunnel_proxy
  1030. #endif
  1031. ) {
  1032. /* Talking the same protocol scheme or a TLS upgraded protocol in the
  1033. * same protocol family? */
  1034. if(!strcasecompare(needle->handler->scheme, check->handler->scheme) &&
  1035. (get_protocol_family(check->handler) !=
  1036. needle->handler->protocol || !check->bits.tls_upgraded))
  1037. continue;
  1038. /* If needle has "conn_to_*" set, check must match this */
  1039. if((needle->bits.conn_to_host && !strcasecompare(
  1040. needle->conn_to_host.name, check->conn_to_host.name)) ||
  1041. (needle->bits.conn_to_port &&
  1042. needle->conn_to_port != check->conn_to_port))
  1043. continue;
  1044. /* hostname and port must match */
  1045. if(!strcasecompare(needle->host.name, check->host.name) ||
  1046. needle->remote_port != check->remote_port)
  1047. continue;
  1048. /* If talking TLS, check needs to use the same SSL options. */
  1049. if((needle->handler->flags & PROTOPT_SSL) &&
  1050. !Curl_ssl_conn_config_match(data, check, FALSE)) {
  1051. DEBUGF(infof(data,
  1052. "Connection #%" CURL_FORMAT_CURL_OFF_T
  1053. " has different SSL parameters, can't reuse",
  1054. check->connection_id));
  1055. continue;
  1056. }
  1057. }
  1058. #if defined(USE_NTLM)
  1059. /* If we are looking for an HTTP+NTLM connection, check if this is
  1060. already authenticating with the right credentials. If not, keep
  1061. looking so that we can reuse NTLM connections if
  1062. possible. (Especially we must not reuse the same connection if
  1063. partway through a handshake!) */
  1064. if(wantNTLMhttp) {
  1065. if(Curl_timestrcmp(needle->user, check->user) ||
  1066. Curl_timestrcmp(needle->passwd, check->passwd)) {
  1067. /* we prefer a credential match, but this is at least a connection
  1068. that can be reused and "upgraded" to NTLM */
  1069. if(check->http_ntlm_state == NTLMSTATE_NONE)
  1070. chosen = check;
  1071. continue;
  1072. }
  1073. }
  1074. else if(check->http_ntlm_state != NTLMSTATE_NONE) {
  1075. /* Connection is using NTLM auth but we don't want NTLM */
  1076. continue;
  1077. }
  1078. #ifndef CURL_DISABLE_PROXY
  1079. /* Same for Proxy NTLM authentication */
  1080. if(wantProxyNTLMhttp) {
  1081. /* Both check->http_proxy.user and check->http_proxy.passwd can be
  1082. * NULL */
  1083. if(!check->http_proxy.user || !check->http_proxy.passwd)
  1084. continue;
  1085. if(Curl_timestrcmp(needle->http_proxy.user,
  1086. check->http_proxy.user) ||
  1087. Curl_timestrcmp(needle->http_proxy.passwd,
  1088. check->http_proxy.passwd))
  1089. continue;
  1090. }
  1091. else if(check->proxy_ntlm_state != NTLMSTATE_NONE) {
  1092. /* Proxy connection is using NTLM auth but we don't want NTLM */
  1093. continue;
  1094. }
  1095. #endif
  1096. if(wantNTLMhttp || wantProxyNTLMhttp) {
  1097. /* Credentials are already checked, we may use this connection.
  1098. * With NTLM being weird as it is, we MUST use a
  1099. * connection where it has already been fully negotiated.
  1100. * If it has not, we keep on looking for a better one. */
  1101. chosen = check;
  1102. if((wantNTLMhttp &&
  1103. (check->http_ntlm_state != NTLMSTATE_NONE)) ||
  1104. (wantProxyNTLMhttp &&
  1105. (check->proxy_ntlm_state != NTLMSTATE_NONE))) {
  1106. /* We must use this connection, no other */
  1107. *force_reuse = TRUE;
  1108. break;
  1109. }
  1110. /* Continue look up for a better connection */
  1111. continue;
  1112. }
  1113. #endif
  1114. if(CONN_INUSE(check)) {
  1115. DEBUGASSERT(canmultiplex);
  1116. DEBUGASSERT(check->bits.multiplex);
  1117. /* If multiplexed, make sure we don't go over concurrency limit */
  1118. if(CONN_INUSE(check) >=
  1119. Curl_multi_max_concurrent_streams(data->multi)) {
  1120. infof(data, "client side MAX_CONCURRENT_STREAMS reached"
  1121. ", skip (%zu)", CONN_INUSE(check));
  1122. continue;
  1123. }
  1124. if(CONN_INUSE(check) >=
  1125. Curl_conn_get_max_concurrent(data, check, FIRSTSOCKET)) {
  1126. infof(data, "MAX_CONCURRENT_STREAMS reached, skip (%zu)",
  1127. CONN_INUSE(check));
  1128. continue;
  1129. }
  1130. /* When not multiplexed, we have a match here! */
  1131. infof(data, "Multiplexed connection found");
  1132. }
  1133. else if(extract_if_dead(check, data)) {
  1134. /* disconnect it */
  1135. Curl_disconnect(data, check, TRUE);
  1136. continue;
  1137. }
  1138. /* We have found a connection. Let's stop searching. */
  1139. chosen = check;
  1140. break;
  1141. } /* loop over connection bundle */
  1142. if(chosen) {
  1143. /* mark it as used before releasing the lock */
  1144. Curl_attach_connection(data, chosen);
  1145. CONNCACHE_UNLOCK(data);
  1146. *usethis = chosen;
  1147. return TRUE; /* yes, we found one to use! */
  1148. }
  1149. CONNCACHE_UNLOCK(data);
  1150. if(foundPendingCandidate && data->set.pipewait) {
  1151. infof(data,
  1152. "Found pending candidate for reuse and CURLOPT_PIPEWAIT is set");
  1153. *waitpipe = TRUE;
  1154. }
  1155. return FALSE; /* no matching connecting exists */
  1156. }
  1157. /*
  1158. * verboseconnect() displays verbose information after a connect
  1159. */
  1160. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1161. void Curl_verboseconnect(struct Curl_easy *data,
  1162. struct connectdata *conn)
  1163. {
  1164. if(data->set.verbose)
  1165. infof(data, "Connected to %s (%s) port %u",
  1166. CURL_CONN_HOST_DISPNAME(conn), conn->primary_ip, conn->port);
  1167. }
  1168. #endif
  1169. /*
  1170. * Allocate and initialize a new connectdata object.
  1171. */
  1172. static struct connectdata *allocate_conn(struct Curl_easy *data)
  1173. {
  1174. struct connectdata *conn = calloc(1, sizeof(struct connectdata));
  1175. if(!conn)
  1176. return NULL;
  1177. /* and we setup a few fields in case we end up actually using this struct */
  1178. conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
  1179. conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
  1180. conn->connection_id = -1; /* no ID */
  1181. conn->port = -1; /* unknown at this point */
  1182. conn->remote_port = -1; /* unknown at this point */
  1183. /* Default protocol-independent behavior doesn't support persistent
  1184. connections, so we set this to force-close. Protocols that support
  1185. this need to set this to FALSE in their "curl_do" functions. */
  1186. connclose(conn, "Default to force-close");
  1187. /* Store creation time to help future close decision making */
  1188. conn->created = Curl_now();
  1189. /* Store current time to give a baseline to keepalive connection times. */
  1190. conn->keepalive = conn->created;
  1191. #ifndef CURL_DISABLE_PROXY
  1192. conn->http_proxy.proxytype = data->set.proxytype;
  1193. conn->socks_proxy.proxytype = CURLPROXY_SOCKS4;
  1194. /* note that these two proxy bits are now just on what looks to be
  1195. requested, they may be altered down the road */
  1196. conn->bits.proxy = (data->set.str[STRING_PROXY] &&
  1197. *data->set.str[STRING_PROXY]) ? TRUE : FALSE;
  1198. conn->bits.httpproxy = (conn->bits.proxy &&
  1199. (conn->http_proxy.proxytype == CURLPROXY_HTTP ||
  1200. conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0 ||
  1201. IS_HTTPS_PROXY(conn->http_proxy.proxytype))) ?
  1202. TRUE : FALSE;
  1203. conn->bits.socksproxy = (conn->bits.proxy &&
  1204. !conn->bits.httpproxy) ? TRUE : FALSE;
  1205. if(data->set.str[STRING_PRE_PROXY] && *data->set.str[STRING_PRE_PROXY]) {
  1206. conn->bits.proxy = TRUE;
  1207. conn->bits.socksproxy = TRUE;
  1208. }
  1209. conn->bits.proxy_user_passwd =
  1210. (data->state.aptr.proxyuser) ? TRUE : FALSE;
  1211. conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
  1212. #endif /* CURL_DISABLE_PROXY */
  1213. #ifndef CURL_DISABLE_FTP
  1214. conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
  1215. conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
  1216. #endif
  1217. conn->ip_version = data->set.ipver;
  1218. conn->connect_only = data->set.connect_only;
  1219. conn->transport = TRNSPRT_TCP; /* most of them are TCP streams */
  1220. #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
  1221. defined(NTLM_WB_ENABLED)
  1222. conn->ntlm.ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
  1223. conn->proxyntlm.ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
  1224. #endif
  1225. /* Initialize the easy handle list */
  1226. Curl_llist_init(&conn->easyq, NULL);
  1227. #ifdef HAVE_GSSAPI
  1228. conn->data_prot = PROT_CLEAR;
  1229. #endif
  1230. /* Store the local bind parameters that will be used for this connection */
  1231. if(data->set.str[STRING_DEVICE]) {
  1232. conn->localdev = strdup(data->set.str[STRING_DEVICE]);
  1233. if(!conn->localdev)
  1234. goto error;
  1235. }
  1236. #ifndef CURL_DISABLE_BINDLOCAL
  1237. conn->localportrange = data->set.localportrange;
  1238. conn->localport = data->set.localport;
  1239. #endif
  1240. /* the close socket stuff needs to be copied to the connection struct as
  1241. it may live on without (this specific) Curl_easy */
  1242. conn->fclosesocket = data->set.fclosesocket;
  1243. conn->closesocket_client = data->set.closesocket_client;
  1244. conn->lastused = conn->created;
  1245. conn->gssapi_delegation = data->set.gssapi_delegation;
  1246. return conn;
  1247. error:
  1248. free(conn->localdev);
  1249. free(conn);
  1250. return NULL;
  1251. }
  1252. const struct Curl_handler *Curl_get_scheme_handler(const char *scheme)
  1253. {
  1254. return Curl_getn_scheme_handler(scheme, strlen(scheme));
  1255. }
  1256. /* returns the handler if the given scheme is built-in */
  1257. const struct Curl_handler *Curl_getn_scheme_handler(const char *scheme,
  1258. size_t len)
  1259. {
  1260. /* table generated by schemetable.c:
  1261. 1. gcc schemetable.c && ./a.out
  1262. 2. check how small the table gets
  1263. 3. tweak the hash algorithm, then rerun from 1
  1264. 4. when the table is good enough
  1265. 5. copy the table into this source code
  1266. 6. make sure this function uses the same hash function that worked for
  1267. schemetable.c
  1268. 7. if needed, adjust the #ifdefs in schemetable.c and rerun
  1269. */
  1270. static const struct Curl_handler * const protocols[67] = {
  1271. #ifndef CURL_DISABLE_FILE
  1272. &Curl_handler_file,
  1273. #else
  1274. NULL,
  1275. #endif
  1276. NULL, NULL,
  1277. #if defined(USE_SSL) && !defined(CURL_DISABLE_GOPHER)
  1278. &Curl_handler_gophers,
  1279. #else
  1280. NULL,
  1281. #endif
  1282. NULL,
  1283. #ifdef USE_LIBRTMP
  1284. &Curl_handler_rtmpe,
  1285. #else
  1286. NULL,
  1287. #endif
  1288. #ifndef CURL_DISABLE_SMTP
  1289. &Curl_handler_smtp,
  1290. #else
  1291. NULL,
  1292. #endif
  1293. #if defined(USE_SSH)
  1294. &Curl_handler_sftp,
  1295. #else
  1296. NULL,
  1297. #endif
  1298. #if !defined(CURL_DISABLE_SMB) && defined(USE_CURL_NTLM_CORE) && \
  1299. (SIZEOF_CURL_OFF_T > 4)
  1300. &Curl_handler_smb,
  1301. #else
  1302. NULL,
  1303. #endif
  1304. #if defined(USE_SSL) && !defined(CURL_DISABLE_SMTP)
  1305. &Curl_handler_smtps,
  1306. #else
  1307. NULL,
  1308. #endif
  1309. #ifndef CURL_DISABLE_TELNET
  1310. &Curl_handler_telnet,
  1311. #else
  1312. NULL,
  1313. #endif
  1314. #ifndef CURL_DISABLE_GOPHER
  1315. &Curl_handler_gopher,
  1316. #else
  1317. NULL,
  1318. #endif
  1319. #ifndef CURL_DISABLE_TFTP
  1320. &Curl_handler_tftp,
  1321. #else
  1322. NULL,
  1323. #endif
  1324. NULL, NULL, NULL,
  1325. #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
  1326. &Curl_handler_ftps,
  1327. #else
  1328. NULL,
  1329. #endif
  1330. #ifndef CURL_DISABLE_HTTP
  1331. &Curl_handler_http,
  1332. #else
  1333. NULL,
  1334. #endif
  1335. #ifndef CURL_DISABLE_IMAP
  1336. &Curl_handler_imap,
  1337. #else
  1338. NULL,
  1339. #endif
  1340. #ifdef USE_LIBRTMP
  1341. &Curl_handler_rtmps,
  1342. #else
  1343. NULL,
  1344. #endif
  1345. #ifdef USE_LIBRTMP
  1346. &Curl_handler_rtmpt,
  1347. #else
  1348. NULL,
  1349. #endif
  1350. NULL, NULL, NULL,
  1351. #if !defined(CURL_DISABLE_LDAP) && \
  1352. !defined(CURL_DISABLE_LDAPS) && \
  1353. ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
  1354. (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
  1355. &Curl_handler_ldaps,
  1356. #else
  1357. NULL,
  1358. #endif
  1359. #if defined(USE_WEBSOCKETS) && \
  1360. defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
  1361. &Curl_handler_wss,
  1362. #else
  1363. NULL,
  1364. #endif
  1365. #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
  1366. &Curl_handler_https,
  1367. #else
  1368. NULL,
  1369. #endif
  1370. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  1371. #ifndef CURL_DISABLE_RTSP
  1372. &Curl_handler_rtsp,
  1373. #else
  1374. NULL,
  1375. #endif
  1376. #if defined(USE_SSL) && !defined(CURL_DISABLE_SMB) && \
  1377. defined(USE_CURL_NTLM_CORE) && (SIZEOF_CURL_OFF_T > 4)
  1378. &Curl_handler_smbs,
  1379. #else
  1380. NULL,
  1381. #endif
  1382. #if defined(USE_SSH) && !defined(USE_WOLFSSH)
  1383. &Curl_handler_scp,
  1384. #else
  1385. NULL,
  1386. #endif
  1387. NULL, NULL, NULL,
  1388. #ifndef CURL_DISABLE_POP3
  1389. &Curl_handler_pop3,
  1390. #else
  1391. NULL,
  1392. #endif
  1393. NULL, NULL,
  1394. #ifdef USE_LIBRTMP
  1395. &Curl_handler_rtmp,
  1396. #else
  1397. NULL,
  1398. #endif
  1399. NULL, NULL, NULL,
  1400. #ifdef USE_LIBRTMP
  1401. &Curl_handler_rtmpte,
  1402. #else
  1403. NULL,
  1404. #endif
  1405. NULL, NULL, NULL,
  1406. #ifndef CURL_DISABLE_DICT
  1407. &Curl_handler_dict,
  1408. #else
  1409. NULL,
  1410. #endif
  1411. NULL, NULL, NULL,
  1412. #ifndef CURL_DISABLE_MQTT
  1413. &Curl_handler_mqtt,
  1414. #else
  1415. NULL,
  1416. #endif
  1417. #if defined(USE_SSL) && !defined(CURL_DISABLE_POP3)
  1418. &Curl_handler_pop3s,
  1419. #else
  1420. NULL,
  1421. #endif
  1422. #if defined(USE_SSL) && !defined(CURL_DISABLE_IMAP)
  1423. &Curl_handler_imaps,
  1424. #else
  1425. NULL,
  1426. #endif
  1427. NULL,
  1428. #if defined(USE_WEBSOCKETS) && !defined(CURL_DISABLE_HTTP)
  1429. &Curl_handler_ws,
  1430. #else
  1431. NULL,
  1432. #endif
  1433. NULL,
  1434. #ifdef USE_LIBRTMP
  1435. &Curl_handler_rtmpts,
  1436. #else
  1437. NULL,
  1438. #endif
  1439. #ifndef CURL_DISABLE_LDAP
  1440. &Curl_handler_ldap,
  1441. #else
  1442. NULL,
  1443. #endif
  1444. NULL, NULL,
  1445. #ifndef CURL_DISABLE_FTP
  1446. &Curl_handler_ftp,
  1447. #else
  1448. NULL,
  1449. #endif
  1450. };
  1451. if(len && (len <= 7)) {
  1452. const char *s = scheme;
  1453. size_t l = len;
  1454. const struct Curl_handler *h;
  1455. unsigned int c = 978;
  1456. while(l) {
  1457. c <<= 5;
  1458. c += Curl_raw_tolower(*s);
  1459. s++;
  1460. l--;
  1461. }
  1462. h = protocols[c % 67];
  1463. if(h && strncasecompare(scheme, h->scheme, len) && !h->scheme[len])
  1464. return h;
  1465. }
  1466. return NULL;
  1467. }
  1468. static CURLcode findprotocol(struct Curl_easy *data,
  1469. struct connectdata *conn,
  1470. const char *protostr)
  1471. {
  1472. const struct Curl_handler *p = Curl_get_scheme_handler(protostr);
  1473. if(p && /* Protocol found in table. Check if allowed */
  1474. (data->set.allowed_protocols & p->protocol)) {
  1475. /* it is allowed for "normal" request, now do an extra check if this is
  1476. the result of a redirect */
  1477. if(data->state.this_is_a_follow &&
  1478. !(data->set.redir_protocols & p->protocol))
  1479. /* nope, get out */
  1480. ;
  1481. else {
  1482. /* Perform setup complement if some. */
  1483. conn->handler = conn->given = p;
  1484. /* 'port' and 'remote_port' are set in setup_connection_internals() */
  1485. return CURLE_OK;
  1486. }
  1487. }
  1488. /* The protocol was not found in the table, but we don't have to assign it
  1489. to anything since it is already assigned to a dummy-struct in the
  1490. create_conn() function when the connectdata struct is allocated. */
  1491. failf(data, "Protocol \"%s\" not supported or disabled in " LIBCURL_NAME,
  1492. protostr);
  1493. return CURLE_UNSUPPORTED_PROTOCOL;
  1494. }
  1495. CURLcode Curl_uc_to_curlcode(CURLUcode uc)
  1496. {
  1497. switch(uc) {
  1498. default:
  1499. return CURLE_URL_MALFORMAT;
  1500. case CURLUE_UNSUPPORTED_SCHEME:
  1501. return CURLE_UNSUPPORTED_PROTOCOL;
  1502. case CURLUE_OUT_OF_MEMORY:
  1503. return CURLE_OUT_OF_MEMORY;
  1504. case CURLUE_USER_NOT_ALLOWED:
  1505. return CURLE_LOGIN_DENIED;
  1506. }
  1507. }
  1508. #ifdef ENABLE_IPV6
  1509. /*
  1510. * If the URL was set with an IPv6 numerical address with a zone id part, set
  1511. * the scope_id based on that!
  1512. */
  1513. static void zonefrom_url(CURLU *uh, struct Curl_easy *data,
  1514. struct connectdata *conn)
  1515. {
  1516. char *zoneid;
  1517. CURLUcode uc = curl_url_get(uh, CURLUPART_ZONEID, &zoneid, 0);
  1518. #ifdef CURL_DISABLE_VERBOSE_STRINGS
  1519. (void)data;
  1520. #endif
  1521. if(!uc && zoneid) {
  1522. char *endp;
  1523. unsigned long scope = strtoul(zoneid, &endp, 10);
  1524. if(!*endp && (scope < UINT_MAX))
  1525. /* A plain number, use it directly as a scope id. */
  1526. conn->scope_id = (unsigned int)scope;
  1527. #if defined(HAVE_IF_NAMETOINDEX)
  1528. else {
  1529. #elif defined(_WIN32)
  1530. else if(Curl_if_nametoindex) {
  1531. #endif
  1532. #if defined(HAVE_IF_NAMETOINDEX) || defined(_WIN32)
  1533. /* Zone identifier is not numeric */
  1534. unsigned int scopeidx = 0;
  1535. #if defined(_WIN32)
  1536. scopeidx = Curl_if_nametoindex(zoneid);
  1537. #else
  1538. scopeidx = if_nametoindex(zoneid);
  1539. #endif
  1540. if(!scopeidx) {
  1541. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1542. char buffer[STRERROR_LEN];
  1543. infof(data, "Invalid zoneid: %s; %s", zoneid,
  1544. Curl_strerror(errno, buffer, sizeof(buffer)));
  1545. #endif
  1546. }
  1547. else
  1548. conn->scope_id = scopeidx;
  1549. }
  1550. #endif /* HAVE_IF_NAMETOINDEX || _WIN32 */
  1551. free(zoneid);
  1552. }
  1553. }
  1554. #else
  1555. #define zonefrom_url(a,b,c) Curl_nop_stmt
  1556. #endif
  1557. /*
  1558. * Parse URL and fill in the relevant members of the connection struct.
  1559. */
  1560. static CURLcode parseurlandfillconn(struct Curl_easy *data,
  1561. struct connectdata *conn)
  1562. {
  1563. CURLcode result;
  1564. CURLU *uh;
  1565. CURLUcode uc;
  1566. char *hostname;
  1567. bool use_set_uh = (data->set.uh && !data->state.this_is_a_follow);
  1568. up_free(data); /* cleanup previous leftovers first */
  1569. /* parse the URL */
  1570. if(use_set_uh) {
  1571. uh = data->state.uh = curl_url_dup(data->set.uh);
  1572. }
  1573. else {
  1574. uh = data->state.uh = curl_url();
  1575. }
  1576. if(!uh)
  1577. return CURLE_OUT_OF_MEMORY;
  1578. if(data->set.str[STRING_DEFAULT_PROTOCOL] &&
  1579. !Curl_is_absolute_url(data->state.url, NULL, 0, TRUE)) {
  1580. char *url = aprintf("%s://%s", data->set.str[STRING_DEFAULT_PROTOCOL],
  1581. data->state.url);
  1582. if(!url)
  1583. return CURLE_OUT_OF_MEMORY;
  1584. if(data->state.url_alloc)
  1585. free(data->state.url);
  1586. data->state.url = url;
  1587. data->state.url_alloc = TRUE;
  1588. }
  1589. if(!use_set_uh) {
  1590. char *newurl;
  1591. uc = curl_url_set(uh, CURLUPART_URL, data->state.url,
  1592. CURLU_GUESS_SCHEME |
  1593. CURLU_NON_SUPPORT_SCHEME |
  1594. (data->set.disallow_username_in_url ?
  1595. CURLU_DISALLOW_USER : 0) |
  1596. (data->set.path_as_is ? CURLU_PATH_AS_IS : 0));
  1597. if(uc) {
  1598. failf(data, "URL rejected: %s", curl_url_strerror(uc));
  1599. return Curl_uc_to_curlcode(uc);
  1600. }
  1601. /* after it was parsed, get the generated normalized version */
  1602. uc = curl_url_get(uh, CURLUPART_URL, &newurl, 0);
  1603. if(uc)
  1604. return Curl_uc_to_curlcode(uc);
  1605. if(data->state.url_alloc)
  1606. free(data->state.url);
  1607. data->state.url = newurl;
  1608. data->state.url_alloc = TRUE;
  1609. }
  1610. uc = curl_url_get(uh, CURLUPART_SCHEME, &data->state.up.scheme, 0);
  1611. if(uc)
  1612. return Curl_uc_to_curlcode(uc);
  1613. uc = curl_url_get(uh, CURLUPART_HOST, &data->state.up.hostname, 0);
  1614. if(uc) {
  1615. if(!strcasecompare("file", data->state.up.scheme))
  1616. return CURLE_OUT_OF_MEMORY;
  1617. }
  1618. else if(strlen(data->state.up.hostname) > MAX_URL_LEN) {
  1619. failf(data, "Too long host name (maximum is %d)", MAX_URL_LEN);
  1620. return CURLE_URL_MALFORMAT;
  1621. }
  1622. hostname = data->state.up.hostname;
  1623. if(hostname && hostname[0] == '[') {
  1624. /* This looks like an IPv6 address literal. See if there is an address
  1625. scope. */
  1626. size_t hlen;
  1627. conn->bits.ipv6_ip = TRUE;
  1628. /* cut off the brackets! */
  1629. hostname++;
  1630. hlen = strlen(hostname);
  1631. hostname[hlen - 1] = 0;
  1632. zonefrom_url(uh, data, conn);
  1633. }
  1634. /* make sure the connect struct gets its own copy of the host name */
  1635. conn->host.rawalloc = strdup(hostname ? hostname : "");
  1636. if(!conn->host.rawalloc)
  1637. return CURLE_OUT_OF_MEMORY;
  1638. conn->host.name = conn->host.rawalloc;
  1639. /*************************************************************
  1640. * IDN-convert the hostnames
  1641. *************************************************************/
  1642. result = Curl_idnconvert_hostname(&conn->host);
  1643. if(result)
  1644. return result;
  1645. #ifndef CURL_DISABLE_HSTS
  1646. /* HSTS upgrade */
  1647. if(data->hsts && strcasecompare("http", data->state.up.scheme)) {
  1648. /* This MUST use the IDN decoded name */
  1649. if(Curl_hsts(data->hsts, conn->host.name, TRUE)) {
  1650. char *url;
  1651. Curl_safefree(data->state.up.scheme);
  1652. uc = curl_url_set(uh, CURLUPART_SCHEME, "https", 0);
  1653. if(uc)
  1654. return Curl_uc_to_curlcode(uc);
  1655. if(data->state.url_alloc)
  1656. Curl_safefree(data->state.url);
  1657. /* after update, get the updated version */
  1658. uc = curl_url_get(uh, CURLUPART_URL, &url, 0);
  1659. if(uc)
  1660. return Curl_uc_to_curlcode(uc);
  1661. uc = curl_url_get(uh, CURLUPART_SCHEME, &data->state.up.scheme, 0);
  1662. if(uc) {
  1663. free(url);
  1664. return Curl_uc_to_curlcode(uc);
  1665. }
  1666. data->state.url = url;
  1667. data->state.url_alloc = TRUE;
  1668. infof(data, "Switched from HTTP to HTTPS due to HSTS => %s",
  1669. data->state.url);
  1670. }
  1671. }
  1672. #endif
  1673. result = findprotocol(data, conn, data->state.up.scheme);
  1674. if(result)
  1675. return result;
  1676. /*
  1677. * User name and password set with their own options override the
  1678. * credentials possibly set in the URL.
  1679. */
  1680. if(!data->set.str[STRING_PASSWORD]) {
  1681. uc = curl_url_get(uh, CURLUPART_PASSWORD, &data->state.up.password, 0);
  1682. if(!uc) {
  1683. char *decoded;
  1684. result = Curl_urldecode(data->state.up.password, 0, &decoded, NULL,
  1685. conn->handler->flags&PROTOPT_USERPWDCTRL ?
  1686. REJECT_ZERO : REJECT_CTRL);
  1687. if(result)
  1688. return result;
  1689. conn->passwd = decoded;
  1690. result = Curl_setstropt(&data->state.aptr.passwd, decoded);
  1691. if(result)
  1692. return result;
  1693. }
  1694. else if(uc != CURLUE_NO_PASSWORD)
  1695. return Curl_uc_to_curlcode(uc);
  1696. }
  1697. if(!data->set.str[STRING_USERNAME]) {
  1698. /* we don't use the URL API's URL decoder option here since it rejects
  1699. control codes and we want to allow them for some schemes in the user
  1700. and password fields */
  1701. uc = curl_url_get(uh, CURLUPART_USER, &data->state.up.user, 0);
  1702. if(!uc) {
  1703. char *decoded;
  1704. result = Curl_urldecode(data->state.up.user, 0, &decoded, NULL,
  1705. conn->handler->flags&PROTOPT_USERPWDCTRL ?
  1706. REJECT_ZERO : REJECT_CTRL);
  1707. if(result)
  1708. return result;
  1709. conn->user = decoded;
  1710. result = Curl_setstropt(&data->state.aptr.user, decoded);
  1711. }
  1712. else if(uc != CURLUE_NO_USER)
  1713. return Curl_uc_to_curlcode(uc);
  1714. else if(data->state.aptr.passwd) {
  1715. /* no user was set but a password, set a blank user */
  1716. result = Curl_setstropt(&data->state.aptr.user, "");
  1717. }
  1718. if(result)
  1719. return result;
  1720. }
  1721. uc = curl_url_get(uh, CURLUPART_OPTIONS, &data->state.up.options,
  1722. CURLU_URLDECODE);
  1723. if(!uc) {
  1724. conn->options = strdup(data->state.up.options);
  1725. if(!conn->options)
  1726. return CURLE_OUT_OF_MEMORY;
  1727. }
  1728. else if(uc != CURLUE_NO_OPTIONS)
  1729. return Curl_uc_to_curlcode(uc);
  1730. uc = curl_url_get(uh, CURLUPART_PATH, &data->state.up.path,
  1731. CURLU_URLENCODE);
  1732. if(uc)
  1733. return Curl_uc_to_curlcode(uc);
  1734. uc = curl_url_get(uh, CURLUPART_PORT, &data->state.up.port,
  1735. CURLU_DEFAULT_PORT);
  1736. if(uc) {
  1737. if(!strcasecompare("file", data->state.up.scheme))
  1738. return CURLE_OUT_OF_MEMORY;
  1739. }
  1740. else {
  1741. unsigned long port = strtoul(data->state.up.port, NULL, 10);
  1742. conn->port = conn->remote_port =
  1743. (data->set.use_port && data->state.allow_port) ?
  1744. data->set.use_port : curlx_ultous(port);
  1745. }
  1746. (void)curl_url_get(uh, CURLUPART_QUERY, &data->state.up.query, 0);
  1747. #ifdef ENABLE_IPV6
  1748. if(data->set.scope_id)
  1749. /* Override any scope that was set above. */
  1750. conn->scope_id = data->set.scope_id;
  1751. #endif
  1752. return CURLE_OK;
  1753. }
  1754. /*
  1755. * If we're doing a resumed transfer, we need to setup our stuff
  1756. * properly.
  1757. */
  1758. static CURLcode setup_range(struct Curl_easy *data)
  1759. {
  1760. struct UrlState *s = &data->state;
  1761. s->resume_from = data->set.set_resume_from;
  1762. if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
  1763. if(s->rangestringalloc)
  1764. free(s->range);
  1765. if(s->resume_from)
  1766. s->range = aprintf("%" CURL_FORMAT_CURL_OFF_T "-", s->resume_from);
  1767. else
  1768. s->range = strdup(data->set.str[STRING_SET_RANGE]);
  1769. s->rangestringalloc = (s->range) ? TRUE : FALSE;
  1770. if(!s->range)
  1771. return CURLE_OUT_OF_MEMORY;
  1772. /* tell ourselves to fetch this range */
  1773. s->use_range = TRUE; /* enable range download */
  1774. }
  1775. else
  1776. s->use_range = FALSE; /* disable range download */
  1777. return CURLE_OK;
  1778. }
  1779. /*
  1780. * setup_connection_internals() -
  1781. *
  1782. * Setup connection internals specific to the requested protocol in the
  1783. * Curl_easy. This is inited and setup before the connection is made but
  1784. * is about the particular protocol that is to be used.
  1785. *
  1786. * This MUST get called after proxy magic has been figured out.
  1787. */
  1788. static CURLcode setup_connection_internals(struct Curl_easy *data,
  1789. struct connectdata *conn)
  1790. {
  1791. const struct Curl_handler *p;
  1792. CURLcode result;
  1793. /* Perform setup complement if some. */
  1794. p = conn->handler;
  1795. if(p->setup_connection) {
  1796. result = (*p->setup_connection)(data, conn);
  1797. if(result)
  1798. return result;
  1799. p = conn->handler; /* May have changed. */
  1800. }
  1801. if(conn->port < 0)
  1802. /* we check for -1 here since if proxy was detected already, this
  1803. was very likely already set to the proxy port */
  1804. conn->port = p->defport;
  1805. return CURLE_OK;
  1806. }
  1807. /*
  1808. * Curl_free_request_state() should free temp data that was allocated in the
  1809. * Curl_easy for this single request.
  1810. */
  1811. void Curl_free_request_state(struct Curl_easy *data)
  1812. {
  1813. Curl_safefree(data->req.p.http);
  1814. Curl_safefree(data->req.newurl);
  1815. #ifndef CURL_DISABLE_DOH
  1816. if(data->req.doh) {
  1817. Curl_close(&data->req.doh->probe[0].easy);
  1818. Curl_close(&data->req.doh->probe[1].easy);
  1819. }
  1820. #endif
  1821. Curl_client_cleanup(data);
  1822. }
  1823. #ifndef CURL_DISABLE_PROXY
  1824. #ifndef CURL_DISABLE_HTTP
  1825. /****************************************************************
  1826. * Detect what (if any) proxy to use. Remember that this selects a host
  1827. * name and is not limited to HTTP proxies only.
  1828. * The returned pointer must be freed by the caller (unless NULL)
  1829. ****************************************************************/
  1830. static char *detect_proxy(struct Curl_easy *data,
  1831. struct connectdata *conn)
  1832. {
  1833. char *proxy = NULL;
  1834. /* If proxy was not specified, we check for default proxy environment
  1835. * variables, to enable i.e Lynx compliance:
  1836. *
  1837. * http_proxy=http://some.server.dom:port/
  1838. * https_proxy=http://some.server.dom:port/
  1839. * ftp_proxy=http://some.server.dom:port/
  1840. * no_proxy=domain1.dom,host.domain2.dom
  1841. * (a comma-separated list of hosts which should
  1842. * not be proxied, or an asterisk to override
  1843. * all proxy variables)
  1844. * all_proxy=http://some.server.dom:port/
  1845. * (seems to exist for the CERN www lib. Probably
  1846. * the first to check for.)
  1847. *
  1848. * For compatibility, the all-uppercase versions of these variables are
  1849. * checked if the lowercase versions don't exist.
  1850. */
  1851. char proxy_env[128];
  1852. const char *protop = conn->handler->scheme;
  1853. char *envp = proxy_env;
  1854. #ifdef CURL_DISABLE_VERBOSE_STRINGS
  1855. (void)data;
  1856. #endif
  1857. /* Now, build <protocol>_proxy and check for such a one to use */
  1858. while(*protop)
  1859. *envp++ = Curl_raw_tolower(*protop++);
  1860. /* append _proxy */
  1861. strcpy(envp, "_proxy");
  1862. /* read the protocol proxy: */
  1863. proxy = curl_getenv(proxy_env);
  1864. /*
  1865. * We don't try the uppercase version of HTTP_PROXY because of
  1866. * security reasons:
  1867. *
  1868. * When curl is used in a webserver application
  1869. * environment (cgi or php), this environment variable can
  1870. * be controlled by the web server user by setting the
  1871. * http header 'Proxy:' to some value.
  1872. *
  1873. * This can cause 'internal' http/ftp requests to be
  1874. * arbitrarily redirected by any external attacker.
  1875. */
  1876. if(!proxy && !strcasecompare("http_proxy", proxy_env)) {
  1877. /* There was no lowercase variable, try the uppercase version: */
  1878. Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
  1879. proxy = curl_getenv(proxy_env);
  1880. }
  1881. envp = proxy_env;
  1882. if(!proxy) {
  1883. #ifdef USE_WEBSOCKETS
  1884. /* websocket proxy fallbacks */
  1885. if(strcasecompare("ws_proxy", proxy_env)) {
  1886. proxy = curl_getenv("http_proxy");
  1887. }
  1888. else if(strcasecompare("wss_proxy", proxy_env)) {
  1889. proxy = curl_getenv("https_proxy");
  1890. if(!proxy)
  1891. proxy = curl_getenv("HTTPS_PROXY");
  1892. }
  1893. if(!proxy) {
  1894. #endif
  1895. envp = (char *)"all_proxy";
  1896. proxy = curl_getenv(envp); /* default proxy to use */
  1897. if(!proxy) {
  1898. envp = (char *)"ALL_PROXY";
  1899. proxy = curl_getenv(envp);
  1900. }
  1901. #ifdef USE_WEBSOCKETS
  1902. }
  1903. #endif
  1904. }
  1905. if(proxy)
  1906. infof(data, "Uses proxy env variable %s == '%s'", envp, proxy);
  1907. return proxy;
  1908. }
  1909. #endif /* CURL_DISABLE_HTTP */
  1910. /*
  1911. * If this is supposed to use a proxy, we need to figure out the proxy
  1912. * host name, so that we can reuse an existing connection
  1913. * that may exist registered to the same proxy host.
  1914. */
  1915. static CURLcode parse_proxy(struct Curl_easy *data,
  1916. struct connectdata *conn, char *proxy,
  1917. curl_proxytype proxytype)
  1918. {
  1919. char *portptr = NULL;
  1920. int port = -1;
  1921. char *proxyuser = NULL;
  1922. char *proxypasswd = NULL;
  1923. char *host = NULL;
  1924. bool sockstype;
  1925. CURLUcode uc;
  1926. struct proxy_info *proxyinfo;
  1927. CURLU *uhp = curl_url();
  1928. CURLcode result = CURLE_OK;
  1929. char *scheme = NULL;
  1930. #ifdef USE_UNIX_SOCKETS
  1931. char *path = NULL;
  1932. bool is_unix_proxy = FALSE;
  1933. #endif
  1934. if(!uhp) {
  1935. result = CURLE_OUT_OF_MEMORY;
  1936. goto error;
  1937. }
  1938. /* When parsing the proxy, allowing non-supported schemes since we have
  1939. these made up ones for proxies. Guess scheme for URLs without it. */
  1940. uc = curl_url_set(uhp, CURLUPART_URL, proxy,
  1941. CURLU_NON_SUPPORT_SCHEME|CURLU_GUESS_SCHEME);
  1942. if(!uc) {
  1943. /* parsed okay as a URL */
  1944. uc = curl_url_get(uhp, CURLUPART_SCHEME, &scheme, 0);
  1945. if(uc) {
  1946. result = CURLE_OUT_OF_MEMORY;
  1947. goto error;
  1948. }
  1949. if(strcasecompare("https", scheme)) {
  1950. if(proxytype != CURLPROXY_HTTPS2)
  1951. proxytype = CURLPROXY_HTTPS;
  1952. else
  1953. proxytype = CURLPROXY_HTTPS2;
  1954. }
  1955. else if(strcasecompare("socks5h", scheme))
  1956. proxytype = CURLPROXY_SOCKS5_HOSTNAME;
  1957. else if(strcasecompare("socks5", scheme))
  1958. proxytype = CURLPROXY_SOCKS5;
  1959. else if(strcasecompare("socks4a", scheme))
  1960. proxytype = CURLPROXY_SOCKS4A;
  1961. else if(strcasecompare("socks4", scheme) ||
  1962. strcasecompare("socks", scheme))
  1963. proxytype = CURLPROXY_SOCKS4;
  1964. else if(strcasecompare("http", scheme))
  1965. ; /* leave it as HTTP or HTTP/1.0 */
  1966. else {
  1967. /* Any other xxx:// reject! */
  1968. failf(data, "Unsupported proxy scheme for \'%s\'", proxy);
  1969. result = CURLE_COULDNT_CONNECT;
  1970. goto error;
  1971. }
  1972. }
  1973. else {
  1974. failf(data, "Unsupported proxy syntax in \'%s\': %s", proxy,
  1975. curl_url_strerror(uc));
  1976. result = CURLE_COULDNT_RESOLVE_PROXY;
  1977. goto error;
  1978. }
  1979. #ifdef USE_SSL
  1980. if(!Curl_ssl_supports(data, SSLSUPP_HTTPS_PROXY))
  1981. #endif
  1982. if(IS_HTTPS_PROXY(proxytype)) {
  1983. failf(data, "Unsupported proxy \'%s\', libcurl is built without the "
  1984. "HTTPS-proxy support.", proxy);
  1985. result = CURLE_NOT_BUILT_IN;
  1986. goto error;
  1987. }
  1988. sockstype =
  1989. proxytype == CURLPROXY_SOCKS5_HOSTNAME ||
  1990. proxytype == CURLPROXY_SOCKS5 ||
  1991. proxytype == CURLPROXY_SOCKS4A ||
  1992. proxytype == CURLPROXY_SOCKS4;
  1993. proxyinfo = sockstype ? &conn->socks_proxy : &conn->http_proxy;
  1994. proxyinfo->proxytype = (unsigned char)proxytype;
  1995. /* Is there a username and password given in this proxy url? */
  1996. uc = curl_url_get(uhp, CURLUPART_USER, &proxyuser, CURLU_URLDECODE);
  1997. if(uc && (uc != CURLUE_NO_USER))
  1998. goto error;
  1999. uc = curl_url_get(uhp, CURLUPART_PASSWORD, &proxypasswd, CURLU_URLDECODE);
  2000. if(uc && (uc != CURLUE_NO_PASSWORD))
  2001. goto error;
  2002. if(proxyuser || proxypasswd) {
  2003. Curl_safefree(proxyinfo->user);
  2004. proxyinfo->user = proxyuser;
  2005. result = Curl_setstropt(&data->state.aptr.proxyuser, proxyuser);
  2006. proxyuser = NULL;
  2007. if(result)
  2008. goto error;
  2009. Curl_safefree(proxyinfo->passwd);
  2010. if(!proxypasswd) {
  2011. proxypasswd = strdup("");
  2012. if(!proxypasswd) {
  2013. result = CURLE_OUT_OF_MEMORY;
  2014. goto error;
  2015. }
  2016. }
  2017. proxyinfo->passwd = proxypasswd;
  2018. result = Curl_setstropt(&data->state.aptr.proxypasswd, proxypasswd);
  2019. proxypasswd = NULL;
  2020. if(result)
  2021. goto error;
  2022. conn->bits.proxy_user_passwd = TRUE; /* enable it */
  2023. }
  2024. (void)curl_url_get(uhp, CURLUPART_PORT, &portptr, 0);
  2025. if(portptr) {
  2026. port = (int)strtol(portptr, NULL, 10);
  2027. free(portptr);
  2028. }
  2029. else {
  2030. if(data->set.proxyport)
  2031. /* None given in the proxy string, then get the default one if it is
  2032. given */
  2033. port = (int)data->set.proxyport;
  2034. else {
  2035. if(IS_HTTPS_PROXY(proxytype))
  2036. port = CURL_DEFAULT_HTTPS_PROXY_PORT;
  2037. else
  2038. port = CURL_DEFAULT_PROXY_PORT;
  2039. }
  2040. }
  2041. if(port >= 0) {
  2042. proxyinfo->port = port;
  2043. if(conn->port < 0 || sockstype || !conn->socks_proxy.host.rawalloc)
  2044. conn->port = port;
  2045. }
  2046. /* now, clone the proxy host name */
  2047. uc = curl_url_get(uhp, CURLUPART_HOST, &host, CURLU_URLDECODE);
  2048. if(uc) {
  2049. result = CURLE_OUT_OF_MEMORY;
  2050. goto error;
  2051. }
  2052. #ifdef USE_UNIX_SOCKETS
  2053. if(sockstype && strcasecompare(UNIX_SOCKET_PREFIX, host)) {
  2054. uc = curl_url_get(uhp, CURLUPART_PATH, &path, CURLU_URLDECODE);
  2055. if(uc) {
  2056. result = CURLE_OUT_OF_MEMORY;
  2057. goto error;
  2058. }
  2059. /* path will be "/", if no path was found */
  2060. if(strcmp("/", path)) {
  2061. is_unix_proxy = TRUE;
  2062. free(host);
  2063. host = aprintf(UNIX_SOCKET_PREFIX"%s", path);
  2064. if(!host) {
  2065. result = CURLE_OUT_OF_MEMORY;
  2066. goto error;
  2067. }
  2068. Curl_safefree(proxyinfo->host.rawalloc);
  2069. proxyinfo->host.rawalloc = host;
  2070. proxyinfo->host.name = host;
  2071. host = NULL;
  2072. }
  2073. }
  2074. if(!is_unix_proxy) {
  2075. #endif
  2076. Curl_safefree(proxyinfo->host.rawalloc);
  2077. proxyinfo->host.rawalloc = host;
  2078. if(host[0] == '[') {
  2079. /* this is a numerical IPv6, strip off the brackets */
  2080. size_t len = strlen(host);
  2081. host[len-1] = 0; /* clear the trailing bracket */
  2082. host++;
  2083. zonefrom_url(uhp, data, conn);
  2084. }
  2085. proxyinfo->host.name = host;
  2086. host = NULL;
  2087. #ifdef USE_UNIX_SOCKETS
  2088. }
  2089. #endif
  2090. error:
  2091. free(proxyuser);
  2092. free(proxypasswd);
  2093. free(host);
  2094. free(scheme);
  2095. #ifdef USE_UNIX_SOCKETS
  2096. free(path);
  2097. #endif
  2098. curl_url_cleanup(uhp);
  2099. return result;
  2100. }
  2101. /*
  2102. * Extract the user and password from the authentication string
  2103. */
  2104. static CURLcode parse_proxy_auth(struct Curl_easy *data,
  2105. struct connectdata *conn)
  2106. {
  2107. const char *proxyuser = data->state.aptr.proxyuser ?
  2108. data->state.aptr.proxyuser : "";
  2109. const char *proxypasswd = data->state.aptr.proxypasswd ?
  2110. data->state.aptr.proxypasswd : "";
  2111. CURLcode result = Curl_urldecode(proxyuser, 0, &conn->http_proxy.user, NULL,
  2112. REJECT_ZERO);
  2113. if(!result)
  2114. result = Curl_setstropt(&data->state.aptr.proxyuser,
  2115. conn->http_proxy.user);
  2116. if(!result)
  2117. result = Curl_urldecode(proxypasswd, 0, &conn->http_proxy.passwd,
  2118. NULL, REJECT_ZERO);
  2119. if(!result)
  2120. result = Curl_setstropt(&data->state.aptr.proxypasswd,
  2121. conn->http_proxy.passwd);
  2122. return result;
  2123. }
  2124. /* create_conn helper to parse and init proxy values. to be called after unix
  2125. socket init but before any proxy vars are evaluated. */
  2126. static CURLcode create_conn_helper_init_proxy(struct Curl_easy *data,
  2127. struct connectdata *conn)
  2128. {
  2129. char *proxy = NULL;
  2130. char *socksproxy = NULL;
  2131. char *no_proxy = NULL;
  2132. CURLcode result = CURLE_OK;
  2133. bool spacesep = FALSE;
  2134. /*************************************************************
  2135. * Extract the user and password from the authentication string
  2136. *************************************************************/
  2137. if(conn->bits.proxy_user_passwd) {
  2138. result = parse_proxy_auth(data, conn);
  2139. if(result)
  2140. goto out;
  2141. }
  2142. /*************************************************************
  2143. * Detect what (if any) proxy to use
  2144. *************************************************************/
  2145. if(data->set.str[STRING_PROXY]) {
  2146. proxy = strdup(data->set.str[STRING_PROXY]);
  2147. /* if global proxy is set, this is it */
  2148. if(!proxy) {
  2149. failf(data, "memory shortage");
  2150. result = CURLE_OUT_OF_MEMORY;
  2151. goto out;
  2152. }
  2153. }
  2154. if(data->set.str[STRING_PRE_PROXY]) {
  2155. socksproxy = strdup(data->set.str[STRING_PRE_PROXY]);
  2156. /* if global socks proxy is set, this is it */
  2157. if(!socksproxy) {
  2158. failf(data, "memory shortage");
  2159. result = CURLE_OUT_OF_MEMORY;
  2160. goto out;
  2161. }
  2162. }
  2163. if(!data->set.str[STRING_NOPROXY]) {
  2164. const char *p = "no_proxy";
  2165. no_proxy = curl_getenv(p);
  2166. if(!no_proxy) {
  2167. p = "NO_PROXY";
  2168. no_proxy = curl_getenv(p);
  2169. }
  2170. if(no_proxy) {
  2171. infof(data, "Uses proxy env variable %s == '%s'", p, no_proxy);
  2172. }
  2173. }
  2174. if(Curl_check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY] ?
  2175. data->set.str[STRING_NOPROXY] : no_proxy,
  2176. &spacesep)) {
  2177. Curl_safefree(proxy);
  2178. Curl_safefree(socksproxy);
  2179. }
  2180. #ifndef CURL_DISABLE_HTTP
  2181. else if(!proxy && !socksproxy)
  2182. /* if the host is not in the noproxy list, detect proxy. */
  2183. proxy = detect_proxy(data, conn);
  2184. #endif /* CURL_DISABLE_HTTP */
  2185. if(spacesep)
  2186. infof(data, "space-separated NOPROXY patterns are deprecated");
  2187. Curl_safefree(no_proxy);
  2188. #ifdef USE_UNIX_SOCKETS
  2189. /* For the time being do not mix proxy and unix domain sockets. See #1274 */
  2190. if(proxy && conn->unix_domain_socket) {
  2191. free(proxy);
  2192. proxy = NULL;
  2193. }
  2194. #endif
  2195. if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
  2196. free(proxy); /* Don't bother with an empty proxy string or if the
  2197. protocol doesn't work with network */
  2198. proxy = NULL;
  2199. }
  2200. if(socksproxy && (!*socksproxy ||
  2201. (conn->handler->flags & PROTOPT_NONETWORK))) {
  2202. free(socksproxy); /* Don't bother with an empty socks proxy string or if
  2203. the protocol doesn't work with network */
  2204. socksproxy = NULL;
  2205. }
  2206. /***********************************************************************
  2207. * If this is supposed to use a proxy, we need to figure out the proxy host
  2208. * name, proxy type and port number, so that we can reuse an existing
  2209. * connection that may exist registered to the same proxy host.
  2210. ***********************************************************************/
  2211. if(proxy || socksproxy) {
  2212. curl_proxytype ptype = (curl_proxytype)conn->http_proxy.proxytype;
  2213. if(proxy) {
  2214. result = parse_proxy(data, conn, proxy, ptype);
  2215. Curl_safefree(proxy); /* parse_proxy copies the proxy string */
  2216. if(result)
  2217. goto out;
  2218. }
  2219. if(socksproxy) {
  2220. result = parse_proxy(data, conn, socksproxy, ptype);
  2221. /* parse_proxy copies the socks proxy string */
  2222. Curl_safefree(socksproxy);
  2223. if(result)
  2224. goto out;
  2225. }
  2226. if(conn->http_proxy.host.rawalloc) {
  2227. #ifdef CURL_DISABLE_HTTP
  2228. /* asking for an HTTP proxy is a bit funny when HTTP is disabled... */
  2229. result = CURLE_UNSUPPORTED_PROTOCOL;
  2230. goto out;
  2231. #else
  2232. /* force this connection's protocol to become HTTP if compatible */
  2233. if(!(conn->handler->protocol & PROTO_FAMILY_HTTP)) {
  2234. if((conn->handler->flags & PROTOPT_PROXY_AS_HTTP) &&
  2235. !conn->bits.tunnel_proxy)
  2236. conn->handler = &Curl_handler_http;
  2237. else
  2238. /* if not converting to HTTP over the proxy, enforce tunneling */
  2239. conn->bits.tunnel_proxy = TRUE;
  2240. }
  2241. conn->bits.httpproxy = TRUE;
  2242. #endif
  2243. }
  2244. else {
  2245. conn->bits.httpproxy = FALSE; /* not an HTTP proxy */
  2246. conn->bits.tunnel_proxy = FALSE; /* no tunneling if not HTTP */
  2247. }
  2248. if(conn->socks_proxy.host.rawalloc) {
  2249. if(!conn->http_proxy.host.rawalloc) {
  2250. /* once a socks proxy */
  2251. if(!conn->socks_proxy.user) {
  2252. conn->socks_proxy.user = conn->http_proxy.user;
  2253. conn->http_proxy.user = NULL;
  2254. Curl_safefree(conn->socks_proxy.passwd);
  2255. conn->socks_proxy.passwd = conn->http_proxy.passwd;
  2256. conn->http_proxy.passwd = NULL;
  2257. }
  2258. }
  2259. conn->bits.socksproxy = TRUE;
  2260. }
  2261. else
  2262. conn->bits.socksproxy = FALSE; /* not a socks proxy */
  2263. }
  2264. else {
  2265. conn->bits.socksproxy = FALSE;
  2266. conn->bits.httpproxy = FALSE;
  2267. }
  2268. conn->bits.proxy = conn->bits.httpproxy || conn->bits.socksproxy;
  2269. if(!conn->bits.proxy) {
  2270. /* we aren't using the proxy after all... */
  2271. conn->bits.proxy = FALSE;
  2272. conn->bits.httpproxy = FALSE;
  2273. conn->bits.socksproxy = FALSE;
  2274. conn->bits.proxy_user_passwd = FALSE;
  2275. conn->bits.tunnel_proxy = FALSE;
  2276. /* CURLPROXY_HTTPS does not have its own flag in conn->bits, yet we need
  2277. to signal that CURLPROXY_HTTPS is not used for this connection */
  2278. conn->http_proxy.proxytype = CURLPROXY_HTTP;
  2279. }
  2280. out:
  2281. free(socksproxy);
  2282. free(proxy);
  2283. return result;
  2284. }
  2285. #endif /* CURL_DISABLE_PROXY */
  2286. /*
  2287. * Curl_parse_login_details()
  2288. *
  2289. * This is used to parse a login string for user name, password and options in
  2290. * the following formats:
  2291. *
  2292. * user
  2293. * user:password
  2294. * user:password;options
  2295. * user;options
  2296. * user;options:password
  2297. * :password
  2298. * :password;options
  2299. * ;options
  2300. * ;options:password
  2301. *
  2302. * Parameters:
  2303. *
  2304. * login [in] - The login string.
  2305. * len [in] - The length of the login string.
  2306. * userp [in/out] - The address where a pointer to newly allocated memory
  2307. * holding the user will be stored upon completion.
  2308. * passwdp [in/out] - The address where a pointer to newly allocated memory
  2309. * holding the password will be stored upon completion.
  2310. * optionsp [in/out] - The address where a pointer to newly allocated memory
  2311. * holding the options will be stored upon completion.
  2312. *
  2313. * Returns CURLE_OK on success.
  2314. */
  2315. CURLcode Curl_parse_login_details(const char *login, const size_t len,
  2316. char **userp, char **passwdp,
  2317. char **optionsp)
  2318. {
  2319. CURLcode result = CURLE_OK;
  2320. char *ubuf = NULL;
  2321. char *pbuf = NULL;
  2322. char *obuf = NULL;
  2323. const char *psep = NULL;
  2324. const char *osep = NULL;
  2325. size_t ulen;
  2326. size_t plen;
  2327. size_t olen;
  2328. /* Attempt to find the password separator */
  2329. if(passwdp)
  2330. psep = memchr(login, ':', len);
  2331. /* Attempt to find the options separator */
  2332. if(optionsp)
  2333. osep = memchr(login, ';', len);
  2334. /* Calculate the portion lengths */
  2335. ulen = (psep ?
  2336. (size_t)(osep && psep > osep ? osep - login : psep - login) :
  2337. (osep ? (size_t)(osep - login) : len));
  2338. plen = (psep ?
  2339. (osep && osep > psep ? (size_t)(osep - psep) :
  2340. (size_t)(login + len - psep)) - 1 : 0);
  2341. olen = (osep ?
  2342. (psep && psep > osep ? (size_t)(psep - osep) :
  2343. (size_t)(login + len - osep)) - 1 : 0);
  2344. /* Allocate the user portion buffer, which can be zero length */
  2345. if(userp) {
  2346. ubuf = malloc(ulen + 1);
  2347. if(!ubuf)
  2348. result = CURLE_OUT_OF_MEMORY;
  2349. }
  2350. /* Allocate the password portion buffer */
  2351. if(!result && passwdp && psep) {
  2352. pbuf = malloc(plen + 1);
  2353. if(!pbuf) {
  2354. free(ubuf);
  2355. result = CURLE_OUT_OF_MEMORY;
  2356. }
  2357. }
  2358. /* Allocate the options portion buffer */
  2359. if(!result && optionsp && olen) {
  2360. obuf = malloc(olen + 1);
  2361. if(!obuf) {
  2362. free(pbuf);
  2363. free(ubuf);
  2364. result = CURLE_OUT_OF_MEMORY;
  2365. }
  2366. }
  2367. if(!result) {
  2368. /* Store the user portion if necessary */
  2369. if(ubuf) {
  2370. memcpy(ubuf, login, ulen);
  2371. ubuf[ulen] = '\0';
  2372. Curl_safefree(*userp);
  2373. *userp = ubuf;
  2374. }
  2375. /* Store the password portion if necessary */
  2376. if(pbuf) {
  2377. memcpy(pbuf, psep + 1, plen);
  2378. pbuf[plen] = '\0';
  2379. Curl_safefree(*passwdp);
  2380. *passwdp = pbuf;
  2381. }
  2382. /* Store the options portion if necessary */
  2383. if(obuf) {
  2384. memcpy(obuf, osep + 1, olen);
  2385. obuf[olen] = '\0';
  2386. Curl_safefree(*optionsp);
  2387. *optionsp = obuf;
  2388. }
  2389. }
  2390. return result;
  2391. }
  2392. /*************************************************************
  2393. * Figure out the remote port number and fix it in the URL
  2394. *
  2395. * No matter if we use a proxy or not, we have to figure out the remote
  2396. * port number of various reasons.
  2397. *
  2398. * The port number embedded in the URL is replaced, if necessary.
  2399. *************************************************************/
  2400. static CURLcode parse_remote_port(struct Curl_easy *data,
  2401. struct connectdata *conn)
  2402. {
  2403. if(data->set.use_port && data->state.allow_port) {
  2404. /* if set, we use this instead of the port possibly given in the URL */
  2405. char portbuf[16];
  2406. CURLUcode uc;
  2407. conn->remote_port = data->set.use_port;
  2408. msnprintf(portbuf, sizeof(portbuf), "%d", conn->remote_port);
  2409. uc = curl_url_set(data->state.uh, CURLUPART_PORT, portbuf, 0);
  2410. if(uc)
  2411. return CURLE_OUT_OF_MEMORY;
  2412. }
  2413. return CURLE_OK;
  2414. }
  2415. /*
  2416. * Override the login details from the URL with that in the CURLOPT_USERPWD
  2417. * option or a .netrc file, if applicable.
  2418. */
  2419. static CURLcode override_login(struct Curl_easy *data,
  2420. struct connectdata *conn)
  2421. {
  2422. CURLUcode uc;
  2423. char **userp = &conn->user;
  2424. char **passwdp = &conn->passwd;
  2425. char **optionsp = &conn->options;
  2426. if(data->set.str[STRING_OPTIONS]) {
  2427. free(*optionsp);
  2428. *optionsp = strdup(data->set.str[STRING_OPTIONS]);
  2429. if(!*optionsp)
  2430. return CURLE_OUT_OF_MEMORY;
  2431. }
  2432. #ifndef CURL_DISABLE_NETRC
  2433. if(data->set.use_netrc == CURL_NETRC_REQUIRED) {
  2434. Curl_safefree(*userp);
  2435. Curl_safefree(*passwdp);
  2436. }
  2437. conn->bits.netrc = FALSE;
  2438. if(data->set.use_netrc && !data->set.str[STRING_USERNAME]) {
  2439. int ret;
  2440. bool url_provided = FALSE;
  2441. if(data->state.aptr.user) {
  2442. /* there was a user name in the URL. Use the URL decoded version */
  2443. userp = &data->state.aptr.user;
  2444. url_provided = TRUE;
  2445. }
  2446. ret = Curl_parsenetrc(conn->host.name,
  2447. userp, passwdp,
  2448. data->set.str[STRING_NETRC_FILE]);
  2449. if(ret > 0) {
  2450. infof(data, "Couldn't find host %s in the %s file; using defaults",
  2451. conn->host.name,
  2452. (data->set.str[STRING_NETRC_FILE] ?
  2453. data->set.str[STRING_NETRC_FILE] : ".netrc"));
  2454. }
  2455. else if(ret < 0) {
  2456. failf(data, ".netrc parser error");
  2457. return CURLE_READ_ERROR;
  2458. }
  2459. else {
  2460. /* set bits.netrc TRUE to remember that we got the name from a .netrc
  2461. file, so that it is safe to use even if we followed a Location: to a
  2462. different host or similar. */
  2463. conn->bits.netrc = TRUE;
  2464. }
  2465. if(url_provided) {
  2466. Curl_safefree(conn->user);
  2467. conn->user = strdup(*userp);
  2468. if(!conn->user)
  2469. return CURLE_OUT_OF_MEMORY;
  2470. }
  2471. /* no user was set but a password, set a blank user */
  2472. if(!*userp && *passwdp) {
  2473. *userp = strdup("");
  2474. if(!*userp)
  2475. return CURLE_OUT_OF_MEMORY;
  2476. }
  2477. }
  2478. #endif
  2479. /* for updated strings, we update them in the URL */
  2480. if(*userp) {
  2481. CURLcode result;
  2482. if(data->state.aptr.user != *userp) {
  2483. /* nothing to do then */
  2484. result = Curl_setstropt(&data->state.aptr.user, *userp);
  2485. if(result)
  2486. return result;
  2487. }
  2488. }
  2489. if(data->state.aptr.user) {
  2490. uc = curl_url_set(data->state.uh, CURLUPART_USER, data->state.aptr.user,
  2491. CURLU_URLENCODE);
  2492. if(uc)
  2493. return Curl_uc_to_curlcode(uc);
  2494. if(!*userp) {
  2495. *userp = strdup(data->state.aptr.user);
  2496. if(!*userp)
  2497. return CURLE_OUT_OF_MEMORY;
  2498. }
  2499. }
  2500. if(*passwdp) {
  2501. CURLcode result = Curl_setstropt(&data->state.aptr.passwd, *passwdp);
  2502. if(result)
  2503. return result;
  2504. }
  2505. if(data->state.aptr.passwd) {
  2506. uc = curl_url_set(data->state.uh, CURLUPART_PASSWORD,
  2507. data->state.aptr.passwd, CURLU_URLENCODE);
  2508. if(uc)
  2509. return Curl_uc_to_curlcode(uc);
  2510. if(!*passwdp) {
  2511. *passwdp = strdup(data->state.aptr.passwd);
  2512. if(!*passwdp)
  2513. return CURLE_OUT_OF_MEMORY;
  2514. }
  2515. }
  2516. return CURLE_OK;
  2517. }
  2518. /*
  2519. * Set the login details so they're available in the connection
  2520. */
  2521. static CURLcode set_login(struct Curl_easy *data,
  2522. struct connectdata *conn)
  2523. {
  2524. CURLcode result = CURLE_OK;
  2525. const char *setuser = CURL_DEFAULT_USER;
  2526. const char *setpasswd = CURL_DEFAULT_PASSWORD;
  2527. /* If our protocol needs a password and we have none, use the defaults */
  2528. if((conn->handler->flags & PROTOPT_NEEDSPWD) && !data->state.aptr.user)
  2529. ;
  2530. else {
  2531. setuser = "";
  2532. setpasswd = "";
  2533. }
  2534. /* Store the default user */
  2535. if(!conn->user) {
  2536. conn->user = strdup(setuser);
  2537. if(!conn->user)
  2538. return CURLE_OUT_OF_MEMORY;
  2539. }
  2540. /* Store the default password */
  2541. if(!conn->passwd) {
  2542. conn->passwd = strdup(setpasswd);
  2543. if(!conn->passwd)
  2544. result = CURLE_OUT_OF_MEMORY;
  2545. }
  2546. return result;
  2547. }
  2548. /*
  2549. * Parses a "host:port" string to connect to.
  2550. * The hostname and the port may be empty; in this case, NULL is returned for
  2551. * the hostname and -1 for the port.
  2552. */
  2553. static CURLcode parse_connect_to_host_port(struct Curl_easy *data,
  2554. const char *host,
  2555. char **hostname_result,
  2556. int *port_result)
  2557. {
  2558. char *host_dup;
  2559. char *hostptr;
  2560. char *host_portno;
  2561. char *portptr;
  2562. int port = -1;
  2563. CURLcode result = CURLE_OK;
  2564. #if defined(CURL_DISABLE_VERBOSE_STRINGS)
  2565. (void) data;
  2566. #endif
  2567. *hostname_result = NULL;
  2568. *port_result = -1;
  2569. if(!host || !*host)
  2570. return CURLE_OK;
  2571. host_dup = strdup(host);
  2572. if(!host_dup)
  2573. return CURLE_OUT_OF_MEMORY;
  2574. hostptr = host_dup;
  2575. /* start scanning for port number at this point */
  2576. portptr = hostptr;
  2577. /* detect and extract RFC6874-style IPv6-addresses */
  2578. if(*hostptr == '[') {
  2579. #ifdef ENABLE_IPV6
  2580. char *ptr = ++hostptr; /* advance beyond the initial bracket */
  2581. while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
  2582. ptr++;
  2583. if(*ptr == '%') {
  2584. /* There might be a zone identifier */
  2585. if(strncmp("%25", ptr, 3))
  2586. infof(data, "Please URL encode %% as %%25, see RFC 6874.");
  2587. ptr++;
  2588. /* Allow unreserved characters as defined in RFC 3986 */
  2589. while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
  2590. (*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
  2591. ptr++;
  2592. }
  2593. if(*ptr == ']')
  2594. /* yeps, it ended nicely with a bracket as well */
  2595. *ptr++ = '\0';
  2596. else
  2597. infof(data, "Invalid IPv6 address format");
  2598. portptr = ptr;
  2599. /* Note that if this didn't end with a bracket, we still advanced the
  2600. * hostptr first, but I can't see anything wrong with that as no host
  2601. * name nor a numeric can legally start with a bracket.
  2602. */
  2603. #else
  2604. failf(data, "Use of IPv6 in *_CONNECT_TO without IPv6 support built-in");
  2605. result = CURLE_NOT_BUILT_IN;
  2606. goto error;
  2607. #endif
  2608. }
  2609. /* Get port number off server.com:1080 */
  2610. host_portno = strchr(portptr, ':');
  2611. if(host_portno) {
  2612. char *endp = NULL;
  2613. *host_portno = '\0'; /* cut off number from host name */
  2614. host_portno++;
  2615. if(*host_portno) {
  2616. long portparse = strtol(host_portno, &endp, 10);
  2617. if((endp && *endp) || (portparse < 0) || (portparse > 65535)) {
  2618. failf(data, "No valid port number in connect to host string (%s)",
  2619. host_portno);
  2620. result = CURLE_SETOPT_OPTION_SYNTAX;
  2621. goto error;
  2622. }
  2623. else
  2624. port = (int)portparse; /* we know it will fit */
  2625. }
  2626. }
  2627. /* now, clone the cleaned host name */
  2628. DEBUGASSERT(hostptr);
  2629. *hostname_result = strdup(hostptr);
  2630. if(!*hostname_result) {
  2631. result = CURLE_OUT_OF_MEMORY;
  2632. goto error;
  2633. }
  2634. *port_result = port;
  2635. error:
  2636. free(host_dup);
  2637. return result;
  2638. }
  2639. /*
  2640. * Parses one "connect to" string in the form:
  2641. * "HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT".
  2642. */
  2643. static CURLcode parse_connect_to_string(struct Curl_easy *data,
  2644. struct connectdata *conn,
  2645. const char *conn_to_host,
  2646. char **host_result,
  2647. int *port_result)
  2648. {
  2649. CURLcode result = CURLE_OK;
  2650. const char *ptr = conn_to_host;
  2651. int host_match = FALSE;
  2652. int port_match = FALSE;
  2653. *host_result = NULL;
  2654. *port_result = -1;
  2655. if(*ptr == ':') {
  2656. /* an empty hostname always matches */
  2657. host_match = TRUE;
  2658. ptr++;
  2659. }
  2660. else {
  2661. /* check whether the URL's hostname matches */
  2662. size_t hostname_to_match_len;
  2663. char *hostname_to_match = aprintf("%s%s%s",
  2664. conn->bits.ipv6_ip ? "[" : "",
  2665. conn->host.name,
  2666. conn->bits.ipv6_ip ? "]" : "");
  2667. if(!hostname_to_match)
  2668. return CURLE_OUT_OF_MEMORY;
  2669. hostname_to_match_len = strlen(hostname_to_match);
  2670. host_match = strncasecompare(ptr, hostname_to_match,
  2671. hostname_to_match_len);
  2672. free(hostname_to_match);
  2673. ptr += hostname_to_match_len;
  2674. host_match = host_match && *ptr == ':';
  2675. ptr++;
  2676. }
  2677. if(host_match) {
  2678. if(*ptr == ':') {
  2679. /* an empty port always matches */
  2680. port_match = TRUE;
  2681. ptr++;
  2682. }
  2683. else {
  2684. /* check whether the URL's port matches */
  2685. char *ptr_next = strchr(ptr, ':');
  2686. if(ptr_next) {
  2687. char *endp = NULL;
  2688. long port_to_match = strtol(ptr, &endp, 10);
  2689. if((endp == ptr_next) && (port_to_match == conn->remote_port)) {
  2690. port_match = TRUE;
  2691. ptr = ptr_next + 1;
  2692. }
  2693. }
  2694. }
  2695. }
  2696. if(host_match && port_match) {
  2697. /* parse the hostname and port to connect to */
  2698. result = parse_connect_to_host_port(data, ptr, host_result, port_result);
  2699. }
  2700. return result;
  2701. }
  2702. /*
  2703. * Processes all strings in the "connect to" slist, and uses the "connect
  2704. * to host" and "connect to port" of the first string that matches.
  2705. */
  2706. static CURLcode parse_connect_to_slist(struct Curl_easy *data,
  2707. struct connectdata *conn,
  2708. struct curl_slist *conn_to_host)
  2709. {
  2710. CURLcode result = CURLE_OK;
  2711. char *host = NULL;
  2712. int port = -1;
  2713. while(conn_to_host && !host && port == -1) {
  2714. result = parse_connect_to_string(data, conn, conn_to_host->data,
  2715. &host, &port);
  2716. if(result)
  2717. return result;
  2718. if(host && *host) {
  2719. conn->conn_to_host.rawalloc = host;
  2720. conn->conn_to_host.name = host;
  2721. conn->bits.conn_to_host = TRUE;
  2722. infof(data, "Connecting to hostname: %s", host);
  2723. }
  2724. else {
  2725. /* no "connect to host" */
  2726. conn->bits.conn_to_host = FALSE;
  2727. Curl_safefree(host);
  2728. }
  2729. if(port >= 0) {
  2730. conn->conn_to_port = port;
  2731. conn->bits.conn_to_port = TRUE;
  2732. infof(data, "Connecting to port: %d", port);
  2733. }
  2734. else {
  2735. /* no "connect to port" */
  2736. conn->bits.conn_to_port = FALSE;
  2737. port = -1;
  2738. }
  2739. conn_to_host = conn_to_host->next;
  2740. }
  2741. #ifndef CURL_DISABLE_ALTSVC
  2742. if(data->asi && !host && (port == -1) &&
  2743. ((conn->handler->protocol == CURLPROTO_HTTPS) ||
  2744. #ifdef CURLDEBUG
  2745. /* allow debug builds to circumvent the HTTPS restriction */
  2746. getenv("CURL_ALTSVC_HTTP")
  2747. #else
  2748. 0
  2749. #endif
  2750. )) {
  2751. /* no connect_to match, try alt-svc! */
  2752. enum alpnid srcalpnid;
  2753. bool hit;
  2754. struct altsvc *as;
  2755. const int allowed_versions = ( ALPN_h1
  2756. #ifdef USE_HTTP2
  2757. | ALPN_h2
  2758. #endif
  2759. #ifdef ENABLE_QUIC
  2760. | ALPN_h3
  2761. #endif
  2762. ) & data->asi->flags;
  2763. host = conn->host.rawalloc;
  2764. #ifdef USE_HTTP2
  2765. /* with h2 support, check that first */
  2766. srcalpnid = ALPN_h2;
  2767. hit = Curl_altsvc_lookup(data->asi,
  2768. srcalpnid, host, conn->remote_port, /* from */
  2769. &as /* to */,
  2770. allowed_versions);
  2771. if(!hit)
  2772. #endif
  2773. {
  2774. srcalpnid = ALPN_h1;
  2775. hit = Curl_altsvc_lookup(data->asi,
  2776. srcalpnid, host, conn->remote_port, /* from */
  2777. &as /* to */,
  2778. allowed_versions);
  2779. }
  2780. if(hit) {
  2781. char *hostd = strdup((char *)as->dst.host);
  2782. if(!hostd)
  2783. return CURLE_OUT_OF_MEMORY;
  2784. conn->conn_to_host.rawalloc = hostd;
  2785. conn->conn_to_host.name = hostd;
  2786. conn->bits.conn_to_host = TRUE;
  2787. conn->conn_to_port = as->dst.port;
  2788. conn->bits.conn_to_port = TRUE;
  2789. conn->bits.altused = TRUE;
  2790. infof(data, "Alt-svc connecting from [%s]%s:%d to [%s]%s:%d",
  2791. Curl_alpnid2str(srcalpnid), host, conn->remote_port,
  2792. Curl_alpnid2str(as->dst.alpnid), hostd, as->dst.port);
  2793. if(srcalpnid != as->dst.alpnid) {
  2794. /* protocol version switch */
  2795. switch(as->dst.alpnid) {
  2796. case ALPN_h1:
  2797. conn->httpversion = 11;
  2798. break;
  2799. case ALPN_h2:
  2800. conn->httpversion = 20;
  2801. break;
  2802. case ALPN_h3:
  2803. conn->transport = TRNSPRT_QUIC;
  2804. conn->httpversion = 30;
  2805. break;
  2806. default: /* shouldn't be possible */
  2807. break;
  2808. }
  2809. }
  2810. }
  2811. }
  2812. #endif
  2813. return result;
  2814. }
  2815. #ifdef USE_UNIX_SOCKETS
  2816. static CURLcode resolve_unix(struct Curl_easy *data,
  2817. struct connectdata *conn,
  2818. char *unix_path)
  2819. {
  2820. struct Curl_dns_entry *hostaddr = NULL;
  2821. bool longpath = FALSE;
  2822. DEBUGASSERT(unix_path);
  2823. DEBUGASSERT(conn->dns_entry == NULL);
  2824. /* Unix domain sockets are local. The host gets ignored, just use the
  2825. * specified domain socket address. Do not cache "DNS entries". There is
  2826. * no DNS involved and we already have the filesystem path available. */
  2827. hostaddr = calloc(1, sizeof(struct Curl_dns_entry));
  2828. if(!hostaddr)
  2829. return CURLE_OUT_OF_MEMORY;
  2830. hostaddr->addr = Curl_unix2addr(unix_path, &longpath,
  2831. conn->bits.abstract_unix_socket);
  2832. if(!hostaddr->addr) {
  2833. if(longpath)
  2834. /* Long paths are not supported for now */
  2835. failf(data, "Unix socket path too long: '%s'", unix_path);
  2836. free(hostaddr);
  2837. return longpath ? CURLE_COULDNT_RESOLVE_HOST : CURLE_OUT_OF_MEMORY;
  2838. }
  2839. hostaddr->inuse++;
  2840. conn->dns_entry = hostaddr;
  2841. return CURLE_OK;
  2842. }
  2843. #endif
  2844. #ifndef CURL_DISABLE_PROXY
  2845. static CURLcode resolve_proxy(struct Curl_easy *data,
  2846. struct connectdata *conn,
  2847. bool *async)
  2848. {
  2849. struct Curl_dns_entry *hostaddr = NULL;
  2850. struct hostname *host;
  2851. timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
  2852. int rc;
  2853. DEBUGASSERT(conn->dns_entry == NULL);
  2854. host = conn->bits.socksproxy ? &conn->socks_proxy.host :
  2855. &conn->http_proxy.host;
  2856. conn->hostname_resolve = strdup(host->name);
  2857. if(!conn->hostname_resolve)
  2858. return CURLE_OUT_OF_MEMORY;
  2859. rc = Curl_resolv_timeout(data, conn->hostname_resolve, (int)conn->port,
  2860. &hostaddr, timeout_ms);
  2861. conn->dns_entry = hostaddr;
  2862. if(rc == CURLRESOLV_PENDING)
  2863. *async = TRUE;
  2864. else if(rc == CURLRESOLV_TIMEDOUT)
  2865. return CURLE_OPERATION_TIMEDOUT;
  2866. else if(!hostaddr) {
  2867. failf(data, "Couldn't resolve proxy '%s'", host->dispname);
  2868. return CURLE_COULDNT_RESOLVE_PROXY;
  2869. }
  2870. return CURLE_OK;
  2871. }
  2872. #endif
  2873. static CURLcode resolve_host(struct Curl_easy *data,
  2874. struct connectdata *conn,
  2875. bool *async)
  2876. {
  2877. struct Curl_dns_entry *hostaddr = NULL;
  2878. struct hostname *connhost;
  2879. timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
  2880. int rc;
  2881. DEBUGASSERT(conn->dns_entry == NULL);
  2882. connhost = conn->bits.conn_to_host ? &conn->conn_to_host : &conn->host;
  2883. /* If not connecting via a proxy, extract the port from the URL, if it is
  2884. * there, thus overriding any defaults that might have been set above. */
  2885. conn->port = conn->bits.conn_to_port ? conn->conn_to_port :
  2886. conn->remote_port;
  2887. /* Resolve target host right on */
  2888. conn->hostname_resolve = strdup(connhost->name);
  2889. if(!conn->hostname_resolve)
  2890. return CURLE_OUT_OF_MEMORY;
  2891. rc = Curl_resolv_timeout(data, conn->hostname_resolve, (int)conn->port,
  2892. &hostaddr, timeout_ms);
  2893. conn->dns_entry = hostaddr;
  2894. if(rc == CURLRESOLV_PENDING)
  2895. *async = TRUE;
  2896. else if(rc == CURLRESOLV_TIMEDOUT) {
  2897. failf(data, "Failed to resolve host '%s' with timeout after %"
  2898. CURL_FORMAT_TIMEDIFF_T " ms", connhost->dispname,
  2899. Curl_timediff(Curl_now(), data->progress.t_startsingle));
  2900. return CURLE_OPERATION_TIMEDOUT;
  2901. }
  2902. else if(!hostaddr) {
  2903. failf(data, "Could not resolve host: %s", connhost->dispname);
  2904. return CURLE_COULDNT_RESOLVE_HOST;
  2905. }
  2906. return CURLE_OK;
  2907. }
  2908. /* Perform a fresh resolve */
  2909. static CURLcode resolve_fresh(struct Curl_easy *data,
  2910. struct connectdata *conn,
  2911. bool *async)
  2912. {
  2913. #ifdef USE_UNIX_SOCKETS
  2914. char *unix_path = conn->unix_domain_socket;
  2915. #ifndef CURL_DISABLE_PROXY
  2916. if(!unix_path && conn->socks_proxy.host.name &&
  2917. !strncmp(UNIX_SOCKET_PREFIX"/",
  2918. conn->socks_proxy.host.name, sizeof(UNIX_SOCKET_PREFIX)))
  2919. unix_path = conn->socks_proxy.host.name + sizeof(UNIX_SOCKET_PREFIX) - 1;
  2920. #endif
  2921. if(unix_path) {
  2922. conn->transport = TRNSPRT_UNIX;
  2923. return resolve_unix(data, conn, unix_path);
  2924. }
  2925. #endif
  2926. #ifndef CURL_DISABLE_PROXY
  2927. if(CONN_IS_PROXIED(conn))
  2928. return resolve_proxy(data, conn, async);
  2929. #endif
  2930. return resolve_host(data, conn, async);
  2931. }
  2932. /*************************************************************
  2933. * Resolve the address of the server or proxy
  2934. *************************************************************/
  2935. static CURLcode resolve_server(struct Curl_easy *data,
  2936. struct connectdata *conn,
  2937. bool *async)
  2938. {
  2939. DEBUGASSERT(conn);
  2940. DEBUGASSERT(data);
  2941. /* Resolve the name of the server or proxy */
  2942. if(conn->bits.reuse) {
  2943. /* We're reusing the connection - no need to resolve anything, and
  2944. idnconvert_hostname() was called already in create_conn() for the reuse
  2945. case. */
  2946. *async = FALSE;
  2947. return CURLE_OK;
  2948. }
  2949. return resolve_fresh(data, conn, async);
  2950. }
  2951. /*
  2952. * Cleanup the connection `temp`, just allocated for `data`, before using the
  2953. * previously `existing` one for `data`. All relevant info is copied over
  2954. * and `temp` is freed.
  2955. */
  2956. static void reuse_conn(struct Curl_easy *data,
  2957. struct connectdata *temp,
  2958. struct connectdata *existing)
  2959. {
  2960. /* get the user+password information from the temp struct since it may
  2961. * be new for this request even when we reuse an existing connection */
  2962. if(temp->user) {
  2963. /* use the new user name and password though */
  2964. Curl_safefree(existing->user);
  2965. Curl_safefree(existing->passwd);
  2966. existing->user = temp->user;
  2967. existing->passwd = temp->passwd;
  2968. temp->user = NULL;
  2969. temp->passwd = NULL;
  2970. }
  2971. #ifndef CURL_DISABLE_PROXY
  2972. existing->bits.proxy_user_passwd = temp->bits.proxy_user_passwd;
  2973. if(existing->bits.proxy_user_passwd) {
  2974. /* use the new proxy user name and proxy password though */
  2975. Curl_safefree(existing->http_proxy.user);
  2976. Curl_safefree(existing->socks_proxy.user);
  2977. Curl_safefree(existing->http_proxy.passwd);
  2978. Curl_safefree(existing->socks_proxy.passwd);
  2979. existing->http_proxy.user = temp->http_proxy.user;
  2980. existing->socks_proxy.user = temp->socks_proxy.user;
  2981. existing->http_proxy.passwd = temp->http_proxy.passwd;
  2982. existing->socks_proxy.passwd = temp->socks_proxy.passwd;
  2983. temp->http_proxy.user = NULL;
  2984. temp->socks_proxy.user = NULL;
  2985. temp->http_proxy.passwd = NULL;
  2986. temp->socks_proxy.passwd = NULL;
  2987. }
  2988. #endif
  2989. /* Finding a connection for reuse in the cache matches, among other
  2990. * things on the "remote-relevant" hostname. This is not necessarily
  2991. * the authority of the URL, e.g. conn->host. For example:
  2992. * - we use a proxy (not tunneling). we want to send all requests
  2993. * that use the same proxy on this connection.
  2994. * - we have a "connect-to" setting that may redirect the hostname of
  2995. * a new request to the same remote endpoint of an existing conn.
  2996. * We want to reuse an existing conn to the remote endpoint.
  2997. * Since connection reuse does not match on conn->host necessarily, we
  2998. * switch `existing` conn to `temp` conn's host settings.
  2999. * TODO: is this correct in the case of TLS connections that have
  3000. * used the original hostname in SNI to negotiate? Do we send
  3001. * requests for another host through the different SNI?
  3002. */
  3003. Curl_free_idnconverted_hostname(&existing->host);
  3004. Curl_free_idnconverted_hostname(&existing->conn_to_host);
  3005. Curl_safefree(existing->host.rawalloc);
  3006. Curl_safefree(existing->conn_to_host.rawalloc);
  3007. existing->host = temp->host;
  3008. temp->host.rawalloc = NULL;
  3009. temp->host.encalloc = NULL;
  3010. existing->conn_to_host = temp->conn_to_host;
  3011. temp->conn_to_host.rawalloc = NULL;
  3012. existing->conn_to_port = temp->conn_to_port;
  3013. existing->remote_port = temp->remote_port;
  3014. Curl_safefree(existing->hostname_resolve);
  3015. existing->hostname_resolve = temp->hostname_resolve;
  3016. temp->hostname_resolve = NULL;
  3017. /* reuse init */
  3018. existing->bits.reuse = TRUE; /* yes, we're reusing here */
  3019. conn_free(data, temp);
  3020. }
  3021. /**
  3022. * create_conn() sets up a new connectdata struct, or reuses an already
  3023. * existing one, and resolves host name.
  3024. *
  3025. * if this function returns CURLE_OK and *async is set to TRUE, the resolve
  3026. * response will be coming asynchronously. If *async is FALSE, the name is
  3027. * already resolved.
  3028. *
  3029. * @param data The sessionhandle pointer
  3030. * @param in_connect is set to the next connection data pointer
  3031. * @param async is set TRUE when an async DNS resolution is pending
  3032. * @see Curl_setup_conn()
  3033. *
  3034. */
  3035. static CURLcode create_conn(struct Curl_easy *data,
  3036. struct connectdata **in_connect,
  3037. bool *async)
  3038. {
  3039. CURLcode result = CURLE_OK;
  3040. struct connectdata *conn;
  3041. struct connectdata *existing = NULL;
  3042. bool reuse;
  3043. bool connections_available = TRUE;
  3044. bool force_reuse = FALSE;
  3045. bool waitpipe = FALSE;
  3046. size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
  3047. size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
  3048. *async = FALSE;
  3049. *in_connect = NULL;
  3050. /*************************************************************
  3051. * Check input data
  3052. *************************************************************/
  3053. if(!data->state.url) {
  3054. result = CURLE_URL_MALFORMAT;
  3055. goto out;
  3056. }
  3057. /* First, split up the current URL in parts so that we can use the
  3058. parts for checking against the already present connections. In order
  3059. to not have to modify everything at once, we allocate a temporary
  3060. connection data struct and fill in for comparison purposes. */
  3061. conn = allocate_conn(data);
  3062. if(!conn) {
  3063. result = CURLE_OUT_OF_MEMORY;
  3064. goto out;
  3065. }
  3066. /* We must set the return variable as soon as possible, so that our
  3067. parent can cleanup any possible allocs we may have done before
  3068. any failure */
  3069. *in_connect = conn;
  3070. result = parseurlandfillconn(data, conn);
  3071. if(result)
  3072. goto out;
  3073. if(data->set.str[STRING_SASL_AUTHZID]) {
  3074. conn->sasl_authzid = strdup(data->set.str[STRING_SASL_AUTHZID]);
  3075. if(!conn->sasl_authzid) {
  3076. result = CURLE_OUT_OF_MEMORY;
  3077. goto out;
  3078. }
  3079. }
  3080. if(data->set.str[STRING_BEARER]) {
  3081. conn->oauth_bearer = strdup(data->set.str[STRING_BEARER]);
  3082. if(!conn->oauth_bearer) {
  3083. result = CURLE_OUT_OF_MEMORY;
  3084. goto out;
  3085. }
  3086. }
  3087. #ifdef USE_UNIX_SOCKETS
  3088. if(data->set.str[STRING_UNIX_SOCKET_PATH]) {
  3089. conn->unix_domain_socket = strdup(data->set.str[STRING_UNIX_SOCKET_PATH]);
  3090. if(!conn->unix_domain_socket) {
  3091. result = CURLE_OUT_OF_MEMORY;
  3092. goto out;
  3093. }
  3094. conn->bits.abstract_unix_socket = data->set.abstract_unix_socket;
  3095. }
  3096. #endif
  3097. /* After the unix socket init but before the proxy vars are used, parse and
  3098. initialize the proxy vars */
  3099. #ifndef CURL_DISABLE_PROXY
  3100. result = create_conn_helper_init_proxy(data, conn);
  3101. if(result)
  3102. goto out;
  3103. /*************************************************************
  3104. * If the protocol is using SSL and HTTP proxy is used, we set
  3105. * the tunnel_proxy bit.
  3106. *************************************************************/
  3107. if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
  3108. conn->bits.tunnel_proxy = TRUE;
  3109. #endif
  3110. /*************************************************************
  3111. * Figure out the remote port number and fix it in the URL
  3112. *************************************************************/
  3113. result = parse_remote_port(data, conn);
  3114. if(result)
  3115. goto out;
  3116. /* Check for overridden login details and set them accordingly so that
  3117. they are known when protocol->setup_connection is called! */
  3118. result = override_login(data, conn);
  3119. if(result)
  3120. goto out;
  3121. result = set_login(data, conn); /* default credentials */
  3122. if(result)
  3123. goto out;
  3124. /*************************************************************
  3125. * Process the "connect to" linked list of hostname/port mappings.
  3126. * Do this after the remote port number has been fixed in the URL.
  3127. *************************************************************/
  3128. result = parse_connect_to_slist(data, conn, data->set.connect_to);
  3129. if(result)
  3130. goto out;
  3131. /*************************************************************
  3132. * IDN-convert the proxy hostnames
  3133. *************************************************************/
  3134. #ifndef CURL_DISABLE_PROXY
  3135. if(conn->bits.httpproxy) {
  3136. result = Curl_idnconvert_hostname(&conn->http_proxy.host);
  3137. if(result)
  3138. return result;
  3139. }
  3140. if(conn->bits.socksproxy) {
  3141. result = Curl_idnconvert_hostname(&conn->socks_proxy.host);
  3142. if(result)
  3143. return result;
  3144. }
  3145. #endif
  3146. if(conn->bits.conn_to_host) {
  3147. result = Curl_idnconvert_hostname(&conn->conn_to_host);
  3148. if(result)
  3149. return result;
  3150. }
  3151. /*************************************************************
  3152. * Check whether the host and the "connect to host" are equal.
  3153. * Do this after the hostnames have been IDN-converted.
  3154. *************************************************************/
  3155. if(conn->bits.conn_to_host &&
  3156. strcasecompare(conn->conn_to_host.name, conn->host.name)) {
  3157. conn->bits.conn_to_host = FALSE;
  3158. }
  3159. /*************************************************************
  3160. * Check whether the port and the "connect to port" are equal.
  3161. * Do this after the remote port number has been fixed in the URL.
  3162. *************************************************************/
  3163. if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) {
  3164. conn->bits.conn_to_port = FALSE;
  3165. }
  3166. #ifndef CURL_DISABLE_PROXY
  3167. /*************************************************************
  3168. * If the "connect to" feature is used with an HTTP proxy,
  3169. * we set the tunnel_proxy bit.
  3170. *************************************************************/
  3171. if((conn->bits.conn_to_host || conn->bits.conn_to_port) &&
  3172. conn->bits.httpproxy)
  3173. conn->bits.tunnel_proxy = TRUE;
  3174. #endif
  3175. /*************************************************************
  3176. * Setup internals depending on protocol. Needs to be done after
  3177. * we figured out what/if proxy to use.
  3178. *************************************************************/
  3179. result = setup_connection_internals(data, conn);
  3180. if(result)
  3181. goto out;
  3182. /***********************************************************************
  3183. * file: is a special case in that it doesn't need a network connection
  3184. ***********************************************************************/
  3185. #ifndef CURL_DISABLE_FILE
  3186. if(conn->handler->flags & PROTOPT_NONETWORK) {
  3187. bool done;
  3188. /* this is supposed to be the connect function so we better at least check
  3189. that the file is present here! */
  3190. DEBUGASSERT(conn->handler->connect_it);
  3191. Curl_persistconninfo(data, conn, NULL, -1);
  3192. result = conn->handler->connect_it(data, &done);
  3193. /* Setup a "faked" transfer that'll do nothing */
  3194. if(!result) {
  3195. Curl_attach_connection(data, conn);
  3196. result = Curl_conncache_add_conn(data);
  3197. if(result)
  3198. goto out;
  3199. /*
  3200. * Setup whatever necessary for a resumed transfer
  3201. */
  3202. result = setup_range(data);
  3203. if(result) {
  3204. DEBUGASSERT(conn->handler->done);
  3205. /* we ignore the return code for the protocol-specific DONE */
  3206. (void)conn->handler->done(data, result, FALSE);
  3207. goto out;
  3208. }
  3209. Curl_setup_transfer(data, -1, -1, FALSE, -1);
  3210. }
  3211. /* since we skip do_init() */
  3212. Curl_init_do(data, conn);
  3213. goto out;
  3214. }
  3215. #endif
  3216. /* Setup filter for network connections */
  3217. conn->recv[FIRSTSOCKET] = Curl_conn_recv;
  3218. conn->send[FIRSTSOCKET] = Curl_conn_send;
  3219. conn->recv[SECONDARYSOCKET] = Curl_conn_recv;
  3220. conn->send[SECONDARYSOCKET] = Curl_conn_send;
  3221. conn->bits.tcp_fastopen = data->set.tcp_fastopen;
  3222. /* Complete the easy's SSL configuration for connection cache matching */
  3223. result = Curl_ssl_easy_config_complete(data);
  3224. if(result)
  3225. goto out;
  3226. prune_dead_connections(data);
  3227. /*************************************************************
  3228. * Check the current list of connections to see if we can
  3229. * reuse an already existing one or if we have to create a
  3230. * new one.
  3231. *************************************************************/
  3232. DEBUGASSERT(conn->user);
  3233. DEBUGASSERT(conn->passwd);
  3234. /* reuse_fresh is TRUE if we are told to use a new connection by force, but
  3235. we only acknowledge this option if this is not a reused connection
  3236. already (which happens due to follow-location or during an HTTP
  3237. authentication phase). CONNECT_ONLY transfers also refuse reuse. */
  3238. if((data->set.reuse_fresh && !data->state.followlocation) ||
  3239. data->set.connect_only)
  3240. reuse = FALSE;
  3241. else
  3242. reuse = ConnectionExists(data, conn, &existing, &force_reuse, &waitpipe);
  3243. if(reuse) {
  3244. /*
  3245. * We already have a connection for this, we got the former connection in
  3246. * `existing` and thus we need to cleanup the one we just
  3247. * allocated before we can move along and use `existing`.
  3248. */
  3249. reuse_conn(data, conn, existing);
  3250. conn = existing;
  3251. *in_connect = conn;
  3252. #ifndef CURL_DISABLE_PROXY
  3253. infof(data, "Re-using existing connection with %s %s",
  3254. conn->bits.proxy?"proxy":"host",
  3255. conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname :
  3256. conn->http_proxy.host.name ? conn->http_proxy.host.dispname :
  3257. conn->host.dispname);
  3258. #else
  3259. infof(data, "Re-using existing connection with host %s",
  3260. conn->host.dispname);
  3261. #endif
  3262. }
  3263. else {
  3264. /* We have decided that we want a new connection. However, we may not
  3265. be able to do that if we have reached the limit of how many
  3266. connections we are allowed to open. */
  3267. if(conn->handler->flags & PROTOPT_ALPN) {
  3268. /* The protocol wants it, so set the bits if enabled in the easy handle
  3269. (default) */
  3270. if(data->set.ssl_enable_alpn)
  3271. conn->bits.tls_enable_alpn = TRUE;
  3272. }
  3273. if(waitpipe)
  3274. /* There is a connection that *might* become usable for multiplexing
  3275. "soon", and we wait for that */
  3276. connections_available = FALSE;
  3277. else {
  3278. /* this gets a lock on the conncache */
  3279. struct connectbundle *bundle =
  3280. Curl_conncache_find_bundle(data, conn, data->state.conn_cache);
  3281. if(max_host_connections > 0 && bundle &&
  3282. (bundle->num_connections >= max_host_connections)) {
  3283. struct connectdata *conn_candidate;
  3284. /* The bundle is full. Extract the oldest connection. */
  3285. conn_candidate = Curl_conncache_extract_bundle(data, bundle);
  3286. CONNCACHE_UNLOCK(data);
  3287. if(conn_candidate)
  3288. Curl_disconnect(data, conn_candidate, FALSE);
  3289. else {
  3290. infof(data, "No more connections allowed to host: %zu",
  3291. max_host_connections);
  3292. connections_available = FALSE;
  3293. }
  3294. }
  3295. else
  3296. CONNCACHE_UNLOCK(data);
  3297. }
  3298. if(connections_available &&
  3299. (max_total_connections > 0) &&
  3300. (Curl_conncache_size(data) >= max_total_connections)) {
  3301. struct connectdata *conn_candidate;
  3302. /* The cache is full. Let's see if we can kill a connection. */
  3303. conn_candidate = Curl_conncache_extract_oldest(data);
  3304. if(conn_candidate)
  3305. Curl_disconnect(data, conn_candidate, FALSE);
  3306. else {
  3307. infof(data, "No connections available in cache");
  3308. connections_available = FALSE;
  3309. }
  3310. }
  3311. if(!connections_available) {
  3312. infof(data, "No connections available.");
  3313. conn_free(data, conn);
  3314. *in_connect = NULL;
  3315. result = CURLE_NO_CONNECTION_AVAILABLE;
  3316. goto out;
  3317. }
  3318. else {
  3319. /*
  3320. * This is a brand new connection, so let's store it in the connection
  3321. * cache of ours!
  3322. */
  3323. result = Curl_ssl_conn_config_init(data, conn);
  3324. if(result) {
  3325. DEBUGF(fprintf(stderr, "Error: init connection ssl config\n"));
  3326. goto out;
  3327. }
  3328. result = Curl_resolver_init(data, &conn->resolve_async.resolver);
  3329. if(result) {
  3330. DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
  3331. goto out;
  3332. }
  3333. Curl_attach_connection(data, conn);
  3334. #ifdef USE_ARES
  3335. result = Curl_set_dns_servers(data, data->set.str[STRING_DNS_SERVERS]);
  3336. if(result && result != CURLE_NOT_BUILT_IN)
  3337. goto out;
  3338. result = Curl_set_dns_interface(data,
  3339. data->set.str[STRING_DNS_INTERFACE]);
  3340. if(result && result != CURLE_NOT_BUILT_IN)
  3341. goto out;
  3342. result = Curl_set_dns_local_ip4(data,
  3343. data->set.str[STRING_DNS_LOCAL_IP4]);
  3344. if(result && result != CURLE_NOT_BUILT_IN)
  3345. goto out;
  3346. result = Curl_set_dns_local_ip6(data,
  3347. data->set.str[STRING_DNS_LOCAL_IP6]);
  3348. if(result && result != CURLE_NOT_BUILT_IN)
  3349. goto out;
  3350. #endif /* USE_ARES */
  3351. result = Curl_conncache_add_conn(data);
  3352. if(result)
  3353. goto out;
  3354. }
  3355. #if defined(USE_NTLM)
  3356. /* If NTLM is requested in a part of this connection, make sure we don't
  3357. assume the state is fine as this is a fresh connection and NTLM is
  3358. connection based. */
  3359. if((data->state.authhost.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
  3360. data->state.authhost.done) {
  3361. infof(data, "NTLM picked AND auth done set, clear picked");
  3362. data->state.authhost.picked = CURLAUTH_NONE;
  3363. data->state.authhost.done = FALSE;
  3364. }
  3365. if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
  3366. data->state.authproxy.done) {
  3367. infof(data, "NTLM-proxy picked AND auth done set, clear picked");
  3368. data->state.authproxy.picked = CURLAUTH_NONE;
  3369. data->state.authproxy.done = FALSE;
  3370. }
  3371. #endif
  3372. }
  3373. /* Setup and init stuff before DO starts, in preparing for the transfer. */
  3374. Curl_init_do(data, conn);
  3375. /*
  3376. * Setup whatever necessary for a resumed transfer
  3377. */
  3378. result = setup_range(data);
  3379. if(result)
  3380. goto out;
  3381. /* Continue connectdata initialization here. */
  3382. /*
  3383. * Inherit the proper values from the urldata struct AFTER we have arranged
  3384. * the persistent connection stuff
  3385. */
  3386. conn->seek_func = data->set.seek_func;
  3387. conn->seek_client = data->set.seek_client;
  3388. /*************************************************************
  3389. * Resolve the address of the server or proxy
  3390. *************************************************************/
  3391. result = resolve_server(data, conn, async);
  3392. if(result)
  3393. goto out;
  3394. /* Everything general done, inform filters that they need
  3395. * to prepare for a data transfer.
  3396. */
  3397. result = Curl_conn_ev_data_setup(data);
  3398. out:
  3399. return result;
  3400. }
  3401. /* Curl_setup_conn() is called after the name resolve initiated in
  3402. * create_conn() is all done.
  3403. *
  3404. * Curl_setup_conn() also handles reused connections
  3405. */
  3406. CURLcode Curl_setup_conn(struct Curl_easy *data,
  3407. bool *protocol_done)
  3408. {
  3409. CURLcode result = CURLE_OK;
  3410. struct connectdata *conn = data->conn;
  3411. Curl_pgrsTime(data, TIMER_NAMELOOKUP);
  3412. if(conn->handler->flags & PROTOPT_NONETWORK) {
  3413. /* nothing to setup when not using a network */
  3414. *protocol_done = TRUE;
  3415. return result;
  3416. }
  3417. #ifndef CURL_DISABLE_PROXY
  3418. /* set proxy_connect_closed to false unconditionally already here since it
  3419. is used strictly to provide extra information to a parent function in the
  3420. case of proxy CONNECT failures and we must make sure we don't have it
  3421. lingering set from a previous invoke */
  3422. conn->bits.proxy_connect_closed = FALSE;
  3423. #endif
  3424. #ifdef CURL_DO_LINEEND_CONV
  3425. data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
  3426. #endif /* CURL_DO_LINEEND_CONV */
  3427. /* set start time here for timeout purposes in the connect procedure, it
  3428. is later set again for the progress meter purpose */
  3429. conn->now = Curl_now();
  3430. if(!conn->bits.reuse)
  3431. result = Curl_conn_setup(data, conn, FIRSTSOCKET, conn->dns_entry,
  3432. CURL_CF_SSL_DEFAULT);
  3433. /* not sure we need this flag to be passed around any more */
  3434. *protocol_done = FALSE;
  3435. return result;
  3436. }
  3437. CURLcode Curl_connect(struct Curl_easy *data,
  3438. bool *asyncp,
  3439. bool *protocol_done)
  3440. {
  3441. CURLcode result;
  3442. struct connectdata *conn;
  3443. *asyncp = FALSE; /* assume synchronous resolves by default */
  3444. /* init the single-transfer specific data */
  3445. Curl_free_request_state(data);
  3446. memset(&data->req, 0, sizeof(struct SingleRequest));
  3447. data->req.size = data->req.maxdownload = -1;
  3448. data->req.no_body = data->set.opt_no_body;
  3449. /* call the stuff that needs to be called */
  3450. result = create_conn(data, &conn, asyncp);
  3451. if(!result) {
  3452. if(CONN_INUSE(conn) > 1)
  3453. /* multiplexed */
  3454. *protocol_done = TRUE;
  3455. else if(!*asyncp) {
  3456. /* DNS resolution is done: that's either because this is a reused
  3457. connection, in which case DNS was unnecessary, or because DNS
  3458. really did finish already (synch resolver/fast async resolve) */
  3459. result = Curl_setup_conn(data, protocol_done);
  3460. }
  3461. }
  3462. if(result == CURLE_NO_CONNECTION_AVAILABLE) {
  3463. return result;
  3464. }
  3465. else if(result && conn) {
  3466. /* We're not allowed to return failure with memory left allocated in the
  3467. connectdata struct, free those here */
  3468. Curl_detach_connection(data);
  3469. Curl_conncache_remove_conn(data, conn, TRUE);
  3470. Curl_disconnect(data, conn, TRUE);
  3471. }
  3472. return result;
  3473. }
  3474. /*
  3475. * Curl_init_do() inits the readwrite session. This is inited each time (in
  3476. * the DO function before the protocol-specific DO functions are invoked) for
  3477. * a transfer, sometimes multiple times on the same Curl_easy. Make sure
  3478. * nothing in here depends on stuff that are setup dynamically for the
  3479. * transfer.
  3480. *
  3481. * Allow this function to get called with 'conn' set to NULL.
  3482. */
  3483. CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn)
  3484. {
  3485. struct SingleRequest *k = &data->req;
  3486. /* if this is a pushed stream, we need this: */
  3487. CURLcode result = Curl_preconnect(data);
  3488. if(result)
  3489. return result;
  3490. if(conn) {
  3491. conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to
  3492. use */
  3493. /* if the protocol used doesn't support wildcards, switch it off */
  3494. if(data->state.wildcardmatch &&
  3495. !(conn->handler->flags & PROTOPT_WILDCARD))
  3496. data->state.wildcardmatch = FALSE;
  3497. }
  3498. data->state.done = FALSE; /* *_done() is not called yet */
  3499. data->state.expect100header = FALSE;
  3500. if(data->req.no_body)
  3501. /* in HTTP lingo, no body means using the HEAD request... */
  3502. data->state.httpreq = HTTPREQ_HEAD;
  3503. k->start = Curl_now(); /* start time */
  3504. k->header = TRUE; /* assume header */
  3505. k->bytecount = 0;
  3506. k->ignorebody = FALSE;
  3507. Curl_client_cleanup(data);
  3508. Curl_speedinit(data);
  3509. Curl_pgrsSetUploadCounter(data, 0);
  3510. Curl_pgrsSetDownloadCounter(data, 0);
  3511. return CURLE_OK;
  3512. }
  3513. #if defined(USE_HTTP2) || defined(USE_HTTP3)
  3514. #ifdef USE_NGHTTP2
  3515. static void priority_remove_child(struct Curl_easy *parent,
  3516. struct Curl_easy *child)
  3517. {
  3518. struct Curl_data_prio_node **pnext = &parent->set.priority.children;
  3519. struct Curl_data_prio_node *pnode = parent->set.priority.children;
  3520. DEBUGASSERT(child->set.priority.parent == parent);
  3521. while(pnode && pnode->data != child) {
  3522. pnext = &pnode->next;
  3523. pnode = pnode->next;
  3524. }
  3525. DEBUGASSERT(pnode);
  3526. if(pnode) {
  3527. *pnext = pnode->next;
  3528. free(pnode);
  3529. }
  3530. child->set.priority.parent = 0;
  3531. child->set.priority.exclusive = FALSE;
  3532. }
  3533. CURLcode Curl_data_priority_add_child(struct Curl_easy *parent,
  3534. struct Curl_easy *child,
  3535. bool exclusive)
  3536. {
  3537. if(child->set.priority.parent) {
  3538. priority_remove_child(child->set.priority.parent, child);
  3539. }
  3540. if(parent) {
  3541. struct Curl_data_prio_node **tail;
  3542. struct Curl_data_prio_node *pnode;
  3543. pnode = calloc(1, sizeof(*pnode));
  3544. if(!pnode)
  3545. return CURLE_OUT_OF_MEMORY;
  3546. pnode->data = child;
  3547. if(parent->set.priority.children && exclusive) {
  3548. /* exclusive: move all existing children underneath the new child */
  3549. struct Curl_data_prio_node *node = parent->set.priority.children;
  3550. while(node) {
  3551. node->data->set.priority.parent = child;
  3552. node = node->next;
  3553. }
  3554. tail = &child->set.priority.children;
  3555. while(*tail)
  3556. tail = &(*tail)->next;
  3557. DEBUGASSERT(!*tail);
  3558. *tail = parent->set.priority.children;
  3559. parent->set.priority.children = 0;
  3560. }
  3561. tail = &parent->set.priority.children;
  3562. while(*tail) {
  3563. (*tail)->data->set.priority.exclusive = FALSE;
  3564. tail = &(*tail)->next;
  3565. }
  3566. DEBUGASSERT(!*tail);
  3567. *tail = pnode;
  3568. }
  3569. child->set.priority.parent = parent;
  3570. child->set.priority.exclusive = exclusive;
  3571. return CURLE_OK;
  3572. }
  3573. #endif /* USE_NGHTTP2 */
  3574. #ifdef USE_NGHTTP2
  3575. static void data_priority_cleanup(struct Curl_easy *data)
  3576. {
  3577. while(data->set.priority.children) {
  3578. struct Curl_easy *tmp = data->set.priority.children->data;
  3579. priority_remove_child(data, tmp);
  3580. if(data->set.priority.parent)
  3581. Curl_data_priority_add_child(data->set.priority.parent, tmp, FALSE);
  3582. }
  3583. if(data->set.priority.parent)
  3584. priority_remove_child(data->set.priority.parent, data);
  3585. }
  3586. #endif
  3587. void Curl_data_priority_clear_state(struct Curl_easy *data)
  3588. {
  3589. memset(&data->state.priority, 0, sizeof(data->state.priority));
  3590. }
  3591. #endif /* defined(USE_HTTP2) || defined(USE_HTTP3) */