config.go 17 KB

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