config.go 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516
  1. /*
  2. * Copyright (c) 2015, 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. package psiphon
  20. import (
  21. "crypto/md5"
  22. "encoding/base64"
  23. "encoding/binary"
  24. "encoding/json"
  25. "fmt"
  26. "io/ioutil"
  27. "net/http"
  28. "os"
  29. "path/filepath"
  30. "regexp"
  31. "strconv"
  32. "strings"
  33. "sync"
  34. "unicode"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/resolver"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/transforms"
  41. )
  42. const (
  43. TUNNEL_POOL_SIZE = 1
  44. MAX_TUNNEL_POOL_SIZE = 32
  45. // Psiphon data directory name, relative to config.DataRootDirectory.
  46. // See config.GetPsiphonDataDirectory().
  47. PsiphonDataDirectoryName = "ca.psiphon.PsiphonTunnel.tunnel-core"
  48. // Filename constants, all relative to config.GetPsiphonDataDirectory().
  49. HomepageFilename = "homepage"
  50. NoticesFilename = "notices"
  51. OldNoticesFilename = "notices.1"
  52. UpgradeDownloadFilename = "upgrade"
  53. )
  54. // Config is the Psiphon configuration specified by the application. This
  55. // configuration controls the behavior of the core tunnel functionality.
  56. //
  57. // To distinguish omitted timeout params from explicit 0 value timeout params,
  58. // corresponding fields are int pointers. nil means no value was supplied and
  59. // to use the default; a non-nil pointer to 0 means no timeout.
  60. type Config struct {
  61. // DataRootDirectory is the directory in which to store persistent files,
  62. // which contain information such as server entries. By default, current
  63. // working directory.
  64. //
  65. // Psiphon will assume full control of files under this directory. They may
  66. // be deleted, moved or overwritten.
  67. DataRootDirectory string
  68. // UseNoticeFiles configures notice files for writing. If set, homepages
  69. // will be written to a file created at config.GetHomePageFilename()
  70. // and notices will be written to a file created at
  71. // config.GetNoticesFilename().
  72. //
  73. // The homepage file may be read after the Tunnels notice with count of 1.
  74. //
  75. // The value of UseNoticeFiles sets the size and frequency at which the
  76. // notices file, config.GetNoticesFilename(), will be rotated. See the
  77. // comment for UseNoticeFiles for more details. One rotated older file,
  78. // config.GetOldNoticesFilename(), is retained.
  79. //
  80. // The notice files may be may be read at any time; and should be opened
  81. // read-only for reading. Diagnostic notices are omitted from the notice
  82. // files.
  83. //
  84. // See comment for setNoticeFiles in notice.go for further details.
  85. UseNoticeFiles *UseNoticeFiles
  86. // PropagationChannelId is a string identifier which indicates how the
  87. // Psiphon client was distributed. This parameter is required. This value
  88. // is supplied by and depends on the Psiphon Network, and is typically
  89. // embedded in the client binary.
  90. PropagationChannelId string
  91. // SponsorId is a string identifier which indicates who is sponsoring this
  92. // Psiphon client. One purpose of this value is to determine the home
  93. // pages for display. This parameter is required. This value is supplied
  94. // by and depends on the Psiphon Network, and is typically embedded in the
  95. // client binary.
  96. SponsorId string
  97. // ClientVersion is the client version number that the client reports to
  98. // the server. The version number refers to the host client application,
  99. // not the core tunnel library. One purpose of this value is to enable
  100. // automatic updates. This value is supplied by and depends on the Psiphon
  101. // Network, and is typically embedded in the client binary.
  102. //
  103. // Note that sending a ClientPlatform string which includes "windows"
  104. // (case insensitive) and a ClientVersion of <= 44 will cause an error in
  105. // processing the response to DoConnectedRequest calls.
  106. ClientVersion string
  107. // ClientPlatform is the client platform ("Windows", "Android", etc.) that
  108. // the client reports to the server.
  109. ClientPlatform string
  110. // ClientFeatures is a list of feature names denoting enabled application
  111. // features. Clients report enabled features to the server for stats
  112. // purposes.
  113. ClientFeatures []string
  114. // EgressRegion is a ISO 3166-1 alpha-2 country code which indicates which
  115. // country to egress from. For the default, "", the best performing server
  116. // in any country is selected.
  117. EgressRegion string
  118. // SplitTunnelOwnRegion enables split tunnel mode for the client's own
  119. // country. When enabled, TCP port forward destinations that resolve to
  120. // the same GeoIP country as the client are connected to directly,
  121. // untunneled.
  122. SplitTunnelOwnRegion bool
  123. // SplitTunnelRegions enables selected split tunnel mode in which the
  124. // client specifies a list of ISO 3166-1 alpha-2 country codes for which
  125. // traffic should be untunneled. TCP port forwards destined to any
  126. // country specified in SplitTunnelRegions will be untunneled, regardless
  127. // of whether SplitTunnelOwnRegion is on or off.
  128. SplitTunnelRegions []string
  129. // ListenInterface specifies which interface to listen on. If no
  130. // interface is provided then listen on 127.0.0.1. If 'any' is provided
  131. // then use 0.0.0.0. If there are multiple IP addresses on an interface
  132. // use the first IPv4 address.
  133. ListenInterface string
  134. // DisableLocalSocksProxy disables running the local SOCKS proxy.
  135. DisableLocalSocksProxy bool
  136. // LocalSocksProxyPort specifies a port number for the local SOCKS proxy
  137. // running at 127.0.0.1. For the default value, 0, the system selects a
  138. // free port (a notice reporting the selected port is emitted).
  139. LocalSocksProxyPort int
  140. // LocalHttpProxyPort specifies a port number for the local HTTP proxy
  141. // running at 127.0.0.1. For the default value, 0, the system selects a
  142. // free port (a notice reporting the selected port is emitted).
  143. LocalHttpProxyPort int
  144. // DisableLocalHTTPProxy disables running the local HTTP proxy.
  145. DisableLocalHTTPProxy bool
  146. // NetworkLatencyMultiplier is a multiplier that is to be applied to
  147. // default network event timeouts. Set this to tune performance for
  148. // slow networks.
  149. // When set, must be >= 1.0.
  150. NetworkLatencyMultiplier float64
  151. // LimitTunnelProtocols indicates which protocols to use. Valid values
  152. // include: "SSH", "OSSH", "UNFRONTED-MEEK-OSSH",
  153. // "UNFRONTED-MEEK-HTTPS-OSSH", "UNFRONTED-MEEK-SESSION-TICKET-OSSH",
  154. // "FRONTED-MEEK-OSSH", "FRONTED-MEEK-HTTP-OSSH", "QUIC-OSSH",
  155. // "FRONTED-MEEK-QUIC-OSSH", "TAPDANCE-OSSH", and "CONJURE-OSSH".
  156. // For the default, an empty list, all protocols are used.
  157. LimitTunnelProtocols []string
  158. // InitialLimitTunnelProtocols is an optional initial phase of limited
  159. // protocols for the first InitialLimitTunnelProtocolsCandidateCount
  160. // candidates; after these candidates, LimitTunnelProtocols applies.
  161. //
  162. // For the default, an empty list, InitialLimitTunnelProtocols is off.
  163. InitialLimitTunnelProtocols []string
  164. // InitialLimitTunnelProtocolsCandidateCount is the number of candidates
  165. // to which InitialLimitTunnelProtocols is applied instead of
  166. // LimitTunnelProtocols.
  167. //
  168. // For the default, 0, InitialLimitTunnelProtocols is off.
  169. InitialLimitTunnelProtocolsCandidateCount int
  170. // LimitTLSProfiles indicates which TLS profiles to select from. Valid
  171. // values are listed in protocols.SupportedTLSProfiles.
  172. // For the default, an empty list, all profiles are candidates for
  173. // selection.
  174. LimitTLSProfiles []string
  175. // LimitQUICVersions indicates which QUIC versions to select from. Valid
  176. // values are listed in protocols.SupportedQUICVersions.
  177. // For the default, an empty list, all versions are candidates for
  178. // selection.
  179. LimitQUICVersions []string
  180. // EstablishTunnelTimeoutSeconds specifies a time limit after which to
  181. // halt the core tunnel controller if no tunnel has been established. The
  182. // default is parameters.EstablishTunnelTimeout.
  183. EstablishTunnelTimeoutSeconds *int
  184. // EstablishTunnelPausePeriodSeconds specifies the delay between attempts
  185. // to establish tunnels. Briefly pausing allows for network conditions to
  186. // improve and for asynchronous operations such as fetch remote server
  187. // list to complete. If omitted, a default value is used. This value is
  188. // typical overridden for testing.
  189. EstablishTunnelPausePeriodSeconds *int
  190. // EstablishTunnelPausePeriodSeconds specifies the grace period, or head
  191. // start, provided to the affinity server candidate when establishing. The
  192. // affinity server is the server used for the last established tunnel.
  193. EstablishTunnelServerAffinityGracePeriodMilliseconds *int
  194. // ConnectionWorkerPoolSize specifies how many connection attempts to
  195. // attempt in parallel. If omitted of when 0, a default is used; this is
  196. // recommended.
  197. ConnectionWorkerPoolSize int
  198. // TunnelPoolSize specifies how many tunnels to run in parallel. Port
  199. // forwards are multiplexed over multiple tunnels. If omitted or when 0,
  200. // the default is TUNNEL_POOL_SIZE, which is recommended. Any value over
  201. // MAX_TUNNEL_POOL_SIZE is treated as MAX_TUNNEL_POOL_SIZE.
  202. TunnelPoolSize int
  203. // StaggerConnectionWorkersMilliseconds adds a specified delay before
  204. // making each server candidate available to connection workers. This
  205. // option is enabled when StaggerConnectionWorkersMilliseconds > 0.
  206. StaggerConnectionWorkersMilliseconds int
  207. // LimitIntensiveConnectionWorkers limits the number of concurrent
  208. // connection workers attempting connections with resource intensive
  209. // protocols. This option is enabled when LimitIntensiveConnectionWorkers
  210. // > 0.
  211. LimitIntensiveConnectionWorkers int
  212. // LimitMeekBufferSizes selects smaller buffers for meek protocols.
  213. LimitMeekBufferSizes bool
  214. // LimitCPUThreads minimizes the number of CPU threads -- and associated
  215. // overhead -- the are used.
  216. LimitCPUThreads bool
  217. // LimitRelayBufferSizes selects smaller buffers for port forward relaying.
  218. LimitRelayBufferSizes bool
  219. // IgnoreHandshakeStatsRegexps skips compiling and using stats regexes.
  220. IgnoreHandshakeStatsRegexps bool
  221. // UpstreamProxyURL is a URL specifying an upstream proxy to use for all
  222. // outbound connections. The URL should include proxy type and
  223. // authentication information, as required. See example URLs here:
  224. // https://github.com/Psiphon-Labs/psiphon-tunnel-core/tree/master/psiphon/upstreamproxy
  225. UpstreamProxyURL string
  226. // CustomHeaders is a set of additional arbitrary HTTP headers that are
  227. // added to all plaintext HTTP requests and requests made through an HTTP
  228. // upstream proxy when specified by UpstreamProxyURL.
  229. CustomHeaders http.Header
  230. // NetworkConnectivityChecker is an interface that enables tunnel-core to
  231. // call into the host application to check for network connectivity. See:
  232. // NetworkConnectivityChecker doc.
  233. NetworkConnectivityChecker NetworkConnectivityChecker
  234. // DeviceBinder is an interface that enables tunnel-core to call into the
  235. // host application to bind sockets to specific devices. See: DeviceBinder
  236. // doc.
  237. //
  238. // When DeviceBinder is set, the "VPN" feature name is automatically added
  239. // when reporting ClientFeatures.
  240. DeviceBinder DeviceBinder
  241. // AllowDefaultDNSResolverWithBindToDevice indicates that it's safe to use
  242. // the default resolver when DeviceBinder is configured, as the host OS
  243. // will automatically exclude DNS requests from the VPN.
  244. AllowDefaultDNSResolverWithBindToDevice bool
  245. // IPv6Synthesizer is an interface that allows tunnel-core to call into
  246. // the host application to synthesize IPv6 addresses. See: IPv6Synthesizer
  247. // doc.
  248. IPv6Synthesizer IPv6Synthesizer
  249. // HasIPv6RouteGetter is an interface that allows tunnel-core to call into
  250. // the host application to determine if the host has an IPv6 route. See:
  251. // HasIPv6RouteGetter doc.
  252. HasIPv6RouteGetter HasIPv6RouteGetter
  253. // DNSServerGetter is an interface that enables tunnel-core to call into
  254. // the host application to discover the native network DNS server
  255. // settings. See: DNSServerGetter doc.
  256. DNSServerGetter DNSServerGetter
  257. // NetworkIDGetter in an interface that enables tunnel-core to call into
  258. // the host application to get an identifier for the host's current active
  259. // network. See: NetworkIDGetter doc.
  260. NetworkIDGetter NetworkIDGetter
  261. // NetworkID, when not blank, is used as the identifier for the host's
  262. // current active network.
  263. // NetworkID is ignored when NetworkIDGetter is set.
  264. NetworkID string
  265. // DisableTactics disables tactics operations including requests, payload
  266. // handling, and application of parameters.
  267. DisableTactics bool
  268. // DisableReplay causes any persisted dial parameters to be ignored when
  269. // they would otherwise be used for replay.
  270. DisableReplay bool
  271. // TargetServerEntry is an encoded server entry. When specified, this
  272. // server entry is used exclusively and all other known servers are
  273. // ignored; also, when set, ConnectionWorkerPoolSize is ignored and
  274. // the pool size is 1.
  275. TargetServerEntry string
  276. // DisableApi disables Psiphon server API calls including handshake,
  277. // connected, status, etc. This is used for special case temporary tunnels
  278. // (Windows VPN mode).
  279. DisableApi bool
  280. // TargetApiProtocol specifies whether to force use of "ssh" or "web" API
  281. // protocol. When blank, the default, the optimal API protocol is used.
  282. // Note that this capability check is not applied before the
  283. // "CandidateServers" count is emitted.
  284. //
  285. // This parameter is intended for testing and debugging only. Not all
  286. // parameters are supported in the legacy "web" API protocol, including
  287. // speed test samples.
  288. TargetApiProtocol string
  289. // RemoteServerListURLs is list of URLs which specify locations to fetch
  290. // out-of-band server entries. This facility is used when a tunnel cannot
  291. // be established to known servers. This value is supplied by and depends
  292. // on the Psiphon Network, and is typically embedded in the client binary.
  293. // All URLs must point to the same entity with the same ETag. At least one
  294. // TransferURL must have OnlyAfterAttempts = 0.
  295. RemoteServerListURLs parameters.TransferURLs
  296. // RemoteServerListSignaturePublicKey specifies a public key that's used
  297. // to authenticate the remote server list payload. This value is supplied
  298. // by and depends on the Psiphon Network, and is typically embedded in the
  299. // client binary.
  300. RemoteServerListSignaturePublicKey string
  301. // DisableRemoteServerListFetcher disables fetching remote server lists.
  302. // This is used for special case temporary tunnels.
  303. DisableRemoteServerListFetcher bool
  304. // FetchRemoteServerListRetryPeriodMilliseconds specifies the delay before
  305. // resuming a remote server list download after a failure. If omitted, a
  306. // default value is used. This value is typical overridden for testing.
  307. FetchRemoteServerListRetryPeriodMilliseconds *int
  308. // ObfuscatedServerListRootURLs is a list of URLs which specify root
  309. // locations from which to fetch obfuscated server list files. This value
  310. // is supplied by and depends on the Psiphon Network, and is typically
  311. // embedded in the client binary. All URLs must point to the same entity
  312. // with the same ETag. At least one DownloadURL must have
  313. // OnlyAfterAttempts = 0.
  314. ObfuscatedServerListRootURLs parameters.TransferURLs
  315. // UpgradeDownloadURLs is list of URLs which specify locations from which
  316. // to download a host client upgrade file, when one is available. The core
  317. // tunnel controller provides a resumable download facility which
  318. // downloads this resource and emits a notice when complete. This value is
  319. // supplied by and depends on the Psiphon Network, and is typically
  320. // embedded in the client binary. All URLs must point to the same entity
  321. // with the same ETag. At least one DownloadURL must have
  322. // OnlyAfterAttempts = 0.
  323. UpgradeDownloadURLs parameters.TransferURLs
  324. // UpgradeDownloadClientVersionHeader specifies the HTTP header name for
  325. // the entity at UpgradeDownloadURLs which specifies the client version
  326. // (an integer value). A HEAD request may be made to check the version
  327. // number available at UpgradeDownloadURLs.
  328. // UpgradeDownloadClientVersionHeader is required when UpgradeDownloadURLs
  329. // is specified.
  330. UpgradeDownloadClientVersionHeader string
  331. // FetchUpgradeRetryPeriodMilliseconds specifies the delay before resuming
  332. // a client upgrade download after a failure. If omitted, a default value
  333. // is used. This value is typical overridden for testing.
  334. FetchUpgradeRetryPeriodMilliseconds *int
  335. // FeedbackUploadURLs is a list of SecureTransferURLs which specify
  336. // locations where feedback data can be uploaded, pairing with each
  337. // location a public key with which to encrypt the feedback data. This
  338. // value is supplied by and depends on the Psiphon Network, and is
  339. // typically embedded in the client binary. At least one TransferURL must
  340. // have OnlyAfterAttempts = 0.
  341. FeedbackUploadURLs parameters.TransferURLs
  342. // FeedbackEncryptionPublicKey is a default base64-encoded, RSA public key
  343. // value used to encrypt feedback data. Used when uploading feedback with a
  344. // TransferURL which has no public key value configured, i.e.
  345. // B64EncodedPublicKey = "".
  346. FeedbackEncryptionPublicKey string
  347. // TrustedCACertificatesFilename specifies a file containing trusted CA
  348. // certs. When set, this toggles use of the trusted CA certs, specified in
  349. // TrustedCACertificatesFilename, for tunneled TLS connections that expect
  350. // server certificates signed with public certificate authorities
  351. // (currently, only upgrade downloads). This option is used with stock Go
  352. // TLS in cases where Go may fail to obtain a list of root CAs from the
  353. // operating system.
  354. TrustedCACertificatesFilename string
  355. // DisablePeriodicSshKeepAlive indicates whether to send an SSH keepalive
  356. // every 1-2 minutes, when the tunnel is idle. If the SSH keepalive times
  357. // out, the tunnel is considered to have failed.
  358. DisablePeriodicSshKeepAlive bool
  359. // DeviceRegion is the optional, reported region the host device is
  360. // running in. This input value should be a ISO 3166-1 alpha-2 country
  361. // code. The device region is reported to the server in the connected
  362. // request and recorded for Psiphon stats.
  363. //
  364. // When provided, this value may be used, pre-connection, to select
  365. // performance or circumvention optimization strategies for the given
  366. // region.
  367. DeviceRegion string
  368. // EmitDiagnosticNotices indicates whether to output notices containing
  369. // detailed information about the Psiphon session. As these notices may
  370. // contain sensitive information, they should not be insecurely distributed
  371. // or displayed to users. Default is off.
  372. EmitDiagnosticNotices bool
  373. // EmitDiagnosticNetworkParameters indicates whether to include network
  374. // parameters in diagnostic notices. As these parameters are sensitive
  375. // circumvention network information, they should not be insecurely
  376. // distributed or displayed to users. Default is off.
  377. EmitDiagnosticNetworkParameters bool
  378. // EmitBytesTransferred indicates whether to emit periodic notices showing
  379. // bytes sent and received.
  380. EmitBytesTransferred bool
  381. // EmitSLOKs indicates whether to emit notices for each seeded SLOK. As
  382. // this could reveal user browsing activity, it's intended for debugging
  383. // and testing only.
  384. EmitSLOKs bool
  385. // EmitRefractionNetworkingLogs indicates whether to emit gotapdance log
  386. // messages to stdout. Note that gotapdance log messages do not conform to
  387. // the Notice format standard. Default is off.
  388. EmitRefractionNetworkingLogs bool
  389. // EmitServerAlerts indicates whether to emit notices for server alerts.
  390. EmitServerAlerts bool
  391. // EmitClientAddress indicates whether to emit the client's public network
  392. // address, IP and port, as seen by the server.
  393. EmitClientAddress bool
  394. // RateLimits specify throttling configuration for the tunnel.
  395. RateLimits common.RateLimits
  396. // PacketTunnelTunDeviceFileDescriptor specifies a tun device file
  397. // descriptor to use for running a packet tunnel. When this value is > 0,
  398. // a packet tunnel is established through the server and packets are
  399. // relayed via the tun device file descriptor. The file descriptor is
  400. // duped in NewController. When PacketTunnelTunDeviceFileDescriptor is
  401. // set, TunnelPoolSize must be 1.
  402. PacketTunnelTunFileDescriptor int
  403. // SessionID specifies a client session ID to use in the Psiphon API. The
  404. // session ID should be a randomly generated value that is used only for a
  405. // single session, which is defined as the period between a user starting
  406. // a Psiphon client and stopping the client.
  407. //
  408. // A session ID must be 32 hex digits (lower case). When blank, a random
  409. // session ID is automatically generated. Supply a session ID when a
  410. // single client session will cross multiple Controller instances.
  411. SessionID string
  412. // Authorizations is a list of encoded, signed access control
  413. // authorizations that the client has obtained and will present to the
  414. // server.
  415. Authorizations []string
  416. // ServerEntrySignaturePublicKey is a base64-encoded, ed25519 public
  417. // key value used to verify individual server entry signatures. This value
  418. // is supplied by and depends on the Psiphon Network, and is typically
  419. // embedded in the client binary.
  420. ServerEntrySignaturePublicKey string
  421. // ExchangeObfuscationKey is a base64-encoded, NaCl secretbox key used to
  422. // obfuscate server info exchanges between clients.
  423. // Required for the exchange functionality.
  424. ExchangeObfuscationKey string
  425. // MigrateHomepageNoticesFilename migrates a homepage file from the path
  426. // previously configured with setNoticeFiles to the new path for homepage
  427. // files under the data root directory. The file specified by this config
  428. // value will be moved to config.GetHomePageFilename().
  429. //
  430. // Note: see comment for config.Commit() for a description of how file
  431. // migrations are performed.
  432. //
  433. // If not set, no migration operation will be performed.
  434. MigrateHomepageNoticesFilename string
  435. // MigrateRotatingNoticesFilename migrates notice files from the path
  436. // previously configured with setNoticeFiles to the new path for notice
  437. // files under the data root directory.
  438. //
  439. // MigrateRotatingNoticesFilename will be moved to
  440. // config.GetNoticesFilename().
  441. //
  442. // MigrateRotatingNoticesFilename.1 will be moved to
  443. // config.GetOldNoticesFilename().
  444. //
  445. // Note: see comment for config.Commit() for a description of how file
  446. // migrations are performed.
  447. //
  448. // If not set, no migration operation will be performed.
  449. MigrateRotatingNoticesFilename string
  450. // MigrateDataStoreDirectory indicates the location of the datastore
  451. // directory, as previously configured with the deprecated
  452. // DataStoreDirectory config field. Datastore files found in the specified
  453. // directory will be moved under the data root directory.
  454. //
  455. // Note: see comment for config.Commit() for a description of how file
  456. // migrations are performed.
  457. MigrateDataStoreDirectory string
  458. // MigrateRemoteServerListDownloadFilename indicates the location of
  459. // remote server list download files. The remote server list files found at
  460. // the specified path will be moved under the data root directory.
  461. //
  462. // Note: see comment for config.Commit() for a description of how file
  463. // migrations are performed.
  464. MigrateRemoteServerListDownloadFilename string
  465. // MigrateObfuscatedServerListDownloadDirectory indicates the location of
  466. // the obfuscated server list downloads directory, as previously configured
  467. // with ObfuscatedServerListDownloadDirectory. Obfuscated server list
  468. // download files found in the specified directory will be moved under the
  469. // data root directory.
  470. //
  471. // Warning: if the directory is empty after obfuscated server
  472. // list files are moved, then it will be deleted.
  473. //
  474. // Note: see comment for config.Commit() for a description of how file
  475. // migrations are performed.
  476. MigrateObfuscatedServerListDownloadDirectory string
  477. // MigrateUpgradeDownloadFilename indicates the location of downloaded
  478. // application upgrade files. Downloaded upgrade files found at the
  479. // specified path will be moved under the data root directory.
  480. //
  481. // Note: see comment for config.Commit() for a description of how file
  482. // migrations are performed.
  483. MigrateUpgradeDownloadFilename string
  484. //
  485. // The following parameters are deprecated.
  486. //
  487. // DataStoreDirectory is the directory in which to store the persistent
  488. // database, which contains information such as server entries. By
  489. // default, current working directory.
  490. //
  491. // Deprecated:
  492. // Use MigrateDataStoreDirectory. When MigrateDataStoreDirectory
  493. // is set, this parameter is ignored.
  494. //
  495. // DataStoreDirectory has been subsumed by the new data root directory,
  496. // which is configured with DataRootDirectory. If set, datastore files
  497. // found in the specified directory will be moved under the data root
  498. // directory.
  499. DataStoreDirectory string
  500. // RemoteServerListDownloadFilename specifies a target filename for
  501. // storing the remote server list download. Data is stored in co-located
  502. // files (RemoteServerListDownloadFilename.part*) to allow for resumable
  503. // downloading.
  504. //
  505. // Deprecated:
  506. // Use MigrateRemoteServerListDownloadFilename. When
  507. // MigrateRemoteServerListDownloadFilename is set, this parameter is
  508. // ignored.
  509. //
  510. // If set, remote server list download files found at the specified path
  511. // will be moved under the data root directory.
  512. RemoteServerListDownloadFilename string
  513. // ObfuscatedServerListDownloadDirectory specifies a target directory for
  514. // storing the obfuscated remote server list downloads. Data is stored in
  515. // co-located files (<OSL filename>.part*) to allow for resumable
  516. // downloading.
  517. //
  518. // Deprecated:
  519. // Use MigrateObfuscatedServerListDownloadDirectory. When
  520. // MigrateObfuscatedServerListDownloadDirectory is set, this parameter is
  521. // ignored.
  522. //
  523. // If set, obfuscated server list download files found at the specified path
  524. // will be moved under the data root directory.
  525. ObfuscatedServerListDownloadDirectory string
  526. // UpgradeDownloadFilename is the local target filename for an upgrade
  527. // download. This parameter is required when UpgradeDownloadURLs (or
  528. // UpgradeDownloadUrl) is specified. Data is stored in co-located files
  529. // (UpgradeDownloadFilename.part*) to allow for resumable downloading.
  530. //
  531. // Deprecated:
  532. // Use MigrateUpgradeDownloadFilename. When MigrateUpgradeDownloadFilename
  533. // is set, this parameter is ignored.
  534. //
  535. // If set, upgrade download files found at the specified path will be moved
  536. // under the data root directory.
  537. UpgradeDownloadFilename string
  538. // TunnelProtocol indicates which protocol to use. For the default, "",
  539. // all protocols are used.
  540. //
  541. // Deprecated: Use LimitTunnelProtocols. When LimitTunnelProtocols is not
  542. // nil, this parameter is ignored.
  543. TunnelProtocol string
  544. // Deprecated: Use CustomHeaders. When CustomHeaders is not nil, this
  545. // parameter is ignored.
  546. UpstreamProxyCustomHeaders http.Header
  547. // RemoteServerListUrl is a URL which specifies a location to fetch out-
  548. // of-band server entries. This facility is used when a tunnel cannot be
  549. // established to known servers. This value is supplied by and depends on
  550. // the Psiphon Network, and is typically embedded in the client binary.
  551. //
  552. // Deprecated: Use RemoteServerListURLs. When RemoteServerListURLs is not
  553. // nil, this parameter is ignored.
  554. RemoteServerListUrl string
  555. // ObfuscatedServerListRootURL is a URL which specifies the root location
  556. // from which to fetch obfuscated server list files. This value is
  557. // supplied by and depends on the Psiphon Network, and is typically
  558. // embedded in the client binary.
  559. //
  560. // Deprecated: Use ObfuscatedServerListRootURLs. When
  561. // ObfuscatedServerListRootURLs is not nil, this parameter is ignored.
  562. ObfuscatedServerListRootURL string
  563. // UpgradeDownloadUrl specifies a URL from which to download a host client
  564. // upgrade file, when one is available. The core tunnel controller
  565. // provides a resumable download facility which downloads this resource
  566. // and emits a notice when complete. This value is supplied by and depends
  567. // on the Psiphon Network, and is typically embedded in the client binary.
  568. //
  569. // Deprecated: Use UpgradeDownloadURLs. When UpgradeDownloadURLs is not
  570. // nil, this parameter is ignored.
  571. UpgradeDownloadUrl string
  572. //
  573. // The following parameters are for testing purposes.
  574. //
  575. // TransformHostNameProbability is for testing purposes.
  576. TransformHostNameProbability *float64
  577. // FragmentorProbability and associated Fragmentor fields are for testing
  578. // purposes.
  579. FragmentorProbability *float64
  580. FragmentorLimitProtocols []string
  581. FragmentorMinTotalBytes *int
  582. FragmentorMaxTotalBytes *int
  583. FragmentorMinWriteBytes *int
  584. FragmentorMaxWriteBytes *int
  585. FragmentorMinDelayMicroseconds *int
  586. FragmentorMaxDelayMicroseconds *int
  587. // MeekTrafficShapingProbability and associated fields are for testing
  588. // purposes.
  589. MeekTrafficShapingProbability *float64
  590. MeekTrafficShapingLimitProtocols []string
  591. MeekMinTLSPadding *int
  592. MeekMaxTLSPadding *int
  593. MeekMinLimitRequestPayloadLength *int
  594. MeekMaxLimitRequestPayloadLength *int
  595. MeekRedialTLSProbability *float64
  596. MeekAlternateCookieNameProbability *float64
  597. MeekAlternateContentTypeProbability *float64
  598. // ObfuscatedSSHAlgorithms and associated ObfuscatedSSH fields are for
  599. // testing purposes. If specified, ObfuscatedSSHAlgorithms must have 4 SSH
  600. // KEX elements in order: the kex algorithm, cipher, MAC, and server host
  601. // key algorithm.
  602. ObfuscatedSSHAlgorithms []string
  603. ObfuscatedSSHMinPadding *int
  604. ObfuscatedSSHMaxPadding *int
  605. // LivenessTestMinUpstreamBytes and other LivenessTest fields are for
  606. // testing purposes.
  607. LivenessTestMinUpstreamBytes *int
  608. LivenessTestMaxUpstreamBytes *int
  609. LivenessTestMinDownstreamBytes *int
  610. LivenessTestMaxDownstreamBytes *int
  611. // ReplayCandidateCount and other Replay fields are for testing purposes.
  612. ReplayCandidateCount *int
  613. ReplayDialParametersTTLSeconds *int
  614. ReplayTargetUpstreamBytes *int
  615. ReplayTargetDownstreamBytes *int
  616. ReplayTargetTunnelDurationSeconds *int
  617. ReplayLaterRoundMoveToFrontProbability *float64
  618. ReplayRetainFailedProbability *float64
  619. // NetworkLatencyMultiplierMin and other NetworkLatencyMultiplier fields are
  620. // for testing purposes.
  621. NetworkLatencyMultiplierMin float64
  622. NetworkLatencyMultiplierMax float64
  623. NetworkLatencyMultiplierLambda float64
  624. // UseOnlyCustomTLSProfiles and other TLS configuration fields are for
  625. // testing purposes.
  626. UseOnlyCustomTLSProfiles *bool
  627. CustomTLSProfiles protocol.CustomTLSProfiles
  628. SelectRandomizedTLSProfileProbability *float64
  629. NoDefaultTLSSessionIDProbability *float64
  630. DisableFrontingProviderTLSProfiles protocol.LabeledTLSProfiles
  631. // ClientBurstUpstreamTargetBytes and other burst metric fields are for
  632. // testing purposes.
  633. ClientBurstUpstreamTargetBytes *int
  634. ClientBurstUpstreamDeadlineMilliseconds *int
  635. ClientBurstDownstreamTargetBytes *int
  636. ClientBurstDownstreamDeadlineMilliseconds *int
  637. // ApplicationParameters is for testing purposes.
  638. ApplicationParameters parameters.KeyValues
  639. // CustomHostNameRegexes and other custom host name fields are for testing
  640. // purposes.
  641. CustomHostNameRegexes []string
  642. CustomHostNameProbability *float64
  643. CustomHostNameLimitProtocols []string
  644. // ConjureCachedRegistrationTTLSeconds and other Conjure fields are for
  645. // testing purposes.
  646. ConjureCachedRegistrationTTLSeconds *int
  647. ConjureAPIRegistrarBidirectionalURL string
  648. ConjureAPIRegistrarFrontingSpecs parameters.FrontingSpecs
  649. ConjureAPIRegistrarMinDelayMilliseconds *int
  650. ConjureAPIRegistrarMaxDelayMilliseconds *int
  651. ConjureDecoyRegistrarProbability *float64
  652. ConjureDecoyRegistrarWidth *int
  653. ConjureDecoyRegistrarMinDelayMilliseconds *int
  654. ConjureDecoyRegistrarMaxDelayMilliseconds *int
  655. // HoldOffTunnelMinDurationMilliseconds and other HoldOffTunnel fields are
  656. // for testing purposes.
  657. HoldOffTunnelMinDurationMilliseconds *int
  658. HoldOffTunnelMaxDurationMilliseconds *int
  659. HoldOffTunnelProtocols []string
  660. HoldOffTunnelFrontingProviderIDs []string
  661. HoldOffTunnelProbability *float64
  662. // RestrictFrontingProviderIDs and other RestrictFrontingProviderIDs fields
  663. // are for testing purposes.
  664. RestrictFrontingProviderIDs []string
  665. RestrictFrontingProviderIDsClientProbability *float64
  666. // UpstreamProxyAllowAllServerEntrySources is for testing purposes.
  667. UpstreamProxyAllowAllServerEntrySources *bool
  668. // LimitTunnelDialPortNumbers is for testing purposes.
  669. LimitTunnelDialPortNumbers parameters.TunnelProtocolPortLists
  670. // QUICDisablePathMTUDiscoveryProbability is for testing purposes.
  671. QUICDisablePathMTUDiscoveryProbability *float64
  672. // DNSResolverAttemptsPerServer and other DNSResolver fields are for
  673. // testing purposes.
  674. DNSResolverAttemptsPerServer *int
  675. DNSResolverAttemptsPerPreferredServer *int
  676. DNSResolverRequestTimeoutMilliseconds *int
  677. DNSResolverAwaitTimeoutMilliseconds *int
  678. DNSResolverPreresolvedIPAddressCIDRs parameters.LabeledCIDRs
  679. DNSResolverPreresolvedIPAddressProbability *float64
  680. DNSResolverAlternateServers []string
  681. DNSResolverPreferredAlternateServers []string
  682. DNSResolverPreferAlternateServerProbability *float64
  683. DNSResolverProtocolTransformSpecs transforms.Specs
  684. DNSResolverProtocolTransformScopedSpecNames transforms.ScopedSpecNames
  685. DNSResolverProtocolTransformProbability *float64
  686. DNSResolverIncludeEDNS0Probability *float64
  687. DNSResolverCacheExtensionInitialTTLMilliseconds *int
  688. DNSResolverCacheExtensionVerifiedTTLMilliseconds *int
  689. // params is the active parameters.Parameters with defaults, config values,
  690. // and, optionally, tactics applied.
  691. //
  692. // New tactics must be applied by calling Config.SetParameters; calling
  693. // params.Set directly will fail to add config values.
  694. params *parameters.Parameters
  695. dialParametersHash []byte
  696. dynamicConfigMutex sync.Mutex
  697. sponsorID string
  698. authorizations []string
  699. deviceBinder DeviceBinder
  700. networkIDGetter NetworkIDGetter
  701. clientFeatures []string
  702. resolverMutex sync.Mutex
  703. resolver *resolver.Resolver
  704. committed bool
  705. loadTimestamp string
  706. }
  707. // Config field which specifies if notice files should be used and at which
  708. // frequency and size they should be rotated.
  709. //
  710. // If either RotatingFileSize or RotatingSyncFrequency are <= 0, default values
  711. // are used.
  712. //
  713. // See comment for setNoticeFiles in notice.go for further details.
  714. type UseNoticeFiles struct {
  715. RotatingFileSize int
  716. RotatingSyncFrequency int
  717. }
  718. // LoadConfig parses a JSON format Psiphon config JSON string and returns a
  719. // Config struct populated with config values.
  720. //
  721. // The Config struct may then be programmatically populated with additional
  722. // values, including callbacks such as DeviceBinder.
  723. //
  724. // Before using the Config, Commit must be called, which will perform further
  725. // validation and initialize internal data structures.
  726. func LoadConfig(configJson []byte) (*Config, error) {
  727. var config Config
  728. err := json.Unmarshal(configJson, &config)
  729. if err != nil {
  730. return nil, errors.Trace(err)
  731. }
  732. config.loadTimestamp = common.TruncateTimestampToHour(
  733. common.GetCurrentTimestamp())
  734. return &config, nil
  735. }
  736. // IsCommitted checks if Commit was called.
  737. func (config *Config) IsCommitted() bool {
  738. return config.committed
  739. }
  740. // Commit validates Config fields finalizes initialization.
  741. //
  742. // Config fields should not be set after calling Config, as any changes may
  743. // not be reflected in internal data structures.
  744. //
  745. // If migrateFromLegacyFields is set to true, then an attempt to migrate from
  746. // legacy fields is made.
  747. //
  748. // Migration from legacy fields:
  749. // Config fields of the naming Migrate* (e.g. MigrateDataStoreDirectory) specify
  750. // a file migration operation which should be performed. These fields correspond
  751. // to deprecated fields, which previously could be used to specify where Psiphon
  752. // stored different sets of persistent files (e.g. MigrateDataStoreDirectory
  753. // corresponds to the deprecated field DataStoreDirectory).
  754. //
  755. // Psiphon now stores all persistent data under the configurable
  756. // DataRootDirectory (see Config.DataRootDirectory). The deprecated fields, and
  757. // corresponding Migrate* fields, are now used to specify the file or directory
  758. // path where, or under which, persistent files and directories created by
  759. // previous versions of Psiphon exist, so they can be moved under the
  760. // DataRootDirectory.
  761. //
  762. // For each migration operation:
  763. // - In the case of directories that could have defaulted to the current working
  764. // directory, persistent files and directories created by Psiphon are
  765. // precisely targeted to avoid moving files which were not created by Psiphon.
  766. // - If no file is found at the specified path, or an error is encountered while
  767. // migrating the file, then an error is logged and execution continues
  768. // normally.
  769. //
  770. // A sentinel file which signals that file migration has been completed, and
  771. // should not be attempted again, is created under DataRootDirectory after one
  772. // full pass through Commit(), regardless of whether file migration succeeds or
  773. // fails. It is better to not endlessly retry file migrations on each Commit()
  774. // because file system errors are expected to be rare and persistent files will
  775. // be re-populated over time.
  776. func (config *Config) Commit(migrateFromLegacyFields bool) error {
  777. // Do SetEmitDiagnosticNotices first, to ensure config file errors are
  778. // emitted.
  779. if config.EmitDiagnosticNotices {
  780. SetEmitDiagnosticNotices(
  781. true, config.EmitDiagnosticNetworkParameters)
  782. }
  783. // Migrate and set notice files before any operations that may emit an
  784. // error. This is to ensure config file errors are written to file when
  785. // notice files are configured with config.UseNoticeFiles.
  786. //
  787. // Note:
  788. // Errors encountered while configuring the data directory cannot be written
  789. // to notice files. This is because notices files are created within the
  790. // data directory.
  791. if config.DataRootDirectory == "" {
  792. wd, err := os.Getwd()
  793. if err != nil {
  794. return errors.Trace(common.RedactFilePathsError(err))
  795. }
  796. config.DataRootDirectory = wd
  797. }
  798. // Create root directory
  799. dataDirectoryPath := config.GetPsiphonDataDirectory()
  800. if !common.FileExists(dataDirectoryPath) {
  801. err := os.Mkdir(dataDirectoryPath, os.ModePerm)
  802. if err != nil {
  803. return errors.Tracef(
  804. "failed to create datastore directory with error: %s",
  805. common.RedactFilePathsError(err, dataDirectoryPath))
  806. }
  807. }
  808. // Check if the migration from legacy config fields has already been
  809. // completed. See the Migrate* config fields for more details.
  810. migrationCompleteFilePath := filepath.Join(config.GetPsiphonDataDirectory(), "migration_complete")
  811. needMigration := !common.FileExists(migrationCompleteFilePath)
  812. // Collect notices to emit them after notice files are set
  813. var noticeMigrationAlertMsgs []string
  814. var noticeMigrationInfoMsgs []string
  815. // Migrate notices first to ensure notice files are used for notices if
  816. // UseNoticeFiles is set.
  817. homepageFilePath := config.GetHomePageFilename()
  818. noticesFilePath := config.GetNoticesFilename()
  819. if migrateFromLegacyFields {
  820. if needMigration {
  821. // Move notice files that exist at legacy file paths under the data root
  822. // directory.
  823. noticeMigrationInfoMsgs = append(noticeMigrationInfoMsgs, "Config migration: need migration")
  824. noticeMigrations := migrationsFromLegacyNoticeFilePaths(config)
  825. successfulMigrations := 0
  826. for _, migration := range noticeMigrations {
  827. err := DoFileMigration(migration)
  828. if err != nil {
  829. alertMsg := fmt.Sprintf("Config migration: %s", errors.Trace(err))
  830. noticeMigrationAlertMsgs = append(noticeMigrationAlertMsgs, alertMsg)
  831. } else {
  832. successfulMigrations += 1
  833. }
  834. }
  835. infoMsg := fmt.Sprintf("Config migration: %d/%d notice files successfully migrated", successfulMigrations, len(noticeMigrations))
  836. noticeMigrationInfoMsgs = append(noticeMigrationInfoMsgs, infoMsg)
  837. } else {
  838. noticeMigrationInfoMsgs = append(noticeMigrationInfoMsgs, "Config migration: migration already completed")
  839. }
  840. }
  841. if config.UseNoticeFiles != nil {
  842. setNoticeFiles(
  843. homepageFilePath,
  844. noticesFilePath,
  845. config.UseNoticeFiles.RotatingFileSize,
  846. config.UseNoticeFiles.RotatingSyncFrequency)
  847. }
  848. // Emit notices now that notice files are set if configured
  849. for _, msg := range noticeMigrationAlertMsgs {
  850. NoticeWarning(msg)
  851. }
  852. for _, msg := range noticeMigrationInfoMsgs {
  853. NoticeInfo(msg)
  854. }
  855. // Promote legacy fields.
  856. if config.CustomHeaders == nil {
  857. config.CustomHeaders = config.UpstreamProxyCustomHeaders
  858. config.UpstreamProxyCustomHeaders = nil
  859. }
  860. if config.RemoteServerListUrl != "" && config.RemoteServerListURLs == nil {
  861. config.RemoteServerListURLs = promoteLegacyTransferURL(config.RemoteServerListUrl)
  862. }
  863. if config.ObfuscatedServerListRootURL != "" && config.ObfuscatedServerListRootURLs == nil {
  864. config.ObfuscatedServerListRootURLs = promoteLegacyTransferURL(config.ObfuscatedServerListRootURL)
  865. }
  866. if config.UpgradeDownloadUrl != "" && config.UpgradeDownloadURLs == nil {
  867. config.UpgradeDownloadURLs = promoteLegacyTransferURL(config.UpgradeDownloadUrl)
  868. }
  869. if config.TunnelProtocol != "" && len(config.LimitTunnelProtocols) == 0 {
  870. config.LimitTunnelProtocols = []string{config.TunnelProtocol}
  871. }
  872. if config.DataStoreDirectory != "" && config.MigrateDataStoreDirectory == "" {
  873. config.MigrateDataStoreDirectory = config.DataStoreDirectory
  874. }
  875. if config.RemoteServerListDownloadFilename != "" && config.MigrateRemoteServerListDownloadFilename == "" {
  876. config.MigrateRemoteServerListDownloadFilename = config.RemoteServerListDownloadFilename
  877. }
  878. if config.ObfuscatedServerListDownloadDirectory != "" && config.MigrateObfuscatedServerListDownloadDirectory == "" {
  879. config.MigrateObfuscatedServerListDownloadDirectory = config.ObfuscatedServerListDownloadDirectory
  880. }
  881. if config.UpgradeDownloadFilename != "" && config.MigrateUpgradeDownloadFilename == "" {
  882. config.MigrateUpgradeDownloadFilename = config.UpgradeDownloadFilename
  883. }
  884. // Supply default values.
  885. // Create datastore directory.
  886. dataStoreDirectoryPath := config.GetDataStoreDirectory()
  887. if !common.FileExists(dataStoreDirectoryPath) {
  888. err := os.Mkdir(dataStoreDirectoryPath, os.ModePerm)
  889. if err != nil {
  890. return errors.Tracef(
  891. "failed to create datastore directory with error: %s",
  892. common.RedactFilePathsError(err, dataStoreDirectoryPath))
  893. }
  894. }
  895. // Create OSL directory.
  896. oslDirectoryPath := config.GetObfuscatedServerListDownloadDirectory()
  897. if !common.FileExists(oslDirectoryPath) {
  898. err := os.Mkdir(oslDirectoryPath, os.ModePerm)
  899. if err != nil {
  900. return errors.Tracef(
  901. "failed to create osl directory with error: %s",
  902. common.RedactFilePathsError(err, oslDirectoryPath))
  903. }
  904. }
  905. if config.ClientVersion == "" {
  906. config.ClientVersion = "0"
  907. }
  908. if config.TunnelPoolSize == 0 {
  909. config.TunnelPoolSize = TUNNEL_POOL_SIZE
  910. }
  911. // Validate config fields.
  912. if !common.FileExists(config.DataRootDirectory) {
  913. return errors.TraceNew("DataRootDirectory does not exist")
  914. }
  915. if config.PropagationChannelId == "" {
  916. return errors.TraceNew("propagation channel ID is missing from the configuration file")
  917. }
  918. if config.SponsorId == "" {
  919. return errors.TraceNew("sponsor ID is missing from the configuration file")
  920. }
  921. _, err := strconv.Atoi(config.ClientVersion)
  922. if err != nil {
  923. return errors.Tracef("invalid client version: %s", err)
  924. }
  925. if !common.Contains(
  926. []string{"", protocol.PSIPHON_SSH_API_PROTOCOL, protocol.PSIPHON_WEB_API_PROTOCOL},
  927. config.TargetApiProtocol) {
  928. return errors.TraceNew("invalid TargetApiProtocol")
  929. }
  930. if !config.DisableRemoteServerListFetcher {
  931. if config.RemoteServerListURLs != nil {
  932. if config.RemoteServerListSignaturePublicKey == "" {
  933. return errors.TraceNew("missing RemoteServerListSignaturePublicKey")
  934. }
  935. }
  936. if config.ObfuscatedServerListRootURLs != nil {
  937. if config.RemoteServerListSignaturePublicKey == "" {
  938. return errors.TraceNew("missing RemoteServerListSignaturePublicKey")
  939. }
  940. }
  941. }
  942. if config.UpgradeDownloadURLs != nil {
  943. if config.UpgradeDownloadClientVersionHeader == "" {
  944. return errors.TraceNew("missing UpgradeDownloadClientVersionHeader")
  945. }
  946. }
  947. if config.FeedbackUploadURLs != nil {
  948. if config.FeedbackEncryptionPublicKey == "" {
  949. return errors.TraceNew("missing FeedbackEncryptionPublicKey")
  950. }
  951. }
  952. // This constraint is expected by logic in Controller.runTunnels().
  953. if config.PacketTunnelTunFileDescriptor > 0 && config.TunnelPoolSize != 1 {
  954. return errors.TraceNew("packet tunnel mode requires TunnelPoolSize to be 1")
  955. }
  956. // SessionID must be PSIPHON_API_CLIENT_SESSION_ID_LENGTH lowercase hex-encoded bytes.
  957. if config.SessionID == "" {
  958. sessionID, err := MakeSessionId()
  959. if err != nil {
  960. return errors.Trace(err)
  961. }
  962. config.SessionID = sessionID
  963. }
  964. if len(config.SessionID) != 2*protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH ||
  965. -1 != strings.IndexFunc(config.SessionID, func(c rune) bool {
  966. return !unicode.Is(unicode.ASCII_Hex_Digit, c) || unicode.IsUpper(c)
  967. }) {
  968. return errors.TraceNew("invalid SessionID")
  969. }
  970. config.params, err = parameters.NewParameters(
  971. func(err error) {
  972. NoticeWarning("Parameters getValue failed: %s", err)
  973. })
  974. if err != nil {
  975. return errors.Trace(err)
  976. }
  977. if config.ObfuscatedSSHAlgorithms != nil &&
  978. len(config.ObfuscatedSSHAlgorithms) != 4 {
  979. // TODO: validate each algorithm?
  980. return errors.TraceNew("invalid ObfuscatedSSHAlgorithms")
  981. }
  982. // parametersParameters.Set will validate the config fields applied to
  983. // parametersParameters.
  984. err = config.SetParameters("", false, nil)
  985. if err != nil {
  986. return errors.Trace(err)
  987. }
  988. // Calculate and set the dial parameters hash. After this point, related
  989. // config fields must not change.
  990. config.setDialParametersHash()
  991. // Set defaults for dynamic config fields.
  992. config.SetDynamicConfig(config.SponsorId, config.Authorizations)
  993. // Initialize config.deviceBinder and config.config.networkIDGetter. These
  994. // wrap config.DeviceBinder and config.NetworkIDGetter/NetworkID with
  995. // loggers.
  996. //
  997. // New variables are set to avoid mutating input config fields.
  998. // Internally, code must use config.deviceBinder and
  999. // config.networkIDGetter and not the input/exported fields.
  1000. if config.DeviceBinder != nil {
  1001. config.deviceBinder = newLoggingDeviceBinder(config.DeviceBinder)
  1002. }
  1003. networkIDGetter := config.NetworkIDGetter
  1004. if networkIDGetter == nil {
  1005. // Limitation: unlike NetworkIDGetter, which calls back to platform APIs
  1006. // this method of network identification is not dynamic and will not reflect
  1007. // network changes that occur while running.
  1008. if config.NetworkID != "" {
  1009. networkIDGetter = newStaticNetworkGetter(config.NetworkID)
  1010. } else {
  1011. networkIDGetter = newStaticNetworkGetter("UNKNOWN")
  1012. }
  1013. }
  1014. config.networkIDGetter = newLoggingNetworkIDGetter(networkIDGetter)
  1015. // Initialize config.clientFeatures, which adds feature names on top of
  1016. // those specified by the host application in config.ClientFeatures.
  1017. config.clientFeatures = config.ClientFeatures
  1018. feature := "VPN"
  1019. if config.DeviceBinder != nil && !common.Contains(config.clientFeatures, feature) {
  1020. config.clientFeatures = append(config.clientFeatures, feature)
  1021. }
  1022. // Migrate from old config fields. This results in files being moved under
  1023. // a config specified data root directory.
  1024. if migrateFromLegacyFields && needMigration {
  1025. // If unset, set MigrateDataStoreDirectory to the previous default value for
  1026. // DataStoreDirectory to ensure that datastore files are migrated.
  1027. if config.MigrateDataStoreDirectory == "" {
  1028. wd, err := os.Getwd()
  1029. if err != nil {
  1030. return errors.Trace(err)
  1031. }
  1032. NoticeInfo("MigrateDataStoreDirectory unset, using working directory")
  1033. config.MigrateDataStoreDirectory = wd
  1034. }
  1035. // Move files that exist at legacy file paths under the data root
  1036. // directory.
  1037. migrations, err := migrationsFromLegacyFilePaths(config)
  1038. if err != nil {
  1039. return errors.Trace(err)
  1040. }
  1041. // Do migrations
  1042. successfulMigrations := 0
  1043. for _, migration := range migrations {
  1044. err := DoFileMigration(migration)
  1045. if err != nil {
  1046. NoticeWarning("Config migration: %s", errors.Trace(err))
  1047. } else {
  1048. successfulMigrations += 1
  1049. }
  1050. }
  1051. NoticeInfo(fmt.Sprintf(
  1052. "Config migration: %d/%d legacy files successfully migrated",
  1053. successfulMigrations, len(migrations)))
  1054. // Remove OSL directory if empty
  1055. if config.MigrateObfuscatedServerListDownloadDirectory != "" {
  1056. files, err := ioutil.ReadDir(config.MigrateObfuscatedServerListDownloadDirectory)
  1057. if err != nil {
  1058. NoticeWarning(
  1059. "Error reading OSL directory: %s",
  1060. errors.Trace(common.RedactFilePathsError(err, config.MigrateObfuscatedServerListDownloadDirectory)))
  1061. } else if len(files) == 0 {
  1062. err := os.Remove(config.MigrateObfuscatedServerListDownloadDirectory)
  1063. if err != nil {
  1064. NoticeWarning(
  1065. "Error deleting empty OSL directory: %s",
  1066. errors.Trace(common.RedactFilePathsError(err, config.MigrateObfuscatedServerListDownloadDirectory)))
  1067. }
  1068. }
  1069. }
  1070. f, err := os.Create(migrationCompleteFilePath)
  1071. if err != nil {
  1072. NoticeWarning(
  1073. "Config migration: failed to create migration completed file with error %s",
  1074. errors.Trace(common.RedactFilePathsError(err, migrationCompleteFilePath)))
  1075. } else {
  1076. NoticeInfo("Config migration: completed")
  1077. f.Close()
  1078. }
  1079. }
  1080. config.committed = true
  1081. return nil
  1082. }
  1083. // GetParameters returns the current parameters.Parameters.
  1084. func (config *Config) GetParameters() *parameters.Parameters {
  1085. return config.params
  1086. }
  1087. // SetParameters resets the parameters.Parameters to the default values,
  1088. // applies any config file values, and then applies the input parameters (from
  1089. // tactics, etc.)
  1090. //
  1091. // Set skipOnError to false when initially applying only config values, as
  1092. // this will validate the values and should fail. Set skipOnError to true when
  1093. // applying tactics to ignore invalid or unknown parameter values from tactics.
  1094. //
  1095. // In the case of applying tactics, do not call Config.parameters.Set
  1096. // directly as this will not first apply config values.
  1097. //
  1098. // If there is an error, the existing Config.parameters are left
  1099. // entirely unmodified.
  1100. func (config *Config) SetParameters(tag string, skipOnError bool, applyParameters map[string]interface{}) error {
  1101. setParameters := []map[string]interface{}{config.makeConfigParameters()}
  1102. if applyParameters != nil {
  1103. setParameters = append(setParameters, applyParameters)
  1104. }
  1105. counts, err := config.params.Set(tag, skipOnError, setParameters...)
  1106. if err != nil {
  1107. return errors.Trace(err)
  1108. }
  1109. NoticeInfo("applied %v parameters with tag '%s'", counts, tag)
  1110. // Emit certain individual parameter values for quick reference in diagnostics.
  1111. p := config.params.Get()
  1112. NoticeInfo(
  1113. "NetworkLatencyMultiplier Min/Max/Lambda: %f/%f/%f",
  1114. p.Float(parameters.NetworkLatencyMultiplierMin),
  1115. p.Float(parameters.NetworkLatencyMultiplierMax),
  1116. p.Float(parameters.NetworkLatencyMultiplierLambda))
  1117. // Application Parameters are feature flags/config info, delivered as Client
  1118. // Parameters via tactics/etc., to be communicated to the outer application.
  1119. // Emit these now, as notices.
  1120. if p.WeightedCoinFlip(parameters.ApplicationParametersProbability) {
  1121. NoticeApplicationParameters(p.KeyValues(parameters.ApplicationParameters))
  1122. }
  1123. return nil
  1124. }
  1125. // SetResolver sets the current resolver.
  1126. func (config *Config) SetResolver(resolver *resolver.Resolver) {
  1127. config.resolverMutex.Lock()
  1128. defer config.resolverMutex.Unlock()
  1129. config.resolver = resolver
  1130. }
  1131. // GetResolver returns the current resolver. May return nil.
  1132. func (config *Config) GetResolver() *resolver.Resolver {
  1133. config.resolverMutex.Lock()
  1134. defer config.resolverMutex.Unlock()
  1135. return config.resolver
  1136. }
  1137. // SetDynamicConfig sets the current client sponsor ID and authorizations.
  1138. // Invalid values for sponsor ID are ignored. The caller must not modify the
  1139. // input authorizations slice.
  1140. func (config *Config) SetDynamicConfig(sponsorID string, authorizations []string) {
  1141. config.dynamicConfigMutex.Lock()
  1142. defer config.dynamicConfigMutex.Unlock()
  1143. if sponsorID != "" {
  1144. config.sponsorID = sponsorID
  1145. }
  1146. config.authorizations = authorizations
  1147. }
  1148. // GetSponsorID returns the current client sponsor ID.
  1149. func (config *Config) GetSponsorID() string {
  1150. config.dynamicConfigMutex.Lock()
  1151. defer config.dynamicConfigMutex.Unlock()
  1152. return config.sponsorID
  1153. }
  1154. // IsSplitTunnelEnabled indicates if split tunnel mode is enabled, either for
  1155. // the client's own country, a specified list of countries, or both.
  1156. func (config *Config) IsSplitTunnelEnabled() bool {
  1157. return config.SplitTunnelOwnRegion || len(config.SplitTunnelRegions) > 0
  1158. }
  1159. // GetAuthorizations returns the current client authorizations.
  1160. // The caller must not modify the returned slice.
  1161. func (config *Config) GetAuthorizations() []string {
  1162. config.dynamicConfigMutex.Lock()
  1163. defer config.dynamicConfigMutex.Unlock()
  1164. return config.authorizations
  1165. }
  1166. // GetPsiphonDataDirectory returns the directory under which all persistent
  1167. // files should be stored. This directory is created under
  1168. // config.DataRootDirectory. The motivation for an additional directory is that
  1169. // config.DataRootDirectory defaults to the current working directory, which may
  1170. // include non-tunnel-core files that should be excluded from directory-spanning
  1171. // operations (e.g. excluding all tunnel-core files from backup).
  1172. func (config *Config) GetPsiphonDataDirectory() string {
  1173. return filepath.Join(config.DataRootDirectory, PsiphonDataDirectoryName)
  1174. }
  1175. // GetHomePageFilename the path where the homepage notices file will be created.
  1176. func (config *Config) GetHomePageFilename() string {
  1177. return filepath.Join(config.GetPsiphonDataDirectory(), HomepageFilename)
  1178. }
  1179. // GetNoticesFilename returns the path where the notices file will be created.
  1180. // When the file is rotated it will be moved to config.GetOldNoticesFilename().
  1181. func (config *Config) GetNoticesFilename() string {
  1182. return filepath.Join(config.GetPsiphonDataDirectory(), NoticesFilename)
  1183. }
  1184. // GetOldNoticeFilename returns the path where the rotated notices file will be
  1185. // created.
  1186. func (config *Config) GetOldNoticesFilename() string {
  1187. return filepath.Join(config.GetPsiphonDataDirectory(), OldNoticesFilename)
  1188. }
  1189. // GetDataStoreDirectory returns the directory in which the persistent database
  1190. // will be stored. Created in Config.Commit(). The persistent database contains
  1191. // information such as server entries.
  1192. func (config *Config) GetDataStoreDirectory() string {
  1193. return filepath.Join(config.GetPsiphonDataDirectory(), "datastore")
  1194. }
  1195. // GetObfuscatedServerListDownloadDirectory returns the directory in which
  1196. // obfuscated remote server list downloads will be stored. Created in
  1197. // Config.Commit().
  1198. func (config *Config) GetObfuscatedServerListDownloadDirectory() string {
  1199. return filepath.Join(config.GetPsiphonDataDirectory(), "osl")
  1200. }
  1201. // GetRemoteServerListDownloadFilename returns the filename where the remote
  1202. // server list download will be stored. Data is stored in co-located files
  1203. // (RemoteServerListDownloadFilename.part*) to allow for resumable downloading.
  1204. func (config *Config) GetRemoteServerListDownloadFilename() string {
  1205. return filepath.Join(config.GetPsiphonDataDirectory(), "remote_server_list")
  1206. }
  1207. // GetUpgradeDownloadFilename specifies the filename where upgrade downloads
  1208. // will be stored. This filename is valid when UpgradeDownloadURLs
  1209. // (or UpgradeDownloadUrl) is specified. Data is stored in co-located files
  1210. // (UpgradeDownloadFilename.part*) to allow for resumable downloading.
  1211. func (config *Config) GetUpgradeDownloadFilename() string {
  1212. return filepath.Join(config.GetPsiphonDataDirectory(), UpgradeDownloadFilename)
  1213. }
  1214. // UseUpstreamProxy indicates if an upstream proxy has been
  1215. // configured.
  1216. func (config *Config) UseUpstreamProxy() bool {
  1217. return config.UpstreamProxyURL != ""
  1218. }
  1219. // GetNetworkID returns the current network ID. When NetworkIDGetter
  1220. // is set, this calls into the host application; otherwise, a default
  1221. // value is returned.
  1222. func (config *Config) GetNetworkID() string {
  1223. return config.networkIDGetter.GetNetworkID()
  1224. }
  1225. func (config *Config) makeConfigParameters() map[string]interface{} {
  1226. // Build set of config values to apply to parameters.
  1227. //
  1228. // Note: names of some config fields such as
  1229. // StaggerConnectionWorkersMilliseconds and LimitMeekBufferSizes have
  1230. // changed in the parameters. The existing config fields are retained for
  1231. // backwards compatibility.
  1232. applyParameters := make(map[string]interface{})
  1233. // To support platform clients that configure NetworkLatencyMultiplier, set
  1234. // the NetworkLatencyMultiplierMin/NetworkLatencyMultiplierMax range to the
  1235. // specified value. Also set the older NetworkLatencyMultiplier tactic, since
  1236. // that will be used in the case of replaying with dial parameters persisted
  1237. // by an older client version.
  1238. if config.NetworkLatencyMultiplier > 0.0 {
  1239. applyParameters[parameters.NetworkLatencyMultiplier] = config.NetworkLatencyMultiplier
  1240. applyParameters[parameters.NetworkLatencyMultiplierMin] = config.NetworkLatencyMultiplier
  1241. applyParameters[parameters.NetworkLatencyMultiplierMax] = config.NetworkLatencyMultiplier
  1242. }
  1243. if config.NetworkLatencyMultiplierMin > 0.0 {
  1244. applyParameters[parameters.NetworkLatencyMultiplierMin] = config.NetworkLatencyMultiplierMin
  1245. }
  1246. if config.NetworkLatencyMultiplierMax > 0.0 {
  1247. applyParameters[parameters.NetworkLatencyMultiplierMax] = config.NetworkLatencyMultiplierMax
  1248. }
  1249. if config.NetworkLatencyMultiplierLambda > 0.0 {
  1250. applyParameters[parameters.NetworkLatencyMultiplierLambda] = config.NetworkLatencyMultiplierLambda
  1251. }
  1252. if len(config.LimitTunnelProtocols) > 0 {
  1253. applyParameters[parameters.LimitTunnelProtocols] = protocol.TunnelProtocols(config.LimitTunnelProtocols)
  1254. }
  1255. if len(config.InitialLimitTunnelProtocols) > 0 && config.InitialLimitTunnelProtocolsCandidateCount > 0 {
  1256. applyParameters[parameters.InitialLimitTunnelProtocols] = protocol.TunnelProtocols(config.InitialLimitTunnelProtocols)
  1257. applyParameters[parameters.InitialLimitTunnelProtocolsCandidateCount] = config.InitialLimitTunnelProtocolsCandidateCount
  1258. }
  1259. if len(config.LimitTLSProfiles) > 0 {
  1260. applyParameters[parameters.LimitTLSProfiles] = protocol.TunnelProtocols(config.LimitTLSProfiles)
  1261. }
  1262. if len(config.LimitQUICVersions) > 0 {
  1263. applyParameters[parameters.LimitQUICVersions] = protocol.QUICVersions(config.LimitQUICVersions)
  1264. }
  1265. if config.EstablishTunnelTimeoutSeconds != nil {
  1266. applyParameters[parameters.EstablishTunnelTimeout] = fmt.Sprintf("%ds", *config.EstablishTunnelTimeoutSeconds)
  1267. }
  1268. if config.EstablishTunnelServerAffinityGracePeriodMilliseconds != nil {
  1269. applyParameters[parameters.EstablishTunnelServerAffinityGracePeriod] = fmt.Sprintf("%dms", *config.EstablishTunnelServerAffinityGracePeriodMilliseconds)
  1270. }
  1271. if config.EstablishTunnelPausePeriodSeconds != nil {
  1272. applyParameters[parameters.EstablishTunnelPausePeriod] = fmt.Sprintf("%ds", *config.EstablishTunnelPausePeriodSeconds)
  1273. }
  1274. if config.ConnectionWorkerPoolSize != 0 {
  1275. applyParameters[parameters.ConnectionWorkerPoolSize] = config.ConnectionWorkerPoolSize
  1276. }
  1277. if config.TunnelPoolSize != 0 {
  1278. applyParameters[parameters.TunnelPoolSize] = config.TunnelPoolSize
  1279. }
  1280. if config.StaggerConnectionWorkersMilliseconds > 0 {
  1281. applyParameters[parameters.StaggerConnectionWorkersPeriod] = fmt.Sprintf("%dms", config.StaggerConnectionWorkersMilliseconds)
  1282. }
  1283. if config.LimitIntensiveConnectionWorkers > 0 {
  1284. applyParameters[parameters.LimitIntensiveConnectionWorkers] = config.LimitIntensiveConnectionWorkers
  1285. }
  1286. applyParameters[parameters.MeekLimitBufferSizes] = config.LimitMeekBufferSizes
  1287. applyParameters[parameters.IgnoreHandshakeStatsRegexps] = config.IgnoreHandshakeStatsRegexps
  1288. if config.EstablishTunnelTimeoutSeconds != nil {
  1289. applyParameters[parameters.EstablishTunnelTimeout] = fmt.Sprintf("%ds", *config.EstablishTunnelTimeoutSeconds)
  1290. }
  1291. if config.FetchRemoteServerListRetryPeriodMilliseconds != nil {
  1292. applyParameters[parameters.FetchRemoteServerListRetryPeriod] = fmt.Sprintf("%dms", *config.FetchRemoteServerListRetryPeriodMilliseconds)
  1293. }
  1294. if config.FetchUpgradeRetryPeriodMilliseconds != nil {
  1295. applyParameters[parameters.FetchUpgradeRetryPeriod] = fmt.Sprintf("%dms", *config.FetchUpgradeRetryPeriodMilliseconds)
  1296. }
  1297. if !config.DisableRemoteServerListFetcher {
  1298. if config.RemoteServerListURLs != nil {
  1299. applyParameters[parameters.RemoteServerListSignaturePublicKey] = config.RemoteServerListSignaturePublicKey
  1300. applyParameters[parameters.RemoteServerListURLs] = config.RemoteServerListURLs
  1301. }
  1302. if config.ObfuscatedServerListRootURLs != nil {
  1303. applyParameters[parameters.RemoteServerListSignaturePublicKey] = config.RemoteServerListSignaturePublicKey
  1304. applyParameters[parameters.ObfuscatedServerListRootURLs] = config.ObfuscatedServerListRootURLs
  1305. }
  1306. }
  1307. if config.UpgradeDownloadURLs != nil {
  1308. applyParameters[parameters.UpgradeDownloadClientVersionHeader] = config.UpgradeDownloadClientVersionHeader
  1309. applyParameters[parameters.UpgradeDownloadURLs] = config.UpgradeDownloadURLs
  1310. }
  1311. if len(config.FeedbackUploadURLs) > 0 {
  1312. applyParameters[parameters.FeedbackUploadURLs] = config.FeedbackUploadURLs
  1313. }
  1314. if config.FeedbackEncryptionPublicKey != "" {
  1315. applyParameters[parameters.FeedbackEncryptionPublicKey] = config.FeedbackEncryptionPublicKey
  1316. }
  1317. applyParameters[parameters.TunnelRateLimits] = config.RateLimits
  1318. if config.TransformHostNameProbability != nil {
  1319. applyParameters[parameters.TransformHostNameProbability] = *config.TransformHostNameProbability
  1320. }
  1321. if config.FragmentorProbability != nil {
  1322. applyParameters[parameters.FragmentorProbability] = *config.FragmentorProbability
  1323. }
  1324. if len(config.FragmentorLimitProtocols) > 0 {
  1325. applyParameters[parameters.FragmentorLimitProtocols] = protocol.TunnelProtocols(config.FragmentorLimitProtocols)
  1326. }
  1327. if config.FragmentorMinTotalBytes != nil {
  1328. applyParameters[parameters.FragmentorMinTotalBytes] = *config.FragmentorMinTotalBytes
  1329. }
  1330. if config.FragmentorMaxTotalBytes != nil {
  1331. applyParameters[parameters.FragmentorMaxTotalBytes] = *config.FragmentorMaxTotalBytes
  1332. }
  1333. if config.FragmentorMinWriteBytes != nil {
  1334. applyParameters[parameters.FragmentorMinWriteBytes] = *config.FragmentorMinWriteBytes
  1335. }
  1336. if config.FragmentorMaxWriteBytes != nil {
  1337. applyParameters[parameters.FragmentorMaxWriteBytes] = *config.FragmentorMaxWriteBytes
  1338. }
  1339. if config.FragmentorMinDelayMicroseconds != nil {
  1340. applyParameters[parameters.FragmentorMinDelay] = fmt.Sprintf("%dus", *config.FragmentorMinDelayMicroseconds)
  1341. }
  1342. if config.FragmentorMaxDelayMicroseconds != nil {
  1343. applyParameters[parameters.FragmentorMaxDelay] = fmt.Sprintf("%dus", *config.FragmentorMaxDelayMicroseconds)
  1344. }
  1345. if config.MeekTrafficShapingProbability != nil {
  1346. applyParameters[parameters.MeekTrafficShapingProbability] = *config.MeekTrafficShapingProbability
  1347. }
  1348. if len(config.MeekTrafficShapingLimitProtocols) > 0 {
  1349. applyParameters[parameters.MeekTrafficShapingLimitProtocols] = protocol.TunnelProtocols(config.MeekTrafficShapingLimitProtocols)
  1350. }
  1351. if config.MeekMinTLSPadding != nil {
  1352. applyParameters[parameters.MeekMinTLSPadding] = *config.MeekMinTLSPadding
  1353. }
  1354. if config.MeekMaxTLSPadding != nil {
  1355. applyParameters[parameters.MeekMaxTLSPadding] = *config.MeekMaxTLSPadding
  1356. }
  1357. if config.MeekMinLimitRequestPayloadLength != nil {
  1358. applyParameters[parameters.MeekMinLimitRequestPayloadLength] = *config.MeekMinLimitRequestPayloadLength
  1359. }
  1360. if config.MeekMaxLimitRequestPayloadLength != nil {
  1361. applyParameters[parameters.MeekMaxLimitRequestPayloadLength] = *config.MeekMaxLimitRequestPayloadLength
  1362. }
  1363. if config.MeekRedialTLSProbability != nil {
  1364. applyParameters[parameters.MeekRedialTLSProbability] = *config.MeekRedialTLSProbability
  1365. }
  1366. if config.MeekAlternateCookieNameProbability != nil {
  1367. applyParameters[parameters.MeekAlternateCookieNameProbability] = *config.MeekAlternateCookieNameProbability
  1368. }
  1369. if config.MeekAlternateContentTypeProbability != nil {
  1370. applyParameters[parameters.MeekAlternateContentTypeProbability] = *config.MeekAlternateContentTypeProbability
  1371. }
  1372. if config.ObfuscatedSSHMinPadding != nil {
  1373. applyParameters[parameters.ObfuscatedSSHMinPadding] = *config.ObfuscatedSSHMinPadding
  1374. }
  1375. if config.ObfuscatedSSHMaxPadding != nil {
  1376. applyParameters[parameters.ObfuscatedSSHMaxPadding] = *config.ObfuscatedSSHMaxPadding
  1377. }
  1378. if config.LivenessTestMinUpstreamBytes != nil {
  1379. applyParameters[parameters.LivenessTestMinUpstreamBytes] = *config.LivenessTestMinUpstreamBytes
  1380. }
  1381. if config.LivenessTestMaxUpstreamBytes != nil {
  1382. applyParameters[parameters.LivenessTestMaxUpstreamBytes] = *config.LivenessTestMaxUpstreamBytes
  1383. }
  1384. if config.LivenessTestMinDownstreamBytes != nil {
  1385. applyParameters[parameters.LivenessTestMinDownstreamBytes] = *config.LivenessTestMinDownstreamBytes
  1386. }
  1387. if config.LivenessTestMaxDownstreamBytes != nil {
  1388. applyParameters[parameters.LivenessTestMaxDownstreamBytes] = *config.LivenessTestMaxDownstreamBytes
  1389. }
  1390. if config.ReplayCandidateCount != nil {
  1391. applyParameters[parameters.ReplayCandidateCount] = *config.ReplayCandidateCount
  1392. }
  1393. if config.ReplayDialParametersTTLSeconds != nil {
  1394. applyParameters[parameters.ReplayDialParametersTTL] = fmt.Sprintf("%ds", *config.ReplayDialParametersTTLSeconds)
  1395. }
  1396. if config.ReplayTargetUpstreamBytes != nil {
  1397. applyParameters[parameters.ReplayTargetUpstreamBytes] = *config.ReplayTargetUpstreamBytes
  1398. }
  1399. if config.ReplayTargetDownstreamBytes != nil {
  1400. applyParameters[parameters.ReplayTargetDownstreamBytes] = *config.ReplayTargetDownstreamBytes
  1401. }
  1402. if config.ReplayTargetTunnelDurationSeconds != nil {
  1403. applyParameters[parameters.ReplayTargetTunnelDuration] = fmt.Sprintf("%ds", *config.ReplayTargetTunnelDurationSeconds)
  1404. }
  1405. if config.ReplayLaterRoundMoveToFrontProbability != nil {
  1406. applyParameters[parameters.ReplayLaterRoundMoveToFrontProbability] = *config.ReplayLaterRoundMoveToFrontProbability
  1407. }
  1408. if config.ReplayRetainFailedProbability != nil {
  1409. applyParameters[parameters.ReplayRetainFailedProbability] = *config.ReplayRetainFailedProbability
  1410. }
  1411. if config.UseOnlyCustomTLSProfiles != nil {
  1412. applyParameters[parameters.UseOnlyCustomTLSProfiles] = *config.UseOnlyCustomTLSProfiles
  1413. }
  1414. if len(config.CustomTLSProfiles) > 0 {
  1415. applyParameters[parameters.CustomTLSProfiles] = config.CustomTLSProfiles
  1416. }
  1417. if config.SelectRandomizedTLSProfileProbability != nil {
  1418. applyParameters[parameters.SelectRandomizedTLSProfileProbability] = *config.SelectRandomizedTLSProfileProbability
  1419. }
  1420. if config.NoDefaultTLSSessionIDProbability != nil {
  1421. applyParameters[parameters.NoDefaultTLSSessionIDProbability] = *config.NoDefaultTLSSessionIDProbability
  1422. }
  1423. if len(config.DisableFrontingProviderTLSProfiles) > 0 {
  1424. applyParameters[parameters.DisableFrontingProviderTLSProfiles] = config.DisableFrontingProviderTLSProfiles
  1425. }
  1426. if config.ClientBurstUpstreamTargetBytes != nil {
  1427. applyParameters[parameters.ClientBurstUpstreamTargetBytes] = *config.ClientBurstUpstreamTargetBytes
  1428. }
  1429. if config.ClientBurstUpstreamDeadlineMilliseconds != nil {
  1430. applyParameters[parameters.ClientBurstUpstreamDeadline] = fmt.Sprintf("%dms", *config.ClientBurstUpstreamDeadlineMilliseconds)
  1431. }
  1432. if config.ClientBurstDownstreamTargetBytes != nil {
  1433. applyParameters[parameters.ClientBurstDownstreamTargetBytes] = *config.ClientBurstDownstreamTargetBytes
  1434. }
  1435. if config.ClientBurstDownstreamDeadlineMilliseconds != nil {
  1436. applyParameters[parameters.ClientBurstDownstreamDeadline] = fmt.Sprintf("%dms", *config.ClientBurstDownstreamDeadlineMilliseconds)
  1437. }
  1438. if config.ApplicationParameters != nil {
  1439. applyParameters[parameters.ApplicationParameters] = config.ApplicationParameters
  1440. }
  1441. if config.CustomHostNameRegexes != nil {
  1442. applyParameters[parameters.CustomHostNameRegexes] = parameters.RegexStrings(config.CustomHostNameRegexes)
  1443. }
  1444. if config.CustomHostNameProbability != nil {
  1445. applyParameters[parameters.CustomHostNameProbability] = *config.CustomHostNameProbability
  1446. }
  1447. if config.CustomHostNameLimitProtocols != nil {
  1448. applyParameters[parameters.CustomHostNameLimitProtocols] = protocol.TunnelProtocols(config.CustomHostNameLimitProtocols)
  1449. }
  1450. if config.ConjureCachedRegistrationTTLSeconds != nil {
  1451. applyParameters[parameters.ConjureCachedRegistrationTTL] = fmt.Sprintf("%ds", *config.ConjureCachedRegistrationTTLSeconds)
  1452. }
  1453. if config.ConjureAPIRegistrarBidirectionalURL != "" {
  1454. applyParameters[parameters.ConjureAPIRegistrarBidirectionalURL] = config.ConjureAPIRegistrarBidirectionalURL
  1455. }
  1456. if len(config.ConjureAPIRegistrarFrontingSpecs) > 0 {
  1457. applyParameters[parameters.ConjureAPIRegistrarFrontingSpecs] = config.ConjureAPIRegistrarFrontingSpecs
  1458. }
  1459. if config.ConjureAPIRegistrarMinDelayMilliseconds != nil {
  1460. applyParameters[parameters.ConjureAPIRegistrarMinDelay] = fmt.Sprintf("%dms", *config.ConjureAPIRegistrarMinDelayMilliseconds)
  1461. }
  1462. if config.ConjureAPIRegistrarMaxDelayMilliseconds != nil {
  1463. applyParameters[parameters.ConjureAPIRegistrarMaxDelay] = fmt.Sprintf("%dms", *config.ConjureAPIRegistrarMaxDelayMilliseconds)
  1464. }
  1465. if config.ConjureDecoyRegistrarProbability != nil {
  1466. applyParameters[parameters.ConjureDecoyRegistrarProbability] = *config.ConjureDecoyRegistrarProbability
  1467. }
  1468. if config.ConjureDecoyRegistrarWidth != nil {
  1469. applyParameters[parameters.ConjureDecoyRegistrarWidth] = *config.ConjureDecoyRegistrarWidth
  1470. }
  1471. if config.ConjureDecoyRegistrarMinDelayMilliseconds != nil {
  1472. applyParameters[parameters.ConjureDecoyRegistrarMinDelay] = fmt.Sprintf("%dms", *config.ConjureDecoyRegistrarMinDelayMilliseconds)
  1473. }
  1474. if config.ConjureDecoyRegistrarMaxDelayMilliseconds != nil {
  1475. applyParameters[parameters.ConjureDecoyRegistrarMaxDelay] = fmt.Sprintf("%dms", *config.ConjureDecoyRegistrarMaxDelayMilliseconds)
  1476. }
  1477. if config.HoldOffTunnelMinDurationMilliseconds != nil {
  1478. applyParameters[parameters.HoldOffTunnelMinDuration] = fmt.Sprintf("%dms", *config.HoldOffTunnelMinDurationMilliseconds)
  1479. }
  1480. if config.HoldOffTunnelMaxDurationMilliseconds != nil {
  1481. applyParameters[parameters.HoldOffTunnelMaxDuration] = fmt.Sprintf("%dms", *config.HoldOffTunnelMaxDurationMilliseconds)
  1482. }
  1483. if len(config.HoldOffTunnelProtocols) > 0 {
  1484. applyParameters[parameters.HoldOffTunnelProtocols] = protocol.TunnelProtocols(config.HoldOffTunnelProtocols)
  1485. }
  1486. if len(config.HoldOffTunnelFrontingProviderIDs) > 0 {
  1487. applyParameters[parameters.HoldOffTunnelFrontingProviderIDs] = config.HoldOffTunnelFrontingProviderIDs
  1488. }
  1489. if config.HoldOffTunnelProbability != nil {
  1490. applyParameters[parameters.HoldOffTunnelProbability] = *config.HoldOffTunnelProbability
  1491. }
  1492. if len(config.RestrictFrontingProviderIDs) > 0 {
  1493. applyParameters[parameters.RestrictFrontingProviderIDs] = config.RestrictFrontingProviderIDs
  1494. }
  1495. if config.RestrictFrontingProviderIDsClientProbability != nil {
  1496. applyParameters[parameters.RestrictFrontingProviderIDsClientProbability] = *config.RestrictFrontingProviderIDsClientProbability
  1497. }
  1498. if config.UpstreamProxyAllowAllServerEntrySources != nil {
  1499. applyParameters[parameters.UpstreamProxyAllowAllServerEntrySources] = *config.UpstreamProxyAllowAllServerEntrySources
  1500. }
  1501. if len(config.LimitTunnelDialPortNumbers) > 0 {
  1502. applyParameters[parameters.LimitTunnelDialPortNumbers] = config.LimitTunnelDialPortNumbers
  1503. }
  1504. if config.QUICDisablePathMTUDiscoveryProbability != nil {
  1505. applyParameters[parameters.QUICDisableClientPathMTUDiscoveryProbability] = *config.QUICDisablePathMTUDiscoveryProbability
  1506. }
  1507. if config.DNSResolverAttemptsPerServer != nil {
  1508. applyParameters[parameters.DNSResolverAttemptsPerServer] = *config.DNSResolverAttemptsPerServer
  1509. }
  1510. if config.DNSResolverAttemptsPerPreferredServer != nil {
  1511. applyParameters[parameters.DNSResolverAttemptsPerPreferredServer] = *config.DNSResolverAttemptsPerPreferredServer
  1512. }
  1513. if config.DNSResolverRequestTimeoutMilliseconds != nil {
  1514. applyParameters[parameters.DNSResolverRequestTimeout] = fmt.Sprintf("%dms", *config.DNSResolverRequestTimeoutMilliseconds)
  1515. }
  1516. if config.DNSResolverAwaitTimeoutMilliseconds != nil {
  1517. applyParameters[parameters.DNSResolverAwaitTimeout] = fmt.Sprintf("%dms", *config.DNSResolverAwaitTimeoutMilliseconds)
  1518. }
  1519. if config.DNSResolverPreresolvedIPAddressProbability != nil {
  1520. applyParameters[parameters.DNSResolverPreresolvedIPAddressProbability] = *config.DNSResolverPreresolvedIPAddressProbability
  1521. }
  1522. if config.DNSResolverPreresolvedIPAddressCIDRs != nil {
  1523. applyParameters[parameters.DNSResolverPreresolvedIPAddressCIDRs] = config.DNSResolverPreresolvedIPAddressCIDRs
  1524. }
  1525. if config.DNSResolverAlternateServers != nil {
  1526. applyParameters[parameters.DNSResolverAlternateServers] = config.DNSResolverAlternateServers
  1527. }
  1528. if config.DNSResolverPreferredAlternateServers != nil {
  1529. applyParameters[parameters.DNSResolverPreferredAlternateServers] = config.DNSResolverPreferredAlternateServers
  1530. }
  1531. if config.DNSResolverPreferAlternateServerProbability != nil {
  1532. applyParameters[parameters.DNSResolverPreferAlternateServerProbability] = *config.DNSResolverPreferAlternateServerProbability
  1533. }
  1534. if config.DNSResolverProtocolTransformSpecs != nil {
  1535. applyParameters[parameters.DNSResolverProtocolTransformSpecs] = config.DNSResolverProtocolTransformSpecs
  1536. }
  1537. if config.DNSResolverProtocolTransformScopedSpecNames != nil {
  1538. applyParameters[parameters.DNSResolverProtocolTransformScopedSpecNames] = config.DNSResolverProtocolTransformScopedSpecNames
  1539. }
  1540. if config.DNSResolverProtocolTransformProbability != nil {
  1541. applyParameters[parameters.DNSResolverProtocolTransformProbability] = *config.DNSResolverProtocolTransformProbability
  1542. }
  1543. if config.DNSResolverIncludeEDNS0Probability != nil {
  1544. applyParameters[parameters.DNSResolverIncludeEDNS0Probability] = *config.DNSResolverIncludeEDNS0Probability
  1545. }
  1546. if config.DNSResolverCacheExtensionInitialTTLMilliseconds != nil {
  1547. applyParameters[parameters.DNSResolverCacheExtensionInitialTTL] = fmt.Sprintf("%dms", *config.DNSResolverCacheExtensionInitialTTLMilliseconds)
  1548. }
  1549. if config.DNSResolverCacheExtensionVerifiedTTLMilliseconds != nil {
  1550. applyParameters[parameters.DNSResolverCacheExtensionVerifiedTTL] = fmt.Sprintf("%dms", *config.DNSResolverCacheExtensionVerifiedTTLMilliseconds)
  1551. }
  1552. // When adding new config dial parameters that may override tactics, also
  1553. // update setDialParametersHash.
  1554. return applyParameters
  1555. }
  1556. func (config *Config) setDialParametersHash() {
  1557. // Calculate and store a hash of the config values that may impact
  1558. // dial parameters. This hash is used as part of the dial parameters
  1559. // replay mechanism to detect when persisted dial parameters should
  1560. // be discarded due to conflicting config changes.
  1561. //
  1562. // With a couple of minor exceptions, configuring dial parameters via the
  1563. // config is intended for testing only, and so these parameters are expected
  1564. // to be present in test runs only. It remains an important case to discard
  1565. // replay dial parameters when test config parameters are varied.
  1566. //
  1567. // Hashing the parameter names detects some ambiguous hash cases, such as two
  1568. // consecutive int64 parameters, one omitted and one not, that are flipped.
  1569. // The serialization is not completely unambiguous, and the format is
  1570. // currently limited by legacy cases (not invalidating replay dial parameters
  1571. // for production clients is more important than invalidating for test runs).
  1572. // We cannot hash the entire config JSON as it contains non-dial parameter
  1573. // fields which may frequently change across runs.
  1574. //
  1575. // MD5 hash is used solely as a data checksum and not for any security
  1576. // purpose.
  1577. hash := md5.New()
  1578. if len(config.LimitTunnelProtocols) > 0 {
  1579. hash.Write([]byte("LimitTunnelProtocols"))
  1580. for _, protocol := range config.LimitTunnelProtocols {
  1581. hash.Write([]byte(protocol))
  1582. }
  1583. }
  1584. if len(config.InitialLimitTunnelProtocols) > 0 && config.InitialLimitTunnelProtocolsCandidateCount > 0 {
  1585. hash.Write([]byte("InitialLimitTunnelProtocols"))
  1586. for _, protocol := range config.InitialLimitTunnelProtocols {
  1587. hash.Write([]byte(protocol))
  1588. }
  1589. binary.Write(hash, binary.LittleEndian, int64(config.InitialLimitTunnelProtocolsCandidateCount))
  1590. }
  1591. if len(config.LimitTLSProfiles) > 0 {
  1592. hash.Write([]byte("LimitTLSProfiles"))
  1593. for _, profile := range config.LimitTLSProfiles {
  1594. hash.Write([]byte(profile))
  1595. }
  1596. }
  1597. if len(config.LimitQUICVersions) > 0 {
  1598. hash.Write([]byte("LimitQUICVersions"))
  1599. for _, version := range config.LimitQUICVersions {
  1600. hash.Write([]byte(version))
  1601. }
  1602. }
  1603. // Whether a custom User-Agent is specified is a binary flag: when not set,
  1604. // the replay dial parameters value applies. When set, external
  1605. // considerations apply.
  1606. if _, ok := config.CustomHeaders["User-Agent"]; ok {
  1607. hash.Write([]byte("CustomHeaders User-Agent"))
  1608. hash.Write([]byte{1})
  1609. }
  1610. if config.UpstreamProxyURL != "" {
  1611. hash.Write([]byte("UpstreamProxyURL"))
  1612. hash.Write([]byte(config.UpstreamProxyURL))
  1613. }
  1614. if config.TransformHostNameProbability != nil {
  1615. hash.Write([]byte("TransformHostNameProbability"))
  1616. binary.Write(hash, binary.LittleEndian, *config.TransformHostNameProbability)
  1617. }
  1618. if config.FragmentorProbability != nil {
  1619. hash.Write([]byte("FragmentorProbability"))
  1620. binary.Write(hash, binary.LittleEndian, *config.FragmentorProbability)
  1621. }
  1622. if len(config.FragmentorLimitProtocols) > 0 {
  1623. hash.Write([]byte("FragmentorLimitProtocols"))
  1624. for _, protocol := range config.FragmentorLimitProtocols {
  1625. hash.Write([]byte(protocol))
  1626. }
  1627. }
  1628. if config.FragmentorMinTotalBytes != nil {
  1629. hash.Write([]byte("FragmentorMinTotalBytes"))
  1630. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMinTotalBytes))
  1631. }
  1632. if config.FragmentorMaxTotalBytes != nil {
  1633. hash.Write([]byte("FragmentorMaxTotalBytes"))
  1634. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMaxTotalBytes))
  1635. }
  1636. if config.FragmentorMinWriteBytes != nil {
  1637. hash.Write([]byte("FragmentorMinWriteBytes"))
  1638. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMinWriteBytes))
  1639. }
  1640. if config.FragmentorMaxWriteBytes != nil {
  1641. hash.Write([]byte("FragmentorMaxWriteBytes"))
  1642. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMaxWriteBytes))
  1643. }
  1644. if config.FragmentorMinDelayMicroseconds != nil {
  1645. hash.Write([]byte("FragmentorMinDelayMicroseconds"))
  1646. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMinDelayMicroseconds))
  1647. }
  1648. if config.FragmentorMaxDelayMicroseconds != nil {
  1649. hash.Write([]byte("FragmentorMaxDelayMicroseconds"))
  1650. binary.Write(hash, binary.LittleEndian, int64(*config.FragmentorMaxDelayMicroseconds))
  1651. }
  1652. if config.MeekTrafficShapingProbability != nil {
  1653. hash.Write([]byte("MeekTrafficShapingProbability"))
  1654. binary.Write(hash, binary.LittleEndian, int64(*config.MeekTrafficShapingProbability))
  1655. }
  1656. if len(config.MeekTrafficShapingLimitProtocols) > 0 {
  1657. hash.Write([]byte("MeekTrafficShapingLimitProtocols"))
  1658. for _, protocol := range config.MeekTrafficShapingLimitProtocols {
  1659. hash.Write([]byte(protocol))
  1660. }
  1661. }
  1662. if config.MeekMinLimitRequestPayloadLength != nil {
  1663. hash.Write([]byte("MeekMinLimitRequestPayloadLength"))
  1664. binary.Write(hash, binary.LittleEndian, int64(*config.MeekMinLimitRequestPayloadLength))
  1665. }
  1666. if config.MeekMaxLimitRequestPayloadLength != nil {
  1667. hash.Write([]byte("MeekMaxLimitRequestPayloadLength"))
  1668. binary.Write(hash, binary.LittleEndian, int64(*config.MeekMaxLimitRequestPayloadLength))
  1669. }
  1670. if config.MeekRedialTLSProbability != nil {
  1671. hash.Write([]byte("MeekRedialTLSProbability"))
  1672. binary.Write(hash, binary.LittleEndian, *config.MeekRedialTLSProbability)
  1673. }
  1674. if config.ObfuscatedSSHMinPadding != nil {
  1675. hash.Write([]byte("ObfuscatedSSHMinPadding"))
  1676. binary.Write(hash, binary.LittleEndian, int64(*config.ObfuscatedSSHMinPadding))
  1677. }
  1678. if config.ObfuscatedSSHMaxPadding != nil {
  1679. hash.Write([]byte("ObfuscatedSSHMaxPadding"))
  1680. binary.Write(hash, binary.LittleEndian, int64(*config.ObfuscatedSSHMaxPadding))
  1681. }
  1682. if config.LivenessTestMinUpstreamBytes != nil {
  1683. hash.Write([]byte("LivenessTestMinUpstreamBytes"))
  1684. binary.Write(hash, binary.LittleEndian, int64(*config.LivenessTestMinUpstreamBytes))
  1685. }
  1686. if config.LivenessTestMaxUpstreamBytes != nil {
  1687. hash.Write([]byte("LivenessTestMaxUpstreamBytes"))
  1688. binary.Write(hash, binary.LittleEndian, int64(*config.LivenessTestMaxUpstreamBytes))
  1689. }
  1690. if config.LivenessTestMinDownstreamBytes != nil {
  1691. hash.Write([]byte("LivenessTestMinDownstreamBytes"))
  1692. binary.Write(hash, binary.LittleEndian, int64(*config.LivenessTestMinDownstreamBytes))
  1693. }
  1694. if config.LivenessTestMaxDownstreamBytes != nil {
  1695. hash.Write([]byte("LivenessTestMaxDownstreamBytes"))
  1696. binary.Write(hash, binary.LittleEndian, int64(*config.LivenessTestMaxDownstreamBytes))
  1697. }
  1698. // Legacy case: these parameters are included in the hash unconditionally,
  1699. // and so will impact almost all production clients. These parameter names
  1700. // are not hashed since that would invalidate all replay dial parameters for
  1701. // existing clients whose hashes predate the inclusion of parameter names.
  1702. binary.Write(hash, binary.LittleEndian, config.NetworkLatencyMultiplierMin)
  1703. binary.Write(hash, binary.LittleEndian, config.NetworkLatencyMultiplierMax)
  1704. binary.Write(hash, binary.LittleEndian, config.NetworkLatencyMultiplierLambda)
  1705. if config.UseOnlyCustomTLSProfiles != nil {
  1706. hash.Write([]byte("UseOnlyCustomTLSProfiles"))
  1707. binary.Write(hash, binary.LittleEndian, *config.UseOnlyCustomTLSProfiles)
  1708. }
  1709. if len(config.CustomTLSProfiles) > 0 {
  1710. hash.Write([]byte("CustomTLSProfiles"))
  1711. for _, customTLSProfile := range config.CustomTLSProfiles {
  1712. encodedCustomTLSProofile, _ := json.Marshal(customTLSProfile)
  1713. hash.Write(encodedCustomTLSProofile)
  1714. }
  1715. }
  1716. if config.SelectRandomizedTLSProfileProbability != nil {
  1717. hash.Write([]byte("SelectRandomizedTLSProfileProbability"))
  1718. binary.Write(hash, binary.LittleEndian, *config.SelectRandomizedTLSProfileProbability)
  1719. }
  1720. if config.NoDefaultTLSSessionIDProbability != nil {
  1721. hash.Write([]byte("NoDefaultTLSSessionIDProbability"))
  1722. binary.Write(hash, binary.LittleEndian, *config.NoDefaultTLSSessionIDProbability)
  1723. }
  1724. if len(config.DisableFrontingProviderTLSProfiles) > 0 {
  1725. hash.Write([]byte("DisableFrontingProviderTLSProfiles"))
  1726. encodedDisableFrontingProviderTLSProfiles, _ :=
  1727. json.Marshal(config.DisableFrontingProviderTLSProfiles)
  1728. hash.Write(encodedDisableFrontingProviderTLSProfiles)
  1729. }
  1730. if len(config.CustomHostNameRegexes) > 0 {
  1731. hash.Write([]byte("CustomHostNameRegexes"))
  1732. for _, customHostNameRegex := range config.CustomHostNameRegexes {
  1733. hash.Write([]byte(customHostNameRegex))
  1734. }
  1735. }
  1736. if config.CustomHostNameProbability != nil {
  1737. hash.Write([]byte("CustomHostNameProbability"))
  1738. binary.Write(hash, binary.LittleEndian, *config.CustomHostNameProbability)
  1739. }
  1740. if len(config.CustomHostNameLimitProtocols) > 0 {
  1741. hash.Write([]byte("CustomHostNameLimitProtocols"))
  1742. for _, protocol := range config.CustomHostNameLimitProtocols {
  1743. hash.Write([]byte(protocol))
  1744. }
  1745. }
  1746. if config.ConjureCachedRegistrationTTLSeconds != nil {
  1747. hash.Write([]byte("ConjureCachedRegistrationTTLSeconds"))
  1748. binary.Write(hash, binary.LittleEndian, int64(*config.ConjureCachedRegistrationTTLSeconds))
  1749. }
  1750. if config.ConjureAPIRegistrarBidirectionalURL != "" {
  1751. hash.Write([]byte("ConjureAPIRegistrarBidirectionalURL"))
  1752. hash.Write([]byte(config.ConjureAPIRegistrarBidirectionalURL))
  1753. }
  1754. if len(config.ConjureAPIRegistrarFrontingSpecs) > 0 {
  1755. hash.Write([]byte("ConjureAPIRegistrarFrontingSpecs"))
  1756. for _, frontingSpec := range config.ConjureAPIRegistrarFrontingSpecs {
  1757. encodedFrontSpec, _ := json.Marshal(frontingSpec)
  1758. hash.Write(encodedFrontSpec)
  1759. }
  1760. }
  1761. if config.ConjureAPIRegistrarMinDelayMilliseconds != nil {
  1762. hash.Write([]byte("ConjureAPIRegistrarMinDelayMilliseconds"))
  1763. binary.Write(hash, binary.LittleEndian, int64(*config.ConjureAPIRegistrarMinDelayMilliseconds))
  1764. }
  1765. if config.ConjureAPIRegistrarMaxDelayMilliseconds != nil {
  1766. hash.Write([]byte("ConjureAPIRegistrarMaxDelayMilliseconds"))
  1767. binary.Write(hash, binary.LittleEndian, int64(*config.ConjureAPIRegistrarMaxDelayMilliseconds))
  1768. }
  1769. if config.ConjureDecoyRegistrarWidth != nil {
  1770. hash.Write([]byte("ConjureDecoyRegistrarWidth"))
  1771. binary.Write(hash, binary.LittleEndian, int64(*config.ConjureDecoyRegistrarWidth))
  1772. }
  1773. if config.ConjureDecoyRegistrarMinDelayMilliseconds != nil {
  1774. hash.Write([]byte("ConjureDecoyRegistrarMinDelayMilliseconds"))
  1775. binary.Write(hash, binary.LittleEndian, int64(*config.ConjureDecoyRegistrarMinDelayMilliseconds))
  1776. }
  1777. if config.ConjureDecoyRegistrarMaxDelayMilliseconds != nil {
  1778. hash.Write([]byte("ConjureDecoyRegistrarMaxDelayMilliseconds"))
  1779. binary.Write(hash, binary.LittleEndian, int64(*config.ConjureDecoyRegistrarMaxDelayMilliseconds))
  1780. }
  1781. if config.HoldOffTunnelMinDurationMilliseconds != nil {
  1782. hash.Write([]byte("HoldOffTunnelMinDurationMilliseconds"))
  1783. binary.Write(hash, binary.LittleEndian, int64(*config.HoldOffTunnelMinDurationMilliseconds))
  1784. }
  1785. if config.HoldOffTunnelMaxDurationMilliseconds != nil {
  1786. hash.Write([]byte("HoldOffTunnelMaxDurationMilliseconds"))
  1787. binary.Write(hash, binary.LittleEndian, int64(*config.HoldOffTunnelMaxDurationMilliseconds))
  1788. }
  1789. if len(config.HoldOffTunnelProtocols) > 0 {
  1790. hash.Write([]byte("HoldOffTunnelProtocols"))
  1791. for _, protocol := range config.HoldOffTunnelProtocols {
  1792. hash.Write([]byte(protocol))
  1793. }
  1794. }
  1795. if len(config.HoldOffTunnelFrontingProviderIDs) > 0 {
  1796. hash.Write([]byte("HoldOffTunnelFrontingProviderIDs"))
  1797. for _, providerID := range config.HoldOffTunnelFrontingProviderIDs {
  1798. hash.Write([]byte(providerID))
  1799. }
  1800. }
  1801. if config.HoldOffTunnelProbability != nil {
  1802. hash.Write([]byte("HoldOffTunnelProbability"))
  1803. binary.Write(hash, binary.LittleEndian, *config.HoldOffTunnelProbability)
  1804. }
  1805. if len(config.RestrictFrontingProviderIDs) > 0 {
  1806. hash.Write([]byte("RestrictFrontingProviderIDs"))
  1807. for _, providerID := range config.RestrictFrontingProviderIDs {
  1808. hash.Write([]byte(providerID))
  1809. }
  1810. }
  1811. if config.RestrictFrontingProviderIDsClientProbability != nil {
  1812. hash.Write([]byte("RestrictFrontingProviderIDsClientProbability"))
  1813. binary.Write(hash, binary.LittleEndian, *config.RestrictFrontingProviderIDsClientProbability)
  1814. }
  1815. if config.UpstreamProxyAllowAllServerEntrySources != nil {
  1816. hash.Write([]byte("UpstreamProxyAllowAllServerEntrySources"))
  1817. binary.Write(hash, binary.LittleEndian, *config.UpstreamProxyAllowAllServerEntrySources)
  1818. }
  1819. if len(config.LimitTunnelDialPortNumbers) > 0 {
  1820. hash.Write([]byte("LimitTunnelDialPortNumbers"))
  1821. encodedLimitTunnelDialPortNumbers, _ :=
  1822. json.Marshal(config.LimitTunnelDialPortNumbers)
  1823. hash.Write(encodedLimitTunnelDialPortNumbers)
  1824. }
  1825. if config.QUICDisablePathMTUDiscoveryProbability != nil {
  1826. hash.Write([]byte("QUICDisablePathMTUDiscoveryProbability"))
  1827. binary.Write(hash, binary.LittleEndian, *config.QUICDisablePathMTUDiscoveryProbability)
  1828. }
  1829. if config.DNSResolverAttemptsPerServer != nil {
  1830. hash.Write([]byte("DNSResolverAttemptsPerServer"))
  1831. binary.Write(hash, binary.LittleEndian, int64(*config.DNSResolverAttemptsPerServer))
  1832. }
  1833. if config.DNSResolverRequestTimeoutMilliseconds != nil {
  1834. hash.Write([]byte("DNSResolverRequestTimeoutMilliseconds"))
  1835. binary.Write(hash, binary.LittleEndian, int64(*config.DNSResolverRequestTimeoutMilliseconds))
  1836. }
  1837. if config.DNSResolverAwaitTimeoutMilliseconds != nil {
  1838. hash.Write([]byte("DNSResolverAwaitTimeoutMilliseconds"))
  1839. binary.Write(hash, binary.LittleEndian, int64(*config.DNSResolverAwaitTimeoutMilliseconds))
  1840. }
  1841. if config.DNSResolverPreresolvedIPAddressCIDRs != nil {
  1842. hash.Write([]byte("DNSResolverPreresolvedIPAddressCIDRs"))
  1843. encodedDNSResolverPreresolvedIPAddressCIDRs, _ :=
  1844. json.Marshal(config.DNSResolverPreresolvedIPAddressCIDRs)
  1845. hash.Write(encodedDNSResolverPreresolvedIPAddressCIDRs)
  1846. }
  1847. if config.DNSResolverPreresolvedIPAddressProbability != nil {
  1848. hash.Write([]byte("DNSResolverPreresolvedIPAddressProbability"))
  1849. binary.Write(hash, binary.LittleEndian, *config.DNSResolverPreresolvedIPAddressProbability)
  1850. }
  1851. if config.DNSResolverAlternateServers != nil {
  1852. hash.Write([]byte("DNSResolverAlternateServers"))
  1853. for _, server := range config.DNSResolverAlternateServers {
  1854. hash.Write([]byte(server))
  1855. }
  1856. }
  1857. if config.DNSResolverPreferAlternateServerProbability != nil {
  1858. hash.Write([]byte("DNSResolverPreferAlternateServerProbability"))
  1859. binary.Write(hash, binary.LittleEndian, *config.DNSResolverPreferAlternateServerProbability)
  1860. }
  1861. if config.DNSResolverProtocolTransformSpecs != nil {
  1862. hash.Write([]byte("DNSResolverProtocolTransformSpecs"))
  1863. encodedDNSResolverProtocolTransformSpecs, _ :=
  1864. json.Marshal(config.DNSResolverProtocolTransformSpecs)
  1865. hash.Write(encodedDNSResolverProtocolTransformSpecs)
  1866. }
  1867. if config.DNSResolverProtocolTransformScopedSpecNames != nil {
  1868. hash.Write([]byte(""))
  1869. encodedDNSResolverProtocolTransformScopedSpecNames, _ :=
  1870. json.Marshal(config.DNSResolverProtocolTransformScopedSpecNames)
  1871. hash.Write(encodedDNSResolverProtocolTransformScopedSpecNames)
  1872. }
  1873. if config.DNSResolverProtocolTransformProbability != nil {
  1874. hash.Write([]byte("DNSResolverProtocolTransformProbability"))
  1875. binary.Write(hash, binary.LittleEndian, *config.DNSResolverProtocolTransformProbability)
  1876. }
  1877. if config.DNSResolverIncludeEDNS0Probability != nil {
  1878. hash.Write([]byte("DNSResolverIncludeEDNS0Probability"))
  1879. binary.Write(hash, binary.LittleEndian, *config.DNSResolverIncludeEDNS0Probability)
  1880. }
  1881. if config.DNSResolverCacheExtensionInitialTTLMilliseconds != nil {
  1882. hash.Write([]byte("DNSResolverCacheExtensionInitialTTLMilliseconds"))
  1883. binary.Write(hash, binary.LittleEndian, int64(*config.DNSResolverCacheExtensionInitialTTLMilliseconds))
  1884. }
  1885. if config.DNSResolverCacheExtensionVerifiedTTLMilliseconds != nil {
  1886. hash.Write([]byte("DNSResolverCacheExtensionVerifiedTTLMilliseconds"))
  1887. binary.Write(hash, binary.LittleEndian, int64(*config.DNSResolverCacheExtensionVerifiedTTLMilliseconds))
  1888. }
  1889. config.dialParametersHash = hash.Sum(nil)
  1890. }
  1891. func promoteLegacyTransferURL(URL string) parameters.TransferURLs {
  1892. transferURLs := make(parameters.TransferURLs, 1)
  1893. transferURLs[0] = &parameters.TransferURL{
  1894. URL: base64.StdEncoding.EncodeToString([]byte(URL)),
  1895. SkipVerify: false,
  1896. OnlyAfterAttempts: 0,
  1897. }
  1898. return transferURLs
  1899. }
  1900. type loggingDeviceBinder struct {
  1901. d DeviceBinder
  1902. }
  1903. func newLoggingDeviceBinder(d DeviceBinder) *loggingDeviceBinder {
  1904. return &loggingDeviceBinder{d: d}
  1905. }
  1906. func (d *loggingDeviceBinder) BindToDevice(fileDescriptor int) (string, error) {
  1907. deviceInfo, err := d.d.BindToDevice(fileDescriptor)
  1908. if err == nil && deviceInfo != "" {
  1909. NoticeBindToDevice(deviceInfo)
  1910. }
  1911. return deviceInfo, err
  1912. }
  1913. type staticNetworkGetter struct {
  1914. networkID string
  1915. }
  1916. func newStaticNetworkGetter(networkID string) *staticNetworkGetter {
  1917. return &staticNetworkGetter{networkID: networkID}
  1918. }
  1919. func (n *staticNetworkGetter) GetNetworkID() string {
  1920. return n.networkID
  1921. }
  1922. type loggingNetworkIDGetter struct {
  1923. n NetworkIDGetter
  1924. }
  1925. func newLoggingNetworkIDGetter(n NetworkIDGetter) *loggingNetworkIDGetter {
  1926. return &loggingNetworkIDGetter{n: n}
  1927. }
  1928. func (n *loggingNetworkIDGetter) GetNetworkID() string {
  1929. networkID := n.n.GetNetworkID()
  1930. // All PII must appear after the initial "-"
  1931. // See: https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter
  1932. logNetworkID := networkID
  1933. index := strings.Index(logNetworkID, "-")
  1934. if index != -1 {
  1935. logNetworkID = logNetworkID[:index]
  1936. }
  1937. if len(logNetworkID)+1 < len(networkID) {
  1938. // Indicate when additional network info was present after the first "-".
  1939. logNetworkID += "+[redacted]"
  1940. }
  1941. NoticeNetworkID(logNetworkID)
  1942. return networkID
  1943. }
  1944. // migrationsFromLegacyNoticeFilePaths returns the file migrations which must be
  1945. // performed to move notice files from legacy file paths, which were configured
  1946. // with the legacy config fields HomepageNoticesFilename and
  1947. // RotatingNoticesFilename, to the new file paths used by Psiphon which exist
  1948. // under the data root directory.
  1949. func migrationsFromLegacyNoticeFilePaths(config *Config) []FileMigration {
  1950. var noticeMigrations []FileMigration
  1951. if config.MigrateHomepageNoticesFilename != "" {
  1952. noticeMigrations = append(noticeMigrations, FileMigration{
  1953. Name: "hompage",
  1954. OldPath: config.MigrateHomepageNoticesFilename,
  1955. NewPath: config.GetHomePageFilename(),
  1956. })
  1957. }
  1958. if config.MigrateRotatingNoticesFilename != "" {
  1959. migrations := []FileMigration{
  1960. {
  1961. Name: "notices",
  1962. OldPath: config.MigrateRotatingNoticesFilename,
  1963. NewPath: config.GetNoticesFilename(),
  1964. IsDir: false,
  1965. },
  1966. {
  1967. Name: "notices.1",
  1968. OldPath: config.MigrateRotatingNoticesFilename + ".1",
  1969. NewPath: config.GetNoticesFilename() + ".1",
  1970. },
  1971. }
  1972. noticeMigrations = append(noticeMigrations, migrations...)
  1973. }
  1974. return noticeMigrations
  1975. }
  1976. // migrationsFromLegacyFilePaths returns the file migrations which must be
  1977. // performed to move files from legacy file paths, which were configured with
  1978. // legacy config fields, to the new file paths used by Psiphon which exist
  1979. // under the data root directory.
  1980. // Note: an attempt is made to redact any file paths from the returned error.
  1981. func migrationsFromLegacyFilePaths(config *Config) ([]FileMigration, error) {
  1982. migrations := []FileMigration{
  1983. {
  1984. Name: "psiphon.boltdb",
  1985. OldPath: filepath.Join(config.MigrateDataStoreDirectory, "psiphon.boltdb"),
  1986. NewPath: filepath.Join(config.GetDataStoreDirectory(), "psiphon.boltdb"),
  1987. },
  1988. {
  1989. Name: "psiphon.boltdb.lock",
  1990. OldPath: filepath.Join(config.MigrateDataStoreDirectory, "psiphon.boltdb.lock"),
  1991. NewPath: filepath.Join(config.GetDataStoreDirectory(), "psiphon.boltdb.lock"),
  1992. },
  1993. }
  1994. if config.MigrateRemoteServerListDownloadFilename != "" {
  1995. // Migrate remote server list files
  1996. rslMigrations := []FileMigration{
  1997. {
  1998. Name: "remote_server_list",
  1999. OldPath: config.MigrateRemoteServerListDownloadFilename,
  2000. NewPath: config.GetRemoteServerListDownloadFilename(),
  2001. },
  2002. {
  2003. Name: "remote_server_list.part",
  2004. OldPath: config.MigrateRemoteServerListDownloadFilename + ".part",
  2005. NewPath: config.GetRemoteServerListDownloadFilename() + ".part",
  2006. },
  2007. {
  2008. Name: "remote_server_list.part.etag",
  2009. OldPath: config.MigrateRemoteServerListDownloadFilename + ".part.etag",
  2010. NewPath: config.GetRemoteServerListDownloadFilename() + ".part.etag",
  2011. },
  2012. }
  2013. migrations = append(migrations, rslMigrations...)
  2014. }
  2015. if config.MigrateObfuscatedServerListDownloadDirectory != "" {
  2016. // Migrate OSL registry file and downloads
  2017. oslFileRegex, err := regexp.Compile(`^osl-.+$`)
  2018. if err != nil {
  2019. return nil, errors.TraceMsg(err, "failed to compile regex for osl files")
  2020. }
  2021. files, err := ioutil.ReadDir(config.MigrateObfuscatedServerListDownloadDirectory)
  2022. if err != nil {
  2023. NoticeWarning(
  2024. "Migration: failed to read OSL download directory with error %s",
  2025. common.RedactFilePathsError(err, config.MigrateObfuscatedServerListDownloadDirectory))
  2026. } else {
  2027. for _, file := range files {
  2028. if oslFileRegex.MatchString(file.Name()) {
  2029. fileMigration := FileMigration{
  2030. Name: "osl",
  2031. OldPath: filepath.Join(config.MigrateObfuscatedServerListDownloadDirectory, file.Name()),
  2032. NewPath: filepath.Join(config.GetObfuscatedServerListDownloadDirectory(), file.Name()),
  2033. }
  2034. migrations = append(migrations, fileMigration)
  2035. }
  2036. }
  2037. }
  2038. }
  2039. if config.MigrateUpgradeDownloadFilename != "" {
  2040. // Migrate downloaded upgrade files
  2041. oldUpgradeDownloadFilename := filepath.Base(config.MigrateUpgradeDownloadFilename)
  2042. // Create regex for:
  2043. // <old_upgrade_download_filename>
  2044. // <old_upgrade_download_filename>.<client_version_number>
  2045. // <old_upgrade_download_filename>.<client_version_number>.part
  2046. // <old_upgrade_download_filename>.<client_version_number>.part.etag
  2047. upgradeDownloadFileRegex, err := regexp.Compile(`^` + oldUpgradeDownloadFilename + `(\.\d+(\.part(\.etag)?)?)?$`)
  2048. if err != nil {
  2049. return nil, errors.TraceMsg(err, "failed to compile regex for upgrade files")
  2050. }
  2051. upgradeDownloadDir := filepath.Dir(config.MigrateUpgradeDownloadFilename)
  2052. files, err := ioutil.ReadDir(upgradeDownloadDir)
  2053. if err != nil {
  2054. NoticeWarning(
  2055. "Migration: failed to read upgrade download directory with error %s",
  2056. common.RedactFilePathsError(err, upgradeDownloadDir))
  2057. } else {
  2058. for _, file := range files {
  2059. if upgradeDownloadFileRegex.MatchString(file.Name()) {
  2060. oldFileSuffix := strings.TrimPrefix(file.Name(), oldUpgradeDownloadFilename)
  2061. fileMigration := FileMigration{
  2062. Name: "upgrade",
  2063. OldPath: filepath.Join(upgradeDownloadDir, file.Name()),
  2064. NewPath: config.GetUpgradeDownloadFilename() + oldFileSuffix,
  2065. }
  2066. migrations = append(migrations, fileMigration)
  2067. }
  2068. }
  2069. }
  2070. }
  2071. return migrations, nil
  2072. }