clientParameters.go 34 KB

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