parameters.go 57 KB

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