controller.go 121 KB

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