url.c 123 KB

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