url.c 117 KB

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