config.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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 https://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. "errors"
  12. "fmt"
  13. "io"
  14. "io/ioutil"
  15. "net"
  16. "net/url"
  17. "os"
  18. "runtime"
  19. "sort"
  20. "strconv"
  21. "strings"
  22. "github.com/syncthing/syncthing/lib/fs"
  23. "github.com/syncthing/syncthing/lib/protocol"
  24. "github.com/syncthing/syncthing/lib/rand"
  25. "github.com/syncthing/syncthing/lib/util"
  26. )
  27. const (
  28. OldestHandledVersion = 10
  29. CurrentVersion = 29
  30. MaxRescanIntervalS = 365 * 24 * 60 * 60
  31. )
  32. var (
  33. // DefaultTCPPort defines default TCP port used if the URI does not specify one, for example tcp://0.0.0.0
  34. DefaultTCPPort = 22000
  35. // DefaultQUICPort defines default QUIC port used if the URI does not specify one, for example quic://0.0.0.0
  36. DefaultQUICPort = 22000
  37. // DefaultListenAddresses should be substituted when the configuration
  38. // contains <listenAddress>default</listenAddress>. This is done by the
  39. // "consumer" of the configuration as we don't want these saved to the
  40. // config.
  41. DefaultListenAddresses = []string{
  42. util.Address("tcp", net.JoinHostPort("0.0.0.0", strconv.Itoa(DefaultTCPPort))),
  43. "dynamic+https://relays.syncthing.net/endpoint",
  44. util.Address("quic", net.JoinHostPort("0.0.0.0", strconv.Itoa(DefaultQUICPort))),
  45. }
  46. DefaultGUIPort = 8384
  47. // DefaultDiscoveryServersV4 should be substituted when the configuration
  48. // contains <globalAnnounceServer>default-v4</globalAnnounceServer>.
  49. DefaultDiscoveryServersV4 = []string{
  50. "https://discovery.syncthing.net/v2/?noannounce&id=LYXKCHX-VI3NYZR-ALCJBHF-WMZYSPK-QG6QJA3-MPFYMSO-U56GTUK-NA2MIAW",
  51. "https://discovery-v4.syncthing.net/v2/?nolookup&id=LYXKCHX-VI3NYZR-ALCJBHF-WMZYSPK-QG6QJA3-MPFYMSO-U56GTUK-NA2MIAW",
  52. }
  53. // DefaultDiscoveryServersV6 should be substituted when the configuration
  54. // contains <globalAnnounceServer>default-v6</globalAnnounceServer>.
  55. DefaultDiscoveryServersV6 = []string{
  56. "https://discovery.syncthing.net/v2/?noannounce&id=LYXKCHX-VI3NYZR-ALCJBHF-WMZYSPK-QG6QJA3-MPFYMSO-U56GTUK-NA2MIAW",
  57. "https://discovery-v6.syncthing.net/v2/?nolookup&id=LYXKCHX-VI3NYZR-ALCJBHF-WMZYSPK-QG6QJA3-MPFYMSO-U56GTUK-NA2MIAW",
  58. }
  59. // DefaultDiscoveryServers should be substituted when the configuration
  60. // contains <globalAnnounceServer>default</globalAnnounceServer>.
  61. DefaultDiscoveryServers = append(DefaultDiscoveryServersV4, DefaultDiscoveryServersV6...)
  62. // DefaultTheme is the default and fallback theme for the web UI.
  63. DefaultTheme = "default"
  64. // Default stun servers should be substituted when the configuration
  65. // contains <stunServer>default</stunServer>.
  66. // DefaultPrimaryStunServers are servers provided by us (to avoid causing the public servers burden)
  67. DefaultPrimaryStunServers = []string{
  68. "stun.syncthing.net:3478",
  69. }
  70. DefaultSecondaryStunServers = []string{
  71. "stun.callwithus.com:3478",
  72. "stun.counterpath.com:3478",
  73. "stun.counterpath.net:3478",
  74. "stun.ekiga.net:3478",
  75. "stun.ideasip.com:3478",
  76. "stun.internetcalls.com:3478",
  77. "stun.schlund.de:3478",
  78. "stun.sipgate.net:10000",
  79. "stun.sipgate.net:3478",
  80. "stun.voip.aebc.com:3478",
  81. "stun.voiparound.com:3478",
  82. "stun.voipbuster.com:3478",
  83. "stun.voipstunt.com:3478",
  84. "stun.voxgratia.org:3478",
  85. "stun.xten.com:3478",
  86. }
  87. )
  88. var (
  89. errFolderIDEmpty = errors.New("folder has empty ID")
  90. errFolderIDDuplicate = errors.New("folder has duplicate ID")
  91. errFolderPathEmpty = errors.New("folder has empty path")
  92. )
  93. func New(myID protocol.DeviceID) Configuration {
  94. var cfg Configuration
  95. cfg.Version = CurrentVersion
  96. cfg.OriginalVersion = CurrentVersion
  97. util.SetDefaults(&cfg)
  98. util.SetDefaults(&cfg.Options)
  99. util.SetDefaults(&cfg.GUI)
  100. // Can't happen.
  101. if err := cfg.prepare(myID); err != nil {
  102. panic("bug: error in preparing new folder: " + err.Error())
  103. }
  104. return cfg
  105. }
  106. func NewWithFreePorts(myID protocol.DeviceID) (Configuration, error) {
  107. cfg := New(myID)
  108. port, err := getFreePort("127.0.0.1", DefaultGUIPort)
  109. if err != nil {
  110. return Configuration{}, fmt.Errorf("get free port (GUI): %v", err)
  111. }
  112. cfg.GUI.RawAddress = fmt.Sprintf("127.0.0.1:%d", port)
  113. port, err = getFreePort("0.0.0.0", DefaultTCPPort)
  114. if err != nil {
  115. return Configuration{}, fmt.Errorf("get free port (BEP): %v", err)
  116. }
  117. if port == DefaultTCPPort {
  118. cfg.Options.ListenAddresses = []string{"default"}
  119. } else {
  120. cfg.Options.ListenAddresses = []string{
  121. fmt.Sprintf("tcp://%s", net.JoinHostPort("0.0.0.0", strconv.Itoa(port))),
  122. "dynamic+https://relays.syncthing.net/endpoint",
  123. }
  124. }
  125. return cfg, nil
  126. }
  127. func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  128. var cfg Configuration
  129. util.SetDefaults(&cfg)
  130. util.SetDefaults(&cfg.Options)
  131. util.SetDefaults(&cfg.GUI)
  132. if err := xml.NewDecoder(r).Decode(&cfg); err != nil {
  133. return Configuration{}, err
  134. }
  135. cfg.OriginalVersion = cfg.Version
  136. if err := cfg.prepare(myID); err != nil {
  137. return Configuration{}, err
  138. }
  139. return cfg, nil
  140. }
  141. func ReadJSON(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  142. var cfg Configuration
  143. util.SetDefaults(&cfg)
  144. util.SetDefaults(&cfg.Options)
  145. util.SetDefaults(&cfg.GUI)
  146. bs, err := ioutil.ReadAll(r)
  147. if err != nil {
  148. return Configuration{}, err
  149. }
  150. if err := json.Unmarshal(bs, &cfg); err != nil {
  151. return Configuration{}, err
  152. }
  153. cfg.OriginalVersion = cfg.Version
  154. if err := cfg.prepare(myID); err != nil {
  155. return Configuration{}, err
  156. }
  157. return cfg, nil
  158. }
  159. type Configuration struct {
  160. Version int `xml:"version,attr" json:"version"`
  161. Folders []FolderConfiguration `xml:"folder" json:"folders"`
  162. Devices []DeviceConfiguration `xml:"device" json:"devices"`
  163. GUI GUIConfiguration `xml:"gui" json:"gui"`
  164. LDAP LDAPConfiguration `xml:"ldap" json:"ldap"`
  165. Options OptionsConfiguration `xml:"options" json:"options"`
  166. IgnoredDevices []ObservedDevice `xml:"remoteIgnoredDevice" json:"remoteIgnoredDevices"`
  167. PendingDevices []ObservedDevice `xml:"pendingDevice" json:"pendingDevices"`
  168. XMLName xml.Name `xml:"configuration" json:"-"`
  169. MyID protocol.DeviceID `xml:"-" json:"-"` // Provided by the instantiator.
  170. OriginalVersion int `xml:"-" json:"-"` // The version we read from disk, before any conversion
  171. }
  172. func (cfg Configuration) Copy() Configuration {
  173. newCfg := cfg
  174. // Deep copy FolderConfigurations
  175. newCfg.Folders = make([]FolderConfiguration, len(cfg.Folders))
  176. for i := range newCfg.Folders {
  177. newCfg.Folders[i] = cfg.Folders[i].Copy()
  178. }
  179. // Deep copy DeviceConfigurations
  180. newCfg.Devices = make([]DeviceConfiguration, len(cfg.Devices))
  181. for i := range newCfg.Devices {
  182. newCfg.Devices[i] = cfg.Devices[i].Copy()
  183. }
  184. newCfg.Options = cfg.Options.Copy()
  185. newCfg.GUI = cfg.GUI.Copy()
  186. // DeviceIDs are values
  187. newCfg.IgnoredDevices = make([]ObservedDevice, len(cfg.IgnoredDevices))
  188. copy(newCfg.IgnoredDevices, cfg.IgnoredDevices)
  189. newCfg.PendingDevices = make([]ObservedDevice, len(cfg.PendingDevices))
  190. copy(newCfg.PendingDevices, cfg.PendingDevices)
  191. return newCfg
  192. }
  193. func (cfg *Configuration) WriteXML(w io.Writer) error {
  194. e := xml.NewEncoder(w)
  195. e.Indent("", " ")
  196. err := e.Encode(cfg)
  197. if err != nil {
  198. return err
  199. }
  200. _, err = w.Write([]byte("\n"))
  201. return err
  202. }
  203. func (cfg *Configuration) prepare(myID protocol.DeviceID) error {
  204. var myName string
  205. cfg.MyID = myID
  206. // Ensure this device is present in the config
  207. for _, device := range cfg.Devices {
  208. if device.DeviceID == myID {
  209. goto found
  210. }
  211. }
  212. myName, _ = os.Hostname()
  213. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  214. DeviceID: myID,
  215. Name: myName,
  216. })
  217. found:
  218. if err := cfg.clean(); err != nil {
  219. return err
  220. }
  221. // Ensure that we are part of the devices
  222. for i := range cfg.Folders {
  223. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  224. }
  225. return nil
  226. }
  227. func (cfg *Configuration) clean() error {
  228. util.FillNilSlices(&cfg.Options)
  229. // Ensure that the device list is
  230. // - free from duplicates
  231. // - no devices with empty ID
  232. // - sorted by ID
  233. // Happen before preparting folders as that needs a correct device list.
  234. cfg.Devices = ensureNoDuplicateOrEmptyIDDevices(cfg.Devices)
  235. sort.Slice(cfg.Devices, func(a, b int) bool {
  236. return cfg.Devices[a].DeviceID.Compare(cfg.Devices[b].DeviceID) == -1
  237. })
  238. // Prepare folders and check for duplicates. Duplicates are bad and
  239. // dangerous, can't currently be resolved in the GUI, and shouldn't
  240. // happen when configured by the GUI. We return with an error in that
  241. // situation.
  242. existingFolders := make(map[string]*FolderConfiguration)
  243. for i := range cfg.Folders {
  244. folder := &cfg.Folders[i]
  245. folder.prepare()
  246. if folder.ID == "" {
  247. return errFolderIDEmpty
  248. }
  249. if folder.Path == "" {
  250. return fmt.Errorf("folder %q: %v", folder.ID, errFolderPathEmpty)
  251. }
  252. if _, ok := existingFolders[folder.ID]; ok {
  253. return fmt.Errorf("folder %q: %v", folder.ID, errFolderIDDuplicate)
  254. }
  255. existingFolders[folder.ID] = folder
  256. }
  257. cfg.Options.ListenAddresses = util.UniqueTrimmedStrings(cfg.Options.ListenAddresses)
  258. cfg.Options.GlobalAnnServers = util.UniqueTrimmedStrings(cfg.Options.GlobalAnnServers)
  259. if cfg.Version > 0 && cfg.Version < OldestHandledVersion {
  260. l.Warnf("Configuration version %d is deprecated. Attempting best effort conversion, but please verify manually.", cfg.Version)
  261. }
  262. // Upgrade configuration versions as appropriate
  263. migrations.apply(cfg)
  264. // Build a list of available devices
  265. existingDevices := make(map[protocol.DeviceID]bool)
  266. for _, device := range cfg.Devices {
  267. existingDevices[device.DeviceID] = true
  268. }
  269. // Ensure that the folder list is sorted by ID
  270. sort.Slice(cfg.Folders, func(a, b int) bool {
  271. return cfg.Folders[a].ID < cfg.Folders[b].ID
  272. })
  273. // Ensure that in all folder configs
  274. // - any loose devices are not present in the wrong places
  275. // - there are no duplicate devices
  276. // - the versioning configuration parameter map is not nil
  277. sharedFolders := make(map[protocol.DeviceID][]string, len(cfg.Devices))
  278. for i := range cfg.Folders {
  279. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  280. cfg.Folders[i].Devices = ensureNoDuplicateFolderDevices(cfg.Folders[i].Devices)
  281. if cfg.Folders[i].Versioning.Params == nil {
  282. cfg.Folders[i].Versioning.Params = map[string]string{}
  283. }
  284. sort.Slice(cfg.Folders[i].Devices, func(a, b int) bool {
  285. return cfg.Folders[i].Devices[a].DeviceID.Compare(cfg.Folders[i].Devices[b].DeviceID) == -1
  286. })
  287. for _, dev := range cfg.Folders[i].Devices {
  288. sharedFolders[dev.DeviceID] = append(sharedFolders[dev.DeviceID], cfg.Folders[i].ID)
  289. }
  290. }
  291. for i := range cfg.Devices {
  292. cfg.Devices[i].prepare(sharedFolders[cfg.Devices[i].DeviceID])
  293. }
  294. // Very short reconnection intervals are annoying
  295. if cfg.Options.ReconnectIntervalS < 5 {
  296. cfg.Options.ReconnectIntervalS = 5
  297. }
  298. if cfg.GUI.APIKey == "" {
  299. cfg.GUI.APIKey = rand.String(32)
  300. }
  301. // The list of ignored devices should not contain any devices that have
  302. // been manually added to the config.
  303. var newIgnoredDevices []ObservedDevice
  304. ignoredDevices := make(map[protocol.DeviceID]bool)
  305. for _, dev := range cfg.IgnoredDevices {
  306. if !existingDevices[dev.ID] {
  307. ignoredDevices[dev.ID] = true
  308. newIgnoredDevices = append(newIgnoredDevices, dev)
  309. }
  310. }
  311. cfg.IgnoredDevices = newIgnoredDevices
  312. // The list of pending devices should not contain devices that were added manually, nor should it contain
  313. // ignored devices.
  314. // Sort by time, so that in case of duplicates latest "time" is used.
  315. sort.Slice(cfg.PendingDevices, func(i, j int) bool {
  316. return cfg.PendingDevices[i].Time.Before(cfg.PendingDevices[j].Time)
  317. })
  318. var newPendingDevices []ObservedDevice
  319. nextPendingDevice:
  320. for _, pendingDevice := range cfg.PendingDevices {
  321. if !existingDevices[pendingDevice.ID] && !ignoredDevices[pendingDevice.ID] {
  322. // Deduplicate
  323. for _, existingPendingDevice := range newPendingDevices {
  324. if existingPendingDevice.ID == pendingDevice.ID {
  325. continue nextPendingDevice
  326. }
  327. }
  328. newPendingDevices = append(newPendingDevices, pendingDevice)
  329. }
  330. }
  331. cfg.PendingDevices = newPendingDevices
  332. // Deprecated protocols are removed from the list of listeners and
  333. // device addresses. So far just kcp*.
  334. for _, prefix := range []string{"kcp"} {
  335. cfg.Options.ListenAddresses = filterURLSchemePrefix(cfg.Options.ListenAddresses, prefix)
  336. for i := range cfg.Devices {
  337. dev := &cfg.Devices[i]
  338. dev.Addresses = filterURLSchemePrefix(dev.Addresses, prefix)
  339. }
  340. }
  341. // Initialize any empty slices
  342. if cfg.Folders == nil {
  343. cfg.Folders = []FolderConfiguration{}
  344. }
  345. if cfg.IgnoredDevices == nil {
  346. cfg.IgnoredDevices = []ObservedDevice{}
  347. }
  348. if cfg.PendingDevices == nil {
  349. cfg.PendingDevices = []ObservedDevice{}
  350. }
  351. if cfg.Options.AlwaysLocalNets == nil {
  352. cfg.Options.AlwaysLocalNets = []string{}
  353. }
  354. if cfg.Options.UnackedNotificationIDs == nil {
  355. cfg.Options.UnackedNotificationIDs = []string{}
  356. }
  357. return nil
  358. }
  359. // DeviceMap returns a map of device ID to device configuration for the given configuration.
  360. func (cfg *Configuration) DeviceMap() map[protocol.DeviceID]DeviceConfiguration {
  361. m := make(map[protocol.DeviceID]DeviceConfiguration, len(cfg.Devices))
  362. for _, dev := range cfg.Devices {
  363. m[dev.DeviceID] = dev
  364. }
  365. return m
  366. }
  367. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  368. for _, device := range devices {
  369. if device.DeviceID.Equals(myID) {
  370. return devices
  371. }
  372. }
  373. devices = append(devices, FolderDeviceConfiguration{
  374. DeviceID: myID,
  375. })
  376. return devices
  377. }
  378. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  379. count := len(devices)
  380. i := 0
  381. loop:
  382. for i < count {
  383. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  384. devices[i] = devices[count-1]
  385. count--
  386. continue loop
  387. }
  388. i++
  389. }
  390. return devices[0:count]
  391. }
  392. func ensureNoDuplicateFolderDevices(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  393. count := len(devices)
  394. i := 0
  395. seenDevices := make(map[protocol.DeviceID]bool)
  396. loop:
  397. for i < count {
  398. id := devices[i].DeviceID
  399. if _, ok := seenDevices[id]; ok {
  400. devices[i] = devices[count-1]
  401. count--
  402. continue loop
  403. }
  404. seenDevices[id] = true
  405. i++
  406. }
  407. return devices[0:count]
  408. }
  409. func ensureNoDuplicateOrEmptyIDDevices(devices []DeviceConfiguration) []DeviceConfiguration {
  410. count := len(devices)
  411. i := 0
  412. seenDevices := make(map[protocol.DeviceID]bool)
  413. loop:
  414. for i < count {
  415. id := devices[i].DeviceID
  416. if _, ok := seenDevices[id]; ok || id == protocol.EmptyDeviceID {
  417. devices[i] = devices[count-1]
  418. count--
  419. continue loop
  420. }
  421. seenDevices[id] = true
  422. i++
  423. }
  424. return devices[0:count]
  425. }
  426. func cleanSymlinks(filesystem fs.Filesystem, dir string) {
  427. if runtime.GOOS == "windows" {
  428. // We don't do symlinks on Windows. Additionally, there may
  429. // be things that look like symlinks that are not, which we
  430. // should leave alone. Deduplicated files, for example.
  431. return
  432. }
  433. filesystem.Walk(dir, func(path string, info fs.FileInfo, err error) error {
  434. if err != nil {
  435. return err
  436. }
  437. if info.IsSymlink() {
  438. l.Infoln("Removing incorrectly versioned symlink", path)
  439. filesystem.Remove(path)
  440. return fs.SkipDir
  441. }
  442. return nil
  443. })
  444. }
  445. // filterURLSchemePrefix returns the list of addresses after removing all
  446. // entries whose URL scheme matches the given prefix.
  447. func filterURLSchemePrefix(addrs []string, prefix string) []string {
  448. for i := 0; i < len(addrs); i++ {
  449. uri, err := url.Parse(addrs[i])
  450. if err != nil {
  451. continue
  452. }
  453. if strings.HasPrefix(uri.Scheme, prefix) {
  454. // Remove this entry
  455. copy(addrs[i:], addrs[i+1:])
  456. addrs = addrs[:len(addrs)-1]
  457. i--
  458. }
  459. }
  460. return addrs
  461. }
  462. // tried in succession and the first to succeed is returned. If none succeed,
  463. // a random high port is returned.
  464. func getFreePort(host string, ports ...int) (int, error) {
  465. for _, port := range ports {
  466. c, err := net.Listen("tcp", fmt.Sprintf("%s:%d", host, port))
  467. if err == nil {
  468. c.Close()
  469. return port, nil
  470. }
  471. }
  472. c, err := net.Listen("tcp", host+":0")
  473. if err != nil {
  474. return 0, err
  475. }
  476. addr := c.Addr().(*net.TCPAddr)
  477. c.Close()
  478. return addr.Port, nil
  479. }