controller.go 118 KB

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