2
0

url.c 117 KB

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