config.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 = 15
  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. cfg.prepare(myID)
  65. return cfg
  66. }
  67. func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  68. var cfg Configuration
  69. util.SetDefaults(&cfg)
  70. util.SetDefaults(&cfg.Options)
  71. util.SetDefaults(&cfg.GUI)
  72. if err := xml.NewDecoder(r).Decode(&cfg); err != nil {
  73. return Configuration{}, err
  74. }
  75. cfg.OriginalVersion = cfg.Version
  76. if err := cfg.prepare(myID); err != nil {
  77. return Configuration{}, err
  78. }
  79. return cfg, nil
  80. }
  81. func ReadJSON(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  82. var cfg Configuration
  83. util.SetDefaults(&cfg)
  84. util.SetDefaults(&cfg.Options)
  85. util.SetDefaults(&cfg.GUI)
  86. bs, err := ioutil.ReadAll(r)
  87. if err != nil {
  88. return Configuration{}, err
  89. }
  90. err = json.Unmarshal(bs, &cfg)
  91. cfg.OriginalVersion = cfg.Version
  92. if err := cfg.prepare(myID); err != nil {
  93. return Configuration{}, err
  94. }
  95. return cfg, nil
  96. }
  97. type Configuration struct {
  98. Version int `xml:"version,attr" json:"version"`
  99. Folders []FolderConfiguration `xml:"folder" json:"folders"`
  100. Devices []DeviceConfiguration `xml:"device" json:"devices"`
  101. GUI GUIConfiguration `xml:"gui" json:"gui"`
  102. Options OptionsConfiguration `xml:"options" json:"options"`
  103. IgnoredDevices []protocol.DeviceID `xml:"ignoredDevice" json:"ignoredDevices"`
  104. XMLName xml.Name `xml:"configuration" json:"-"`
  105. OriginalVersion int `xml:"-" json:"-"` // The version we read from disk, before any conversion
  106. }
  107. func (cfg Configuration) Copy() Configuration {
  108. newCfg := cfg
  109. // Deep copy FolderConfigurations
  110. newCfg.Folders = make([]FolderConfiguration, len(cfg.Folders))
  111. for i := range newCfg.Folders {
  112. newCfg.Folders[i] = cfg.Folders[i].Copy()
  113. }
  114. // Deep copy DeviceConfigurations
  115. newCfg.Devices = make([]DeviceConfiguration, len(cfg.Devices))
  116. for i := range newCfg.Devices {
  117. newCfg.Devices[i] = cfg.Devices[i].Copy()
  118. }
  119. newCfg.Options = cfg.Options.Copy()
  120. // DeviceIDs are values
  121. newCfg.IgnoredDevices = make([]protocol.DeviceID, len(cfg.IgnoredDevices))
  122. copy(newCfg.IgnoredDevices, cfg.IgnoredDevices)
  123. return newCfg
  124. }
  125. func (cfg *Configuration) WriteXML(w io.Writer) error {
  126. e := xml.NewEncoder(w)
  127. e.Indent("", " ")
  128. err := e.Encode(cfg)
  129. if err != nil {
  130. return err
  131. }
  132. _, err = w.Write([]byte("\n"))
  133. return err
  134. }
  135. func (cfg *Configuration) prepare(myID protocol.DeviceID) error {
  136. util.FillNilSlices(&cfg.Options)
  137. // Initialize any empty slices
  138. if cfg.Folders == nil {
  139. cfg.Folders = []FolderConfiguration{}
  140. }
  141. if cfg.IgnoredDevices == nil {
  142. cfg.IgnoredDevices = []protocol.DeviceID{}
  143. }
  144. if cfg.Options.AlwaysLocalNets == nil {
  145. cfg.Options.AlwaysLocalNets = []string{}
  146. }
  147. // Prepare folders and check for duplicates. Duplicates are bad and
  148. // dangerous, can't currently be resolved in the GUI, and shouldn't
  149. // happen when configured by the GUI. We return with an error in that
  150. // situation.
  151. seenFolders := make(map[string]struct{})
  152. for i := range cfg.Folders {
  153. folder := &cfg.Folders[i]
  154. folder.prepare()
  155. if _, ok := seenFolders[folder.ID]; ok {
  156. return fmt.Errorf("duplicate folder ID %q in configuration", folder.ID)
  157. }
  158. seenFolders[folder.ID] = struct{}{}
  159. }
  160. cfg.Options.ListenAddresses = util.UniqueStrings(cfg.Options.ListenAddresses)
  161. cfg.Options.GlobalAnnServers = util.UniqueStrings(cfg.Options.GlobalAnnServers)
  162. if cfg.Version > 0 && cfg.Version < OldestHandledVersion {
  163. l.Warnf("Configuration version %d is deprecated. Attempting best effort conversion, but please verify manually.", cfg.Version)
  164. }
  165. // Upgrade configuration versions as appropriate
  166. if cfg.Version <= 10 {
  167. convertV10V11(cfg)
  168. }
  169. if cfg.Version == 11 {
  170. convertV11V12(cfg)
  171. }
  172. if cfg.Version == 12 {
  173. convertV12V13(cfg)
  174. }
  175. if cfg.Version == 13 {
  176. convertV13V14(cfg)
  177. }
  178. if cfg.Version == 14 {
  179. convertV14V15(cfg)
  180. }
  181. // Build a list of available devices
  182. existingDevices := make(map[protocol.DeviceID]bool)
  183. for _, device := range cfg.Devices {
  184. existingDevices[device.DeviceID] = true
  185. }
  186. // Ensure this device is present in the config
  187. if !existingDevices[myID] {
  188. myName, _ := os.Hostname()
  189. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  190. DeviceID: myID,
  191. Name: myName,
  192. })
  193. existingDevices[myID] = true
  194. }
  195. // Ensure that the device list is free from duplicates
  196. cfg.Devices = ensureNoDuplicateDevices(cfg.Devices)
  197. sort.Sort(DeviceConfigurationList(cfg.Devices))
  198. // Ensure that any loose devices are not present in the wrong places
  199. // Ensure that there are no duplicate devices
  200. // Ensure that puller settings are sane
  201. // Ensure that the versioning configuration parameter map is not nil
  202. for i := range cfg.Folders {
  203. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  204. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  205. cfg.Folders[i].Devices = ensureNoDuplicateFolderDevices(cfg.Folders[i].Devices)
  206. if cfg.Folders[i].Versioning.Params == nil {
  207. cfg.Folders[i].Versioning.Params = map[string]string{}
  208. }
  209. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  210. }
  211. // An empty address list is equivalent to a single "dynamic" entry
  212. for i := range cfg.Devices {
  213. n := &cfg.Devices[i]
  214. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  215. n.Addresses = []string{"dynamic"}
  216. }
  217. }
  218. // Very short reconnection intervals are annoying
  219. if cfg.Options.ReconnectIntervalS < 5 {
  220. cfg.Options.ReconnectIntervalS = 5
  221. }
  222. if cfg.GUI.APIKey == "" {
  223. cfg.GUI.APIKey = rand.String(32)
  224. }
  225. return nil
  226. }
  227. func convertV14V15(cfg *Configuration) {
  228. // Undo v0.13.0 broken migration
  229. for i, addr := range cfg.Options.GlobalAnnServers {
  230. switch addr {
  231. case "default-v4v2/":
  232. cfg.Options.GlobalAnnServers[i] = "default-v4"
  233. case "default-v6v2/":
  234. cfg.Options.GlobalAnnServers[i] = "default-v6"
  235. }
  236. }
  237. cfg.Version = 15
  238. }
  239. func convertV13V14(cfg *Configuration) {
  240. // Not using the ignore cache is the new default. Disable it on existing
  241. // configurations.
  242. cfg.Options.CacheIgnoredFiles = false
  243. // Migrate UPnP -> NAT options
  244. cfg.Options.NATEnabled = cfg.Options.DeprecatedUPnPEnabled
  245. cfg.Options.DeprecatedUPnPEnabled = false
  246. cfg.Options.NATLeaseM = cfg.Options.DeprecatedUPnPLeaseM
  247. cfg.Options.DeprecatedUPnPLeaseM = 0
  248. cfg.Options.NATRenewalM = cfg.Options.DeprecatedUPnPRenewalM
  249. cfg.Options.DeprecatedUPnPRenewalM = 0
  250. cfg.Options.NATTimeoutS = cfg.Options.DeprecatedUPnPTimeoutS
  251. cfg.Options.DeprecatedUPnPTimeoutS = 0
  252. // Replace the default listen address "tcp://0.0.0.0:22000" with the
  253. // string "default", but only if we also have the default relay pool
  254. // among the relay servers as this is implied by the new "default"
  255. // entry.
  256. hasDefault := false
  257. for _, raddr := range cfg.Options.DeprecatedRelayServers {
  258. if raddr == "dynamic+https://relays.syncthing.net/endpoint" {
  259. for i, addr := range cfg.Options.ListenAddresses {
  260. if addr == "tcp://0.0.0.0:22000" {
  261. cfg.Options.ListenAddresses[i] = "default"
  262. hasDefault = true
  263. break
  264. }
  265. }
  266. break
  267. }
  268. }
  269. // Copy relay addresses into listen addresses.
  270. for _, addr := range cfg.Options.DeprecatedRelayServers {
  271. if hasDefault && addr == "dynamic+https://relays.syncthing.net/endpoint" {
  272. // Skip the default relay address if we already have the
  273. // "default" entry in the list.
  274. continue
  275. }
  276. if addr == "" {
  277. continue
  278. }
  279. cfg.Options.ListenAddresses = append(cfg.Options.ListenAddresses, addr)
  280. }
  281. cfg.Options.DeprecatedRelayServers = nil
  282. // For consistency
  283. sort.Strings(cfg.Options.ListenAddresses)
  284. var newAddrs []string
  285. for _, addr := range cfg.Options.GlobalAnnServers {
  286. uri, err := url.Parse(addr)
  287. if err != nil {
  288. // That's odd. Skip the broken address.
  289. continue
  290. }
  291. if uri.Scheme == "https" {
  292. uri.Path = path.Join(uri.Path, "v2") + "/"
  293. addr = uri.String()
  294. }
  295. newAddrs = append(newAddrs, addr)
  296. }
  297. cfg.Options.GlobalAnnServers = newAddrs
  298. for i, fcfg := range cfg.Folders {
  299. if fcfg.DeprecatedReadOnly {
  300. cfg.Folders[i].Type = FolderTypeReadOnly
  301. } else {
  302. cfg.Folders[i].Type = FolderTypeReadWrite
  303. }
  304. cfg.Folders[i].DeprecatedReadOnly = false
  305. }
  306. // v0.13-beta already had config version 13 but did not get the new URL
  307. if cfg.Options.ReleasesURL == "https://api.github.com/repos/syncthing/syncthing/releases?per_page=30" {
  308. cfg.Options.ReleasesURL = "https://upgrades.syncthing.net/meta.json"
  309. }
  310. cfg.Version = 14
  311. }
  312. func convertV12V13(cfg *Configuration) {
  313. if cfg.Options.ReleasesURL == "https://api.github.com/repos/syncthing/syncthing/releases?per_page=30" {
  314. cfg.Options.ReleasesURL = "https://upgrades.syncthing.net/meta.json"
  315. }
  316. cfg.Version = 13
  317. }
  318. func convertV11V12(cfg *Configuration) {
  319. // Change listen address schema
  320. for i, addr := range cfg.Options.ListenAddresses {
  321. if len(addr) > 0 && !strings.HasPrefix(addr, "tcp://") {
  322. cfg.Options.ListenAddresses[i] = util.Address("tcp", addr)
  323. }
  324. }
  325. for i, device := range cfg.Devices {
  326. for j, addr := range device.Addresses {
  327. if addr != "dynamic" && addr != "" {
  328. cfg.Devices[i].Addresses[j] = util.Address("tcp", addr)
  329. }
  330. }
  331. }
  332. // Use new discovery server
  333. var newDiscoServers []string
  334. var useDefault bool
  335. for _, addr := range cfg.Options.GlobalAnnServers {
  336. if addr == "udp4://announce.syncthing.net:22026" {
  337. useDefault = true
  338. } else if addr == "udp6://announce-v6.syncthing.net:22026" {
  339. useDefault = true
  340. } else {
  341. newDiscoServers = append(newDiscoServers, addr)
  342. }
  343. }
  344. if useDefault {
  345. newDiscoServers = append(newDiscoServers, "default")
  346. }
  347. cfg.Options.GlobalAnnServers = newDiscoServers
  348. // Use new multicast group
  349. if cfg.Options.LocalAnnMCAddr == "[ff32::5222]:21026" {
  350. cfg.Options.LocalAnnMCAddr = "[ff12::8384]:21027"
  351. }
  352. // Use new local discovery port
  353. if cfg.Options.LocalAnnPort == 21025 {
  354. cfg.Options.LocalAnnPort = 21027
  355. }
  356. // Set MaxConflicts to unlimited
  357. for i := range cfg.Folders {
  358. cfg.Folders[i].MaxConflicts = -1
  359. }
  360. cfg.Version = 12
  361. }
  362. func convertV10V11(cfg *Configuration) {
  363. // Set minimum disk free of existing folders to 1%
  364. for i := range cfg.Folders {
  365. cfg.Folders[i].MinDiskFreePct = 1
  366. }
  367. cfg.Version = 11
  368. }
  369. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  370. for _, device := range devices {
  371. if device.DeviceID.Equals(myID) {
  372. return devices
  373. }
  374. }
  375. devices = append(devices, FolderDeviceConfiguration{
  376. DeviceID: myID,
  377. })
  378. return devices
  379. }
  380. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  381. count := len(devices)
  382. i := 0
  383. loop:
  384. for i < count {
  385. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  386. devices[i] = devices[count-1]
  387. count--
  388. continue loop
  389. }
  390. i++
  391. }
  392. return devices[0:count]
  393. }
  394. func ensureNoDuplicateFolderDevices(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  395. count := len(devices)
  396. i := 0
  397. seenDevices := make(map[protocol.DeviceID]bool)
  398. loop:
  399. for i < count {
  400. id := devices[i].DeviceID
  401. if _, ok := seenDevices[id]; ok {
  402. devices[i] = devices[count-1]
  403. count--
  404. continue loop
  405. }
  406. seenDevices[id] = true
  407. i++
  408. }
  409. return devices[0:count]
  410. }
  411. func ensureNoDuplicateDevices(devices []DeviceConfiguration) []DeviceConfiguration {
  412. count := len(devices)
  413. i := 0
  414. seenDevices := make(map[protocol.DeviceID]bool)
  415. loop:
  416. for i < count {
  417. id := devices[i].DeviceID
  418. if _, ok := seenDevices[id]; ok {
  419. devices[i] = devices[count-1]
  420. count--
  421. continue loop
  422. }
  423. seenDevices[id] = true
  424. i++
  425. }
  426. return devices[0:count]
  427. }