url.c 119 KB

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