clientParameters.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. /*
  2. * Copyright (c) 2018, 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. /*
  20. Package parameters implements dynamic, concurrency-safe parameters that
  21. determine Psiphon client behavior.
  22. Parameters include network timeouts, probabilities for actions, lists of
  23. protocols, etc. Parameters are initialized with reasonable defaults. New
  24. values may be applied, allowing the client to customized its parameters from
  25. both a config file and tactics data. Sane minimum values are enforced.
  26. Parameters may be read and updated concurrently. The read mechanism offers a
  27. snapshot so that related parameters, such as two Ints representing a range; or
  28. a more complex series of related parameters; may be read in an atomic and
  29. consistent way. For example:
  30. p := clientParameters.Get()
  31. min := p.Int("Min")
  32. max := p.Int("Max")
  33. p = nil
  34. For long-running operations, it is recommended to set any pointer to the
  35. snapshot to nil to allow garbage collection of old snaphots in cases where the
  36. parameters change.
  37. In general, client parameters should be read as close to the point of use as
  38. possible to ensure that dynamic changes to the parameter values take effect.
  39. For duration parameters, time.ParseDuration-compatible string values are
  40. supported when applying new values. This allows specifying durations as, for
  41. example, "100ms" or "24h".
  42. Values read from the parameters are not deep copies and must be treated as
  43. read-only.
  44. */
  45. package parameters
  46. import (
  47. "encoding/json"
  48. "fmt"
  49. "net/http"
  50. "reflect"
  51. "sync/atomic"
  52. "time"
  53. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  54. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/obfuscator"
  55. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  56. )
  57. const (
  58. NetworkLatencyMultiplier = "NetworkLatencyMultiplier"
  59. TacticsWaitPeriod = "TacticsWaitPeriod"
  60. TacticsRetryPeriod = "TacticsRetryPeriod"
  61. TacticsRetryPeriodJitter = "TacticsRetryPeriodJitter"
  62. TacticsTimeout = "TacticsTimeout"
  63. ConnectionWorkerPoolSize = "ConnectionWorkerPoolSize"
  64. TunnelConnectTimeout = "TunnelConnectTimeout"
  65. EstablishTunnelTimeout = "EstablishTunnelTimeout"
  66. EstablishTunnelWorkTime = "EstablishTunnelWorkTime"
  67. EstablishTunnelPausePeriod = "EstablishTunnelPausePeriod"
  68. EstablishTunnelPausePeriodJitter = "EstablishTunnelPausePeriodJitter"
  69. EstablishTunnelServerAffinityGracePeriod = "EstablishTunnelServerAffinityGracePeriod"
  70. StaggerConnectionWorkersPeriod = "StaggerConnectionWorkersPeriod"
  71. StaggerConnectionWorkersJitter = "StaggerConnectionWorkersJitter"
  72. LimitIntensiveConnectionWorkers = "LimitIntensiveConnectionWorkers"
  73. IgnoreHandshakeStatsRegexps = "IgnoreHandshakeStatsRegexps"
  74. PrioritizeTunnelProtocolsProbability = "PrioritizeTunnelProtocolsProbability"
  75. PrioritizeTunnelProtocols = "PrioritizeTunnelProtocols"
  76. PrioritizeTunnelProtocolsCandidateCount = "PrioritizeTunnelProtocolsCandidateCount"
  77. LimitTunnelProtocolsProbability = "LimitTunnelProtocolsProbability"
  78. LimitTunnelProtocols = "LimitTunnelProtocols"
  79. LimitTLSProfilesProbability = "LimitTLSProfilesProbability"
  80. LimitTLSProfiles = "LimitTLSProfiles"
  81. FragmentorProbability = "FragmentorProbability"
  82. FragmentorLimitProtocols = "FragmentorLimitProtocols"
  83. FragmentorMinTotalBytes = "FragmentorMinTotalBytes"
  84. FragmentorMaxTotalBytes = "FragmentorMaxTotalBytes"
  85. FragmentorMinWriteBytes = "FragmentorMinWriteBytes"
  86. FragmentorMaxWriteBytes = "FragmentorMaxWriteBytes"
  87. FragmentorMinDelay = "FragmentorMinDelay"
  88. FragmentorMaxDelay = "FragmentorMaxDelay"
  89. ObfuscatedSSHMinPadding = "ObfuscatedSSHMinPadding"
  90. ObfuscatedSSHMaxPadding = "ObfuscatedSSHMaxPadding"
  91. TunnelOperateShutdownTimeout = "TunnelOperateShutdownTimeout"
  92. TunnelPortForwardDialTimeout = "TunnelPortForwardDialTimeout"
  93. TunnelRateLimits = "TunnelRateLimits"
  94. AdditionalCustomHeaders = "AdditionalCustomHeaders"
  95. SpeedTestPaddingMinBytes = "SpeedTestPaddingMinBytes"
  96. SpeedTestPaddingMaxBytes = "SpeedTestPaddingMaxBytes"
  97. SpeedTestMaxSampleCount = "SpeedTestMaxSampleCount"
  98. SSHKeepAliveSpeedTestSampleProbability = "SSHKeepAliveSpeedTestSampleProbability"
  99. SSHKeepAlivePaddingMinBytes = "SSHKeepAlivePaddingMinBytes"
  100. SSHKeepAlivePaddingMaxBytes = "SSHKeepAlivePaddingMaxBytes"
  101. SSHKeepAlivePeriodMin = "SSHKeepAlivePeriodMin"
  102. SSHKeepAlivePeriodMax = "SSHKeepAlivePeriodMax"
  103. SSHKeepAlivePeriodicTimeout = "SSHKeepAlivePeriodicTimeout"
  104. SSHKeepAlivePeriodicInactivePeriod = "SSHKeepAlivePeriodicInactivePeriod"
  105. SSHKeepAliveProbeTimeout = "SSHKeepAliveProbeTimeout"
  106. SSHKeepAliveProbeInactivePeriod = "SSHKeepAliveProbeInactivePeriod"
  107. HTTPProxyOriginServerTimeout = "HTTPProxyOriginServerTimeout"
  108. HTTPProxyMaxIdleConnectionsPerHost = "HTTPProxyMaxIdleConnectionsPerHost"
  109. FetchRemoteServerListTimeout = "FetchRemoteServerListTimeout"
  110. FetchRemoteServerListRetryPeriod = "FetchRemoteServerListRetryPeriod"
  111. FetchRemoteServerListStalePeriod = "FetchRemoteServerListStalePeriod"
  112. RemoteServerListSignaturePublicKey = "RemoteServerListSignaturePublicKey"
  113. RemoteServerListURLs = "RemoteServerListURLs"
  114. ObfuscatedServerListRootURLs = "ObfuscatedServerListRootURLs"
  115. PsiphonAPIRequestTimeout = "PsiphonAPIRequestTimeout"
  116. PsiphonAPIStatusRequestPeriodMin = "PsiphonAPIStatusRequestPeriodMin"
  117. PsiphonAPIStatusRequestPeriodMax = "PsiphonAPIStatusRequestPeriodMax"
  118. PsiphonAPIStatusRequestShortPeriodMin = "PsiphonAPIStatusRequestShortPeriodMin"
  119. PsiphonAPIStatusRequestShortPeriodMax = "PsiphonAPIStatusRequestShortPeriodMax"
  120. PsiphonAPIStatusRequestPaddingMinBytes = "PsiphonAPIStatusRequestPaddingMinBytes"
  121. PsiphonAPIStatusRequestPaddingMaxBytes = "PsiphonAPIStatusRequestPaddingMaxBytes"
  122. PsiphonAPIPersistentStatsMaxCount = "PsiphonAPIPersistentStatsMaxCount"
  123. PsiphonAPIConnectedRequestPeriod = "PsiphonAPIConnectedRequestPeriod"
  124. PsiphonAPIConnectedRequestRetryPeriod = "PsiphonAPIConnectedRequestRetryPeriod"
  125. FetchSplitTunnelRoutesTimeout = "FetchSplitTunnelRoutesTimeout"
  126. SplitTunnelRoutesURLFormat = "SplitTunnelRoutesURLFormat"
  127. SplitTunnelRoutesSignaturePublicKey = "SplitTunnelRoutesSignaturePublicKey"
  128. SplitTunnelDNSServer = "SplitTunnelDNSServer"
  129. FetchUpgradeTimeout = "FetchUpgradeTimeout"
  130. FetchUpgradeRetryPeriod = "FetchUpgradeRetryPeriod"
  131. FetchUpgradeStalePeriod = "FetchUpgradeStalePeriod"
  132. UpgradeDownloadURLs = "UpgradeDownloadURLs"
  133. UpgradeDownloadClientVersionHeader = "UpgradeDownloadClientVersionHeader"
  134. ImpairedProtocolClassificationDuration = "ImpairedProtocolClassificationDuration"
  135. ImpairedProtocolClassificationThreshold = "ImpairedProtocolClassificationThreshold"
  136. TotalBytesTransferredNoticePeriod = "TotalBytesTransferredNoticePeriod"
  137. MeekDialDomainsOnly = "MeekDialDomainsOnly"
  138. MeekLimitBufferSizes = "MeekLimitBufferSizes"
  139. MeekCookieMaxPadding = "MeekCookieMaxPadding"
  140. MeekFullReceiveBufferLength = "MeekFullReceiveBufferLength"
  141. MeekReadPayloadChunkLength = "MeekReadPayloadChunkLength"
  142. MeekLimitedFullReceiveBufferLength = "MeekLimitedFullReceiveBufferLength"
  143. MeekLimitedReadPayloadChunkLength = "MeekLimitedReadPayloadChunkLength"
  144. MeekMinPollInterval = "MeekMinPollInterval"
  145. MeekMinPollIntervalJitter = "MeekMinPollIntervalJitter"
  146. MeekMaxPollInterval = "MeekMaxPollInterval"
  147. MeekMaxPollIntervalJitter = "MeekMaxPollIntervalJitter"
  148. MeekPollIntervalMultiplier = "MeekPollIntervalMultiplier"
  149. MeekPollIntervalJitter = "MeekPollIntervalJitter"
  150. MeekApplyPollIntervalMultiplierProbability = "MeekApplyPollIntervalMultiplierProbability"
  151. MeekRoundTripRetryDeadline = "MeekRoundTripRetryDeadline"
  152. MeekRoundTripRetryMinDelay = "MeekRoundTripRetryMinDelay"
  153. MeekRoundTripRetryMaxDelay = "MeekRoundTripRetryMaxDelay"
  154. MeekRoundTripRetryMultiplier = "MeekRoundTripRetryMultiplier"
  155. MeekRoundTripTimeout = "MeekRoundTripTimeout"
  156. TransformHostNameProbability = "TransformHostNameProbability"
  157. PickUserAgentProbability = "PickUserAgentProbability"
  158. )
  159. const (
  160. useNetworkLatencyMultiplier = 1
  161. )
  162. // defaultClientParameters specifies the type, default value, and minimum
  163. // value for all dynamically configurable client parameters.
  164. //
  165. // Do not change the names or types of existing values, as that can break
  166. // client logic or cause parameters to not be applied.
  167. //
  168. // Minimum values are a fail-safe for cases where lower values would break the
  169. // client logic. For example, setting a ConnectionWorkerPoolSize of 0 would
  170. // make the client never connect.
  171. var defaultClientParameters = map[string]struct {
  172. value interface{}
  173. minimum interface{}
  174. flags int32
  175. }{
  176. // NetworkLatencyMultiplier defaults to 0, meaning off. But when set, it
  177. // must be a multiplier >= 1.
  178. NetworkLatencyMultiplier: {value: 0.0, minimum: 1.0},
  179. TacticsWaitPeriod: {value: 10 * time.Second, minimum: 0 * time.Second, flags: useNetworkLatencyMultiplier},
  180. TacticsRetryPeriod: {value: 5 * time.Second, minimum: 1 * time.Millisecond},
  181. TacticsRetryPeriodJitter: {value: 0.3, minimum: 0.0},
  182. TacticsTimeout: {value: 2 * time.Minute, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  183. ConnectionWorkerPoolSize: {value: 10, minimum: 1},
  184. TunnelConnectTimeout: {value: 20 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  185. EstablishTunnelTimeout: {value: 300 * time.Second, minimum: time.Duration(0)},
  186. EstablishTunnelWorkTime: {value: 60 * time.Second, minimum: 1 * time.Second},
  187. EstablishTunnelPausePeriod: {value: 5 * time.Second, minimum: 1 * time.Millisecond},
  188. EstablishTunnelPausePeriodJitter: {value: 0.1, minimum: 0.0},
  189. EstablishTunnelServerAffinityGracePeriod: {value: 1 * time.Second, minimum: time.Duration(0), flags: useNetworkLatencyMultiplier},
  190. StaggerConnectionWorkersPeriod: {value: time.Duration(0), minimum: time.Duration(0)},
  191. StaggerConnectionWorkersJitter: {value: 0.1, minimum: 0.0},
  192. LimitIntensiveConnectionWorkers: {value: 0, minimum: 0},
  193. IgnoreHandshakeStatsRegexps: {value: false},
  194. TunnelOperateShutdownTimeout: {value: 1 * time.Second, minimum: 1 * time.Millisecond, flags: useNetworkLatencyMultiplier},
  195. TunnelPortForwardDialTimeout: {value: 10 * time.Second, minimum: 1 * time.Millisecond, flags: useNetworkLatencyMultiplier},
  196. TunnelRateLimits: {value: common.RateLimits{}},
  197. // PrioritizeTunnelProtocolsCandidateCount should be set to at least
  198. // ConnectionWorkerPoolSize in order to use only priotitized protocols in
  199. // the first establishment round. Even then, this will only happen if the
  200. // client has sufficient candidates supporting the prioritized protocols.
  201. PrioritizeTunnelProtocolsProbability: {value: 1.0, minimum: 0.0},
  202. PrioritizeTunnelProtocols: {value: protocol.TunnelProtocols{}},
  203. PrioritizeTunnelProtocolsCandidateCount: {value: 10, minimum: 0},
  204. LimitTunnelProtocolsProbability: {value: 1.0, minimum: 0.0},
  205. LimitTunnelProtocols: {value: protocol.TunnelProtocols{}},
  206. LimitTLSProfilesProbability: {value: 1.0, minimum: 0.0},
  207. LimitTLSProfiles: {value: protocol.TLSProfiles{}},
  208. FragmentorProbability: {value: 0.5, minimum: 0.0},
  209. FragmentorLimitProtocols: {value: protocol.TunnelProtocols{}},
  210. FragmentorMinTotalBytes: {value: 0, minimum: 0},
  211. FragmentorMaxTotalBytes: {value: 0, minimum: 0},
  212. FragmentorMinWriteBytes: {value: 1, minimum: 1},
  213. FragmentorMaxWriteBytes: {value: 1500, minimum: 1},
  214. FragmentorMinDelay: {value: time.Duration(0), minimum: time.Duration(0)},
  215. FragmentorMaxDelay: {value: 10 * time.Millisecond, minimum: time.Duration(0)},
  216. // The Psiphon server will reject obfuscated SSH seed messages with
  217. // padding greater than OBFUSCATE_MAX_PADDING.
  218. // obfuscator.NewClientObfuscator will ignore invalid min/max padding
  219. // configurations.
  220. ObfuscatedSSHMinPadding: {value: 0, minimum: 0},
  221. ObfuscatedSSHMaxPadding: {value: obfuscator.OBFUSCATE_MAX_PADDING, minimum: 0},
  222. AdditionalCustomHeaders: {value: make(http.Header)},
  223. // Speed test and SSH keep alive padding is intended to frustrate
  224. // fingerprinting and should not exceed ~1 IP packet size.
  225. //
  226. // Currently, each serialized speed test sample, populated with real
  227. // values, is approximately 100 bytes. All SpeedTestMaxSampleCount samples
  228. // are loaded into memory are sent as API inputs.
  229. SpeedTestPaddingMinBytes: {value: 0, minimum: 0},
  230. SpeedTestPaddingMaxBytes: {value: 256, minimum: 0},
  231. SpeedTestMaxSampleCount: {value: 25, minimum: 1},
  232. // The Psiphon server times out inactive tunnels after 5 minutes, so this
  233. // is a soft max for SSHKeepAlivePeriodMax.
  234. SSHKeepAliveSpeedTestSampleProbability: {value: 0.5, minimum: 0.0},
  235. SSHKeepAlivePaddingMinBytes: {value: 0, minimum: 0},
  236. SSHKeepAlivePaddingMaxBytes: {value: 256, minimum: 0},
  237. SSHKeepAlivePeriodMin: {value: 1 * time.Minute, minimum: 1 * time.Second},
  238. SSHKeepAlivePeriodMax: {value: 2 * time.Minute, minimum: 1 * time.Second},
  239. SSHKeepAlivePeriodicTimeout: {value: 30 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  240. SSHKeepAlivePeriodicInactivePeriod: {value: 10 * time.Second, minimum: 1 * time.Second},
  241. SSHKeepAliveProbeTimeout: {value: 30 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  242. SSHKeepAliveProbeInactivePeriod: {value: 10 * time.Second, minimum: 1 * time.Second},
  243. HTTPProxyOriginServerTimeout: {value: 15 * time.Second, minimum: time.Duration(0), flags: useNetworkLatencyMultiplier},
  244. HTTPProxyMaxIdleConnectionsPerHost: {value: 50, minimum: 0},
  245. FetchRemoteServerListTimeout: {value: 30 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  246. FetchRemoteServerListRetryPeriod: {value: 30 * time.Second, minimum: 1 * time.Millisecond},
  247. FetchRemoteServerListStalePeriod: {value: 6 * time.Hour, minimum: 1 * time.Hour},
  248. RemoteServerListSignaturePublicKey: {value: ""},
  249. RemoteServerListURLs: {value: DownloadURLs{}},
  250. ObfuscatedServerListRootURLs: {value: DownloadURLs{}},
  251. PsiphonAPIRequestTimeout: {value: 20 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  252. PsiphonAPIStatusRequestPeriodMin: {value: 5 * time.Minute, minimum: 1 * time.Second},
  253. PsiphonAPIStatusRequestPeriodMax: {value: 10 * time.Minute, minimum: 1 * time.Second},
  254. PsiphonAPIStatusRequestShortPeriodMin: {value: 5 * time.Second, minimum: 1 * time.Second},
  255. PsiphonAPIStatusRequestShortPeriodMax: {value: 10 * time.Second, minimum: 1 * time.Second},
  256. PsiphonAPIStatusRequestPaddingMinBytes: {value: 0, minimum: 0},
  257. PsiphonAPIStatusRequestPaddingMaxBytes: {value: 256, minimum: 0},
  258. PsiphonAPIPersistentStatsMaxCount: {value: 100, minimum: 1},
  259. PsiphonAPIConnectedRequestRetryPeriod: {value: 5 * time.Second, minimum: 1 * time.Millisecond},
  260. FetchSplitTunnelRoutesTimeout: {value: 60 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  261. SplitTunnelRoutesURLFormat: {value: ""},
  262. SplitTunnelRoutesSignaturePublicKey: {value: ""},
  263. SplitTunnelDNSServer: {value: ""},
  264. FetchUpgradeTimeout: {value: 60 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  265. FetchUpgradeRetryPeriod: {value: 30 * time.Second, minimum: 1 * time.Millisecond},
  266. FetchUpgradeStalePeriod: {value: 6 * time.Hour, minimum: 1 * time.Hour},
  267. UpgradeDownloadURLs: {value: DownloadURLs{}},
  268. UpgradeDownloadClientVersionHeader: {value: ""},
  269. ImpairedProtocolClassificationDuration: {value: 2 * time.Minute, minimum: 1 * time.Millisecond, flags: useNetworkLatencyMultiplier},
  270. ImpairedProtocolClassificationThreshold: {value: 3, minimum: 1},
  271. TotalBytesTransferredNoticePeriod: {value: 5 * time.Minute, minimum: 1 * time.Second},
  272. // The meek server times out inactive sessions after 45 seconds, so this
  273. // is a soft max for MeekMaxPollInterval, MeekRoundTripTimeout, and
  274. // MeekRoundTripRetryDeadline. MeekCookieMaxPadding cannot exceed
  275. // common.OBFUSCATE_SEED_LENGTH.
  276. MeekDialDomainsOnly: {value: false},
  277. MeekLimitBufferSizes: {value: false},
  278. MeekCookieMaxPadding: {value: 256, minimum: 0},
  279. MeekFullReceiveBufferLength: {value: 4194304, minimum: 1024},
  280. MeekReadPayloadChunkLength: {value: 65536, minimum: 1024},
  281. MeekLimitedFullReceiveBufferLength: {value: 131072, minimum: 1024},
  282. MeekLimitedReadPayloadChunkLength: {value: 4096, minimum: 1024},
  283. MeekMinPollInterval: {value: 100 * time.Millisecond, minimum: 1 * time.Millisecond},
  284. MeekMinPollIntervalJitter: {value: 0.3, minimum: 0.0},
  285. MeekMaxPollInterval: {value: 5 * time.Second, minimum: 1 * time.Millisecond},
  286. MeekMaxPollIntervalJitter: {value: 0.1, minimum: 0.0},
  287. MeekPollIntervalMultiplier: {value: 1.5, minimum: 0.0},
  288. MeekPollIntervalJitter: {value: 0.1, minimum: 0.0},
  289. MeekApplyPollIntervalMultiplierProbability: {value: 0.5},
  290. MeekRoundTripRetryDeadline: {value: 5 * time.Second, minimum: 1 * time.Millisecond, flags: useNetworkLatencyMultiplier},
  291. MeekRoundTripRetryMinDelay: {value: 50 * time.Millisecond, minimum: time.Duration(0)},
  292. MeekRoundTripRetryMaxDelay: {value: 1 * time.Second, minimum: time.Duration(0)},
  293. MeekRoundTripRetryMultiplier: {value: 2.0, minimum: 0.0},
  294. MeekRoundTripTimeout: {value: 20 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  295. TransformHostNameProbability: {value: 0.5, minimum: 0.0},
  296. PickUserAgentProbability: {value: 0.5, minimum: 0.0},
  297. }
  298. // ClientParameters is a set of client parameters. To use the parameters, call
  299. // Get. To apply new values to the parameters, call Set.
  300. type ClientParameters struct {
  301. getValueLogger func(error)
  302. snapshot atomic.Value
  303. }
  304. // ClientParametersSnapshot is an atomic snapshot of the client parameter
  305. // values. ClientParameters.Get will return a snapshot which may be used to
  306. // read multiple related values atomically and consistently while the current
  307. // snapshot in ClientParameters may change concurrently.
  308. type ClientParametersSnapshot struct {
  309. getValueLogger func(error)
  310. tag string
  311. parameters map[string]interface{}
  312. }
  313. // NewClientParameters initializes a new ClientParameters with the default
  314. // parameter values.
  315. //
  316. // getValueLogger is optional, and is used to report runtime errors with
  317. // getValue; see comment in getValue.
  318. func NewClientParameters(
  319. getValueLogger func(error)) (*ClientParameters, error) {
  320. clientParameters := &ClientParameters{
  321. getValueLogger: getValueLogger,
  322. }
  323. _, err := clientParameters.Set("", false)
  324. if err != nil {
  325. return nil, common.ContextError(err)
  326. }
  327. return clientParameters, nil
  328. }
  329. func makeDefaultParameters() (map[string]interface{}, error) {
  330. parameters := make(map[string]interface{})
  331. for name, defaults := range defaultClientParameters {
  332. if defaults.value == nil {
  333. return nil, common.ContextError(fmt.Errorf("default parameter missing value: %s", name))
  334. }
  335. if defaults.minimum != nil &&
  336. reflect.TypeOf(defaults.value) != reflect.TypeOf(defaults.minimum) {
  337. return nil, common.ContextError(fmt.Errorf("default parameter value and minimum type mismatch: %s", name))
  338. }
  339. _, isDuration := defaults.value.(time.Duration)
  340. if defaults.flags&useNetworkLatencyMultiplier != 0 && !isDuration {
  341. return nil, common.ContextError(fmt.Errorf("default non-duration parameter uses multipler: %s", name))
  342. }
  343. parameters[name] = defaults.value
  344. }
  345. return parameters, nil
  346. }
  347. // Set replaces the current parameters. First, a set of parameters are
  348. // initialized using the default values. Then, each applyParameters is applied
  349. // in turn, with the later instances having precedence.
  350. //
  351. // When skipOnError is true, unknown or invalid parameters in any
  352. // applyParameters are skipped instead of aborting with an error.
  353. //
  354. // For protocol.TunnelProtocols and protocol.TLSProfiles type values, when
  355. // skipOnError is true the values are filtered instead of validated, so
  356. // only known tunnel protocols and TLS profiles are retained.
  357. //
  358. // When an error is returned, the previous parameters remain completely
  359. // unmodified.
  360. //
  361. // For use in logging, Set returns a count of the number of parameters applied
  362. // from each applyParameters.
  363. func (p *ClientParameters) Set(
  364. tag string, skipOnError bool, applyParameters ...map[string]interface{}) ([]int, error) {
  365. var counts []int
  366. parameters, err := makeDefaultParameters()
  367. if err != nil {
  368. return nil, common.ContextError(err)
  369. }
  370. for i := 0; i < len(applyParameters); i++ {
  371. count := 0
  372. for name, value := range applyParameters[i] {
  373. existingValue, ok := parameters[name]
  374. if !ok {
  375. if skipOnError {
  376. continue
  377. }
  378. return nil, common.ContextError(fmt.Errorf("unknown parameter: %s", name))
  379. }
  380. // Accept strings such as "1h" for duration parameters.
  381. switch existingValue.(type) {
  382. case time.Duration:
  383. if s, ok := value.(string); ok {
  384. if d, err := time.ParseDuration(s); err == nil {
  385. value = d
  386. }
  387. }
  388. }
  389. // A JSON remarshal resolves cases where applyParameters is a
  390. // result of unmarshal-into-interface, in which case non-scalar
  391. // values will not have the expected types; see:
  392. // https://golang.org/pkg/encoding/json/#Unmarshal. This remarshal
  393. // also results in a deep copy.
  394. marshaledValue, err := json.Marshal(value)
  395. if err != nil {
  396. continue
  397. }
  398. newValuePtr := reflect.New(reflect.TypeOf(existingValue))
  399. err = json.Unmarshal(marshaledValue, newValuePtr.Interface())
  400. if err != nil {
  401. if skipOnError {
  402. continue
  403. }
  404. return nil, common.ContextError(fmt.Errorf("unmarshal parameter %s failed: %s", name, err))
  405. }
  406. newValue := newValuePtr.Elem().Interface()
  407. // Perform type-specific validation for some cases.
  408. // TODO: require RemoteServerListSignaturePublicKey when
  409. // RemoteServerListURLs is set?
  410. switch v := newValue.(type) {
  411. case DownloadURLs:
  412. err := v.DecodeAndValidate()
  413. if err != nil {
  414. if skipOnError {
  415. continue
  416. }
  417. return nil, common.ContextError(err)
  418. }
  419. case protocol.TunnelProtocols:
  420. if skipOnError {
  421. newValue = v.PruneInvalid()
  422. } else {
  423. err := v.Validate()
  424. if err != nil {
  425. return nil, common.ContextError(err)
  426. }
  427. }
  428. case protocol.TLSProfiles:
  429. if skipOnError {
  430. newValue = v.PruneInvalid()
  431. } else {
  432. err := v.Validate()
  433. if err != nil {
  434. return nil, common.ContextError(err)
  435. }
  436. }
  437. }
  438. // Enforce any minimums. Assumes defaultClientParameters[name]
  439. // exists.
  440. if defaultClientParameters[name].minimum != nil {
  441. valid := true
  442. switch v := newValue.(type) {
  443. case int:
  444. m, ok := defaultClientParameters[name].minimum.(int)
  445. if !ok || v < m {
  446. valid = false
  447. }
  448. case float64:
  449. m, ok := defaultClientParameters[name].minimum.(float64)
  450. if !ok || v < m {
  451. valid = false
  452. }
  453. case time.Duration:
  454. m, ok := defaultClientParameters[name].minimum.(time.Duration)
  455. if !ok || v < m {
  456. valid = false
  457. }
  458. default:
  459. if skipOnError {
  460. continue
  461. }
  462. return nil, common.ContextError(fmt.Errorf("unexpected parameter with minimum: %s", name))
  463. }
  464. if !valid {
  465. if skipOnError {
  466. continue
  467. }
  468. return nil, common.ContextError(fmt.Errorf("parameter below minimum: %s", name))
  469. }
  470. }
  471. parameters[name] = newValue
  472. count++
  473. }
  474. counts = append(counts, count)
  475. }
  476. snapshot := &ClientParametersSnapshot{
  477. getValueLogger: p.getValueLogger,
  478. tag: tag,
  479. parameters: parameters,
  480. }
  481. p.snapshot.Store(snapshot)
  482. return counts, nil
  483. }
  484. // Get returns the current parameters. Values read from the current parameters
  485. // are not deep copies and must be treated read-only.
  486. func (p *ClientParameters) Get() *ClientParametersSnapshot {
  487. return p.snapshot.Load().(*ClientParametersSnapshot)
  488. }
  489. // Tag returns the tag associated with these parameters.
  490. func (p *ClientParametersSnapshot) Tag() string {
  491. return p.tag
  492. }
  493. // getValue sets target to the value of the named parameter.
  494. //
  495. // It is an error if the name is not found, target is not a pointer, or the
  496. // type of target points to does not match the value.
  497. //
  498. // Any of these conditions would be a bug in the caller. getValue does not
  499. // panic in these cases as the client is deployed as a library in various apps
  500. // and the failure of Psiphon may not be a failure for the app process.
  501. //
  502. // Instead, errors are logged to the getValueLogger and getValue leaves the
  503. // target unset, which will result in the caller getting and using a zero
  504. // value of the requested type.
  505. func (p *ClientParametersSnapshot) getValue(name string, target interface{}) {
  506. value, ok := p.parameters[name]
  507. if !ok {
  508. if p.getValueLogger != nil {
  509. p.getValueLogger(common.ContextError(fmt.Errorf(
  510. "value %s not found", name)))
  511. }
  512. return
  513. }
  514. valueType := reflect.TypeOf(value)
  515. if reflect.PtrTo(valueType) != reflect.TypeOf(target) {
  516. if p.getValueLogger != nil {
  517. p.getValueLogger(common.ContextError(fmt.Errorf(
  518. "value %s has unexpected type %s", name, valueType.Name())))
  519. }
  520. return
  521. }
  522. // Note: there is no deep copy of parameter values; the returned value may
  523. // share memory with the original and should not be modified.
  524. targetValue := reflect.ValueOf(target)
  525. if targetValue.Kind() != reflect.Ptr {
  526. p.getValueLogger(common.ContextError(fmt.Errorf(
  527. "target for value %s is not pointer", name)))
  528. return
  529. }
  530. targetValue.Elem().Set(reflect.ValueOf(value))
  531. }
  532. // String returns a string parameter value.
  533. func (p *ClientParametersSnapshot) String(name string) string {
  534. value := ""
  535. p.getValue(name, &value)
  536. return value
  537. }
  538. // Strings returns a []string parameter value.
  539. func (p *ClientParametersSnapshot) Strings(name string) []string {
  540. value := []string{}
  541. p.getValue(name, &value)
  542. return value
  543. }
  544. // Int returns an int parameter value.
  545. func (p *ClientParametersSnapshot) Int(name string) int {
  546. value := int(0)
  547. p.getValue(name, &value)
  548. return value
  549. }
  550. // Bool returns a bool parameter value.
  551. func (p *ClientParametersSnapshot) Bool(name string) bool {
  552. value := false
  553. p.getValue(name, &value)
  554. return value
  555. }
  556. // Float returns a float64 parameter value.
  557. func (p *ClientParametersSnapshot) Float(name string) float64 {
  558. value := float64(0.0)
  559. p.getValue(name, &value)
  560. return value
  561. }
  562. // WeightedCoinFlip returns the result of common.FlipWeightedCoin using the
  563. // specified float parameter as the probability input.
  564. func (p *ClientParametersSnapshot) WeightedCoinFlip(name string) bool {
  565. var value float64
  566. p.getValue(name, &value)
  567. return common.FlipWeightedCoin(value)
  568. }
  569. // Duration returns a time.Duration parameter value. When the duration
  570. // parameter has the useNetworkLatencyMultiplier flag, the
  571. // NetworkLatencyMultiplier is applied to the returned value.
  572. func (p *ClientParametersSnapshot) Duration(name string) time.Duration {
  573. value := time.Duration(0)
  574. p.getValue(name, &value)
  575. defaultParameter, ok := defaultClientParameters[name]
  576. if value > 0 && ok && defaultParameter.flags&useNetworkLatencyMultiplier != 0 {
  577. multiplier := float64(0.0)
  578. p.getValue(NetworkLatencyMultiplier, &multiplier)
  579. if multiplier > 0.0 {
  580. value = time.Duration(float64(value) * multiplier)
  581. }
  582. }
  583. return value
  584. }
  585. // TunnelProtocols returns a protocol.TunnelProtocols parameter value.
  586. // If there is a corresponding Probability value, a weighted coin flip
  587. // will be performed and, depending on the result, the value or the
  588. // parameter default will be returned.
  589. func (p *ClientParametersSnapshot) TunnelProtocols(name string) protocol.TunnelProtocols {
  590. probabilityName := name + "Probability"
  591. _, ok := p.parameters[probabilityName]
  592. if ok {
  593. probabilityValue := float64(1.0)
  594. p.getValue(probabilityName, &probabilityValue)
  595. if !common.FlipWeightedCoin(probabilityValue) {
  596. defaultParameter, ok := defaultClientParameters[name]
  597. if ok {
  598. defaultValue, ok := defaultParameter.value.(protocol.TunnelProtocols)
  599. if ok {
  600. value := make(protocol.TunnelProtocols, len(defaultValue))
  601. copy(value, defaultValue)
  602. return value
  603. }
  604. }
  605. }
  606. }
  607. value := protocol.TunnelProtocols{}
  608. p.getValue(name, &value)
  609. return value
  610. }
  611. // TLSProfiles returns a protocol.TLSProfiles parameter value.
  612. // If there is a corresponding Probability value, a weighted coin flip
  613. // will be performed and, depending on the result, the value or the
  614. // parameter default will be returned.
  615. func (p *ClientParametersSnapshot) TLSProfiles(name string) protocol.TLSProfiles {
  616. probabilityName := name + "Probability"
  617. _, ok := p.parameters[probabilityName]
  618. if ok {
  619. probabilityValue := float64(1.0)
  620. p.getValue(probabilityName, &probabilityValue)
  621. if !common.FlipWeightedCoin(probabilityValue) {
  622. defaultParameter, ok := defaultClientParameters[name]
  623. if ok {
  624. defaultValue, ok := defaultParameter.value.(protocol.TLSProfiles)
  625. if ok {
  626. value := make(protocol.TLSProfiles, len(defaultValue))
  627. copy(value, defaultValue)
  628. return value
  629. }
  630. }
  631. }
  632. }
  633. value := protocol.TLSProfiles{}
  634. p.getValue(name, &value)
  635. return value
  636. }
  637. // DownloadURLs returns a DownloadURLs parameter value.
  638. func (p *ClientParametersSnapshot) DownloadURLs(name string) DownloadURLs {
  639. value := DownloadURLs{}
  640. p.getValue(name, &value)
  641. return value
  642. }
  643. // RateLimits returns a common.RateLimits parameter value.
  644. func (p *ClientParametersSnapshot) RateLimits(name string) common.RateLimits {
  645. value := common.RateLimits{}
  646. p.getValue(name, &value)
  647. return value
  648. }
  649. // HTTPHeaders returns an http.Header parameter value.
  650. func (p *ClientParametersSnapshot) HTTPHeaders(name string) http.Header {
  651. value := make(http.Header)
  652. p.getValue(name, &value)
  653. return value
  654. }