controller.go 115 KB

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