controller.go 100 KB

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