url.c 133 KB

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