clientParameters.go 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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. "net/http"
  49. "reflect"
  50. "sync/atomic"
  51. "time"
  52. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  53. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  54. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/obfuscator"
  55. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  56. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  57. )
  58. const (
  59. NetworkLatencyMultiplier = "NetworkLatencyMultiplier"
  60. NetworkLatencyMultiplierMin = "NetworkLatencyMultiplierMin"
  61. NetworkLatencyMultiplierMax = "NetworkLatencyMultiplierMax"
  62. NetworkLatencyMultiplierLambda = "NetworkLatencyMultiplierLambda"
  63. TacticsWaitPeriod = "TacticsWaitPeriod"
  64. TacticsRetryPeriod = "TacticsRetryPeriod"
  65. TacticsRetryPeriodJitter = "TacticsRetryPeriodJitter"
  66. TacticsTimeout = "TacticsTimeout"
  67. ConnectionWorkerPoolSize = "ConnectionWorkerPoolSize"
  68. TunnelConnectTimeout = "TunnelConnectTimeout"
  69. EstablishTunnelTimeout = "EstablishTunnelTimeout"
  70. EstablishTunnelWorkTime = "EstablishTunnelWorkTime"
  71. EstablishTunnelPausePeriod = "EstablishTunnelPausePeriod"
  72. EstablishTunnelPausePeriodJitter = "EstablishTunnelPausePeriodJitter"
  73. EstablishTunnelServerAffinityGracePeriod = "EstablishTunnelServerAffinityGracePeriod"
  74. StaggerConnectionWorkersPeriod = "StaggerConnectionWorkersPeriod"
  75. StaggerConnectionWorkersJitter = "StaggerConnectionWorkersJitter"
  76. LimitIntensiveConnectionWorkers = "LimitIntensiveConnectionWorkers"
  77. IgnoreHandshakeStatsRegexps = "IgnoreHandshakeStatsRegexps"
  78. PrioritizeTunnelProtocolsProbability = "PrioritizeTunnelProtocolsProbability"
  79. PrioritizeTunnelProtocols = "PrioritizeTunnelProtocols"
  80. PrioritizeTunnelProtocolsCandidateCount = "PrioritizeTunnelProtocolsCandidateCount"
  81. InitialLimitTunnelProtocolsProbability = "InitialLimitTunnelProtocolsProbability"
  82. InitialLimitTunnelProtocols = "InitialLimitTunnelProtocols"
  83. InitialLimitTunnelProtocolsCandidateCount = "InitialLimitTunnelProtocolsCandidateCount"
  84. LimitTunnelProtocolsProbability = "LimitTunnelProtocolsProbability"
  85. LimitTunnelProtocols = "LimitTunnelProtocols"
  86. LimitTLSProfilesProbability = "LimitTLSProfilesProbability"
  87. LimitTLSProfiles = "LimitTLSProfiles"
  88. UseOnlyCustomTLSProfiles = "UseOnlyCustomTLSProfiles"
  89. CustomTLSProfiles = "CustomTLSProfiles"
  90. SelectRandomizedTLSProfileProbability = "SelectRandomizedTLSProfileProbability"
  91. NoDefaultTLSSessionIDProbability = "NoDefaultTLSSessionIDProbability"
  92. LimitQUICVersionsProbability = "LimitQUICVersionsProbability"
  93. LimitQUICVersions = "LimitQUICVersions"
  94. FragmentorProbability = "FragmentorProbability"
  95. FragmentorLimitProtocols = "FragmentorLimitProtocols"
  96. FragmentorMinTotalBytes = "FragmentorMinTotalBytes"
  97. FragmentorMaxTotalBytes = "FragmentorMaxTotalBytes"
  98. FragmentorMinWriteBytes = "FragmentorMinWriteBytes"
  99. FragmentorMaxWriteBytes = "FragmentorMaxWriteBytes"
  100. FragmentorMinDelay = "FragmentorMinDelay"
  101. FragmentorMaxDelay = "FragmentorMaxDelay"
  102. FragmentorDownstreamProbability = "FragmentorDownstreamProbability"
  103. FragmentorDownstreamLimitProtocols = "FragmentorDownstreamLimitProtocols"
  104. FragmentorDownstreamMinTotalBytes = "FragmentorDownstreamMinTotalBytes"
  105. FragmentorDownstreamMaxTotalBytes = "FragmentorDownstreamMaxTotalBytes"
  106. FragmentorDownstreamMinWriteBytes = "FragmentorDownstreamMinWriteBytes"
  107. FragmentorDownstreamMaxWriteBytes = "FragmentorDownstreamMaxWriteBytes"
  108. FragmentorDownstreamMinDelay = "FragmentorDownstreamMinDelay"
  109. FragmentorDownstreamMaxDelay = "FragmentorDownstreamMaxDelay"
  110. ObfuscatedSSHMinPadding = "ObfuscatedSSHMinPadding"
  111. ObfuscatedSSHMaxPadding = "ObfuscatedSSHMaxPadding"
  112. TunnelOperateShutdownTimeout = "TunnelOperateShutdownTimeout"
  113. TunnelPortForwardDialTimeout = "TunnelPortForwardDialTimeout"
  114. TunnelRateLimits = "TunnelRateLimits"
  115. AdditionalCustomHeaders = "AdditionalCustomHeaders"
  116. SpeedTestPaddingMinBytes = "SpeedTestPaddingMinBytes"
  117. SpeedTestPaddingMaxBytes = "SpeedTestPaddingMaxBytes"
  118. SpeedTestMaxSampleCount = "SpeedTestMaxSampleCount"
  119. SSHKeepAliveSpeedTestSampleProbability = "SSHKeepAliveSpeedTestSampleProbability"
  120. SSHKeepAlivePaddingMinBytes = "SSHKeepAlivePaddingMinBytes"
  121. SSHKeepAlivePaddingMaxBytes = "SSHKeepAlivePaddingMaxBytes"
  122. SSHKeepAlivePeriodMin = "SSHKeepAlivePeriodMin"
  123. SSHKeepAlivePeriodMax = "SSHKeepAlivePeriodMax"
  124. SSHKeepAlivePeriodicTimeout = "SSHKeepAlivePeriodicTimeout"
  125. SSHKeepAlivePeriodicInactivePeriod = "SSHKeepAlivePeriodicInactivePeriod"
  126. SSHKeepAliveProbeTimeout = "SSHKeepAliveProbeTimeout"
  127. SSHKeepAliveProbeInactivePeriod = "SSHKeepAliveProbeInactivePeriod"
  128. HTTPProxyOriginServerTimeout = "HTTPProxyOriginServerTimeout"
  129. HTTPProxyMaxIdleConnectionsPerHost = "HTTPProxyMaxIdleConnectionsPerHost"
  130. FetchRemoteServerListTimeout = "FetchRemoteServerListTimeout"
  131. FetchRemoteServerListRetryPeriod = "FetchRemoteServerListRetryPeriod"
  132. FetchRemoteServerListStalePeriod = "FetchRemoteServerListStalePeriod"
  133. RemoteServerListSignaturePublicKey = "RemoteServerListSignaturePublicKey"
  134. RemoteServerListURLs = "RemoteServerListURLs"
  135. ObfuscatedServerListRootURLs = "ObfuscatedServerListRootURLs"
  136. PsiphonAPIRequestTimeout = "PsiphonAPIRequestTimeout"
  137. PsiphonAPIStatusRequestPeriodMin = "PsiphonAPIStatusRequestPeriodMin"
  138. PsiphonAPIStatusRequestPeriodMax = "PsiphonAPIStatusRequestPeriodMax"
  139. PsiphonAPIStatusRequestShortPeriodMin = "PsiphonAPIStatusRequestShortPeriodMin"
  140. PsiphonAPIStatusRequestShortPeriodMax = "PsiphonAPIStatusRequestShortPeriodMax"
  141. PsiphonAPIStatusRequestPaddingMinBytes = "PsiphonAPIStatusRequestPaddingMinBytes"
  142. PsiphonAPIStatusRequestPaddingMaxBytes = "PsiphonAPIStatusRequestPaddingMaxBytes"
  143. PsiphonAPIPersistentStatsMaxCount = "PsiphonAPIPersistentStatsMaxCount"
  144. PsiphonAPIConnectedRequestPeriod = "PsiphonAPIConnectedRequestPeriod"
  145. PsiphonAPIConnectedRequestRetryPeriod = "PsiphonAPIConnectedRequestRetryPeriod"
  146. FetchSplitTunnelRoutesTimeout = "FetchSplitTunnelRoutesTimeout"
  147. SplitTunnelRoutesURLFormat = "SplitTunnelRoutesURLFormat"
  148. SplitTunnelRoutesSignaturePublicKey = "SplitTunnelRoutesSignaturePublicKey"
  149. SplitTunnelDNSServer = "SplitTunnelDNSServer"
  150. FetchUpgradeTimeout = "FetchUpgradeTimeout"
  151. FetchUpgradeRetryPeriod = "FetchUpgradeRetryPeriod"
  152. FetchUpgradeStalePeriod = "FetchUpgradeStalePeriod"
  153. UpgradeDownloadURLs = "UpgradeDownloadURLs"
  154. UpgradeDownloadClientVersionHeader = "UpgradeDownloadClientVersionHeader"
  155. TotalBytesTransferredNoticePeriod = "TotalBytesTransferredNoticePeriod"
  156. MeekDialDomainsOnly = "MeekDialDomainsOnly"
  157. MeekLimitBufferSizes = "MeekLimitBufferSizes"
  158. MeekCookieMaxPadding = "MeekCookieMaxPadding"
  159. MeekFullReceiveBufferLength = "MeekFullReceiveBufferLength"
  160. MeekReadPayloadChunkLength = "MeekReadPayloadChunkLength"
  161. MeekLimitedFullReceiveBufferLength = "MeekLimitedFullReceiveBufferLength"
  162. MeekLimitedReadPayloadChunkLength = "MeekLimitedReadPayloadChunkLength"
  163. MeekMinPollInterval = "MeekMinPollInterval"
  164. MeekMinPollIntervalJitter = "MeekMinPollIntervalJitter"
  165. MeekMaxPollInterval = "MeekMaxPollInterval"
  166. MeekMaxPollIntervalJitter = "MeekMaxPollIntervalJitter"
  167. MeekPollIntervalMultiplier = "MeekPollIntervalMultiplier"
  168. MeekPollIntervalJitter = "MeekPollIntervalJitter"
  169. MeekApplyPollIntervalMultiplierProbability = "MeekApplyPollIntervalMultiplierProbability"
  170. MeekRoundTripRetryDeadline = "MeekRoundTripRetryDeadline"
  171. MeekRoundTripRetryMinDelay = "MeekRoundTripRetryMinDelay"
  172. MeekRoundTripRetryMaxDelay = "MeekRoundTripRetryMaxDelay"
  173. MeekRoundTripRetryMultiplier = "MeekRoundTripRetryMultiplier"
  174. MeekRoundTripTimeout = "MeekRoundTripTimeout"
  175. MeekTrafficShapingProbability = "MeekTrafficShapingProbability"
  176. MeekTrafficShapingLimitProtocols = "MeekTrafficShapingLimitProtocols"
  177. MeekMinLimitRequestPayloadLength = "MeekMinLimitRequestPayloadLength"
  178. MeekMaxLimitRequestPayloadLength = "MeekMaxLimitRequestPayloadLength"
  179. MeekRedialTLSProbability = "MeekRedialTLSProbability"
  180. TransformHostNameProbability = "TransformHostNameProbability"
  181. PickUserAgentProbability = "PickUserAgentProbability"
  182. LivenessTestMinUpstreamBytes = "LivenessTestMinUpstreamBytes"
  183. LivenessTestMaxUpstreamBytes = "LivenessTestMaxUpstreamBytes"
  184. LivenessTestMinDownstreamBytes = "LivenessTestMinDownstreamBytes"
  185. LivenessTestMaxDownstreamBytes = "LivenessTestMaxDownstreamBytes"
  186. ReplayCandidateCount = "ReplayCandidateCount"
  187. ReplayDialParametersTTL = "ReplayDialParametersTTL"
  188. ReplayTargetUpstreamBytes = "ReplayTargetUpstreamBytes"
  189. ReplayTargetDownstreamBytes = "ReplayTargetDownstreamBytes"
  190. ReplayTargetTunnelDuration = "ReplayTargetTunnelDuration"
  191. ReplaySSH = "ReplaySSH"
  192. ReplayObfuscatorPadding = "ReplayObfuscatorPadding"
  193. ReplayFragmentor = "ReplayFragmentor"
  194. ReplayTLSProfile = "ReplayTLSProfile"
  195. ReplayRandomizedTLSProfile = "ReplayRandomizedTLSProfile"
  196. ReplayFronting = "ReplayFronting"
  197. ReplayHostname = "ReplayHostname"
  198. ReplayQUICVersion = "ReplayQUICVersion"
  199. ReplayObfuscatedQUIC = "ReplayObfuscatedQUIC"
  200. ReplayLivenessTest = "ReplayLivenessTest"
  201. ReplayUserAgent = "ReplayUserAgent"
  202. ReplayAPIRequestPadding = "ReplayAPIRequestPadding"
  203. ReplayLaterRoundMoveToFrontProbability = "ReplayLaterRoundMoveToFrontProbability"
  204. ReplayRetainFailedProbability = "ReplayRetainFailedProbability"
  205. APIRequestUpstreamPaddingMinBytes = "APIRequestUpstreamPaddingMinBytes"
  206. APIRequestUpstreamPaddingMaxBytes = "APIRequestUpstreamPaddingMaxBytes"
  207. APIRequestDownstreamPaddingMinBytes = "APIRequestDownstreamPaddingMinBytes"
  208. APIRequestDownstreamPaddingMaxBytes = "APIRequestDownstreamPaddingMaxBytes"
  209. PersistentStatsMaxStoreRecords = "PersistentStatsMaxStoreRecords"
  210. PersistentStatsMaxSendBytes = "PersistentStatsMaxSendBytes"
  211. RecordRemoteServerListPersistentStatsProbability = "RecordRemoteServerListPersistentStatsProbability"
  212. RecordFailedTunnelPersistentStatsProbability = "RecordFailedTunnelPersistentStatsProbability"
  213. ServerEntryMinimumAgeForPruning = "ServerEntryMinimumAgeForPruning"
  214. ApplicationParametersProbability = "ApplicationParametersProbability"
  215. ApplicationParameters = "ApplicationParameters"
  216. )
  217. const (
  218. useNetworkLatencyMultiplier = 1
  219. serverSideOnly = 2
  220. )
  221. // defaultClientParameters specifies the type, default value, and minimum
  222. // value for all dynamically configurable client parameters.
  223. //
  224. // Do not change the names or types of existing values, as that can break
  225. // client logic or cause parameters to not be applied.
  226. //
  227. // Minimum values are a fail-safe for cases where lower values would break the
  228. // client logic. For example, setting a ConnectionWorkerPoolSize of 0 would
  229. // make the client never connect.
  230. var defaultClientParameters = map[string]struct {
  231. value interface{}
  232. minimum interface{}
  233. flags int32
  234. }{
  235. // NetworkLatencyMultiplier defaults to 0, meaning off. But when set, it
  236. // must be a multiplier >= 1.
  237. NetworkLatencyMultiplier: {value: 0.0, minimum: 1.0},
  238. NetworkLatencyMultiplierMin: {value: 1.0, minimum: 1.0},
  239. NetworkLatencyMultiplierMax: {value: 3.0, minimum: 1.0},
  240. NetworkLatencyMultiplierLambda: {value: 2.0, minimum: 0.001},
  241. TacticsWaitPeriod: {value: 10 * time.Second, minimum: 0 * time.Second, flags: useNetworkLatencyMultiplier},
  242. TacticsRetryPeriod: {value: 5 * time.Second, minimum: 1 * time.Millisecond},
  243. TacticsRetryPeriodJitter: {value: 0.3, minimum: 0.0},
  244. TacticsTimeout: {value: 2 * time.Minute, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  245. ConnectionWorkerPoolSize: {value: 10, minimum: 1},
  246. TunnelConnectTimeout: {value: 20 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  247. EstablishTunnelTimeout: {value: 300 * time.Second, minimum: time.Duration(0)},
  248. EstablishTunnelWorkTime: {value: 60 * time.Second, minimum: 1 * time.Second},
  249. EstablishTunnelPausePeriod: {value: 5 * time.Second, minimum: 1 * time.Millisecond},
  250. EstablishTunnelPausePeriodJitter: {value: 0.1, minimum: 0.0},
  251. EstablishTunnelServerAffinityGracePeriod: {value: 1 * time.Second, minimum: time.Duration(0), flags: useNetworkLatencyMultiplier},
  252. StaggerConnectionWorkersPeriod: {value: time.Duration(0), minimum: time.Duration(0)},
  253. StaggerConnectionWorkersJitter: {value: 0.1, minimum: 0.0},
  254. LimitIntensiveConnectionWorkers: {value: 0, minimum: 0},
  255. IgnoreHandshakeStatsRegexps: {value: false},
  256. TunnelOperateShutdownTimeout: {value: 1 * time.Second, minimum: 1 * time.Millisecond, flags: useNetworkLatencyMultiplier},
  257. TunnelPortForwardDialTimeout: {value: 10 * time.Second, minimum: 1 * time.Millisecond, flags: useNetworkLatencyMultiplier},
  258. TunnelRateLimits: {value: common.RateLimits{}},
  259. // PrioritizeTunnelProtocols parameters are obsoleted by InitialLimitTunnelProtocols.
  260. // TODO: remove once no longer required for older clients.
  261. PrioritizeTunnelProtocolsProbability: {value: 1.0, minimum: 0.0},
  262. PrioritizeTunnelProtocols: {value: protocol.TunnelProtocols{}},
  263. PrioritizeTunnelProtocolsCandidateCount: {value: 10, minimum: 0},
  264. InitialLimitTunnelProtocolsProbability: {value: 1.0, minimum: 0.0},
  265. InitialLimitTunnelProtocols: {value: protocol.TunnelProtocols{}},
  266. InitialLimitTunnelProtocolsCandidateCount: {value: 0, minimum: 0},
  267. LimitTunnelProtocolsProbability: {value: 1.0, minimum: 0.0},
  268. LimitTunnelProtocols: {value: protocol.TunnelProtocols{}},
  269. LimitTLSProfilesProbability: {value: 1.0, minimum: 0.0},
  270. LimitTLSProfiles: {value: protocol.TLSProfiles{}},
  271. UseOnlyCustomTLSProfiles: {value: false},
  272. CustomTLSProfiles: {value: protocol.CustomTLSProfiles{}},
  273. SelectRandomizedTLSProfileProbability: {value: 0.25, minimum: 0.0},
  274. NoDefaultTLSSessionIDProbability: {value: 0.5, minimum: 0.0},
  275. LimitQUICVersionsProbability: {value: 1.0, minimum: 0.0},
  276. LimitQUICVersions: {value: protocol.QUICVersions{}},
  277. FragmentorProbability: {value: 0.5, minimum: 0.0},
  278. FragmentorLimitProtocols: {value: protocol.TunnelProtocols{}},
  279. FragmentorMinTotalBytes: {value: 0, minimum: 0},
  280. FragmentorMaxTotalBytes: {value: 0, minimum: 0},
  281. FragmentorMinWriteBytes: {value: 1, minimum: 1},
  282. FragmentorMaxWriteBytes: {value: 1500, minimum: 1},
  283. FragmentorMinDelay: {value: time.Duration(0), minimum: time.Duration(0)},
  284. FragmentorMaxDelay: {value: 10 * time.Millisecond, minimum: time.Duration(0)},
  285. FragmentorDownstreamProbability: {value: 0.5, minimum: 0.0, flags: serverSideOnly},
  286. FragmentorDownstreamLimitProtocols: {value: protocol.TunnelProtocols{}, flags: serverSideOnly},
  287. FragmentorDownstreamMinTotalBytes: {value: 0, minimum: 0, flags: serverSideOnly},
  288. FragmentorDownstreamMaxTotalBytes: {value: 0, minimum: 0, flags: serverSideOnly},
  289. FragmentorDownstreamMinWriteBytes: {value: 1, minimum: 1, flags: serverSideOnly},
  290. FragmentorDownstreamMaxWriteBytes: {value: 1500, minimum: 1, flags: serverSideOnly},
  291. FragmentorDownstreamMinDelay: {value: time.Duration(0), minimum: time.Duration(0), flags: serverSideOnly},
  292. FragmentorDownstreamMaxDelay: {value: 10 * time.Millisecond, minimum: time.Duration(0), flags: serverSideOnly},
  293. // The Psiphon server will reject obfuscated SSH seed messages with
  294. // padding greater than OBFUSCATE_MAX_PADDING.
  295. // obfuscator.NewClientObfuscator will ignore invalid min/max padding
  296. // configurations.
  297. ObfuscatedSSHMinPadding: {value: 0, minimum: 0},
  298. ObfuscatedSSHMaxPadding: {value: obfuscator.OBFUSCATE_MAX_PADDING, minimum: 0},
  299. AdditionalCustomHeaders: {value: make(http.Header)},
  300. // Speed test and SSH keep alive padding is intended to frustrate
  301. // fingerprinting and should not exceed ~1 IP packet size.
  302. //
  303. // Currently, each serialized speed test sample, populated with real
  304. // values, is approximately 100 bytes. All SpeedTestMaxSampleCount samples
  305. // are loaded into memory are sent as API inputs.
  306. SpeedTestPaddingMinBytes: {value: 0, minimum: 0},
  307. SpeedTestPaddingMaxBytes: {value: 256, minimum: 0},
  308. SpeedTestMaxSampleCount: {value: 25, minimum: 1},
  309. // The Psiphon server times out inactive tunnels after 5 minutes, so this
  310. // is a soft max for SSHKeepAlivePeriodMax.
  311. SSHKeepAliveSpeedTestSampleProbability: {value: 0.5, minimum: 0.0},
  312. SSHKeepAlivePaddingMinBytes: {value: 0, minimum: 0},
  313. SSHKeepAlivePaddingMaxBytes: {value: 256, minimum: 0},
  314. SSHKeepAlivePeriodMin: {value: 1 * time.Minute, minimum: 1 * time.Second},
  315. SSHKeepAlivePeriodMax: {value: 2 * time.Minute, minimum: 1 * time.Second},
  316. SSHKeepAlivePeriodicTimeout: {value: 30 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  317. SSHKeepAlivePeriodicInactivePeriod: {value: 10 * time.Second, minimum: 1 * time.Second},
  318. SSHKeepAliveProbeTimeout: {value: 5 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  319. SSHKeepAliveProbeInactivePeriod: {value: 10 * time.Second, minimum: 1 * time.Second},
  320. HTTPProxyOriginServerTimeout: {value: 15 * time.Second, minimum: time.Duration(0), flags: useNetworkLatencyMultiplier},
  321. HTTPProxyMaxIdleConnectionsPerHost: {value: 50, minimum: 0},
  322. FetchRemoteServerListTimeout: {value: 30 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  323. FetchRemoteServerListRetryPeriod: {value: 30 * time.Second, minimum: 1 * time.Millisecond},
  324. FetchRemoteServerListStalePeriod: {value: 6 * time.Hour, minimum: 1 * time.Hour},
  325. RemoteServerListSignaturePublicKey: {value: ""},
  326. RemoteServerListURLs: {value: DownloadURLs{}},
  327. ObfuscatedServerListRootURLs: {value: DownloadURLs{}},
  328. PsiphonAPIRequestTimeout: {value: 20 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  329. PsiphonAPIStatusRequestPeriodMin: {value: 5 * time.Minute, minimum: 1 * time.Second},
  330. PsiphonAPIStatusRequestPeriodMax: {value: 10 * time.Minute, minimum: 1 * time.Second},
  331. PsiphonAPIStatusRequestShortPeriodMin: {value: 5 * time.Second, minimum: 1 * time.Second},
  332. PsiphonAPIStatusRequestShortPeriodMax: {value: 10 * time.Second, minimum: 1 * time.Second},
  333. // PsiphonAPIPersistentStatsMaxCount parameter is obsoleted by PersistentStatsMaxSendBytes.
  334. // TODO: remove once no longer required for older clients.
  335. PsiphonAPIPersistentStatsMaxCount: {value: 100, minimum: 1},
  336. // PsiphonAPIStatusRequestPadding parameters are obsoleted by APIRequestUp/DownstreamPadding.
  337. // TODO: remove once no longer required for older clients.
  338. PsiphonAPIStatusRequestPaddingMinBytes: {value: 0, minimum: 0},
  339. PsiphonAPIStatusRequestPaddingMaxBytes: {value: 256, minimum: 0},
  340. PsiphonAPIConnectedRequestRetryPeriod: {value: 5 * time.Second, minimum: 1 * time.Millisecond},
  341. FetchSplitTunnelRoutesTimeout: {value: 60 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  342. SplitTunnelRoutesURLFormat: {value: ""},
  343. SplitTunnelRoutesSignaturePublicKey: {value: ""},
  344. SplitTunnelDNSServer: {value: ""},
  345. FetchUpgradeTimeout: {value: 60 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  346. FetchUpgradeRetryPeriod: {value: 30 * time.Second, minimum: 1 * time.Millisecond},
  347. FetchUpgradeStalePeriod: {value: 6 * time.Hour, minimum: 1 * time.Hour},
  348. UpgradeDownloadURLs: {value: DownloadURLs{}},
  349. UpgradeDownloadClientVersionHeader: {value: ""},
  350. TotalBytesTransferredNoticePeriod: {value: 5 * time.Minute, minimum: 1 * time.Second},
  351. // The meek server times out inactive sessions after 45 seconds, so this
  352. // is a soft max for MeekMaxPollInterval, MeekRoundTripTimeout, and
  353. // MeekRoundTripRetryDeadline.
  354. //
  355. // MeekCookieMaxPadding cannot exceed common.OBFUSCATE_SEED_LENGTH.
  356. //
  357. // MeekMinLimitRequestPayloadLength/MeekMaxLimitRequestPayloadLength
  358. // cannot exceed server.MEEK_MAX_REQUEST_PAYLOAD_LENGTH.
  359. MeekDialDomainsOnly: {value: false},
  360. MeekLimitBufferSizes: {value: false},
  361. MeekCookieMaxPadding: {value: 256, minimum: 0},
  362. MeekFullReceiveBufferLength: {value: 4194304, minimum: 1024},
  363. MeekReadPayloadChunkLength: {value: 65536, minimum: 1024},
  364. MeekLimitedFullReceiveBufferLength: {value: 131072, minimum: 1024},
  365. MeekLimitedReadPayloadChunkLength: {value: 4096, minimum: 1024},
  366. MeekMinPollInterval: {value: 100 * time.Millisecond, minimum: 1 * time.Millisecond},
  367. MeekMinPollIntervalJitter: {value: 0.3, minimum: 0.0},
  368. MeekMaxPollInterval: {value: 5 * time.Second, minimum: 1 * time.Millisecond},
  369. MeekMaxPollIntervalJitter: {value: 0.1, minimum: 0.0},
  370. MeekPollIntervalMultiplier: {value: 1.5, minimum: 0.0},
  371. MeekPollIntervalJitter: {value: 0.1, minimum: 0.0},
  372. MeekApplyPollIntervalMultiplierProbability: {value: 0.5},
  373. MeekRoundTripRetryDeadline: {value: 5 * time.Second, minimum: 1 * time.Millisecond, flags: useNetworkLatencyMultiplier},
  374. MeekRoundTripRetryMinDelay: {value: 50 * time.Millisecond, minimum: time.Duration(0)},
  375. MeekRoundTripRetryMaxDelay: {value: 1 * time.Second, minimum: time.Duration(0)},
  376. MeekRoundTripRetryMultiplier: {value: 2.0, minimum: 0.0},
  377. MeekRoundTripTimeout: {value: 20 * time.Second, minimum: 1 * time.Second, flags: useNetworkLatencyMultiplier},
  378. MeekTrafficShapingProbability: {value: 1.0, minimum: 0.0},
  379. MeekTrafficShapingLimitProtocols: {value: protocol.TunnelProtocols{}},
  380. MeekMinLimitRequestPayloadLength: {value: 65536, minimum: 1},
  381. MeekMaxLimitRequestPayloadLength: {value: 65536, minimum: 1},
  382. MeekRedialTLSProbability: {value: 0.0, minimum: 0.0},
  383. TransformHostNameProbability: {value: 0.5, minimum: 0.0},
  384. PickUserAgentProbability: {value: 0.5, minimum: 0.0},
  385. LivenessTestMinUpstreamBytes: {value: 0, minimum: 0},
  386. LivenessTestMaxUpstreamBytes: {value: 0, minimum: 0},
  387. LivenessTestMinDownstreamBytes: {value: 0, minimum: 0},
  388. LivenessTestMaxDownstreamBytes: {value: 0, minimum: 0},
  389. ReplayCandidateCount: {value: 10, minimum: -1},
  390. ReplayDialParametersTTL: {value: 24 * time.Hour, minimum: time.Duration(0)},
  391. ReplayTargetUpstreamBytes: {value: 0, minimum: 0},
  392. ReplayTargetDownstreamBytes: {value: 0, minimum: 0},
  393. ReplayTargetTunnelDuration: {value: 1 * time.Second, minimum: time.Duration(0)},
  394. ReplaySSH: {value: true},
  395. ReplayObfuscatorPadding: {value: true},
  396. ReplayFragmentor: {value: true},
  397. ReplayTLSProfile: {value: true},
  398. ReplayRandomizedTLSProfile: {value: true},
  399. ReplayFronting: {value: true},
  400. ReplayHostname: {value: true},
  401. ReplayQUICVersion: {value: true},
  402. ReplayObfuscatedQUIC: {value: true},
  403. ReplayLivenessTest: {value: true},
  404. ReplayUserAgent: {value: true},
  405. ReplayAPIRequestPadding: {value: true},
  406. ReplayLaterRoundMoveToFrontProbability: {value: 0.0, minimum: 0.0},
  407. ReplayRetainFailedProbability: {value: 0.5, minimum: 0.0},
  408. APIRequestUpstreamPaddingMinBytes: {value: 0, minimum: 0},
  409. APIRequestUpstreamPaddingMaxBytes: {value: 1024, minimum: 0},
  410. APIRequestDownstreamPaddingMinBytes: {value: 0, minimum: 0},
  411. APIRequestDownstreamPaddingMaxBytes: {value: 1024, minimum: 0},
  412. PersistentStatsMaxStoreRecords: {value: 200, minimum: 1},
  413. PersistentStatsMaxSendBytes: {value: 65536, minimum: 1},
  414. RecordRemoteServerListPersistentStatsProbability: {value: 1.0, minimum: 0.0},
  415. RecordFailedTunnelPersistentStatsProbability: {value: 0.0, minimum: 0.0},
  416. ServerEntryMinimumAgeForPruning: {value: 7 * 24 * time.Hour, minimum: 24 * time.Hour},
  417. ApplicationParametersProbability: {value: 1.0, minimum: 0.0},
  418. ApplicationParameters: {value: KeyValues{}},
  419. }
  420. // IsServerSideOnly indicates if the parameter specified by name is used
  421. // server-side only.
  422. func IsServerSideOnly(name string) bool {
  423. defaultParameter, ok := defaultClientParameters[name]
  424. return ok && (defaultParameter.flags&serverSideOnly) != 0
  425. }
  426. // ClientParameters is a set of client parameters. To use the parameters, call
  427. // Get. To apply new values to the parameters, call Set.
  428. type ClientParameters struct {
  429. getValueLogger func(error)
  430. snapshot atomic.Value
  431. }
  432. // NewClientParameters initializes a new ClientParameters with the default
  433. // parameter values.
  434. //
  435. // getValueLogger is optional, and is used to report runtime errors with
  436. // getValue; see comment in getValue.
  437. func NewClientParameters(
  438. getValueLogger func(error)) (*ClientParameters, error) {
  439. clientParameters := &ClientParameters{
  440. getValueLogger: getValueLogger,
  441. }
  442. _, err := clientParameters.Set("", false)
  443. if err != nil {
  444. return nil, errors.Trace(err)
  445. }
  446. return clientParameters, nil
  447. }
  448. func makeDefaultParameters() (map[string]interface{}, error) {
  449. parameters := make(map[string]interface{})
  450. for name, defaults := range defaultClientParameters {
  451. if defaults.value == nil {
  452. return nil, errors.Tracef("default parameter missing value: %s", name)
  453. }
  454. if defaults.minimum != nil &&
  455. reflect.TypeOf(defaults.value) != reflect.TypeOf(defaults.minimum) {
  456. return nil, errors.Tracef("default parameter value and minimum type mismatch: %s", name)
  457. }
  458. _, isDuration := defaults.value.(time.Duration)
  459. if defaults.flags&useNetworkLatencyMultiplier != 0 && !isDuration {
  460. return nil, errors.Tracef("default non-duration parameter uses multipler: %s", name)
  461. }
  462. parameters[name] = defaults.value
  463. }
  464. return parameters, nil
  465. }
  466. // Set replaces the current parameters. First, a set of parameters are
  467. // initialized using the default values. Then, each applyParameters is applied
  468. // in turn, with the later instances having precedence.
  469. //
  470. // When skipOnError is true, unknown or invalid parameters in any
  471. // applyParameters are skipped instead of aborting with an error.
  472. //
  473. // For protocol.TunnelProtocols and protocol.TLSProfiles type values, when
  474. // skipOnError is true the values are filtered instead of validated, so
  475. // only known tunnel protocols and TLS profiles are retained.
  476. //
  477. // When an error is returned, the previous parameters remain completely
  478. // unmodified.
  479. //
  480. // For use in logging, Set returns a count of the number of parameters applied
  481. // from each applyParameters.
  482. func (p *ClientParameters) Set(
  483. tag string, skipOnError bool, applyParameters ...map[string]interface{}) ([]int, error) {
  484. var counts []int
  485. parameters, err := makeDefaultParameters()
  486. if err != nil {
  487. return nil, errors.Trace(err)
  488. }
  489. for i := 0; i < len(applyParameters); i++ {
  490. count := 0
  491. for name, value := range applyParameters[i] {
  492. existingValue, ok := parameters[name]
  493. if !ok {
  494. if skipOnError {
  495. continue
  496. }
  497. return nil, errors.Tracef("unknown parameter: %s", name)
  498. }
  499. // Accept strings such as "1h" for duration parameters.
  500. switch existingValue.(type) {
  501. case time.Duration:
  502. if s, ok := value.(string); ok {
  503. if d, err := time.ParseDuration(s); err == nil {
  504. value = d
  505. }
  506. }
  507. }
  508. // A JSON remarshal resolves cases where applyParameters is a
  509. // result of unmarshal-into-interface, in which case non-scalar
  510. // values will not have the expected types; see:
  511. // https://golang.org/pkg/encoding/json/#Unmarshal. This remarshal
  512. // also results in a deep copy.
  513. marshaledValue, err := json.Marshal(value)
  514. if err != nil {
  515. continue
  516. }
  517. newValuePtr := reflect.New(reflect.TypeOf(existingValue))
  518. err = json.Unmarshal(marshaledValue, newValuePtr.Interface())
  519. if err != nil {
  520. if skipOnError {
  521. continue
  522. }
  523. return nil, errors.Tracef("unmarshal parameter %s failed: %s", name, err)
  524. }
  525. newValue := newValuePtr.Elem().Interface()
  526. // Perform type-specific validation for some cases.
  527. // TODO: require RemoteServerListSignaturePublicKey when
  528. // RemoteServerListURLs is set?
  529. switch v := newValue.(type) {
  530. case DownloadURLs:
  531. err := v.DecodeAndValidate()
  532. if err != nil {
  533. if skipOnError {
  534. continue
  535. }
  536. return nil, errors.Trace(err)
  537. }
  538. case protocol.TunnelProtocols:
  539. if skipOnError {
  540. newValue = v.PruneInvalid()
  541. } else {
  542. err := v.Validate()
  543. if err != nil {
  544. return nil, errors.Trace(err)
  545. }
  546. }
  547. case protocol.TLSProfiles:
  548. if skipOnError {
  549. newValue = v.PruneInvalid()
  550. } else {
  551. err := v.Validate()
  552. if err != nil {
  553. return nil, errors.Trace(err)
  554. }
  555. }
  556. case protocol.QUICVersions:
  557. if skipOnError {
  558. newValue = v.PruneInvalid()
  559. } else {
  560. err := v.Validate()
  561. if err != nil {
  562. return nil, errors.Trace(err)
  563. }
  564. }
  565. case protocol.CustomTLSProfiles:
  566. err := v.Validate()
  567. if err != nil {
  568. if skipOnError {
  569. continue
  570. }
  571. return nil, errors.Trace(err)
  572. }
  573. case KeyValues:
  574. err := v.Validate()
  575. if err != nil {
  576. if skipOnError {
  577. continue
  578. }
  579. return nil, errors.Trace(err)
  580. }
  581. }
  582. // Enforce any minimums. Assumes defaultClientParameters[name]
  583. // exists.
  584. if defaultClientParameters[name].minimum != nil {
  585. valid := true
  586. switch v := newValue.(type) {
  587. case int:
  588. m, ok := defaultClientParameters[name].minimum.(int)
  589. if !ok || v < m {
  590. valid = false
  591. }
  592. case float64:
  593. m, ok := defaultClientParameters[name].minimum.(float64)
  594. if !ok || v < m {
  595. valid = false
  596. }
  597. case time.Duration:
  598. m, ok := defaultClientParameters[name].minimum.(time.Duration)
  599. if !ok || v < m {
  600. valid = false
  601. }
  602. default:
  603. if skipOnError {
  604. continue
  605. }
  606. return nil, errors.Tracef("unexpected parameter with minimum: %s", name)
  607. }
  608. if !valid {
  609. if skipOnError {
  610. continue
  611. }
  612. return nil, errors.Tracef("parameter below minimum: %s", name)
  613. }
  614. }
  615. parameters[name] = newValue
  616. count++
  617. }
  618. counts = append(counts, count)
  619. }
  620. snapshot := &clientParametersSnapshot{
  621. getValueLogger: p.getValueLogger,
  622. tag: tag,
  623. parameters: parameters,
  624. }
  625. p.snapshot.Store(snapshot)
  626. return counts, nil
  627. }
  628. // Get returns the current parameters.
  629. //
  630. // Values read from the current parameters are not deep copies and must be
  631. // treated read-only.
  632. //
  633. // The returned ClientParametersAccessor may be used to read multiple related
  634. // values atomically and consistently while the current set of values in
  635. // ClientParameters may change concurrently.
  636. //
  637. // Get does not perform any heap allocations and is intended for repeated,
  638. // direct, low-overhead invocations.
  639. func (p *ClientParameters) Get() ClientParametersAccessor {
  640. return ClientParametersAccessor{
  641. snapshot: p.snapshot.Load().(*clientParametersSnapshot)}
  642. }
  643. // GetCustom returns the current parameters while also setting customizations
  644. // for this instance.
  645. //
  646. // The properties of Get also apply to GetCustom: must be read-only; atomic
  647. // and consisent view; no heap allocations.
  648. //
  649. // Customizations include:
  650. //
  651. // - customNetworkLatencyMultiplier, which overrides NetworkLatencyMultiplier
  652. // for this instance only.
  653. //
  654. func (p *ClientParameters) GetCustom(
  655. customNetworkLatencyMultiplier float64) ClientParametersAccessor {
  656. return ClientParametersAccessor{
  657. snapshot: p.snapshot.Load().(*clientParametersSnapshot),
  658. customNetworkLatencyMultiplier: customNetworkLatencyMultiplier,
  659. }
  660. }
  661. // clientParametersSnapshot is an atomic snapshot of the client parameter
  662. // values. ClientParameters.Get will return a snapshot which may be used to
  663. // read multiple related values atomically and consistently while the current
  664. // snapshot in ClientParameters may change concurrently.
  665. type clientParametersSnapshot struct {
  666. getValueLogger func(error)
  667. tag string
  668. parameters map[string]interface{}
  669. }
  670. // getValue sets target to the value of the named parameter.
  671. //
  672. // It is an error if the name is not found, target is not a pointer, or the
  673. // type of target points to does not match the value.
  674. //
  675. // Any of these conditions would be a bug in the caller. getValue does not
  676. // panic in these cases as the client is deployed as a library in various apps
  677. // and the failure of Psiphon may not be a failure for the app process.
  678. //
  679. // Instead, errors are logged to the getValueLogger and getValue leaves the
  680. // target unset, which will result in the caller getting and using a zero
  681. // value of the requested type.
  682. func (p *clientParametersSnapshot) getValue(name string, target interface{}) {
  683. value, ok := p.parameters[name]
  684. if !ok {
  685. if p.getValueLogger != nil {
  686. p.getValueLogger(errors.Tracef(
  687. "value %s not found", name))
  688. }
  689. return
  690. }
  691. valueType := reflect.TypeOf(value)
  692. if reflect.PtrTo(valueType) != reflect.TypeOf(target) {
  693. if p.getValueLogger != nil {
  694. p.getValueLogger(errors.Tracef(
  695. "value %s has unexpected type %s", name, valueType.Name()))
  696. }
  697. return
  698. }
  699. // Note: there is no deep copy of parameter values; the returned value may
  700. // share memory with the original and should not be modified.
  701. targetValue := reflect.ValueOf(target)
  702. if targetValue.Kind() != reflect.Ptr {
  703. p.getValueLogger(errors.Tracef(
  704. "target for value %s is not pointer", name))
  705. return
  706. }
  707. targetValue.Elem().Set(reflect.ValueOf(value))
  708. }
  709. // ClientParametersAccessor provides consistent, atomic access to client
  710. // parameter values. Any customizations are applied transparently.
  711. type ClientParametersAccessor struct {
  712. snapshot *clientParametersSnapshot
  713. customNetworkLatencyMultiplier float64
  714. }
  715. // Close clears internal references to large memory objects, allowing them to
  716. // be garbage collected. Call Close when done using a
  717. // ClientParametersAccessor, where memory footprint is a concern, and where
  718. // the ClientParametersAccessor is not immediately going out of scope. After
  719. // Close is called, all other ClientParametersAccessor functions will panic if
  720. // called.
  721. func (p ClientParametersAccessor) Close() {
  722. p.snapshot = nil
  723. }
  724. // Tag returns the tag associated with these parameters.
  725. func (p ClientParametersAccessor) Tag() string {
  726. return p.snapshot.tag
  727. }
  728. // String returns a string parameter value.
  729. func (p ClientParametersAccessor) String(name string) string {
  730. value := ""
  731. p.snapshot.getValue(name, &value)
  732. return value
  733. }
  734. func (p ClientParametersAccessor) Strings(name string) []string {
  735. value := []string{}
  736. p.snapshot.getValue(name, &value)
  737. return value
  738. }
  739. // Int returns an int parameter value.
  740. func (p ClientParametersAccessor) Int(name string) int {
  741. value := int(0)
  742. p.snapshot.getValue(name, &value)
  743. return value
  744. }
  745. // Bool returns a bool parameter value.
  746. func (p ClientParametersAccessor) Bool(name string) bool {
  747. value := false
  748. p.snapshot.getValue(name, &value)
  749. return value
  750. }
  751. // Float returns a float64 parameter value.
  752. func (p ClientParametersAccessor) Float(name string) float64 {
  753. value := float64(0.0)
  754. p.snapshot.getValue(name, &value)
  755. return value
  756. }
  757. // WeightedCoinFlip returns the result of prng.FlipWeightedCoin using the
  758. // specified float parameter as the probability input.
  759. func (p ClientParametersAccessor) WeightedCoinFlip(name string) bool {
  760. var value float64
  761. p.snapshot.getValue(name, &value)
  762. return prng.FlipWeightedCoin(value)
  763. }
  764. // Duration returns a time.Duration parameter value. When the duration
  765. // parameter has the useNetworkLatencyMultiplier flag, the
  766. // NetworkLatencyMultiplier is applied to the returned value.
  767. func (p ClientParametersAccessor) Duration(name string) time.Duration {
  768. value := time.Duration(0)
  769. p.snapshot.getValue(name, &value)
  770. defaultParameter, ok := defaultClientParameters[name]
  771. if value > 0 && ok && defaultParameter.flags&useNetworkLatencyMultiplier != 0 {
  772. multiplier := float64(0.0)
  773. if p.customNetworkLatencyMultiplier != 0.0 {
  774. multiplier = p.customNetworkLatencyMultiplier
  775. } else {
  776. p.snapshot.getValue(NetworkLatencyMultiplier, &multiplier)
  777. }
  778. if multiplier > 0.0 {
  779. value = time.Duration(float64(value) * multiplier)
  780. }
  781. }
  782. return value
  783. }
  784. // TunnelProtocols returns a protocol.TunnelProtocols parameter value.
  785. // If there is a corresponding Probability value, a weighted coin flip
  786. // will be performed and, depending on the result, the value or the
  787. // parameter default will be returned.
  788. func (p ClientParametersAccessor) TunnelProtocols(name string) protocol.TunnelProtocols {
  789. probabilityName := name + "Probability"
  790. _, ok := p.snapshot.parameters[probabilityName]
  791. if ok {
  792. probabilityValue := float64(1.0)
  793. p.snapshot.getValue(probabilityName, &probabilityValue)
  794. if !prng.FlipWeightedCoin(probabilityValue) {
  795. defaultParameter, ok := defaultClientParameters[name]
  796. if ok {
  797. defaultValue, ok := defaultParameter.value.(protocol.TunnelProtocols)
  798. if ok {
  799. value := make(protocol.TunnelProtocols, len(defaultValue))
  800. copy(value, defaultValue)
  801. return value
  802. }
  803. }
  804. }
  805. }
  806. value := protocol.TunnelProtocols{}
  807. p.snapshot.getValue(name, &value)
  808. return value
  809. }
  810. // TLSProfiles returns a protocol.TLSProfiles parameter value.
  811. // If there is a corresponding Probability value, a weighted coin flip
  812. // will be performed and, depending on the result, the value or the
  813. // parameter default will be returned.
  814. func (p ClientParametersAccessor) TLSProfiles(name string) protocol.TLSProfiles {
  815. probabilityName := name + "Probability"
  816. _, ok := p.snapshot.parameters[probabilityName]
  817. if ok {
  818. probabilityValue := float64(1.0)
  819. p.snapshot.getValue(probabilityName, &probabilityValue)
  820. if !prng.FlipWeightedCoin(probabilityValue) {
  821. defaultParameter, ok := defaultClientParameters[name]
  822. if ok {
  823. defaultValue, ok := defaultParameter.value.(protocol.TLSProfiles)
  824. if ok {
  825. value := make(protocol.TLSProfiles, len(defaultValue))
  826. copy(value, defaultValue)
  827. return value
  828. }
  829. }
  830. }
  831. }
  832. value := protocol.TLSProfiles{}
  833. p.snapshot.getValue(name, &value)
  834. return value
  835. }
  836. // QUICVersions returns a protocol.QUICVersions parameter value.
  837. // If there is a corresponding Probability value, a weighted coin flip
  838. // will be performed and, depending on the result, the value or the
  839. // parameter default will be returned.
  840. func (p ClientParametersAccessor) QUICVersions(name string) protocol.QUICVersions {
  841. probabilityName := name + "Probability"
  842. _, ok := p.snapshot.parameters[probabilityName]
  843. if ok {
  844. probabilityValue := float64(1.0)
  845. p.snapshot.getValue(probabilityName, &probabilityValue)
  846. if !prng.FlipWeightedCoin(probabilityValue) {
  847. defaultParameter, ok := defaultClientParameters[name]
  848. if ok {
  849. defaultValue, ok := defaultParameter.value.(protocol.QUICVersions)
  850. if ok {
  851. value := make(protocol.QUICVersions, len(defaultValue))
  852. copy(value, defaultValue)
  853. return value
  854. }
  855. }
  856. }
  857. }
  858. value := protocol.QUICVersions{}
  859. p.snapshot.getValue(name, &value)
  860. return value
  861. }
  862. // DownloadURLs returns a DownloadURLs parameter value.
  863. func (p ClientParametersAccessor) DownloadURLs(name string) DownloadURLs {
  864. value := DownloadURLs{}
  865. p.snapshot.getValue(name, &value)
  866. return value
  867. }
  868. // RateLimits returns a common.RateLimits parameter value.
  869. func (p ClientParametersAccessor) RateLimits(name string) common.RateLimits {
  870. value := common.RateLimits{}
  871. p.snapshot.getValue(name, &value)
  872. return value
  873. }
  874. // HTTPHeaders returns an http.Header parameter value.
  875. func (p ClientParametersAccessor) HTTPHeaders(name string) http.Header {
  876. value := make(http.Header)
  877. p.snapshot.getValue(name, &value)
  878. return value
  879. }
  880. // CustomTLSProfileNames returns the CustomTLSProfile.Name fields for
  881. // each profile in the CustomTLSProfiles parameter value.
  882. func (p ClientParametersAccessor) CustomTLSProfileNames() []string {
  883. value := protocol.CustomTLSProfiles{}
  884. p.snapshot.getValue(CustomTLSProfiles, &value)
  885. names := make([]string, len(value))
  886. for i := 0; i < len(value); i++ {
  887. names[i] = value[i].Name
  888. }
  889. return names
  890. }
  891. // CustomTLSProfile returns the CustomTLSProfile fields with the specified
  892. // Name field if it exists in the CustomTLSProfiles parameter value.
  893. // Returns nil if not found.
  894. func (p ClientParametersAccessor) CustomTLSProfile(name string) *protocol.CustomTLSProfile {
  895. value := protocol.CustomTLSProfiles{}
  896. p.snapshot.getValue(CustomTLSProfiles, &value)
  897. // Note: linear lookup -- assumes a short list
  898. for i := 0; i < len(value); i++ {
  899. if value[i].Name == name {
  900. return value[i]
  901. }
  902. }
  903. return nil
  904. }
  905. // KeyValues returns a KeyValues parameter value.
  906. func (p ClientParametersAccessor) KeyValues(name string) KeyValues {
  907. value := KeyValues{}
  908. p.snapshot.getValue(name, &value)
  909. return value
  910. }