clientParameters.go 33 KB

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