url.c 123 KB

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