controller.go 126 KB

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