controller.go 132 KB

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