controller.go 118 KB

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