controller.go 109 KB

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