2
0

url.c 123 KB

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