clientParameters.go 50 KB

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