parameters.go 58 KB

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