config.go 15 KB

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