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