trafficRules.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. /*
  2. * Copyright (c) 2016, 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 server
  20. import (
  21. "encoding/json"
  22. "errors"
  23. "fmt"
  24. "net"
  25. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  26. )
  27. const (
  28. DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS = 30000
  29. DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS = 30000
  30. DEFAULT_DIAL_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS = 10000
  31. DEFAULT_MAX_TCP_DIALING_PORT_FORWARD_COUNT = 64
  32. DEFAULT_MAX_TCP_PORT_FORWARD_COUNT = 512
  33. DEFAULT_MAX_UDP_PORT_FORWARD_COUNT = 32
  34. DEFAULT_MEEK_RATE_LIMITER_GARBAGE_COLLECTOR_TRIGGER_COUNT = 5000
  35. DEFAULT_MEEK_RATE_LIMITER_REAP_HISTORY_FREQUENCY_SECONDS = 600
  36. )
  37. // TrafficRulesSet represents the various traffic rules to
  38. // apply to Psiphon client tunnels. The Reload function supports
  39. // hot reloading of rules data while the server is running.
  40. //
  41. // For a given client, the traffic rules are determined by starting
  42. // with DefaultRules, then finding the first (if any)
  43. // FilteredTrafficRules match and overriding the defaults with fields
  44. // set in the selected FilteredTrafficRules.
  45. type TrafficRulesSet struct {
  46. common.ReloadableFile
  47. // DefaultRules are the base values to use as defaults for all
  48. // clients.
  49. DefaultRules TrafficRules
  50. // FilteredTrafficRules is an ordered list of filter/rules pairs.
  51. // For each client, the first matching Filter in FilteredTrafficRules
  52. // determines the additional Rules that are selected and applied
  53. // on top of DefaultRules.
  54. FilteredRules []struct {
  55. Filter TrafficRulesFilter
  56. Rules TrafficRules
  57. }
  58. // MeekRateLimiterHistorySize enables the late-stage meek rate limiter and
  59. // sets its history size. The late-stage meek rate limiter acts on client
  60. // IPs relayed in MeekProxyForwardedForHeaders, and so it must wait for
  61. // the HTTP headers to be read. This rate limiter immediately terminates
  62. // any client endpoint request or any request to create a new session, but
  63. // not any meek request for an existing session, if the
  64. // MeekRateLimiterHistorySize requests occur in
  65. // MeekRateLimiterThresholdSeconds. The scope of rate limiting may be
  66. // limited using LimitMeekRateLimiterRegions.
  67. //
  68. // Hot reloading a new history size will result in existing history being
  69. // truncated.
  70. MeekRateLimiterHistorySize int
  71. // MeekRateLimiterThresholdSeconds is part of the meek rate limiter
  72. // specification and must be set when MeekRateLimiterHistorySize is set.
  73. MeekRateLimiterThresholdSeconds int
  74. // MeekRateLimiterRegions, if set, limits application of the meek
  75. // late-stage rate limiter to clients in the specified list of GeoIP
  76. // countries. When omitted or empty, meek rate limiting, if configured,
  77. // is applied to all clients.
  78. MeekRateLimiterRegions []string
  79. // MeekRateLimiterGarbageCollectionTriggerCount specifies the number of
  80. // rate limit events after which garbage collection is manually triggered
  81. // in order to reclaim memory used by rate limited and other rejected
  82. // requests.
  83. // A default of 5000 is used when
  84. // MeekRateLimiterGarbageCollectionTriggerCount is 0.
  85. MeekRateLimiterGarbageCollectionTriggerCount int
  86. // MeekRateLimiterReapHistoryFrequencySeconds specifies a schedule for
  87. // reaping old records from the rate limit history.
  88. // A default of 600 is used when
  89. // MeekRateLimiterReapHistoryFrequencySeconds is 0.
  90. MeekRateLimiterReapHistoryFrequencySeconds int
  91. }
  92. // TrafficRulesFilter defines a filter to match against client attributes.
  93. type TrafficRulesFilter struct {
  94. // TunnelProtocols is a list of client tunnel protocols that must be
  95. // in use to match this filter. When omitted or empty, any protocol
  96. // matches.
  97. TunnelProtocols []string
  98. // Regions is a list of client GeoIP countries that the client must
  99. // reolve to to match this filter. When omitted or empty, any client
  100. // region matches.
  101. Regions []string
  102. // APIProtocol specifies whether the client must use the SSH
  103. // API protocol (when "ssh") or the web API protocol (when "web").
  104. // When omitted or blank, any API protocol matches.
  105. APIProtocol string
  106. // HandshakeParameters specifies handshake API parameter names and
  107. // a list of values, one of which must be specified to match this
  108. // filter. Only scalar string API parameters may be filtered.
  109. // Values may be patterns containing the '*' wildcard.
  110. HandshakeParameters map[string][]string
  111. // AuthorizedAccessTypes specifies a list of access types, at least
  112. // one of which the client must have presented an active authorization
  113. // for and which must not be revoked.
  114. // AuthorizedAccessTypes is ignored when AuthorizationsRevoked is true.
  115. AuthorizedAccessTypes []string
  116. // AuthorizationsRevoked indicates whether the client's authorizations
  117. // must have been revoked. When true, authorizations must have been
  118. // revoked. When omitted or false, this field is ignored.
  119. AuthorizationsRevoked bool
  120. }
  121. // TrafficRules specify the limits placed on client traffic.
  122. type TrafficRules struct {
  123. // RateLimits specifies data transfer rate limits for the
  124. // client traffic.
  125. RateLimits RateLimits
  126. // DialTCPPortForwardTimeoutMilliseconds is the timeout period
  127. // for dialing TCP port forwards. A value of 0 specifies no timeout.
  128. // When omitted in DefaultRules,
  129. // DEFAULT_TCP_PORT_FORWARD_DIAL_TIMEOUT_MILLISECONDS is used.
  130. DialTCPPortForwardTimeoutMilliseconds *int
  131. // IdleTCPPortForwardTimeoutMilliseconds is the timeout period
  132. // after which idle (no bytes flowing in either direction)
  133. // client TCP port forwards are preemptively closed.
  134. // A value of 0 specifies no idle timeout. When omitted in
  135. // DefaultRules, DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS
  136. // is used.
  137. IdleTCPPortForwardTimeoutMilliseconds *int
  138. // IdleUDPPortForwardTimeoutMilliseconds is the timeout period
  139. // after which idle (no bytes flowing in either direction)
  140. // client UDP port forwards are preemptively closed.
  141. // A value of 0 specifies no idle timeout. When omitted in
  142. // DefaultRules, DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS
  143. // is used.
  144. IdleUDPPortForwardTimeoutMilliseconds *int
  145. // MaxTCPDialingPortForwardCount is the maximum number of dialing
  146. // TCP port forwards each client may have open concurrently. When
  147. // persistently at the limit, new TCP port forwards are rejected.
  148. // A value of 0 specifies no maximum. When omitted in
  149. // DefaultRules, DEFAULT_MAX_TCP_DIALING_PORT_FORWARD_COUNT is used.
  150. MaxTCPDialingPortForwardCount *int
  151. // MaxTCPPortForwardCount is the maximum number of established TCP
  152. // port forwards each client may have open concurrently. If at the
  153. // limit when a new TCP port forward is established, the LRU
  154. // established TCP port forward is closed.
  155. // A value of 0 specifies no maximum. When omitted in
  156. // DefaultRules, DEFAULT_MAX_TCP_PORT_FORWARD_COUNT is used.
  157. MaxTCPPortForwardCount *int
  158. // MaxUDPPortForwardCount is the maximum number of UDP port
  159. // forwards each client may have open concurrently. If at the
  160. // limit when a new UDP port forward is created, the LRU
  161. // UDP port forward is closed.
  162. // A value of 0 specifies no maximum. When omitted in
  163. // DefaultRules, DEFAULT_MAX_UDP_PORT_FORWARD_COUNT is used.
  164. MaxUDPPortForwardCount *int
  165. // AllowTCPPorts specifies a whitelist of TCP ports that
  166. // are permitted for port forwarding. When set, only ports
  167. // in the list are accessible to clients.
  168. AllowTCPPorts []int
  169. // AllowUDPPorts specifies a whitelist of UDP ports that
  170. // are permitted for port forwarding. When set, only ports
  171. // in the list are accessible to clients.
  172. AllowUDPPorts []int
  173. // AllowSubnets specifies a list of IP address subnets for
  174. // which all TCP and UDP ports are allowed. This list is
  175. // consulted if a port is disallowed by the AllowTCPPorts
  176. // or AllowUDPPorts configuration. Each entry is a IP subnet
  177. // in CIDR notation.
  178. // Limitation: currently, AllowSubnets only matches port
  179. // forwards where the client sends an IP address. Domain
  180. // names aren not resolved before checking AllowSubnets.
  181. AllowSubnets []string
  182. }
  183. // RateLimits is a clone of common.RateLimits with pointers
  184. // to fields to enable distinguishing between zero values and
  185. // omitted values in JSON serialized traffic rules.
  186. // See common.RateLimits for field descriptions.
  187. type RateLimits struct {
  188. ReadUnthrottledBytes *int64
  189. ReadBytesPerSecond *int64
  190. WriteUnthrottledBytes *int64
  191. WriteBytesPerSecond *int64
  192. CloseAfterExhausted *bool
  193. // UnthrottleFirstTunnelOnly specifies whether any
  194. // ReadUnthrottledBytes/WriteUnthrottledBytes apply
  195. // only to the first tunnel in a session.
  196. UnthrottleFirstTunnelOnly *bool
  197. }
  198. // CommonRateLimits converts a RateLimits to a common.RateLimits.
  199. func (rateLimits *RateLimits) CommonRateLimits() common.RateLimits {
  200. return common.RateLimits{
  201. ReadUnthrottledBytes: *rateLimits.ReadUnthrottledBytes,
  202. ReadBytesPerSecond: *rateLimits.ReadBytesPerSecond,
  203. WriteUnthrottledBytes: *rateLimits.WriteUnthrottledBytes,
  204. WriteBytesPerSecond: *rateLimits.WriteBytesPerSecond,
  205. CloseAfterExhausted: *rateLimits.CloseAfterExhausted,
  206. }
  207. }
  208. // NewTrafficRulesSet initializes a TrafficRulesSet with
  209. // the rules data in the specified config file.
  210. func NewTrafficRulesSet(filename string) (*TrafficRulesSet, error) {
  211. set := &TrafficRulesSet{}
  212. set.ReloadableFile = common.NewReloadableFile(
  213. filename,
  214. func(fileContent []byte) error {
  215. var newSet TrafficRulesSet
  216. err := json.Unmarshal(fileContent, &newSet)
  217. if err != nil {
  218. return common.ContextError(err)
  219. }
  220. err = newSet.Validate()
  221. if err != nil {
  222. return common.ContextError(err)
  223. }
  224. // Modify actual traffic rules only after validation
  225. set.MeekRateLimiterHistorySize = newSet.MeekRateLimiterHistorySize
  226. set.MeekRateLimiterThresholdSeconds = newSet.MeekRateLimiterThresholdSeconds
  227. set.MeekRateLimiterRegions = newSet.MeekRateLimiterRegions
  228. set.MeekRateLimiterGarbageCollectionTriggerCount = newSet.MeekRateLimiterGarbageCollectionTriggerCount
  229. set.MeekRateLimiterReapHistoryFrequencySeconds = newSet.MeekRateLimiterReapHistoryFrequencySeconds
  230. set.DefaultRules = newSet.DefaultRules
  231. set.FilteredRules = newSet.FilteredRules
  232. return nil
  233. })
  234. _, err := set.Reload()
  235. if err != nil {
  236. return nil, common.ContextError(err)
  237. }
  238. return set, nil
  239. }
  240. // Validate checks for correct input formats in a TrafficRulesSet.
  241. func (set *TrafficRulesSet) Validate() error {
  242. if set.MeekRateLimiterHistorySize < 0 ||
  243. set.MeekRateLimiterThresholdSeconds < 0 ||
  244. set.MeekRateLimiterGarbageCollectionTriggerCount < 0 ||
  245. set.MeekRateLimiterReapHistoryFrequencySeconds < 0 {
  246. return common.ContextError(
  247. errors.New("MeekRateLimiter values must be >= 0"))
  248. }
  249. if set.MeekRateLimiterHistorySize > 0 {
  250. if set.MeekRateLimiterThresholdSeconds <= 0 {
  251. return common.ContextError(
  252. errors.New("MeekRateLimiterThresholdSeconds must be > 0"))
  253. }
  254. }
  255. validateTrafficRules := func(rules *TrafficRules) error {
  256. if (rules.RateLimits.ReadUnthrottledBytes != nil && *rules.RateLimits.ReadUnthrottledBytes < 0) ||
  257. (rules.RateLimits.ReadBytesPerSecond != nil && *rules.RateLimits.ReadBytesPerSecond < 0) ||
  258. (rules.RateLimits.WriteUnthrottledBytes != nil && *rules.RateLimits.WriteUnthrottledBytes < 0) ||
  259. (rules.RateLimits.WriteBytesPerSecond != nil && *rules.RateLimits.WriteBytesPerSecond < 0) ||
  260. (rules.DialTCPPortForwardTimeoutMilliseconds != nil && *rules.DialTCPPortForwardTimeoutMilliseconds < 0) ||
  261. (rules.IdleTCPPortForwardTimeoutMilliseconds != nil && *rules.IdleTCPPortForwardTimeoutMilliseconds < 0) ||
  262. (rules.IdleUDPPortForwardTimeoutMilliseconds != nil && *rules.IdleUDPPortForwardTimeoutMilliseconds < 0) ||
  263. (rules.MaxTCPDialingPortForwardCount != nil && *rules.MaxTCPDialingPortForwardCount < 0) ||
  264. (rules.MaxTCPPortForwardCount != nil && *rules.MaxTCPPortForwardCount < 0) ||
  265. (rules.MaxUDPPortForwardCount != nil && *rules.MaxUDPPortForwardCount < 0) {
  266. return common.ContextError(
  267. errors.New("TrafficRules values must be >= 0"))
  268. }
  269. for _, subnet := range rules.AllowSubnets {
  270. _, _, err := net.ParseCIDR(subnet)
  271. if err != nil {
  272. return common.ContextError(
  273. fmt.Errorf("invalid subnet: %s %s", subnet, err))
  274. }
  275. }
  276. return nil
  277. }
  278. err := validateTrafficRules(&set.DefaultRules)
  279. if err != nil {
  280. return common.ContextError(err)
  281. }
  282. for _, filteredRule := range set.FilteredRules {
  283. for paramName := range filteredRule.Filter.HandshakeParameters {
  284. validParamName := false
  285. for _, paramSpec := range baseRequestParams {
  286. if paramSpec.name == paramName {
  287. validParamName = true
  288. break
  289. }
  290. }
  291. if !validParamName {
  292. return common.ContextError(
  293. fmt.Errorf("invalid parameter name: %s", paramName))
  294. }
  295. }
  296. err := validateTrafficRules(&filteredRule.Rules)
  297. if err != nil {
  298. return common.ContextError(err)
  299. }
  300. }
  301. return nil
  302. }
  303. // GetTrafficRules determines the traffic rules for a client based on its attributes.
  304. // For the return value TrafficRules, all pointer and slice fields are initialized,
  305. // so nil checks are not required. The caller must not modify the returned TrafficRules.
  306. func (set *TrafficRulesSet) GetTrafficRules(
  307. isFirstTunnelInSession bool,
  308. tunnelProtocol string,
  309. geoIPData GeoIPData,
  310. state handshakeState) TrafficRules {
  311. set.ReloadableFile.RLock()
  312. defer set.ReloadableFile.RUnlock()
  313. // Start with a copy of the DefaultRules, and then select the first
  314. // matching Rules from FilteredTrafficRules, taking only the explicitly
  315. // specified fields from that Rules.
  316. //
  317. // Notes:
  318. // - Scalar pointers are used in TrafficRules and RateLimits to distinguish between
  319. // omitted fields (in serialized JSON) and default values. For example, if a filtered
  320. // Rules specifies a field value of 0, this will override the default; but if the
  321. // serialized filtered rule omits the field, the default is to be retained.
  322. // - We use shallow copies and slices and scalar pointers are shared between the
  323. // return value TrafficRules, so callers must treat the return value as immutable.
  324. // This also means that these slices and pointers can remain referenced in memory even
  325. // after a hot reload.
  326. trafficRules := set.DefaultRules
  327. // Populate defaults for omitted DefaultRules fields
  328. if trafficRules.RateLimits.ReadUnthrottledBytes == nil {
  329. trafficRules.RateLimits.ReadUnthrottledBytes = new(int64)
  330. }
  331. if trafficRules.RateLimits.ReadBytesPerSecond == nil {
  332. trafficRules.RateLimits.ReadBytesPerSecond = new(int64)
  333. }
  334. if trafficRules.RateLimits.WriteUnthrottledBytes == nil {
  335. trafficRules.RateLimits.WriteUnthrottledBytes = new(int64)
  336. }
  337. if trafficRules.RateLimits.WriteBytesPerSecond == nil {
  338. trafficRules.RateLimits.WriteBytesPerSecond = new(int64)
  339. }
  340. if trafficRules.RateLimits.CloseAfterExhausted == nil {
  341. trafficRules.RateLimits.CloseAfterExhausted = new(bool)
  342. }
  343. if trafficRules.RateLimits.UnthrottleFirstTunnelOnly == nil {
  344. trafficRules.RateLimits.UnthrottleFirstTunnelOnly = new(bool)
  345. }
  346. intPtr := func(i int) *int {
  347. return &i
  348. }
  349. if trafficRules.DialTCPPortForwardTimeoutMilliseconds == nil {
  350. trafficRules.DialTCPPortForwardTimeoutMilliseconds =
  351. intPtr(DEFAULT_DIAL_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  352. }
  353. if trafficRules.IdleTCPPortForwardTimeoutMilliseconds == nil {
  354. trafficRules.IdleTCPPortForwardTimeoutMilliseconds =
  355. intPtr(DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  356. }
  357. if trafficRules.IdleUDPPortForwardTimeoutMilliseconds == nil {
  358. trafficRules.IdleUDPPortForwardTimeoutMilliseconds =
  359. intPtr(DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  360. }
  361. if trafficRules.MaxTCPDialingPortForwardCount == nil {
  362. trafficRules.MaxTCPDialingPortForwardCount =
  363. intPtr(DEFAULT_MAX_TCP_DIALING_PORT_FORWARD_COUNT)
  364. }
  365. if trafficRules.MaxTCPPortForwardCount == nil {
  366. trafficRules.MaxTCPPortForwardCount =
  367. intPtr(DEFAULT_MAX_TCP_PORT_FORWARD_COUNT)
  368. }
  369. if trafficRules.MaxUDPPortForwardCount == nil {
  370. trafficRules.MaxUDPPortForwardCount =
  371. intPtr(DEFAULT_MAX_UDP_PORT_FORWARD_COUNT)
  372. }
  373. if trafficRules.AllowTCPPorts == nil {
  374. trafficRules.AllowTCPPorts = make([]int, 0)
  375. }
  376. if trafficRules.AllowUDPPorts == nil {
  377. trafficRules.AllowUDPPorts = make([]int, 0)
  378. }
  379. if trafficRules.AllowSubnets == nil {
  380. trafficRules.AllowSubnets = make([]string, 0)
  381. }
  382. // TODO: faster lookup?
  383. for _, filteredRules := range set.FilteredRules {
  384. log.WithContextFields(LogFields{"filter": filteredRules.Filter}).Debug("filter check")
  385. if len(filteredRules.Filter.TunnelProtocols) > 0 {
  386. if !common.Contains(filteredRules.Filter.TunnelProtocols, tunnelProtocol) {
  387. continue
  388. }
  389. }
  390. if len(filteredRules.Filter.Regions) > 0 {
  391. if !common.Contains(filteredRules.Filter.Regions, geoIPData.Country) {
  392. continue
  393. }
  394. }
  395. if filteredRules.Filter.APIProtocol != "" {
  396. if !state.completed {
  397. continue
  398. }
  399. if state.apiProtocol != filteredRules.Filter.APIProtocol {
  400. continue
  401. }
  402. }
  403. if filteredRules.Filter.HandshakeParameters != nil {
  404. if !state.completed {
  405. continue
  406. }
  407. mismatch := false
  408. for name, values := range filteredRules.Filter.HandshakeParameters {
  409. clientValue, err := getStringRequestParam(state.apiParams, name)
  410. if err != nil || !common.ContainsWildcard(values, clientValue) {
  411. mismatch = true
  412. break
  413. }
  414. }
  415. if mismatch {
  416. continue
  417. }
  418. }
  419. if filteredRules.Filter.AuthorizationsRevoked {
  420. if !state.completed {
  421. continue
  422. }
  423. if !state.authorizationsRevoked {
  424. continue
  425. }
  426. } else if len(filteredRules.Filter.AuthorizedAccessTypes) > 0 {
  427. if !state.completed {
  428. continue
  429. }
  430. if state.authorizationsRevoked {
  431. continue
  432. }
  433. if !common.ContainsAny(filteredRules.Filter.AuthorizedAccessTypes, state.authorizedAccessTypes) {
  434. continue
  435. }
  436. }
  437. log.WithContextFields(LogFields{"filter": filteredRules.Filter}).Debug("filter match")
  438. // This is the first match. Override defaults using provided fields from selected rules, and return result.
  439. if filteredRules.Rules.RateLimits.ReadUnthrottledBytes != nil {
  440. trafficRules.RateLimits.ReadUnthrottledBytes = filteredRules.Rules.RateLimits.ReadUnthrottledBytes
  441. }
  442. if filteredRules.Rules.RateLimits.ReadBytesPerSecond != nil {
  443. trafficRules.RateLimits.ReadBytesPerSecond = filteredRules.Rules.RateLimits.ReadBytesPerSecond
  444. }
  445. if filteredRules.Rules.RateLimits.WriteUnthrottledBytes != nil {
  446. trafficRules.RateLimits.WriteUnthrottledBytes = filteredRules.Rules.RateLimits.WriteUnthrottledBytes
  447. }
  448. if filteredRules.Rules.RateLimits.WriteBytesPerSecond != nil {
  449. trafficRules.RateLimits.WriteBytesPerSecond = filteredRules.Rules.RateLimits.WriteBytesPerSecond
  450. }
  451. if filteredRules.Rules.RateLimits.CloseAfterExhausted != nil {
  452. trafficRules.RateLimits.CloseAfterExhausted = filteredRules.Rules.RateLimits.CloseAfterExhausted
  453. }
  454. if filteredRules.Rules.RateLimits.UnthrottleFirstTunnelOnly != nil {
  455. trafficRules.RateLimits.UnthrottleFirstTunnelOnly = filteredRules.Rules.RateLimits.UnthrottleFirstTunnelOnly
  456. }
  457. if filteredRules.Rules.DialTCPPortForwardTimeoutMilliseconds != nil {
  458. trafficRules.DialTCPPortForwardTimeoutMilliseconds = filteredRules.Rules.DialTCPPortForwardTimeoutMilliseconds
  459. }
  460. if filteredRules.Rules.IdleTCPPortForwardTimeoutMilliseconds != nil {
  461. trafficRules.IdleTCPPortForwardTimeoutMilliseconds = filteredRules.Rules.IdleTCPPortForwardTimeoutMilliseconds
  462. }
  463. if filteredRules.Rules.IdleUDPPortForwardTimeoutMilliseconds != nil {
  464. trafficRules.IdleUDPPortForwardTimeoutMilliseconds = filteredRules.Rules.IdleUDPPortForwardTimeoutMilliseconds
  465. }
  466. if filteredRules.Rules.MaxTCPDialingPortForwardCount != nil {
  467. trafficRules.MaxTCPDialingPortForwardCount = filteredRules.Rules.MaxTCPDialingPortForwardCount
  468. }
  469. if filteredRules.Rules.MaxTCPPortForwardCount != nil {
  470. trafficRules.MaxTCPPortForwardCount = filteredRules.Rules.MaxTCPPortForwardCount
  471. }
  472. if filteredRules.Rules.MaxUDPPortForwardCount != nil {
  473. trafficRules.MaxUDPPortForwardCount = filteredRules.Rules.MaxUDPPortForwardCount
  474. }
  475. if filteredRules.Rules.AllowTCPPorts != nil {
  476. trafficRules.AllowTCPPorts = filteredRules.Rules.AllowTCPPorts
  477. }
  478. if filteredRules.Rules.AllowUDPPorts != nil {
  479. trafficRules.AllowUDPPorts = filteredRules.Rules.AllowUDPPorts
  480. }
  481. if filteredRules.Rules.AllowSubnets != nil {
  482. trafficRules.AllowSubnets = filteredRules.Rules.AllowSubnets
  483. }
  484. break
  485. }
  486. if *trafficRules.RateLimits.UnthrottleFirstTunnelOnly && !isFirstTunnelInSession {
  487. trafficRules.RateLimits.ReadUnthrottledBytes = new(int64)
  488. trafficRules.RateLimits.WriteUnthrottledBytes = new(int64)
  489. }
  490. log.WithContextFields(LogFields{"trafficRules": trafficRules}).Debug("selected traffic rules")
  491. return trafficRules
  492. }
  493. // GetMeekRateLimiterConfig gets a snapshot of the meek rate limiter
  494. // configuration values.
  495. func (set *TrafficRulesSet) GetMeekRateLimiterConfig() (int, int, []string, int, int) {
  496. set.ReloadableFile.RLock()
  497. defer set.ReloadableFile.RUnlock()
  498. GCTriggerCount := set.MeekRateLimiterGarbageCollectionTriggerCount
  499. if GCTriggerCount <= 0 {
  500. GCTriggerCount = DEFAULT_MEEK_RATE_LIMITER_GARBAGE_COLLECTOR_TRIGGER_COUNT
  501. }
  502. reapFrequencySeconds := set.MeekRateLimiterReapHistoryFrequencySeconds
  503. if reapFrequencySeconds <= 0 {
  504. reapFrequencySeconds = DEFAULT_MEEK_RATE_LIMITER_REAP_HISTORY_FREQUENCY_SECONDS
  505. }
  506. return set.MeekRateLimiterHistorySize,
  507. set.MeekRateLimiterThresholdSeconds,
  508. set.MeekRateLimiterRegions,
  509. GCTriggerCount,
  510. reapFrequencySeconds
  511. }