url.c 124 KB

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