clientParameters.go 50 KB

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