clientParameters.go 50 KB

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