controller.go 97 KB

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