2
0

url.c 128 KB

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