url.c 123 KB

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