controller.go 122 KB

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