clientParameters.go 53 KB

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