config.go 16 KB

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