config.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. // Package config implements reading and writing of the syncthing configuration file.
  7. package config
  8. import (
  9. "encoding/json"
  10. "encoding/xml"
  11. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "net/url"
  15. "os"
  16. "path"
  17. "sort"
  18. "strings"
  19. "github.com/syncthing/syncthing/lib/protocol"
  20. "github.com/syncthing/syncthing/lib/rand"
  21. "github.com/syncthing/syncthing/lib/upgrade"
  22. "github.com/syncthing/syncthing/lib/util"
  23. )
  24. const (
  25. OldestHandledVersion = 10
  26. CurrentVersion = 19
  27. MaxRescanIntervalS = 365 * 24 * 60 * 60
  28. )
  29. var (
  30. // DefaultListenAddresses should be substituted when the configuration
  31. // contains <listenAddress>default</listenAddress>. This is done by the
  32. // "consumer" of the configuration as we don't want these saved to the
  33. // config.
  34. DefaultListenAddresses = []string{
  35. "tcp://0.0.0.0:22000",
  36. "dynamic+https://relays.syncthing.net/endpoint",
  37. }
  38. // DefaultDiscoveryServersV4 should be substituted when the configuration
  39. // contains <globalAnnounceServer>default-v4</globalAnnounceServer>.
  40. DefaultDiscoveryServersV4 = []string{
  41. "https://discovery-v4-2.syncthing.net/v2/?id=DVU36WY-H3LVZHW-E6LLFRE-YAFN5EL-HILWRYP-OC2M47J-Z4PE62Y-ADIBDQC", // 45.55.230.38, USA
  42. "https://discovery-v4-3.syncthing.net/v2/?id=VK6HNJ3-VVMM66S-HRVWSCR-IXEHL2H-U4AQ4MW-UCPQBWX-J2L2UBK-NVZRDQZ", // 128.199.95.124, Singapore
  43. "https://discovery-v4-4.syncthing.net/v2/?id=LYXKCHX-VI3NYZR-ALCJBHF-WMZYSPK-QG6QJA3-MPFYMSO-U56GTUK-NA2MIAW", // 95.85.19.244, NL
  44. }
  45. // DefaultDiscoveryServersV6 should be substituted when the configuration
  46. // contains <globalAnnounceServer>default-v6</globalAnnounceServer>.
  47. DefaultDiscoveryServersV6 = []string{
  48. "https://discovery-v6-2.syncthing.net/v2/?id=DVU36WY-H3LVZHW-E6LLFRE-YAFN5EL-HILWRYP-OC2M47J-Z4PE62Y-ADIBDQC", // 2604:a880:800:10::182:a001, USA
  49. "https://discovery-v6-3.syncthing.net/v2/?id=VK6HNJ3-VVMM66S-HRVWSCR-IXEHL2H-U4AQ4MW-UCPQBWX-J2L2UBK-NVZRDQZ", // 2400:6180:0:d0::d9:d001, Singapore
  50. "https://discovery-v6-4.syncthing.net/v2/?id=LYXKCHX-VI3NYZR-ALCJBHF-WMZYSPK-QG6QJA3-MPFYMSO-U56GTUK-NA2MIAW", // 2a03:b0c0:0:1010::4ed:3001, NL
  51. }
  52. // DefaultDiscoveryServers should be substituted when the configuration
  53. // contains <globalAnnounceServer>default</globalAnnounceServer>.
  54. DefaultDiscoveryServers = append(DefaultDiscoveryServersV4, DefaultDiscoveryServersV6...)
  55. // DefaultTheme is the default and fallback theme for the web UI.
  56. DefaultTheme = "default"
  57. )
  58. func New(myID protocol.DeviceID) Configuration {
  59. var cfg Configuration
  60. cfg.Version = CurrentVersion
  61. cfg.OriginalVersion = CurrentVersion
  62. util.SetDefaults(&cfg)
  63. util.SetDefaults(&cfg.Options)
  64. util.SetDefaults(&cfg.GUI)
  65. // Can't happen.
  66. if err := cfg.prepare(myID); err != nil {
  67. panic("bug: error in preparing new folder: " + err.Error())
  68. }
  69. return cfg
  70. }
  71. func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  72. var cfg Configuration
  73. util.SetDefaults(&cfg)
  74. util.SetDefaults(&cfg.Options)
  75. util.SetDefaults(&cfg.GUI)
  76. if err := xml.NewDecoder(r).Decode(&cfg); err != nil {
  77. return Configuration{}, err
  78. }
  79. cfg.OriginalVersion = cfg.Version
  80. if err := cfg.prepare(myID); err != nil {
  81. return Configuration{}, err
  82. }
  83. return cfg, nil
  84. }
  85. func ReadJSON(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  86. var cfg Configuration
  87. util.SetDefaults(&cfg)
  88. util.SetDefaults(&cfg.Options)
  89. util.SetDefaults(&cfg.GUI)
  90. bs, err := ioutil.ReadAll(r)
  91. if err != nil {
  92. return Configuration{}, err
  93. }
  94. if err := json.Unmarshal(bs, &cfg); err != nil {
  95. return Configuration{}, err
  96. }
  97. cfg.OriginalVersion = cfg.Version
  98. if err := cfg.prepare(myID); err != nil {
  99. return Configuration{}, err
  100. }
  101. return cfg, nil
  102. }
  103. type Configuration struct {
  104. Version int `xml:"version,attr" json:"version"`
  105. Folders []FolderConfiguration `xml:"folder" json:"folders"`
  106. Devices []DeviceConfiguration `xml:"device" json:"devices"`
  107. GUI GUIConfiguration `xml:"gui" json:"gui"`
  108. Options OptionsConfiguration `xml:"options" json:"options"`
  109. IgnoredDevices []protocol.DeviceID `xml:"ignoredDevice" json:"ignoredDevices"`
  110. XMLName xml.Name `xml:"configuration" json:"-"`
  111. OriginalVersion int `xml:"-" json:"-"` // The version we read from disk, before any conversion
  112. }
  113. func (cfg Configuration) Copy() Configuration {
  114. newCfg := cfg
  115. // Deep copy FolderConfigurations
  116. newCfg.Folders = make([]FolderConfiguration, len(cfg.Folders))
  117. for i := range newCfg.Folders {
  118. newCfg.Folders[i] = cfg.Folders[i].Copy()
  119. }
  120. // Deep copy DeviceConfigurations
  121. newCfg.Devices = make([]DeviceConfiguration, len(cfg.Devices))
  122. for i := range newCfg.Devices {
  123. newCfg.Devices[i] = cfg.Devices[i].Copy()
  124. }
  125. newCfg.Options = cfg.Options.Copy()
  126. // DeviceIDs are values
  127. newCfg.IgnoredDevices = make([]protocol.DeviceID, len(cfg.IgnoredDevices))
  128. copy(newCfg.IgnoredDevices, cfg.IgnoredDevices)
  129. return newCfg
  130. }
  131. func (cfg *Configuration) WriteXML(w io.Writer) error {
  132. e := xml.NewEncoder(w)
  133. e.Indent("", " ")
  134. err := e.Encode(cfg)
  135. if err != nil {
  136. return err
  137. }
  138. _, err = w.Write([]byte("\n"))
  139. return err
  140. }
  141. func (cfg *Configuration) prepare(myID protocol.DeviceID) error {
  142. var myName string
  143. // Ensure this device is present in the config
  144. for _, device := range cfg.Devices {
  145. if device.DeviceID == myID {
  146. goto found
  147. }
  148. }
  149. myName, _ = os.Hostname()
  150. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  151. DeviceID: myID,
  152. Name: myName,
  153. })
  154. found:
  155. if err := cfg.clean(); err != nil {
  156. return err
  157. }
  158. // Ensure that we are part of the devices
  159. for i := range cfg.Folders {
  160. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  161. }
  162. return nil
  163. }
  164. func (cfg *Configuration) clean() error {
  165. util.FillNilSlices(&cfg.Options)
  166. // Initialize any empty slices
  167. if cfg.Folders == nil {
  168. cfg.Folders = []FolderConfiguration{}
  169. }
  170. if cfg.IgnoredDevices == nil {
  171. cfg.IgnoredDevices = []protocol.DeviceID{}
  172. }
  173. if cfg.Options.AlwaysLocalNets == nil {
  174. cfg.Options.AlwaysLocalNets = []string{}
  175. }
  176. if cfg.Options.UnackedNotificationIDs == nil {
  177. cfg.Options.UnackedNotificationIDs = []string{}
  178. }
  179. // Prepare folders and check for duplicates. Duplicates are bad and
  180. // dangerous, can't currently be resolved in the GUI, and shouldn't
  181. // happen when configured by the GUI. We return with an error in that
  182. // situation.
  183. seenFolders := make(map[string]struct{})
  184. for i := range cfg.Folders {
  185. folder := &cfg.Folders[i]
  186. folder.prepare()
  187. if _, ok := seenFolders[folder.ID]; ok {
  188. return fmt.Errorf("duplicate folder ID %q in configuration", folder.ID)
  189. }
  190. seenFolders[folder.ID] = struct{}{}
  191. }
  192. cfg.Options.ListenAddresses = util.UniqueStrings(cfg.Options.ListenAddresses)
  193. cfg.Options.GlobalAnnServers = util.UniqueStrings(cfg.Options.GlobalAnnServers)
  194. if cfg.Version > 0 && cfg.Version < OldestHandledVersion {
  195. l.Warnf("Configuration version %d is deprecated. Attempting best effort conversion, but please verify manually.", cfg.Version)
  196. }
  197. // Upgrade configuration versions as appropriate
  198. if cfg.Version <= 10 {
  199. convertV10V11(cfg)
  200. }
  201. if cfg.Version == 11 {
  202. convertV11V12(cfg)
  203. }
  204. if cfg.Version == 12 {
  205. convertV12V13(cfg)
  206. }
  207. if cfg.Version == 13 {
  208. convertV13V14(cfg)
  209. }
  210. if cfg.Version == 14 {
  211. convertV14V15(cfg)
  212. }
  213. if cfg.Version == 15 {
  214. convertV15V16(cfg)
  215. }
  216. if cfg.Version == 16 {
  217. convertV16V17(cfg)
  218. }
  219. if cfg.Version == 17 {
  220. convertV17V18(cfg)
  221. }
  222. if cfg.Version == 18 {
  223. convertV18V19(cfg)
  224. }
  225. // Build a list of available devices
  226. existingDevices := make(map[protocol.DeviceID]bool)
  227. for _, device := range cfg.Devices {
  228. existingDevices[device.DeviceID] = true
  229. }
  230. // Ensure that the device list is free from duplicates
  231. cfg.Devices = ensureNoDuplicateDevices(cfg.Devices)
  232. sort.Sort(DeviceConfigurationList(cfg.Devices))
  233. // Ensure that any loose devices are not present in the wrong places
  234. // Ensure that there are no duplicate devices
  235. // Ensure that the versioning configuration parameter map is not nil
  236. for i := range cfg.Folders {
  237. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  238. cfg.Folders[i].Devices = ensureNoDuplicateFolderDevices(cfg.Folders[i].Devices)
  239. if cfg.Folders[i].Versioning.Params == nil {
  240. cfg.Folders[i].Versioning.Params = map[string]string{}
  241. }
  242. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  243. }
  244. // An empty address list is equivalent to a single "dynamic" entry
  245. for i := range cfg.Devices {
  246. n := &cfg.Devices[i]
  247. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  248. n.Addresses = []string{"dynamic"}
  249. }
  250. }
  251. // Very short reconnection intervals are annoying
  252. if cfg.Options.ReconnectIntervalS < 5 {
  253. cfg.Options.ReconnectIntervalS = 5
  254. }
  255. if cfg.GUI.APIKey == "" {
  256. cfg.GUI.APIKey = rand.String(32)
  257. }
  258. // The list of ignored devices should not contain any devices that have
  259. // been manually added to the config.
  260. newIgnoredDevices := []protocol.DeviceID{}
  261. for _, dev := range cfg.IgnoredDevices {
  262. if !existingDevices[dev] {
  263. newIgnoredDevices = append(newIgnoredDevices, dev)
  264. }
  265. }
  266. cfg.IgnoredDevices = newIgnoredDevices
  267. return nil
  268. }
  269. func convertV18V19(cfg *Configuration) {
  270. // Triggers a database tweak
  271. cfg.Version = 19
  272. }
  273. func convertV17V18(cfg *Configuration) {
  274. // Do channel selection for existing users. Those who have auto upgrades
  275. // and usage reporting on default to the candidate channel. Others get
  276. // stable.
  277. if cfg.Options.URAccepted > 0 && cfg.Options.AutoUpgradeIntervalH > 0 {
  278. cfg.Options.UpgradeToPreReleases = true
  279. }
  280. // Show a notification to explain what's going on, except if upgrades
  281. // are disabled by compilation or environment variable in which case
  282. // it's not relevant.
  283. if !upgrade.DisabledByCompilation && os.Getenv("STNOUPGRADE") == "" {
  284. cfg.Options.UnackedNotificationIDs = append(cfg.Options.UnackedNotificationIDs, "channelNotification")
  285. }
  286. cfg.Version = 18
  287. }
  288. func convertV16V17(cfg *Configuration) {
  289. for i := range cfg.Folders {
  290. cfg.Folders[i].Fsync = true
  291. }
  292. cfg.Version = 17
  293. }
  294. func convertV15V16(cfg *Configuration) {
  295. // Triggers a database tweak
  296. cfg.Version = 16
  297. }
  298. func convertV14V15(cfg *Configuration) {
  299. // Undo v0.13.0 broken migration
  300. for i, addr := range cfg.Options.GlobalAnnServers {
  301. switch addr {
  302. case "default-v4v2/":
  303. cfg.Options.GlobalAnnServers[i] = "default-v4"
  304. case "default-v6v2/":
  305. cfg.Options.GlobalAnnServers[i] = "default-v6"
  306. }
  307. }
  308. cfg.Version = 15
  309. }
  310. func convertV13V14(cfg *Configuration) {
  311. // Not using the ignore cache is the new default. Disable it on existing
  312. // configurations.
  313. cfg.Options.CacheIgnoredFiles = false
  314. // Migrate UPnP -> NAT options
  315. cfg.Options.NATEnabled = cfg.Options.DeprecatedUPnPEnabled
  316. cfg.Options.DeprecatedUPnPEnabled = false
  317. cfg.Options.NATLeaseM = cfg.Options.DeprecatedUPnPLeaseM
  318. cfg.Options.DeprecatedUPnPLeaseM = 0
  319. cfg.Options.NATRenewalM = cfg.Options.DeprecatedUPnPRenewalM
  320. cfg.Options.DeprecatedUPnPRenewalM = 0
  321. cfg.Options.NATTimeoutS = cfg.Options.DeprecatedUPnPTimeoutS
  322. cfg.Options.DeprecatedUPnPTimeoutS = 0
  323. // Replace the default listen address "tcp://0.0.0.0:22000" with the
  324. // string "default", but only if we also have the default relay pool
  325. // among the relay servers as this is implied by the new "default"
  326. // entry.
  327. hasDefault := false
  328. for _, raddr := range cfg.Options.DeprecatedRelayServers {
  329. if raddr == "dynamic+https://relays.syncthing.net/endpoint" {
  330. for i, addr := range cfg.Options.ListenAddresses {
  331. if addr == "tcp://0.0.0.0:22000" {
  332. cfg.Options.ListenAddresses[i] = "default"
  333. hasDefault = true
  334. break
  335. }
  336. }
  337. break
  338. }
  339. }
  340. // Copy relay addresses into listen addresses.
  341. for _, addr := range cfg.Options.DeprecatedRelayServers {
  342. if hasDefault && addr == "dynamic+https://relays.syncthing.net/endpoint" {
  343. // Skip the default relay address if we already have the
  344. // "default" entry in the list.
  345. continue
  346. }
  347. if addr == "" {
  348. continue
  349. }
  350. cfg.Options.ListenAddresses = append(cfg.Options.ListenAddresses, addr)
  351. }
  352. cfg.Options.DeprecatedRelayServers = nil
  353. // For consistency
  354. sort.Strings(cfg.Options.ListenAddresses)
  355. var newAddrs []string
  356. for _, addr := range cfg.Options.GlobalAnnServers {
  357. uri, err := url.Parse(addr)
  358. if err != nil {
  359. // That's odd. Skip the broken address.
  360. continue
  361. }
  362. if uri.Scheme == "https" {
  363. uri.Path = path.Join(uri.Path, "v2") + "/"
  364. addr = uri.String()
  365. }
  366. newAddrs = append(newAddrs, addr)
  367. }
  368. cfg.Options.GlobalAnnServers = newAddrs
  369. for i, fcfg := range cfg.Folders {
  370. if fcfg.DeprecatedReadOnly {
  371. cfg.Folders[i].Type = FolderTypeSendOnly
  372. } else {
  373. cfg.Folders[i].Type = FolderTypeSendReceive
  374. }
  375. cfg.Folders[i].DeprecatedReadOnly = false
  376. }
  377. // v0.13-beta already had config version 13 but did not get the new URL
  378. if cfg.Options.ReleasesURL == "https://api.github.com/repos/syncthing/syncthing/releases?per_page=30" {
  379. cfg.Options.ReleasesURL = "https://upgrades.syncthing.net/meta.json"
  380. }
  381. cfg.Version = 14
  382. }
  383. func convertV12V13(cfg *Configuration) {
  384. if cfg.Options.ReleasesURL == "https://api.github.com/repos/syncthing/syncthing/releases?per_page=30" {
  385. cfg.Options.ReleasesURL = "https://upgrades.syncthing.net/meta.json"
  386. }
  387. cfg.Version = 13
  388. }
  389. func convertV11V12(cfg *Configuration) {
  390. // Change listen address schema
  391. for i, addr := range cfg.Options.ListenAddresses {
  392. if len(addr) > 0 && !strings.HasPrefix(addr, "tcp://") {
  393. cfg.Options.ListenAddresses[i] = util.Address("tcp", addr)
  394. }
  395. }
  396. for i, device := range cfg.Devices {
  397. for j, addr := range device.Addresses {
  398. if addr != "dynamic" && addr != "" {
  399. cfg.Devices[i].Addresses[j] = util.Address("tcp", addr)
  400. }
  401. }
  402. }
  403. // Use new discovery server
  404. var newDiscoServers []string
  405. var useDefault bool
  406. for _, addr := range cfg.Options.GlobalAnnServers {
  407. if addr == "udp4://announce.syncthing.net:22026" {
  408. useDefault = true
  409. } else if addr == "udp6://announce-v6.syncthing.net:22026" {
  410. useDefault = true
  411. } else {
  412. newDiscoServers = append(newDiscoServers, addr)
  413. }
  414. }
  415. if useDefault {
  416. newDiscoServers = append(newDiscoServers, "default")
  417. }
  418. cfg.Options.GlobalAnnServers = newDiscoServers
  419. // Use new multicast group
  420. if cfg.Options.LocalAnnMCAddr == "[ff32::5222]:21026" {
  421. cfg.Options.LocalAnnMCAddr = "[ff12::8384]:21027"
  422. }
  423. // Use new local discovery port
  424. if cfg.Options.LocalAnnPort == 21025 {
  425. cfg.Options.LocalAnnPort = 21027
  426. }
  427. // Set MaxConflicts to unlimited
  428. for i := range cfg.Folders {
  429. cfg.Folders[i].MaxConflicts = -1
  430. }
  431. cfg.Version = 12
  432. }
  433. func convertV10V11(cfg *Configuration) {
  434. // Set minimum disk free of existing folders to 1%
  435. for i := range cfg.Folders {
  436. cfg.Folders[i].MinDiskFreePct = 1
  437. }
  438. cfg.Version = 11
  439. }
  440. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  441. for _, device := range devices {
  442. if device.DeviceID.Equals(myID) {
  443. return devices
  444. }
  445. }
  446. devices = append(devices, FolderDeviceConfiguration{
  447. DeviceID: myID,
  448. })
  449. return devices
  450. }
  451. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  452. count := len(devices)
  453. i := 0
  454. loop:
  455. for i < count {
  456. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  457. devices[i] = devices[count-1]
  458. count--
  459. continue loop
  460. }
  461. i++
  462. }
  463. return devices[0:count]
  464. }
  465. func ensureNoDuplicateFolderDevices(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  466. count := len(devices)
  467. i := 0
  468. seenDevices := make(map[protocol.DeviceID]bool)
  469. loop:
  470. for i < count {
  471. id := devices[i].DeviceID
  472. if _, ok := seenDevices[id]; ok {
  473. devices[i] = devices[count-1]
  474. count--
  475. continue loop
  476. }
  477. seenDevices[id] = true
  478. i++
  479. }
  480. return devices[0:count]
  481. }
  482. func ensureNoDuplicateDevices(devices []DeviceConfiguration) []DeviceConfiguration {
  483. count := len(devices)
  484. i := 0
  485. seenDevices := make(map[protocol.DeviceID]bool)
  486. loop:
  487. for i < count {
  488. id := devices[i].DeviceID
  489. if _, ok := seenDevices[id]; ok {
  490. devices[i] = devices[count-1]
  491. count--
  492. continue loop
  493. }
  494. seenDevices[id] = true
  495. i++
  496. }
  497. return devices[0:count]
  498. }