controller.go 133 KB

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