config.go 17 KB

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