proxy.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. /*
  2. * Copyright (c) 2023, 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 inproxy
  20. import (
  21. "context"
  22. "io"
  23. "net"
  24. "sync"
  25. "sync/atomic"
  26. "time"
  27. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  28. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  30. "github.com/pion/webrtc/v3"
  31. )
  32. const (
  33. proxyAnnounceRetryDelay = 2 * time.Second
  34. proxyAnnounceRetryJitter = 0.3
  35. proxyAnnounceMaxRetryDelay = 6 * time.Hour
  36. proxyWebRTCAnswerTimeout = 20 * time.Second
  37. proxyDestinationDialTimeout = 20 * time.Second
  38. )
  39. // Proxy is the in-proxy proxying component, which relays traffic from a
  40. // client to a Psiphon server.
  41. type Proxy struct {
  42. // Note: 64-bit ints used with atomic operations are placed
  43. // at the start of struct to ensure 64-bit alignment.
  44. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  45. bytesUp int64
  46. bytesDown int64
  47. peakBytesUp int64
  48. peakBytesDown int64
  49. connectingClients int32
  50. connectedClients int32
  51. config *ProxyConfig
  52. activityUpdateWrapper *activityUpdateWrapper
  53. networkDiscoveryMutex sync.Mutex
  54. networkDiscoveryRunOnce bool
  55. networkDiscoveryNetworkID string
  56. }
  57. // TODO: add PublicNetworkAddress/ListenNetworkAddress to facilitate manually
  58. // configured, permanent port mappings.
  59. // ProxyConfig specifies the configuration for a Proxy run.
  60. type ProxyConfig struct {
  61. // Logger is used to log events.
  62. Logger common.Logger
  63. // EnableWebRTCDebugLogging indicates whether to emit WebRTC debug logs.
  64. EnableWebRTCDebugLogging bool
  65. // GetBrokerClient provides a BrokerClient which the proxy will use for
  66. // making broker requests. If GetBrokerClient returns a shared
  67. // BrokerClient instance, the BrokerClient must support multiple,
  68. // concurrent round trips, as the proxy will use it to concurrently
  69. // announce many proxy instances. The BrokerClient should be implemented
  70. // using multiplexing over a shared network connection -- for example,
  71. // HTTP/2 -- and a shared broker session for optimal performance.
  72. GetBrokerClient func() (*BrokerClient, error)
  73. // GetBaseAPIParameters returns Psiphon API parameters to be sent to and
  74. // logged by the broker. Expected parameters include client/proxy
  75. // application and build version information. GetBaseAPIParameters also
  76. // returns the network ID, corresponding to the parameters, to be used in
  77. // tactics logic; the network ID is not sent to the broker.
  78. GetBaseAPIParameters func() (common.APIParameters, string, error)
  79. // MakeWebRTCDialCoordinator provides a WebRTCDialCoordinator which
  80. // specifies WebRTC-related dial parameters, including selected STUN
  81. // server addresses; network topology information for the current netork;
  82. // NAT logic settings; and other settings.
  83. //
  84. // MakeWebRTCDialCoordinator is invoked for each proxy/client connection,
  85. // and the provider can select new parameters per connection as reqired.
  86. MakeWebRTCDialCoordinator func() (WebRTCDialCoordinator, error)
  87. // HandleTacticsPayload is a callback that receives any tactics payload,
  88. // provided by the broker in proxy announcement request responses.
  89. // HandleTacticsPayload must return true when the tacticsPayload includes
  90. // new tactics, indicating that the proxy should reinitialize components
  91. // controlled by tactics parameters.
  92. HandleTacticsPayload func(networkID string, tacticsPayload []byte) bool
  93. // OperatorMessageHandler is a callback that is invoked with any user
  94. // message JSON object that is sent to the Proxy from the Broker. This
  95. // facility may be used to alert proxy operators when required. The JSON
  96. // object schema is arbitrary and not defined here.
  97. OperatorMessageHandler func(messageJSON string)
  98. // MaxClients is the maximum number of clients that are allowed to connect
  99. // to the proxy.
  100. MaxClients int
  101. // LimitUpstreamBytesPerSecond limits the upstream data transfer rate for
  102. // a single client. When 0, there is no limit.
  103. LimitUpstreamBytesPerSecond int
  104. // LimitDownstreamBytesPerSecond limits the downstream data transfer rate
  105. // for a single client. When 0, there is no limit.
  106. LimitDownstreamBytesPerSecond int
  107. // ActivityUpdater specifies an ActivityUpdater for activity associated
  108. // with this proxy.
  109. ActivityUpdater ActivityUpdater
  110. }
  111. // ActivityUpdater is a callback that is invoked when clients connect and
  112. // disconnect and periodically with data transfer updates (unless idle). This
  113. // callback may be used to update an activity UI. This callback should post
  114. // this data to another thread or handler and return immediately and not
  115. // block on UI updates.
  116. type ActivityUpdater func(
  117. connectingClients int32,
  118. connectedClients int32,
  119. bytesUp int64,
  120. bytesDown int64,
  121. bytesDuration time.Duration)
  122. // NewProxy initializes a new Proxy with the specified configuration.
  123. func NewProxy(config *ProxyConfig) (*Proxy, error) {
  124. p := &Proxy{
  125. config: config,
  126. }
  127. p.activityUpdateWrapper = &activityUpdateWrapper{p: p}
  128. return p, nil
  129. }
  130. // activityUpdateWrapper implements the psiphon/common.ActivityUpdater
  131. // interface and is used to receive bytes transferred updates from the
  132. // ActivityConns wrapping proxied traffic. A wrapper is used so that
  133. // UpdateProgress is not exported from Proxy.
  134. type activityUpdateWrapper struct {
  135. p *Proxy
  136. }
  137. func (w *activityUpdateWrapper) UpdateProgress(bytesRead, bytesWritten int64, _ int64) {
  138. atomic.AddInt64(&w.p.bytesUp, bytesWritten)
  139. atomic.AddInt64(&w.p.bytesDown, bytesRead)
  140. }
  141. // Run runs the proxy. The proxy sends requests to the Broker announcing its
  142. // availability; the Broker matches the proxy with clients, and facilitates
  143. // an exchange of WebRTC connection information; the proxy and each client
  144. // attempt to establish a connection; and the client's traffic is relayed to
  145. // Psiphon server.
  146. //
  147. // Run ends when ctx is Done. A proxy run may continue across underlying
  148. // network changes assuming that the ProxyConfig GetBrokerClient and
  149. // MakeWebRTCDialCoordinator callbacks react to network changes and provide
  150. // instances that are reflect network changes.
  151. func (p *Proxy) Run(ctx context.Context) {
  152. // Run MaxClient proxying workers. Each worker handles one client at a time.
  153. proxyWaitGroup := new(sync.WaitGroup)
  154. for i := 0; i < p.config.MaxClients; i++ {
  155. // Give the very first announcement a head start, by delaying the
  156. // others, so that the first announcement request can obtain and
  157. // apply any new tactics first, avoiding all MaxClients initial
  158. // announcement requests returning with potentially no match and new
  159. // tactics responses. After this initial launch point, we assume
  160. // proxy announcement requests are somewhat staggered.
  161. delayFirstAnnounce := i > 0
  162. proxyWaitGroup.Add(1)
  163. go func(delayFirstAnnounce bool) {
  164. defer proxyWaitGroup.Done()
  165. p.proxyClients(ctx, delayFirstAnnounce)
  166. }(delayFirstAnnounce)
  167. }
  168. // Capture activity updates every second, which is the required frequency
  169. // for PeakUp/DownstreamBytesPerSecond. This is also a reasonable
  170. // frequency for invoking the ActivityUpdater and updating UI widgets.
  171. activityUpdatePeriod := 1 * time.Second
  172. ticker := time.NewTicker(activityUpdatePeriod)
  173. defer ticker.Stop()
  174. loop:
  175. for {
  176. select {
  177. case <-ticker.C:
  178. p.activityUpdate(activityUpdatePeriod)
  179. case <-ctx.Done():
  180. break loop
  181. }
  182. }
  183. proxyWaitGroup.Wait()
  184. }
  185. // getAnnounceDelayParameters is a helper that fetches the proxy announcement
  186. // delay parameters from the current broker client.
  187. //
  188. // getAnnounceDelayParameters is used to configure a delay when
  189. // proxyOneClient fails. As having no broker clients is a possible
  190. // proxyOneClient failure case, GetBrokerClient errors are ignored here and
  191. // defaults used in that case.
  192. func (p *Proxy) getAnnounceDelayParameters() (time.Duration, float64) {
  193. brokerClient, err := p.config.GetBrokerClient()
  194. if err != nil {
  195. return proxyAnnounceRetryDelay, proxyAnnounceRetryJitter
  196. }
  197. brokerCoordinator := brokerClient.GetBrokerDialCoordinator()
  198. return common.ValueOrDefault(brokerCoordinator.AnnounceRetryDelay(), proxyAnnounceRetryDelay),
  199. common.ValueOrDefault(brokerCoordinator.AnnounceRetryJitter(), proxyAnnounceRetryJitter)
  200. }
  201. func (p *Proxy) activityUpdate(period time.Duration) {
  202. connectingClients := atomic.LoadInt32(&p.connectingClients)
  203. connectedClients := atomic.LoadInt32(&p.connectedClients)
  204. bytesUp := atomic.SwapInt64(&p.bytesUp, 0)
  205. bytesDown := atomic.SwapInt64(&p.bytesDown, 0)
  206. greaterThanSwapInt64(&p.peakBytesUp, bytesUp)
  207. greaterThanSwapInt64(&p.peakBytesDown, bytesDown)
  208. if connectingClients == 0 &&
  209. connectedClients == 0 &&
  210. bytesUp == 0 &&
  211. bytesDown == 0 {
  212. // Skip the activity callback on idle.
  213. return
  214. }
  215. p.config.ActivityUpdater(
  216. connectingClients,
  217. connectedClients,
  218. bytesUp,
  219. bytesDown,
  220. period)
  221. }
  222. func greaterThanSwapInt64(addr *int64, new int64) bool {
  223. // Limitation: if there are two concurrent calls, the greater value could
  224. // get overwritten.
  225. old := atomic.LoadInt64(addr)
  226. if new > old {
  227. return atomic.CompareAndSwapInt64(addr, old, new)
  228. }
  229. return false
  230. }
  231. func (p *Proxy) proxyClients(ctx context.Context, delayFirstAnnounce bool) {
  232. // Proxy one client, repeating until ctx is done.
  233. //
  234. // This worker starts with posting a long-polling announcement request.
  235. // The broker response with a matched client, and the proxy and client
  236. // attempt to establish a WebRTC connection for relaying traffic.
  237. //
  238. // Limitation: this design may not maximize the utility of the proxy,
  239. // since some proxy/client connections will fail at the WebRTC stage due
  240. // to NAT traversal failure, and at most MaxClient concurrent
  241. // establishments are attempted. Another scenario comes from the Psiphon
  242. // client horse race, which may start in-proxy dials but then abort them
  243. // when some other tunnel protocol succeeds.
  244. //
  245. // As a future enhancement, consider using M announcement goroutines and N
  246. // WebRTC dial goroutines. When an announcement gets a response,
  247. // immediately announce again unless there are already MaxClient active
  248. // connections established. This approach may require the proxy to
  249. // backpedal and reject connections when establishment is too successful.
  250. //
  251. // Another enhancement could be a signal from the client, to the broker,
  252. // relayed to the proxy, when a dial is aborted.
  253. failureDelayFactor := time.Duration(1)
  254. for i := 0; ctx.Err() == nil; i++ {
  255. // When delayFirstAnnounce is true, the very first proxyOneClient
  256. // proxy announcement is delayed to give another, concurrent
  257. // proxyClients proxy announcment a head start in order to fetch and
  258. // apply any new tactics.
  259. //
  260. // This delay is distinct from the post-failure delay, although both
  261. // use the same delay parameter settings.
  262. backOff, err := p.proxyOneClient(ctx, delayFirstAnnounce && i == 0)
  263. if err != nil && ctx.Err() == nil {
  264. p.config.Logger.WithTraceFields(
  265. common.LogFields{
  266. "error": err.Error(),
  267. }).Error("proxy client failed")
  268. // Apply a simple exponential backoff base on whether
  269. // proxyOneClient either relayed client traffic or got no match,
  270. // or encountered a failure.
  271. //
  272. // The proxyOneClient failure could range from local
  273. // configuration (no broker clients) to network issues(failure to
  274. // completely establish WebRTC connection) and this backoff
  275. // prevents both excess local logging and churning in the former
  276. // case and excessive bad service to clients or unintentionally
  277. // overloading the broker in the latter case.
  278. //
  279. // TODO: specific tactics parameters to control this logic.
  280. delay, jitter := p.getAnnounceDelayParameters()
  281. if !backOff {
  282. failureDelayFactor = 1
  283. }
  284. delay = delay * failureDelayFactor
  285. if delay > proxyAnnounceMaxRetryDelay {
  286. delay = proxyAnnounceMaxRetryDelay
  287. }
  288. if failureDelayFactor < 1<<20 {
  289. failureDelayFactor *= 2
  290. }
  291. common.SleepWithJitter(ctx, delay, jitter)
  292. }
  293. }
  294. }
  295. // resetNetworkDiscovery resets the network discovery state, which will force
  296. // another network discovery when doNetworkDiscovery is invoked.
  297. // resetNetworkDiscovery is called when new tactics have been received from
  298. // the broker, as new tactics may change parameters that control network
  299. // discovery.
  300. func (p *Proxy) resetNetworkDiscovery() {
  301. p.networkDiscoveryMutex.Lock()
  302. defer p.networkDiscoveryMutex.Unlock()
  303. p.networkDiscoveryRunOnce = false
  304. p.networkDiscoveryNetworkID = ""
  305. }
  306. func (p *Proxy) doNetworkDiscovery(
  307. ctx context.Context,
  308. webRTCCoordinator WebRTCDialCoordinator) {
  309. // Allow only one concurrent network discovery. In practise, this may
  310. // block all other proxyOneClient goroutines while one single goroutine
  311. // runs doNetworkDiscovery. Subsequently, all other goroutines will find
  312. // networkDiscoveryRunOnce is true and use the cached results.
  313. p.networkDiscoveryMutex.Lock()
  314. defer p.networkDiscoveryMutex.Unlock()
  315. networkID := webRTCCoordinator.NetworkID()
  316. if p.networkDiscoveryRunOnce &&
  317. p.networkDiscoveryNetworkID == networkID {
  318. // Already ran discovery for this network.
  319. return
  320. }
  321. // Reset and configure port mapper component, as required. See
  322. // initPortMapper comment.
  323. initPortMapper(webRTCCoordinator)
  324. // Gather local network NAT/port mapping metrics before sending any
  325. // announce requests. NAT topology metrics are used by the Broker to
  326. // optimize client and in-proxy matching. Unlike the client, we always
  327. // perform this synchronous step here, since waiting doesn't necessarily
  328. // block a client tunnel dial.
  329. waitGroup := new(sync.WaitGroup)
  330. waitGroup.Add(1)
  331. go func() {
  332. defer waitGroup.Done()
  333. // NATDiscover may use cached NAT type/port mapping values from
  334. // DialParameters, based on the network ID. If discovery is not
  335. // successful, the proxy still proceeds to announce.
  336. NATDiscover(
  337. ctx,
  338. &NATDiscoverConfig{
  339. Logger: p.config.Logger,
  340. WebRTCDialCoordinator: webRTCCoordinator,
  341. })
  342. }()
  343. waitGroup.Wait()
  344. p.networkDiscoveryNetworkID = networkID
  345. }
  346. func (p *Proxy) proxyOneClient(ctx context.Context, delayAnnounce bool) (bool, error) {
  347. // Do not trigger back-off unless the proxy successfully announces and
  348. // only then performs poorly.
  349. //
  350. // A no-match response should not trigger back-off, nor should broker
  351. // request transport errors which may include non-200 responses due to
  352. // CDN timeout mismatches or TLS errors due to CDN TLS fingerprint
  353. // incompatibility.
  354. backOff := false
  355. // Get a new WebRTCDialCoordinator, which should be configured with the
  356. // latest network tactics.
  357. webRTCCoordinator, err := p.config.MakeWebRTCDialCoordinator()
  358. if err != nil {
  359. return backOff, errors.Trace(err)
  360. }
  361. // Perform network discovery, to determine NAT type and other network
  362. // topology information that is reported to the broker in the proxy
  363. // announcement and used to optimize proxy/client matching. Unlike
  364. // clients, which can't easily delay dials in the tunnel establishment
  365. // horse race, proxies will always perform network discovery.
  366. // doNetworkDiscovery allows only one concurrent discovery and caches
  367. // results for the current network (as determined by
  368. // WebRTCCoordinator.GetNetworkID), so when multiple proxyOneClient
  369. // goroutines call doNetworkDiscovery, at most one discovery is performed
  370. // per network.
  371. p.doNetworkDiscovery(ctx, webRTCCoordinator)
  372. // delayAnnounce delays the proxy announcement request in order to give a
  373. // concurrent request a head start. See comments in Run and proxyClients.
  374. // This head start delay is applied here, after doNetworkDiscovery, as
  375. // otherwise the delay might be negated if the head-start proxyOneClient
  376. // blocks on doNetworkDiscovery and subsequently this proxyOneClient
  377. // quickly finds cached results in doNetworkDiscovery.
  378. if delayAnnounce {
  379. announceRetryDelay, announceRetryJitter := p.getAnnounceDelayParameters()
  380. common.SleepWithJitter(
  381. ctx,
  382. common.ValueOrDefault(announceRetryDelay, proxyAnnounceRetryDelay),
  383. common.ValueOrDefault(announceRetryJitter, proxyAnnounceRetryJitter))
  384. }
  385. // Send the announce request
  386. // At this point, no NAT traversal operations have been performed by the
  387. // proxy, since its announcement may sit idle for the long-polling period
  388. // and NAT hole punches or port mappings could expire before the
  389. // long-polling period.
  390. //
  391. // As a future enhancement, the proxy could begin gathering WebRTC ICE
  392. // candidates while awaiting a client match, reducing the turn around
  393. // time after a match. This would make sense if there's high demand for
  394. // proxies, and so hole punches unlikely to expire while awaiting a client match.
  395. //
  396. // Another possibility may be to prepare and send a full offer SDP in the
  397. // announcment; and have the broker modify either the proxy or client
  398. // offer SDP to produce an answer SDP. In this case, the entire
  399. // ProxyAnswerRequest could be skipped as the WebRTC dial can begin after
  400. // the ProxyAnnounceRequest response (and ClientOfferRequest response).
  401. //
  402. // Furthermore, if a port mapping can be established, instead of using
  403. // WebRTC the proxy could run a Psiphon tunnel protocol listener at the
  404. // mapped port and send the dial information -- including some secret to
  405. // authenticate the client -- in its announcement. The client would then
  406. // receive this direct dial information from the broker and connect. The
  407. // proxy should be able to send keep alives to extend the port mapping
  408. // lifetime.
  409. brokerClient, err := p.config.GetBrokerClient()
  410. if err != nil {
  411. return backOff, errors.Trace(err)
  412. }
  413. brokerCoordinator := brokerClient.GetBrokerDialCoordinator()
  414. // Get the base Psiphon API parameters and additional proxy metrics,
  415. // including performance information, which is sent to the broker in the
  416. // proxy announcment.
  417. //
  418. // tacticsNetworkID is the exact network ID that corresponds to the
  419. // tactics tag sent in the base parameters; this is passed to
  420. // HandleTacticsPayload in order to double check that any tactics
  421. // returned in the proxy announcment response are associated and stored
  422. // with the original network ID.
  423. metrics, tacticsNetworkID, err := p.getMetrics(webRTCCoordinator)
  424. if err != nil {
  425. return backOff, errors.Trace(err)
  426. }
  427. // A proxy ID is implicitly sent with requests; it's the proxy's session
  428. // public key.
  429. //
  430. // ProxyAnnounce applies an additional request timeout to facilitate
  431. // long-polling.
  432. announceResponse, err := brokerClient.ProxyAnnounce(
  433. ctx,
  434. &ProxyAnnounceRequest{
  435. PersonalCompartmentIDs: brokerCoordinator.PersonalCompartmentIDs(),
  436. Metrics: metrics,
  437. })
  438. if err != nil {
  439. return backOff, errors.Trace(err)
  440. }
  441. if announceResponse.OperatorMessageJSON != "" {
  442. p.config.OperatorMessageHandler(announceResponse.OperatorMessageJSON)
  443. }
  444. if len(announceResponse.TacticsPayload) > 0 {
  445. // The TacticsPayload may include new tactics, or may simply signal,
  446. // to the Psiphon client, that its tactics tag remains up-to-date and
  447. // to extend cached tactics TTL. HandleTacticsPayload returns true
  448. // when tactics haved changed; in this case we clear cached network
  449. // discovery but proceed with handling the proxy announcement
  450. // response as there may still be a match.
  451. if p.config.HandleTacticsPayload(tacticsNetworkID, announceResponse.TacticsPayload) {
  452. p.resetNetworkDiscovery()
  453. }
  454. }
  455. if announceResponse.NoMatch {
  456. return backOff, errors.TraceNew("no match")
  457. }
  458. if announceResponse.ClientProxyProtocolVersion != ProxyProtocolVersion1 {
  459. return backOff, errors.Tracef(
  460. "Unsupported proxy protocol version: %d",
  461. announceResponse.ClientProxyProtocolVersion)
  462. }
  463. // Trigger back-off if the following WebRTC operations fail to establish a
  464. // connections.
  465. //
  466. // Limitation: the proxy answer request to the broker may fail due to the
  467. // non-back-off reasons documented above for the proxy announcment request;
  468. // however, these should be unlikely assuming that the broker client is
  469. // using a persistent transport connection.
  470. backOff = true
  471. // For activity updates, indicate that a client connection is now underway.
  472. atomic.AddInt32(&p.connectingClients, 1)
  473. connected := false
  474. defer func() {
  475. if !connected {
  476. atomic.AddInt32(&p.connectingClients, -1)
  477. }
  478. }()
  479. // Initialize WebRTC using the client's offer SDP
  480. webRTCAnswerCtx, webRTCAnswerCancelFunc := context.WithTimeout(
  481. ctx, common.ValueOrDefault(webRTCCoordinator.WebRTCAnswerTimeout(), proxyWebRTCAnswerTimeout))
  482. defer webRTCAnswerCancelFunc()
  483. webRTCConn, SDP, sdpMetrics, webRTCErr := NewWebRTCConnWithAnswer(
  484. webRTCAnswerCtx,
  485. &WebRTCConfig{
  486. Logger: p.config.Logger,
  487. EnableDebugLogging: p.config.EnableWebRTCDebugLogging,
  488. WebRTCDialCoordinator: webRTCCoordinator,
  489. ClientRootObfuscationSecret: announceResponse.ClientRootObfuscationSecret,
  490. DoDTLSRandomization: announceResponse.DoDTLSRandomization,
  491. TrafficShapingParameters: announceResponse.TrafficShapingParameters,
  492. },
  493. announceResponse.ClientOfferSDP)
  494. var webRTCRequestErr string
  495. if webRTCErr != nil {
  496. webRTCErr = errors.Trace(webRTCErr)
  497. webRTCRequestErr = webRTCErr.Error()
  498. SDP = webrtc.SessionDescription{}
  499. sdpMetrics = &SDPMetrics{}
  500. // Continue to report the error to the broker. The broker will respond
  501. // with failure to the client's offer request.
  502. } else {
  503. defer webRTCConn.Close()
  504. }
  505. // Send answer request with SDP or error.
  506. _, err = brokerClient.ProxyAnswer(
  507. ctx,
  508. &ProxyAnswerRequest{
  509. ConnectionID: announceResponse.ConnectionID,
  510. SelectedProxyProtocolVersion: announceResponse.ClientProxyProtocolVersion,
  511. ProxyAnswerSDP: SDP,
  512. ICECandidateTypes: sdpMetrics.ICECandidateTypes,
  513. AnswerError: webRTCRequestErr,
  514. })
  515. if err != nil {
  516. if webRTCErr != nil {
  517. // Prioritize returning any WebRTC error for logging.
  518. return backOff, webRTCErr
  519. }
  520. return backOff, errors.Trace(err)
  521. }
  522. // Now that an answer is sent, stop if WebRTC initialization failed.
  523. if webRTCErr != nil {
  524. return backOff, webRTCErr
  525. }
  526. // Await the WebRTC connection.
  527. // We could concurrently dial the destination, to have that network
  528. // connection available immediately once the WebRTC channel is
  529. // established. This would work only for TCP, not UDP, network protocols
  530. // and could only include the TCP connection, as client traffic is
  531. // required for all higher layers such as TLS, SSH, etc. This could also
  532. // create wasted load on destination Psiphon servers, particularly when
  533. // WebRTC connections fail.
  534. awaitDataChannelCtx, awaitDataChannelCancelFunc := context.WithTimeout(
  535. ctx,
  536. common.ValueOrDefault(
  537. webRTCCoordinator.WebRTCAwaitDataChannelTimeout(), dataChannelAwaitTimeout))
  538. defer awaitDataChannelCancelFunc()
  539. err = webRTCConn.AwaitInitialDataChannel(awaitDataChannelCtx)
  540. if err != nil {
  541. return backOff, errors.Trace(err)
  542. }
  543. p.config.Logger.WithTraceFields(common.LogFields{
  544. "connectionID": announceResponse.ConnectionID,
  545. }).Info("WebRTC data channel established")
  546. // Dial the destination, a Psiphon server. The broker validates that the
  547. // dial destination is a Psiphon server.
  548. destinationDialContext, destinationDialCancelFunc := context.WithTimeout(
  549. ctx, common.ValueOrDefault(webRTCCoordinator.ProxyDestinationDialTimeout(), proxyDestinationDialTimeout))
  550. defer destinationDialCancelFunc()
  551. // Use the custom resolver when resolving destination hostnames, such as
  552. // those used in domain fronted protocols.
  553. //
  554. // - Resolving at the in-proxy should yield a more optimal CDN edge, vs.
  555. // resolving at the client.
  556. //
  557. // - Sending unresolved hostnames to in-proxies can expose some domain
  558. // fronting configuration. This can be mitigated by enabling domain
  559. // fronting on this 2nd hop only when the in-proxy is located in a
  560. // region that may be censored or blocked; this is to be enforced by
  561. // the broker.
  562. //
  563. // - Any DNSResolverPreresolved tactics applied will be relative to the
  564. // in-proxy location.
  565. destinationAddress, err := webRTCCoordinator.ResolveAddress(
  566. ctx, "ip", announceResponse.DestinationAddress)
  567. if err != nil {
  568. return backOff, errors.Trace(err)
  569. }
  570. var dialer net.Dialer
  571. destinationConn, err := dialer.DialContext(
  572. destinationDialContext,
  573. announceResponse.NetworkProtocol.String(),
  574. destinationAddress)
  575. if err != nil {
  576. return backOff, errors.Trace(err)
  577. }
  578. defer destinationConn.Close()
  579. // For activity updates, indicate that a client connection is established.
  580. connected = true
  581. atomic.AddInt32(&p.connectingClients, -1)
  582. atomic.AddInt32(&p.connectedClients, 1)
  583. defer func() {
  584. atomic.AddInt32(&p.connectedClients, -1)
  585. }()
  586. // Throttle the relay connection.
  587. //
  588. // Here, each client gets LimitUp/DownstreamBytesPerSecond. Proxy
  589. // operators may to want to limit their bandwidth usage with a single
  590. // up/down value, an overall limit. The ProxyConfig can simply be
  591. // generated by dividing the limit by MaxClients. This approach favors
  592. // performance stability: each client gets the same throttling limits
  593. // regardless of how many other clients are connected.
  594. destinationConn = common.NewThrottledConn(
  595. destinationConn,
  596. common.RateLimits{
  597. ReadBytesPerSecond: int64(p.config.LimitUpstreamBytesPerSecond),
  598. WriteBytesPerSecond: int64(p.config.LimitDownstreamBytesPerSecond),
  599. })
  600. // Hook up bytes transferred counting for activity updates.
  601. // The ActivityMonitoredConn inactivity timeout is not configured, since
  602. // the Psiphon server will close its connection to inactive clients on
  603. // its own schedule.
  604. destinationConn, err = common.NewActivityMonitoredConn(
  605. destinationConn, 0, false, nil, p.activityUpdateWrapper)
  606. if err != nil {
  607. return backOff, errors.Trace(err)
  608. }
  609. // Relay the client traffic to the destination. The client traffic is a
  610. // standard Psiphon tunnel protocol destinated to a Psiphon server. Any
  611. // blocking/censorship at the 2nd hop will be mitigated by the use of
  612. // Psiphon circumvention protocols and techniques.
  613. // Limitation: clients may apply fragmentation to traffic relayed over the
  614. // data channel, and there's no guarantee that the fragmentation write
  615. // sizes or delays will carry over to the egress side.
  616. // The proxy operator's ISP may be able to observe that the operator's
  617. // host has nearly matching ingress and egress traffic. The traffic
  618. // content won't be the same: the ingress traffic is wrapped in a WebRTC
  619. // data channel, and the egress traffic is a Psiphon tunnel protocol.
  620. // With padding and decoy packets, the ingress and egress traffic shape
  621. // will differ beyond the basic WebRTC overheader. Even with this
  622. // measure, over time the number of bytes in and out of the proxy may
  623. // still indicate proxying.
  624. waitGroup := new(sync.WaitGroup)
  625. relayErrors := make(chan error, 2)
  626. var relayedUp, relayedDown int32
  627. waitGroup.Add(1)
  628. go func() {
  629. defer waitGroup.Done()
  630. // WebRTC data channels are based on SCTP, which is actually
  631. // message-based, not a stream. The (default) max message size for
  632. // pion/sctp is 65536:
  633. // https://github.com/pion/sctp/blob/44ed465396c880e379aae9c1bf81809a9e06b580/association.go#L52.
  634. //
  635. // As io.Copy uses a buffer size of 32K, each relayed message will be
  636. // less than the maximum. Calls to ClientConn.Write are also expected
  637. // to use io.Copy, keeping messages at most 32K in size.
  638. // io.Copy doesn't return an error on EOF, but we still want to signal
  639. // that relaying is done, so in this case a nil error is sent to the
  640. // channel.
  641. //
  642. // Limitation: if one io.Copy goproutine sends nil and the other
  643. // io.Copy goroutine sends a non-nil error concurrently, the non-nil
  644. // error isn't prioritized.
  645. n, err := io.Copy(webRTCConn, destinationConn)
  646. if n > 0 {
  647. atomic.StoreInt32(&relayedDown, 1)
  648. }
  649. relayErrors <- errors.Trace(err)
  650. }()
  651. waitGroup.Add(1)
  652. go func() {
  653. defer waitGroup.Done()
  654. n, err := io.Copy(destinationConn, webRTCConn)
  655. if n > 0 {
  656. atomic.StoreInt32(&relayedUp, 1)
  657. }
  658. relayErrors <- errors.Trace(err)
  659. }()
  660. select {
  661. case err = <-relayErrors:
  662. case <-ctx.Done():
  663. }
  664. // Interrupt the relay goroutines by closing the connections.
  665. webRTCConn.Close()
  666. destinationConn.Close()
  667. waitGroup.Wait()
  668. p.config.Logger.WithTraceFields(common.LogFields{
  669. "connectionID": announceResponse.ConnectionID,
  670. }).Info("connection closed")
  671. // Don't apply a back-off delay to the next announcement since this
  672. // iteration successfully relayed bytes.
  673. if atomic.LoadInt32(&relayedUp) == 1 || atomic.LoadInt32(&relayedDown) == 1 {
  674. backOff = false
  675. }
  676. return backOff, err
  677. }
  678. func (p *Proxy) getMetrics(webRTCCoordinator WebRTCDialCoordinator) (*ProxyMetrics, string, error) {
  679. // tacticsNetworkID records the exact network ID that corresponds to the
  680. // tactics tag sent in the base parameters, and is used when applying any
  681. // new tactics returned by the broker.
  682. baseParams, tacticsNetworkID, err := p.config.GetBaseAPIParameters()
  683. if err != nil {
  684. return nil, "", errors.Trace(err)
  685. }
  686. packedBaseParams, err := protocol.EncodePackedAPIParameters(baseParams)
  687. if err != nil {
  688. return nil, "", errors.Trace(err)
  689. }
  690. return &ProxyMetrics{
  691. BaseAPIParameters: packedBaseParams,
  692. ProxyProtocolVersion: ProxyProtocolVersion1,
  693. NATType: webRTCCoordinator.NATType(),
  694. PortMappingTypes: webRTCCoordinator.PortMappingTypes(),
  695. MaxClients: int32(p.config.MaxClients),
  696. ConnectingClients: atomic.LoadInt32(&p.connectingClients),
  697. ConnectedClients: atomic.LoadInt32(&p.connectedClients),
  698. LimitUpstreamBytesPerSecond: int64(p.config.LimitUpstreamBytesPerSecond),
  699. LimitDownstreamBytesPerSecond: int64(p.config.LimitDownstreamBytesPerSecond),
  700. PeakUpstreamBytesPerSecond: atomic.LoadInt64(&p.peakBytesUp),
  701. PeakDownstreamBytesPerSecond: atomic.LoadInt64(&p.peakBytesDown),
  702. }, tacticsNetworkID, nil
  703. }