url.c 118 KB

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