url.c 120 KB

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