2
0

url.c 117 KB

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