url.c 118 KB

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