config.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. "io"
  12. "io/ioutil"
  13. "net/url"
  14. "os"
  15. "sort"
  16. "strings"
  17. "github.com/syncthing/syncthing/lib/protocol"
  18. "github.com/syncthing/syncthing/lib/util"
  19. )
  20. const (
  21. OldestHandledVersion = 10
  22. CurrentVersion = 13
  23. MaxRescanIntervalS = 365 * 24 * 60 * 60
  24. )
  25. var (
  26. // DefaultListenAddresses should be substituted when the configuration
  27. // contains <listenAddress>default</listenAddress>. This is
  28. // done by the "consumer" of the configuration, as we don't want these
  29. // saved to the config.
  30. DefaultListenAddresses = []string{
  31. "tcp://0.0.0.0:22000",
  32. "dynamic+https://relays.syncthing.net/endpoint",
  33. }
  34. // DefaultDiscoveryServersV4 should be substituted when the configuration
  35. // contains <globalAnnounceServer>default-v4</globalAnnounceServer>.
  36. DefaultDiscoveryServersV4 = []string{
  37. "https://discovery-v4-1.syncthing.net/v2/?id=SR7AARM-TCBUZ5O-VFAXY4D-CECGSDE-3Q6IZ4G-XG7AH75-OBIXJQV-QJ6NLQA", // 194.126.249.5, Sweden
  38. "https://discovery-v4-2.syncthing.net/v2/?id=DVU36WY-H3LVZHW-E6LLFRE-YAFN5EL-HILWRYP-OC2M47J-Z4PE62Y-ADIBDQC", // 45.55.230.38, USA
  39. "https://discovery-v4-3.syncthing.net/v2/?id=VK6HNJ3-VVMM66S-HRVWSCR-IXEHL2H-U4AQ4MW-UCPQBWX-J2L2UBK-NVZRDQZ", // 128.199.95.124, Singapore
  40. }
  41. // DefaultDiscoveryServersV6 should be substituted when the configuration
  42. // contains <globalAnnounceServer>default-v6</globalAnnounceServer>.
  43. DefaultDiscoveryServersV6 = []string{
  44. "https://discovery-v6-1.syncthing.net/v2/?id=SR7AARM-TCBUZ5O-VFAXY4D-CECGSDE-3Q6IZ4G-XG7AH75-OBIXJQV-QJ6NLQA", // 2001:470:28:4d6::5, Sweden
  45. "https://discovery-v6-2.syncthing.net/v2/?id=DVU36WY-H3LVZHW-E6LLFRE-YAFN5EL-HILWRYP-OC2M47J-Z4PE62Y-ADIBDQC", // 2604:a880:800:10::182:a001, USA
  46. "https://discovery-v6-3.syncthing.net/v2/?id=VK6HNJ3-VVMM66S-HRVWSCR-IXEHL2H-U4AQ4MW-UCPQBWX-J2L2UBK-NVZRDQZ", // 2400:6180:0:d0::d9:d001, Singapore
  47. }
  48. // DefaultDiscoveryServers should be substituted when the configuration
  49. // contains <globalAnnounceServer>default</globalAnnounceServer>.
  50. DefaultDiscoveryServers = append(DefaultDiscoveryServersV4, DefaultDiscoveryServersV6...)
  51. // DefaultTheme is the default and fallback theme for the web UI.
  52. DefaultTheme = "default"
  53. )
  54. func New(myID protocol.DeviceID) Configuration {
  55. var cfg Configuration
  56. cfg.Version = CurrentVersion
  57. cfg.OriginalVersion = CurrentVersion
  58. util.SetDefaults(&cfg)
  59. util.SetDefaults(&cfg.Options)
  60. util.SetDefaults(&cfg.GUI)
  61. cfg.prepare(myID)
  62. return cfg
  63. }
  64. func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  65. var cfg Configuration
  66. util.SetDefaults(&cfg)
  67. util.SetDefaults(&cfg.Options)
  68. util.SetDefaults(&cfg.GUI)
  69. err := xml.NewDecoder(r).Decode(&cfg)
  70. cfg.OriginalVersion = cfg.Version
  71. cfg.prepare(myID)
  72. return cfg, err
  73. }
  74. func ReadJSON(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  75. var cfg Configuration
  76. util.SetDefaults(&cfg)
  77. util.SetDefaults(&cfg.Options)
  78. util.SetDefaults(&cfg.GUI)
  79. bs, err := ioutil.ReadAll(r)
  80. if err != nil {
  81. return cfg, err
  82. }
  83. err = json.Unmarshal(bs, &cfg)
  84. cfg.OriginalVersion = cfg.Version
  85. cfg.prepare(myID)
  86. return cfg, err
  87. }
  88. type Configuration struct {
  89. Version int `xml:"version,attr" json:"version"`
  90. Folders []FolderConfiguration `xml:"folder" json:"folders"`
  91. Devices []DeviceConfiguration `xml:"device" json:"devices"`
  92. GUI GUIConfiguration `xml:"gui" json:"gui"`
  93. Options OptionsConfiguration `xml:"options" json:"options"`
  94. IgnoredDevices []protocol.DeviceID `xml:"ignoredDevice" json:"ignoredDevices"`
  95. XMLName xml.Name `xml:"configuration" json:"-"`
  96. OriginalVersion int `xml:"-" json:"-"` // The version we read from disk, before any conversion
  97. }
  98. func (cfg Configuration) Copy() Configuration {
  99. newCfg := cfg
  100. // Deep copy FolderConfigurations
  101. newCfg.Folders = make([]FolderConfiguration, len(cfg.Folders))
  102. for i := range newCfg.Folders {
  103. newCfg.Folders[i] = cfg.Folders[i].Copy()
  104. }
  105. // Deep copy DeviceConfigurations
  106. newCfg.Devices = make([]DeviceConfiguration, len(cfg.Devices))
  107. for i := range newCfg.Devices {
  108. newCfg.Devices[i] = cfg.Devices[i].Copy()
  109. }
  110. newCfg.Options = cfg.Options.Copy()
  111. // DeviceIDs are values
  112. newCfg.IgnoredDevices = make([]protocol.DeviceID, len(cfg.IgnoredDevices))
  113. copy(newCfg.IgnoredDevices, cfg.IgnoredDevices)
  114. return newCfg
  115. }
  116. func (cfg *Configuration) WriteXML(w io.Writer) error {
  117. e := xml.NewEncoder(w)
  118. e.Indent("", " ")
  119. err := e.Encode(cfg)
  120. if err != nil {
  121. return err
  122. }
  123. _, err = w.Write([]byte("\n"))
  124. return err
  125. }
  126. func (cfg *Configuration) prepare(myID protocol.DeviceID) {
  127. util.FillNilSlices(&cfg.Options)
  128. // Initialize any empty slices
  129. if cfg.Folders == nil {
  130. cfg.Folders = []FolderConfiguration{}
  131. }
  132. if cfg.IgnoredDevices == nil {
  133. cfg.IgnoredDevices = []protocol.DeviceID{}
  134. }
  135. if cfg.Options.AlwaysLocalNets == nil {
  136. cfg.Options.AlwaysLocalNets = []string{}
  137. }
  138. // Check for missing, bad or duplicate folder ID:s
  139. var seenFolders = map[string]*FolderConfiguration{}
  140. for i := range cfg.Folders {
  141. folder := &cfg.Folders[i]
  142. folder.prepare()
  143. if seen, ok := seenFolders[folder.ID]; ok {
  144. l.Warnf("Multiple folders with ID %q; disabling", folder.ID)
  145. seen.Invalid = "duplicate folder ID"
  146. folder.Invalid = "duplicate folder ID"
  147. } else {
  148. seenFolders[folder.ID] = folder
  149. }
  150. }
  151. cfg.Options.ListenAddresses = util.UniqueStrings(cfg.Options.ListenAddresses)
  152. cfg.Options.GlobalAnnServers = util.UniqueStrings(cfg.Options.GlobalAnnServers)
  153. if cfg.Version > 0 && cfg.Version < OldestHandledVersion {
  154. l.Warnf("Configuration version %d is deprecated. Attempting best effort conversion, but please verify manually.", cfg.Version)
  155. }
  156. // Upgrade configuration versions as appropriate
  157. if cfg.Version <= 10 {
  158. convertV10V11(cfg)
  159. }
  160. if cfg.Version == 11 {
  161. convertV11V12(cfg)
  162. }
  163. if cfg.Version == 12 {
  164. convertV12V13(cfg)
  165. }
  166. // Build a list of available devices
  167. existingDevices := make(map[protocol.DeviceID]bool)
  168. for _, device := range cfg.Devices {
  169. existingDevices[device.DeviceID] = true
  170. }
  171. // Ensure this device is present in the config
  172. if !existingDevices[myID] {
  173. myName, _ := os.Hostname()
  174. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  175. DeviceID: myID,
  176. Name: myName,
  177. })
  178. existingDevices[myID] = true
  179. }
  180. // Ensure that the device list is free from duplicates
  181. cfg.Devices = ensureNoDuplicateDevices(cfg.Devices)
  182. sort.Sort(DeviceConfigurationList(cfg.Devices))
  183. // Ensure that any loose devices are not present in the wrong places
  184. // Ensure that there are no duplicate devices
  185. // Ensure that puller settings are sane
  186. // Ensure that the versioning configuration parameter map is not nil
  187. for i := range cfg.Folders {
  188. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  189. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  190. cfg.Folders[i].Devices = ensureNoDuplicateFolderDevices(cfg.Folders[i].Devices)
  191. if cfg.Folders[i].Versioning.Params == nil {
  192. cfg.Folders[i].Versioning.Params = map[string]string{}
  193. }
  194. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  195. }
  196. // An empty address list is equivalent to a single "dynamic" entry
  197. for i := range cfg.Devices {
  198. n := &cfg.Devices[i]
  199. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  200. n.Addresses = []string{"dynamic"}
  201. }
  202. }
  203. // Very short reconnection intervals are annoying
  204. if cfg.Options.ReconnectIntervalS < 5 {
  205. cfg.Options.ReconnectIntervalS = 5
  206. }
  207. if cfg.GUI.APIKey == "" {
  208. cfg.GUI.APIKey = util.RandomString(32)
  209. }
  210. }
  211. func convertV12V13(cfg *Configuration) {
  212. // Not using the ignore cache is the new default. Disable it on existing
  213. // configurations.
  214. cfg.Options.CacheIgnoredFiles = false
  215. cfg.Options.NATEnabled = cfg.Options.DeprecatedUPnPEnabled
  216. cfg.Options.NATLeaseM = cfg.Options.DeprecatedUPnPLeaseM
  217. cfg.Options.NATRenewalM = cfg.Options.DeprecatedUPnPRenewalM
  218. cfg.Options.NATTimeoutS = cfg.Options.DeprecatedUPnPTimeoutS
  219. if cfg.Options.DeprecatedRelaysEnabled {
  220. cfg.Options.ListenAddresses = append(cfg.Options.ListenAddresses, cfg.Options.DeprecatedRelayServers...)
  221. // Replace our two fairly long addresses with 'default' if both exist.
  222. var newAddresses []string
  223. for _, addr := range cfg.Options.ListenAddresses {
  224. if addr != "tcp://0.0.0.0:22000" && addr != "dynamic+https://relays.syncthing.net/endpoint" {
  225. newAddresses = append(newAddresses, addr)
  226. }
  227. }
  228. if len(newAddresses)+2 == len(cfg.Options.ListenAddresses) {
  229. cfg.Options.ListenAddresses = append([]string{"default"}, newAddresses...)
  230. }
  231. }
  232. cfg.Options.DeprecatedRelaysEnabled = false
  233. cfg.Options.DeprecatedRelayServers = nil
  234. var newAddrs []string
  235. for _, addr := range cfg.Options.GlobalAnnServers {
  236. if addr != "default" {
  237. uri, err := url.Parse(addr)
  238. if err != nil {
  239. panic(err)
  240. }
  241. uri.Path += "v2/"
  242. addr = uri.String()
  243. }
  244. newAddrs = append(newAddrs, addr)
  245. }
  246. cfg.Options.GlobalAnnServers = newAddrs
  247. cfg.Version = 13
  248. for i, fcfg := range cfg.Folders {
  249. if fcfg.DeprecatedReadOnly {
  250. cfg.Folders[i].Type = FolderTypeReadOnly
  251. } else {
  252. cfg.Folders[i].Type = FolderTypeReadWrite
  253. }
  254. cfg.Folders[i].DeprecatedReadOnly = false
  255. }
  256. }
  257. func convertV11V12(cfg *Configuration) {
  258. // Change listen address schema
  259. for i, addr := range cfg.Options.ListenAddresses {
  260. if len(addr) > 0 && !strings.HasPrefix(addr, "tcp://") {
  261. cfg.Options.ListenAddresses[i] = util.Address("tcp", addr)
  262. }
  263. }
  264. for i, device := range cfg.Devices {
  265. for j, addr := range device.Addresses {
  266. if addr != "dynamic" && addr != "" {
  267. cfg.Devices[i].Addresses[j] = util.Address("tcp", addr)
  268. }
  269. }
  270. }
  271. // Use new discovery server
  272. var newDiscoServers []string
  273. var useDefault bool
  274. for _, addr := range cfg.Options.GlobalAnnServers {
  275. if addr == "udp4://announce.syncthing.net:22026" {
  276. useDefault = true
  277. } else if addr == "udp6://announce-v6.syncthing.net:22026" {
  278. useDefault = true
  279. } else {
  280. newDiscoServers = append(newDiscoServers, addr)
  281. }
  282. }
  283. if useDefault {
  284. newDiscoServers = append(newDiscoServers, "default")
  285. }
  286. cfg.Options.GlobalAnnServers = newDiscoServers
  287. // Use new multicast group
  288. if cfg.Options.LocalAnnMCAddr == "[ff32::5222]:21026" {
  289. cfg.Options.LocalAnnMCAddr = "[ff12::8384]:21027"
  290. }
  291. // Use new local discovery port
  292. if cfg.Options.LocalAnnPort == 21025 {
  293. cfg.Options.LocalAnnPort = 21027
  294. }
  295. // Set MaxConflicts to unlimited
  296. for i := range cfg.Folders {
  297. cfg.Folders[i].MaxConflicts = -1
  298. }
  299. cfg.Version = 12
  300. }
  301. func convertV10V11(cfg *Configuration) {
  302. // Set minimum disk free of existing folders to 1%
  303. for i := range cfg.Folders {
  304. cfg.Folders[i].MinDiskFreePct = 1
  305. }
  306. cfg.Version = 11
  307. }
  308. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  309. for _, device := range devices {
  310. if device.DeviceID.Equals(myID) {
  311. return devices
  312. }
  313. }
  314. devices = append(devices, FolderDeviceConfiguration{
  315. DeviceID: myID,
  316. })
  317. return devices
  318. }
  319. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  320. count := len(devices)
  321. i := 0
  322. loop:
  323. for i < count {
  324. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  325. devices[i] = devices[count-1]
  326. count--
  327. continue loop
  328. }
  329. i++
  330. }
  331. return devices[0:count]
  332. }
  333. func ensureNoDuplicateFolderDevices(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  334. count := len(devices)
  335. i := 0
  336. seenDevices := make(map[protocol.DeviceID]bool)
  337. loop:
  338. for i < count {
  339. id := devices[i].DeviceID
  340. if _, ok := seenDevices[id]; ok {
  341. devices[i] = devices[count-1]
  342. count--
  343. continue loop
  344. }
  345. seenDevices[id] = true
  346. i++
  347. }
  348. return devices[0:count]
  349. }
  350. func ensureNoDuplicateDevices(devices []DeviceConfiguration) []DeviceConfiguration {
  351. count := len(devices)
  352. i := 0
  353. seenDevices := make(map[protocol.DeviceID]bool)
  354. loop:
  355. for i < count {
  356. id := devices[i].DeviceID
  357. if _, ok := seenDevices[id]; ok {
  358. devices[i] = devices[count-1]
  359. count--
  360. continue loop
  361. }
  362. seenDevices[id] = true
  363. i++
  364. }
  365. return devices[0:count]
  366. }