controller.go 123 KB

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