config.go 116 KB

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