controller.go 110 KB

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