config.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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 = 32
  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. newCfg.PendingDevices = make([]ObservedDevice, len(cfg.PendingDevices))
  174. copy(newCfg.PendingDevices, cfg.PendingDevices)
  175. return newCfg
  176. }
  177. func (cfg *Configuration) WriteXML(w io.Writer) error {
  178. e := xml.NewEncoder(w)
  179. e.Indent("", " ")
  180. xmlCfg := xmlConfiguration{Configuration: *cfg}
  181. err := e.Encode(xmlCfg)
  182. if err != nil {
  183. return err
  184. }
  185. _, err = w.Write([]byte("\n"))
  186. return err
  187. }
  188. func (cfg *Configuration) prepare(myID protocol.DeviceID) error {
  189. cfg.ensureMyDevice(myID)
  190. existingDevices, err := cfg.prepareFoldersAndDevices(myID)
  191. if err != nil {
  192. return err
  193. }
  194. cfg.GUI.prepare()
  195. guiPWIsSet := cfg.GUI.User != "" && cfg.GUI.Password != ""
  196. cfg.Options.prepare(guiPWIsSet)
  197. ignoredDevices := cfg.prepareIgnoredDevices(existingDevices)
  198. cfg.preparePendingDevices(existingDevices, ignoredDevices)
  199. cfg.removeDeprecatedProtocols()
  200. util.FillNilExceptDeprecated(cfg)
  201. // TestIssue1750 relies on migrations happening after preparing options.
  202. cfg.applyMigrations()
  203. return nil
  204. }
  205. func (cfg *Configuration) ensureMyDevice(myID protocol.DeviceID) {
  206. // Ensure this device is present in the config
  207. for _, device := range cfg.Devices {
  208. if device.DeviceID == myID {
  209. return
  210. }
  211. }
  212. myName, _ := os.Hostname()
  213. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  214. DeviceID: myID,
  215. Name: myName,
  216. })
  217. }
  218. func (cfg *Configuration) prepareFoldersAndDevices(myID protocol.DeviceID) (map[protocol.DeviceID]bool, error) {
  219. existingDevices := cfg.prepareDeviceList()
  220. sharedFolders, err := cfg.prepareFolders(myID, existingDevices)
  221. if err != nil {
  222. return nil, err
  223. }
  224. cfg.prepareDevices(sharedFolders)
  225. return existingDevices, nil
  226. }
  227. func (cfg *Configuration) prepareDeviceList() map[protocol.DeviceID]bool {
  228. // Ensure that the device list is
  229. // - free from duplicates
  230. // - no devices with empty ID
  231. // - sorted by ID
  232. // Happen before preparting folders as that needs a correct device list.
  233. cfg.Devices = ensureNoDuplicateOrEmptyIDDevices(cfg.Devices)
  234. sort.Slice(cfg.Devices, func(a, b int) bool {
  235. return cfg.Devices[a].DeviceID.Compare(cfg.Devices[b].DeviceID) == -1
  236. })
  237. // Build a list of available devices
  238. existingDevices := make(map[protocol.DeviceID]bool, len(cfg.Devices))
  239. for _, device := range cfg.Devices {
  240. existingDevices[device.DeviceID] = true
  241. }
  242. return existingDevices
  243. }
  244. func (cfg *Configuration) prepareFolders(myID protocol.DeviceID, existingDevices map[protocol.DeviceID]bool) (map[protocol.DeviceID][]string, error) {
  245. // Prepare folders and check for duplicates. Duplicates are bad and
  246. // dangerous, can't currently be resolved in the GUI, and shouldn't
  247. // happen when configured by the GUI. We return with an error in that
  248. // situation.
  249. sharedFolders := make(map[protocol.DeviceID][]string, len(cfg.Devices))
  250. existingFolders := make(map[string]*FolderConfiguration, len(cfg.Folders))
  251. for i := range cfg.Folders {
  252. folder := &cfg.Folders[i]
  253. if folder.ID == "" {
  254. return nil, errFolderIDEmpty
  255. }
  256. if folder.Path == "" {
  257. return nil, fmt.Errorf("folder %q: %w", folder.ID, errFolderPathEmpty)
  258. }
  259. if _, ok := existingFolders[folder.ID]; ok {
  260. return nil, fmt.Errorf("folder %q: %w", folder.ID, errFolderIDDuplicate)
  261. }
  262. folder.prepare(myID, existingDevices)
  263. existingFolders[folder.ID] = folder
  264. for _, dev := range folder.Devices {
  265. sharedFolders[dev.DeviceID] = append(sharedFolders[dev.DeviceID], folder.ID)
  266. }
  267. }
  268. // Ensure that the folder list is sorted by ID
  269. sort.Slice(cfg.Folders, func(a, b int) bool {
  270. return cfg.Folders[a].ID < cfg.Folders[b].ID
  271. })
  272. return sharedFolders, nil
  273. }
  274. func (cfg *Configuration) prepareDevices(sharedFolders map[protocol.DeviceID][]string) {
  275. for i := range cfg.Devices {
  276. cfg.Devices[i].prepare(sharedFolders[cfg.Devices[i].DeviceID])
  277. }
  278. }
  279. func (cfg *Configuration) prepareIgnoredDevices(existingDevices map[protocol.DeviceID]bool) map[protocol.DeviceID]bool {
  280. // The list of ignored devices should not contain any devices that have
  281. // been manually added to the config.
  282. newIgnoredDevices := cfg.IgnoredDevices[:0]
  283. ignoredDevices := make(map[protocol.DeviceID]bool, len(cfg.IgnoredDevices))
  284. for _, dev := range cfg.IgnoredDevices {
  285. if !existingDevices[dev.ID] {
  286. ignoredDevices[dev.ID] = true
  287. newIgnoredDevices = append(newIgnoredDevices, dev)
  288. }
  289. }
  290. cfg.IgnoredDevices = newIgnoredDevices
  291. return ignoredDevices
  292. }
  293. func (cfg *Configuration) preparePendingDevices(existingDevices, ignoredDevices map[protocol.DeviceID]bool) {
  294. // The list of pending devices should not contain devices that were added manually, nor should it contain
  295. // ignored devices.
  296. // Sort by time, so that in case of duplicates latest "time" is used.
  297. sort.Slice(cfg.PendingDevices, func(i, j int) bool {
  298. return cfg.PendingDevices[i].Time.Before(cfg.PendingDevices[j].Time)
  299. })
  300. newPendingDevices := cfg.PendingDevices[:0]
  301. nextPendingDevice:
  302. for _, pendingDevice := range cfg.PendingDevices {
  303. if !existingDevices[pendingDevice.ID] && !ignoredDevices[pendingDevice.ID] {
  304. // Deduplicate
  305. for _, existingPendingDevice := range newPendingDevices {
  306. if existingPendingDevice.ID == pendingDevice.ID {
  307. continue nextPendingDevice
  308. }
  309. }
  310. newPendingDevices = append(newPendingDevices, pendingDevice)
  311. }
  312. }
  313. cfg.PendingDevices = newPendingDevices
  314. }
  315. func (cfg *Configuration) removeDeprecatedProtocols() {
  316. // Deprecated protocols are removed from the list of listeners and
  317. // device addresses. So far just kcp*.
  318. for _, prefix := range []string{"kcp"} {
  319. cfg.Options.RawListenAddresses = filterURLSchemePrefix(cfg.Options.RawListenAddresses, prefix)
  320. for i := range cfg.Devices {
  321. dev := &cfg.Devices[i]
  322. dev.Addresses = filterURLSchemePrefix(dev.Addresses, prefix)
  323. }
  324. }
  325. }
  326. func (cfg *Configuration) applyMigrations() {
  327. if cfg.Version > 0 && cfg.Version < OldestHandledVersion {
  328. l.Warnf("Configuration version %d is deprecated. Attempting best effort conversion, but please verify manually.", cfg.Version)
  329. }
  330. // Upgrade configuration versions as appropriate
  331. migrationsMut.Lock()
  332. migrations.apply(cfg)
  333. migrationsMut.Unlock()
  334. }
  335. // DeviceMap returns a map of device ID to device configuration for the given configuration.
  336. func (cfg *Configuration) DeviceMap() map[protocol.DeviceID]DeviceConfiguration {
  337. m := make(map[protocol.DeviceID]DeviceConfiguration, len(cfg.Devices))
  338. for _, dev := range cfg.Devices {
  339. m[dev.DeviceID] = dev
  340. }
  341. return m
  342. }
  343. // FolderPasswords returns the folder passwords set for this device, for
  344. // folders that have an encryption password set.
  345. func (cfg Configuration) FolderPasswords(device protocol.DeviceID) map[string]string {
  346. res := make(map[string]string, len(cfg.Folders))
  347. nextFolder:
  348. for _, folder := range cfg.Folders {
  349. for _, dev := range folder.Devices {
  350. if dev.DeviceID == device && dev.EncryptionPassword != "" {
  351. res[folder.ID] = dev.EncryptionPassword
  352. continue nextFolder
  353. }
  354. }
  355. }
  356. return res
  357. }
  358. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  359. for _, device := range devices {
  360. if device.DeviceID.Equals(myID) {
  361. return devices
  362. }
  363. }
  364. devices = append(devices, FolderDeviceConfiguration{
  365. DeviceID: myID,
  366. })
  367. return devices
  368. }
  369. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  370. count := len(devices)
  371. i := 0
  372. loop:
  373. for i < count {
  374. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  375. devices[i] = devices[count-1]
  376. count--
  377. continue loop
  378. }
  379. i++
  380. }
  381. return devices[0:count]
  382. }
  383. func ensureNoDuplicateFolderDevices(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  384. count := len(devices)
  385. i := 0
  386. seenDevices := make(map[protocol.DeviceID]bool)
  387. loop:
  388. for i < count {
  389. id := devices[i].DeviceID
  390. if _, ok := seenDevices[id]; ok {
  391. devices[i] = devices[count-1]
  392. count--
  393. continue loop
  394. }
  395. seenDevices[id] = true
  396. i++
  397. }
  398. return devices[0:count]
  399. }
  400. func ensureNoDuplicateOrEmptyIDDevices(devices []DeviceConfiguration) []DeviceConfiguration {
  401. count := len(devices)
  402. i := 0
  403. seenDevices := make(map[protocol.DeviceID]bool)
  404. loop:
  405. for i < count {
  406. id := devices[i].DeviceID
  407. if _, ok := seenDevices[id]; ok || id == protocol.EmptyDeviceID {
  408. devices[i] = devices[count-1]
  409. count--
  410. continue loop
  411. }
  412. seenDevices[id] = true
  413. i++
  414. }
  415. return devices[0:count]
  416. }
  417. func cleanSymlinks(filesystem fs.Filesystem, dir string) {
  418. if runtime.GOOS == "windows" {
  419. // We don't do symlinks on Windows. Additionally, there may
  420. // be things that look like symlinks that are not, which we
  421. // should leave alone. Deduplicated files, for example.
  422. return
  423. }
  424. filesystem.Walk(dir, func(path string, info fs.FileInfo, err error) error {
  425. if err != nil {
  426. return err
  427. }
  428. if info.IsSymlink() {
  429. l.Infoln("Removing incorrectly versioned symlink", path)
  430. filesystem.Remove(path)
  431. return fs.SkipDir
  432. }
  433. return nil
  434. })
  435. }
  436. // filterURLSchemePrefix returns the list of addresses after removing all
  437. // entries whose URL scheme matches the given prefix.
  438. func filterURLSchemePrefix(addrs []string, prefix string) []string {
  439. for i := 0; i < len(addrs); i++ {
  440. uri, err := url.Parse(addrs[i])
  441. if err != nil {
  442. continue
  443. }
  444. if strings.HasPrefix(uri.Scheme, prefix) {
  445. // Remove this entry
  446. copy(addrs[i:], addrs[i+1:])
  447. addrs = addrs[:len(addrs)-1]
  448. i--
  449. }
  450. }
  451. return addrs
  452. }
  453. // tried in succession and the first to succeed is returned. If none succeed,
  454. // a random high port is returned.
  455. func getFreePort(host string, ports ...int) (int, error) {
  456. for _, port := range ports {
  457. c, err := net.Listen("tcp", fmt.Sprintf("%s:%d", host, port))
  458. if err == nil {
  459. c.Close()
  460. return port, nil
  461. }
  462. }
  463. c, err := net.Listen("tcp", host+":0")
  464. if err != nil {
  465. return 0, err
  466. }
  467. addr := c.Addr().(*net.TCPAddr)
  468. c.Close()
  469. return addr.Port, nil
  470. }