parameters.go 57 KB

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