config.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. "math/rand"
  13. "net/url"
  14. "os"
  15. "reflect"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. "github.com/syncthing/syncthing/lib/protocol"
  20. )
  21. const (
  22. OldestHandledVersion = 10
  23. CurrentVersion = 12
  24. MaxRescanIntervalS = 365 * 24 * 60 * 60
  25. )
  26. var (
  27. // DefaultDiscoveryServersV4 should be substituted when the configuration
  28. // contains <globalAnnounceServer>default-v4</globalAnnounceServer>. This is
  29. // done by the "consumer" of the configuration, as we don't want these
  30. // saved to the config.
  31. DefaultDiscoveryServersV4 = []string{
  32. "https://discovery-v4-1.syncthing.net/?id=SR7AARM-TCBUZ5O-VFAXY4D-CECGSDE-3Q6IZ4G-XG7AH75-OBIXJQV-QJ6NLQA", // 194.126.249.5, Sweden
  33. "https://discovery-v4-2.syncthing.net/?id=DVU36WY-H3LVZHW-E6LLFRE-YAFN5EL-HILWRYP-OC2M47J-Z4PE62Y-ADIBDQC", // 45.55.230.38, USA
  34. "https://discovery-v4-3.syncthing.net/?id=VK6HNJ3-VVMM66S-HRVWSCR-IXEHL2H-U4AQ4MW-UCPQBWX-J2L2UBK-NVZRDQZ", // 128.199.95.124, Singapore
  35. }
  36. // DefaultDiscoveryServersV6 should be substituted when the configuration
  37. // contains <globalAnnounceServer>default-v6</globalAnnounceServer>.
  38. DefaultDiscoveryServersV6 = []string{
  39. "https://discovery-v6-1.syncthing.net/?id=SR7AARM-TCBUZ5O-VFAXY4D-CECGSDE-3Q6IZ4G-XG7AH75-OBIXJQV-QJ6NLQA", // 2001:470:28:4d6::5, Sweden
  40. "https://discovery-v6-2.syncthing.net/?id=DVU36WY-H3LVZHW-E6LLFRE-YAFN5EL-HILWRYP-OC2M47J-Z4PE62Y-ADIBDQC", // 2604:a880:800:10::182:a001, USA
  41. "https://discovery-v6-3.syncthing.net/?id=VK6HNJ3-VVMM66S-HRVWSCR-IXEHL2H-U4AQ4MW-UCPQBWX-J2L2UBK-NVZRDQZ", // 2400:6180:0:d0::d9:d001, Singapore
  42. }
  43. // DefaultDiscoveryServers should be substituted when the configuration
  44. // contains <globalAnnounceServer>default</globalAnnounceServer>.
  45. DefaultDiscoveryServers = append(DefaultDiscoveryServersV4, DefaultDiscoveryServersV6...)
  46. )
  47. func New(myID protocol.DeviceID) Configuration {
  48. var cfg Configuration
  49. cfg.Version = CurrentVersion
  50. cfg.OriginalVersion = CurrentVersion
  51. setDefaults(&cfg)
  52. setDefaults(&cfg.Options)
  53. setDefaults(&cfg.GUI)
  54. cfg.prepare(myID)
  55. return cfg
  56. }
  57. func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  58. var cfg Configuration
  59. setDefaults(&cfg)
  60. setDefaults(&cfg.Options)
  61. setDefaults(&cfg.GUI)
  62. err := xml.NewDecoder(r).Decode(&cfg)
  63. cfg.OriginalVersion = cfg.Version
  64. cfg.prepare(myID)
  65. return cfg, err
  66. }
  67. func ReadJSON(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  68. var cfg Configuration
  69. setDefaults(&cfg)
  70. setDefaults(&cfg.Options)
  71. setDefaults(&cfg.GUI)
  72. err := json.NewDecoder(r).Decode(&cfg)
  73. cfg.OriginalVersion = cfg.Version
  74. cfg.prepare(myID)
  75. return cfg, err
  76. }
  77. type Configuration struct {
  78. Version int `xml:"version,attr" json:"version"`
  79. Folders []FolderConfiguration `xml:"folder" json:"folders"`
  80. Devices []DeviceConfiguration `xml:"device" json:"devices"`
  81. GUI GUIConfiguration `xml:"gui" json:"gui"`
  82. Options OptionsConfiguration `xml:"options" json:"options"`
  83. IgnoredDevices []protocol.DeviceID `xml:"ignoredDevice" json:"ignoredDevices"`
  84. XMLName xml.Name `xml:"configuration" json:"-"`
  85. OriginalVersion int `xml:"-" json:"-"` // The version we read from disk, before any conversion
  86. }
  87. func (cfg Configuration) Copy() Configuration {
  88. newCfg := cfg
  89. // Deep copy FolderConfigurations
  90. newCfg.Folders = make([]FolderConfiguration, len(cfg.Folders))
  91. for i := range newCfg.Folders {
  92. newCfg.Folders[i] = cfg.Folders[i].Copy()
  93. }
  94. // Deep copy DeviceConfigurations
  95. newCfg.Devices = make([]DeviceConfiguration, len(cfg.Devices))
  96. for i := range newCfg.Devices {
  97. newCfg.Devices[i] = cfg.Devices[i].Copy()
  98. }
  99. newCfg.Options = cfg.Options.Copy()
  100. // DeviceIDs are values
  101. newCfg.IgnoredDevices = make([]protocol.DeviceID, len(cfg.IgnoredDevices))
  102. copy(newCfg.IgnoredDevices, cfg.IgnoredDevices)
  103. return newCfg
  104. }
  105. func (cfg *Configuration) WriteXML(w io.Writer) error {
  106. e := xml.NewEncoder(w)
  107. e.Indent("", " ")
  108. err := e.Encode(cfg)
  109. if err != nil {
  110. return err
  111. }
  112. _, err = w.Write([]byte("\n"))
  113. return err
  114. }
  115. func (cfg *Configuration) prepare(myID protocol.DeviceID) {
  116. fillNilSlices(&cfg.Options)
  117. // Initialize any empty slices
  118. if cfg.Folders == nil {
  119. cfg.Folders = []FolderConfiguration{}
  120. }
  121. if cfg.IgnoredDevices == nil {
  122. cfg.IgnoredDevices = []protocol.DeviceID{}
  123. }
  124. if cfg.Options.AlwaysLocalNets == nil {
  125. cfg.Options.AlwaysLocalNets = []string{}
  126. }
  127. // Check for missing, bad or duplicate folder ID:s
  128. var seenFolders = map[string]*FolderConfiguration{}
  129. for i := range cfg.Folders {
  130. folder := &cfg.Folders[i]
  131. folder.prepare()
  132. if seen, ok := seenFolders[folder.ID]; ok {
  133. l.Warnf("Multiple folders with ID %q; disabling", folder.ID)
  134. seen.Invalid = "duplicate folder ID"
  135. folder.Invalid = "duplicate folder ID"
  136. } else {
  137. seenFolders[folder.ID] = folder
  138. }
  139. }
  140. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  141. cfg.Options.GlobalAnnServers = uniqueStrings(cfg.Options.GlobalAnnServers)
  142. if cfg.Version > 0 && cfg.Version < OldestHandledVersion {
  143. l.Warnf("Configuration version %d is deprecated. Attempting best effort conversion, but please verify manually.", cfg.Version)
  144. }
  145. // Upgrade configuration versions as appropriate
  146. if cfg.Version <= 10 {
  147. convertV10V11(cfg)
  148. }
  149. if cfg.Version == 11 {
  150. convertV11V12(cfg)
  151. }
  152. // Build a list of available devices
  153. existingDevices := make(map[protocol.DeviceID]bool)
  154. for _, device := range cfg.Devices {
  155. existingDevices[device.DeviceID] = true
  156. }
  157. // Ensure this device is present in the config
  158. if !existingDevices[myID] {
  159. myName, _ := os.Hostname()
  160. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  161. DeviceID: myID,
  162. Name: myName,
  163. })
  164. existingDevices[myID] = true
  165. }
  166. // Ensure that the device list is free from duplicates
  167. cfg.Devices = ensureNoDuplicateDevices(cfg.Devices)
  168. sort.Sort(DeviceConfigurationList(cfg.Devices))
  169. // Ensure that any loose devices are not present in the wrong places
  170. // Ensure that there are no duplicate devices
  171. // Ensure that puller settings are sane
  172. for i := range cfg.Folders {
  173. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  174. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  175. cfg.Folders[i].Devices = ensureNoDuplicateFolderDevices(cfg.Folders[i].Devices)
  176. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  177. }
  178. // An empty address list is equivalent to a single "dynamic" entry
  179. for i := range cfg.Devices {
  180. n := &cfg.Devices[i]
  181. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  182. n.Addresses = []string{"dynamic"}
  183. }
  184. }
  185. // Very short reconnection intervals are annoying
  186. if cfg.Options.ReconnectIntervalS < 5 {
  187. cfg.Options.ReconnectIntervalS = 5
  188. }
  189. if cfg.GUI.RawAPIKey == "" {
  190. cfg.GUI.RawAPIKey = randomString(32)
  191. }
  192. }
  193. func convertV11V12(cfg *Configuration) {
  194. // Change listen address schema
  195. for i, addr := range cfg.Options.ListenAddress {
  196. if len(addr) > 0 && !strings.HasPrefix(addr, "tcp://") {
  197. cfg.Options.ListenAddress[i] = tcpAddr(addr)
  198. }
  199. }
  200. for i, device := range cfg.Devices {
  201. for j, addr := range device.Addresses {
  202. if addr != "dynamic" && addr != "" {
  203. cfg.Devices[i].Addresses[j] = tcpAddr(addr)
  204. }
  205. }
  206. }
  207. // Use new discovery server
  208. var newDiscoServers []string
  209. var useDefault bool
  210. for _, addr := range cfg.Options.GlobalAnnServers {
  211. if addr == "udp4://announce.syncthing.net:22026" {
  212. useDefault = true
  213. } else if addr == "udp6://announce-v6.syncthing.net:22026" {
  214. useDefault = true
  215. } else {
  216. newDiscoServers = append(newDiscoServers, addr)
  217. }
  218. }
  219. if useDefault {
  220. newDiscoServers = append(newDiscoServers, "default")
  221. }
  222. cfg.Options.GlobalAnnServers = newDiscoServers
  223. // Use new multicast group
  224. if cfg.Options.LocalAnnMCAddr == "[ff32::5222]:21026" {
  225. cfg.Options.LocalAnnMCAddr = "[ff12::8384]:21027"
  226. }
  227. // Use new local discovery port
  228. if cfg.Options.LocalAnnPort == 21025 {
  229. cfg.Options.LocalAnnPort = 21027
  230. }
  231. // Set MaxConflicts to unlimited
  232. for i := range cfg.Folders {
  233. cfg.Folders[i].MaxConflicts = -1
  234. }
  235. cfg.Version = 12
  236. }
  237. func convertV10V11(cfg *Configuration) {
  238. // Set minimum disk free of existing folders to 1%
  239. for i := range cfg.Folders {
  240. cfg.Folders[i].MinDiskFreePct = 1
  241. }
  242. cfg.Version = 11
  243. }
  244. func setDefaults(data interface{}) error {
  245. s := reflect.ValueOf(data).Elem()
  246. t := s.Type()
  247. for i := 0; i < s.NumField(); i++ {
  248. f := s.Field(i)
  249. tag := t.Field(i).Tag
  250. v := tag.Get("default")
  251. if len(v) > 0 {
  252. switch f.Interface().(type) {
  253. case string:
  254. f.SetString(v)
  255. case int:
  256. i, err := strconv.ParseInt(v, 10, 64)
  257. if err != nil {
  258. return err
  259. }
  260. f.SetInt(i)
  261. case float64:
  262. i, err := strconv.ParseFloat(v, 64)
  263. if err != nil {
  264. return err
  265. }
  266. f.SetFloat(i)
  267. case bool:
  268. f.SetBool(v == "true")
  269. case []string:
  270. // We don't do anything with string slices here. Any default
  271. // we set will be appended to by the XML decoder, so we fill
  272. // those after decoding.
  273. default:
  274. panic(f.Type())
  275. }
  276. }
  277. }
  278. return nil
  279. }
  280. // fillNilSlices sets default value on slices that are still nil.
  281. func fillNilSlices(data interface{}) error {
  282. s := reflect.ValueOf(data).Elem()
  283. t := s.Type()
  284. for i := 0; i < s.NumField(); i++ {
  285. f := s.Field(i)
  286. tag := t.Field(i).Tag
  287. v := tag.Get("default")
  288. if len(v) > 0 {
  289. switch f.Interface().(type) {
  290. case []string:
  291. if f.IsNil() {
  292. // Treat the default as a comma separated slice
  293. vs := strings.Split(v, ",")
  294. for i := range vs {
  295. vs[i] = strings.TrimSpace(vs[i])
  296. }
  297. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), len(vs), len(vs))
  298. for i, v := range vs {
  299. rv.Index(i).SetString(v)
  300. }
  301. f.Set(rv)
  302. }
  303. }
  304. }
  305. }
  306. return nil
  307. }
  308. func uniqueStrings(ss []string) []string {
  309. var m = make(map[string]bool, len(ss))
  310. for _, s := range ss {
  311. m[strings.Trim(s, " ")] = true
  312. }
  313. var us = make([]string, 0, len(m))
  314. for k := range m {
  315. us = append(us, k)
  316. }
  317. sort.Strings(us)
  318. return us
  319. }
  320. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  321. for _, device := range devices {
  322. if device.DeviceID.Equals(myID) {
  323. return devices
  324. }
  325. }
  326. devices = append(devices, FolderDeviceConfiguration{
  327. DeviceID: myID,
  328. })
  329. return devices
  330. }
  331. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  332. count := len(devices)
  333. i := 0
  334. loop:
  335. for i < count {
  336. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  337. devices[i] = devices[count-1]
  338. count--
  339. continue loop
  340. }
  341. i++
  342. }
  343. return devices[0:count]
  344. }
  345. func ensureNoDuplicateFolderDevices(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  346. count := len(devices)
  347. i := 0
  348. seenDevices := make(map[protocol.DeviceID]bool)
  349. loop:
  350. for i < count {
  351. id := devices[i].DeviceID
  352. if _, ok := seenDevices[id]; ok {
  353. devices[i] = devices[count-1]
  354. count--
  355. continue loop
  356. }
  357. seenDevices[id] = true
  358. i++
  359. }
  360. return devices[0:count]
  361. }
  362. func ensureNoDuplicateDevices(devices []DeviceConfiguration) []DeviceConfiguration {
  363. count := len(devices)
  364. i := 0
  365. seenDevices := make(map[protocol.DeviceID]bool)
  366. loop:
  367. for i < count {
  368. id := devices[i].DeviceID
  369. if _, ok := seenDevices[id]; ok {
  370. devices[i] = devices[count-1]
  371. count--
  372. continue loop
  373. }
  374. seenDevices[id] = true
  375. i++
  376. }
  377. return devices[0:count]
  378. }
  379. // randomCharset contains the characters that can make up a randomString().
  380. const randomCharset = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
  381. // randomString returns a string of random characters (taken from
  382. // randomCharset) of the specified length.
  383. func randomString(l int) string {
  384. bs := make([]byte, l)
  385. for i := range bs {
  386. bs[i] = randomCharset[rand.Intn(len(randomCharset))]
  387. }
  388. return string(bs)
  389. }
  390. func tcpAddr(host string) string {
  391. u := url.URL{
  392. Scheme: "tcp",
  393. Host: host,
  394. }
  395. return u.String()
  396. }