controller.go 116 KB

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