url.c 131 KB

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