config.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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. "path"
  18. "path/filepath"
  19. "runtime"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "github.com/syncthing/syncthing/lib/fs"
  24. "github.com/syncthing/syncthing/lib/protocol"
  25. "github.com/syncthing/syncthing/lib/rand"
  26. "github.com/syncthing/syncthing/lib/upgrade"
  27. "github.com/syncthing/syncthing/lib/util"
  28. )
  29. const (
  30. OldestHandledVersion = 10
  31. CurrentVersion = 27
  32. MaxRescanIntervalS = 365 * 24 * 60 * 60
  33. )
  34. var (
  35. // DefaultTCPPort defines default TCP port used if the URI does not specify one, for example tcp://0.0.0.0
  36. DefaultTCPPort = 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. }
  45. // DefaultDiscoveryServersV4 should be substituted when the configuration
  46. // contains <globalAnnounceServer>default-v4</globalAnnounceServer>.
  47. DefaultDiscoveryServersV4 = []string{
  48. "https://discovery.syncthing.net/v2/?noannounce&id=LYXKCHX-VI3NYZR-ALCJBHF-WMZYSPK-QG6QJA3-MPFYMSO-U56GTUK-NA2MIAW",
  49. "https://discovery-v4.syncthing.net/v2/?nolookup&id=LYXKCHX-VI3NYZR-ALCJBHF-WMZYSPK-QG6QJA3-MPFYMSO-U56GTUK-NA2MIAW",
  50. }
  51. // DefaultDiscoveryServersV6 should be substituted when the configuration
  52. // contains <globalAnnounceServer>default-v6</globalAnnounceServer>.
  53. DefaultDiscoveryServersV6 = []string{
  54. "https://discovery.syncthing.net/v2/?noannounce&id=LYXKCHX-VI3NYZR-ALCJBHF-WMZYSPK-QG6QJA3-MPFYMSO-U56GTUK-NA2MIAW",
  55. "https://discovery-v6.syncthing.net/v2/?nolookup&id=LYXKCHX-VI3NYZR-ALCJBHF-WMZYSPK-QG6QJA3-MPFYMSO-U56GTUK-NA2MIAW",
  56. }
  57. // DefaultDiscoveryServers should be substituted when the configuration
  58. // contains <globalAnnounceServer>default</globalAnnounceServer>.
  59. DefaultDiscoveryServers = append(DefaultDiscoveryServersV4, DefaultDiscoveryServersV6...)
  60. // DefaultTheme is the default and fallback theme for the web UI.
  61. DefaultTheme = "default"
  62. )
  63. func New(myID protocol.DeviceID) Configuration {
  64. var cfg Configuration
  65. cfg.Version = CurrentVersion
  66. cfg.OriginalVersion = CurrentVersion
  67. util.SetDefaults(&cfg)
  68. util.SetDefaults(&cfg.Options)
  69. util.SetDefaults(&cfg.GUI)
  70. // Can't happen.
  71. if err := cfg.prepare(myID); err != nil {
  72. panic("bug: error in preparing new folder: " + err.Error())
  73. }
  74. return cfg
  75. }
  76. func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  77. var cfg Configuration
  78. util.SetDefaults(&cfg)
  79. util.SetDefaults(&cfg.Options)
  80. util.SetDefaults(&cfg.GUI)
  81. if err := xml.NewDecoder(r).Decode(&cfg); err != nil {
  82. return Configuration{}, err
  83. }
  84. cfg.OriginalVersion = cfg.Version
  85. if err := cfg.prepare(myID); err != nil {
  86. return Configuration{}, err
  87. }
  88. return cfg, nil
  89. }
  90. func ReadJSON(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  91. var cfg Configuration
  92. util.SetDefaults(&cfg)
  93. util.SetDefaults(&cfg.Options)
  94. util.SetDefaults(&cfg.GUI)
  95. bs, err := ioutil.ReadAll(r)
  96. if err != nil {
  97. return Configuration{}, err
  98. }
  99. if err := json.Unmarshal(bs, &cfg); err != nil {
  100. return Configuration{}, err
  101. }
  102. cfg.OriginalVersion = cfg.Version
  103. if err := cfg.prepare(myID); err != nil {
  104. return Configuration{}, err
  105. }
  106. return cfg, nil
  107. }
  108. type Configuration struct {
  109. Version int `xml:"version,attr" json:"version"`
  110. Folders []FolderConfiguration `xml:"folder" json:"folders"`
  111. Devices []DeviceConfiguration `xml:"device" json:"devices"`
  112. GUI GUIConfiguration `xml:"gui" json:"gui"`
  113. Options OptionsConfiguration `xml:"options" json:"options"`
  114. IgnoredDevices []protocol.DeviceID `xml:"ignoredDevice" json:"ignoredDevices"`
  115. IgnoredFolders []string `xml:"ignoredFolder" json:"ignoredFolders"`
  116. XMLName xml.Name `xml:"configuration" json:"-"`
  117. MyID protocol.DeviceID `xml:"-" json:"-"` // Provided by the instantiator.
  118. OriginalVersion int `xml:"-" json:"-"` // The version we read from disk, before any conversion
  119. }
  120. func (cfg Configuration) Copy() Configuration {
  121. newCfg := cfg
  122. // Deep copy FolderConfigurations
  123. newCfg.Folders = make([]FolderConfiguration, len(cfg.Folders))
  124. for i := range newCfg.Folders {
  125. newCfg.Folders[i] = cfg.Folders[i].Copy()
  126. }
  127. // Deep copy DeviceConfigurations
  128. newCfg.Devices = make([]DeviceConfiguration, len(cfg.Devices))
  129. for i := range newCfg.Devices {
  130. newCfg.Devices[i] = cfg.Devices[i].Copy()
  131. }
  132. newCfg.Options = cfg.Options.Copy()
  133. // DeviceIDs are values
  134. newCfg.IgnoredDevices = make([]protocol.DeviceID, len(cfg.IgnoredDevices))
  135. copy(newCfg.IgnoredDevices, cfg.IgnoredDevices)
  136. // FolderConfiguraion.ID is type string
  137. newCfg.IgnoredFolders = make([]string, len(cfg.IgnoredFolders))
  138. copy(newCfg.IgnoredFolders, cfg.IgnoredFolders)
  139. return newCfg
  140. }
  141. func (cfg *Configuration) WriteXML(w io.Writer) error {
  142. e := xml.NewEncoder(w)
  143. e.Indent("", " ")
  144. err := e.Encode(cfg)
  145. if err != nil {
  146. return err
  147. }
  148. _, err = w.Write([]byte("\n"))
  149. return err
  150. }
  151. func (cfg *Configuration) prepare(myID protocol.DeviceID) error {
  152. var myName string
  153. cfg.MyID = myID
  154. // Ensure this device is present in the config
  155. for _, device := range cfg.Devices {
  156. if device.DeviceID == myID {
  157. goto found
  158. }
  159. }
  160. myName, _ = os.Hostname()
  161. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  162. DeviceID: myID,
  163. Name: myName,
  164. })
  165. found:
  166. if err := cfg.clean(); err != nil {
  167. return err
  168. }
  169. // Ensure that we are part of the devices
  170. for i := range cfg.Folders {
  171. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  172. }
  173. return nil
  174. }
  175. func (cfg *Configuration) clean() error {
  176. util.FillNilSlices(&cfg.Options)
  177. // Initialize any empty slices
  178. if cfg.Folders == nil {
  179. cfg.Folders = []FolderConfiguration{}
  180. }
  181. if cfg.IgnoredDevices == nil {
  182. cfg.IgnoredDevices = []protocol.DeviceID{}
  183. }
  184. if cfg.IgnoredFolders == nil {
  185. cfg.IgnoredFolders = []string{}
  186. }
  187. if cfg.Options.AlwaysLocalNets == nil {
  188. cfg.Options.AlwaysLocalNets = []string{}
  189. }
  190. if cfg.Options.UnackedNotificationIDs == nil {
  191. cfg.Options.UnackedNotificationIDs = []string{}
  192. }
  193. // Prepare folders and check for duplicates. Duplicates are bad and
  194. // dangerous, can't currently be resolved in the GUI, and shouldn't
  195. // happen when configured by the GUI. We return with an error in that
  196. // situation.
  197. seenFolders := make(map[string]struct{})
  198. for i := range cfg.Folders {
  199. folder := &cfg.Folders[i]
  200. folder.prepare()
  201. if folder.ID == "" {
  202. return fmt.Errorf("folder with empty ID in configuration")
  203. }
  204. if _, ok := seenFolders[folder.ID]; ok {
  205. return fmt.Errorf("duplicate folder ID %q in configuration", folder.ID)
  206. }
  207. seenFolders[folder.ID] = struct{}{}
  208. }
  209. // Remove ignored folders that are anyway part of the configuration.
  210. for i := 0; i < len(cfg.IgnoredFolders); i++ {
  211. if _, ok := seenFolders[cfg.IgnoredFolders[i]]; ok {
  212. cfg.IgnoredFolders = append(cfg.IgnoredFolders[:i], cfg.IgnoredFolders[i+1:]...)
  213. i-- // IgnoredFolders[i] now points to something else, so needs to be rechecked
  214. }
  215. }
  216. cfg.Options.ListenAddresses = util.UniqueStrings(cfg.Options.ListenAddresses)
  217. cfg.Options.GlobalAnnServers = util.UniqueStrings(cfg.Options.GlobalAnnServers)
  218. if cfg.Version > 0 && cfg.Version < OldestHandledVersion {
  219. l.Warnf("Configuration version %d is deprecated. Attempting best effort conversion, but please verify manually.", cfg.Version)
  220. }
  221. // Upgrade configuration versions as appropriate
  222. if cfg.Version <= 10 {
  223. convertV10V11(cfg)
  224. }
  225. if cfg.Version == 11 {
  226. convertV11V12(cfg)
  227. }
  228. if cfg.Version == 12 {
  229. convertV12V13(cfg)
  230. }
  231. if cfg.Version == 13 {
  232. convertV13V14(cfg)
  233. }
  234. if cfg.Version == 14 {
  235. convertV14V15(cfg)
  236. }
  237. if cfg.Version == 15 {
  238. convertV15V16(cfg)
  239. }
  240. if cfg.Version == 16 {
  241. convertV16V17(cfg)
  242. }
  243. if cfg.Version == 17 {
  244. convertV17V18(cfg)
  245. }
  246. if cfg.Version == 18 {
  247. convertV18V19(cfg)
  248. }
  249. if cfg.Version == 19 {
  250. convertV19V20(cfg)
  251. }
  252. if cfg.Version == 20 {
  253. convertV20V21(cfg)
  254. }
  255. if cfg.Version == 21 {
  256. convertV21V22(cfg)
  257. }
  258. if cfg.Version == 22 {
  259. convertV22V23(cfg)
  260. }
  261. if cfg.Version == 23 {
  262. convertV23V24(cfg)
  263. }
  264. if cfg.Version == 24 {
  265. convertV24V25(cfg)
  266. }
  267. if cfg.Version == 25 {
  268. convertV25V26(cfg)
  269. }
  270. if cfg.Version == 26 {
  271. convertV26V27(cfg)
  272. }
  273. // Build a list of available devices
  274. existingDevices := make(map[protocol.DeviceID]bool)
  275. for _, device := range cfg.Devices {
  276. existingDevices[device.DeviceID] = true
  277. }
  278. // Ensure that the device list is free from duplicates
  279. cfg.Devices = ensureNoDuplicateDevices(cfg.Devices)
  280. sort.Sort(DeviceConfigurationList(cfg.Devices))
  281. // Ensure that any loose devices are not present in the wrong places
  282. // Ensure that there are no duplicate devices
  283. // Ensure that the versioning configuration parameter map is not nil
  284. for i := range cfg.Folders {
  285. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  286. cfg.Folders[i].Devices = ensureNoDuplicateFolderDevices(cfg.Folders[i].Devices)
  287. if cfg.Folders[i].Versioning.Params == nil {
  288. cfg.Folders[i].Versioning.Params = map[string]string{}
  289. }
  290. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  291. }
  292. for i := range cfg.Devices {
  293. cfg.Devices[i].prepare()
  294. }
  295. // Very short reconnection intervals are annoying
  296. if cfg.Options.ReconnectIntervalS < 5 {
  297. cfg.Options.ReconnectIntervalS = 5
  298. }
  299. if cfg.GUI.APIKey == "" {
  300. cfg.GUI.APIKey = rand.String(32)
  301. }
  302. // The list of ignored devices should not contain any devices that have
  303. // been manually added to the config.
  304. newIgnoredDevices := []protocol.DeviceID{}
  305. for _, dev := range cfg.IgnoredDevices {
  306. if !existingDevices[dev] {
  307. newIgnoredDevices = append(newIgnoredDevices, dev)
  308. }
  309. }
  310. cfg.IgnoredDevices = newIgnoredDevices
  311. // Deprecated protocols are removed from the list of listeners and
  312. // device addresses. So far just kcp*.
  313. for _, prefix := range []string{"kcp"} {
  314. cfg.Options.ListenAddresses = filterURLSchemePrefix(cfg.Options.ListenAddresses, prefix)
  315. for i := range cfg.Devices {
  316. dev := &cfg.Devices[i]
  317. dev.Addresses = filterURLSchemePrefix(dev.Addresses, prefix)
  318. }
  319. }
  320. return nil
  321. }
  322. func convertV26V27(cfg *Configuration) {
  323. for i := range cfg.Folders {
  324. f := &cfg.Folders[i]
  325. if f.DeprecatedPullers != 0 {
  326. f.PullerMaxPendingKiB = 128 * f.DeprecatedPullers
  327. f.DeprecatedPullers = 0
  328. }
  329. }
  330. cfg.Version = 27
  331. }
  332. func convertV25V26(cfg *Configuration) {
  333. // triggers database update
  334. cfg.Version = 26
  335. }
  336. func convertV24V25(cfg *Configuration) {
  337. for i := range cfg.Folders {
  338. cfg.Folders[i].FSWatcherDelayS = 10
  339. }
  340. cfg.Version = 25
  341. }
  342. func convertV23V24(cfg *Configuration) {
  343. cfg.Options.URSeen = 2
  344. cfg.Version = 24
  345. }
  346. func convertV22V23(cfg *Configuration) {
  347. permBits := fs.FileMode(0777)
  348. if runtime.GOOS == "windows" {
  349. // Windows has no umask so we must chose a safer set of bits to
  350. // begin with.
  351. permBits = 0700
  352. }
  353. // Upgrade code remains hardcoded for .stfolder despite configurable
  354. // marker name in later versions.
  355. for i := range cfg.Folders {
  356. fs := cfg.Folders[i].Filesystem()
  357. // Invalid config posted, or tests.
  358. if fs == nil {
  359. continue
  360. }
  361. if stat, err := fs.Stat(DefaultMarkerName); err == nil && !stat.IsDir() {
  362. err = fs.Remove(DefaultMarkerName)
  363. if err == nil {
  364. err = fs.Mkdir(DefaultMarkerName, permBits)
  365. fs.Hide(DefaultMarkerName) // ignore error
  366. }
  367. if err != nil {
  368. l.Infoln("Failed to upgrade folder marker:", err)
  369. }
  370. }
  371. }
  372. cfg.Version = 23
  373. }
  374. func convertV21V22(cfg *Configuration) {
  375. for i := range cfg.Folders {
  376. cfg.Folders[i].FilesystemType = fs.FilesystemTypeBasic
  377. // Migrate to templated external versioner commands
  378. if cfg.Folders[i].Versioning.Type == "external" {
  379. cfg.Folders[i].Versioning.Params["command"] += " %FOLDER_PATH% %FILE_PATH%"
  380. }
  381. }
  382. cfg.Version = 22
  383. }
  384. func convertV20V21(cfg *Configuration) {
  385. for _, folder := range cfg.Folders {
  386. if folder.FilesystemType != fs.FilesystemTypeBasic {
  387. continue
  388. }
  389. switch folder.Versioning.Type {
  390. case "simple", "trashcan":
  391. // Clean out symlinks in the known place
  392. cleanSymlinks(folder.Filesystem(), ".stversions")
  393. case "staggered":
  394. versionDir := folder.Versioning.Params["versionsPath"]
  395. if versionDir == "" {
  396. // default place
  397. cleanSymlinks(folder.Filesystem(), ".stversions")
  398. } else if filepath.IsAbs(versionDir) {
  399. // absolute
  400. cleanSymlinks(fs.NewFilesystem(fs.FilesystemTypeBasic, versionDir), ".")
  401. } else {
  402. // relative to folder
  403. cleanSymlinks(folder.Filesystem(), versionDir)
  404. }
  405. }
  406. }
  407. cfg.Version = 21
  408. }
  409. func convertV19V20(cfg *Configuration) {
  410. cfg.Options.MinHomeDiskFree = Size{Value: cfg.Options.DeprecatedMinHomeDiskFreePct, Unit: "%"}
  411. cfg.Options.DeprecatedMinHomeDiskFreePct = 0
  412. for i := range cfg.Folders {
  413. cfg.Folders[i].MinDiskFree = Size{Value: cfg.Folders[i].DeprecatedMinDiskFreePct, Unit: "%"}
  414. cfg.Folders[i].DeprecatedMinDiskFreePct = 0
  415. }
  416. cfg.Version = 20
  417. }
  418. func convertV18V19(cfg *Configuration) {
  419. // Triggers a database tweak
  420. cfg.Version = 19
  421. }
  422. func convertV17V18(cfg *Configuration) {
  423. // Do channel selection for existing users. Those who have auto upgrades
  424. // and usage reporting on default to the candidate channel. Others get
  425. // stable.
  426. if cfg.Options.URAccepted > 0 && cfg.Options.AutoUpgradeIntervalH > 0 {
  427. cfg.Options.UpgradeToPreReleases = true
  428. }
  429. // Show a notification to explain what's going on, except if upgrades
  430. // are disabled by compilation or environment variable in which case
  431. // it's not relevant.
  432. if !upgrade.DisabledByCompilation && os.Getenv("STNOUPGRADE") == "" {
  433. cfg.Options.UnackedNotificationIDs = append(cfg.Options.UnackedNotificationIDs, "channelNotification")
  434. }
  435. cfg.Version = 18
  436. }
  437. func convertV16V17(cfg *Configuration) {
  438. // Fsync = true removed
  439. cfg.Version = 17
  440. }
  441. func convertV15V16(cfg *Configuration) {
  442. // Triggers a database tweak
  443. cfg.Version = 16
  444. }
  445. func convertV14V15(cfg *Configuration) {
  446. // Undo v0.13.0 broken migration
  447. for i, addr := range cfg.Options.GlobalAnnServers {
  448. switch addr {
  449. case "default-v4v2/":
  450. cfg.Options.GlobalAnnServers[i] = "default-v4"
  451. case "default-v6v2/":
  452. cfg.Options.GlobalAnnServers[i] = "default-v6"
  453. }
  454. }
  455. cfg.Version = 15
  456. }
  457. func convertV13V14(cfg *Configuration) {
  458. // Not using the ignore cache is the new default. Disable it on existing
  459. // configurations.
  460. cfg.Options.CacheIgnoredFiles = false
  461. // Migrate UPnP -> NAT options
  462. cfg.Options.NATEnabled = cfg.Options.DeprecatedUPnPEnabled
  463. cfg.Options.DeprecatedUPnPEnabled = false
  464. cfg.Options.NATLeaseM = cfg.Options.DeprecatedUPnPLeaseM
  465. cfg.Options.DeprecatedUPnPLeaseM = 0
  466. cfg.Options.NATRenewalM = cfg.Options.DeprecatedUPnPRenewalM
  467. cfg.Options.DeprecatedUPnPRenewalM = 0
  468. cfg.Options.NATTimeoutS = cfg.Options.DeprecatedUPnPTimeoutS
  469. cfg.Options.DeprecatedUPnPTimeoutS = 0
  470. // Replace the default listen address "tcp://0.0.0.0:22000" with the
  471. // string "default", but only if we also have the default relay pool
  472. // among the relay servers as this is implied by the new "default"
  473. // entry.
  474. hasDefault := false
  475. for _, raddr := range cfg.Options.DeprecatedRelayServers {
  476. if raddr == "dynamic+https://relays.syncthing.net/endpoint" {
  477. for i, addr := range cfg.Options.ListenAddresses {
  478. if addr == "tcp://0.0.0.0:22000" {
  479. cfg.Options.ListenAddresses[i] = "default"
  480. hasDefault = true
  481. break
  482. }
  483. }
  484. break
  485. }
  486. }
  487. // Copy relay addresses into listen addresses.
  488. for _, addr := range cfg.Options.DeprecatedRelayServers {
  489. if hasDefault && addr == "dynamic+https://relays.syncthing.net/endpoint" {
  490. // Skip the default relay address if we already have the
  491. // "default" entry in the list.
  492. continue
  493. }
  494. if addr == "" {
  495. continue
  496. }
  497. cfg.Options.ListenAddresses = append(cfg.Options.ListenAddresses, addr)
  498. }
  499. cfg.Options.DeprecatedRelayServers = nil
  500. // For consistency
  501. sort.Strings(cfg.Options.ListenAddresses)
  502. var newAddrs []string
  503. for _, addr := range cfg.Options.GlobalAnnServers {
  504. uri, err := url.Parse(addr)
  505. if err != nil {
  506. // That's odd. Skip the broken address.
  507. continue
  508. }
  509. if uri.Scheme == "https" {
  510. uri.Path = path.Join(uri.Path, "v2") + "/"
  511. addr = uri.String()
  512. }
  513. newAddrs = append(newAddrs, addr)
  514. }
  515. cfg.Options.GlobalAnnServers = newAddrs
  516. for i, fcfg := range cfg.Folders {
  517. if fcfg.DeprecatedReadOnly {
  518. cfg.Folders[i].Type = FolderTypeSendOnly
  519. } else {
  520. cfg.Folders[i].Type = FolderTypeSendReceive
  521. }
  522. cfg.Folders[i].DeprecatedReadOnly = false
  523. }
  524. // v0.13-beta already had config version 13 but did not get the new URL
  525. if cfg.Options.ReleasesURL == "https://api.github.com/repos/syncthing/syncthing/releases?per_page=30" {
  526. cfg.Options.ReleasesURL = "https://upgrades.syncthing.net/meta.json"
  527. }
  528. cfg.Version = 14
  529. }
  530. func convertV12V13(cfg *Configuration) {
  531. if cfg.Options.ReleasesURL == "https://api.github.com/repos/syncthing/syncthing/releases?per_page=30" {
  532. cfg.Options.ReleasesURL = "https://upgrades.syncthing.net/meta.json"
  533. }
  534. cfg.Version = 13
  535. }
  536. func convertV11V12(cfg *Configuration) {
  537. // Change listen address schema
  538. for i, addr := range cfg.Options.ListenAddresses {
  539. if len(addr) > 0 && !strings.HasPrefix(addr, "tcp://") {
  540. cfg.Options.ListenAddresses[i] = util.Address("tcp", addr)
  541. }
  542. }
  543. for i, device := range cfg.Devices {
  544. for j, addr := range device.Addresses {
  545. if addr != "dynamic" && addr != "" {
  546. cfg.Devices[i].Addresses[j] = util.Address("tcp", addr)
  547. }
  548. }
  549. }
  550. // Use new discovery server
  551. var newDiscoServers []string
  552. var useDefault bool
  553. for _, addr := range cfg.Options.GlobalAnnServers {
  554. if addr == "udp4://announce.syncthing.net:22026" {
  555. useDefault = true
  556. } else if addr == "udp6://announce-v6.syncthing.net:22026" {
  557. useDefault = true
  558. } else {
  559. newDiscoServers = append(newDiscoServers, addr)
  560. }
  561. }
  562. if useDefault {
  563. newDiscoServers = append(newDiscoServers, "default")
  564. }
  565. cfg.Options.GlobalAnnServers = newDiscoServers
  566. // Use new multicast group
  567. if cfg.Options.LocalAnnMCAddr == "[ff32::5222]:21026" {
  568. cfg.Options.LocalAnnMCAddr = "[ff12::8384]:21027"
  569. }
  570. // Use new local discovery port
  571. if cfg.Options.LocalAnnPort == 21025 {
  572. cfg.Options.LocalAnnPort = 21027
  573. }
  574. // Set MaxConflicts to unlimited
  575. for i := range cfg.Folders {
  576. cfg.Folders[i].MaxConflicts = -1
  577. }
  578. cfg.Version = 12
  579. }
  580. func convertV10V11(cfg *Configuration) {
  581. // Set minimum disk free of existing folders to 1%
  582. for i := range cfg.Folders {
  583. cfg.Folders[i].DeprecatedMinDiskFreePct = 1
  584. }
  585. cfg.Version = 11
  586. }
  587. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  588. for _, device := range devices {
  589. if device.DeviceID.Equals(myID) {
  590. return devices
  591. }
  592. }
  593. devices = append(devices, FolderDeviceConfiguration{
  594. DeviceID: myID,
  595. })
  596. return devices
  597. }
  598. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  599. count := len(devices)
  600. i := 0
  601. loop:
  602. for i < count {
  603. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  604. devices[i] = devices[count-1]
  605. count--
  606. continue loop
  607. }
  608. i++
  609. }
  610. return devices[0:count]
  611. }
  612. func ensureNoDuplicateFolderDevices(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  613. count := len(devices)
  614. i := 0
  615. seenDevices := make(map[protocol.DeviceID]bool)
  616. loop:
  617. for i < count {
  618. id := devices[i].DeviceID
  619. if _, ok := seenDevices[id]; ok {
  620. devices[i] = devices[count-1]
  621. count--
  622. continue loop
  623. }
  624. seenDevices[id] = true
  625. i++
  626. }
  627. return devices[0:count]
  628. }
  629. func ensureNoDuplicateDevices(devices []DeviceConfiguration) []DeviceConfiguration {
  630. count := len(devices)
  631. i := 0
  632. seenDevices := make(map[protocol.DeviceID]bool)
  633. loop:
  634. for i < count {
  635. id := devices[i].DeviceID
  636. if _, ok := seenDevices[id]; ok {
  637. devices[i] = devices[count-1]
  638. count--
  639. continue loop
  640. }
  641. seenDevices[id] = true
  642. i++
  643. }
  644. return devices[0:count]
  645. }
  646. func cleanSymlinks(filesystem fs.Filesystem, dir string) {
  647. if runtime.GOOS == "windows" {
  648. // We don't do symlinks on Windows. Additionally, there may
  649. // be things that look like symlinks that are not, which we
  650. // should leave alone. Deduplicated files, for example.
  651. return
  652. }
  653. filesystem.Walk(dir, func(path string, info fs.FileInfo, err error) error {
  654. if err != nil {
  655. return err
  656. }
  657. if info.IsSymlink() {
  658. l.Infoln("Removing incorrectly versioned symlink", path)
  659. filesystem.Remove(path)
  660. return fs.SkipDir
  661. }
  662. return nil
  663. })
  664. }
  665. // filterURLSchemePrefix returns the list of addresses after removing all
  666. // entries whose URL scheme matches the given prefix.
  667. func filterURLSchemePrefix(addrs []string, prefix string) []string {
  668. for i := 0; i < len(addrs); i++ {
  669. uri, err := url.Parse(addrs[i])
  670. if err != nil {
  671. continue
  672. }
  673. if strings.HasPrefix(uri.Scheme, prefix) {
  674. // Remove this entry
  675. copy(addrs[i:], addrs[i+1:])
  676. addrs = addrs[:len(addrs)-1]
  677. i--
  678. }
  679. }
  680. return addrs
  681. }