controller.go 110 KB

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