controller.go 109 KB

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