controller.go 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846
  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(false),
  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.InproxyClientPersonalCompartmentIDs) > 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. }
  1491. // This covers two cases: if there was no limitTunnelProtocols to
  1492. // start, then limit to any in-proxy tunnel protocol; or, if there
  1493. // was a limit but OnlyInproxyTunnelProtocols evaluates to an empty
  1494. // list, also set the limit to any in-proxy tunnel protocol.
  1495. if len(controller.protocolSelectionConstraints.limitTunnelProtocols) == 0 {
  1496. controller.protocolSelectionConstraints.limitTunnelProtocols =
  1497. protocol.InproxyTunnelProtocols
  1498. }
  1499. }
  1500. // ConnectionWorkerPoolSize may be set by tactics.
  1501. workerPoolSize := p.Int(parameters.ConnectionWorkerPoolSize)
  1502. // When TargetServerEntry is used, override any worker pool size config or
  1503. // tactic parameter and use a pool size of 1. The typical use case for
  1504. // TargetServerEntry is to test a specific server with a single connection
  1505. // attempt. Furthermore, too many concurrent attempts to connect to the
  1506. // same server will trigger rate limiting.
  1507. if controller.config.TargetServerEntry != "" {
  1508. workerPoolSize = 1
  1509. }
  1510. // TunnelPoolSize may be set by tactics, subject to local constraints. A pool
  1511. // size of one is forced in packet tunnel mode or when using a
  1512. // TargetServerEntry. The tunnel pool size is reduced when there are
  1513. // insufficent known server entries, within the set region and protocol
  1514. // constraints, to satisfy the target.
  1515. //
  1516. // Limitations, to simplify concurrent access to shared state: a ceiling of
  1517. // MAX_TUNNEL_POOL_SIZE is enforced by setTunnelPoolSize; the tunnel pool
  1518. // size target is not re-adjusted after an API handshake, even though the
  1519. // handshake response may deliver new tactics, or prune server entries which
  1520. // were potential candidates; nor is the target re-adjusted after fetching
  1521. // new server entries during this establishment.
  1522. tunnelPoolSize := p.Int(parameters.TunnelPoolSize)
  1523. if controller.config.PacketTunnelTunFileDescriptor > 0 ||
  1524. controller.config.TargetServerEntry != "" {
  1525. tunnelPoolSize = 1
  1526. }
  1527. p.Close()
  1528. // Trigger CandidateServers and AvailableEgressRegions notices. By default,
  1529. // this is an asynchronous operation, as the underlying full server entry
  1530. // list enumeration may be a slow operation. In certain cases, where
  1531. // candidate counts are required up front, await the result before
  1532. // proceeding.
  1533. awaitResponse := tunnelPoolSize > 1 ||
  1534. controller.protocolSelectionConstraints.initialLimitTunnelProtocolsCandidateCount > 0
  1535. // AvailableEgressRegions: after a fresh install, the outer client may not
  1536. // have a list of regions to display; and LimitTunnelProtocols may reduce the
  1537. // number of available regions.
  1538. //
  1539. // When the outer client receives NoticeAvailableEgressRegions and the
  1540. // configured EgressRegion is not included in the region list, the outer
  1541. // client _should_ stop tunnel-core and prompt the user to change the region
  1542. // selection, as there are insufficient servers/capabilities to establish a
  1543. // tunnel in the selected region.
  1544. //
  1545. // This report is delayed until after tactics are likely to be applied,
  1546. // above; this avoids a ReportAvailableRegions reporting too many regions,
  1547. // followed shortly by a ReportAvailableRegions reporting fewer regions. That
  1548. // sequence could cause issues in the outer client UI.
  1549. //
  1550. // The reported regions are limited by protocolSelectionConstraints; in the
  1551. // case where an initial limit is in place, only regions available for the
  1552. // initial limit are reported. The initial phase will not complete if
  1553. // EgressRegion is set such that there are no server entries with the
  1554. // necessary protocol capabilities (either locally or from a remote server
  1555. // list fetch).
  1556. // Concurrency note: controller.protocolSelectionConstraints may be
  1557. // overwritten before serverEntriesReporter reads it, and so cannot be
  1558. // accessed directly by serverEntriesReporter.
  1559. reportRequest := &serverEntriesReportRequest{
  1560. constraints: controller.protocolSelectionConstraints,
  1561. }
  1562. if awaitResponse {
  1563. // Buffer size of 1 ensures the sender, serverEntryReporter, won't block on
  1564. // sending the response in the case where launchEstablishing exits due to
  1565. // stopping establishment.
  1566. reportRequest.awaitResponse = make(chan *serverEntriesReportResponse, 1)
  1567. }
  1568. controller.signalServerEntriesReporter(reportRequest)
  1569. if awaitResponse {
  1570. var reportResponse *serverEntriesReportResponse
  1571. select {
  1572. case reportResponse = <-reportRequest.awaitResponse:
  1573. case <-controller.establishCtx.Done():
  1574. // The sender may be gone when shutting down, or may not send until after
  1575. // stopping establishment.
  1576. return
  1577. }
  1578. if reportResponse.err != nil {
  1579. NoticeError("failed to report server entries: %v",
  1580. errors.Trace(reportResponse.err))
  1581. controller.SignalComponentFailure()
  1582. return
  1583. }
  1584. // Make adjustments based on candidate counts.
  1585. if tunnelPoolSize > 1 {
  1586. // Initial canidate count is ignored as count candidates will eventually
  1587. // become available.
  1588. if reportResponse.candidates < tunnelPoolSize {
  1589. tunnelPoolSize = reportResponse.candidates
  1590. }
  1591. if tunnelPoolSize < 1 {
  1592. tunnelPoolSize = 1
  1593. }
  1594. }
  1595. controller.setTunnelPoolSize(tunnelPoolSize)
  1596. // If InitialLimitTunnelProtocols is configured but cannot be satisfied,
  1597. // skip the initial phase in this establishment. This avoids spinning,
  1598. // unable to connect, in this case. InitialLimitTunnelProtocols is
  1599. // intended to prioritize certain protocols, but not strictly select them.
  1600. //
  1601. // The candidate count check ignores egress region selection. When an egress
  1602. // region is selected, it's the responsibility of the outer client to react
  1603. // to the following ReportAvailableRegions output and clear the user's
  1604. // selected region to prevent spinning, unable to connect. The initial phase
  1605. // is skipped only when InitialLimitTunnelProtocols cannot be satisfied
  1606. // _regardless_ of region selection.
  1607. //
  1608. // We presume that, in practise, most clients will have embedded server
  1609. // entries with capabilities for most protocols; and that clients will
  1610. // often perform RSL checks. So clients should most often have the
  1611. // necessary capabilities to satisfy InitialLimitTunnelProtocols. When
  1612. // this check fails, RSL/OSL/upgrade checks are triggered in order to gain
  1613. // new capabilities.
  1614. //
  1615. // LimitTunnelProtocols remains a hard limit, as using prohibited
  1616. // protocols may have some bad effect, such as a firewall blocking all
  1617. // traffic from a host.
  1618. if controller.protocolSelectionConstraints.initialLimitTunnelProtocolsCandidateCount > 0 {
  1619. if reportResponse.initialCandidatesAnyEgressRegion == 0 {
  1620. NoticeWarning("skipping initial limit tunnel protocols")
  1621. controller.protocolSelectionConstraints.initialLimitTunnelProtocolsCandidateCount = 0
  1622. // Since we were unable to satisfy the InitialLimitTunnelProtocols
  1623. // tactic, trigger RSL, OSL, and upgrade fetches to potentially
  1624. // gain new capabilities.
  1625. controller.triggerFetches()
  1626. }
  1627. }
  1628. }
  1629. for i := 0; i < workerPoolSize; i++ {
  1630. controller.establishWaitGroup.Add(1)
  1631. go controller.establishTunnelWorker()
  1632. }
  1633. controller.establishWaitGroup.Add(1)
  1634. go controller.establishCandidateGenerator()
  1635. }
  1636. // stopEstablishing signals the establish goroutines to stop and waits
  1637. // for the group to halt.
  1638. func (controller *Controller) stopEstablishing() {
  1639. if !controller.isEstablishing {
  1640. return
  1641. }
  1642. NoticeInfo("stop establishing")
  1643. controller.stopEstablish()
  1644. // Note: establishCandidateGenerator closes controller.candidateServerEntries
  1645. // (as it may be sending to that channel).
  1646. controller.establishWaitGroup.Wait()
  1647. NoticeInfo("stopped establishing")
  1648. controller.isEstablishing = false
  1649. controller.establishStartTime = time.Time{}
  1650. controller.establishCtx = nil
  1651. controller.stopEstablish = nil
  1652. controller.establishWaitGroup = nil
  1653. controller.candidateServerEntries = nil
  1654. controller.serverAffinityDoneBroadcast = nil
  1655. controller.concurrentEstablishTunnelsMutex.Lock()
  1656. peakConcurrent := controller.peakConcurrentEstablishTunnels
  1657. peakConcurrentIntensive := controller.peakConcurrentIntensiveEstablishTunnels
  1658. controller.establishConnectTunnelCount = 0
  1659. controller.concurrentEstablishTunnels = 0
  1660. controller.concurrentIntensiveEstablishTunnels = 0
  1661. controller.peakConcurrentEstablishTunnels = 0
  1662. controller.peakConcurrentIntensiveEstablishTunnels = 0
  1663. controller.concurrentEstablishTunnelsMutex.Unlock()
  1664. NoticeInfo("peak concurrent establish tunnels: %d", peakConcurrent)
  1665. NoticeInfo("peak concurrent resource intensive establish tunnels: %d", peakConcurrentIntensive)
  1666. emitMemoryMetrics()
  1667. DoGarbageCollection()
  1668. // Record datastore metrics after establishment, the phase which generates
  1669. // the bulk of all datastore transactions: iterating over server entries,
  1670. // storing new server entries, etc.
  1671. emitDatastoreMetrics()
  1672. // Similarly, establishment generates the bulk of domain resolves.
  1673. emitDNSMetrics(controller.resolver)
  1674. }
  1675. // establishCandidateGenerator populates the candidate queue with server entries
  1676. // from the data store. Server entries are iterated in rank order, so that promoted
  1677. // servers with higher rank are priority candidates.
  1678. func (controller *Controller) establishCandidateGenerator() {
  1679. defer controller.establishWaitGroup.Done()
  1680. defer close(controller.candidateServerEntries)
  1681. // networkWaitDuration is the elapsed time spent waiting
  1682. // for network connectivity. This duration will be excluded
  1683. // from reported tunnel establishment duration.
  1684. var totalNetworkWaitDuration time.Duration
  1685. applyServerAffinity, iterator, err := NewServerEntryIterator(controller.config)
  1686. if err != nil {
  1687. NoticeError("failed to iterate over candidates: %v", errors.Trace(err))
  1688. controller.SignalComponentFailure()
  1689. return
  1690. }
  1691. defer iterator.Close()
  1692. // TODO: reconcile server affinity scheme with multi-tunnel mode
  1693. if controller.getTunnelPoolSize() > 1 {
  1694. applyServerAffinity = false
  1695. }
  1696. isServerAffinityCandidate := true
  1697. if !applyServerAffinity {
  1698. isServerAffinityCandidate = false
  1699. close(controller.serverAffinityDoneBroadcast)
  1700. }
  1701. loop:
  1702. // Repeat until stopped
  1703. for {
  1704. // A "round" consists of a new shuffle of the server entries and attempted
  1705. // connections up to the end of the server entry iterator, or
  1706. // parameters.EstablishTunnelWorkTime elapsed. Time spent waiting for
  1707. // network connectivity is excluded from round elapsed time.
  1708. //
  1709. // After a round, if parameters.EstablishTunnelWorkTime has elapsed in total
  1710. // with no tunnel established, remote server list and upgrade checks are
  1711. // triggered.
  1712. //
  1713. // A complete server entry iteration does not trigger fetches since it's
  1714. // possible to have fewer than parameters.ConnectionWorkerPoolSize
  1715. // candidates, in which case rounds end instantly due to the complete server
  1716. // entry iteration. An exception is made for an empty server entry iterator;
  1717. // in that case fetches may be triggered immediately.
  1718. //
  1719. // The number of server candidates may change during this loop, due to
  1720. // remote server list fetches. Due to the performance impact, we will not
  1721. // trigger additional, informational CandidateServer notices while in the
  1722. // establishing loop. Clients typically re-establish often enough that we
  1723. // will see the effect of the remote server list fetch in diagnostics.
  1724. roundStartTime := time.Now()
  1725. var roundNetworkWaitDuration time.Duration
  1726. workTime := controller.config.GetParameters().Get().Duration(
  1727. parameters.EstablishTunnelWorkTime)
  1728. candidateServerEntryCount := 0
  1729. // Send each iterator server entry to the establish workers
  1730. for {
  1731. networkWaitStartTime := time.Now()
  1732. if !WaitForNetworkConnectivity(
  1733. controller.establishCtx,
  1734. controller.config.NetworkConnectivityChecker) {
  1735. break loop
  1736. }
  1737. networkWaitDuration := time.Since(networkWaitStartTime)
  1738. roundNetworkWaitDuration += networkWaitDuration
  1739. totalNetworkWaitDuration += networkWaitDuration
  1740. serverEntry, err := iterator.Next()
  1741. if err != nil {
  1742. NoticeError("failed to get next candidate: %v", errors.Trace(err))
  1743. controller.SignalComponentFailure()
  1744. break loop
  1745. }
  1746. if serverEntry == nil {
  1747. // Completed this iteration
  1748. NoticeInfo("completed server entry iteration")
  1749. break
  1750. }
  1751. if controller.config.TargetAPIProtocol == protocol.PSIPHON_API_PROTOCOL_SSH &&
  1752. !serverEntry.SupportsSSHAPIRequests() {
  1753. continue
  1754. }
  1755. candidateServerEntryCount += 1
  1756. // adjustedEstablishStartTime is establishStartTime shifted
  1757. // to exclude time spent waiting for network connectivity.
  1758. adjustedEstablishStartTime := controller.establishStartTime.Add(
  1759. totalNetworkWaitDuration)
  1760. candidate := &candidateServerEntry{
  1761. serverEntry: serverEntry,
  1762. isServerAffinityCandidate: isServerAffinityCandidate,
  1763. adjustedEstablishStartTime: adjustedEstablishStartTime,
  1764. }
  1765. wasServerAffinityCandidate := isServerAffinityCandidate
  1766. // Note: there must be only one server affinity candidate, as it
  1767. // closes the serverAffinityDoneBroadcast channel.
  1768. isServerAffinityCandidate = false
  1769. // TODO: here we could generate multiple candidates from the
  1770. // server entry when there are many MeekFrontingAddresses.
  1771. select {
  1772. case controller.candidateServerEntries <- candidate:
  1773. case <-controller.establishCtx.Done():
  1774. break loop
  1775. }
  1776. if time.Since(roundStartTime)-roundNetworkWaitDuration > workTime {
  1777. // Start over, after a brief pause, with a new shuffle of the server
  1778. // entries, and potentially some newly fetched server entries.
  1779. break
  1780. }
  1781. if wasServerAffinityCandidate {
  1782. // Don't start the next candidate until either the server affinity
  1783. // candidate has completed (success or failure) or is still working
  1784. // and the grace period has elapsed.
  1785. gracePeriod := controller.config.GetParameters().Get().Duration(
  1786. parameters.EstablishTunnelServerAffinityGracePeriod)
  1787. if gracePeriod > 0 {
  1788. timer := time.NewTimer(gracePeriod)
  1789. select {
  1790. case <-timer.C:
  1791. case <-controller.serverAffinityDoneBroadcast:
  1792. case <-controller.establishCtx.Done():
  1793. timer.Stop()
  1794. break loop
  1795. }
  1796. timer.Stop()
  1797. }
  1798. }
  1799. }
  1800. // Free up resources now, but don't reset until after the pause.
  1801. iterator.Close()
  1802. // Trigger RSL, OSL, and upgrade checks after failing to establish a
  1803. // tunnel within parameters.EstablishTunnelWorkTime, or if there are
  1804. // no server entries present.
  1805. //
  1806. // While the trigger is made after each round,
  1807. // parameter.FetchRemoteServerListStalePeriod will limit the actual
  1808. // frequency of fetches. Continuing to trigger allows for very long running
  1809. // establishments to perhaps eventually succeed.
  1810. //
  1811. // No fetches are triggered when TargetServerEntry is specified. In that
  1812. // case, we're only trying to connect to a specific server entry.
  1813. if (candidateServerEntryCount == 0 ||
  1814. time.Since(controller.establishStartTime)-totalNetworkWaitDuration > workTime) &&
  1815. controller.config.TargetServerEntry == "" {
  1816. controller.triggerFetches()
  1817. }
  1818. // After a complete iteration of candidate servers, pause before iterating again.
  1819. // This helps avoid some busy wait loop conditions, and also allows some time for
  1820. // network conditions to change. Also allows for fetch remote to complete,
  1821. // in typical conditions (it isn't strictly necessary to wait for this, there will
  1822. // be more rounds if required).
  1823. p := controller.config.GetParameters().Get()
  1824. timeout := prng.JitterDuration(
  1825. p.Duration(parameters.EstablishTunnelPausePeriod),
  1826. p.Float(parameters.EstablishTunnelPausePeriodJitter))
  1827. p.Close()
  1828. timer := time.NewTimer(timeout)
  1829. select {
  1830. case <-timer.C:
  1831. // Retry iterating
  1832. case <-controller.establishCtx.Done():
  1833. timer.Stop()
  1834. break loop
  1835. }
  1836. timer.Stop()
  1837. iterator.Reset()
  1838. }
  1839. }
  1840. // establishTunnelWorker pulls candidates from the candidate queue, establishes
  1841. // a connection to the tunnel server, and delivers the connected tunnel to a channel.
  1842. func (controller *Controller) establishTunnelWorker() {
  1843. defer controller.establishWaitGroup.Done()
  1844. loop:
  1845. for candidateServerEntry := range controller.candidateServerEntries {
  1846. // Note: don't receive from candidateServerEntries and isStopEstablishing
  1847. // in the same select, since we want to prioritize receiving the stop signal
  1848. if controller.isStopEstablishing() {
  1849. break loop
  1850. }
  1851. // There may already be a tunnel to this candidate. If so, skip it.
  1852. if controller.isActiveTunnelServerEntry(candidateServerEntry.serverEntry) {
  1853. continue
  1854. }
  1855. // TODO: we allow multiple, concurrent workers to attempt to connect to the
  1856. // same server. This is not wasteful if the server supports several
  1857. // different protocols, some of which may be blocked while others are not
  1858. // blocked. Limiting protocols with [Initial]LimitTunnelProtocols may make
  1859. // these multiple attempts redundent. Also, replay should be used only by
  1860. // the first attempt.
  1861. // upstreamProxyErrorCallback will post NoticeUpstreamProxyError when the
  1862. // tunnel dial fails due to an upstream proxy error. As the upstream proxy
  1863. // is user configured, the error message may need to be relayed to the user.
  1864. // As the callback may be invoked after establishment is over (e.g., if an
  1865. // initial dial isn't fully shutdown when ConnectTunnel returns; or a meek
  1866. // underlying TCP connection re-dial) don't access these variables
  1867. // directly.
  1868. callbackCandidateServerEntry := candidateServerEntry
  1869. callbackEstablishCtx := controller.establishCtx
  1870. upstreamProxyErrorCallback := func(err error) {
  1871. // Do not post the notice when overall establishment context is canceled or
  1872. // timed-out: the upstream proxy connection error is likely a result of the
  1873. // cancellation, and not a condition to be fixed by the user. In the case
  1874. // of meek underlying TCP connection re-dials, this condition will always
  1875. // be true; however in this case the initial dial succeeded with the
  1876. // current upstream proxy settings, so any upstream proxy error is
  1877. // transient.
  1878. if callbackEstablishCtx.Err() != nil {
  1879. return
  1880. }
  1881. // Another class of non-fatal upstream proxy error arises from proxies
  1882. // which limit permitted proxied ports. In this case, some tunnels may fail
  1883. // due to dial port, while others may eventually succeed. To avoid this
  1884. // class of errors, delay posting the notice. If the upstream proxy works,
  1885. // _some_ tunnel should connect. If the upstream proxy configuration is
  1886. // broken, the error should persist and eventually get posted.
  1887. p := controller.config.GetParameters().Get()
  1888. workerPoolSize := p.Int(parameters.ConnectionWorkerPoolSize)
  1889. minWaitDuration := p.Duration(parameters.UpstreamProxyErrorMinWaitDuration)
  1890. maxWaitDuration := p.Duration(parameters.UpstreamProxyErrorMaxWaitDuration)
  1891. p.Close()
  1892. controller.concurrentEstablishTunnelsMutex.Lock()
  1893. establishConnectTunnelCount := controller.establishConnectTunnelCount
  1894. controller.concurrentEstablishTunnelsMutex.Unlock()
  1895. // Delay UpstreamProxyErrorMinWaitDuration (excluding time spent waiting
  1896. // for network connectivity) and then until either
  1897. // UpstreamProxyErrorMaxWaitDuration has elapsed or, to post sooner if many
  1898. // candidates are failing, at least workerPoolSize tunnel connection
  1899. // attempts have completed. We infer that at least workerPoolSize
  1900. // candidates have completed by checking that at least 2*workerPoolSize
  1901. // candidates have started.
  1902. elapsedTime := time.Since(
  1903. callbackCandidateServerEntry.adjustedEstablishStartTime)
  1904. if elapsedTime < minWaitDuration ||
  1905. (elapsedTime < maxWaitDuration &&
  1906. establishConnectTunnelCount < 2*workerPoolSize) {
  1907. return
  1908. }
  1909. NoticeUpstreamProxyError(err)
  1910. }
  1911. // Select the tunnel protocol. The selection will be made at random
  1912. // from protocols supported by the server entry, optionally limited by
  1913. // LimitTunnelProtocols.
  1914. //
  1915. // When limiting concurrent resource intensive protocol connection
  1916. // workers, and at the limit, do not select resource intensive
  1917. // protocols since otherwise the candidate must be skipped.
  1918. //
  1919. // If at the limit and unabled to select a non-intensive protocol,
  1920. // skip the candidate entirely and move on to the next. Since
  1921. // candidates are shuffled it's likely that the next candidate is not
  1922. // intensive. In this case, a StaggerConnectionWorkersMilliseconds
  1923. // delay may still be incurred.
  1924. p := controller.config.GetParameters().Get()
  1925. limitIntensiveConnectionWorkers := p.Int(parameters.LimitIntensiveConnectionWorkers)
  1926. inproxySelectionProbability := p.Float(parameters.InproxyTunnelProtocolSelectionProbability)
  1927. staggerPeriod := p.Duration(parameters.StaggerConnectionWorkersPeriod)
  1928. staggerJitter := p.Float(parameters.StaggerConnectionWorkersJitter)
  1929. p.Close()
  1930. controller.concurrentEstablishTunnelsMutex.Lock()
  1931. excludeIntensive := false
  1932. if limitIntensiveConnectionWorkers > 0 &&
  1933. controller.concurrentIntensiveEstablishTunnels >= limitIntensiveConnectionWorkers {
  1934. excludeIntensive = true
  1935. }
  1936. canReplay := func(serverEntry *protocol.ServerEntry, replayProtocol string) bool {
  1937. return controller.protocolSelectionConstraints.canReplay(
  1938. controller.establishConnectTunnelCount,
  1939. excludeIntensive,
  1940. serverEntry,
  1941. replayProtocol)
  1942. }
  1943. selectProtocol := func(serverEntry *protocol.ServerEntry) (string, bool) {
  1944. // The in-proxy protocol selection probability allows for
  1945. // tuning/limiting in-proxy usage independent of
  1946. // LimitTunnelProtocol targeting.
  1947. onlyInproxy := len(controller.config.InproxyClientPersonalCompartmentIDs) > 0
  1948. includeInproxy := onlyInproxy || prng.FlipWeightedCoin(inproxySelectionProbability)
  1949. return controller.protocolSelectionConstraints.selectProtocol(
  1950. controller.establishConnectTunnelCount,
  1951. excludeIntensive,
  1952. !includeInproxy,
  1953. serverEntry)
  1954. }
  1955. // MakeDialParameters may return a replay instance, if the server
  1956. // entry has a previous, recent successful connection and
  1957. // tactics/config has not changed.
  1958. //
  1959. // In the first round -- and later rounds, with some probability -- of
  1960. // establishing, ServerEntryIterator will move potential replay candidates
  1961. // to the front of the iterator after the random shuffle, which greatly
  1962. // prioritizes previously successful servers for that round.
  1963. //
  1964. // As ServerEntryIterator does not unmarshal and validate replay
  1965. // candidate dial parameters, some potential replay candidates may
  1966. // have expired or otherwise ineligible dial parameters; in this case
  1967. // the candidate proceeds without replay.
  1968. //
  1969. // The ReplayCandidateCount tactic determines how many candidates may use
  1970. // replay. After ReplayCandidateCount candidates of any type, replay or no,
  1971. // replay is skipped. If ReplayCandidateCount exceeds the intial round,
  1972. // replay may still be performed but the iterator may no longer move
  1973. // potential replay server entries to the front. When ReplayCandidateCount
  1974. // is set to -1, unlimited candidates may use replay.
  1975. dialParams, err := MakeDialParameters(
  1976. controller.config,
  1977. controller.steeringIPCache,
  1978. upstreamProxyErrorCallback,
  1979. canReplay,
  1980. selectProtocol,
  1981. candidateServerEntry.serverEntry,
  1982. controller.inproxyClientBrokerClientManager,
  1983. controller.inproxyNATStateManager,
  1984. false,
  1985. controller.establishConnectTunnelCount,
  1986. int(atomic.LoadInt32(&controller.establishedTunnelsCount)))
  1987. if dialParams == nil || err != nil {
  1988. controller.concurrentEstablishTunnelsMutex.Unlock()
  1989. // MakeDialParameters returns nil/nil when the server entry is to
  1990. // be skipped. See MakeDialParameters for skip cases and skip
  1991. // logging. Silently fail the candidate in this case. Otherwise,
  1992. // emit error.
  1993. if err != nil {
  1994. NoticeInfo("failed to make dial parameters for %s: %v",
  1995. candidateServerEntry.serverEntry.GetDiagnosticID(),
  1996. errors.Trace(err))
  1997. }
  1998. // Unblock other candidates immediately when server affinity
  1999. // candidate is skipped.
  2000. if candidateServerEntry.isServerAffinityCandidate {
  2001. close(controller.serverAffinityDoneBroadcast)
  2002. }
  2003. continue
  2004. }
  2005. // Increment establishConnectTunnelCount only after selectProtocol has
  2006. // succeeded to ensure InitialLimitTunnelProtocolsCandidateCount
  2007. // candidates use InitialLimitTunnelProtocols.
  2008. establishConnectTunnelCount := controller.establishConnectTunnelCount
  2009. controller.establishConnectTunnelCount += 1
  2010. isIntensive := protocol.TunnelProtocolIsResourceIntensive(dialParams.TunnelProtocol)
  2011. if isIntensive {
  2012. controller.concurrentIntensiveEstablishTunnels += 1
  2013. if controller.concurrentIntensiveEstablishTunnels > controller.peakConcurrentIntensiveEstablishTunnels {
  2014. controller.peakConcurrentIntensiveEstablishTunnels = controller.concurrentIntensiveEstablishTunnels
  2015. }
  2016. }
  2017. controller.concurrentEstablishTunnels += 1
  2018. if controller.concurrentEstablishTunnels > controller.peakConcurrentEstablishTunnels {
  2019. controller.peakConcurrentEstablishTunnels = controller.concurrentEstablishTunnels
  2020. }
  2021. controller.concurrentEstablishTunnelsMutex.Unlock()
  2022. // Apply stagger only now that we're past MakeDialParameters and
  2023. // protocol selection logic which may have caused the candidate to be
  2024. // skipped. The stagger logic delays dialing, and we don't want to
  2025. // incur that delay that when skipping.
  2026. //
  2027. // Locking staggerMutex serializes staggers, so that multiple workers
  2028. // don't simply sleep in parallel.
  2029. //
  2030. // The stagger is applied when establishConnectTunnelCount > 0 -- that
  2031. // is, for all but the first dial.
  2032. if establishConnectTunnelCount > 0 && staggerPeriod != 0 {
  2033. controller.staggerMutex.Lock()
  2034. timer := time.NewTimer(prng.JitterDuration(staggerPeriod, staggerJitter))
  2035. select {
  2036. case <-timer.C:
  2037. case <-controller.establishCtx.Done():
  2038. }
  2039. timer.Stop()
  2040. controller.staggerMutex.Unlock()
  2041. }
  2042. // ConnectTunnel will allocate significant memory, so first attempt to
  2043. // reclaim as much as possible.
  2044. DoGarbageCollection()
  2045. tunnel, err := ConnectTunnel(
  2046. controller.establishCtx,
  2047. controller.config,
  2048. candidateServerEntry.adjustedEstablishStartTime,
  2049. dialParams)
  2050. controller.concurrentEstablishTunnelsMutex.Lock()
  2051. if isIntensive {
  2052. controller.concurrentIntensiveEstablishTunnels -= 1
  2053. }
  2054. controller.concurrentEstablishTunnels -= 1
  2055. controller.concurrentEstablishTunnelsMutex.Unlock()
  2056. // Periodically emit memory metrics during the establishment cycle.
  2057. if !controller.isStopEstablishing() {
  2058. emitMemoryMetrics()
  2059. }
  2060. // Immediately reclaim memory allocated by the establishment. In the case
  2061. // of failure, first clear the reference to the tunnel. In the case of
  2062. // success, the garbage collection may still be effective as the initial
  2063. // phases of some protocols involve significant memory allocation that
  2064. // could now be reclaimed.
  2065. if err != nil {
  2066. tunnel = nil
  2067. }
  2068. DoGarbageCollection()
  2069. if err != nil {
  2070. // Unblock other candidates immediately when server affinity
  2071. // candidate fails.
  2072. if candidateServerEntry.isServerAffinityCandidate {
  2073. close(controller.serverAffinityDoneBroadcast)
  2074. }
  2075. // Before emitting error, check if establish interrupted, in which
  2076. // case the error is noise.
  2077. if controller.isStopEstablishing() {
  2078. break loop
  2079. }
  2080. NoticeInfo("failed to connect to %s: %v",
  2081. candidateServerEntry.serverEntry.GetDiagnosticID(),
  2082. errors.Trace(err))
  2083. continue
  2084. }
  2085. // Deliver connected tunnel.
  2086. // Don't block. Assumes the receiver has a buffer large enough for
  2087. // the number of desired tunnels. If there's no room, the tunnel must
  2088. // not be required so it's discarded.
  2089. select {
  2090. case controller.connectedTunnels <- tunnel:
  2091. default:
  2092. controller.discardTunnel(tunnel)
  2093. // Clear the reference to this discarded tunnel and immediately run
  2094. // a garbage collection to reclaim its memory.
  2095. tunnel = nil
  2096. DoGarbageCollection()
  2097. }
  2098. // Unblock other candidates only after delivering when
  2099. // server affinity candidate succeeds.
  2100. if candidateServerEntry.isServerAffinityCandidate {
  2101. close(controller.serverAffinityDoneBroadcast)
  2102. }
  2103. }
  2104. }
  2105. func (controller *Controller) isStopEstablishing() bool {
  2106. select {
  2107. case <-controller.establishCtx.Done():
  2108. return true
  2109. default:
  2110. }
  2111. return false
  2112. }
  2113. func (controller *Controller) runInproxyProxy() {
  2114. defer controller.runWaitGroup.Done()
  2115. if !controller.config.DisableTactics {
  2116. // Obtain and apply tactics before connecting to the broker and
  2117. // announcing proxies.
  2118. if controller.config.DisableTunnels {
  2119. // When not running client tunnel establishment, perform an OOB tactics
  2120. // fetch, if required, here.
  2121. GetTactics(controller.runCtx, controller.config)
  2122. } else if !controller.config.InproxySkipAwaitFullyConnected {
  2123. // When running client tunnel establishment, await establishment
  2124. // as this guarantees fresh tactics from either an OOB request or
  2125. // a handshake response.
  2126. //
  2127. // While it may be possible to proceed sooner, using cached
  2128. // tactics, waiting until establishment is complete avoids
  2129. // potential races between tactics updates.
  2130. if !controller.awaitFullyEstablished() {
  2131. // Controller is shutting down
  2132. return
  2133. }
  2134. } else {
  2135. // InproxySkipAwaitFullyConnected is a special case to support
  2136. // server/server_test, where a client must be its own proxy; in
  2137. // this case, awaitFullyEstablished will block forever.
  2138. // inproxyAwaitBrokerSpecs simply waits until any broker specs
  2139. // become available, which is sufficient for the test but is not
  2140. // as robust as awaiting fresh tactics.
  2141. isProxy := true
  2142. if !controller.inproxyAwaitBrokerSpecs(isProxy) {
  2143. // Controller is shutting down
  2144. return
  2145. }
  2146. }
  2147. }
  2148. // Don't announce proxies if tactics indicates it won't be allowed. This
  2149. // is also enforced on the broker; this client-side check cuts down on
  2150. // load from well-behaved proxies.
  2151. p := controller.config.GetParameters().Get()
  2152. allowProxy := p.Bool(parameters.InproxyAllowProxy)
  2153. p.Close()
  2154. // Don't announce proxies when running on an incompatible network, such as
  2155. // a non-Psiphon VPN.
  2156. compatibleNetwork := IsInproxyCompatibleNetworkType(controller.config.GetNetworkID())
  2157. // Running an unstream proxy is also an incompatible case.
  2158. useUpstreamProxy := controller.config.UseUpstreamProxy()
  2159. if !allowProxy || !compatibleNetwork || useUpstreamProxy || !inproxy.Enabled() {
  2160. if !allowProxy {
  2161. NoticeError("inproxy proxy: not allowed")
  2162. }
  2163. if !compatibleNetwork {
  2164. NoticeError("inproxy proxy: not run due to incompatible network")
  2165. }
  2166. if useUpstreamProxy {
  2167. NoticeError("inproxy proxy: not run due to upstream proxy configuration")
  2168. }
  2169. if !inproxy.Enabled() {
  2170. NoticeError("inproxy proxy: inproxy implementation is not enabled")
  2171. }
  2172. if controller.config.DisableTunnels {
  2173. // Signal failure -- and shutdown -- only if running in proxy-only mode. If also
  2174. // running a tunnel, keep running without proxies.
  2175. controller.SignalComponentFailure()
  2176. }
  2177. return
  2178. }
  2179. // The debugLogging flag is passed to both NoticeCommonLogger and to the
  2180. // inproxy package as well; skipping debug logs in the inproxy package,
  2181. // before calling into the notice logger, avoids unnecessary allocations
  2182. // and formatting when debug logging is off.
  2183. debugLogging := controller.config.InproxyEnableWebRTCDebugLogging
  2184. activityNoticePeriod := p.Duration(parameters.InproxyProxyTotalActivityNoticePeriod)
  2185. var lastActivityNotice time.Time
  2186. var lastActivityConnectingClients, lastActivityConnectedClients int32
  2187. var activityTotalBytesUp, activityTotalBytesDown int64
  2188. activityUpdater := func(
  2189. connectingClients int32,
  2190. connectedClients int32,
  2191. bytesUp int64,
  2192. bytesDown int64,
  2193. _ time.Duration) {
  2194. // This emit logic mirrors the logic for NoticeBytesTransferred and
  2195. // NoticeTotalBytesTransferred in tunnel.operateTunnel.
  2196. if controller.config.EmitInproxyProxyActivity &&
  2197. (bytesUp > 0 || bytesDown > 0) {
  2198. NoticeInproxyProxyActivity(
  2199. connectingClients, connectedClients, bytesUp, bytesDown)
  2200. }
  2201. activityTotalBytesUp += bytesUp
  2202. activityTotalBytesDown += bytesDown
  2203. if lastActivityNotice.Add(activityNoticePeriod).Before(time.Now()) ||
  2204. connectingClients != lastActivityConnectingClients ||
  2205. connectedClients != lastActivityConnectedClients {
  2206. NoticeInproxyProxyTotalActivity(
  2207. connectingClients, connectedClients,
  2208. activityTotalBytesUp, activityTotalBytesDown)
  2209. lastActivityNotice = time.Now()
  2210. }
  2211. lastActivityConnectingClients = connectingClients
  2212. lastActivityConnectedClients = connectedClients
  2213. }
  2214. config := &inproxy.ProxyConfig{
  2215. Logger: NoticeCommonLogger(debugLogging),
  2216. EnableWebRTCDebugLogging: debugLogging,
  2217. WaitForNetworkConnectivity: controller.inproxyWaitForNetworkConnectivity,
  2218. GetBrokerClient: controller.inproxyGetProxyBrokerClient,
  2219. GetBaseAPIParameters: controller.inproxyGetAPIParameters,
  2220. MakeWebRTCDialCoordinator: controller.inproxyMakeWebRTCDialCoordinator,
  2221. HandleTacticsPayload: controller.inproxyHandleTacticsPayload,
  2222. MaxClients: controller.config.InproxyMaxClients,
  2223. LimitUpstreamBytesPerSecond: controller.config.InproxyLimitUpstreamBytesPerSecond,
  2224. LimitDownstreamBytesPerSecond: controller.config.InproxyLimitDownstreamBytesPerSecond,
  2225. OperatorMessageHandler: func(messageJSON string) {
  2226. NoticeInproxyOperatorMessage(messageJSON)
  2227. },
  2228. ActivityUpdater: activityUpdater,
  2229. }
  2230. proxy, err := inproxy.NewProxy(config)
  2231. if err != nil {
  2232. NoticeError("inproxy.NewProxy failed: %v", errors.Trace(err))
  2233. controller.SignalComponentFailure()
  2234. return
  2235. }
  2236. NoticeInfo("inproxy proxy: running")
  2237. proxy.Run(controller.runCtx)
  2238. // Emit one last NoticeInproxyProxyTotalActivity with the final byte counts.
  2239. NoticeInproxyProxyTotalActivity(
  2240. lastActivityConnectingClients, lastActivityConnectedClients,
  2241. activityTotalBytesUp, activityTotalBytesDown)
  2242. NoticeInfo("inproxy proxy: stopped")
  2243. }
  2244. func (controller *Controller) inproxyAwaitBrokerSpecs(isProxy bool) bool {
  2245. ticker := time.NewTicker(100 * time.Millisecond)
  2246. defer ticker.Stop()
  2247. for {
  2248. p := controller.config.GetParameters().Get()
  2249. var brokerSpecs parameters.InproxyBrokerSpecsValue
  2250. if isProxy {
  2251. brokerSpecs = p.InproxyBrokerSpecs(
  2252. parameters.InproxyProxyBrokerSpecs, parameters.InproxyBrokerSpecs)
  2253. } else {
  2254. brokerSpecs = p.InproxyBrokerSpecs(
  2255. parameters.InproxyClientBrokerSpecs, parameters.InproxyBrokerSpecs)
  2256. }
  2257. p.Close()
  2258. if len(brokerSpecs) > 0 {
  2259. return true
  2260. }
  2261. select {
  2262. case <-ticker.C:
  2263. // Check isFullyEstablished again
  2264. case <-controller.runCtx.Done():
  2265. return false
  2266. }
  2267. }
  2268. }
  2269. func (controller *Controller) inproxyWaitForNetworkConnectivity() bool {
  2270. return WaitForNetworkConnectivity(
  2271. controller.runCtx,
  2272. controller.config.NetworkConnectivityChecker)
  2273. }
  2274. // inproxyGetProxyBrokerClient returns the broker client shared by all proxy
  2275. // operations.
  2276. func (controller *Controller) inproxyGetProxyBrokerClient() (*inproxy.BrokerClient, error) {
  2277. brokerClient, _, err := controller.inproxyProxyBrokerClientManager.GetBrokerClient(
  2278. controller.config.GetNetworkID())
  2279. if err != nil {
  2280. return nil, errors.Trace(err)
  2281. }
  2282. return brokerClient, nil
  2283. }
  2284. func (controller *Controller) inproxyGetAPIParameters() (common.APIParameters, string, error) {
  2285. // TODO: include broker fronting dial parameters to be logged by the
  2286. // broker.
  2287. params := getBaseAPIParameters(baseParametersNoDialParameters, controller.config, nil)
  2288. networkID := controller.config.GetNetworkID()
  2289. params["network_type"] = GetNetworkType(networkID)
  2290. if controller.config.DisableTactics {
  2291. return params, "", nil
  2292. }
  2293. // Add the known tactics tag, so that the broker can return new tactics if
  2294. // available.
  2295. //
  2296. // The active network ID is recorded returned and rechecked for
  2297. // consistency when storing any new tactics returned from the broker;
  2298. // other tactics fetches have this same check.
  2299. err := tactics.SetTacticsAPIParameters(GetTacticsStorer(controller.config), networkID, params)
  2300. if err != nil {
  2301. return nil, "", errors.Trace(err)
  2302. }
  2303. return params, networkID, nil
  2304. }
  2305. func (controller *Controller) inproxyMakeWebRTCDialCoordinator() (inproxy.WebRTCDialCoordinator, error) {
  2306. // nil is passed in for both InproxySTUNDialParameters and
  2307. // InproxyWebRTCDialParameters, so those parameters will be newly
  2308. // auto-generated for each client/proxy connection attempt. Unlike the
  2309. // in-proxy client, there is currently no replay of STUN or WebRTC dial
  2310. // parameters.
  2311. isProxy := true
  2312. webRTCDialInstance, err := NewInproxyWebRTCDialInstance(
  2313. controller.config,
  2314. controller.config.GetNetworkID(),
  2315. isProxy,
  2316. controller.inproxyNATStateManager,
  2317. nil,
  2318. nil)
  2319. if err != nil {
  2320. return nil, errors.Trace(err)
  2321. }
  2322. return webRTCDialInstance, nil
  2323. }
  2324. // inproxyHandleTacticsPayload handles new tactics returned from the proxy and
  2325. // returns when tactics have changed.
  2326. //
  2327. // inproxyHandleTacticsPayload duplicates some tactics-handling code from
  2328. // doHandshakeRequest.
  2329. func (controller *Controller) inproxyHandleTacticsPayload(
  2330. networkID string, tacticsPayload []byte) bool {
  2331. if controller.config.DisableTactics {
  2332. return false
  2333. }
  2334. if controller.config.GetNetworkID() != networkID {
  2335. // Ignore the tactics if the network ID has changed.
  2336. return false
  2337. }
  2338. var payload *tactics.Payload
  2339. err := json.Unmarshal(tacticsPayload, &payload)
  2340. if err != nil {
  2341. NoticeError("unmarshal tactics payload failed: %v", errors.Trace(err))
  2342. return false
  2343. }
  2344. if payload == nil {
  2345. // See "null" comment in doHandshakeRequest.
  2346. return false
  2347. }
  2348. // The in-proxy proxy implementation arranges for the first ProxyAnnounce
  2349. // request to get a head start in case there are new tactics available
  2350. // from the broker. Additional requests are also staggered.
  2351. //
  2352. // It can still happen that concurrent in-flight ProxyAnnounce requests
  2353. // receive duplicate new-tactics responses.
  2354. //
  2355. // TODO: detect this case and avoid resetting the broker client and NAT
  2356. // state managers more than necessary.
  2357. // Serialize processing of tactics from ProxyAnnounce responses.
  2358. controller.inproxyHandleTacticsMutex.Lock()
  2359. defer controller.inproxyHandleTacticsMutex.Unlock()
  2360. // When tactics are unchanged, the broker, as in the handshake case,
  2361. // returns a tactics payload, but without new tactics. As in the
  2362. // handshake case, HandleTacticsPayload is called in order to extend the
  2363. // TTL of the locally cached, unchanged tactics. Due to the potential
  2364. // high frequency and concurrency of ProxyAnnnounce requests vs.
  2365. // handshakes, a limit is added to update the data store's tactics TTL no
  2366. // more than one per minute.
  2367. appliedNewTactics := payload.Tactics != nil
  2368. now := time.Now()
  2369. if !appliedNewTactics && now.Sub(controller.inproxyLastStoredTactics) > 1*time.Minute {
  2370. // Skip TTL-only disk write.
  2371. return false
  2372. }
  2373. controller.inproxyLastStoredTactics = now
  2374. tacticsRecord, err := tactics.HandleTacticsPayload(
  2375. GetTacticsStorer(controller.config), networkID, payload)
  2376. if err != nil {
  2377. NoticeError("HandleTacticsPayload failed: %v", errors.Trace(err))
  2378. return false
  2379. }
  2380. if tacticsRecord != nil &&
  2381. prng.FlipWeightedCoin(tacticsRecord.Tactics.Probability) {
  2382. // SetParameters signals registered components, including broker
  2383. // client and NAT state managers, that must reset upon tactics changes.
  2384. err := controller.config.SetParameters(
  2385. tacticsRecord.Tag, true, tacticsRecord.Tactics.Parameters)
  2386. if err != nil {
  2387. NoticeInfo("apply inproxy broker tactics failed: %s", err)
  2388. return false
  2389. }
  2390. } else {
  2391. appliedNewTactics = false
  2392. }
  2393. return appliedNewTactics
  2394. }