controller.go 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793
  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. controller.protocolSelectionConstraints,
  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. if isFirstTunnel {
  906. // Signal a connected request on each 1st tunnel establishment. For
  907. // multi-tunnels, the session is connected as long as at least one
  908. // tunnel is established.
  909. controller.signalConnectedReporter()
  910. // If the handshake indicated that a new client version is available,
  911. // trigger an upgrade download.
  912. // Note: serverContext is nil when DisableApi is set
  913. if connectedTunnel.serverContext != nil &&
  914. connectedTunnel.serverContext.clientUpgradeVersion != "" {
  915. handshakeVersion := connectedTunnel.serverContext.clientUpgradeVersion
  916. select {
  917. case controller.signalDownloadUpgrade <- handshakeVersion:
  918. default:
  919. }
  920. }
  921. }
  922. // Set the new tunnel as the transport for the packet tunnel. The packet tunnel
  923. // client remains up when reestablishing, but no packets are relayed while there
  924. // is no connected tunnel. UseTunnel will establish a new packet tunnel SSH
  925. // channel over the new SSH tunnel and configure the packet tunnel client to use
  926. // the new SSH channel as its transport.
  927. //
  928. // Note: as is, this logic is suboptimal for tunnelPoolSize > 1, as this would
  929. // continuously initialize new packet tunnel sessions for each established
  930. // server. For now, config validation requires tunnelPoolSize == 1 when
  931. // the packet tunnel is used.
  932. if controller.packetTunnelTransport != nil {
  933. controller.packetTunnelTransport.UseTunnel(connectedTunnel)
  934. }
  935. if controller.isFullyEstablished() {
  936. controller.stopEstablishing()
  937. }
  938. case <-controller.runCtx.Done():
  939. break loop
  940. }
  941. }
  942. // Stop running
  943. controller.stopEstablishing()
  944. controller.terminateAllTunnels()
  945. // Drain tunnel channels
  946. close(controller.connectedTunnels)
  947. for tunnel := range controller.connectedTunnels {
  948. controller.discardTunnel(tunnel)
  949. }
  950. close(controller.failedTunnels)
  951. for tunnel := range controller.failedTunnels {
  952. controller.discardTunnel(tunnel)
  953. }
  954. NoticeInfo("exiting run tunnels")
  955. }
  956. // SignalSeededNewSLOK implements the TunnelOwner interface. This function
  957. // is called by Tunnel.operateTunnel when the tunnel has received a new,
  958. // previously unknown SLOK from the server. The Controller triggers an OSL
  959. // fetch, as the new SLOK may be sufficient to access new OSLs.
  960. func (controller *Controller) SignalSeededNewSLOK() {
  961. select {
  962. case controller.signalFetchObfuscatedServerLists <- struct{}{}:
  963. default:
  964. }
  965. }
  966. // SignalTunnelFailure implements the TunnelOwner interface. This function
  967. // is called by Tunnel.operateTunnel when the tunnel has detected that it
  968. // has failed. The Controller will signal runTunnels to create a new
  969. // tunnel and/or remove the tunnel from the list of active tunnels.
  970. func (controller *Controller) SignalTunnelFailure(tunnel *Tunnel) {
  971. // Don't block. Assumes the receiver has a buffer large enough for
  972. // the typical number of operated tunnels. In case there's no room,
  973. // terminate the tunnel (runTunnels won't get a signal in this case,
  974. // but the tunnel will be removed from the list of active tunnels).
  975. select {
  976. case controller.failedTunnels <- tunnel:
  977. default:
  978. controller.terminateTunnel(tunnel)
  979. }
  980. }
  981. // discardTunnel disposes of a successful connection that is no longer required.
  982. func (controller *Controller) discardTunnel(tunnel *Tunnel) {
  983. NoticeInfo("discard tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  984. // TODO: not calling PromoteServerEntry, since that would rank the
  985. // discarded tunnel before fully active tunnels. Can a discarded tunnel
  986. // be promoted (since it connects), but with lower rank than all active
  987. // tunnels?
  988. tunnel.Close(true)
  989. }
  990. // registerTunnel adds the connected tunnel to the pool of active tunnels
  991. // which are candidates for port forwarding. Returns true if the pool has an
  992. // empty slot and false if the pool is full (caller should discard the tunnel).
  993. func (controller *Controller) registerTunnel(tunnel *Tunnel) bool {
  994. controller.tunnelMutex.Lock()
  995. defer controller.tunnelMutex.Unlock()
  996. if len(controller.tunnels) >= controller.tunnelPoolSize {
  997. return false
  998. }
  999. // Perform a final check just in case we've established
  1000. // a duplicate connection.
  1001. for _, activeTunnel := range controller.tunnels {
  1002. if activeTunnel.dialParams.ServerEntry.IpAddress ==
  1003. tunnel.dialParams.ServerEntry.IpAddress {
  1004. NoticeWarning("duplicate tunnel: %s", tunnel.dialParams.ServerEntry.GetDiagnosticID())
  1005. return false
  1006. }
  1007. }
  1008. controller.establishedOnce = true
  1009. controller.tunnels = append(controller.tunnels, tunnel)
  1010. NoticeTunnels(len(controller.tunnels))
  1011. // Promote this successful tunnel to first rank so it's one
  1012. // of the first candidates next time establish runs.
  1013. // Connecting to a TargetServerEntry does not change the
  1014. // ranking.
  1015. if controller.config.TargetServerEntry == "" {
  1016. PromoteServerEntry(controller.config, tunnel.dialParams.ServerEntry.IpAddress)
  1017. }
  1018. return true
  1019. }
  1020. // hasEstablishedOnce indicates if at least one active tunnel has
  1021. // been established up to this point. This is regardeless of how many
  1022. // tunnels are presently active.
  1023. func (controller *Controller) hasEstablishedOnce() bool {
  1024. controller.tunnelMutex.Lock()
  1025. defer controller.tunnelMutex.Unlock()
  1026. return controller.establishedOnce
  1027. }
  1028. // isFullyEstablished indicates if the pool of active tunnels is full.
  1029. func (controller *Controller) isFullyEstablished() bool {
  1030. controller.tunnelMutex.Lock()
  1031. defer controller.tunnelMutex.Unlock()
  1032. return len(controller.tunnels) >= controller.tunnelPoolSize
  1033. }
  1034. // awaitFullyEstablished blocks until isFullyEstablished is true or the
  1035. // controller run ends.
  1036. func (controller *Controller) awaitFullyEstablished() bool {
  1037. // TODO: don't poll, add a signal
  1038. ticker := time.NewTicker(1 * time.Second)
  1039. defer ticker.Stop()
  1040. for {
  1041. if controller.isFullyEstablished() {
  1042. return true
  1043. }
  1044. select {
  1045. case <-ticker.C:
  1046. // Check isFullyEstablished again
  1047. case <-controller.runCtx.Done():
  1048. return false
  1049. }
  1050. }
  1051. }
  1052. // numTunnels returns the number of active and outstanding tunnels.
  1053. // Oustanding is the number of tunnels required to fill the pool of
  1054. // active tunnels.
  1055. func (controller *Controller) numTunnels() (int, int) {
  1056. controller.tunnelMutex.Lock()
  1057. defer controller.tunnelMutex.Unlock()
  1058. active := len(controller.tunnels)
  1059. outstanding := controller.tunnelPoolSize - len(controller.tunnels)
  1060. return active, outstanding
  1061. }
  1062. // terminateTunnel removes a tunnel from the pool of active tunnels
  1063. // and closes the tunnel. The next-tunnel state used by getNextActiveTunnel
  1064. // is adjusted as required.
  1065. func (controller *Controller) terminateTunnel(tunnel *Tunnel) {
  1066. controller.tunnelMutex.Lock()
  1067. defer controller.tunnelMutex.Unlock()
  1068. for index, activeTunnel := range controller.tunnels {
  1069. if tunnel == activeTunnel {
  1070. controller.tunnels = append(
  1071. controller.tunnels[:index], controller.tunnels[index+1:]...)
  1072. if controller.nextTunnel > index {
  1073. controller.nextTunnel--
  1074. }
  1075. if controller.nextTunnel >= len(controller.tunnels) {
  1076. controller.nextTunnel = 0
  1077. }
  1078. activeTunnel.Close(false)
  1079. NoticeTunnels(len(controller.tunnels))
  1080. break
  1081. }
  1082. }
  1083. }
  1084. // terminateAllTunnels empties the tunnel pool, closing all active tunnels.
  1085. // This is used when shutting down the controller.
  1086. func (controller *Controller) terminateAllTunnels() {
  1087. controller.tunnelMutex.Lock()
  1088. defer controller.tunnelMutex.Unlock()
  1089. // Closing all tunnels in parallel. In an orderly shutdown, each tunnel
  1090. // may take a few seconds to send a final status request. We only want
  1091. // to wait as long as the single slowest tunnel.
  1092. closeWaitGroup := new(sync.WaitGroup)
  1093. closeWaitGroup.Add(len(controller.tunnels))
  1094. for _, activeTunnel := range controller.tunnels {
  1095. tunnel := activeTunnel
  1096. go func() {
  1097. defer closeWaitGroup.Done()
  1098. tunnel.Close(false)
  1099. }()
  1100. }
  1101. closeWaitGroup.Wait()
  1102. controller.tunnels = make([]*Tunnel, 0)
  1103. controller.nextTunnel = 0
  1104. NoticeTunnels(len(controller.tunnels))
  1105. }
  1106. // getNextActiveTunnel returns the next tunnel from the pool of active
  1107. // tunnels. Currently, tunnel selection order is simple round-robin.
  1108. func (controller *Controller) getNextActiveTunnel() (tunnel *Tunnel) {
  1109. controller.tunnelMutex.Lock()
  1110. defer controller.tunnelMutex.Unlock()
  1111. if len(controller.tunnels) == 0 {
  1112. return nil
  1113. }
  1114. tunnel = controller.tunnels[controller.nextTunnel]
  1115. controller.nextTunnel =
  1116. (controller.nextTunnel + 1) % len(controller.tunnels)
  1117. return tunnel
  1118. }
  1119. // isActiveTunnelServerEntry is used to check if there's already
  1120. // an existing tunnel to a candidate server.
  1121. func (controller *Controller) isActiveTunnelServerEntry(
  1122. serverEntry *protocol.ServerEntry) bool {
  1123. controller.tunnelMutex.Lock()
  1124. defer controller.tunnelMutex.Unlock()
  1125. for _, activeTunnel := range controller.tunnels {
  1126. if activeTunnel.dialParams.ServerEntry.IpAddress == serverEntry.IpAddress {
  1127. return true
  1128. }
  1129. }
  1130. return false
  1131. }
  1132. func (controller *Controller) setTunnelPoolSize(tunnelPoolSize int) {
  1133. controller.tunnelMutex.Lock()
  1134. defer controller.tunnelMutex.Unlock()
  1135. if tunnelPoolSize < 1 {
  1136. tunnelPoolSize = 1
  1137. }
  1138. if tunnelPoolSize > MAX_TUNNEL_POOL_SIZE {
  1139. tunnelPoolSize = MAX_TUNNEL_POOL_SIZE
  1140. }
  1141. controller.tunnelPoolSize = tunnelPoolSize
  1142. }
  1143. func (controller *Controller) getTunnelPoolSize() int {
  1144. controller.tunnelMutex.Lock()
  1145. defer controller.tunnelMutex.Unlock()
  1146. return controller.tunnelPoolSize
  1147. }
  1148. // Dial selects an active tunnel and establishes a port forward
  1149. // connection through the selected tunnel. Failure to connect is considered
  1150. // a port forward failure, for the purpose of monitoring tunnel health.
  1151. //
  1152. // When split tunnel mode is enabled, the connection may be untunneled,
  1153. // depending on GeoIP classification of the destination.
  1154. //
  1155. // downstreamConn is an optional parameter which specifies a connection to be
  1156. // explicitly closed when the dialed connection is closed. For instance, this
  1157. // is used to close downstreamConn App<->LocalProxy connections when the
  1158. // related LocalProxy<->SshPortForward connections close.
  1159. func (controller *Controller) Dial(
  1160. remoteAddr string, downstreamConn net.Conn) (conn net.Conn, err error) {
  1161. tunnel := controller.getNextActiveTunnel()
  1162. if tunnel == nil {
  1163. return nil, errors.TraceNew("no active tunnels")
  1164. }
  1165. if !tunnel.config.IsSplitTunnelEnabled() {
  1166. tunneledConn, splitTunnel, err := tunnel.DialTCPChannel(
  1167. remoteAddr, false, downstreamConn)
  1168. if err != nil {
  1169. return nil, errors.Trace(err)
  1170. }
  1171. if splitTunnel {
  1172. return nil, errors.TraceNew(
  1173. "unexpected split tunnel classification")
  1174. }
  1175. return tunneledConn, nil
  1176. }
  1177. // In split tunnel mode, TCP port forwards to destinations in the same
  1178. // country as the client are untunneled.
  1179. //
  1180. // Split tunnel is implemented with assistence from the server to classify
  1181. // destinations as being in the same country as the client. The server knows
  1182. // the client's public IP GeoIP data, and, for clients with split tunnel mode
  1183. // enabled, the server resolves the port forward destination address and
  1184. // checks the destination IP GeoIP data.
  1185. //
  1186. // When the countries match, the server "rejects" the port forward with a
  1187. // distinct response that indicates to the client that an untunneled port
  1188. // foward should be established locally.
  1189. //
  1190. // The client maintains a classification cache that allows it to make
  1191. // untunneled port forwards without requiring a round trip to the server.
  1192. // Only destinations classified as untunneled are stored in the cache: a
  1193. // destination classified as tunneled requires the same round trip as an
  1194. // unknown destination.
  1195. //
  1196. // When the countries do not match, the server establishes a port forward, as
  1197. // it does for all port forwards in non-split tunnel mode. There is no
  1198. // additional round trip for tunneled port forwards.
  1199. //
  1200. // Each destination includes a host and port. Since there are special
  1201. // cases where the server performs transparent redirection for specific
  1202. // host:port combinations, including UDPInterceptUdpgwServerAddress, the
  1203. // classification can differ for the same host but different ports and so
  1204. // the classification is cached using the full address, host:port, as the
  1205. // key. While this results in additional classification round trips for
  1206. // destinations with the same domain but differing ports, in practise
  1207. // most destinations use only port 443.
  1208. untunneledCache := controller.untunneledSplitTunnelClassifications
  1209. // If the destination is in the untunneled split tunnel classifications
  1210. // cache, skip the round trip to the server and do the direct, untunneled
  1211. // dial immediately.
  1212. _, cachedUntunneled := untunneledCache.Get(remoteAddr)
  1213. if !cachedUntunneled {
  1214. tunneledConn, splitTunnel, err := tunnel.DialTCPChannel(
  1215. remoteAddr, false, downstreamConn)
  1216. if err != nil {
  1217. return nil, errors.Trace(err)
  1218. }
  1219. if !splitTunnel {
  1220. // Clear any cached untunneled classification entry for this
  1221. // destination, as the server is now classifying it as tunneled.
  1222. untunneledCache.Delete(remoteAddr)
  1223. return tunneledConn, nil
  1224. }
  1225. // The server has indicated that the client should make a direct,
  1226. // untunneled dial. Cache the classification to avoid this round trip in
  1227. // the immediate future.
  1228. untunneledCache.Add(remoteAddr, true, lrucache.DefaultExpiration)
  1229. }
  1230. NoticeUntunneled(remoteAddr)
  1231. untunneledConn, err := controller.DirectDial(remoteAddr)
  1232. if err != nil {
  1233. return nil, errors.Trace(err)
  1234. }
  1235. return untunneledConn, nil
  1236. }
  1237. // DirectDial dials an untunneled TCP connection within the controller run context.
  1238. func (controller *Controller) DirectDial(remoteAddr string) (conn net.Conn, err error) {
  1239. return DialTCP(controller.runCtx, remoteAddr, controller.untunneledDialConfig)
  1240. }
  1241. // triggerFetches signals RSL, OSL, and upgrade download fetchers to begin, if
  1242. // not already running. triggerFetches is called when tunnel establishment
  1243. // fails to complete within a deadline and in other cases where local
  1244. // circumvention capabilities are lacking and we may require new server
  1245. // entries or client versions with new capabilities.
  1246. func (controller *Controller) triggerFetches() {
  1247. // Trigger a common remote server list fetch, since we may have failed
  1248. // to connect with all known servers. Don't block sending signal, since
  1249. // this signal may have already been sent.
  1250. // Don't wait for fetch remote to succeed, since it may fail and
  1251. // enter a retry loop and we're better off trying more known servers.
  1252. // TODO: synchronize the fetch response, so it can be incorporated
  1253. // into the server entry iterator as soon as available.
  1254. select {
  1255. case controller.signalFetchCommonRemoteServerList <- struct{}{}:
  1256. default:
  1257. }
  1258. // Trigger an OSL fetch in parallel. Both fetches are run in parallel
  1259. // so that if one out of the common RLS and OSL set is large, it doesn't
  1260. // doesn't entirely block fetching the other.
  1261. select {
  1262. case controller.signalFetchObfuscatedServerLists <- struct{}{}:
  1263. default:
  1264. }
  1265. // Trigger an out-of-band upgrade availability check and download.
  1266. // Since we may have failed to connect, we may benefit from upgrading
  1267. // to a new client version with new circumvention capabilities.
  1268. select {
  1269. case controller.signalDownloadUpgrade <- "":
  1270. default:
  1271. }
  1272. }
  1273. type protocolSelectionConstraints struct {
  1274. useUpstreamProxy bool
  1275. initialLimitTunnelProtocols protocol.TunnelProtocols
  1276. initialLimitTunnelProtocolsCandidateCount int
  1277. limitTunnelProtocols protocol.TunnelProtocols
  1278. limitTunnelDialPortNumbers protocol.TunnelProtocolPortLists
  1279. limitQUICVersions protocol.QUICVersions
  1280. replayCandidateCount int
  1281. }
  1282. func (p *protocolSelectionConstraints) hasInitialProtocols() bool {
  1283. return len(p.initialLimitTunnelProtocols) > 0 && p.initialLimitTunnelProtocolsCandidateCount > 0
  1284. }
  1285. func (p *protocolSelectionConstraints) isInitialCandidate(
  1286. excludeIntensive bool,
  1287. serverEntry *protocol.ServerEntry) bool {
  1288. return p.hasInitialProtocols() &&
  1289. len(serverEntry.GetSupportedProtocols(
  1290. conditionallyEnabledComponents{},
  1291. p.useUpstreamProxy,
  1292. p.initialLimitTunnelProtocols,
  1293. p.limitTunnelDialPortNumbers,
  1294. p.limitQUICVersions,
  1295. excludeIntensive,
  1296. false)) > 0
  1297. }
  1298. func (p *protocolSelectionConstraints) isCandidate(
  1299. excludeIntensive bool,
  1300. serverEntry *protocol.ServerEntry) bool {
  1301. return len(serverEntry.GetSupportedProtocols(
  1302. conditionallyEnabledComponents{},
  1303. p.useUpstreamProxy,
  1304. p.limitTunnelProtocols,
  1305. p.limitTunnelDialPortNumbers,
  1306. p.limitQUICVersions,
  1307. excludeIntensive,
  1308. false)) > 0
  1309. }
  1310. func (p *protocolSelectionConstraints) canReplay(
  1311. connectTunnelCount int,
  1312. excludeIntensive bool,
  1313. serverEntry *protocol.ServerEntry,
  1314. replayProtocol string) bool {
  1315. if p.replayCandidateCount != -1 && connectTunnelCount > p.replayCandidateCount {
  1316. return false
  1317. }
  1318. return common.Contains(
  1319. p.supportedProtocols(
  1320. connectTunnelCount, excludeIntensive, false, serverEntry),
  1321. replayProtocol)
  1322. }
  1323. func (p *protocolSelectionConstraints) supportedProtocols(
  1324. connectTunnelCount int,
  1325. excludeIntensive bool,
  1326. excludeInproxy bool,
  1327. serverEntry *protocol.ServerEntry) []string {
  1328. limitTunnelProtocols := p.limitTunnelProtocols
  1329. if len(p.initialLimitTunnelProtocols) > 0 &&
  1330. p.initialLimitTunnelProtocolsCandidateCount > connectTunnelCount {
  1331. limitTunnelProtocols = p.initialLimitTunnelProtocols
  1332. }
  1333. return serverEntry.GetSupportedProtocols(
  1334. conditionallyEnabledComponents{},
  1335. p.useUpstreamProxy,
  1336. limitTunnelProtocols,
  1337. p.limitTunnelDialPortNumbers,
  1338. p.limitQUICVersions,
  1339. excludeIntensive,
  1340. excludeInproxy)
  1341. }
  1342. func (p *protocolSelectionConstraints) selectProtocol(
  1343. connectTunnelCount int,
  1344. excludeIntensive bool,
  1345. excludeInproxy bool,
  1346. serverEntry *protocol.ServerEntry) (string, bool) {
  1347. candidateProtocols := p.supportedProtocols(
  1348. connectTunnelCount, excludeIntensive, excludeInproxy, serverEntry)
  1349. if len(candidateProtocols) == 0 {
  1350. return "", false
  1351. }
  1352. // Pick at random from the supported protocols. This ensures that we'll
  1353. // eventually try all possible protocols. Depending on network
  1354. // configuration, it may be the case that some protocol is only available
  1355. // through multi-capability servers, and a simpler ranked preference of
  1356. // protocols could lead to that protocol never being selected.
  1357. index := prng.Intn(len(candidateProtocols))
  1358. return candidateProtocols[index], true
  1359. }
  1360. type candidateServerEntry struct {
  1361. serverEntry *protocol.ServerEntry
  1362. isServerAffinityCandidate bool
  1363. adjustedEstablishStartTime time.Time
  1364. }
  1365. // startEstablishing creates a pool of worker goroutines which will
  1366. // attempt to establish tunnels to candidate servers. The candidates
  1367. // are generated by another goroutine.
  1368. func (controller *Controller) startEstablishing() {
  1369. if controller.isEstablishing {
  1370. return
  1371. }
  1372. NoticeInfo("start establishing")
  1373. // establishStartTime is used to calculate and report the client's tunnel
  1374. // establishment duration. Establishment duration should include all
  1375. // initialization in launchEstablishing and establishCandidateGenerator,
  1376. // including any potentially long-running datastore iterations.
  1377. establishStartTime := time.Now()
  1378. controller.concurrentEstablishTunnelsMutex.Lock()
  1379. controller.establishConnectTunnelCount = 0
  1380. controller.concurrentEstablishTunnels = 0
  1381. controller.concurrentIntensiveEstablishTunnels = 0
  1382. controller.peakConcurrentEstablishTunnels = 0
  1383. controller.peakConcurrentIntensiveEstablishTunnels = 0
  1384. controller.concurrentEstablishTunnelsMutex.Unlock()
  1385. DoGarbageCollection()
  1386. emitMemoryMetrics()
  1387. // The establish context cancelFunc, controller.stopEstablish, is called in
  1388. // controller.stopEstablishing.
  1389. controller.isEstablishing = true
  1390. controller.establishStartTime = establishStartTime
  1391. controller.establishCtx, controller.stopEstablish = context.WithCancel(controller.runCtx)
  1392. controller.establishWaitGroup = new(sync.WaitGroup)
  1393. controller.candidateServerEntries = make(chan *candidateServerEntry)
  1394. // The server affinity mechanism attempts to favor the previously
  1395. // used server when reconnecting. This is beneficial for user
  1396. // applications which expect consistency in user IP address (for
  1397. // example, a web site which prompts for additional user
  1398. // authentication when the IP address changes).
  1399. //
  1400. // Only the very first server, as determined by
  1401. // datastore.PromoteServerEntry(), is the server affinity candidate.
  1402. // Concurrent connections attempts to many servers are launched
  1403. // without delay, in case the affinity server connection fails.
  1404. // While the affinity server connection is outstanding, when any
  1405. // other connection is established, there is a short grace period
  1406. // delay before delivering the established tunnel; this allows some
  1407. // time for the affinity server connection to succeed first.
  1408. // When the affinity server connection fails, any other established
  1409. // tunnel is registered without delay.
  1410. //
  1411. // Note: the establishTunnelWorker that receives the affinity
  1412. // candidate is solely resonsible for closing
  1413. // controller.serverAffinityDoneBroadcast.
  1414. controller.serverAffinityDoneBroadcast = make(chan struct{})
  1415. controller.establishWaitGroup.Add(1)
  1416. go controller.launchEstablishing()
  1417. }
  1418. func (controller *Controller) launchEstablishing() {
  1419. defer controller.establishWaitGroup.Done()
  1420. // Before starting the establish tunnel workers, get and apply
  1421. // tactics, launching a tactics request if required.
  1422. //
  1423. // Wait only TacticsWaitPeriod for the tactics request to complete (or
  1424. // fail) before proceeding with tunnel establishment, in case the tactics
  1425. // request is blocked or takes very long to complete.
  1426. //
  1427. // An in-flight tactics request uses meek in round tripper mode, which
  1428. // uses less resources than meek tunnel relay mode. For this reason, the
  1429. // tactics request is not counted in concurrentIntensiveEstablishTunnels.
  1430. //
  1431. // TODO: HTTP/2 uses significantly more memory, so perhaps
  1432. // concurrentIntensiveEstablishTunnels should be counted in that case.
  1433. //
  1434. // Any in-flight tactics request or pending retry will be
  1435. // canceled when establishment is stopped.
  1436. if !controller.config.DisableTactics {
  1437. timeout := controller.config.GetParameters().Get().Duration(
  1438. parameters.TacticsWaitPeriod)
  1439. tacticsDone := make(chan struct{})
  1440. tacticsWaitPeriod := time.NewTimer(timeout)
  1441. defer tacticsWaitPeriod.Stop()
  1442. controller.establishWaitGroup.Add(1)
  1443. go func() {
  1444. defer controller.establishWaitGroup.Done()
  1445. defer close(tacticsDone)
  1446. GetTactics(controller.establishCtx, controller.config)
  1447. }()
  1448. select {
  1449. case <-tacticsDone:
  1450. case <-tacticsWaitPeriod.C:
  1451. }
  1452. tacticsWaitPeriod.Stop()
  1453. if controller.isStopEstablishing() {
  1454. // This check isn't strictly required but avoids the overhead of launching
  1455. // workers if establishment stopped while awaiting a tactics request.
  1456. return
  1457. }
  1458. }
  1459. // Initial- and LimitTunnelProtocols may be set by tactics.
  1460. //
  1461. // These protocol limits are fixed once per establishment, for
  1462. // consistent application of related probabilities (applied by
  1463. // ParametersAccessor.TunnelProtocols). The
  1464. // establishLimitTunnelProtocolsState field must be read-only after this
  1465. // point, allowing concurrent reads by establishment workers.
  1466. p := controller.config.GetParameters().Get()
  1467. controller.protocolSelectionConstraints = &protocolSelectionConstraints{
  1468. useUpstreamProxy: controller.config.UseUpstreamProxy(),
  1469. initialLimitTunnelProtocols: p.TunnelProtocols(parameters.InitialLimitTunnelProtocols),
  1470. initialLimitTunnelProtocolsCandidateCount: p.Int(parameters.InitialLimitTunnelProtocolsCandidateCount),
  1471. limitTunnelProtocols: p.TunnelProtocols(parameters.LimitTunnelProtocols),
  1472. limitTunnelDialPortNumbers: protocol.TunnelProtocolPortLists(
  1473. p.TunnelProtocolPortLists(parameters.LimitTunnelDialPortNumbers)),
  1474. replayCandidateCount: p.Int(parameters.ReplayCandidateCount),
  1475. }
  1476. // Adjust protocol limits for in-proxy personal proxy mode. In this mode,
  1477. // the client will make connections only through a proxy with the
  1478. // corresponding personal compartment ID, so non-in-proxy tunnel
  1479. // protocols are disabled.
  1480. if len(controller.config.InproxyPersonalCompartmentIDs) > 0 {
  1481. if len(controller.protocolSelectionConstraints.initialLimitTunnelProtocols) > 0 {
  1482. controller.protocolSelectionConstraints.initialLimitTunnelProtocols =
  1483. controller.protocolSelectionConstraints.
  1484. initialLimitTunnelProtocols.OnlyInproxyTunnelProtocols()
  1485. }
  1486. if len(controller.protocolSelectionConstraints.limitTunnelProtocols) > 0 {
  1487. controller.protocolSelectionConstraints.limitTunnelProtocols =
  1488. controller.protocolSelectionConstraints.
  1489. limitTunnelProtocols.OnlyInproxyTunnelProtocols()
  1490. } else {
  1491. controller.protocolSelectionConstraints.limitTunnelProtocols =
  1492. protocol.InproxyTunnelProtocols
  1493. }
  1494. }
  1495. // ConnectionWorkerPoolSize may be set by tactics.
  1496. workerPoolSize := p.Int(parameters.ConnectionWorkerPoolSize)
  1497. // When TargetServerEntry is used, override any worker pool size config or
  1498. // tactic parameter and use a pool size of 1. The typical use case for
  1499. // TargetServerEntry is to test a specific server with a single connection
  1500. // attempt. Furthermore, too many concurrent attempts to connect to the
  1501. // same server will trigger rate limiting.
  1502. if controller.config.TargetServerEntry != "" {
  1503. workerPoolSize = 1
  1504. }
  1505. // TunnelPoolSize may be set by tactics, subject to local constraints. A pool
  1506. // size of one is forced in packet tunnel mode or when using a
  1507. // TargetServerEntry. The tunnel pool size is reduced when there are
  1508. // insufficent known server entries, within the set region and protocol
  1509. // constraints, to satisfy the target.
  1510. //
  1511. // Limitations, to simplify concurrent access to shared state: a ceiling of
  1512. // MAX_TUNNEL_POOL_SIZE is enforced by setTunnelPoolSize; the tunnel pool
  1513. // size target is not re-adjusted after an API handshake, even though the
  1514. // handshake response may deliver new tactics, or prune server entries which
  1515. // were potential candidates; nor is the target re-adjusted after fetching
  1516. // new server entries during this establishment.
  1517. tunnelPoolSize := p.Int(parameters.TunnelPoolSize)
  1518. if controller.config.PacketTunnelTunFileDescriptor > 0 ||
  1519. controller.config.TargetServerEntry != "" {
  1520. tunnelPoolSize = 1
  1521. }
  1522. p.Close()
  1523. // Trigger CandidateServers and AvailableEgressRegions notices. By default,
  1524. // this is an asynchronous operation, as the underlying full server entry
  1525. // list enumeration may be a slow operation. In certain cases, where
  1526. // candidate counts are required up front, await the result before
  1527. // proceeding.
  1528. awaitResponse := tunnelPoolSize > 1 ||
  1529. controller.protocolSelectionConstraints.initialLimitTunnelProtocolsCandidateCount > 0
  1530. // AvailableEgressRegions: after a fresh install, the outer client may not
  1531. // have a list of regions to display; and LimitTunnelProtocols may reduce the
  1532. // number of available regions.
  1533. //
  1534. // When the outer client receives NoticeAvailableEgressRegions and the
  1535. // configured EgressRegion is not included in the region list, the outer
  1536. // client _should_ stop tunnel-core and prompt the user to change the region
  1537. // selection, as there are insufficient servers/capabilities to establish a
  1538. // tunnel in the selected region.
  1539. //
  1540. // This report is delayed until after tactics are likely to be applied,
  1541. // above; this avoids a ReportAvailableRegions reporting too many regions,
  1542. // followed shortly by a ReportAvailableRegions reporting fewer regions. That
  1543. // sequence could cause issues in the outer client UI.
  1544. //
  1545. // The reported regions are limited by protocolSelectionConstraints; in the
  1546. // case where an initial limit is in place, only regions available for the
  1547. // initial limit are reported. The initial phase will not complete if
  1548. // EgressRegion is set such that there are no server entries with the
  1549. // necessary protocol capabilities (either locally or from a remote server
  1550. // list fetch).
  1551. // Concurrency note: controller.protocolSelectionConstraints may be
  1552. // overwritten before serverEntriesReporter reads it, and so cannot be
  1553. // accessed directly by serverEntriesReporter.
  1554. reportRequest := &serverEntriesReportRequest{
  1555. constraints: controller.protocolSelectionConstraints,
  1556. }
  1557. if awaitResponse {
  1558. // Buffer size of 1 ensures the sender, serverEntryReporter, won't block on
  1559. // sending the response in the case where launchEstablishing exits due to
  1560. // stopping establishment.
  1561. reportRequest.awaitResponse = make(chan *serverEntriesReportResponse, 1)
  1562. }
  1563. controller.signalServerEntriesReporter(reportRequest)
  1564. if awaitResponse {
  1565. var reportResponse *serverEntriesReportResponse
  1566. select {
  1567. case reportResponse = <-reportRequest.awaitResponse:
  1568. case <-controller.establishCtx.Done():
  1569. // The sender may be gone when shutting down, or may not send until after
  1570. // stopping establishment.
  1571. return
  1572. }
  1573. if reportResponse.err != nil {
  1574. NoticeError("failed to report server entries: %v",
  1575. errors.Trace(reportResponse.err))
  1576. controller.SignalComponentFailure()
  1577. return
  1578. }
  1579. // Make adjustments based on candidate counts.
  1580. if tunnelPoolSize > 1 {
  1581. // Initial canidate count is ignored as count candidates will eventually
  1582. // become available.
  1583. if reportResponse.candidates < tunnelPoolSize {
  1584. tunnelPoolSize = reportResponse.candidates
  1585. }
  1586. if tunnelPoolSize < 1 {
  1587. tunnelPoolSize = 1
  1588. }
  1589. }
  1590. controller.setTunnelPoolSize(tunnelPoolSize)
  1591. // If InitialLimitTunnelProtocols is configured but cannot be satisfied,
  1592. // skip the initial phase in this establishment. This avoids spinning,
  1593. // unable to connect, in this case. InitialLimitTunnelProtocols is
  1594. // intended to prioritize certain protocols, but not strictly select them.
  1595. //
  1596. // The candidate count check ignores egress region selection. When an egress
  1597. // region is selected, it's the responsibility of the outer client to react
  1598. // to the following ReportAvailableRegions output and clear the user's
  1599. // selected region to prevent spinning, unable to connect. The initial phase
  1600. // is skipped only when InitialLimitTunnelProtocols cannot be satisfied
  1601. // _regardless_ of region selection.
  1602. //
  1603. // We presume that, in practise, most clients will have embedded server
  1604. // entries with capabilities for most protocols; and that clients will
  1605. // often perform RSL checks. So clients should most often have the
  1606. // necessary capabilities to satisfy InitialLimitTunnelProtocols. When
  1607. // this check fails, RSL/OSL/upgrade checks are triggered in order to gain
  1608. // new capabilities.
  1609. //
  1610. // LimitTunnelProtocols remains a hard limit, as using prohibited
  1611. // protocols may have some bad effect, such as a firewall blocking all
  1612. // traffic from a host.
  1613. if controller.protocolSelectionConstraints.initialLimitTunnelProtocolsCandidateCount > 0 {
  1614. if reportResponse.initialCandidatesAnyEgressRegion == 0 {
  1615. NoticeWarning("skipping initial limit tunnel protocols")
  1616. controller.protocolSelectionConstraints.initialLimitTunnelProtocolsCandidateCount = 0
  1617. // Since we were unable to satisfy the InitialLimitTunnelProtocols
  1618. // tactic, trigger RSL, OSL, and upgrade fetches to potentially
  1619. // gain new capabilities.
  1620. controller.triggerFetches()
  1621. }
  1622. }
  1623. }
  1624. for i := 0; i < workerPoolSize; i++ {
  1625. controller.establishWaitGroup.Add(1)
  1626. go controller.establishTunnelWorker()
  1627. }
  1628. controller.establishWaitGroup.Add(1)
  1629. go controller.establishCandidateGenerator()
  1630. }
  1631. // stopEstablishing signals the establish goroutines to stop and waits
  1632. // for the group to halt.
  1633. func (controller *Controller) stopEstablishing() {
  1634. if !controller.isEstablishing {
  1635. return
  1636. }
  1637. NoticeInfo("stop establishing")
  1638. controller.stopEstablish()
  1639. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  1640. // (as it may be sending to that channel).
  1641. controller.establishWaitGroup.Wait()
  1642. NoticeInfo("stopped establishing")
  1643. controller.isEstablishing = false
  1644. controller.establishStartTime = time.Time{}
  1645. controller.establishCtx = nil
  1646. controller.stopEstablish = nil
  1647. controller.establishWaitGroup = nil
  1648. controller.candidateServerEntries = nil
  1649. controller.serverAffinityDoneBroadcast = nil
  1650. controller.concurrentEstablishTunnelsMutex.Lock()
  1651. peakConcurrent := controller.peakConcurrentEstablishTunnels
  1652. peakConcurrentIntensive := controller.peakConcurrentIntensiveEstablishTunnels
  1653. controller.establishConnectTunnelCount = 0
  1654. controller.concurrentEstablishTunnels = 0
  1655. controller.concurrentIntensiveEstablishTunnels = 0
  1656. controller.peakConcurrentEstablishTunnels = 0
  1657. controller.peakConcurrentIntensiveEstablishTunnels = 0
  1658. controller.concurrentEstablishTunnelsMutex.Unlock()
  1659. NoticeInfo("peak concurrent establish tunnels: %d", peakConcurrent)
  1660. NoticeInfo("peak concurrent resource intensive establish tunnels: %d", peakConcurrentIntensive)
  1661. emitMemoryMetrics()
  1662. DoGarbageCollection()
  1663. // Record datastore metrics after establishment, the phase which generates
  1664. // the bulk of all datastore transactions: iterating over server entries,
  1665. // storing new server entries, etc.
  1666. emitDatastoreMetrics()
  1667. // Similarly, establishment generates the bulk of domain resolves.
  1668. emitDNSMetrics(controller.resolver)
  1669. }
  1670. // establishCandidateGenerator populates the candidate queue with server entries
  1671. // from the data store. Server entries are iterated in rank order, so that promoted
  1672. // servers with higher rank are priority candidates.
  1673. func (controller *Controller) establishCandidateGenerator() {
  1674. defer controller.establishWaitGroup.Done()
  1675. defer close(controller.candidateServerEntries)
  1676. // networkWaitDuration is the elapsed time spent waiting
  1677. // for network connectivity. This duration will be excluded
  1678. // from reported tunnel establishment duration.
  1679. var totalNetworkWaitDuration time.Duration
  1680. applyServerAffinity, iterator, err := NewServerEntryIterator(controller.config)
  1681. if err != nil {
  1682. NoticeError("failed to iterate over candidates: %v", errors.Trace(err))
  1683. controller.SignalComponentFailure()
  1684. return
  1685. }
  1686. defer iterator.Close()
  1687. // TODO: reconcile server affinity scheme with multi-tunnel mode
  1688. if controller.getTunnelPoolSize() > 1 {
  1689. applyServerAffinity = false
  1690. }
  1691. isServerAffinityCandidate := true
  1692. if !applyServerAffinity {
  1693. isServerAffinityCandidate = false
  1694. close(controller.serverAffinityDoneBroadcast)
  1695. }
  1696. loop:
  1697. // Repeat until stopped
  1698. for {
  1699. // A "round" consists of a new shuffle of the server entries and attempted
  1700. // connections up to the end of the server entry iterator, or
  1701. // parameters.EstablishTunnelWorkTime elapsed. Time spent waiting for
  1702. // network connectivity is excluded from round elapsed time.
  1703. //
  1704. // After a round, if parameters.EstablishTunnelWorkTime has elapsed in total
  1705. // with no tunnel established, remote server list and upgrade checks are
  1706. // triggered.
  1707. //
  1708. // A complete server entry iteration does not trigger fetches since it's
  1709. // possible to have fewer than parameters.ConnectionWorkerPoolSize
  1710. // candidates, in which case rounds end instantly due to the complete server
  1711. // entry iteration. An exception is made for an empty server entry iterator;
  1712. // in that case fetches may be triggered immediately.
  1713. //
  1714. // The number of server candidates may change during this loop, due to
  1715. // remote server list fetches. Due to the performance impact, we will not
  1716. // trigger additional, informational CandidateServer notices while in the
  1717. // establishing loop. Clients typically re-establish often enough that we
  1718. // will see the effect of the remote server list fetch in diagnostics.
  1719. roundStartTime := time.Now()
  1720. var roundNetworkWaitDuration time.Duration
  1721. workTime := controller.config.GetParameters().Get().Duration(
  1722. parameters.EstablishTunnelWorkTime)
  1723. candidateServerEntryCount := 0
  1724. // Send each iterator server entry to the establish workers
  1725. for {
  1726. networkWaitStartTime := time.Now()
  1727. if !WaitForNetworkConnectivity(
  1728. controller.establishCtx,
  1729. controller.config.NetworkConnectivityChecker) {
  1730. break loop
  1731. }
  1732. networkWaitDuration := time.Since(networkWaitStartTime)
  1733. roundNetworkWaitDuration += networkWaitDuration
  1734. totalNetworkWaitDuration += networkWaitDuration
  1735. serverEntry, err := iterator.Next()
  1736. if err != nil {
  1737. NoticeError("failed to get next candidate: %v", errors.Trace(err))
  1738. controller.SignalComponentFailure()
  1739. break loop
  1740. }
  1741. if serverEntry == nil {
  1742. // Completed this iteration
  1743. NoticeInfo("completed server entry iteration")
  1744. break
  1745. }
  1746. if controller.config.TargetAPIProtocol == protocol.PSIPHON_API_PROTOCOL_SSH &&
  1747. !serverEntry.SupportsSSHAPIRequests() {
  1748. continue
  1749. }
  1750. candidateServerEntryCount += 1
  1751. // adjustedEstablishStartTime is establishStartTime shifted
  1752. // to exclude time spent waiting for network connectivity.
  1753. adjustedEstablishStartTime := controller.establishStartTime.Add(
  1754. totalNetworkWaitDuration)
  1755. candidate := &candidateServerEntry{
  1756. serverEntry: serverEntry,
  1757. isServerAffinityCandidate: isServerAffinityCandidate,
  1758. adjustedEstablishStartTime: adjustedEstablishStartTime,
  1759. }
  1760. wasServerAffinityCandidate := isServerAffinityCandidate
  1761. // Note: there must be only one server affinity candidate, as it
  1762. // closes the serverAffinityDoneBroadcast channel.
  1763. isServerAffinityCandidate = false
  1764. // TODO: here we could generate multiple candidates from the
  1765. // server entry when there are many MeekFrontingAddresses.
  1766. select {
  1767. case controller.candidateServerEntries <- candidate:
  1768. case <-controller.establishCtx.Done():
  1769. break loop
  1770. }
  1771. if time.Since(roundStartTime)-roundNetworkWaitDuration > workTime {
  1772. // Start over, after a brief pause, with a new shuffle of the server
  1773. // entries, and potentially some newly fetched server entries.
  1774. break
  1775. }
  1776. if wasServerAffinityCandidate {
  1777. // Don't start the next candidate until either the server affinity
  1778. // candidate has completed (success or failure) or is still working
  1779. // and the grace period has elapsed.
  1780. gracePeriod := controller.config.GetParameters().Get().Duration(
  1781. parameters.EstablishTunnelServerAffinityGracePeriod)
  1782. if gracePeriod > 0 {
  1783. timer := time.NewTimer(gracePeriod)
  1784. select {
  1785. case <-timer.C:
  1786. case <-controller.serverAffinityDoneBroadcast:
  1787. case <-controller.establishCtx.Done():
  1788. timer.Stop()
  1789. break loop
  1790. }
  1791. timer.Stop()
  1792. }
  1793. }
  1794. }
  1795. // Free up resources now, but don't reset until after the pause.
  1796. iterator.Close()
  1797. // Trigger RSL, OSL, and upgrade checks after failing to establish a
  1798. // tunnel within parameters.EstablishTunnelWorkTime, or if there are
  1799. // no server entries present.
  1800. //
  1801. // While the trigger is made after each round,
  1802. // parameter.FetchRemoteServerListStalePeriod will limit the actual
  1803. // frequency of fetches. Continuing to trigger allows for very long running
  1804. // establishments to perhaps eventually succeed.
  1805. //
  1806. // No fetches are triggered when TargetServerEntry is specified. In that
  1807. // case, we're only trying to connect to a specific server entry.
  1808. if (candidateServerEntryCount == 0 ||
  1809. time.Since(controller.establishStartTime)-totalNetworkWaitDuration > workTime) &&
  1810. controller.config.TargetServerEntry == "" {
  1811. controller.triggerFetches()
  1812. }
  1813. // After a complete iteration of candidate servers, pause before iterating again.
  1814. // This helps avoid some busy wait loop conditions, and also allows some time for
  1815. // network conditions to change. Also allows for fetch remote to complete,
  1816. // in typical conditions (it isn't strictly necessary to wait for this, there will
  1817. // be more rounds if required).
  1818. p := controller.config.GetParameters().Get()
  1819. timeout := prng.JitterDuration(
  1820. p.Duration(parameters.EstablishTunnelPausePeriod),
  1821. p.Float(parameters.EstablishTunnelPausePeriodJitter))
  1822. p.Close()
  1823. timer := time.NewTimer(timeout)
  1824. select {
  1825. case <-timer.C:
  1826. // Retry iterating
  1827. case <-controller.establishCtx.Done():
  1828. timer.Stop()
  1829. break loop
  1830. }
  1831. timer.Stop()
  1832. iterator.Reset()
  1833. }
  1834. }
  1835. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  1836. // a connection to the tunnel server, and delivers the connected tunnel to a channel.
  1837. func (controller *Controller) establishTunnelWorker() {
  1838. defer controller.establishWaitGroup.Done()
  1839. loop:
  1840. for candidateServerEntry := range controller.candidateServerEntries {
  1841. // Note: don't receive from candidateServerEntries and isStopEstablishing
  1842. // in the same select, since we want to prioritize receiving the stop signal
  1843. if controller.isStopEstablishing() {
  1844. break loop
  1845. }
  1846. // There may already be a tunnel to this candidate. If so, skip it.
  1847. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1848. continue
  1849. }
  1850. // TODO: we allow multiple, concurrent workers to attempt to connect to the
  1851. // same server. This is not wasteful if the server supports several
  1852. // different protocols, some of which may be blocked while others are not
  1853. // blocked. Limiting protocols with [Initial]LimitTunnelProtocols may make
  1854. // these multiple attempts redundent. Also, replay should be used only by
  1855. // the first attempt.
  1856. // upstreamProxyErrorCallback will post NoticeUpstreamProxyError when the
  1857. // tunnel dial fails due to an upstream proxy error. As the upstream proxy
  1858. // is user configured, the error message may need to be relayed to the user.
  1859. // As the callback may be invoked after establishment is over (e.g., if an
  1860. // initial dial isn't fully shutdown when ConnectTunnel returns; or a meek
  1861. // underlying TCP connection re-dial) don't access these variables
  1862. // directly.
  1863. callbackCandidateServerEntry := candidateServerEntry
  1864. callbackEstablishCtx := controller.establishCtx
  1865. upstreamProxyErrorCallback := func(err error) {
  1866. // Do not post the notice when overall establishment context is canceled or
  1867. // timed-out: the upstream proxy connection error is likely a result of the
  1868. // cancellation, and not a condition to be fixed by the user. In the case
  1869. // of meek underlying TCP connection re-dials, this condition will always
  1870. // be true; however in this case the initial dial succeeded with the
  1871. // current upstream proxy settings, so any upstream proxy error is
  1872. // transient.
  1873. if callbackEstablishCtx.Err() != nil {
  1874. return
  1875. }
  1876. // Another class of non-fatal upstream proxy error arises from proxies
  1877. // which limit permitted proxied ports. In this case, some tunnels may fail
  1878. // due to dial port, while others may eventually succeed. To avoid this
  1879. // class of errors, delay posting the notice. If the upstream proxy works,
  1880. // _some_ tunnel should connect. If the upstream proxy configuration is
  1881. // broken, the error should persist and eventually get posted.
  1882. p := controller.config.GetParameters().Get()
  1883. workerPoolSize := p.Int(parameters.ConnectionWorkerPoolSize)
  1884. minWaitDuration := p.Duration(parameters.UpstreamProxyErrorMinWaitDuration)
  1885. maxWaitDuration := p.Duration(parameters.UpstreamProxyErrorMaxWaitDuration)
  1886. p.Close()
  1887. controller.concurrentEstablishTunnelsMutex.Lock()
  1888. establishConnectTunnelCount := controller.establishConnectTunnelCount
  1889. controller.concurrentEstablishTunnelsMutex.Unlock()
  1890. // Delay UpstreamProxyErrorMinWaitDuration (excluding time spent waiting
  1891. // for network connectivity) and then until either
  1892. // UpstreamProxyErrorMaxWaitDuration has elapsed or, to post sooner if many
  1893. // candidates are failing, at least workerPoolSize tunnel connection
  1894. // attempts have completed. We infer that at least workerPoolSize
  1895. // candidates have completed by checking that at least 2*workerPoolSize
  1896. // candidates have started.
  1897. elapsedTime := time.Since(
  1898. callbackCandidateServerEntry.adjustedEstablishStartTime)
  1899. if elapsedTime < minWaitDuration ||
  1900. (elapsedTime < maxWaitDuration &&
  1901. establishConnectTunnelCount < 2*workerPoolSize) {
  1902. return
  1903. }
  1904. NoticeUpstreamProxyError(err)
  1905. }
  1906. // Select the tunnel protocol. The selection will be made at random
  1907. // from protocols supported by the server entry, optionally limited by
  1908. // LimitTunnelProtocols.
  1909. //
  1910. // When limiting concurrent resource intensive protocol connection
  1911. // workers, and at the limit, do not select resource intensive
  1912. // protocols since otherwise the candidate must be skipped.
  1913. //
  1914. // If at the limit and unabled to select a non-intensive protocol,
  1915. // skip the candidate entirely and move on to the next. Since
  1916. // candidates are shuffled it's likely that the next candidate is not
  1917. // intensive. In this case, a StaggerConnectionWorkersMilliseconds
  1918. // delay may still be incurred.
  1919. p := controller.config.GetParameters().Get()
  1920. limitIntensiveConnectionWorkers := p.Int(parameters.LimitIntensiveConnectionWorkers)
  1921. inproxySelectionProbability := p.Float(parameters.InproxyTunnelProtocolSelectionProbability)
  1922. staggerPeriod := p.Duration(parameters.StaggerConnectionWorkersPeriod)
  1923. staggerJitter := p.Float(parameters.StaggerConnectionWorkersJitter)
  1924. p.Close()
  1925. controller.concurrentEstablishTunnelsMutex.Lock()
  1926. excludeIntensive := false
  1927. if limitIntensiveConnectionWorkers > 0 &&
  1928. controller.concurrentIntensiveEstablishTunnels >= limitIntensiveConnectionWorkers {
  1929. excludeIntensive = true
  1930. }
  1931. canReplay := func(serverEntry *protocol.ServerEntry, replayProtocol string) bool {
  1932. return controller.protocolSelectionConstraints.canReplay(
  1933. controller.establishConnectTunnelCount,
  1934. excludeIntensive,
  1935. serverEntry,
  1936. replayProtocol)
  1937. }
  1938. selectProtocol := func(serverEntry *protocol.ServerEntry) (string, bool) {
  1939. // The in-proxy protocol selection probability allows for
  1940. // tuning/limiting in-proxy usage independent of
  1941. // LimitTunnelProtocol targeting.
  1942. onlyInproxy := len(controller.config.InproxyPersonalCompartmentIDs) > 0
  1943. includeInproxy := onlyInproxy || prng.FlipWeightedCoin(inproxySelectionProbability)
  1944. return controller.protocolSelectionConstraints.selectProtocol(
  1945. controller.establishConnectTunnelCount,
  1946. excludeIntensive,
  1947. !includeInproxy,
  1948. serverEntry)
  1949. }
  1950. // MakeDialParameters may return a replay instance, if the server
  1951. // entry has a previous, recent successful connection and
  1952. // tactics/config has not changed.
  1953. //
  1954. // In the first round -- and later rounds, with some probability -- of
  1955. // establishing, ServerEntryIterator will move potential replay candidates
  1956. // to the front of the iterator after the random shuffle, which greatly
  1957. // prioritizes previously successful servers for that round.
  1958. //
  1959. // As ServerEntryIterator does not unmarshal and validate replay
  1960. // candidate dial parameters, some potential replay candidates may
  1961. // have expired or otherwise ineligible dial parameters; in this case
  1962. // the candidate proceeds without replay.
  1963. //
  1964. // The ReplayCandidateCount tactic determines how many candidates may use
  1965. // replay. After ReplayCandidateCount candidates of any type, replay or no,
  1966. // replay is skipped. If ReplayCandidateCount exceeds the intial round,
  1967. // replay may still be performed but the iterator may no longer move
  1968. // potential replay server entries to the front. When ReplayCandidateCount
  1969. // is set to -1, unlimited candidates may use replay.
  1970. dialParams, err := MakeDialParameters(
  1971. controller.config,
  1972. controller.steeringIPCache,
  1973. upstreamProxyErrorCallback,
  1974. canReplay,
  1975. selectProtocol,
  1976. candidateServerEntry.serverEntry,
  1977. controller.inproxyClientBrokerClientManager,
  1978. controller.inproxyNATStateManager,
  1979. false,
  1980. controller.establishConnectTunnelCount,
  1981. int(atomic.LoadInt32(&controller.establishedTunnelsCount)))
  1982. if dialParams == nil || err != nil {
  1983. controller.concurrentEstablishTunnelsMutex.Unlock()
  1984. // MakeDialParameters returns nil/nil when the server entry is to
  1985. // be skipped. See MakeDialParameters for skip cases and skip
  1986. // logging. Silently fail the candidate in this case. Otherwise,
  1987. // emit error.
  1988. if err != nil {
  1989. NoticeInfo("failed to make dial parameters for %s: %v",
  1990. candidateServerEntry.serverEntry.GetDiagnosticID(),
  1991. errors.Trace(err))
  1992. }
  1993. // Unblock other candidates immediately when server affinity
  1994. // candidate is skipped.
  1995. if candidateServerEntry.isServerAffinityCandidate {
  1996. close(controller.serverAffinityDoneBroadcast)
  1997. }
  1998. continue
  1999. }
  2000. // Increment establishConnectTunnelCount only after selectProtocol has
  2001. // succeeded to ensure InitialLimitTunnelProtocolsCandidateCount
  2002. // candidates use InitialLimitTunnelProtocols.
  2003. establishConnectTunnelCount := controller.establishConnectTunnelCount
  2004. controller.establishConnectTunnelCount += 1
  2005. isIntensive := protocol.TunnelProtocolIsResourceIntensive(dialParams.TunnelProtocol)
  2006. if isIntensive {
  2007. controller.concurrentIntensiveEstablishTunnels += 1
  2008. if controller.concurrentIntensiveEstablishTunnels > controller.peakConcurrentIntensiveEstablishTunnels {
  2009. controller.peakConcurrentIntensiveEstablishTunnels = controller.concurrentIntensiveEstablishTunnels
  2010. }
  2011. }
  2012. controller.concurrentEstablishTunnels += 1
  2013. if controller.concurrentEstablishTunnels > controller.peakConcurrentEstablishTunnels {
  2014. controller.peakConcurrentEstablishTunnels = controller.concurrentEstablishTunnels
  2015. }
  2016. controller.concurrentEstablishTunnelsMutex.Unlock()
  2017. // Apply stagger only now that we're past MakeDialParameters and
  2018. // protocol selection logic which may have caused the candidate to be
  2019. // skipped. The stagger logic delays dialing, and we don't want to
  2020. // incur that delay that when skipping.
  2021. //
  2022. // Locking staggerMutex serializes staggers, so that multiple workers
  2023. // don't simply sleep in parallel.
  2024. //
  2025. // The stagger is applied when establishConnectTunnelCount > 0 -- that
  2026. // is, for all but the first dial.
  2027. if establishConnectTunnelCount > 0 && staggerPeriod != 0 {
  2028. controller.staggerMutex.Lock()
  2029. timer := time.NewTimer(prng.JitterDuration(staggerPeriod, staggerJitter))
  2030. select {
  2031. case <-timer.C:
  2032. case <-controller.establishCtx.Done():
  2033. }
  2034. timer.Stop()
  2035. controller.staggerMutex.Unlock()
  2036. }
  2037. // ConnectTunnel will allocate significant memory, so first attempt to
  2038. // reclaim as much as possible.
  2039. DoGarbageCollection()
  2040. tunnel, err := ConnectTunnel(
  2041. controller.establishCtx,
  2042. controller.config,
  2043. candidateServerEntry.adjustedEstablishStartTime,
  2044. dialParams)
  2045. controller.concurrentEstablishTunnelsMutex.Lock()
  2046. if isIntensive {
  2047. controller.concurrentIntensiveEstablishTunnels -= 1
  2048. }
  2049. controller.concurrentEstablishTunnels -= 1
  2050. controller.concurrentEstablishTunnelsMutex.Unlock()
  2051. // Periodically emit memory metrics during the establishment cycle.
  2052. if !controller.isStopEstablishing() {
  2053. emitMemoryMetrics()
  2054. }
  2055. // Immediately reclaim memory allocated by the establishment. In the case
  2056. // of failure, first clear the reference to the tunnel. In the case of
  2057. // success, the garbage collection may still be effective as the initial
  2058. // phases of some protocols involve significant memory allocation that
  2059. // could now be reclaimed.
  2060. if err != nil {
  2061. tunnel = nil
  2062. }
  2063. DoGarbageCollection()
  2064. if err != nil {
  2065. // Unblock other candidates immediately when server affinity
  2066. // candidate fails.
  2067. if candidateServerEntry.isServerAffinityCandidate {
  2068. close(controller.serverAffinityDoneBroadcast)
  2069. }
  2070. // Before emitting error, check if establish interrupted, in which
  2071. // case the error is noise.
  2072. if controller.isStopEstablishing() {
  2073. break loop
  2074. }
  2075. NoticeInfo("failed to connect to %s: %v",
  2076. candidateServerEntry.serverEntry.GetDiagnosticID(),
  2077. errors.Trace(err))
  2078. continue
  2079. }
  2080. // Deliver connected tunnel.
  2081. // Don't block. Assumes the receiver has a buffer large enough for
  2082. // the number of desired tunnels. If there's no room, the tunnel must
  2083. // not be required so it's discarded.
  2084. select {
  2085. case controller.connectedTunnels <- tunnel:
  2086. default:
  2087. controller.discardTunnel(tunnel)
  2088. // Clear the reference to this discarded tunnel and immediately run
  2089. // a garbage collection to reclaim its memory.
  2090. tunnel = nil
  2091. DoGarbageCollection()
  2092. }
  2093. // Unblock other candidates only after delivering when
  2094. // server affinity candidate succeeds.
  2095. if candidateServerEntry.isServerAffinityCandidate {
  2096. close(controller.serverAffinityDoneBroadcast)
  2097. }
  2098. }
  2099. }
  2100. func (controller *Controller) isStopEstablishing() bool {
  2101. select {
  2102. case <-controller.establishCtx.Done():
  2103. return true
  2104. default:
  2105. }
  2106. return false
  2107. }
  2108. func (controller *Controller) runInproxyProxy() {
  2109. defer controller.runWaitGroup.Done()
  2110. if !controller.config.DisableTactics {
  2111. // Obtain and apply tactics before connecting to the broker and
  2112. // announcing proxies.
  2113. if controller.config.DisableTunnels {
  2114. // When not running client tunnel establishment, perform an OOB tactics
  2115. // fetch, if required, here.
  2116. GetTactics(controller.runCtx, controller.config)
  2117. } else if !controller.config.InproxySkipAwaitFullyConnected {
  2118. // When running client tunnel establishment, await establishment
  2119. // as this guarantees fresh tactics from either an OOB request or
  2120. // a handshake response.
  2121. //
  2122. // While it may be possible to proceed sooner, using cached
  2123. // tactics, waiting until establishment is complete avoids
  2124. // potential races between tactics updates.
  2125. if !controller.awaitFullyEstablished() {
  2126. // Controller is shutting down
  2127. return
  2128. }
  2129. } else {
  2130. // InproxySkipAwaitFullyConnected is a special case to support
  2131. // server/server_test, where a client must be its own proxy; in
  2132. // this case, awaitFullyEstablished will block forever.
  2133. // inproxyAwaitBrokerSpecs simply waits until any broker specs
  2134. // become available, which is sufficient for the test but is not
  2135. // as robust as awaiting fresh tactics.
  2136. isProxy := true
  2137. if !controller.inproxyAwaitBrokerSpecs(isProxy) {
  2138. // Controller is shutting down
  2139. return
  2140. }
  2141. }
  2142. }
  2143. // Don't announce proxies if tactics indicates it won't be allowed. This
  2144. // is also enforced on the broker; this client-side check cuts down on
  2145. // load from well-behaved proxies.
  2146. p := controller.config.GetParameters().Get()
  2147. allowProxy := p.Bool(parameters.InproxyAllowProxy)
  2148. p.Close()
  2149. // Don't announce proxies when running on an incompatible network, such as
  2150. // a non-Psiphon VPN.
  2151. compatibleNetwork := IsInproxyCompatibleNetworkType(controller.config.GetNetworkID())
  2152. // Running an unstream proxy is also an incompatible case.
  2153. useUpstreamProxy := controller.config.UseUpstreamProxy()
  2154. if !allowProxy || !compatibleNetwork || useUpstreamProxy {
  2155. if !allowProxy {
  2156. NoticeError("inproxy proxy: not allowed")
  2157. }
  2158. if !compatibleNetwork {
  2159. NoticeError("inproxy proxy: not run due to incompatible network")
  2160. }
  2161. if useUpstreamProxy {
  2162. NoticeError("inproxy proxy: not run due to upstream proxy configuration")
  2163. }
  2164. if controller.config.DisableTunnels {
  2165. // Signal failure -- and shutdown -- only if running in proxy-only mode. If also
  2166. // running a tunnel, keep running without proxies.
  2167. controller.SignalComponentFailure()
  2168. }
  2169. return
  2170. }
  2171. // The debugLogging flag is passed to both NoticeCommonLogger and to the
  2172. // inproxy package as well; skipping debug logs in the inproxy package,
  2173. // before calling into the notice logger, avoids unnecessary allocations
  2174. // and formatting when debug logging is off.
  2175. debugLogging := controller.config.InproxyEnableWebRTCDebugLogging
  2176. config := &inproxy.ProxyConfig{
  2177. Logger: NoticeCommonLogger(debugLogging),
  2178. EnableWebRTCDebugLogging: debugLogging,
  2179. GetBrokerClient: controller.inproxyGetProxyBrokerClient,
  2180. GetBaseAPIParameters: controller.inproxyGetAPIParameters,
  2181. MakeWebRTCDialCoordinator: controller.inproxyMakeWebRTCDialCoordinator,
  2182. HandleTacticsPayload: controller.inproxyHandleTacticsPayload,
  2183. MaxClients: controller.config.InproxyMaxClients,
  2184. LimitUpstreamBytesPerSecond: controller.config.InproxyLimitUpstreamBytesPerSecond,
  2185. LimitDownstreamBytesPerSecond: controller.config.InproxyLimitDownstreamBytesPerSecond,
  2186. OperatorMessageHandler: func(messageJSON string) {
  2187. NoticeInproxyOperatorMessage(messageJSON)
  2188. },
  2189. ActivityUpdater: func(
  2190. connectingClients int32,
  2191. connectedClients int32,
  2192. bytesUp int64,
  2193. bytesDown int64,
  2194. bytesDuration time.Duration) {
  2195. NoticeInproxyProxyActivity(connectingClients, connectedClients, bytesUp, bytesDown, bytesDuration)
  2196. },
  2197. }
  2198. proxy, err := inproxy.NewProxy(config)
  2199. if err != nil {
  2200. NoticeError("inproxy.NewProxy failed: %v", errors.Trace(err))
  2201. controller.SignalComponentFailure()
  2202. return
  2203. }
  2204. NoticeInfo("inproxy proxy: running")
  2205. proxy.Run(controller.runCtx)
  2206. NoticeInfo("inproxy proxy: stopped")
  2207. }
  2208. func (controller *Controller) inproxyAwaitBrokerSpecs(isProxy bool) bool {
  2209. ticker := time.NewTicker(100 * time.Millisecond)
  2210. defer ticker.Stop()
  2211. for {
  2212. p := controller.config.GetParameters().Get()
  2213. var brokerSpecs parameters.InproxyBrokerSpecsValue
  2214. if isProxy {
  2215. brokerSpecs = p.InproxyBrokerSpecs(
  2216. parameters.InproxyProxyBrokerSpecs, parameters.InproxyBrokerSpecs)
  2217. } else {
  2218. brokerSpecs = p.InproxyBrokerSpecs(
  2219. parameters.InproxyClientBrokerSpecs, parameters.InproxyBrokerSpecs)
  2220. }
  2221. p.Close()
  2222. if len(brokerSpecs) > 0 {
  2223. return true
  2224. }
  2225. select {
  2226. case <-ticker.C:
  2227. // Check isFullyEstablished again
  2228. case <-controller.runCtx.Done():
  2229. return false
  2230. }
  2231. }
  2232. }
  2233. // inproxyGetProxyBrokerClient returns the broker client shared by all proxy
  2234. // operations.
  2235. func (controller *Controller) inproxyGetProxyBrokerClient() (*inproxy.BrokerClient, error) {
  2236. brokerClient, _, err := controller.inproxyProxyBrokerClientManager.GetBrokerClient(
  2237. controller.config.GetNetworkID())
  2238. if err != nil {
  2239. return nil, errors.Trace(err)
  2240. }
  2241. return brokerClient, nil
  2242. }
  2243. func (controller *Controller) inproxyGetAPIParameters() (common.APIParameters, string, error) {
  2244. // TODO: include broker fronting dial parameters to be logged by the
  2245. // broker.
  2246. params := getBaseAPIParameters(baseParametersNoDialParameters, controller.config, nil)
  2247. if controller.config.DisableTactics {
  2248. return params, "", nil
  2249. }
  2250. // Add the known tactics tag, so that the broker can return new tactics if
  2251. // available.
  2252. //
  2253. // The active network ID is recorded returned and rechecked for
  2254. // consistency when storing any new tactics returned from the broker;
  2255. // other tactics fetches have this same check.
  2256. networkID := controller.config.GetNetworkID()
  2257. err := tactics.SetTacticsAPIParameters(GetTacticsStorer(controller.config), networkID, params)
  2258. if err != nil {
  2259. return nil, "", errors.Trace(err)
  2260. }
  2261. return params, networkID, nil
  2262. }
  2263. func (controller *Controller) inproxyMakeWebRTCDialCoordinator() (inproxy.WebRTCDialCoordinator, error) {
  2264. // nil is passed in for both InproxySTUNDialParameters and
  2265. // InproxyWebRTCDialParameters, so those parameters will be newly
  2266. // auto-generated for each client/proxy connection attempt. Unlike the
  2267. // in-proxy client, there is currently no replay of STUN or WebRTC dial
  2268. // parameters.
  2269. isProxy := true
  2270. webRTCDialInstance, err := NewInproxyWebRTCDialInstance(
  2271. controller.config,
  2272. controller.config.GetNetworkID(),
  2273. isProxy,
  2274. controller.inproxyNATStateManager,
  2275. nil,
  2276. nil)
  2277. if err != nil {
  2278. return nil, errors.Trace(err)
  2279. }
  2280. return webRTCDialInstance, nil
  2281. }
  2282. // inproxyHandleTacticsPayload handles new tactics returned from the proxy and
  2283. // returns when tactics have changed.
  2284. //
  2285. // inproxyHandleTacticsPayload duplicates some tactics-handling code from
  2286. // doHandshakeRequest.
  2287. func (controller *Controller) inproxyHandleTacticsPayload(
  2288. networkID string, tacticsPayload []byte) bool {
  2289. if controller.config.DisableTactics {
  2290. return false
  2291. }
  2292. if controller.config.GetNetworkID() != networkID {
  2293. // Ignore the tactics if the network ID has changed.
  2294. return false
  2295. }
  2296. var payload *tactics.Payload
  2297. err := json.Unmarshal(tacticsPayload, &payload)
  2298. if err != nil {
  2299. NoticeError("unmarshal tactics payload failed: %v", errors.Trace(err))
  2300. return false
  2301. }
  2302. if payload == nil {
  2303. // See "null" comment in doHandshakeRequest.
  2304. return false
  2305. }
  2306. // The in-proxy proxy implementation arranges for the first ProxyAnnounce
  2307. // request to get a head start in case there are new tactics available
  2308. // from the broker. Additional requests are also staggered.
  2309. //
  2310. // It can still happen that concurrent in-flight ProxyAnnounce requests
  2311. // receive duplicate new-tactics responses.
  2312. //
  2313. // TODO: detect this case and avoid resetting the broker client and NAT
  2314. // state managers more than necessary.
  2315. // Serialize processing of tactics from ProxyAnnounce responses.
  2316. controller.inproxyHandleTacticsMutex.Lock()
  2317. defer controller.inproxyHandleTacticsMutex.Unlock()
  2318. // When tactics are unchanged, the broker, as in the handshake case,
  2319. // returns a tactics payload, but without new tactics. As in the
  2320. // handshake case, HandleTacticsPayload is called in order to extend the
  2321. // TTL of the locally cached, unchanged tactics. Due to the potential
  2322. // high frequency and concurrency of ProxyAnnnounce requests vs.
  2323. // handshakes, a limit is added to update the data store's tactics TTL no
  2324. // more than one per minute.
  2325. appliedNewTactics := payload.Tactics != nil
  2326. now := time.Now()
  2327. if !appliedNewTactics && now.Sub(controller.inproxyLastStoredTactics) > 1*time.Minute {
  2328. // Skip TTL-only disk write.
  2329. return false
  2330. }
  2331. controller.inproxyLastStoredTactics = now
  2332. tacticsRecord, err := tactics.HandleTacticsPayload(
  2333. GetTacticsStorer(controller.config), networkID, payload)
  2334. if err != nil {
  2335. NoticeError("HandleTacticsPayloadfailed: %v", errors.Trace(err))
  2336. return false
  2337. }
  2338. if tacticsRecord != nil &&
  2339. prng.FlipWeightedCoin(tacticsRecord.Tactics.Probability) {
  2340. // SetParameters signals registered components, including broker
  2341. // client and NAT state managers, that must reset upon tactics changes.
  2342. err := controller.config.SetParameters(
  2343. tacticsRecord.Tag, true, tacticsRecord.Tactics.Parameters)
  2344. if err != nil {
  2345. NoticeInfo("apply inproxy broker tactics failed: %s", err)
  2346. return false
  2347. }
  2348. } else {
  2349. appliedNewTactics = false
  2350. }
  2351. return appliedNewTactics
  2352. }