url.c 130 KB

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