controller.go 131 KB

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