config.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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 = 16
  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-1.syncthing.net/v2/?id=SR7AARM-TCBUZ5O-VFAXY4D-CECGSDE-3Q6IZ4G-XG7AH75-OBIXJQV-QJ6NLQA", // 194.126.249.5, Sweden
  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. }
  44. // DefaultDiscoveryServersV6 should be substituted when the configuration
  45. // contains <globalAnnounceServer>default-v6</globalAnnounceServer>.
  46. DefaultDiscoveryServersV6 = []string{
  47. "https://discovery-v6-1.syncthing.net/v2/?id=SR7AARM-TCBUZ5O-VFAXY4D-CECGSDE-3Q6IZ4G-XG7AH75-OBIXJQV-QJ6NLQA", // 2001:470:28:4d6::5, Sweden
  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. }
  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. // Build a list of available devices
  216. existingDevices := make(map[protocol.DeviceID]bool)
  217. for _, device := range cfg.Devices {
  218. existingDevices[device.DeviceID] = true
  219. }
  220. // Ensure that the device list is free from duplicates
  221. cfg.Devices = ensureNoDuplicateDevices(cfg.Devices)
  222. sort.Sort(DeviceConfigurationList(cfg.Devices))
  223. // Ensure that any loose devices are not present in the wrong places
  224. // Ensure that there are no duplicate devices
  225. // Ensure that the versioning configuration parameter map is not nil
  226. for i := range cfg.Folders {
  227. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  228. cfg.Folders[i].Devices = ensureNoDuplicateFolderDevices(cfg.Folders[i].Devices)
  229. if cfg.Folders[i].Versioning.Params == nil {
  230. cfg.Folders[i].Versioning.Params = map[string]string{}
  231. }
  232. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  233. }
  234. // An empty address list is equivalent to a single "dynamic" entry
  235. for i := range cfg.Devices {
  236. n := &cfg.Devices[i]
  237. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  238. n.Addresses = []string{"dynamic"}
  239. }
  240. }
  241. // Very short reconnection intervals are annoying
  242. if cfg.Options.ReconnectIntervalS < 5 {
  243. cfg.Options.ReconnectIntervalS = 5
  244. }
  245. if cfg.GUI.APIKey == "" {
  246. cfg.GUI.APIKey = rand.String(32)
  247. }
  248. // The list of ignored devices should not contain any devices that have
  249. // been manually added to the config.
  250. newIgnoredDevices := []protocol.DeviceID{}
  251. for _, dev := range cfg.IgnoredDevices {
  252. if !existingDevices[dev] {
  253. newIgnoredDevices = append(newIgnoredDevices, dev)
  254. }
  255. }
  256. cfg.IgnoredDevices = newIgnoredDevices
  257. return nil
  258. }
  259. func convertV14V15(cfg *Configuration) {
  260. // Undo v0.13.0 broken migration
  261. for i, addr := range cfg.Options.GlobalAnnServers {
  262. switch addr {
  263. case "default-v4v2/":
  264. cfg.Options.GlobalAnnServers[i] = "default-v4"
  265. case "default-v6v2/":
  266. cfg.Options.GlobalAnnServers[i] = "default-v6"
  267. }
  268. }
  269. cfg.Version = 15
  270. }
  271. func convertV15V16(cfg *Configuration) {
  272. // Triggers a database tweak
  273. cfg.Version = 16
  274. }
  275. func convertV13V14(cfg *Configuration) {
  276. // Not using the ignore cache is the new default. Disable it on existing
  277. // configurations.
  278. cfg.Options.CacheIgnoredFiles = false
  279. // Migrate UPnP -> NAT options
  280. cfg.Options.NATEnabled = cfg.Options.DeprecatedUPnPEnabled
  281. cfg.Options.DeprecatedUPnPEnabled = false
  282. cfg.Options.NATLeaseM = cfg.Options.DeprecatedUPnPLeaseM
  283. cfg.Options.DeprecatedUPnPLeaseM = 0
  284. cfg.Options.NATRenewalM = cfg.Options.DeprecatedUPnPRenewalM
  285. cfg.Options.DeprecatedUPnPRenewalM = 0
  286. cfg.Options.NATTimeoutS = cfg.Options.DeprecatedUPnPTimeoutS
  287. cfg.Options.DeprecatedUPnPTimeoutS = 0
  288. // Replace the default listen address "tcp://0.0.0.0:22000" with the
  289. // string "default", but only if we also have the default relay pool
  290. // among the relay servers as this is implied by the new "default"
  291. // entry.
  292. hasDefault := false
  293. for _, raddr := range cfg.Options.DeprecatedRelayServers {
  294. if raddr == "dynamic+https://relays.syncthing.net/endpoint" {
  295. for i, addr := range cfg.Options.ListenAddresses {
  296. if addr == "tcp://0.0.0.0:22000" {
  297. cfg.Options.ListenAddresses[i] = "default"
  298. hasDefault = true
  299. break
  300. }
  301. }
  302. break
  303. }
  304. }
  305. // Copy relay addresses into listen addresses.
  306. for _, addr := range cfg.Options.DeprecatedRelayServers {
  307. if hasDefault && addr == "dynamic+https://relays.syncthing.net/endpoint" {
  308. // Skip the default relay address if we already have the
  309. // "default" entry in the list.
  310. continue
  311. }
  312. if addr == "" {
  313. continue
  314. }
  315. cfg.Options.ListenAddresses = append(cfg.Options.ListenAddresses, addr)
  316. }
  317. cfg.Options.DeprecatedRelayServers = nil
  318. // For consistency
  319. sort.Strings(cfg.Options.ListenAddresses)
  320. var newAddrs []string
  321. for _, addr := range cfg.Options.GlobalAnnServers {
  322. uri, err := url.Parse(addr)
  323. if err != nil {
  324. // That's odd. Skip the broken address.
  325. continue
  326. }
  327. if uri.Scheme == "https" {
  328. uri.Path = path.Join(uri.Path, "v2") + "/"
  329. addr = uri.String()
  330. }
  331. newAddrs = append(newAddrs, addr)
  332. }
  333. cfg.Options.GlobalAnnServers = newAddrs
  334. for i, fcfg := range cfg.Folders {
  335. if fcfg.DeprecatedReadOnly {
  336. cfg.Folders[i].Type = FolderTypeReadOnly
  337. } else {
  338. cfg.Folders[i].Type = FolderTypeReadWrite
  339. }
  340. cfg.Folders[i].DeprecatedReadOnly = false
  341. }
  342. // v0.13-beta already had config version 13 but did not get the new URL
  343. if cfg.Options.ReleasesURL == "https://api.github.com/repos/syncthing/syncthing/releases?per_page=30" {
  344. cfg.Options.ReleasesURL = "https://upgrades.syncthing.net/meta.json"
  345. }
  346. cfg.Version = 14
  347. }
  348. func convertV12V13(cfg *Configuration) {
  349. if cfg.Options.ReleasesURL == "https://api.github.com/repos/syncthing/syncthing/releases?per_page=30" {
  350. cfg.Options.ReleasesURL = "https://upgrades.syncthing.net/meta.json"
  351. }
  352. cfg.Version = 13
  353. }
  354. func convertV11V12(cfg *Configuration) {
  355. // Change listen address schema
  356. for i, addr := range cfg.Options.ListenAddresses {
  357. if len(addr) > 0 && !strings.HasPrefix(addr, "tcp://") {
  358. cfg.Options.ListenAddresses[i] = util.Address("tcp", addr)
  359. }
  360. }
  361. for i, device := range cfg.Devices {
  362. for j, addr := range device.Addresses {
  363. if addr != "dynamic" && addr != "" {
  364. cfg.Devices[i].Addresses[j] = util.Address("tcp", addr)
  365. }
  366. }
  367. }
  368. // Use new discovery server
  369. var newDiscoServers []string
  370. var useDefault bool
  371. for _, addr := range cfg.Options.GlobalAnnServers {
  372. if addr == "udp4://announce.syncthing.net:22026" {
  373. useDefault = true
  374. } else if addr == "udp6://announce-v6.syncthing.net:22026" {
  375. useDefault = true
  376. } else {
  377. newDiscoServers = append(newDiscoServers, addr)
  378. }
  379. }
  380. if useDefault {
  381. newDiscoServers = append(newDiscoServers, "default")
  382. }
  383. cfg.Options.GlobalAnnServers = newDiscoServers
  384. // Use new multicast group
  385. if cfg.Options.LocalAnnMCAddr == "[ff32::5222]:21026" {
  386. cfg.Options.LocalAnnMCAddr = "[ff12::8384]:21027"
  387. }
  388. // Use new local discovery port
  389. if cfg.Options.LocalAnnPort == 21025 {
  390. cfg.Options.LocalAnnPort = 21027
  391. }
  392. // Set MaxConflicts to unlimited
  393. for i := range cfg.Folders {
  394. cfg.Folders[i].MaxConflicts = -1
  395. }
  396. cfg.Version = 12
  397. }
  398. func convertV10V11(cfg *Configuration) {
  399. // Set minimum disk free of existing folders to 1%
  400. for i := range cfg.Folders {
  401. cfg.Folders[i].MinDiskFreePct = 1
  402. }
  403. cfg.Version = 11
  404. }
  405. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  406. for _, device := range devices {
  407. if device.DeviceID.Equals(myID) {
  408. return devices
  409. }
  410. }
  411. devices = append(devices, FolderDeviceConfiguration{
  412. DeviceID: myID,
  413. })
  414. return devices
  415. }
  416. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  417. count := len(devices)
  418. i := 0
  419. loop:
  420. for i < count {
  421. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  422. devices[i] = devices[count-1]
  423. count--
  424. continue loop
  425. }
  426. i++
  427. }
  428. return devices[0:count]
  429. }
  430. func ensureNoDuplicateFolderDevices(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  431. count := len(devices)
  432. i := 0
  433. seenDevices := make(map[protocol.DeviceID]bool)
  434. loop:
  435. for i < count {
  436. id := devices[i].DeviceID
  437. if _, ok := seenDevices[id]; ok {
  438. devices[i] = devices[count-1]
  439. count--
  440. continue loop
  441. }
  442. seenDevices[id] = true
  443. i++
  444. }
  445. return devices[0:count]
  446. }
  447. func ensureNoDuplicateDevices(devices []DeviceConfiguration) []DeviceConfiguration {
  448. count := len(devices)
  449. i := 0
  450. seenDevices := make(map[protocol.DeviceID]bool)
  451. loop:
  452. for i < count {
  453. id := devices[i].DeviceID
  454. if _, ok := seenDevices[id]; ok {
  455. devices[i] = devices[count-1]
  456. count--
  457. continue loop
  458. }
  459. seenDevices[id] = true
  460. i++
  461. }
  462. return devices[0:count]
  463. }