controller.go 123 KB

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