controller.go 101 KB

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