controller.go 118 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. // Package psiphon implements the core tunnel functionality of a Psiphon client.
  20. // The main function is RunForever, which runs a Controller that obtains lists of
  21. // servers, establishes tunnel connections, and runs local proxies through which
  22. // tunneled traffic may be sent.
  23. package psiphon
  24. import (
  25. "context"
  26. "encoding/json"
  27. "fmt"
  28. "math/rand"
  29. "net"
  30. "runtime"
  31. "sync"
  32. "sync/atomic"
  33. "time"
  34. tls "github.com/Psiphon-Labs/psiphon-tls"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/inproxy"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/resolver"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tun"
  44. utls "github.com/Psiphon-Labs/utls"
  45. lrucache "github.com/cognusion/go-cache-lru"
  46. "golang.org/x/time/rate"
  47. )
  48. // Controller is a tunnel lifecycle coordinator. It manages lists of servers to
  49. // connect to; establishes and monitors tunnels; and runs local proxies which
  50. // route traffic through the tunnels.
  51. type Controller struct {
  52. config *Config
  53. runCtx context.Context
  54. stopRunning context.CancelFunc
  55. runWaitGroup *sync.WaitGroup
  56. connectedTunnels chan *Tunnel
  57. failedTunnels chan *Tunnel
  58. tunnelMutex sync.Mutex
  59. establishedOnce bool
  60. tunnelPoolSize int
  61. tunnels []*Tunnel
  62. nextTunnel int
  63. isEstablishing bool
  64. establishStartTime time.Time
  65. protocolSelectionConstraints *protocolSelectionConstraints
  66. concurrentEstablishTunnelsMutex sync.Mutex
  67. establishConnectTunnelCount int
  68. concurrentEstablishTunnels int
  69. concurrentIntensiveEstablishTunnels int
  70. peakConcurrentEstablishTunnels int
  71. peakConcurrentIntensiveEstablishTunnels int
  72. establishCtx context.Context
  73. stopEstablish context.CancelFunc
  74. establishWaitGroup *sync.WaitGroup
  75. establishedTunnelsCount int32
  76. candidateServerEntries chan *candidateServerEntry
  77. untunneledDialConfig *DialConfig
  78. untunneledSplitTunnelClassifications *lrucache.Cache
  79. signalFetchCommonRemoteServerList chan struct{}
  80. signalFetchObfuscatedServerLists chan struct{}
  81. signalDownloadUpgrade chan string
  82. signalReportServerEntries chan *serverEntriesReportRequest
  83. signalReportConnected chan struct{}
  84. signalRestartEstablishing chan struct{}
  85. serverAffinityDoneBroadcast chan struct{}
  86. packetTunnelClient *tun.Client
  87. packetTunnelTransport *PacketTunnelTransport
  88. staggerMutex sync.Mutex
  89. resolver *resolver.Resolver
  90. steeringIPCache *lrucache.Cache
  91. tlsClientSessionCache utls.ClientSessionCache
  92. quicTLSClientSessionCache tls.ClientSessionCache
  93. inproxyProxyBrokerClientManager *InproxyBrokerClientManager
  94. inproxyClientBrokerClientManager *InproxyBrokerClientManager
  95. inproxyNATStateManager *InproxyNATStateManager
  96. inproxyHandleTacticsMutex sync.Mutex
  97. inproxyLastStoredTactics time.Time
  98. establishSignalForceTacticsFetch chan struct{}
  99. inproxyClientDialRateLimiter *rate.Limiter
  100. currentNetworkMutex sync.Mutex
  101. currentNetworkCtx context.Context
  102. currentNetworkCancelFunc context.CancelFunc
  103. }
  104. // NewController initializes a new controller.
  105. func NewController(config *Config) (controller *Controller, err error) {
  106. if !config.IsCommitted() {
  107. return nil, errors.TraceNew("uncommitted config")
  108. }
  109. // Needed by regen, at least
  110. rand.Seed(int64(time.Now().Nanosecond()))
  111. // The session ID for the Psiphon server API is used across all
  112. // tunnels established by the controller.
  113. NoticeSessionId(config.SessionID)
  114. if !config.DisableTactics {
  115. // Attempt to apply any valid, local stored tactics. The pre-done context
  116. // ensures no tactics request is attempted now.
  117. doneContext, cancelFunc := context.WithCancel(context.Background())
  118. cancelFunc()
  119. GetTactics(doneContext, config, true)
  120. }
  121. p := config.GetParameters().Get()
  122. splitTunnelClassificationTTL :=
  123. p.Duration(parameters.SplitTunnelClassificationTTL)
  124. splitTunnelClassificationMaxEntries :=
  125. p.Int(parameters.SplitTunnelClassificationMaxEntries)
  126. steeringIPCacheTTL := p.Duration(parameters.SteeringIPCacheTTL)
  127. steeringIPCacheMaxEntries := p.Int(parameters.SteeringIPCacheMaxEntries)
  128. controller = &Controller{
  129. config: config,
  130. runWaitGroup: new(sync.WaitGroup),
  131. // connectedTunnels and failedTunnels buffer sizes are large enough to
  132. // receive full pools of tunnels without blocking. Senders should not block.
  133. connectedTunnels: make(chan *Tunnel, MAX_TUNNEL_POOL_SIZE),
  134. failedTunnels: make(chan *Tunnel, MAX_TUNNEL_POOL_SIZE),
  135. tunnelPoolSize: TUNNEL_POOL_SIZE,
  136. tunnels: make([]*Tunnel, 0),
  137. establishedOnce: false,
  138. isEstablishing: false,
  139. untunneledSplitTunnelClassifications: lrucache.NewWithLRU(
  140. splitTunnelClassificationTTL,
  141. 1*time.Minute,
  142. splitTunnelClassificationMaxEntries),
  143. // TODO: Add a buffer of 1 so we don't miss a signal while receiver is
  144. // starting? Trade-off is potential back-to-back fetch remotes. As-is,
  145. // establish will eventually signal another fetch remote.
  146. signalFetchCommonRemoteServerList: make(chan struct{}),
  147. signalFetchObfuscatedServerLists: make(chan struct{}),
  148. signalDownloadUpgrade: make(chan string),
  149. signalReportConnected: make(chan struct{}),
  150. // Using a buffer of 1 to ensure there's no race between the first signal
  151. // sent and a channel receiver initializing; a side effect is that this
  152. // allows 1 additional scan to enqueue while a scan is in progress, possibly
  153. // resulting in one unnecessary scan.
  154. signalReportServerEntries: make(chan *serverEntriesReportRequest, 1),
  155. // signalRestartEstablishing has a buffer of 1 to ensure sending the
  156. // signal doesn't block and receiving won't miss a signal.
  157. signalRestartEstablishing: make(chan struct{}, 1),
  158. steeringIPCache: lrucache.NewWithLRU(
  159. steeringIPCacheTTL,
  160. 1*time.Minute,
  161. steeringIPCacheMaxEntries),
  162. tlsClientSessionCache: utls.NewLRUClientSessionCache(0),
  163. quicTLSClientSessionCache: tls.NewLRUClientSessionCache(0),
  164. }
  165. // Initialize the current network context. This context represents the
  166. // lifetime of the host's current active network interface. When
  167. // Controller.NetworkChanged is called (by the Android and iOS platform
  168. // code), the previous current network interface is considered to be no
  169. // longer active and the corresponding current network context is canceled.
  170. // Components may use currentNetworkCtx to cancel and close old network
  171. // connections and quickly initiate new connections when the active
  172. // interface changes.
  173. controller.currentNetworkCtx, controller.currentNetworkCancelFunc =
  174. context.WithCancel(context.Background())
  175. // Initialize untunneledDialConfig, used by untunneled dials including
  176. // remote server list and upgrade downloads.
  177. controller.untunneledDialConfig = &DialConfig{
  178. UpstreamProxyURL: controller.config.UpstreamProxyURL,
  179. CustomHeaders: controller.config.CustomHeaders,
  180. DeviceBinder: controller.config.deviceBinder,
  181. IPv6Synthesizer: controller.config.IPv6Synthesizer,
  182. ResolveIP: func(ctx context.Context, hostname string) ([]net.IP, error) {
  183. // Note: when domain fronting would be used for untunneled dials a
  184. // copy of untunneledDialConfig should be used instead, which
  185. // redefines ResolveIP such that the corresponding fronting
  186. // provider ID is passed into UntunneledResolveIP to enable the use
  187. // of pre-resolved IPs.
  188. IPs, err := UntunneledResolveIP(
  189. ctx, controller.config, controller.resolver, hostname, "")
  190. if err != nil {
  191. return nil, errors.Trace(err)
  192. }
  193. return IPs, nil
  194. },
  195. TrustedCACertificatesFilename: controller.config.TrustedCACertificatesFilename,
  196. }
  197. if config.PacketTunnelTunFileDescriptor > 0 {
  198. // Run a packet tunnel client. The lifetime of the tun.Client is the
  199. // lifetime of the Controller, so it exists across tunnel establishments
  200. // and reestablishments. The PacketTunnelTransport provides a layer
  201. // that presents a continuosuly existing transport to the tun.Client;
  202. // it's set to use new SSH channels after new SSH tunnel establishes.
  203. packetTunnelTransport := NewPacketTunnelTransport()
  204. packetTunnelClient, err := tun.NewClient(&tun.ClientConfig{
  205. Logger: NoticeCommonLogger(false),
  206. TunFileDescriptor: config.PacketTunnelTunFileDescriptor,
  207. TransparentDNSIPv4Address: config.PacketTunnelTransparentDNSIPv4Address,
  208. TransparentDNSIPv6Address: config.PacketTunnelTransparentDNSIPv6Address,
  209. Transport: packetTunnelTransport,
  210. })
  211. if err != nil {
  212. return nil, errors.Trace(err)
  213. }
  214. controller.packetTunnelClient = packetTunnelClient
  215. controller.packetTunnelTransport = packetTunnelTransport
  216. }
  217. // Initialize shared in-proxy broker clients to be used for all in-proxy
  218. // client dials and in-proxy proxy operations.
  219. //
  220. // Using shared broker connections minimizes the overhead of establishing
  221. // broker connections at the start of an in-proxy dial or operation. By
  222. // design, established broker connections will be retained for up to the
  223. // entire lifetime of the controller run, so past the end of client
  224. // tunnel establishment.
  225. //
  226. // No network operations are performed by NewInproxyBrokerClientManager or
  227. // NewInproxyNATStateManager; each manager operates on demand, when
  228. // in-proxy dials or operations are invoked.
  229. //
  230. // The controller run may include client tunnel establishment, in-proxy
  231. // proxy operations, or both.
  232. //
  233. // Due to the inproxy.InitiatorSessions.NewRoundTrip waitToShareSession
  234. // application-level round trip limitation, there is one broker client
  235. // manager for each of the client and proxy cases, so that neither
  236. // initially blocks while trying to share the others session.
  237. //
  238. // One NAT state manager is shared between both the in-proxy client and
  239. // proxy. While each may have different network discovery policies, any
  240. // discovered network state is valid and useful for both consumers.
  241. // Both broker client and NAT state managers may require resets and update
  242. // when tactics change.
  243. var tacticAppliedReceivers []TacticsAppliedReceiver
  244. isProxy := false
  245. controller.inproxyClientBrokerClientManager = NewInproxyBrokerClientManager(config, isProxy)
  246. tacticAppliedReceivers = append(tacticAppliedReceivers, controller.inproxyClientBrokerClientManager)
  247. controller.inproxyNATStateManager = NewInproxyNATStateManager(config)
  248. tacticAppliedReceivers = append(tacticAppliedReceivers, controller.inproxyNATStateManager)
  249. if config.InproxyEnableProxy {
  250. isProxy = true
  251. controller.inproxyProxyBrokerClientManager = NewInproxyBrokerClientManager(config, isProxy)
  252. tacticAppliedReceivers = append(tacticAppliedReceivers, controller.inproxyProxyBrokerClientManager)
  253. }
  254. controller.config.SetTacticsAppliedReceivers(tacticAppliedReceivers)
  255. controller.config.SetSignalComponentFailure(controller.SignalComponentFailure)
  256. return controller, nil
  257. }
  258. // Run executes the controller. Run exits if a controller
  259. // component fails or the parent context is canceled.
  260. func (controller *Controller) Run(ctx context.Context) {
  261. if controller.config.LimitCPUThreads {
  262. runtime.GOMAXPROCS(1)
  263. }
  264. pprofRun()
  265. // Ensure fresh repetitive notice state for each run, so the
  266. // client will always get an AvailableEgressRegions notice,
  267. // an initial instance of any repetitive error notice, etc.
  268. ResetRepetitiveNotices()
  269. runCtx, stopRunning := context.WithCancel(ctx)
  270. defer stopRunning()
  271. controller.runCtx = runCtx
  272. controller.stopRunning = stopRunning
  273. // Start components
  274. // Initialize a single resolver to be used by all dials. Sharing a single
  275. // resolver ensures cached results are shared, and that network state
  276. // query overhead is amortized over all dials. Multiple dials can resolve
  277. // domain concurrently.
  278. //
  279. // config.SetResolver makes this resolver available to MakeDialParameters.
  280. controller.resolver = NewResolver(controller.config, true)
  281. defer controller.resolver.Stop()
  282. controller.config.SetResolver(controller.resolver)
  283. // Maintain a cache of steering IPs to be applied to dials. A steering IP
  284. // is an alternate dial IP; for example, steering IPs may be specified by
  285. // a CDN service and used to load balance CDN traffic.
  286. controller.steeringIPCache.Flush()
  287. // TODO: IPv6 support
  288. var listenIP string
  289. if controller.config.ListenInterface == "" {
  290. listenIP = "127.0.0.1"
  291. } else if controller.config.ListenInterface == "any" {
  292. listenIP = "0.0.0.0"
  293. } else {
  294. IPv4Address, _, err := common.GetInterfaceIPAddresses(controller.config.ListenInterface)
  295. if err == nil && IPv4Address == nil {
  296. err = fmt.Errorf("no IPv4 address for interface %s", controller.config.ListenInterface)
  297. }
  298. if err != nil {
  299. NoticeError("error getting listener IP: %v", errors.Trace(err))
  300. return
  301. }
  302. listenIP = IPv4Address.String()
  303. }
  304. // The controller run may include client tunnel establishment, in-proxy
  305. // proxy operations, or both. Local tactics are shared between both modes
  306. // and both modes can fetch tactics.
  307. //
  308. // Limitation: the upgrade downloader is not enabled when client tunnel
  309. // establishment is disabled; upgrade version information is not
  310. // currently distributed to in-proxy proxies
  311. if !controller.config.DisableTunnels {
  312. if !controller.config.DisableLocalSocksProxy {
  313. socksProxy, err := NewSocksProxy(controller.config, controller, listenIP)
  314. if err != nil {
  315. NoticeError("error initializing local SOCKS proxy: %v", errors.Trace(err))
  316. return
  317. }
  318. defer socksProxy.Close()
  319. }
  320. if !controller.config.DisableLocalHTTPProxy {
  321. httpProxy, err := NewHttpProxy(controller.config, controller, listenIP)
  322. if err != nil {
  323. NoticeError("error initializing local HTTP proxy: %v", errors.Trace(err))
  324. return
  325. }
  326. defer httpProxy.Close()
  327. }
  328. if controller.config.EnableUpgradeDownload {
  329. controller.runWaitGroup.Add(1)
  330. go controller.upgradeDownloader()
  331. }
  332. controller.runWaitGroup.Add(1)
  333. go controller.serverEntriesReporter()
  334. controller.runWaitGroup.Add(1)
  335. go controller.connectedReporter()
  336. controller.runWaitGroup.Add(1)
  337. go controller.establishTunnelWatcher()
  338. controller.runWaitGroup.Add(1)
  339. go controller.runTunnels()
  340. if controller.packetTunnelClient != nil {
  341. controller.packetTunnelClient.Start()
  342. }
  343. }
  344. if !controller.config.DisableRemoteServerListFetcher {
  345. if controller.config.RemoteServerListURLs != nil {
  346. controller.runWaitGroup.Add(1)
  347. go controller.remoteServerListFetcher(
  348. "common",
  349. FetchCommonRemoteServerList,
  350. controller.signalFetchCommonRemoteServerList)
  351. }
  352. if controller.config.ObfuscatedServerListRootURLs != nil {
  353. controller.runWaitGroup.Add(1)
  354. go controller.remoteServerListFetcher(
  355. "obfuscated",
  356. FetchObfuscatedServerLists,
  357. controller.signalFetchObfuscatedServerLists)
  358. }
  359. }
  360. if controller.config.InproxyEnableProxy {
  361. controller.runWaitGroup.Add(1)
  362. go controller.runInproxyProxy()
  363. }
  364. // Wait while running
  365. <-controller.runCtx.Done()
  366. NoticeInfo("controller stopped")
  367. if controller.packetTunnelClient != nil {
  368. controller.packetTunnelClient.Stop()
  369. }
  370. // Cleanup current network context
  371. controller.currentNetworkCancelFunc()
  372. // All workers -- runTunnels, establishment workers, and auxilliary
  373. // workers such as fetch remote server list and untunneled uprade
  374. // download -- operate with the controller run context and will all
  375. // be interrupted when the run context is done.
  376. controller.runWaitGroup.Wait()
  377. NoticeInfo("exiting controller")
  378. NoticeExiting()
  379. }
  380. // SignalComponentFailure notifies the controller that an associated component has failed.
  381. // This will terminate the controller.
  382. func (controller *Controller) SignalComponentFailure() {
  383. NoticeWarning("controller shutdown due to component failure")
  384. controller.stopRunning()
  385. }
  386. // SetDynamicConfig overrides the sponsor ID and authorizations fields of the
  387. // Controller config with the input values. The new values will be used in the
  388. // next tunnel connection.
  389. func (controller *Controller) SetDynamicConfig(sponsorID string, authorizations []string) {
  390. controller.config.SetDynamicConfig(sponsorID, authorizations)
  391. }
  392. // NetworkChanged initiates a reset of all open network connections, including
  393. // a tunnel reconnect, if one is running, as well as terminating any in-proxy
  394. // proxy connections.
  395. func (controller *Controller) NetworkChanged() {
  396. // Explicitly reset components that don't use the current network context.
  397. controller.TerminateNextActiveTunnel()
  398. if controller.inproxyProxyBrokerClientManager != nil {
  399. controller.inproxyProxyBrokerClientManager.NetworkChanged()
  400. }
  401. controller.inproxyClientBrokerClientManager.NetworkChanged()
  402. controller.currentNetworkMutex.Lock()
  403. defer controller.currentNetworkMutex.Unlock()
  404. // Cancel the previous current network context, which will interrupt any
  405. // operations using this context.
  406. controller.currentNetworkCancelFunc()
  407. // Create a new context for the new current network.
  408. controller.currentNetworkCtx, controller.currentNetworkCancelFunc =
  409. context.WithCancel(context.Background())
  410. }
  411. func (controller *Controller) getCurrentNetworkContext() context.Context {
  412. controller.currentNetworkMutex.Lock()
  413. defer controller.currentNetworkMutex.Unlock()
  414. return controller.currentNetworkCtx
  415. }
  416. // TerminateNextActiveTunnel terminates the active tunnel, which will initiate
  417. // establishment of a new tunnel.
  418. func (controller *Controller) TerminateNextActiveTunnel() {
  419. tunnel := controller.getNextActiveTunnel()
  420. if tunnel != nil {
  421. controller.SignalTunnelFailure(tunnel)
  422. NoticeInfo("terminated tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  423. }
  424. }
  425. // ExportExchangePayload creates a payload for client-to-client server
  426. // connection info exchange. See the comment for psiphon.ExportExchangePayload
  427. // for more details.
  428. func (controller *Controller) ExportExchangePayload() string {
  429. return ExportExchangePayload(controller.config)
  430. }
  431. // ImportExchangePayload imports a payload generated by ExportExchangePayload.
  432. // See the comment for psiphon.ImportExchangePayload for more details about
  433. // the import.
  434. //
  435. // When the import is successful, a signal is set to trigger a restart any
  436. // establishment in progress. This will cause the newly imported server entry
  437. // to be prioritized, which it otherwise would not be in later establishment
  438. // rounds. The establishment process continues after ImportExchangePayload
  439. // returns.
  440. //
  441. // If the client already has a connected tunnel, or a tunnel connection is
  442. // established concurrently with the import, the signal has no effect as the
  443. // overall goal is establish _any_ connection.
  444. func (controller *Controller) ImportExchangePayload(payload string) bool {
  445. // Race condition: if a new tunnel connection is established concurrently
  446. // with the import, either that tunnel's server entry of the imported server
  447. // entry may end up as the affinity server.
  448. ok := ImportExchangePayload(controller.config, payload)
  449. if !ok {
  450. return false
  451. }
  452. select {
  453. case controller.signalRestartEstablishing <- struct{}{}:
  454. default:
  455. }
  456. return true
  457. }
  458. // remoteServerListFetcher fetches an out-of-band list of server entries
  459. // for more tunnel candidates. It fetches when signalled, with retries
  460. // on failure.
  461. func (controller *Controller) remoteServerListFetcher(
  462. name string,
  463. fetcher RemoteServerListFetcher,
  464. signal <-chan struct{}) {
  465. defer controller.runWaitGroup.Done()
  466. var lastFetchTime time.Time
  467. fetcherLoop:
  468. for {
  469. // Wait for a signal before fetching
  470. select {
  471. case <-signal:
  472. case <-controller.runCtx.Done():
  473. break fetcherLoop
  474. }
  475. // Skip fetch entirely (i.e., send no request at all, even when ETag would save
  476. // on response size) when a recent fetch was successful
  477. stalePeriod := controller.config.GetParameters().Get().Duration(
  478. parameters.FetchRemoteServerListStalePeriod)
  479. if !lastFetchTime.IsZero() &&
  480. lastFetchTime.Add(stalePeriod).After(time.Now()) {
  481. continue
  482. }
  483. retryLoop:
  484. for attempt := 0; ; attempt++ {
  485. // Don't attempt to fetch while there is no network connectivity,
  486. // to avoid alert notice noise.
  487. if !WaitForNetworkConnectivity(
  488. controller.runCtx,
  489. controller.config.NetworkConnectivityChecker,
  490. nil) {
  491. break fetcherLoop
  492. }
  493. // Pick any active tunnel and make the next fetch attempt. If there's
  494. // no active tunnel, the untunneledDialConfig will be used.
  495. tunnel := controller.getNextActiveTunnel()
  496. err := fetcher(
  497. controller.runCtx,
  498. controller.config,
  499. attempt,
  500. tunnel,
  501. controller.untunneledDialConfig)
  502. if err == nil {
  503. lastFetchTime = time.Now()
  504. break retryLoop
  505. }
  506. NoticeWarning("failed to fetch %s remote server list: %v",
  507. name, errors.Trace(err))
  508. retryPeriod := controller.config.GetParameters().Get().Duration(
  509. parameters.FetchRemoteServerListRetryPeriod)
  510. timer := time.NewTimer(retryPeriod)
  511. select {
  512. case <-timer.C:
  513. case <-controller.runCtx.Done():
  514. timer.Stop()
  515. break fetcherLoop
  516. }
  517. }
  518. }
  519. NoticeInfo("exiting %s remote server list fetcher", name)
  520. }
  521. // upgradeDownloader makes periodic attempts to complete a client upgrade
  522. // download. DownloadUpgrade() is resumable, so each attempt has potential for
  523. // getting closer to completion, even in conditions where the download or
  524. // tunnel is repeatedly interrupted.
  525. // An upgrade download is triggered by either a handshake response indicating
  526. // that a new version is available; or after failing to connect, in which case
  527. // it's useful to check, out-of-band, for an upgrade with new circumvention
  528. // capabilities.
  529. // Once the download operation completes successfully, the downloader exits
  530. // and is not run again: either there is not a newer version, or the upgrade
  531. // has been downloaded and is ready to be applied.
  532. // We're assuming that the upgrade will be applied and the entire system
  533. // restarted before another upgrade is to be downloaded.
  534. //
  535. // TODO: refactor upgrade downloader and remote server list fetcher to use
  536. // common code (including the resumable download routines).
  537. func (controller *Controller) upgradeDownloader() {
  538. defer controller.runWaitGroup.Done()
  539. var lastDownloadTime time.Time
  540. downloadLoop:
  541. for {
  542. // Wait for a signal before downloading
  543. var handshakeVersion string
  544. select {
  545. case handshakeVersion = <-controller.signalDownloadUpgrade:
  546. case <-controller.runCtx.Done():
  547. break downloadLoop
  548. }
  549. stalePeriod := controller.config.GetParameters().Get().Duration(
  550. parameters.FetchUpgradeStalePeriod)
  551. // Unless handshake is explicitly advertizing a new version, skip
  552. // checking entirely when a recent download was successful.
  553. if handshakeVersion == "" &&
  554. !lastDownloadTime.IsZero() &&
  555. lastDownloadTime.Add(stalePeriod).After(time.Now()) {
  556. continue
  557. }
  558. retryLoop:
  559. for attempt := 0; ; attempt++ {
  560. // Don't attempt to download while there is no network connectivity,
  561. // to avoid alert notice noise.
  562. if !WaitForNetworkConnectivity(
  563. controller.runCtx,
  564. controller.config.NetworkConnectivityChecker,
  565. nil) {
  566. break downloadLoop
  567. }
  568. // Pick any active tunnel and make the next download attempt. If there's
  569. // no active tunnel, the untunneledDialConfig will be used.
  570. tunnel := controller.getNextActiveTunnel()
  571. err := DownloadUpgrade(
  572. controller.runCtx,
  573. controller.config,
  574. attempt,
  575. handshakeVersion,
  576. tunnel,
  577. controller.untunneledDialConfig)
  578. if err == nil {
  579. lastDownloadTime = time.Now()
  580. break retryLoop
  581. }
  582. NoticeWarning("failed to download upgrade: %v", errors.Trace(err))
  583. timeout := controller.config.GetParameters().Get().Duration(
  584. parameters.FetchUpgradeRetryPeriod)
  585. timer := time.NewTimer(timeout)
  586. select {
  587. case <-timer.C:
  588. case <-controller.runCtx.Done():
  589. timer.Stop()
  590. break downloadLoop
  591. }
  592. }
  593. }
  594. NoticeInfo("exiting upgrade downloader")
  595. }
  596. type serverEntriesReportRequest struct {
  597. constraints *protocolSelectionConstraints
  598. }
  599. // serverEntriesReporter performs scans over all server entries to report on
  600. // available tunnel candidates, subject to protocol selection constraints, and
  601. // available egress regions.
  602. //
  603. // Because scans may be slow, depending on the client device and server entry
  604. // list size, serverEntriesReporter is used to perform asychronous, background
  605. // operations that would otherwise block establishment. This includes emitting
  606. // diagnotic notices that are informational (CandidateServers) or which do not
  607. // need to emit before establishment starts (AvailableEgressRegions).
  608. //
  609. // serverEntriesReporter also serves to combine these scans, which would
  610. // otherwise be logically independent, due to the performance impact of scans.
  611. //
  612. // Limitation: The underlying datastore implementation _may_ block write
  613. // transactions while there are open read transactions. For example, bolt
  614. // write transactions which need to re-map the data file (when the datastore
  615. // grows) will block on open read transactions. In these scenarios, a slow
  616. // scan will still block other operations.
  617. //
  618. // serverEntriesReporter runs beyond the establishment phase, since it's
  619. // important for notices such as AvailableEgressRegions to eventually emit
  620. // even if already established. serverEntriesReporter scans are cancellable,
  621. // so controller shutdown is not blocked by slow scans.
  622. func (controller *Controller) serverEntriesReporter() {
  623. defer controller.runWaitGroup.Done()
  624. loop:
  625. for {
  626. var request *serverEntriesReportRequest
  627. select {
  628. case request = <-controller.signalReportServerEntries:
  629. case <-controller.runCtx.Done():
  630. break loop
  631. }
  632. egressRegion := controller.config.EgressRegion
  633. constraints := request.constraints
  634. regions := make(map[string]bool)
  635. initialCandidates := 0
  636. candidates := 0
  637. callback := func(serverEntry *protocol.ServerEntry) bool {
  638. // In establishment, excludeIntensive depends on what set of protocols are
  639. // already being dialed. For these reports, don't exclude intensive
  640. // protocols as any intensive candidate can always be an available
  641. // candidate at some point.
  642. excludeIntensive := false
  643. isInitialCandidate := constraints.isInitialCandidate(excludeIntensive, serverEntry)
  644. isCandidate := constraints.isCandidate(excludeIntensive, serverEntry)
  645. if egressRegion == "" || serverEntry.Region == egressRegion {
  646. if isInitialCandidate {
  647. initialCandidates += 1
  648. }
  649. if isCandidate {
  650. candidates += 1
  651. }
  652. }
  653. isAvailable := isCandidate
  654. if constraints.hasInitialProtocols() {
  655. // Available egress regions is subject to an initial limit constraint, if
  656. // present: see AvailableEgressRegions comment in launchEstablishing.
  657. isAvailable = isInitialCandidate
  658. }
  659. if isAvailable {
  660. // Ignore server entries with no region field.
  661. if serverEntry.Region != "" {
  662. regions[serverEntry.Region] = true
  663. }
  664. }
  665. select {
  666. case <-controller.runCtx.Done():
  667. // Don't block controller shutdown: cancel the scan.
  668. return false
  669. default:
  670. return true
  671. }
  672. }
  673. startTime := time.Now()
  674. err := ScanServerEntries(callback)
  675. if err != nil {
  676. NoticeWarning("ScanServerEntries failed: %v", errors.Trace(err))
  677. continue
  678. }
  679. // Report this duration in CandidateServers as an indication of datastore
  680. // performance.
  681. duration := time.Since(startTime)
  682. NoticeCandidateServers(
  683. controller.config.EgressRegion,
  684. constraints,
  685. initialCandidates,
  686. candidates,
  687. duration)
  688. availableEgressRegions := make([]string, 0, len(regions))
  689. for region := range regions {
  690. availableEgressRegions = append(availableEgressRegions, region)
  691. }
  692. NoticeAvailableEgressRegions(
  693. availableEgressRegions)
  694. }
  695. NoticeInfo("exiting server entries reporter")
  696. }
  697. // signalServerEntriesReporter triggers a new server entry report.The report
  698. // is considered to be informational and may or may not run, depending on
  699. // whether another run is already in progress.
  700. func (controller *Controller) signalServerEntriesReporter(
  701. request *serverEntriesReportRequest) {
  702. select {
  703. case controller.signalReportServerEntries <- request:
  704. default:
  705. }
  706. }
  707. // connectedReporter sends periodic "connected" requests to the Psiphon API.
  708. // These requests are for server-side unique user stats calculation. See the
  709. // comment in DoConnectedRequest for a description of the request mechanism.
  710. //
  711. // To correctly count daily unique users, only one connected request is made
  712. // across all simultaneous multi-tunnels; and the connected request is
  713. // repeated every 24h.
  714. //
  715. // The signalReportConnected mechanism is used to trigger a connected request
  716. // immediately after a reconnect. While strictly only one connected request
  717. // per 24h is required in order to count daily unique users, the connected
  718. // request also delivers the establishment duration metric (which includes
  719. // time elapsed performing the handshake request) and additional fragmentation
  720. // metrics; these metrics are measured for each tunnel.
  721. func (controller *Controller) connectedReporter() {
  722. defer controller.runWaitGroup.Done()
  723. // session is nil when DisableApi is set
  724. if controller.config.DisableApi {
  725. return
  726. }
  727. select {
  728. case <-controller.signalReportConnected:
  729. // Make the initial connected request
  730. case <-controller.runCtx.Done():
  731. return
  732. }
  733. loop:
  734. for {
  735. // Pick any active tunnel and make the next connected request. No error is
  736. // logged if there's no active tunnel, as that's not an unexpected
  737. // condition.
  738. reported := false
  739. tunnel := controller.getNextActiveTunnel()
  740. if tunnel != nil {
  741. err := tunnel.serverContext.DoConnectedRequest()
  742. if err == nil {
  743. reported = true
  744. } else {
  745. NoticeWarning("failed to make connected request: %v",
  746. errors.Trace(err))
  747. }
  748. }
  749. // Schedule the next connected request and wait. This duration is not a
  750. // dynamic ClientParameter as the daily unique user stats logic specifically
  751. // requires a "connected" request no more or less often than every 24h.
  752. var duration time.Duration
  753. if reported {
  754. duration = 24 * time.Hour
  755. } else {
  756. duration = controller.config.GetParameters().Get().Duration(
  757. parameters.PsiphonAPIConnectedRequestRetryPeriod)
  758. }
  759. timer := time.NewTimer(duration)
  760. doBreak := false
  761. select {
  762. case <-controller.signalReportConnected:
  763. case <-timer.C:
  764. // Make another connected request
  765. case <-controller.runCtx.Done():
  766. doBreak = true
  767. }
  768. timer.Stop()
  769. if doBreak {
  770. break loop
  771. }
  772. }
  773. NoticeInfo("exiting connected reporter")
  774. }
  775. func (controller *Controller) signalConnectedReporter() {
  776. // session is nil when DisableApi is set
  777. if controller.config.DisableApi {
  778. return
  779. }
  780. select {
  781. case controller.signalReportConnected <- struct{}{}:
  782. default:
  783. }
  784. }
  785. // establishTunnelWatcher terminates the controller if a tunnel
  786. // has not been established in the configured time period. This
  787. // is regardless of how many tunnels are presently active -- meaning
  788. // that if an active tunnel was established and lost the controller
  789. // is left running (to re-establish).
  790. func (controller *Controller) establishTunnelWatcher() {
  791. defer controller.runWaitGroup.Done()
  792. timeout := controller.config.GetParameters().Get().Duration(
  793. parameters.EstablishTunnelTimeout)
  794. if timeout > 0 {
  795. timer := time.NewTimer(timeout)
  796. defer timer.Stop()
  797. select {
  798. case <-timer.C:
  799. if !controller.hasEstablishedOnce() {
  800. NoticeEstablishTunnelTimeout(timeout)
  801. controller.SignalComponentFailure()
  802. }
  803. case <-controller.runCtx.Done():
  804. }
  805. }
  806. NoticeInfo("exiting establish tunnel watcher")
  807. }
  808. // runTunnels is the controller tunnel management main loop. It starts and stops
  809. // establishing tunnels based on the target tunnel pool size and the current size
  810. // of the pool. Tunnels are established asynchronously using worker goroutines.
  811. //
  812. // When there are no server entries for the target region/protocol, the
  813. // establishCandidateGenerator will yield no candidates and wait before
  814. // trying again. In the meantime, a remote server entry fetch may supply
  815. // valid candidates.
  816. //
  817. // When a tunnel is established, it's added to the active pool. The tunnel's
  818. // operateTunnel goroutine monitors the tunnel.
  819. //
  820. // When a tunnel fails, it's removed from the pool and the establish process is
  821. // restarted to fill the pool.
  822. func (controller *Controller) runTunnels() {
  823. defer controller.runWaitGroup.Done()
  824. // Start running
  825. controller.startEstablishing()
  826. loop:
  827. for {
  828. select {
  829. case <-controller.signalRestartEstablishing:
  830. // signalRestartEstablishing restarts any establishment in progress. One
  831. // use case for this is to prioritize a newly imported, exchanged server
  832. // entry, which will be in the affinity position.
  833. //
  834. // It's possible for another connection to establish concurrent to signalling;
  835. // since the overall goal remains to establish _any_ connection, we accept that
  836. // in some cases the exchanged server entry may not get used.
  837. if controller.isEstablishing {
  838. controller.stopEstablishing()
  839. controller.startEstablishing()
  840. }
  841. case failedTunnel := <-controller.failedTunnels:
  842. NoticeWarning("tunnel failed: %s", failedTunnel.dialParams.ServerEntry.GetDiagnosticID())
  843. controller.terminateTunnel(failedTunnel)
  844. // Clear the reference to this tunnel before calling startEstablishing,
  845. // which will invoke a garbage collection.
  846. failedTunnel = nil
  847. // Concurrency note: only this goroutine may call startEstablishing/stopEstablishing,
  848. // which reference controller.isEstablishing.
  849. controller.startEstablishing()
  850. case connectedTunnel := <-controller.connectedTunnels:
  851. // Tunnel establishment has two phases: connection and activation.
  852. //
  853. // Connection is run concurrently by the establishTunnelWorkers, to minimize
  854. // delay when it's not yet known which server and protocol will be available
  855. // and unblocked.
  856. //
  857. // Activation is run serially, here, to minimize the overhead of making a
  858. // handshake request and starting the operateTunnel management worker for a
  859. // tunnel which may be discarded.
  860. //
  861. // When the active tunnel will complete establishment, establishment is
  862. // stopped before activation. This interrupts all connecting tunnels and
  863. // garbage collects their memory. The purpose is to minimize memory
  864. // pressure when the handshake request is made. In the unlikely case that the
  865. // handshake fails, establishment is restarted.
  866. //
  867. // Any delays in stopEstablishing will delay the handshake for the last
  868. // active tunnel.
  869. //
  870. // In the typical case of tunnelPoolSize of 1, only a single handshake is
  871. // performed and the homepages notices file, when used, will not be modifed
  872. // after the NoticeTunnels(1) [i.e., connected] until NoticeTunnels(0) [i.e.,
  873. // disconnected]. For tunnelPoolSize > 1, serial handshakes only ensures that
  874. // each set of emitted NoticeHomepages is contiguous.
  875. active, outstanding := controller.numTunnels()
  876. // discardTunnel will be true here when already fully established.
  877. discardTunnel := (outstanding <= 0)
  878. isFirstTunnel := (active == 0)
  879. isLastTunnel := (outstanding == 1)
  880. if !discardTunnel {
  881. if isLastTunnel {
  882. controller.stopEstablishing()
  883. }
  884. err := connectedTunnel.Activate(controller.runCtx, controller)
  885. if err != nil {
  886. NoticeWarning("failed to activate %s: %v",
  887. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(),
  888. errors.Trace(err))
  889. discardTunnel = true
  890. } else {
  891. // It's unlikely that registerTunnel will fail, since only this goroutine
  892. // calls registerTunnel -- and after checking numTunnels; so failure is not
  893. // expected.
  894. if !controller.registerTunnel(connectedTunnel) {
  895. NoticeWarning("failed to register %s: %v",
  896. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(),
  897. errors.Trace(err))
  898. discardTunnel = true
  899. }
  900. }
  901. // May need to replace this tunnel
  902. if isLastTunnel && discardTunnel {
  903. controller.startEstablishing()
  904. }
  905. }
  906. if discardTunnel {
  907. controller.discardTunnel(connectedTunnel)
  908. // Clear the reference to this discarded tunnel and immediately run
  909. // a garbage collection to reclaim its memory.
  910. connectedTunnel = nil
  911. DoGarbageCollection()
  912. // Skip the rest of this case
  913. break
  914. }
  915. atomic.AddInt32(&controller.establishedTunnelsCount, 1)
  916. NoticeActiveTunnel(
  917. connectedTunnel.dialParams.ServerEntry.GetDiagnosticID(),
  918. connectedTunnel.dialParams.TunnelProtocol)
  919. NoticeConnectedServerRegion(connectedTunnel.dialParams.ServerEntry.Region)
  920. if isFirstTunnel {
  921. // Signal a connected request on each 1st tunnel establishment. For
  922. // multi-tunnels, the session is connected as long as at least one
  923. // tunnel is established.
  924. controller.signalConnectedReporter()
  925. // If the handshake indicated that a new client version is available,
  926. // trigger an upgrade download.
  927. // Note: serverContext is nil when DisableApi is set
  928. if connectedTunnel.serverContext != nil &&
  929. connectedTunnel.serverContext.clientUpgradeVersion != "" {
  930. handshakeVersion := connectedTunnel.serverContext.clientUpgradeVersion
  931. select {
  932. case controller.signalDownloadUpgrade <- handshakeVersion:
  933. default:
  934. }
  935. }
  936. }
  937. // Set the new tunnel as the transport for the packet tunnel. The packet tunnel
  938. // client remains up when reestablishing, but no packets are relayed while there
  939. // is no connected tunnel. UseTunnel will establish a new packet tunnel SSH
  940. // channel over the new SSH tunnel and configure the packet tunnel client to use
  941. // the new SSH channel as its transport.
  942. //
  943. // Note: as is, this logic is suboptimal for tunnelPoolSize > 1, as this would
  944. // continuously initialize new packet tunnel sessions for each established
  945. // server. For now, config validation requires tunnelPoolSize == 1 when
  946. // the packet tunnel is used.
  947. if controller.packetTunnelTransport != nil {
  948. controller.packetTunnelTransport.UseTunnel(connectedTunnel)
  949. }
  950. if controller.isFullyEstablished() {
  951. controller.stopEstablishing()
  952. }
  953. case <-controller.runCtx.Done():
  954. break loop
  955. }
  956. }
  957. // Stop running
  958. controller.stopEstablishing()
  959. controller.terminateAllTunnels()
  960. // Drain tunnel channels
  961. close(controller.connectedTunnels)
  962. for tunnel := range controller.connectedTunnels {
  963. controller.discardTunnel(tunnel)
  964. }
  965. close(controller.failedTunnels)
  966. for tunnel := range controller.failedTunnels {
  967. controller.discardTunnel(tunnel)
  968. }
  969. NoticeInfo("exiting run tunnels")
  970. }
  971. // SignalSeededNewSLOK implements the TunnelOwner interface. This function
  972. // is called by Tunnel.operateTunnel when the tunnel has received a new,
  973. // previously unknown SLOK from the server. The Controller triggers an OSL
  974. // fetch, as the new SLOK may be sufficient to access new OSLs.
  975. func (controller *Controller) SignalSeededNewSLOK() {
  976. select {
  977. case controller.signalFetchObfuscatedServerLists <- struct{}{}:
  978. default:
  979. }
  980. }
  981. // SignalTunnelFailure implements the TunnelOwner interface. This function
  982. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  983. // has failed. The Controller will signal runTunnels to create a new
  984. // tunnel and/or remove the tunnel from the list of active tunnels.
  985. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  986. // Don't block. Assumes the receiver has a buffer large enough for
  987. // the typical number of operated tunnels. In case there's no room,
  988. // terminate the tunnel (runTunnels won't get a signal in this case,
  989. // but the tunnel will be removed from the list of active tunnels).
  990. select {
  991. case controller.failedTunnels <- tunnel:
  992. default:
  993. controller.terminateTunnel(tunnel)
  994. }
  995. }
  996. // discardTunnel disposes of a successful connection that is no longer required.
  997. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  998. NoticeInfo("discard tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  999. // TODO: not calling PromoteServerEntry, since that would rank the
  1000. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  1001. // be promoted (since it connects), but with lower rank than all active
  1002. // tunnels?
  1003. tunnel.Close(true)
  1004. }
  1005. // registerTunnel adds the connected tunnel to the pool of active tunnels
  1006. // which are candidates for port forwarding. Returns true if the pool has an
  1007. // empty slot and false if the pool is full (caller should discard the tunnel).
  1008. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  1009. controller.tunnelMutex.Lock()
  1010. defer controller.tunnelMutex.Unlock()
  1011. if len(controller.tunnels) >= controller.tunnelPoolSize {
  1012. return false
  1013. }
  1014. // Perform a final check just in case we've established
  1015. // a duplicate connection.
  1016. for _, activeTunnel := range controller.tunnels {
  1017. if activeTunnel.dialParams.ServerEntry.IpAddress ==
  1018. tunnel.dialParams.ServerEntry.IpAddress {
  1019. NoticeWarning("duplicate tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  1020. return false
  1021. }
  1022. }
  1023. controller.establishedOnce = true
  1024. controller.tunnels = append(controller.tunnels, tunnel)
  1025. NoticeTunnels(len(controller.tunnels))
  1026. // Promote this successful tunnel to first rank so it's one
  1027. // of the first candidates next time establish runs.
  1028. // Connecting to a TargetServerEntry does not change the
  1029. // ranking.
  1030. if controller.config.TargetServerEntry == "" {
  1031. err := PromoteServerEntry(controller.config, tunnel.dialParams.ServerEntry.IpAddress)
  1032. if err != nil {
  1033. NoticeWarning("PromoteServerEntry failed: %v", errors.Trace(err))
  1034. // Proceed with using tunnel
  1035. }
  1036. }
  1037. return true
  1038. }
  1039. // hasEstablishedOnce indicates if at least one active tunnel has
  1040. // been established up to this point. This is regardeless of how many
  1041. // tunnels are presently active.
  1042. func (controller *Controller) hasEstablishedOnce() bool {
  1043. controller.tunnelMutex.Lock()
  1044. defer controller.tunnelMutex.Unlock()
  1045. return controller.establishedOnce
  1046. }
  1047. // isFullyEstablished indicates if the pool of active tunnels is full.
  1048. func (controller *Controller) isFullyEstablished() bool {
  1049. controller.tunnelMutex.Lock()
  1050. defer controller.tunnelMutex.Unlock()
  1051. return len(controller.tunnels) >= controller.tunnelPoolSize
  1052. }
  1053. // awaitFullyEstablished blocks until isFullyEstablished is true or the
  1054. // controller run ends.
  1055. func (controller *Controller) awaitFullyEstablished() bool {
  1056. // TODO: don't poll, add a signal
  1057. ticker := time.NewTicker(1 * time.Second)
  1058. defer ticker.Stop()
  1059. for {
  1060. if controller.isFullyEstablished() {
  1061. return true
  1062. }
  1063. select {
  1064. case <-ticker.C:
  1065. // Check isFullyEstablished again
  1066. case <-controller.runCtx.Done():
  1067. return false
  1068. }
  1069. }
  1070. }
  1071. // numTunnels returns the number of active and outstanding tunnels.
  1072. // Oustanding is the number of tunnels required to fill the pool of
  1073. // active tunnels.
  1074. func (controller *Controller) numTunnels() (int, int) {
  1075. controller.tunnelMutex.Lock()
  1076. defer controller.tunnelMutex.Unlock()
  1077. active := len(controller.tunnels)
  1078. outstanding := controller.tunnelPoolSize - len(controller.tunnels)
  1079. return active, outstanding
  1080. }
  1081. // terminateTunnel removes a tunnel from the pool of active tunnels
  1082. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  1083. // is adjusted as required.
  1084. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  1085. controller.tunnelMutex.Lock()
  1086. defer controller.tunnelMutex.Unlock()
  1087. for index, activeTunnel := range controller.tunnels {
  1088. if tunnel == activeTunnel {
  1089. controller.tunnels = append(
  1090. controller.tunnels[:index], controller.tunnels[index+1:]...)
  1091. if controller.nextTunnel > index {
  1092. controller.nextTunnel--
  1093. }
  1094. if controller.nextTunnel >= len(controller.tunnels) {
  1095. controller.nextTunnel = 0
  1096. }
  1097. activeTunnel.Close(false)
  1098. NoticeTunnels(len(controller.tunnels))
  1099. break
  1100. }
  1101. }
  1102. }
  1103. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  1104. // This is used when shutting down the controller.
  1105. func (controller *Controller) terminateAllTunnels() {
  1106. controller.tunnelMutex.Lock()
  1107. defer controller.tunnelMutex.Unlock()
  1108. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  1109. // may take a few seconds to send a final status request. We only want
  1110. // to wait as long as the single slowest tunnel.
  1111. closeWaitGroup := new(sync.WaitGroup)
  1112. closeWaitGroup.Add(len(controller.tunnels))
  1113. for _, activeTunnel := range controller.tunnels {
  1114. tunnel := activeTunnel
  1115. go func() {
  1116. defer closeWaitGroup.Done()
  1117. tunnel.Close(false)
  1118. }()
  1119. }
  1120. closeWaitGroup.Wait()
  1121. controller.tunnels = make([]*Tunnel, 0)
  1122. controller.nextTunnel = 0
  1123. NoticeTunnels(len(controller.tunnels))
  1124. }
  1125. // getNextActiveTunnel returns the next tunnel from the pool of active
  1126. // tunnels. Currently, tunnel selection order is simple round-robin.
  1127. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  1128. controller.tunnelMutex.Lock()
  1129. defer controller.tunnelMutex.Unlock()
  1130. if len(controller.tunnels) == 0 {
  1131. return nil
  1132. }
  1133. tunnel = controller.tunnels[controller.nextTunnel]
  1134. controller.nextTunnel =
  1135. (controller.nextTunnel + 1) % len(controller.tunnels)
  1136. return tunnel
  1137. }
  1138. // isActiveTunnelServerEntry is used to check if there's already
  1139. // an existing tunnel to a candidate server.
  1140. func (controller *Controller) isActiveTunnelServerEntry(
  1141. serverEntry *protocol.ServerEntry) bool {
  1142. controller.tunnelMutex.Lock()
  1143. defer controller.tunnelMutex.Unlock()
  1144. for _, activeTunnel := range controller.tunnels {
  1145. if activeTunnel.dialParams.ServerEntry.IpAddress == serverEntry.IpAddress {
  1146. return true
  1147. }
  1148. }
  1149. return false
  1150. }
  1151. func (controller *Controller) setTunnelPoolSize(tunnelPoolSize int) {
  1152. controller.tunnelMutex.Lock()
  1153. defer controller.tunnelMutex.Unlock()
  1154. if tunnelPoolSize < 1 {
  1155. tunnelPoolSize = 1
  1156. }
  1157. if tunnelPoolSize > MAX_TUNNEL_POOL_SIZE {
  1158. tunnelPoolSize = MAX_TUNNEL_POOL_SIZE
  1159. }
  1160. controller.tunnelPoolSize = tunnelPoolSize
  1161. }
  1162. func (controller *Controller) getTunnelPoolSize() int {
  1163. controller.tunnelMutex.Lock()
  1164. defer controller.tunnelMutex.Unlock()
  1165. return controller.tunnelPoolSize
  1166. }
  1167. // Dial selects an active tunnel and establishes a port forward
  1168. // connection through the selected tunnel. Failure to connect is considered
  1169. // a port forward failure, for the purpose of monitoring tunnel health.
  1170. //
  1171. // When split tunnel mode is enabled, the connection may be untunneled,
  1172. // depending on GeoIP classification of the destination.
  1173. //
  1174. // downstreamConn is an optional parameter which specifies a connection to be
  1175. // explicitly closed when the dialed connection is closed. For instance, this
  1176. // is used to close downstreamConn App<->LocalProxy connections when the
  1177. // related LocalProxy<->SshPortForward connections close.
  1178. func (controller *Controller) Dial(
  1179. remoteAddr string, downstreamConn net.Conn) (conn net.Conn, err error) {
  1180. tunnel := controller.getNextActiveTunnel()
  1181. if tunnel == nil {
  1182. return nil, errors.TraceNew("no active tunnels")
  1183. }
  1184. if !tunnel.config.IsSplitTunnelEnabled() {
  1185. tunneledConn, splitTunnel, err := tunnel.DialTCPChannel(
  1186. remoteAddr, false, downstreamConn)
  1187. if err != nil {
  1188. return nil, errors.Trace(err)
  1189. }
  1190. if splitTunnel {
  1191. return nil, errors.TraceNew(
  1192. "unexpected split tunnel classification")
  1193. }
  1194. return tunneledConn, nil
  1195. }
  1196. // In split tunnel mode, TCP port forwards to destinations in the same
  1197. // country as the client are untunneled.
  1198. //
  1199. // Split tunnel is implemented with assistence from the server to classify
  1200. // destinations as being in the same country as the client. The server knows
  1201. // the client's public IP GeoIP data, and, for clients with split tunnel mode
  1202. // enabled, the server resolves the port forward destination address and
  1203. // checks the destination IP GeoIP data.
  1204. //
  1205. // When the countries match, the server "rejects" the port forward with a
  1206. // distinct response that indicates to the client that an untunneled port
  1207. // foward should be established locally.
  1208. //
  1209. // The client maintains a classification cache that allows it to make
  1210. // untunneled port forwards without requiring a round trip to the server.
  1211. // Only destinations classified as untunneled are stored in the cache: a
  1212. // destination classified as tunneled requires the same round trip as an
  1213. // unknown destination.
  1214. //
  1215. // When the countries do not match, the server establishes a port forward, as
  1216. // it does for all port forwards in non-split tunnel mode. There is no
  1217. // additional round trip for tunneled port forwards.
  1218. //
  1219. // Each destination includes a host and port. Since there are special
  1220. // cases where the server performs transparent redirection for specific
  1221. // host:port combinations, including UDPInterceptUdpgwServerAddress, the
  1222. // classification can differ for the same host but different ports and so
  1223. // the classification is cached using the full address, host:port, as the
  1224. // key. While this results in additional classification round trips for
  1225. // destinations with the same domain but differing ports, in practise
  1226. // most destinations use only port 443.
  1227. untunneledCache := controller.untunneledSplitTunnelClassifications
  1228. // If the destination is in the untunneled split tunnel classifications
  1229. // cache, skip the round trip to the server and do the direct, untunneled
  1230. // dial immediately.
  1231. _, cachedUntunneled := untunneledCache.Get(remoteAddr)
  1232. if !cachedUntunneled {
  1233. tunneledConn, splitTunnel, err := tunnel.DialTCPChannel(
  1234. remoteAddr, false, downstreamConn)
  1235. if err != nil {
  1236. return nil, errors.Trace(err)
  1237. }
  1238. if !splitTunnel {
  1239. // Clear any cached untunneled classification entry for this
  1240. // destination, as the server is now classifying it as tunneled.
  1241. untunneledCache.Delete(remoteAddr)
  1242. return tunneledConn, nil
  1243. }
  1244. // The server has indicated that the client should make a direct,
  1245. // untunneled dial. Cache the classification to avoid this round trip in
  1246. // the immediate future.
  1247. untunneledCache.Set(remoteAddr, true, lrucache.DefaultExpiration)
  1248. }
  1249. NoticeUntunneled(remoteAddr)
  1250. untunneledConn, err := controller.DirectDial(remoteAddr)
  1251. if err != nil {
  1252. return nil, errors.Trace(err)
  1253. }
  1254. return untunneledConn, nil
  1255. }
  1256. // DirectDial dials an untunneled TCP connection within the controller run context.
  1257. func (controller *Controller) DirectDial(remoteAddr string) (conn net.Conn, err error) {
  1258. return DialTCP(controller.runCtx, remoteAddr, controller.untunneledDialConfig)
  1259. }
  1260. // triggerFetches signals RSL, OSL, and upgrade download fetchers to begin, if
  1261. // not already running. triggerFetches is called when tunnel establishment
  1262. // fails to complete within a deadline and in other cases where local
  1263. // circumvention capabilities are lacking and we may require new server
  1264. // entries or client versions with new capabilities.
  1265. func (controller *Controller) triggerFetches() {
  1266. // Trigger a common remote server list fetch, since we may have failed
  1267. // to connect with all known servers. Don't block sending signal, since
  1268. // this signal may have already been sent.
  1269. // Don't wait for fetch remote to succeed, since it may fail and
  1270. // enter a retry loop and we're better off trying more known servers.
  1271. // TODO: synchronize the fetch response, so it can be incorporated
  1272. // into the server entry iterator as soon as available.
  1273. select {
  1274. case controller.signalFetchCommonRemoteServerList <- struct{}{}:
  1275. default:
  1276. }
  1277. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  1278. // so that if one out of the common RLS and OSL set is large, it doesn't
  1279. // doesn't entirely block fetching the other.
  1280. select {
  1281. case controller.signalFetchObfuscatedServerLists <- struct{}{}:
  1282. default:
  1283. }
  1284. // Trigger an out-of-band upgrade availability check and download.
  1285. // Since we may have failed to connect, we may benefit from upgrading
  1286. // to a new client version with new circumvention capabilities.
  1287. select {
  1288. case controller.signalDownloadUpgrade <- "":
  1289. default:
  1290. }
  1291. }
  1292. type protocolSelectionConstraints struct {
  1293. config *Config
  1294. initialLimitTunnelProtocols protocol.TunnelProtocols
  1295. initialLimitTunnelProtocolsCandidateCount int
  1296. limitTunnelProtocols protocol.TunnelProtocols
  1297. limitTunnelDialPortNumbers protocol.TunnelProtocolPortLists
  1298. limitQUICVersions protocol.QUICVersions
  1299. replayCandidateCount int
  1300. inproxyClientDialRateLimiter *rate.Limiter
  1301. }
  1302. func (p *protocolSelectionConstraints) hasInitialProtocols() bool {
  1303. return len(p.initialLimitTunnelProtocols) > 0 && p.initialLimitTunnelProtocolsCandidateCount > 0
  1304. }
  1305. func (p *protocolSelectionConstraints) isInitialCandidate(
  1306. excludeIntensive bool,
  1307. serverEntry *protocol.ServerEntry) bool {
  1308. return p.hasInitialProtocols() &&
  1309. len(serverEntry.GetSupportedProtocols(
  1310. conditionallyEnabledComponents{},
  1311. p.config.UseUpstreamProxy(),
  1312. p.initialLimitTunnelProtocols,
  1313. p.limitTunnelDialPortNumbers,
  1314. p.limitQUICVersions,
  1315. excludeIntensive,
  1316. false)) > 0
  1317. }
  1318. func (p *protocolSelectionConstraints) isCandidate(
  1319. excludeIntensive bool,
  1320. serverEntry *protocol.ServerEntry) bool {
  1321. return len(serverEntry.GetSupportedProtocols(
  1322. conditionallyEnabledComponents{},
  1323. p.config.UseUpstreamProxy(),
  1324. p.limitTunnelProtocols,
  1325. p.limitTunnelDialPortNumbers,
  1326. p.limitQUICVersions,
  1327. excludeIntensive,
  1328. false)) > 0
  1329. }
  1330. func (p *protocolSelectionConstraints) canReplay(
  1331. connectTunnelCount int,
  1332. excludeIntensive bool,
  1333. serverEntry *protocol.ServerEntry,
  1334. replayProtocol string) bool {
  1335. if p.replayCandidateCount != -1 && connectTunnelCount > p.replayCandidateCount {
  1336. return false
  1337. }
  1338. return common.Contains(
  1339. p.supportedProtocols(
  1340. connectTunnelCount, excludeIntensive, false, serverEntry),
  1341. replayProtocol)
  1342. }
  1343. func (p *protocolSelectionConstraints) getLimitTunnelProtocols(
  1344. connectTunnelCount int) protocol.TunnelProtocols {
  1345. protocols := p.limitTunnelProtocols
  1346. if len(p.initialLimitTunnelProtocols) > 0 &&
  1347. p.initialLimitTunnelProtocolsCandidateCount > connectTunnelCount {
  1348. protocols = p.initialLimitTunnelProtocols
  1349. }
  1350. return protocols
  1351. }
  1352. func (p *protocolSelectionConstraints) supportedProtocols(
  1353. connectTunnelCount int,
  1354. excludeIntensive bool,
  1355. excludeInproxy bool,
  1356. serverEntry *protocol.ServerEntry) []string {
  1357. return serverEntry.GetSupportedProtocols(
  1358. conditionallyEnabledComponents{},
  1359. p.config.UseUpstreamProxy(),
  1360. p.getLimitTunnelProtocols(connectTunnelCount),
  1361. p.limitTunnelDialPortNumbers,
  1362. p.limitQUICVersions,
  1363. excludeIntensive,
  1364. excludeInproxy)
  1365. }
  1366. func (p *protocolSelectionConstraints) selectProtocol(
  1367. connectTunnelCount int,
  1368. excludeIntensive bool,
  1369. excludeInproxy bool,
  1370. serverEntry *protocol.ServerEntry) (string, time.Duration, bool) {
  1371. candidateProtocols := p.supportedProtocols(
  1372. connectTunnelCount, excludeIntensive, excludeInproxy, serverEntry)
  1373. if len(candidateProtocols) == 0 {
  1374. return "", 0, false
  1375. }
  1376. // Pick at random from the supported protocols. This ensures that we'll
  1377. // eventually try all possible protocols. Depending on network
  1378. // configuration, it may be the case that some protocol is only available
  1379. // through multi-capability servers, and a simpler ranked preference of
  1380. // protocols could lead to that protocol never being selected.
  1381. selectedProtocol := candidateProtocols[prng.Intn(len(candidateProtocols))]
  1382. if !protocol.TunnelProtocolUsesInproxy(selectedProtocol) ||
  1383. p.inproxyClientDialRateLimiter == nil {
  1384. return selectedProtocol, 0, true
  1385. }
  1386. // Rate limit in-proxy dials. This avoids triggering rate limits or
  1387. // similar errors from any intermediate CDN between the client and the
  1388. // broker. And avoids unnecessarily triggering the broker's
  1389. // application-level rate limiter, which will incur some overhead logging
  1390. // an event and returning a response.
  1391. //
  1392. // In personal pairing mode, or when protocol limits yield only in-proxy
  1393. // tunnel protocol candidates, no non-in-proxy protocol can be selected,
  1394. // so delay the dial. In other cases, skip the candidate and pick a
  1395. // non-in-proxy tunnel protocol.
  1396. //
  1397. // The delay is not applied here since the caller is holding the
  1398. // concurrentEstablishTunnelsMutex lock, potentially blocking other
  1399. // establishment workers. Instead the delay is returned and applied
  1400. // outside of the lock. This also allows for the delay to be reduced when
  1401. // the StaggerConnectionWorkers facility is active.
  1402. //
  1403. // Limitation: potential fast dial failures may cause excess rate
  1404. // limiting, since tokens are consumed even if the dial fails before a
  1405. // request arrives at the broker. WaitForNetworkConnectivity, when
  1406. // configured, should pause calls to selectProtocol, although there are
  1407. // other possible fast fail cases.
  1408. //
  1409. // TODO: replace token on fast failure that doesn't reach the broker?
  1410. if p.config.IsInproxyClientPersonalPairingMode() ||
  1411. p.getLimitTunnelProtocols(connectTunnelCount).IsOnlyInproxyTunnelProtocols() {
  1412. // Check for missing in-proxy broker request requirements before
  1413. // consuming a rate limit token.
  1414. //
  1415. // As a potential future enhancement, these checks, particularly
  1416. // haveInproxyCommonCompartmentIDs which reads and unmarshals a data
  1417. // store record, could be cached.
  1418. if !haveInproxyClientBrokerSpecs(p.config) {
  1419. NoticeInfo("in-proxy protocol selection failed: no broker specs")
  1420. return "", 0, false
  1421. }
  1422. if !p.config.IsInproxyClientPersonalPairingMode() &&
  1423. !haveInproxyCommonCompartmentIDs(p.config) {
  1424. NoticeInfo("in-proxy protocol selection failed: no common compartment IDs")
  1425. return "", 0, false
  1426. }
  1427. r := p.inproxyClientDialRateLimiter.Reserve()
  1428. if !r.OK() {
  1429. NoticeInfo("in-proxy protocol selection rate limited: burst size exceeded")
  1430. return "", 0, false
  1431. }
  1432. delay := r.Delay()
  1433. if delay > 0 {
  1434. NoticeInfo("in-proxy protocol selection rate limited: %v", delay)
  1435. }
  1436. return selectedProtocol, delay, true
  1437. } else {
  1438. // Check for missing in-proxy broker request requirements before
  1439. // consuming a rate limit token.
  1440. skip := true
  1441. if !haveInproxyClientBrokerSpecs(p.config) {
  1442. NoticeInfo("in-proxy protocol selection skipped: no broker specs")
  1443. } else if !haveInproxyCommonCompartmentIDs(p.config) {
  1444. NoticeInfo("in-proxy protocol selection skipped: no common compartment IDs")
  1445. } else if !p.inproxyClientDialRateLimiter.Allow() {
  1446. NoticeInfo("in-proxy protocol selection skipped: rate limit exceeded")
  1447. } else {
  1448. skip = false
  1449. }
  1450. if skip {
  1451. excludeInproxy = true
  1452. candidateProtocols = p.supportedProtocols(
  1453. connectTunnelCount, excludeIntensive, excludeInproxy, serverEntry)
  1454. if len(candidateProtocols) == 0 {
  1455. return "", 0, false
  1456. }
  1457. return candidateProtocols[prng.Intn(len(candidateProtocols))], 0, true
  1458. }
  1459. }
  1460. return selectedProtocol, 0, true
  1461. }
  1462. type candidateServerEntry struct {
  1463. serverEntry *protocol.ServerEntry
  1464. isServerAffinityCandidate bool
  1465. adjustedEstablishStartTime time.Time
  1466. }
  1467. // startEstablishing creates a pool of worker goroutines which will
  1468. // attempt to establish tunnels to candidate servers. The candidates
  1469. // are generated by another goroutine.
  1470. func (controller *Controller) startEstablishing() {
  1471. if controller.isEstablishing {
  1472. return
  1473. }
  1474. NoticeInfo("start establishing")
  1475. // establishStartTime is used to calculate and report the client's tunnel
  1476. // establishment duration. Establishment duration should include all
  1477. // initialization in launchEstablishing and establishCandidateGenerator,
  1478. // including any potentially long-running datastore iterations.
  1479. establishStartTime := time.Now()
  1480. controller.concurrentEstablishTunnelsMutex.Lock()
  1481. controller.establishConnectTunnelCount = 0
  1482. controller.concurrentEstablishTunnels = 0
  1483. controller.concurrentIntensiveEstablishTunnels = 0
  1484. controller.peakConcurrentEstablishTunnels = 0
  1485. controller.peakConcurrentIntensiveEstablishTunnels = 0
  1486. controller.concurrentEstablishTunnelsMutex.Unlock()
  1487. DoGarbageCollection()
  1488. emitMemoryMetrics()
  1489. // The establish context cancelFunc, controller.stopEstablish, is called in
  1490. // controller.stopEstablishing.
  1491. controller.isEstablishing = true
  1492. controller.establishStartTime = establishStartTime
  1493. controller.establishCtx, controller.stopEstablish = context.WithCancel(controller.runCtx)
  1494. controller.establishWaitGroup = new(sync.WaitGroup)
  1495. controller.candidateServerEntries = make(chan *candidateServerEntry)
  1496. // The server affinity mechanism attempts to favor the previously
  1497. // used server when reconnecting. This is beneficial for user
  1498. // applications which expect consistency in user IP address (for
  1499. // example, a web site which prompts for additional user
  1500. // authentication when the IP address changes).
  1501. //
  1502. // Only the very first server, as determined by
  1503. // datastore.PromoteServerEntry(), is the server affinity candidate.
  1504. // Concurrent connections attempts to many servers are launched
  1505. // without delay, in case the affinity server connection fails.
  1506. // While the affinity server connection is outstanding, when any
  1507. // other connection is established, there is a short grace period
  1508. // delay before delivering the established tunnel; this allows some
  1509. // time for the affinity server connection to succeed first.
  1510. // When the affinity server connection fails, any other established
  1511. // tunnel is registered without delay.
  1512. //
  1513. // Note: the establishTunnelWorker that receives the affinity
  1514. // candidate is solely resonsible for closing
  1515. // controller.serverAffinityDoneBroadcast.
  1516. controller.serverAffinityDoneBroadcast = make(chan struct{})
  1517. // TODO: Add a buffer of 1 so we don't miss a signal while worker is
  1518. // starting? Trade-off is potential back-to-back fetches. As-is,
  1519. // establish will eventually signal another fetch.
  1520. controller.establishSignalForceTacticsFetch = make(chan struct{})
  1521. // Initialize the in-proxy client dial rate limiter. Rate limits are used in
  1522. // protocolSelectionConstraints.selectProtocol. When
  1523. // InproxyClientDialRateLimitQuantity is 0, there is no rate limit.
  1524. //
  1525. // The rate limiter is reset for each establishment, which ensures no
  1526. // delays carry over from a previous establishment run. However, this
  1527. // does mean that very frequent re-establishments may exceed the rate
  1528. // limit overall.
  1529. p := controller.config.GetParameters().Get()
  1530. inproxyRateLimitQuantity := p.Int(parameters.InproxyClientDialRateLimitQuantity)
  1531. inproxyRateLimitInterval := p.Duration(parameters.InproxyClientDialRateLimitInterval)
  1532. if inproxyRateLimitQuantity > 0 {
  1533. controller.inproxyClientDialRateLimiter = rate.NewLimiter(
  1534. rate.Limit(float64(inproxyRateLimitQuantity)/inproxyRateLimitInterval.Seconds()),
  1535. inproxyRateLimitQuantity)
  1536. }
  1537. p.Close()
  1538. controller.establishWaitGroup.Add(1)
  1539. go controller.launchEstablishing()
  1540. }
  1541. func (controller *Controller) launchEstablishing() {
  1542. defer controller.establishWaitGroup.Done()
  1543. // Before starting the establish tunnel workers, get and apply tactics,
  1544. // launching a tactics request if required -- when there are no tactics,
  1545. // or the cached tactics have expired.
  1546. //
  1547. // Wait only TacticsWaitPeriod for the tactics request to complete (or
  1548. // fail) before proceeding with tunnel establishment, in case the tactics
  1549. // request is blocked or takes very long to complete.
  1550. //
  1551. // An in-flight tactics request uses meek in round tripper mode, which
  1552. // uses less resources than meek tunnel relay mode. For this reason, the
  1553. // tactics request is not counted in concurrentIntensiveEstablishTunnels.
  1554. //
  1555. // TODO: HTTP/2 uses significantly more memory, so perhaps
  1556. // concurrentIntensiveEstablishTunnels should be counted in that case.
  1557. //
  1558. // Any in-flight tactics request or pending retry will be
  1559. // canceled when establishment is stopped.
  1560. //
  1561. // In some cases, no tunnel establishment can succeed without a fresh
  1562. // tactics fetch, even if there is existing, non-expired cached tactics.
  1563. // Currently, cases include in-proxy personal pairing mode and limiting
  1564. // tunnel protocols to in-proxy, where broker specs are both required and
  1565. // obtained exclusively from tactics. It is possible that cached tactics
  1566. // are found and used, but broker configurations have recently changed
  1567. // away from the broker specs in cached tactics.
  1568. //
  1569. // Another scenario, with exclusively in-proxy tunnel protocols, is a
  1570. // fresh start with no embedded server entries, where the initial
  1571. // GetTactics will fail with "no capable servers".
  1572. //
  1573. // To handle these cases, when cached tactics are used or no tactics can
  1574. // be fetched, the tactics worker goroutine will remain running and await
  1575. // a signal to force a tactics fetch that ignores any stored/cached
  1576. // tactics. Multiple signals and fetch attempts are supported, to retry
  1577. // when a GetTactics fetch iteration fails, including the "no capable
  1578. // servers" case, which may only succeed after a concurrent server list
  1579. // fetch completes.
  1580. //
  1581. // Limitation: this mechanism doesn't force repeated tactics fetches after
  1582. // one success, which risks being excessive. There's at most one
  1583. // successful fetch per establishment run. As such, it remains remotely
  1584. // possible that a tactics change, such as new broker specs, deployed in
  1585. // the middle of an establishment run, won't be fetched. A user-initiated
  1586. // stop/start toggle will work around this.
  1587. if !controller.config.DisableTactics {
  1588. timeout := controller.config.GetParameters().Get().Duration(
  1589. parameters.TacticsWaitPeriod)
  1590. initialTacticsDone := make(chan struct{})
  1591. tacticsWaitPeriod := time.NewTimer(timeout)
  1592. defer tacticsWaitPeriod.Stop()
  1593. controller.establishWaitGroup.Add(1)
  1594. go func() {
  1595. defer controller.establishWaitGroup.Done()
  1596. useStoredTactics := true
  1597. fetched := GetTactics(
  1598. controller.establishCtx, controller.config, useStoredTactics)
  1599. close(initialTacticsDone)
  1600. if fetched {
  1601. return
  1602. }
  1603. for {
  1604. select {
  1605. case <-controller.establishCtx.Done():
  1606. return
  1607. case <-controller.establishSignalForceTacticsFetch:
  1608. }
  1609. useStoredTactics = false
  1610. fetched = GetTactics(
  1611. controller.establishCtx, controller.config, useStoredTactics)
  1612. if fetched {
  1613. // No more forced tactics fetches after the first success.
  1614. break
  1615. }
  1616. }
  1617. }()
  1618. select {
  1619. case <-initialTacticsDone:
  1620. case <-tacticsWaitPeriod.C:
  1621. }
  1622. tacticsWaitPeriod.Stop()
  1623. if controller.isStopEstablishing() {
  1624. // This check isn't strictly required but avoids the overhead of launching
  1625. // workers if establishment stopped while awaiting a tactics request.
  1626. return
  1627. }
  1628. }
  1629. // Initial- and LimitTunnelProtocols may be set by tactics.
  1630. //
  1631. // These protocol limits are fixed once per establishment, for
  1632. // consistent application of related probabilities (applied by
  1633. // ParametersAccessor.TunnelProtocols). The
  1634. // establishLimitTunnelProtocolsState field must be read-only after this
  1635. // point, allowing concurrent reads by establishment workers.
  1636. p := controller.config.GetParameters().Get()
  1637. controller.protocolSelectionConstraints = &protocolSelectionConstraints{
  1638. config: controller.config,
  1639. initialLimitTunnelProtocols: p.TunnelProtocols(parameters.InitialLimitTunnelProtocols),
  1640. initialLimitTunnelProtocolsCandidateCount: p.Int(parameters.InitialLimitTunnelProtocolsCandidateCount),
  1641. limitTunnelProtocols: p.TunnelProtocols(parameters.LimitTunnelProtocols),
  1642. limitTunnelDialPortNumbers: protocol.TunnelProtocolPortLists(
  1643. p.TunnelProtocolPortLists(parameters.LimitTunnelDialPortNumbers)),
  1644. replayCandidateCount: p.Int(parameters.ReplayCandidateCount),
  1645. inproxyClientDialRateLimiter: controller.inproxyClientDialRateLimiter,
  1646. }
  1647. // Adjust protocol limits for in-proxy personal proxy mode. In this mode,
  1648. // the client will make connections only through a proxy with the
  1649. // corresponding personal compartment ID, so non-in-proxy tunnel
  1650. // protocols are disabled.
  1651. if controller.config.IsInproxyClientPersonalPairingMode() {
  1652. if len(controller.protocolSelectionConstraints.initialLimitTunnelProtocols) > 0 {
  1653. controller.protocolSelectionConstraints.initialLimitTunnelProtocols =
  1654. controller.protocolSelectionConstraints.
  1655. initialLimitTunnelProtocols.PruneNonInproxyTunnelProtocols()
  1656. }
  1657. if len(controller.protocolSelectionConstraints.limitTunnelProtocols) > 0 {
  1658. controller.protocolSelectionConstraints.limitTunnelProtocols =
  1659. controller.protocolSelectionConstraints.
  1660. limitTunnelProtocols.PruneNonInproxyTunnelProtocols()
  1661. }
  1662. // This covers two cases: if there was no limitTunnelProtocols to
  1663. // start, then limit to any in-proxy tunnel protocol; or, if there
  1664. // was a limit but OnlyInproxyTunnelProtocols evaluates to an empty
  1665. // list, also set the limit to any in-proxy tunnel protocol.
  1666. if len(controller.protocolSelectionConstraints.limitTunnelProtocols) == 0 {
  1667. controller.protocolSelectionConstraints.limitTunnelProtocols =
  1668. protocol.InproxyTunnelProtocols
  1669. }
  1670. }
  1671. // ConnectionWorkerPoolSize may be set by tactics.
  1672. //
  1673. // In-proxy personal pairing mode uses a distinct parameter which is
  1674. // typically configured to a lower number, limiting concurrent load and
  1675. // announcement consumption for personal proxies.
  1676. var workerPoolSize int
  1677. if controller.config.IsInproxyClientPersonalPairingMode() {
  1678. workerPoolSize = p.Int(parameters.InproxyPersonalPairingConnectionWorkerPoolSize)
  1679. } else {
  1680. workerPoolSize = p.Int(parameters.ConnectionWorkerPoolSize)
  1681. }
  1682. // When TargetServerEntry is used, override any worker pool size config or
  1683. // tactic parameter and use a pool size of 1. The typical use case for
  1684. // TargetServerEntry is to test a specific server with a single connection
  1685. // attempt. Furthermore, too many concurrent attempts to connect to the
  1686. // same server will trigger rate limiting.
  1687. if controller.config.TargetServerEntry != "" {
  1688. workerPoolSize = 1
  1689. }
  1690. // TunnelPoolSize may be set by tactics, subject to local constraints. A pool
  1691. // size of one is forced in packet tunnel mode or when using a
  1692. // TargetServerEntry. The tunnel pool size is reduced when there are
  1693. // insufficent known server entries, within the set region and protocol
  1694. // constraints, to satisfy the target.
  1695. //
  1696. // Limitations, to simplify concurrent access to shared state: a ceiling of
  1697. // MAX_TUNNEL_POOL_SIZE is enforced by setTunnelPoolSize; the tunnel pool
  1698. // size target is not re-adjusted after an API handshake, even though the
  1699. // handshake response may deliver new tactics, or prune server entries which
  1700. // were potential candidates; nor is the target re-adjusted after fetching
  1701. // new server entries during this establishment.
  1702. tunnelPoolSize := p.Int(parameters.TunnelPoolSize)
  1703. if controller.config.PacketTunnelTunFileDescriptor > 0 ||
  1704. controller.config.TargetServerEntry != "" {
  1705. tunnelPoolSize = 1
  1706. }
  1707. controller.setTunnelPoolSize(tunnelPoolSize)
  1708. p.Close()
  1709. // Trigger CandidateServers and AvailableEgressRegions notices. By default,
  1710. // this is an asynchronous operation, as the underlying full server entry
  1711. // list enumeration may be a slow operation.
  1712. //
  1713. // AvailableEgressRegions: after a fresh install, the outer client may not
  1714. // have a list of regions to display; and LimitTunnelProtocols may reduce the
  1715. // number of available regions.
  1716. //
  1717. // When the outer client receives NoticeAvailableEgressRegions and the
  1718. // configured EgressRegion is not included in the region list, the outer
  1719. // client _should_ stop tunnel-core and prompt the user to change the region
  1720. // selection, as there are insufficient servers/capabilities to establish a
  1721. // tunnel in the selected region.
  1722. //
  1723. // This report is delayed until after tactics are likely to be applied,
  1724. // above; this avoids a ReportAvailableRegions reporting too many regions,
  1725. // followed shortly by a ReportAvailableRegions reporting fewer regions. That
  1726. // sequence could cause issues in the outer client UI.
  1727. //
  1728. // The reported regions are limited by protocolSelectionConstraints; in the
  1729. // case where an initial limit is in place, only regions available for the
  1730. // initial limit are reported. The initial phase will not complete if
  1731. // EgressRegion is set such that there are no server entries with the
  1732. // necessary protocol capabilities (either locally or from a remote server
  1733. // list fetch).
  1734. // Concurrency note: controller.protocolSelectionConstraints and its
  1735. // fields may be overwritten before serverEntriesReporter reads it, and
  1736. // so cannot be accessed directly by serverEntriesReporter.
  1737. //
  1738. // Limitation: the non-deep copy here shares slices (tunnel protocol
  1739. // lists) with the original; the contents of these slices don't change
  1740. // past this point. The rate limiter should not be used by
  1741. // serverEntriesReporter, but is cleared just in case.
  1742. copyConstraints := *controller.protocolSelectionConstraints
  1743. copyConstraints.inproxyClientDialRateLimiter = nil
  1744. controller.signalServerEntriesReporter(
  1745. &serverEntriesReportRequest{
  1746. constraints: &copyConstraints,
  1747. })
  1748. if controller.protocolSelectionConstraints.hasInitialProtocols() ||
  1749. tunnelPoolSize > 1 {
  1750. // Perform a synchronous scan over server entries in order to check if
  1751. // there are sufficient candidates to satisfy any initial tunnel
  1752. // protocol limit constraint and/or tunnel pool size > 1. If these
  1753. // requirements can't be met, the constraint and/or pool size are
  1754. // adjusted in order to avoid spinning unable to select any protocol
  1755. // or trying to establish more tunnels than is possible.
  1756. controller.doConstraintsScan()
  1757. }
  1758. for i := 0; i < workerPoolSize; i++ {
  1759. controller.establishWaitGroup.Add(1)
  1760. go controller.establishTunnelWorker()
  1761. }
  1762. controller.establishWaitGroup.Add(1)
  1763. go controller.establishCandidateGenerator()
  1764. }
  1765. func (controller *Controller) doConstraintsScan() {
  1766. // Scan over server entries in order to check and adjust any initial
  1767. // tunnel protocol limit and tunnel pool size.
  1768. //
  1769. // The scan in serverEntriesReporter is _not_ used for these checks,
  1770. // since it takes too long to complete with 1000s of server entries,
  1771. // greatly delaying the start(or restart, if already scanning) of
  1772. // establishment. Instead a 2nd ScanServerEntries is run here, with an
  1773. // early exit when sufficient candidates are found, which is expected
  1774. // to happen quickly in the typical case.
  1775. hasInitialLimitTunnelProtocols :=
  1776. controller.protocolSelectionConstraints.hasInitialProtocols()
  1777. tunnelPoolSize := controller.getTunnelPoolSize()
  1778. scanCount := 0
  1779. scanCancelled := false
  1780. candidates := 0
  1781. callback := func(serverEntry *protocol.ServerEntry) bool {
  1782. scanCount += 1
  1783. // As in serverEntryReporter:
  1784. // - egress region is ignored, since AvailableEgressRegion alerts
  1785. // the front end client when unable to connect due to egress
  1786. // region constraints.
  1787. // - excludeIntensive is false, as any intensive candidate will
  1788. // eventually be an available candidate.
  1789. excludeIntensive := false
  1790. if (hasInitialLimitTunnelProtocols &&
  1791. controller.protocolSelectionConstraints.isInitialCandidate(excludeIntensive, serverEntry)) ||
  1792. (!hasInitialLimitTunnelProtocols &&
  1793. controller.protocolSelectionConstraints.isCandidate(excludeIntensive, serverEntry)) {
  1794. candidates += 1
  1795. }
  1796. if candidates >= tunnelPoolSize {
  1797. // Exit the scan early once sufficient candidates have been found.
  1798. scanCancelled = true
  1799. return false
  1800. }
  1801. select {
  1802. case <-controller.runCtx.Done():
  1803. // Don't block controller shutdown: cancel the scan.
  1804. return false
  1805. default:
  1806. return true
  1807. }
  1808. }
  1809. startTime := time.Now()
  1810. scanErr := ScanServerEntries(callback)
  1811. if scanErr != nil && !scanCancelled {
  1812. NoticeWarning("ScanServerEntries failed: %v", errors.Trace(scanErr))
  1813. // Continue and make adjustments based on any partial results.
  1814. }
  1815. NoticeInfo("Awaited ScanServerEntries: scanned %d entries in %v", scanCount, time.Since(startTime))
  1816. // Make adjustments based on candidate counts.
  1817. if tunnelPoolSize > candidates && candidates > 0 {
  1818. tunnelPoolSize = candidates
  1819. }
  1820. // If InitialLimitTunnelProtocols is configured but cannot be satisfied,
  1821. // skip the initial phase in this establishment. This avoids spinning,
  1822. // unable to connect, in this case. InitialLimitTunnelProtocols is
  1823. // intended to prioritize certain protocols, but not strictly select them.
  1824. //
  1825. // The candidate count check ignores egress region selection. When an egress
  1826. // region is selected, it's the responsibility of the outer client to react
  1827. // to the following ReportAvailableRegions output and clear the user's
  1828. // selected region to prevent spinning, unable to connect. The initial phase
  1829. // is skipped only when InitialLimitTunnelProtocols cannot be satisfied
  1830. // _regardless_ of region selection.
  1831. //
  1832. // We presume that, in practise, most clients will have embedded server
  1833. // entries with capabilities for most protocols; and that clients will
  1834. // often perform RSL checks. So clients should most often have the
  1835. // necessary capabilities to satisfy InitialLimitTunnelProtocols. When
  1836. // this check fails, RSL/OSL/upgrade checks are triggered in order to gain
  1837. // new capabilities.
  1838. //
  1839. // LimitTunnelProtocols remains a hard limit, as using prohibited
  1840. // protocols may have some bad effect, such as a firewall blocking all
  1841. // traffic from a host.
  1842. if hasInitialLimitTunnelProtocols && candidates == 0 {
  1843. NoticeWarning("skipping initial limit tunnel protocols")
  1844. controller.protocolSelectionConstraints.initialLimitTunnelProtocolsCandidateCount = 0
  1845. // Since we were unable to satisfy the InitialLimitTunnelProtocols
  1846. // tactic, trigger RSL, OSL, and upgrade fetches to potentially
  1847. // gain new capabilities.
  1848. controller.triggerFetches()
  1849. }
  1850. }
  1851. // stopEstablishing signals the establish goroutines to stop and waits
  1852. // for the group to halt.
  1853. func (controller *Controller) stopEstablishing() {
  1854. if !controller.isEstablishing {
  1855. return
  1856. }
  1857. NoticeInfo("stop establishing")
  1858. controller.stopEstablish()
  1859. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  1860. // (as it may be sending to that channel).
  1861. controller.establishWaitGroup.Wait()
  1862. NoticeInfo("stopped establishing")
  1863. controller.isEstablishing = false
  1864. controller.establishStartTime = time.Time{}
  1865. controller.establishCtx = nil
  1866. controller.stopEstablish = nil
  1867. controller.establishWaitGroup = nil
  1868. controller.candidateServerEntries = nil
  1869. controller.serverAffinityDoneBroadcast = nil
  1870. controller.establishSignalForceTacticsFetch = nil
  1871. controller.inproxyClientDialRateLimiter = nil
  1872. controller.concurrentEstablishTunnelsMutex.Lock()
  1873. peakConcurrent := controller.peakConcurrentEstablishTunnels
  1874. peakConcurrentIntensive := controller.peakConcurrentIntensiveEstablishTunnels
  1875. controller.establishConnectTunnelCount = 0
  1876. controller.concurrentEstablishTunnels = 0
  1877. controller.concurrentIntensiveEstablishTunnels = 0
  1878. controller.peakConcurrentEstablishTunnels = 0
  1879. controller.peakConcurrentIntensiveEstablishTunnels = 0
  1880. controller.concurrentEstablishTunnelsMutex.Unlock()
  1881. NoticeInfo("peak concurrent establish tunnels: %d", peakConcurrent)
  1882. NoticeInfo("peak concurrent resource intensive establish tunnels: %d", peakConcurrentIntensive)
  1883. emitMemoryMetrics()
  1884. DoGarbageCollection()
  1885. // Record datastore metrics after establishment, the phase which generates
  1886. // the bulk of all datastore transactions: iterating over server entries,
  1887. // storing new server entries, etc.
  1888. emitDatastoreMetrics()
  1889. // Similarly, establishment generates the bulk of domain resolves.
  1890. emitDNSMetrics(controller.resolver)
  1891. }
  1892. // establishCandidateGenerator populates the candidate queue with server entries
  1893. // from the data store. Server entries are iterated in rank order, so that promoted
  1894. // servers with higher rank are priority candidates.
  1895. func (controller *Controller) establishCandidateGenerator() {
  1896. defer controller.establishWaitGroup.Done()
  1897. defer close(controller.candidateServerEntries)
  1898. // networkWaitDuration is the elapsed time spent waiting
  1899. // for network connectivity. This duration will be excluded
  1900. // from reported tunnel establishment duration.
  1901. var totalNetworkWaitDuration time.Duration
  1902. applyServerAffinity, iterator, err := NewServerEntryIterator(controller.config)
  1903. if err != nil {
  1904. NoticeError("failed to iterate over candidates: %v", errors.Trace(err))
  1905. controller.SignalComponentFailure()
  1906. return
  1907. }
  1908. defer iterator.Close()
  1909. // TODO: reconcile server affinity scheme with multi-tunnel mode
  1910. if controller.getTunnelPoolSize() > 1 {
  1911. applyServerAffinity = false
  1912. }
  1913. isServerAffinityCandidate := true
  1914. if !applyServerAffinity {
  1915. isServerAffinityCandidate = false
  1916. close(controller.serverAffinityDoneBroadcast)
  1917. }
  1918. loop:
  1919. // Repeat until stopped
  1920. for {
  1921. // A "round" consists of a new shuffle of the server entries and attempted
  1922. // connections up to the end of the server entry iterator, or
  1923. // parameters.EstablishTunnelWorkTime elapsed. Time spent waiting for
  1924. // network connectivity is excluded from round elapsed time.
  1925. //
  1926. // After a round, if parameters.EstablishTunnelWorkTime has elapsed in total
  1927. // with no tunnel established, remote server list and upgrade checks are
  1928. // triggered.
  1929. //
  1930. // A complete server entry iteration does not trigger fetches since it's
  1931. // possible to have fewer than parameters.ConnectionWorkerPoolSize
  1932. // candidates, in which case rounds end instantly due to the complete server
  1933. // entry iteration. An exception is made for an empty server entry iterator;
  1934. // in that case fetches may be triggered immediately.
  1935. //
  1936. // The number of server candidates may change during this loop, due to
  1937. // remote server list fetches. Due to the performance impact, we will not
  1938. // trigger additional, informational CandidateServer notices while in the
  1939. // establishing loop. Clients typically re-establish often enough that we
  1940. // will see the effect of the remote server list fetch in diagnostics.
  1941. roundStartTime := time.Now()
  1942. var roundNetworkWaitDuration time.Duration
  1943. workTime := controller.config.GetParameters().Get().Duration(
  1944. parameters.EstablishTunnelWorkTime)
  1945. candidateServerEntryCount := 0
  1946. // Send each iterator server entry to the establish workers
  1947. for {
  1948. networkWaitStartTime := time.Now()
  1949. if !WaitForNetworkConnectivity(
  1950. controller.establishCtx,
  1951. controller.config.NetworkConnectivityChecker,
  1952. nil) {
  1953. break loop
  1954. }
  1955. networkWaitDuration := time.Since(networkWaitStartTime)
  1956. roundNetworkWaitDuration += networkWaitDuration
  1957. totalNetworkWaitDuration += networkWaitDuration
  1958. serverEntry, err := iterator.Next()
  1959. if err != nil {
  1960. NoticeError("failed to get next candidate: %v", errors.Trace(err))
  1961. controller.SignalComponentFailure()
  1962. return
  1963. }
  1964. if serverEntry == nil {
  1965. // Completed this iteration
  1966. NoticeInfo("completed server entry iteration")
  1967. break
  1968. }
  1969. if controller.config.TargetAPIProtocol == protocol.PSIPHON_API_PROTOCOL_SSH &&
  1970. !serverEntry.SupportsSSHAPIRequests() {
  1971. continue
  1972. }
  1973. candidateServerEntryCount += 1
  1974. // adjustedEstablishStartTime is establishStartTime shifted
  1975. // to exclude time spent waiting for network connectivity.
  1976. adjustedEstablishStartTime := controller.establishStartTime.Add(
  1977. totalNetworkWaitDuration)
  1978. candidate := &candidateServerEntry{
  1979. serverEntry: serverEntry,
  1980. isServerAffinityCandidate: isServerAffinityCandidate,
  1981. adjustedEstablishStartTime: adjustedEstablishStartTime,
  1982. }
  1983. wasServerAffinityCandidate := isServerAffinityCandidate
  1984. // Note: there must be only one server affinity candidate, as it
  1985. // closes the serverAffinityDoneBroadcast channel.
  1986. isServerAffinityCandidate = false
  1987. // TODO: here we could generate multiple candidates from the
  1988. // server entry when there are many MeekFrontingAddresses.
  1989. select {
  1990. case controller.candidateServerEntries <- candidate:
  1991. case <-controller.establishCtx.Done():
  1992. break loop
  1993. }
  1994. if time.Since(roundStartTime)-roundNetworkWaitDuration > workTime {
  1995. // Start over, after a brief pause, with a new shuffle of the server
  1996. // entries, and potentially some newly fetched server entries.
  1997. break
  1998. }
  1999. if wasServerAffinityCandidate {
  2000. // Don't start the next candidate until either the server affinity
  2001. // candidate has completed (success or failure) or is still working
  2002. // and the grace period has elapsed.
  2003. gracePeriod := controller.config.GetParameters().Get().Duration(
  2004. parameters.EstablishTunnelServerAffinityGracePeriod)
  2005. if gracePeriod > 0 {
  2006. timer := time.NewTimer(gracePeriod)
  2007. select {
  2008. case <-timer.C:
  2009. case <-controller.serverAffinityDoneBroadcast:
  2010. case <-controller.establishCtx.Done():
  2011. timer.Stop()
  2012. break loop
  2013. }
  2014. timer.Stop()
  2015. }
  2016. }
  2017. }
  2018. // Free up resources now, but don't reset until after the pause.
  2019. iterator.Close()
  2020. // Trigger RSL, OSL, and upgrade checks after failing to establish a
  2021. // tunnel within parameters.EstablishTunnelWorkTime, or if there are
  2022. // no server entries present.
  2023. //
  2024. // While the trigger is made after each round,
  2025. // parameter.FetchRemoteServerListStalePeriod will limit the actual
  2026. // frequency of fetches. Continuing to trigger allows for very long running
  2027. // establishments to perhaps eventually succeed.
  2028. //
  2029. // No fetches are triggered when TargetServerEntry is specified. In that
  2030. // case, we're only trying to connect to a specific server entry.
  2031. if candidateServerEntryCount == 0 ||
  2032. time.Since(controller.establishStartTime)-totalNetworkWaitDuration > workTime {
  2033. if controller.config.TargetServerEntry == "" {
  2034. controller.triggerFetches()
  2035. }
  2036. // Trigger a forced tactics fetch. Currently, this is done only
  2037. // for cases where in-proxy tunnel protocols must be selected.
  2038. // When there were no server entries, wait until a server entry
  2039. // fetch has completed.
  2040. // Lock required to access controller.establishConnectTunnelCount.
  2041. controller.concurrentEstablishTunnelsMutex.Lock()
  2042. limitInproxyOnly := controller.protocolSelectionConstraints.getLimitTunnelProtocols(
  2043. controller.establishConnectTunnelCount).IsOnlyInproxyTunnelProtocols()
  2044. controller.concurrentEstablishTunnelsMutex.Unlock()
  2045. if limitInproxyOnly || controller.config.IsInproxyClientPersonalPairingMode() {
  2046. // Simply sleep and poll for any imported server entries;
  2047. // perform one sleep after HasServerEntries, in order to give
  2048. // the import some extra time. Limitation: if the sleep loop
  2049. // ends too soon, the tactics fetch won't find a
  2050. // tactics-capable server entry; in this case, workTime must
  2051. // elapse before another tactics fetch is triggered.
  2052. //
  2053. // TODO: synchronize with server list fetch/import complete;
  2054. // or use ScanServerEntries (but see function comment about
  2055. // performance concern) to check for at least one
  2056. // tactics-capable server entry.
  2057. if candidateServerEntryCount == 0 {
  2058. stopWaiting := false
  2059. for {
  2060. if HasServerEntries() {
  2061. stopWaiting = true
  2062. }
  2063. common.SleepWithContext(controller.establishCtx, 1*time.Second)
  2064. if stopWaiting || controller.establishCtx.Err() != nil {
  2065. break
  2066. }
  2067. }
  2068. }
  2069. select {
  2070. case controller.establishSignalForceTacticsFetch <- struct{}{}:
  2071. default:
  2072. }
  2073. }
  2074. }
  2075. // After a complete iteration of candidate servers, pause before iterating again.
  2076. // This helps avoid some busy wait loop conditions, and also allows some time for
  2077. // network conditions to change. Also allows for fetch remote to complete,
  2078. // in typical conditions (it isn't strictly necessary to wait for this, there will
  2079. // be more rounds if required).
  2080. p := controller.config.GetParameters().Get()
  2081. timeout := prng.JitterDuration(
  2082. p.Duration(parameters.EstablishTunnelPausePeriod),
  2083. p.Float(parameters.EstablishTunnelPausePeriodJitter))
  2084. p.Close()
  2085. timer := time.NewTimer(timeout)
  2086. select {
  2087. case <-timer.C:
  2088. // Retry iterating
  2089. case <-controller.establishCtx.Done():
  2090. timer.Stop()
  2091. break loop
  2092. }
  2093. timer.Stop()
  2094. err := iterator.Reset()
  2095. if err != nil {
  2096. NoticeError("failed to reset iterator: %v", errors.Trace(err))
  2097. controller.SignalComponentFailure()
  2098. return
  2099. }
  2100. }
  2101. }
  2102. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  2103. // a connection to the tunnel server, and delivers the connected tunnel to a channel.
  2104. func (controller *Controller) establishTunnelWorker() {
  2105. defer controller.establishWaitGroup.Done()
  2106. loop:
  2107. for candidateServerEntry := range controller.candidateServerEntries {
  2108. // Note: don't receive from candidateServerEntries and isStopEstablishing
  2109. // in the same select, since we want to prioritize receiving the stop signal
  2110. if controller.isStopEstablishing() {
  2111. break loop
  2112. }
  2113. // There may already be a tunnel to this candidate. If so, skip it.
  2114. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  2115. continue
  2116. }
  2117. // TODO: we allow multiple, concurrent workers to attempt to connect to the
  2118. // same server. This is not wasteful if the server supports several
  2119. // different protocols, some of which may be blocked while others are not
  2120. // blocked. Limiting protocols with [Initial]LimitTunnelProtocols may make
  2121. // these multiple attempts redundent. Also, replay should be used only by
  2122. // the first attempt.
  2123. // upstreamProxyErrorCallback will post NoticeUpstreamProxyError when the
  2124. // tunnel dial fails due to an upstream proxy error. As the upstream proxy
  2125. // is user configured, the error message may need to be relayed to the user.
  2126. // As the callback may be invoked after establishment is over (e.g., if an
  2127. // initial dial isn't fully shutdown when ConnectTunnel returns; or a meek
  2128. // underlying TCP connection re-dial) don't access these variables
  2129. // directly.
  2130. callbackCandidateServerEntry := candidateServerEntry
  2131. callbackEstablishCtx := controller.establishCtx
  2132. upstreamProxyErrorCallback := func(err error) {
  2133. // Do not post the notice when overall establishment context is canceled or
  2134. // timed-out: the upstream proxy connection error is likely a result of the
  2135. // cancellation, and not a condition to be fixed by the user. In the case
  2136. // of meek underlying TCP connection re-dials, this condition will always
  2137. // be true; however in this case the initial dial succeeded with the
  2138. // current upstream proxy settings, so any upstream proxy error is
  2139. // transient.
  2140. if callbackEstablishCtx.Err() != nil {
  2141. return
  2142. }
  2143. // Another class of non-fatal upstream proxy error arises from proxies
  2144. // which limit permitted proxied ports. In this case, some tunnels may fail
  2145. // due to dial port, while others may eventually succeed. To avoid this
  2146. // class of errors, delay posting the notice. If the upstream proxy works,
  2147. // _some_ tunnel should connect. If the upstream proxy configuration is
  2148. // broken, the error should persist and eventually get posted.
  2149. p := controller.config.GetParameters().Get()
  2150. workerPoolSize := p.Int(parameters.ConnectionWorkerPoolSize)
  2151. minWaitDuration := p.Duration(parameters.UpstreamProxyErrorMinWaitDuration)
  2152. maxWaitDuration := p.Duration(parameters.UpstreamProxyErrorMaxWaitDuration)
  2153. p.Close()
  2154. controller.concurrentEstablishTunnelsMutex.Lock()
  2155. establishConnectTunnelCount := controller.establishConnectTunnelCount
  2156. controller.concurrentEstablishTunnelsMutex.Unlock()
  2157. // Delay UpstreamProxyErrorMinWaitDuration (excluding time spent waiting
  2158. // for network connectivity) and then until either
  2159. // UpstreamProxyErrorMaxWaitDuration has elapsed or, to post sooner if many
  2160. // candidates are failing, at least workerPoolSize tunnel connection
  2161. // attempts have completed. We infer that at least workerPoolSize
  2162. // candidates have completed by checking that at least 2*workerPoolSize
  2163. // candidates have started.
  2164. elapsedTime := time.Since(
  2165. callbackCandidateServerEntry.adjustedEstablishStartTime)
  2166. if elapsedTime < minWaitDuration ||
  2167. (elapsedTime < maxWaitDuration &&
  2168. establishConnectTunnelCount < 2*workerPoolSize) {
  2169. return
  2170. }
  2171. NoticeUpstreamProxyError(err)
  2172. }
  2173. // Select the tunnel protocol. The selection will be made at random
  2174. // from protocols supported by the server entry, optionally limited by
  2175. // LimitTunnelProtocols.
  2176. //
  2177. // When limiting concurrent resource intensive protocol connection
  2178. // workers, and at the limit, do not select resource intensive
  2179. // protocols since otherwise the candidate must be skipped.
  2180. //
  2181. // If at the limit and unabled to select a non-intensive protocol,
  2182. // skip the candidate entirely and move on to the next. Since
  2183. // candidates are shuffled it's likely that the next candidate is not
  2184. // intensive. In this case, a StaggerConnectionWorkersMilliseconds
  2185. // delay may still be incurred.
  2186. p := controller.config.GetParameters().Get()
  2187. limitIntensiveConnectionWorkers := p.Int(parameters.LimitIntensiveConnectionWorkers)
  2188. inproxySelectionProbability := p.Float(parameters.InproxyTunnelProtocolSelectionProbability)
  2189. staggerPeriod := p.Duration(parameters.StaggerConnectionWorkersPeriod)
  2190. staggerJitter := p.Float(parameters.StaggerConnectionWorkersJitter)
  2191. p.Close()
  2192. controller.concurrentEstablishTunnelsMutex.Lock()
  2193. excludeIntensive := false
  2194. if limitIntensiveConnectionWorkers > 0 &&
  2195. controller.concurrentIntensiveEstablishTunnels >= limitIntensiveConnectionWorkers {
  2196. excludeIntensive = true
  2197. }
  2198. canReplay := func(serverEntry *protocol.ServerEntry, replayProtocol string) bool {
  2199. return controller.protocolSelectionConstraints.canReplay(
  2200. controller.establishConnectTunnelCount,
  2201. excludeIntensive,
  2202. serverEntry,
  2203. replayProtocol)
  2204. }
  2205. // The dial rate limit delay, determined by protocolSelectionConstraints.selectProtocol, is
  2206. // not applied within that function since this worker holds the concurrentEstablishTunnelsMutex
  2207. // lock when that's called. Instead, the required delay is passed out and applied below.
  2208. // It's safe for the selectProtocol callback to write to dialRateLimitDelay without
  2209. // synchronization since this worker goroutine invokes the callback.
  2210. var dialRateLimitDelay time.Duration
  2211. selectProtocol := func(serverEntry *protocol.ServerEntry) (string, bool) {
  2212. // The in-proxy protocol selection probability allows for
  2213. // tuning/limiting in-proxy usage independent of
  2214. // LimitTunnelProtocol targeting.
  2215. onlyInproxy := controller.config.IsInproxyClientPersonalPairingMode()
  2216. includeInproxy := onlyInproxy || prng.FlipWeightedCoin(inproxySelectionProbability)
  2217. selectedProtocol, rateLimitDelay, ok := controller.protocolSelectionConstraints.selectProtocol(
  2218. controller.establishConnectTunnelCount,
  2219. excludeIntensive,
  2220. !includeInproxy,
  2221. serverEntry)
  2222. dialRateLimitDelay = rateLimitDelay
  2223. return selectedProtocol, ok
  2224. }
  2225. // MakeDialParameters may return a replay instance, if the server
  2226. // entry has a previous, recent successful connection and
  2227. // tactics/config has not changed.
  2228. //
  2229. // In the first round -- and later rounds, with some probability -- of
  2230. // establishing, ServerEntryIterator will move potential replay candidates
  2231. // to the front of the iterator after the random shuffle, which greatly
  2232. // prioritizes previously successful servers for that round.
  2233. //
  2234. // As ServerEntryIterator does not unmarshal and validate replay
  2235. // candidate dial parameters, some potential replay candidates may
  2236. // have expired or otherwise ineligible dial parameters; in this case
  2237. // the candidate proceeds without replay.
  2238. //
  2239. // The ReplayCandidateCount tactic determines how many candidates may use
  2240. // replay. After ReplayCandidateCount candidates of any type, replay or no,
  2241. // replay is skipped. If ReplayCandidateCount exceeds the intial round,
  2242. // replay may still be performed but the iterator may no longer move
  2243. // potential replay server entries to the front. When ReplayCandidateCount
  2244. // is set to -1, unlimited candidates may use replay.
  2245. dialParams, err := MakeDialParameters(
  2246. controller.config,
  2247. controller.steeringIPCache,
  2248. controller.quicTLSClientSessionCache,
  2249. controller.tlsClientSessionCache,
  2250. upstreamProxyErrorCallback,
  2251. canReplay,
  2252. selectProtocol,
  2253. candidateServerEntry.serverEntry,
  2254. controller.inproxyClientBrokerClientManager,
  2255. controller.inproxyNATStateManager,
  2256. false,
  2257. controller.establishConnectTunnelCount,
  2258. int(atomic.LoadInt32(&controller.establishedTunnelsCount)))
  2259. if dialParams == nil || err != nil {
  2260. controller.concurrentEstablishTunnelsMutex.Unlock()
  2261. // MakeDialParameters returns nil/nil when the server entry is to
  2262. // be skipped. See MakeDialParameters for skip cases and skip
  2263. // logging. Silently fail the candidate in this case. Otherwise,
  2264. // emit error.
  2265. if err != nil {
  2266. NoticeInfo("failed to make dial parameters for %s: %v",
  2267. candidateServerEntry.serverEntry.GetDiagnosticID(),
  2268. errors.Trace(err))
  2269. }
  2270. // Unblock other candidates immediately when server affinity
  2271. // candidate is skipped.
  2272. if candidateServerEntry.isServerAffinityCandidate {
  2273. close(controller.serverAffinityDoneBroadcast)
  2274. }
  2275. continue
  2276. }
  2277. // Increment establishConnectTunnelCount only after selectProtocol has
  2278. // succeeded to ensure InitialLimitTunnelProtocolsCandidateCount
  2279. // candidates use InitialLimitTunnelProtocols.
  2280. //
  2281. // TODO: add escape from initial limit to cover cases where the
  2282. // initial scan indicates there are sufficient candidates, but then
  2283. // server entries are deleted.
  2284. establishConnectTunnelCount := controller.establishConnectTunnelCount
  2285. controller.establishConnectTunnelCount += 1
  2286. isIntensive := protocol.TunnelProtocolIsResourceIntensive(dialParams.TunnelProtocol)
  2287. if isIntensive {
  2288. controller.concurrentIntensiveEstablishTunnels += 1
  2289. if controller.concurrentIntensiveEstablishTunnels > controller.peakConcurrentIntensiveEstablishTunnels {
  2290. controller.peakConcurrentIntensiveEstablishTunnels = controller.concurrentIntensiveEstablishTunnels
  2291. }
  2292. }
  2293. controller.concurrentEstablishTunnels += 1
  2294. if controller.concurrentEstablishTunnels > controller.peakConcurrentEstablishTunnels {
  2295. controller.peakConcurrentEstablishTunnels = controller.concurrentEstablishTunnels
  2296. }
  2297. controller.concurrentEstablishTunnelsMutex.Unlock()
  2298. startStagger := time.Now()
  2299. // Apply stagger only now that we're past MakeDialParameters and
  2300. // protocol selection logic which may have caused the candidate to be
  2301. // skipped. The stagger logic delays dialing, and we don't want to
  2302. // incur that delay that when skipping.
  2303. //
  2304. // Locking staggerMutex serializes staggers, so that multiple workers
  2305. // don't simply sleep in parallel.
  2306. //
  2307. // The stagger is applied when establishConnectTunnelCount > 0 -- that
  2308. // is, for all but the first dial.
  2309. if establishConnectTunnelCount > 0 && staggerPeriod != 0 {
  2310. controller.staggerMutex.Lock()
  2311. timer := time.NewTimer(prng.JitterDuration(staggerPeriod, staggerJitter))
  2312. select {
  2313. case <-timer.C:
  2314. case <-controller.establishCtx.Done():
  2315. }
  2316. timer.Stop()
  2317. controller.staggerMutex.Unlock()
  2318. }
  2319. // Apply any dial rate limit delay now, after unlocking
  2320. // concurrentEstablishTunnelsMutex. The delay may be reduced by the
  2321. // time spent waiting to stagger.
  2322. dialRateLimitDelay -= time.Since(startStagger)
  2323. if dialRateLimitDelay > 0 {
  2324. common.SleepWithContext(controller.establishCtx, dialRateLimitDelay)
  2325. }
  2326. // ConnectTunnel will allocate significant memory, so first attempt to
  2327. // reclaim as much as possible.
  2328. DoGarbageCollection()
  2329. tunnel, err := ConnectTunnel(
  2330. controller.establishCtx,
  2331. controller.config,
  2332. candidateServerEntry.adjustedEstablishStartTime,
  2333. dialParams)
  2334. controller.concurrentEstablishTunnelsMutex.Lock()
  2335. if isIntensive {
  2336. controller.concurrentIntensiveEstablishTunnels -= 1
  2337. }
  2338. controller.concurrentEstablishTunnels -= 1
  2339. controller.concurrentEstablishTunnelsMutex.Unlock()
  2340. // Periodically emit memory metrics during the establishment cycle.
  2341. if !controller.isStopEstablishing() {
  2342. emitMemoryMetrics()
  2343. }
  2344. // Immediately reclaim memory allocated by the establishment. In the case
  2345. // of failure, first clear the reference to the tunnel. In the case of
  2346. // success, the garbage collection may still be effective as the initial
  2347. // phases of some protocols involve significant memory allocation that
  2348. // could now be reclaimed.
  2349. if err != nil {
  2350. tunnel = nil
  2351. }
  2352. DoGarbageCollection()
  2353. if err != nil {
  2354. // Unblock other candidates immediately when server affinity
  2355. // candidate fails.
  2356. if candidateServerEntry.isServerAffinityCandidate {
  2357. close(controller.serverAffinityDoneBroadcast)
  2358. }
  2359. // Before emitting error, check if establish interrupted, in which
  2360. // case the error is noise.
  2361. if controller.isStopEstablishing() {
  2362. break loop
  2363. }
  2364. NoticeInfo("failed to connect to %s: %v",
  2365. candidateServerEntry.serverEntry.GetDiagnosticID(),
  2366. errors.Trace(err))
  2367. continue
  2368. }
  2369. // Deliver connected tunnel.
  2370. // Don't block. Assumes the receiver has a buffer large enough for
  2371. // the number of desired tunnels. If there's no room, the tunnel must
  2372. // not be required so it's discarded.
  2373. select {
  2374. case controller.connectedTunnels <- tunnel:
  2375. default:
  2376. controller.discardTunnel(tunnel)
  2377. // Clear the reference to this discarded tunnel and immediately run
  2378. // a garbage collection to reclaim its memory.
  2379. //
  2380. // Note: this assignment is flagged by github.com/gordonklaus/ineffassign,
  2381. // but should still have some effect on garbage collection?
  2382. tunnel = nil
  2383. DoGarbageCollection()
  2384. }
  2385. // Unblock other candidates only after delivering when
  2386. // server affinity candidate succeeds.
  2387. if candidateServerEntry.isServerAffinityCandidate {
  2388. close(controller.serverAffinityDoneBroadcast)
  2389. }
  2390. }
  2391. }
  2392. func (controller *Controller) isStopEstablishing() bool {
  2393. select {
  2394. case <-controller.establishCtx.Done():
  2395. return true
  2396. default:
  2397. }
  2398. return false
  2399. }
  2400. func (controller *Controller) runInproxyProxy() {
  2401. defer controller.runWaitGroup.Done()
  2402. // Obtain and apply tactics before connecting to the broker and
  2403. // announcing proxies.
  2404. if !controller.config.DisableTunnels &&
  2405. !controller.config.InproxySkipAwaitFullyConnected {
  2406. // When running client tunnel establishment, awaiting establishment
  2407. // guarantees fresh tactics from either an OOB request or a handshake
  2408. // response.
  2409. //
  2410. // While it may be possible to proceed sooner, using cached tactics,
  2411. // waiting until establishment is complete avoids potential races
  2412. // between tactics updates.
  2413. if !controller.awaitFullyEstablished() {
  2414. // Controller is shutting down
  2415. return
  2416. }
  2417. } else {
  2418. // Await the necessary proxy broker specs. These may already be
  2419. // available in cached tactics.
  2420. //
  2421. // When not already available, and when not also running client tunnel
  2422. // establishment, i.e., when DisableTunnels is set,
  2423. // inproxyAwaitProxyBrokerSpecs will perform tactics fetches, in
  2424. // addition to triggering remote server list fetches in case
  2425. // tactics-capable server entries are not available. In this mode,
  2426. // inproxyAwaitProxyBrokerSpecs can return, after a fresh tactics
  2427. // fetch yielding no broker specs, without broker specs.
  2428. // haveInproxyProxyBrokerSpecs is checked again below.
  2429. //
  2430. // InproxySkipAwaitFullyConnected is a special testing case to support
  2431. // server/server_test, where a client must be its own proxy; in this
  2432. // case, awaitFullyEstablished will block forever and can't be used.
  2433. // When InproxySkipAwaitFullyConnected is set and when also running
  2434. // client tunnel establishment, inproxyAwaitProxyBrokerSpecs simply
  2435. // waits until any broker specs become available, which is sufficient
  2436. // for the test but is not as robust as awaiting fresh tactics.
  2437. if !controller.inproxyAwaitProxyBrokerSpecs() {
  2438. // Controller is shutting down
  2439. return
  2440. }
  2441. }
  2442. // Don't announce proxies if tactics indicates it won't be allowed. This
  2443. // is also enforced on the broker; this client-side check cuts down on
  2444. // load from well-behaved proxies.
  2445. //
  2446. // Limitation: InproxyAllowProxy is only checked on start up, but tactics
  2447. // may change while running.
  2448. p := controller.config.GetParameters().Get()
  2449. allowProxy := p.Bool(parameters.InproxyAllowProxy)
  2450. activityNoticePeriod := p.Duration(parameters.InproxyProxyTotalActivityNoticePeriod)
  2451. p.Close()
  2452. // Running an upstream proxy is also an incompatible case.
  2453. useUpstreamProxy := controller.config.UseUpstreamProxy()
  2454. // In both the awaitFullyEstablished and inproxyAwaitProxyBrokerSpecs
  2455. // cases, we may arrive at this point without broker specs, and must
  2456. // recheck.
  2457. haveBrokerSpecs := haveInproxyProxyBrokerSpecs(controller.config)
  2458. if !allowProxy || useUpstreamProxy || !haveBrokerSpecs || !inproxy.Enabled() {
  2459. if !allowProxy {
  2460. NoticeError("inproxy proxy: not allowed")
  2461. }
  2462. if useUpstreamProxy {
  2463. NoticeError("inproxy proxy: not run due to upstream proxy configuration")
  2464. }
  2465. if haveBrokerSpecs {
  2466. NoticeError("inproxy proxy: no proxy broker specs")
  2467. }
  2468. if !inproxy.Enabled() {
  2469. NoticeError("inproxy proxy: inproxy implementation is not enabled")
  2470. }
  2471. // Signal failure -- and shutdown -- only if running in proxy-only
  2472. // mode. If also running a tunnel, keep running without proxies.
  2473. if controller.config.DisableTunnels {
  2474. NoticeError("inproxy proxy: aborting")
  2475. controller.SignalComponentFailure()
  2476. }
  2477. return
  2478. }
  2479. // The debugLogging flag is passed to both NoticeCommonLogger and to the
  2480. // inproxy package as well; skipping debug logs in the inproxy package,
  2481. // before calling into the notice logger, avoids unnecessary allocations
  2482. // and formatting when debug logging is off.
  2483. debugLogging := controller.config.InproxyEnableWebRTCDebugLogging
  2484. var lastActivityNotice time.Time
  2485. var lastActivityConnectingClients, lastActivityConnectedClients int32
  2486. var lastActivityConnectingClientsTotal, lastActivityConnectedClientsTotal int32
  2487. var activityTotalBytesUp, activityTotalBytesDown int64
  2488. activityUpdater := func(
  2489. connectingClients int32,
  2490. connectedClients int32,
  2491. bytesUp int64,
  2492. bytesDown int64,
  2493. _ time.Duration) {
  2494. // This emit logic mirrors the logic for NoticeBytesTransferred and
  2495. // NoticeTotalBytesTransferred in tunnel.operateTunnel.
  2496. // InproxyProxyActivity frequently emits bytes transferred since the
  2497. // last notice, when not idle; in addition to the current number of
  2498. // connecting and connected clients, whenever that changes. This
  2499. // frequent notice is excluded from diagnostics and is for UI
  2500. // activity display.
  2501. if controller.config.EmitInproxyProxyActivity &&
  2502. (bytesUp > 0 || bytesDown > 0) ||
  2503. connectingClients != lastActivityConnectingClients ||
  2504. connectedClients != lastActivityConnectedClients {
  2505. NoticeInproxyProxyActivity(
  2506. connectingClients, connectedClients, bytesUp, bytesDown)
  2507. lastActivityConnectingClients = connectingClients
  2508. lastActivityConnectedClients = connectedClients
  2509. }
  2510. activityTotalBytesUp += bytesUp
  2511. activityTotalBytesDown += bytesDown
  2512. // InproxyProxyTotalActivity periodically emits total bytes
  2513. // transferred since starting; in addition to the current number of
  2514. // connecting and connected clients, whenever that changes. This
  2515. // notice is for diagnostics.
  2516. if lastActivityNotice.Add(activityNoticePeriod).Before(time.Now()) ||
  2517. connectingClients != lastActivityConnectingClientsTotal ||
  2518. connectedClients != lastActivityConnectedClientsTotal {
  2519. NoticeInproxyProxyTotalActivity(
  2520. connectingClients, connectedClients,
  2521. activityTotalBytesUp, activityTotalBytesDown)
  2522. lastActivityNotice = time.Now()
  2523. lastActivityConnectingClientsTotal = connectingClients
  2524. lastActivityConnectedClientsTotal = connectedClients
  2525. }
  2526. }
  2527. config := &inproxy.ProxyConfig{
  2528. Logger: NoticeCommonLogger(debugLogging),
  2529. EnableWebRTCDebugLogging: debugLogging,
  2530. WaitForNetworkConnectivity: controller.inproxyWaitForNetworkConnectivity,
  2531. GetCurrentNetworkContext: controller.getCurrentNetworkContext,
  2532. GetBrokerClient: controller.inproxyGetProxyBrokerClient,
  2533. GetBaseAPIParameters: controller.inproxyGetProxyAPIParameters,
  2534. MakeWebRTCDialCoordinator: controller.inproxyMakeProxyWebRTCDialCoordinator,
  2535. HandleTacticsPayload: controller.inproxyHandleProxyTacticsPayload,
  2536. MaxClients: controller.config.InproxyMaxClients,
  2537. LimitUpstreamBytesPerSecond: controller.config.InproxyLimitUpstreamBytesPerSecond,
  2538. LimitDownstreamBytesPerSecond: controller.config.InproxyLimitDownstreamBytesPerSecond,
  2539. MustUpgrade: controller.config.OnInproxyMustUpgrade,
  2540. ActivityUpdater: activityUpdater,
  2541. }
  2542. proxy, err := inproxy.NewProxy(config)
  2543. if err != nil {
  2544. NoticeError("inproxy.NewProxy failed: %v", errors.Trace(err))
  2545. controller.SignalComponentFailure()
  2546. return
  2547. }
  2548. NoticeInfo("inproxy proxy: running")
  2549. proxy.Run(controller.runCtx)
  2550. // Emit one last NoticeInproxyProxyTotalActivity with the final byte counts.
  2551. NoticeInproxyProxyTotalActivity(
  2552. lastActivityConnectingClients, lastActivityConnectedClients,
  2553. activityTotalBytesUp, activityTotalBytesDown)
  2554. NoticeInfo("inproxy proxy: stopped")
  2555. }
  2556. // inproxyAwaitProxyBrokerSpecs awaits proxy broker specs or a fresh tactics
  2557. // fetch indicating that there are no proxy broker specs. The caller should
  2558. // check haveInproxyProxyBrokerSpecs to determine which is the case.
  2559. //
  2560. // inproxyAwaitProxyBrokerSpecs is intended for use either when DisableTunnels
  2561. // is set or when InproxySkipAwaitFullyConnected is set.
  2562. //
  2563. // In the DisableTunnels case, inproxyAwaitProxyBrokerSpecs will perform
  2564. // tactics fetches and trigger remote server list fetches in case
  2565. // tactics-capable server entries are required. The DisableTunnels case
  2566. // assumes client tunnel establishment is not also running, as the tactics
  2567. // operations could otherwise conflict.
  2568. //
  2569. // In the InproxySkipAwaitFullyConnected case, which is intended only to
  2570. // support testing, inproxyAwaitProxyBrokerSpecs simply polls forever for
  2571. // proxy broker specs expected, in the test, to be obtained from concurrent
  2572. // client tunnel establishment operations.
  2573. //
  2574. // inproxyAwaitProxyBrokerSpecs returns false when the Controller is
  2575. // stopping.
  2576. func (controller *Controller) inproxyAwaitProxyBrokerSpecs() bool {
  2577. NoticeInfo("inproxy proxy: await tactics with proxy broker specs")
  2578. // Check for any broker specs in cached tactics or config parameters
  2579. // already loaded by NewController or Config.Commit.
  2580. if haveInproxyProxyBrokerSpecs(controller.config) {
  2581. return true
  2582. }
  2583. // If there are no broker specs in config parameters and tactics are
  2584. // disabled, there is nothing more to await.
  2585. if controller.config.DisableTactics {
  2586. NoticeWarning("inproxy proxy: no broker specs and tactics disabled")
  2587. return true
  2588. }
  2589. // Orchestrating fetches roughly follows the same pattern as
  2590. // establishCandidateGenerator, with a WaitForNetworkConnectivity check,
  2591. // followed by the fetch operation; and a remote server list trigger when
  2592. // that fails, followed by a short pause.
  2593. doFetches := controller.config.DisableTunnels
  2594. // pollPeriod for InproxySkipAwaitFullyConnected case.
  2595. pollPeriod := 100 * time.Millisecond
  2596. for {
  2597. fetched := false
  2598. if doFetches {
  2599. if !WaitForNetworkConnectivity(
  2600. controller.runCtx,
  2601. controller.config.NetworkConnectivityChecker,
  2602. nil) {
  2603. // Controller is shutting down
  2604. return false
  2605. }
  2606. // Force a fetch for the latest tactics, since cached tactics, if
  2607. // any, did not yield proxy broker specs.
  2608. useStoredTactics := false
  2609. fetched = GetTactics(controller.runCtx, controller.config, useStoredTactics)
  2610. }
  2611. if haveInproxyProxyBrokerSpecs(controller.config) {
  2612. return true
  2613. } else if fetched {
  2614. // If fresh tactics yielded no proxy broker specs, there is
  2615. // nothing more to await.
  2616. NoticeWarning("inproxy proxy: no broker specs in tactics")
  2617. return true
  2618. }
  2619. timeout := pollPeriod
  2620. if doFetches {
  2621. // Trigger remote server list fetches in case the tactics fetch
  2622. // failed due to "no capable servers". Repeated triggers will
  2623. // have no effect, subject to FetchRemoteServerListStalePeriod.
  2624. //
  2625. // While triggerFetches also triggers upgrade downloads, currently
  2626. // the upgrade downloader is not enabled when DisableTunnels is
  2627. // set. See Controller.Run.
  2628. //
  2629. // TODO: make the trigger conditional on the specific "no capable
  2630. // servers" failure condition.
  2631. controller.triggerFetches()
  2632. // Pause before attempting to fetch tactics again. This helps
  2633. // avoid some busy wait loop conditions, allows some time for
  2634. // network conditions to change, and also allows for remote server
  2635. // list fetches to complete. The EstablishTunnelPausePeriod and
  2636. // Jitter parameters used in establishCandidateGenerator are also
  2637. // appropriate in this instance.
  2638. p := controller.config.GetParameters().Get()
  2639. timeout = prng.JitterDuration(
  2640. p.Duration(parameters.EstablishTunnelPausePeriod),
  2641. p.Float(parameters.EstablishTunnelPausePeriodJitter))
  2642. p.Close()
  2643. }
  2644. timer := time.NewTimer(timeout)
  2645. select {
  2646. case <-timer.C:
  2647. case <-controller.runCtx.Done():
  2648. timer.Stop()
  2649. // Controller is shutting down
  2650. return false
  2651. }
  2652. timer.Stop()
  2653. }
  2654. }
  2655. func (controller *Controller) inproxyWaitForNetworkConnectivity() bool {
  2656. var isCompatibleNetwork func() bool
  2657. emittedIncompatibleNetworkNotice := false
  2658. if !controller.config.IsInproxyProxyPersonalPairingMode() {
  2659. // Pause announcing proxies when currently running on an incompatible
  2660. // network, such as a non-Psiphon VPN.
  2661. p := controller.config.GetParameters().Get()
  2662. incompatibleNetworkTypes := p.Strings(parameters.InproxyProxyIncompatibleNetworkTypes)
  2663. p.Close()
  2664. isCompatibleNetwork = func() bool {
  2665. compatibleNetwork := !common.Contains(
  2666. incompatibleNetworkTypes,
  2667. GetNetworkType(controller.config.GetNetworkID()))
  2668. if !compatibleNetwork && !emittedIncompatibleNetworkNotice {
  2669. NoticeInfo("inproxy proxy: waiting due to incompatible network")
  2670. emittedIncompatibleNetworkNotice = true
  2671. }
  2672. return compatibleNetwork
  2673. }
  2674. }
  2675. return WaitForNetworkConnectivity(
  2676. controller.runCtx,
  2677. controller.config.NetworkConnectivityChecker,
  2678. isCompatibleNetwork)
  2679. }
  2680. // inproxyGetProxyBrokerClient returns the broker client shared by all proxy
  2681. // operations.
  2682. func (controller *Controller) inproxyGetProxyBrokerClient() (*inproxy.BrokerClient, error) {
  2683. brokerClient, _, err := controller.inproxyProxyBrokerClientManager.GetBrokerClient(
  2684. controller.config.GetNetworkID())
  2685. if err != nil {
  2686. return nil, errors.Trace(err)
  2687. }
  2688. return brokerClient, nil
  2689. }
  2690. func (controller *Controller) inproxyGetProxyAPIParameters(includeTacticsParameters bool) (
  2691. common.APIParameters, string, error) {
  2692. // TODO: include broker fronting dial parameters to be logged by the
  2693. // broker.
  2694. params := getBaseAPIParameters(
  2695. baseParametersNoDialParameters, true, controller.config, nil)
  2696. if controller.config.DisableTactics {
  2697. return params, "", nil
  2698. }
  2699. // Add the stored tactics tag, so that the broker can return new tactics if
  2700. // available.
  2701. //
  2702. // The active network ID is recorded returned and rechecked for
  2703. // consistency when storing any new tactics returned from the broker;
  2704. // other tactics fetches have this same check.
  2705. networkID := controller.config.GetNetworkID()
  2706. if includeTacticsParameters {
  2707. err := tactics.SetTacticsAPIParameters(
  2708. GetTacticsStorer(controller.config), networkID, params)
  2709. if err != nil {
  2710. return nil, "", errors.Trace(err)
  2711. }
  2712. }
  2713. return params, networkID, nil
  2714. }
  2715. func (controller *Controller) inproxyMakeProxyWebRTCDialCoordinator() (
  2716. inproxy.WebRTCDialCoordinator, error) {
  2717. // nil is passed in for both InproxySTUNDialParameters and
  2718. // InproxyWebRTCDialParameters, so those parameters will be newly
  2719. // auto-generated for each client/proxy connection attempt. Unlike the
  2720. // in-proxy client, there is currently no replay of STUN or WebRTC dial
  2721. // parameters.
  2722. isProxy := true
  2723. webRTCDialInstance, err := NewInproxyWebRTCDialInstance(
  2724. controller.config,
  2725. controller.config.GetNetworkID(),
  2726. isProxy,
  2727. controller.inproxyNATStateManager,
  2728. nil,
  2729. nil)
  2730. if err != nil {
  2731. return nil, errors.Trace(err)
  2732. }
  2733. return webRTCDialInstance, nil
  2734. }
  2735. // inproxyHandleProxyTacticsPayload handles new tactics returned from the
  2736. // proxy and returns when tactics have changed.
  2737. //
  2738. // inproxyHandleTacticsPayload duplicates some tactics-handling code from
  2739. // doHandshakeRequest.
  2740. func (controller *Controller) inproxyHandleProxyTacticsPayload(
  2741. networkID string, tacticsPayload []byte) bool {
  2742. if controller.config.DisableTactics {
  2743. return false
  2744. }
  2745. if controller.config.GetNetworkID() != networkID {
  2746. // Ignore the tactics if the network ID has changed.
  2747. return false
  2748. }
  2749. var payload *tactics.Payload
  2750. err := json.Unmarshal(tacticsPayload, &payload)
  2751. if err != nil {
  2752. NoticeError("unmarshal tactics payload failed: %v", errors.Trace(err))
  2753. return false
  2754. }
  2755. if payload == nil {
  2756. // See "null" comment in doHandshakeRequest.
  2757. return false
  2758. }
  2759. // The in-proxy proxy implementation arranges for the first ProxyAnnounce
  2760. // request to get a head start in case there are new tactics available
  2761. // from the broker. Additional requests are also staggered.
  2762. //
  2763. // It can still happen that concurrent in-flight ProxyAnnounce requests
  2764. // receive duplicate new-tactics responses.
  2765. //
  2766. // TODO: detect this case and avoid resetting the broker client and NAT
  2767. // state managers more than necessary.
  2768. // Serialize processing of tactics from ProxyAnnounce responses.
  2769. controller.inproxyHandleTacticsMutex.Lock()
  2770. defer controller.inproxyHandleTacticsMutex.Unlock()
  2771. // When tactics are unchanged, the broker, as in the handshake case,
  2772. // returns a tactics payload, but without new tactics. As in the
  2773. // handshake case, HandleTacticsPayload is called in order to extend the
  2774. // TTL of the locally cached, unchanged tactics. Due to the potential
  2775. // high frequency and concurrency of ProxyAnnnounce requests vs.
  2776. // handshakes, a limit is added to update the data store's tactics TTL no
  2777. // more than one per minute.
  2778. appliedNewTactics := payload.Tactics != nil
  2779. now := time.Now()
  2780. if !appliedNewTactics && now.Sub(controller.inproxyLastStoredTactics) > 1*time.Minute {
  2781. // Skip TTL-only disk write.
  2782. return false
  2783. }
  2784. controller.inproxyLastStoredTactics = now
  2785. tacticsRecord, err := tactics.HandleTacticsPayload(
  2786. GetTacticsStorer(controller.config), networkID, payload)
  2787. if err != nil {
  2788. NoticeError("HandleTacticsPayload failed: %v", errors.Trace(err))
  2789. return false
  2790. }
  2791. if tacticsRecord != nil {
  2792. // SetParameters signals registered components, including broker
  2793. // client and NAT state managers, that must reset upon tactics changes.
  2794. err := controller.config.SetParameters(
  2795. tacticsRecord.Tag, true, tacticsRecord.Tactics.Parameters)
  2796. if err != nil {
  2797. NoticeInfo("apply inproxy broker tactics failed: %s", err)
  2798. return false
  2799. }
  2800. } else {
  2801. appliedNewTactics = false
  2802. }
  2803. return appliedNewTactics
  2804. }