url.c 123 KB

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