url.c 131 KB

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