config.go 14 KB

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