clientParameters.go 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  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 := len(applyParameters) - 1; i >= 0; i-- {
  519. if v := applyParameters[i][CustomTLSProfiles]; v != nil {
  520. customTLSProfilesValue = v
  521. break
  522. }
  523. }
  524. if customTLSProfiles, ok := customTLSProfilesValue.(protocol.CustomTLSProfiles); ok {
  525. customTLSProfileNames = make([]string, len(customTLSProfiles))
  526. for i := 0; i < len(customTLSProfiles); i++ {
  527. customTLSProfileNames[i] = customTLSProfiles[i].Name
  528. }
  529. }
  530. for i := 0; i < len(applyParameters); i++ {
  531. count := 0
  532. for name, value := range applyParameters[i] {
  533. existingValue, ok := parameters[name]
  534. if !ok {
  535. if skipOnError {
  536. continue
  537. }
  538. return nil, errors.Tracef("unknown parameter: %s", name)
  539. }
  540. // Accept strings such as "1h" for duration parameters.
  541. switch existingValue.(type) {
  542. case time.Duration:
  543. if s, ok := value.(string); ok {
  544. if d, err := time.ParseDuration(s); err == nil {
  545. value = d
  546. }
  547. }
  548. }
  549. // A JSON remarshal resolves cases where applyParameters is a
  550. // result of unmarshal-into-interface, in which case non-scalar
  551. // values will not have the expected types; see:
  552. // https://golang.org/pkg/encoding/json/#Unmarshal. This remarshal
  553. // also results in a deep copy.
  554. marshaledValue, err := json.Marshal(value)
  555. if err != nil {
  556. continue
  557. }
  558. newValuePtr := reflect.New(reflect.TypeOf(existingValue))
  559. err = json.Unmarshal(marshaledValue, newValuePtr.Interface())
  560. if err != nil {
  561. if skipOnError {
  562. continue
  563. }
  564. return nil, errors.Tracef("unmarshal parameter %s failed: %s", name, err)
  565. }
  566. newValue := newValuePtr.Elem().Interface()
  567. // Perform type-specific validation for some cases.
  568. // TODO: require RemoteServerListSignaturePublicKey when
  569. // RemoteServerListURLs is set?
  570. switch v := newValue.(type) {
  571. case DownloadURLs:
  572. err := v.DecodeAndValidate()
  573. if err != nil {
  574. if skipOnError {
  575. continue
  576. }
  577. return nil, errors.Trace(err)
  578. }
  579. case protocol.TunnelProtocols:
  580. if skipOnError {
  581. newValue = v.PruneInvalid()
  582. } else {
  583. err := v.Validate()
  584. if err != nil {
  585. return nil, errors.Trace(err)
  586. }
  587. }
  588. case protocol.TLSProfiles:
  589. if skipOnError {
  590. newValue = v.PruneInvalid(customTLSProfileNames)
  591. } else {
  592. err := v.Validate(customTLSProfileNames)
  593. if err != nil {
  594. return nil, errors.Trace(err)
  595. }
  596. }
  597. case protocol.LabeledTLSProfiles:
  598. if skipOnError {
  599. newValue = v.PruneInvalid(customTLSProfileNames)
  600. } else {
  601. err := v.Validate(customTLSProfileNames)
  602. if err != nil {
  603. return nil, errors.Trace(err)
  604. }
  605. }
  606. case protocol.QUICVersions:
  607. if skipOnError {
  608. newValue = v.PruneInvalid()
  609. } else {
  610. err := v.Validate()
  611. if err != nil {
  612. return nil, errors.Trace(err)
  613. }
  614. }
  615. case protocol.LabeledQUICVersions:
  616. if skipOnError {
  617. newValue = v.PruneInvalid()
  618. } else {
  619. err := v.Validate()
  620. if err != nil {
  621. return nil, errors.Trace(err)
  622. }
  623. }
  624. case protocol.CustomTLSProfiles:
  625. err := v.Validate()
  626. if err != nil {
  627. if skipOnError {
  628. continue
  629. }
  630. return nil, errors.Trace(err)
  631. }
  632. case KeyValues:
  633. err := v.Validate()
  634. if err != nil {
  635. if skipOnError {
  636. continue
  637. }
  638. return nil, errors.Trace(err)
  639. }
  640. case *BPFProgramSpec:
  641. if v != nil {
  642. err := v.Validate()
  643. if err != nil {
  644. if skipOnError {
  645. continue
  646. }
  647. return nil, errors.Trace(err)
  648. }
  649. }
  650. }
  651. // Enforce any minimums. Assumes defaultClientParameters[name]
  652. // exists.
  653. if defaultClientParameters[name].minimum != nil {
  654. valid := true
  655. switch v := newValue.(type) {
  656. case int:
  657. m, ok := defaultClientParameters[name].minimum.(int)
  658. if !ok || v < m {
  659. valid = false
  660. }
  661. case float64:
  662. m, ok := defaultClientParameters[name].minimum.(float64)
  663. if !ok || v < m {
  664. valid = false
  665. }
  666. case time.Duration:
  667. m, ok := defaultClientParameters[name].minimum.(time.Duration)
  668. if !ok || v < m {
  669. valid = false
  670. }
  671. default:
  672. if skipOnError {
  673. continue
  674. }
  675. return nil, errors.Tracef("unexpected parameter with minimum: %s", name)
  676. }
  677. if !valid {
  678. if skipOnError {
  679. continue
  680. }
  681. return nil, errors.Tracef("parameter below minimum: %s", name)
  682. }
  683. }
  684. parameters[name] = newValue
  685. count++
  686. }
  687. counts = append(counts, count)
  688. }
  689. snapshot := &clientParametersSnapshot{
  690. getValueLogger: p.getValueLogger,
  691. tag: tag,
  692. parameters: parameters,
  693. }
  694. p.snapshot.Store(snapshot)
  695. return counts, nil
  696. }
  697. // Get returns the current parameters.
  698. //
  699. // Values read from the current parameters are not deep copies and must be
  700. // treated read-only.
  701. //
  702. // The returned ClientParametersAccessor may be used to read multiple related
  703. // values atomically and consistently while the current set of values in
  704. // ClientParameters may change concurrently.
  705. //
  706. // Get does not perform any heap allocations and is intended for repeated,
  707. // direct, low-overhead invocations.
  708. func (p *ClientParameters) Get() ClientParametersAccessor {
  709. return ClientParametersAccessor{
  710. snapshot: p.snapshot.Load().(*clientParametersSnapshot)}
  711. }
  712. // GetCustom returns the current parameters while also setting customizations
  713. // for this instance.
  714. //
  715. // The properties of Get also apply to GetCustom: must be read-only; atomic
  716. // and consisent view; no heap allocations.
  717. //
  718. // Customizations include:
  719. //
  720. // - customNetworkLatencyMultiplier, which overrides NetworkLatencyMultiplier
  721. // for this instance only.
  722. //
  723. func (p *ClientParameters) GetCustom(
  724. customNetworkLatencyMultiplier float64) ClientParametersAccessor {
  725. return ClientParametersAccessor{
  726. snapshot: p.snapshot.Load().(*clientParametersSnapshot),
  727. customNetworkLatencyMultiplier: customNetworkLatencyMultiplier,
  728. }
  729. }
  730. // clientParametersSnapshot is an atomic snapshot of the client parameter
  731. // values. ClientParameters.Get will return a snapshot which may be used to
  732. // read multiple related values atomically and consistently while the current
  733. // snapshot in ClientParameters may change concurrently.
  734. type clientParametersSnapshot struct {
  735. getValueLogger func(error)
  736. tag string
  737. parameters map[string]interface{}
  738. }
  739. // getValue sets target to the value of the named parameter.
  740. //
  741. // It is an error if the name is not found, target is not a pointer, or the
  742. // type of target points to does not match the value.
  743. //
  744. // Any of these conditions would be a bug in the caller. getValue does not
  745. // panic in these cases as the client is deployed as a library in various apps
  746. // and the failure of Psiphon may not be a failure for the app process.
  747. //
  748. // Instead, errors are logged to the getValueLogger and getValue leaves the
  749. // target unset, which will result in the caller getting and using a zero
  750. // value of the requested type.
  751. func (p *clientParametersSnapshot) getValue(name string, target interface{}) {
  752. value, ok := p.parameters[name]
  753. if !ok {
  754. if p.getValueLogger != nil {
  755. p.getValueLogger(errors.Tracef(
  756. "value %s not found", name))
  757. }
  758. return
  759. }
  760. valueType := reflect.TypeOf(value)
  761. if reflect.PtrTo(valueType) != reflect.TypeOf(target) {
  762. if p.getValueLogger != nil {
  763. p.getValueLogger(errors.Tracef(
  764. "value %s has unexpected type %s", name, valueType.Name()))
  765. }
  766. return
  767. }
  768. // Note: there is no deep copy of parameter values; the returned value may
  769. // share memory with the original and should not be modified.
  770. targetValue := reflect.ValueOf(target)
  771. if targetValue.Kind() != reflect.Ptr {
  772. p.getValueLogger(errors.Tracef(
  773. "target for value %s is not pointer", name))
  774. return
  775. }
  776. targetValue.Elem().Set(reflect.ValueOf(value))
  777. }
  778. // ClientParametersAccessor provides consistent, atomic access to client
  779. // parameter values. Any customizations are applied transparently.
  780. type ClientParametersAccessor struct {
  781. snapshot *clientParametersSnapshot
  782. customNetworkLatencyMultiplier float64
  783. }
  784. // Close clears internal references to large memory objects, allowing them to
  785. // be garbage collected. Call Close when done using a
  786. // ClientParametersAccessor, where memory footprint is a concern, and where
  787. // the ClientParametersAccessor is not immediately going out of scope. After
  788. // Close is called, all other ClientParametersAccessor functions will panic if
  789. // called.
  790. func (p ClientParametersAccessor) Close() {
  791. p.snapshot = nil
  792. }
  793. // Tag returns the tag associated with these parameters.
  794. func (p ClientParametersAccessor) Tag() string {
  795. return p.snapshot.tag
  796. }
  797. // String returns a string parameter value.
  798. func (p ClientParametersAccessor) String(name string) string {
  799. value := ""
  800. p.snapshot.getValue(name, &value)
  801. return value
  802. }
  803. func (p ClientParametersAccessor) Strings(name string) []string {
  804. value := []string{}
  805. p.snapshot.getValue(name, &value)
  806. return value
  807. }
  808. // Int returns an int parameter value.
  809. func (p ClientParametersAccessor) Int(name string) int {
  810. value := int(0)
  811. p.snapshot.getValue(name, &value)
  812. return value
  813. }
  814. // Bool returns a bool parameter value.
  815. func (p ClientParametersAccessor) Bool(name string) bool {
  816. value := false
  817. p.snapshot.getValue(name, &value)
  818. return value
  819. }
  820. // Float returns a float64 parameter value.
  821. func (p ClientParametersAccessor) Float(name string) float64 {
  822. value := float64(0.0)
  823. p.snapshot.getValue(name, &value)
  824. return value
  825. }
  826. // WeightedCoinFlip returns the result of prng.FlipWeightedCoin using the
  827. // specified float parameter as the probability input.
  828. func (p ClientParametersAccessor) WeightedCoinFlip(name string) bool {
  829. var value float64
  830. p.snapshot.getValue(name, &value)
  831. return prng.FlipWeightedCoin(value)
  832. }
  833. // Duration returns a time.Duration parameter value. When the duration
  834. // parameter has the useNetworkLatencyMultiplier flag, the
  835. // NetworkLatencyMultiplier is applied to the returned value.
  836. func (p ClientParametersAccessor) Duration(name string) time.Duration {
  837. value := time.Duration(0)
  838. p.snapshot.getValue(name, &value)
  839. defaultParameter, ok := defaultClientParameters[name]
  840. if value > 0 && ok && defaultParameter.flags&useNetworkLatencyMultiplier != 0 {
  841. multiplier := float64(0.0)
  842. if p.customNetworkLatencyMultiplier != 0.0 {
  843. multiplier = p.customNetworkLatencyMultiplier
  844. } else {
  845. p.snapshot.getValue(NetworkLatencyMultiplier, &multiplier)
  846. }
  847. if multiplier > 0.0 {
  848. value = time.Duration(float64(value) * multiplier)
  849. }
  850. }
  851. return value
  852. }
  853. // TunnelProtocols returns a protocol.TunnelProtocols parameter value.
  854. // If there is a corresponding Probability value, a weighted coin flip
  855. // will be performed and, depending on the result, the value or the
  856. // parameter default will be returned.
  857. func (p ClientParametersAccessor) TunnelProtocols(name string) protocol.TunnelProtocols {
  858. probabilityName := name + "Probability"
  859. _, ok := p.snapshot.parameters[probabilityName]
  860. if ok {
  861. probabilityValue := float64(1.0)
  862. p.snapshot.getValue(probabilityName, &probabilityValue)
  863. if !prng.FlipWeightedCoin(probabilityValue) {
  864. defaultParameter, ok := defaultClientParameters[name]
  865. if ok {
  866. defaultValue, ok := defaultParameter.value.(protocol.TunnelProtocols)
  867. if ok {
  868. value := make(protocol.TunnelProtocols, len(defaultValue))
  869. copy(value, defaultValue)
  870. return value
  871. }
  872. }
  873. }
  874. }
  875. value := protocol.TunnelProtocols{}
  876. p.snapshot.getValue(name, &value)
  877. return value
  878. }
  879. // TLSProfiles returns a protocol.TLSProfiles parameter value.
  880. // If there is a corresponding Probability value, a weighted coin flip
  881. // will be performed and, depending on the result, the value or the
  882. // parameter default will be returned.
  883. func (p ClientParametersAccessor) TLSProfiles(name string) protocol.TLSProfiles {
  884. probabilityName := name + "Probability"
  885. _, ok := p.snapshot.parameters[probabilityName]
  886. if ok {
  887. probabilityValue := float64(1.0)
  888. p.snapshot.getValue(probabilityName, &probabilityValue)
  889. if !prng.FlipWeightedCoin(probabilityValue) {
  890. defaultParameter, ok := defaultClientParameters[name]
  891. if ok {
  892. defaultValue, ok := defaultParameter.value.(protocol.TLSProfiles)
  893. if ok {
  894. value := make(protocol.TLSProfiles, len(defaultValue))
  895. copy(value, defaultValue)
  896. return value
  897. }
  898. }
  899. }
  900. }
  901. value := protocol.TLSProfiles{}
  902. p.snapshot.getValue(name, &value)
  903. return value
  904. }
  905. // LabeledTLSProfiles returns a protocol.TLSProfiles parameter value
  906. // corresponding to the specified labeled set and label value. The return
  907. // value is nil when no set is found.
  908. func (p ClientParametersAccessor) LabeledTLSProfiles(name, label string) protocol.TLSProfiles {
  909. var value protocol.LabeledTLSProfiles
  910. p.snapshot.getValue(name, &value)
  911. return value[label]
  912. }
  913. // QUICVersions returns a protocol.QUICVersions parameter value.
  914. // If there is a corresponding Probability value, a weighted coin flip
  915. // will be performed and, depending on the result, the value or the
  916. // parameter default will be returned.
  917. func (p ClientParametersAccessor) QUICVersions(name string) protocol.QUICVersions {
  918. probabilityName := name + "Probability"
  919. _, ok := p.snapshot.parameters[probabilityName]
  920. if ok {
  921. probabilityValue := float64(1.0)
  922. p.snapshot.getValue(probabilityName, &probabilityValue)
  923. if !prng.FlipWeightedCoin(probabilityValue) {
  924. defaultParameter, ok := defaultClientParameters[name]
  925. if ok {
  926. defaultValue, ok := defaultParameter.value.(protocol.QUICVersions)
  927. if ok {
  928. value := make(protocol.QUICVersions, len(defaultValue))
  929. copy(value, defaultValue)
  930. return value
  931. }
  932. }
  933. }
  934. }
  935. value := protocol.QUICVersions{}
  936. p.snapshot.getValue(name, &value)
  937. return value
  938. }
  939. // LabeledQUICVersions returns a protocol.QUICVersions parameter value
  940. // corresponding to the specified labeled set and label value. The return
  941. // value is nil when no set is found.
  942. func (p ClientParametersAccessor) LabeledQUICVersions(name, label string) protocol.QUICVersions {
  943. var value protocol.LabeledQUICVersions
  944. p.snapshot.getValue(name, &value)
  945. return value[label]
  946. }
  947. // DownloadURLs returns a DownloadURLs parameter value.
  948. func (p ClientParametersAccessor) DownloadURLs(name string) DownloadURLs {
  949. value := DownloadURLs{}
  950. p.snapshot.getValue(name, &value)
  951. return value
  952. }
  953. // RateLimits returns a common.RateLimits parameter value.
  954. func (p ClientParametersAccessor) RateLimits(name string) common.RateLimits {
  955. value := common.RateLimits{}
  956. p.snapshot.getValue(name, &value)
  957. return value
  958. }
  959. // HTTPHeaders returns an http.Header parameter value.
  960. func (p ClientParametersAccessor) HTTPHeaders(name string) http.Header {
  961. value := make(http.Header)
  962. p.snapshot.getValue(name, &value)
  963. return value
  964. }
  965. // CustomTLSProfileNames returns the CustomTLSProfile.Name fields for
  966. // each profile in the CustomTLSProfiles parameter value.
  967. func (p ClientParametersAccessor) CustomTLSProfileNames() []string {
  968. value := protocol.CustomTLSProfiles{}
  969. p.snapshot.getValue(CustomTLSProfiles, &value)
  970. names := make([]string, len(value))
  971. for i := 0; i < len(value); i++ {
  972. names[i] = value[i].Name
  973. }
  974. return names
  975. }
  976. // CustomTLSProfile returns the CustomTLSProfile fields with the specified
  977. // Name field if it exists in the CustomTLSProfiles parameter value.
  978. // Returns nil if not found.
  979. func (p ClientParametersAccessor) CustomTLSProfile(name string) *protocol.CustomTLSProfile {
  980. value := protocol.CustomTLSProfiles{}
  981. p.snapshot.getValue(CustomTLSProfiles, &value)
  982. // Note: linear lookup -- assumes a short list
  983. for i := 0; i < len(value); i++ {
  984. if value[i].Name == name {
  985. return value[i]
  986. }
  987. }
  988. return nil
  989. }
  990. // KeyValues returns a KeyValues parameter value.
  991. func (p ClientParametersAccessor) KeyValues(name string) KeyValues {
  992. value := KeyValues{}
  993. p.snapshot.getValue(name, &value)
  994. return value
  995. }
  996. // BPFProgram returns an assembled BPF program corresponding to a
  997. // BPFProgramSpec parameter value. Returns nil in the case of any empty
  998. // program.
  999. func (p ClientParametersAccessor) BPFProgram(name string) (bool, string, []bpf.RawInstruction) {
  1000. var value *BPFProgramSpec
  1001. p.snapshot.getValue(name, &value)
  1002. if value == nil {
  1003. return false, "", nil
  1004. }
  1005. // Validation checks that Assemble is successful.
  1006. rawInstructions, _ := value.Assemble()
  1007. return true, value.Name, rawInstructions
  1008. }