config.go 16 KB

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