url.c 128 KB

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