url.c 115 KB

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