config.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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 = 28
  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. 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. )
  64. func New(myID protocol.DeviceID) Configuration {
  65. var cfg Configuration
  66. cfg.Version = CurrentVersion
  67. cfg.OriginalVersion = CurrentVersion
  68. util.SetDefaults(&cfg)
  69. util.SetDefaults(&cfg.Options)
  70. util.SetDefaults(&cfg.GUI)
  71. // Can't happen.
  72. if err := cfg.prepare(myID); err != nil {
  73. panic("bug: error in preparing new folder: " + err.Error())
  74. }
  75. return cfg
  76. }
  77. func NewWithFreePorts(myID protocol.DeviceID) (Configuration, error) {
  78. cfg := New(myID)
  79. port, err := getFreePort("127.0.0.1", DefaultGUIPort)
  80. if err != nil {
  81. return Configuration{}, fmt.Errorf("get free port (GUI): %v", err)
  82. }
  83. cfg.GUI.RawAddress = fmt.Sprintf("127.0.0.1:%d", port)
  84. port, err = getFreePort("0.0.0.0", DefaultTCPPort)
  85. if err != nil {
  86. return Configuration{}, fmt.Errorf("get free port (BEP): %v", err)
  87. }
  88. if port == DefaultTCPPort {
  89. cfg.Options.ListenAddresses = []string{"default"}
  90. } else {
  91. cfg.Options.ListenAddresses = []string{
  92. fmt.Sprintf("tcp://%s", net.JoinHostPort("0.0.0.0", strconv.Itoa(port))),
  93. "dynamic+https://relays.syncthing.net/endpoint",
  94. }
  95. }
  96. return cfg, nil
  97. }
  98. func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  99. var cfg Configuration
  100. util.SetDefaults(&cfg)
  101. util.SetDefaults(&cfg.Options)
  102. util.SetDefaults(&cfg.GUI)
  103. if err := xml.NewDecoder(r).Decode(&cfg); err != nil {
  104. return Configuration{}, err
  105. }
  106. cfg.OriginalVersion = cfg.Version
  107. if err := cfg.prepare(myID); err != nil {
  108. return Configuration{}, err
  109. }
  110. return cfg, nil
  111. }
  112. func ReadJSON(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  113. var cfg Configuration
  114. util.SetDefaults(&cfg)
  115. util.SetDefaults(&cfg.Options)
  116. util.SetDefaults(&cfg.GUI)
  117. bs, err := ioutil.ReadAll(r)
  118. if err != nil {
  119. return Configuration{}, err
  120. }
  121. if err := json.Unmarshal(bs, &cfg); err != nil {
  122. return Configuration{}, err
  123. }
  124. cfg.OriginalVersion = cfg.Version
  125. if err := cfg.prepare(myID); err != nil {
  126. return Configuration{}, err
  127. }
  128. return cfg, nil
  129. }
  130. type Configuration struct {
  131. Version int `xml:"version,attr" json:"version"`
  132. Folders []FolderConfiguration `xml:"folder" json:"folders"`
  133. Devices []DeviceConfiguration `xml:"device" json:"devices"`
  134. GUI GUIConfiguration `xml:"gui" json:"gui"`
  135. LDAP LDAPConfiguration `xml:"ldap" json:"ldap"`
  136. Options OptionsConfiguration `xml:"options" json:"options"`
  137. IgnoredDevices []ObservedDevice `xml:"remoteIgnoredDevice" json:"remoteIgnoredDevices"`
  138. PendingDevices []ObservedDevice `xml:"pendingDevice" json:"pendingDevices"`
  139. XMLName xml.Name `xml:"configuration" json:"-"`
  140. MyID protocol.DeviceID `xml:"-" json:"-"` // Provided by the instantiator.
  141. OriginalVersion int `xml:"-" json:"-"` // The version we read from disk, before any conversion
  142. }
  143. func (cfg Configuration) Copy() Configuration {
  144. newCfg := cfg
  145. // Deep copy FolderConfigurations
  146. newCfg.Folders = make([]FolderConfiguration, len(cfg.Folders))
  147. for i := range newCfg.Folders {
  148. newCfg.Folders[i] = cfg.Folders[i].Copy()
  149. }
  150. // Deep copy DeviceConfigurations
  151. newCfg.Devices = make([]DeviceConfiguration, len(cfg.Devices))
  152. for i := range newCfg.Devices {
  153. newCfg.Devices[i] = cfg.Devices[i].Copy()
  154. }
  155. newCfg.Options = cfg.Options.Copy()
  156. newCfg.GUI = cfg.GUI.Copy()
  157. // DeviceIDs are values
  158. newCfg.IgnoredDevices = make([]ObservedDevice, len(cfg.IgnoredDevices))
  159. copy(newCfg.IgnoredDevices, cfg.IgnoredDevices)
  160. newCfg.PendingDevices = make([]ObservedDevice, len(cfg.PendingDevices))
  161. copy(newCfg.PendingDevices, cfg.PendingDevices)
  162. return newCfg
  163. }
  164. func (cfg *Configuration) WriteXML(w io.Writer) error {
  165. e := xml.NewEncoder(w)
  166. e.Indent("", " ")
  167. err := e.Encode(cfg)
  168. if err != nil {
  169. return err
  170. }
  171. _, err = w.Write([]byte("\n"))
  172. return err
  173. }
  174. func (cfg *Configuration) prepare(myID protocol.DeviceID) error {
  175. var myName string
  176. cfg.MyID = myID
  177. // Ensure this device is present in the config
  178. for _, device := range cfg.Devices {
  179. if device.DeviceID == myID {
  180. goto found
  181. }
  182. }
  183. myName, _ = os.Hostname()
  184. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  185. DeviceID: myID,
  186. Name: myName,
  187. })
  188. found:
  189. if err := cfg.clean(); err != nil {
  190. return err
  191. }
  192. // Ensure that we are part of the devices
  193. for i := range cfg.Folders {
  194. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  195. }
  196. return nil
  197. }
  198. func (cfg *Configuration) clean() error {
  199. util.FillNilSlices(&cfg.Options)
  200. // Prepare folders and check for duplicates. Duplicates are bad and
  201. // dangerous, can't currently be resolved in the GUI, and shouldn't
  202. // happen when configured by the GUI. We return with an error in that
  203. // situation.
  204. existingFolders := make(map[string]*FolderConfiguration)
  205. for i := range cfg.Folders {
  206. folder := &cfg.Folders[i]
  207. folder.prepare()
  208. if folder.ID == "" {
  209. return fmt.Errorf("folder with empty ID in configuration")
  210. }
  211. if _, ok := existingFolders[folder.ID]; ok {
  212. return fmt.Errorf("duplicate folder ID %q in configuration", folder.ID)
  213. }
  214. existingFolders[folder.ID] = folder
  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. if cfg.Version == 27 {
  274. convertV27V28(cfg)
  275. }
  276. // Build a list of available devices
  277. existingDevices := make(map[protocol.DeviceID]bool)
  278. for _, device := range cfg.Devices {
  279. existingDevices[device.DeviceID] = true
  280. }
  281. // Ensure that the device list is
  282. // - free from duplicates
  283. // - sorted by ID
  284. cfg.Devices = ensureNoDuplicateDevices(cfg.Devices)
  285. sort.Slice(cfg.Devices, func(a, b int) bool {
  286. return cfg.Devices[a].DeviceID.Compare(cfg.Devices[b].DeviceID) == -1
  287. })
  288. // Ensure that the folder list is sorted by ID
  289. sort.Slice(cfg.Folders, func(a, b int) bool {
  290. return cfg.Folders[a].ID < cfg.Folders[b].ID
  291. })
  292. // Ensure that in all folder configs
  293. // - any loose devices are not present in the wrong places
  294. // - there are no duplicate devices
  295. // - the versioning configuration parameter map is not nil
  296. sharedFolders := make(map[protocol.DeviceID][]string, len(cfg.Devices))
  297. for i := range cfg.Folders {
  298. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  299. cfg.Folders[i].Devices = ensureNoDuplicateFolderDevices(cfg.Folders[i].Devices)
  300. if cfg.Folders[i].Versioning.Params == nil {
  301. cfg.Folders[i].Versioning.Params = map[string]string{}
  302. }
  303. sort.Slice(cfg.Folders[i].Devices, func(a, b int) bool {
  304. return cfg.Folders[i].Devices[a].DeviceID.Compare(cfg.Folders[i].Devices[b].DeviceID) == -1
  305. })
  306. for _, dev := range cfg.Folders[i].Devices {
  307. sharedFolders[dev.DeviceID] = append(sharedFolders[dev.DeviceID], cfg.Folders[i].ID)
  308. }
  309. }
  310. for i := range cfg.Devices {
  311. cfg.Devices[i].prepare(sharedFolders[cfg.Devices[i].DeviceID])
  312. }
  313. // Very short reconnection intervals are annoying
  314. if cfg.Options.ReconnectIntervalS < 5 {
  315. cfg.Options.ReconnectIntervalS = 5
  316. }
  317. if cfg.GUI.APIKey == "" {
  318. cfg.GUI.APIKey = rand.String(32)
  319. }
  320. // The list of ignored devices should not contain any devices that have
  321. // been manually added to the config.
  322. var newIgnoredDevices []ObservedDevice
  323. ignoredDevices := make(map[protocol.DeviceID]bool)
  324. for _, dev := range cfg.IgnoredDevices {
  325. if !existingDevices[dev.ID] {
  326. ignoredDevices[dev.ID] = true
  327. newIgnoredDevices = append(newIgnoredDevices, dev)
  328. }
  329. }
  330. cfg.IgnoredDevices = newIgnoredDevices
  331. // The list of pending devices should not contain devices that were added manually, nor should it contain
  332. // ignored devices.
  333. // Sort by time, so that in case of duplicates latest "time" is used.
  334. sort.Slice(cfg.PendingDevices, func(i, j int) bool {
  335. return cfg.PendingDevices[i].Time.Before(cfg.PendingDevices[j].Time)
  336. })
  337. var newPendingDevices []ObservedDevice
  338. nextPendingDevice:
  339. for _, pendingDevice := range cfg.PendingDevices {
  340. if !existingDevices[pendingDevice.ID] && !ignoredDevices[pendingDevice.ID] {
  341. // Deduplicate
  342. for _, existingPendingDevice := range newPendingDevices {
  343. if existingPendingDevice.ID == pendingDevice.ID {
  344. continue nextPendingDevice
  345. }
  346. }
  347. newPendingDevices = append(newPendingDevices, pendingDevice)
  348. }
  349. }
  350. cfg.PendingDevices = newPendingDevices
  351. // Deprecated protocols are removed from the list of listeners and
  352. // device addresses. So far just kcp*.
  353. for _, prefix := range []string{"kcp"} {
  354. cfg.Options.ListenAddresses = filterURLSchemePrefix(cfg.Options.ListenAddresses, prefix)
  355. for i := range cfg.Devices {
  356. dev := &cfg.Devices[i]
  357. dev.Addresses = filterURLSchemePrefix(dev.Addresses, prefix)
  358. }
  359. }
  360. // Initialize any empty slices
  361. if cfg.Folders == nil {
  362. cfg.Folders = []FolderConfiguration{}
  363. }
  364. if cfg.IgnoredDevices == nil {
  365. cfg.IgnoredDevices = []ObservedDevice{}
  366. }
  367. if cfg.PendingDevices == nil {
  368. cfg.PendingDevices = []ObservedDevice{}
  369. }
  370. if cfg.Options.AlwaysLocalNets == nil {
  371. cfg.Options.AlwaysLocalNets = []string{}
  372. }
  373. if cfg.Options.UnackedNotificationIDs == nil {
  374. cfg.Options.UnackedNotificationIDs = []string{}
  375. }
  376. return nil
  377. }
  378. // DeviceMap returns a map of device ID to device configuration for the given configuration.
  379. func (cfg *Configuration) DeviceMap() map[protocol.DeviceID]DeviceConfiguration {
  380. m := make(map[protocol.DeviceID]DeviceConfiguration, len(cfg.Devices))
  381. for _, dev := range cfg.Devices {
  382. m[dev.DeviceID] = dev
  383. }
  384. return m
  385. }
  386. func convertV27V28(cfg *Configuration) {
  387. // Show a notification about enabling filesystem watching
  388. cfg.Options.UnackedNotificationIDs = append(cfg.Options.UnackedNotificationIDs, "fsWatcherNotification")
  389. cfg.Version = 28
  390. }
  391. func convertV26V27(cfg *Configuration) {
  392. for i := range cfg.Folders {
  393. f := &cfg.Folders[i]
  394. if f.DeprecatedPullers != 0 {
  395. f.PullerMaxPendingKiB = 128 * f.DeprecatedPullers
  396. f.DeprecatedPullers = 0
  397. }
  398. }
  399. cfg.Version = 27
  400. }
  401. func convertV25V26(cfg *Configuration) {
  402. // triggers database update
  403. cfg.Version = 26
  404. }
  405. func convertV24V25(cfg *Configuration) {
  406. for i := range cfg.Folders {
  407. cfg.Folders[i].FSWatcherDelayS = 10
  408. }
  409. cfg.Version = 25
  410. }
  411. func convertV23V24(cfg *Configuration) {
  412. cfg.Options.URSeen = 2
  413. cfg.Version = 24
  414. }
  415. func convertV22V23(cfg *Configuration) {
  416. permBits := fs.FileMode(0777)
  417. if runtime.GOOS == "windows" {
  418. // Windows has no umask so we must chose a safer set of bits to
  419. // begin with.
  420. permBits = 0700
  421. }
  422. // Upgrade code remains hardcoded for .stfolder despite configurable
  423. // marker name in later versions.
  424. for i := range cfg.Folders {
  425. fs := cfg.Folders[i].Filesystem()
  426. // Invalid config posted, or tests.
  427. if fs == nil {
  428. continue
  429. }
  430. if stat, err := fs.Stat(DefaultMarkerName); err == nil && !stat.IsDir() {
  431. err = fs.Remove(DefaultMarkerName)
  432. if err == nil {
  433. err = fs.Mkdir(DefaultMarkerName, permBits)
  434. fs.Hide(DefaultMarkerName) // ignore error
  435. }
  436. if err != nil {
  437. l.Infoln("Failed to upgrade folder marker:", err)
  438. }
  439. }
  440. }
  441. cfg.Version = 23
  442. }
  443. func convertV21V22(cfg *Configuration) {
  444. for i := range cfg.Folders {
  445. cfg.Folders[i].FilesystemType = fs.FilesystemTypeBasic
  446. // Migrate to templated external versioner commands
  447. if cfg.Folders[i].Versioning.Type == "external" {
  448. cfg.Folders[i].Versioning.Params["command"] += " %FOLDER_PATH% %FILE_PATH%"
  449. }
  450. }
  451. cfg.Version = 22
  452. }
  453. func convertV20V21(cfg *Configuration) {
  454. for _, folder := range cfg.Folders {
  455. if folder.FilesystemType != fs.FilesystemTypeBasic {
  456. continue
  457. }
  458. switch folder.Versioning.Type {
  459. case "simple", "trashcan":
  460. // Clean out symlinks in the known place
  461. cleanSymlinks(folder.Filesystem(), ".stversions")
  462. case "staggered":
  463. versionDir := folder.Versioning.Params["versionsPath"]
  464. if versionDir == "" {
  465. // default place
  466. cleanSymlinks(folder.Filesystem(), ".stversions")
  467. } else if filepath.IsAbs(versionDir) {
  468. // absolute
  469. cleanSymlinks(fs.NewFilesystem(fs.FilesystemTypeBasic, versionDir), ".")
  470. } else {
  471. // relative to folder
  472. cleanSymlinks(folder.Filesystem(), versionDir)
  473. }
  474. }
  475. }
  476. cfg.Version = 21
  477. }
  478. func convertV19V20(cfg *Configuration) {
  479. cfg.Options.MinHomeDiskFree = Size{Value: cfg.Options.DeprecatedMinHomeDiskFreePct, Unit: "%"}
  480. cfg.Options.DeprecatedMinHomeDiskFreePct = 0
  481. for i := range cfg.Folders {
  482. cfg.Folders[i].MinDiskFree = Size{Value: cfg.Folders[i].DeprecatedMinDiskFreePct, Unit: "%"}
  483. cfg.Folders[i].DeprecatedMinDiskFreePct = 0
  484. }
  485. cfg.Version = 20
  486. }
  487. func convertV18V19(cfg *Configuration) {
  488. // Triggers a database tweak
  489. cfg.Version = 19
  490. }
  491. func convertV17V18(cfg *Configuration) {
  492. // Do channel selection for existing users. Those who have auto upgrades
  493. // and usage reporting on default to the candidate channel. Others get
  494. // stable.
  495. if cfg.Options.URAccepted > 0 && cfg.Options.AutoUpgradeIntervalH > 0 {
  496. cfg.Options.UpgradeToPreReleases = true
  497. }
  498. // Show a notification to explain what's going on, except if upgrades
  499. // are disabled by compilation or environment variable in which case
  500. // it's not relevant.
  501. if !upgrade.DisabledByCompilation && os.Getenv("STNOUPGRADE") == "" {
  502. cfg.Options.UnackedNotificationIDs = append(cfg.Options.UnackedNotificationIDs, "channelNotification")
  503. }
  504. cfg.Version = 18
  505. }
  506. func convertV16V17(cfg *Configuration) {
  507. // Fsync = true removed
  508. cfg.Version = 17
  509. }
  510. func convertV15V16(cfg *Configuration) {
  511. // Triggers a database tweak
  512. cfg.Version = 16
  513. }
  514. func convertV14V15(cfg *Configuration) {
  515. // Undo v0.13.0 broken migration
  516. for i, addr := range cfg.Options.GlobalAnnServers {
  517. switch addr {
  518. case "default-v4v2/":
  519. cfg.Options.GlobalAnnServers[i] = "default-v4"
  520. case "default-v6v2/":
  521. cfg.Options.GlobalAnnServers[i] = "default-v6"
  522. }
  523. }
  524. cfg.Version = 15
  525. }
  526. func convertV13V14(cfg *Configuration) {
  527. // Not using the ignore cache is the new default. Disable it on existing
  528. // configurations.
  529. cfg.Options.CacheIgnoredFiles = false
  530. // Migrate UPnP -> NAT options
  531. cfg.Options.NATEnabled = cfg.Options.DeprecatedUPnPEnabled
  532. cfg.Options.DeprecatedUPnPEnabled = false
  533. cfg.Options.NATLeaseM = cfg.Options.DeprecatedUPnPLeaseM
  534. cfg.Options.DeprecatedUPnPLeaseM = 0
  535. cfg.Options.NATRenewalM = cfg.Options.DeprecatedUPnPRenewalM
  536. cfg.Options.DeprecatedUPnPRenewalM = 0
  537. cfg.Options.NATTimeoutS = cfg.Options.DeprecatedUPnPTimeoutS
  538. cfg.Options.DeprecatedUPnPTimeoutS = 0
  539. // Replace the default listen address "tcp://0.0.0.0:22000" with the
  540. // string "default", but only if we also have the default relay pool
  541. // among the relay servers as this is implied by the new "default"
  542. // entry.
  543. hasDefault := false
  544. for _, raddr := range cfg.Options.DeprecatedRelayServers {
  545. if raddr == "dynamic+https://relays.syncthing.net/endpoint" {
  546. for i, addr := range cfg.Options.ListenAddresses {
  547. if addr == "tcp://0.0.0.0:22000" {
  548. cfg.Options.ListenAddresses[i] = "default"
  549. hasDefault = true
  550. break
  551. }
  552. }
  553. break
  554. }
  555. }
  556. // Copy relay addresses into listen addresses.
  557. for _, addr := range cfg.Options.DeprecatedRelayServers {
  558. if hasDefault && addr == "dynamic+https://relays.syncthing.net/endpoint" {
  559. // Skip the default relay address if we already have the
  560. // "default" entry in the list.
  561. continue
  562. }
  563. if addr == "" {
  564. continue
  565. }
  566. cfg.Options.ListenAddresses = append(cfg.Options.ListenAddresses, addr)
  567. }
  568. cfg.Options.DeprecatedRelayServers = nil
  569. // For consistency
  570. sort.Strings(cfg.Options.ListenAddresses)
  571. var newAddrs []string
  572. for _, addr := range cfg.Options.GlobalAnnServers {
  573. uri, err := url.Parse(addr)
  574. if err != nil {
  575. // That's odd. Skip the broken address.
  576. continue
  577. }
  578. if uri.Scheme == "https" {
  579. uri.Path = path.Join(uri.Path, "v2") + "/"
  580. addr = uri.String()
  581. }
  582. newAddrs = append(newAddrs, addr)
  583. }
  584. cfg.Options.GlobalAnnServers = newAddrs
  585. for i, fcfg := range cfg.Folders {
  586. if fcfg.DeprecatedReadOnly {
  587. cfg.Folders[i].Type = FolderTypeSendOnly
  588. } else {
  589. cfg.Folders[i].Type = FolderTypeSendReceive
  590. }
  591. cfg.Folders[i].DeprecatedReadOnly = false
  592. }
  593. // v0.13-beta already had config version 13 but did not get the new URL
  594. if cfg.Options.ReleasesURL == "https://api.github.com/repos/syncthing/syncthing/releases?per_page=30" {
  595. cfg.Options.ReleasesURL = "https://upgrades.syncthing.net/meta.json"
  596. }
  597. cfg.Version = 14
  598. }
  599. func convertV12V13(cfg *Configuration) {
  600. if cfg.Options.ReleasesURL == "https://api.github.com/repos/syncthing/syncthing/releases?per_page=30" {
  601. cfg.Options.ReleasesURL = "https://upgrades.syncthing.net/meta.json"
  602. }
  603. cfg.Version = 13
  604. }
  605. func convertV11V12(cfg *Configuration) {
  606. // Change listen address schema
  607. for i, addr := range cfg.Options.ListenAddresses {
  608. if len(addr) > 0 && !strings.HasPrefix(addr, "tcp://") {
  609. cfg.Options.ListenAddresses[i] = util.Address("tcp", addr)
  610. }
  611. }
  612. for i, device := range cfg.Devices {
  613. for j, addr := range device.Addresses {
  614. if addr != "dynamic" && addr != "" {
  615. cfg.Devices[i].Addresses[j] = util.Address("tcp", addr)
  616. }
  617. }
  618. }
  619. // Use new discovery server
  620. var newDiscoServers []string
  621. var useDefault bool
  622. for _, addr := range cfg.Options.GlobalAnnServers {
  623. if addr == "udp4://announce.syncthing.net:22026" {
  624. useDefault = true
  625. } else if addr == "udp6://announce-v6.syncthing.net:22026" {
  626. useDefault = true
  627. } else {
  628. newDiscoServers = append(newDiscoServers, addr)
  629. }
  630. }
  631. if useDefault {
  632. newDiscoServers = append(newDiscoServers, "default")
  633. }
  634. cfg.Options.GlobalAnnServers = newDiscoServers
  635. // Use new multicast group
  636. if cfg.Options.LocalAnnMCAddr == "[ff32::5222]:21026" {
  637. cfg.Options.LocalAnnMCAddr = "[ff12::8384]:21027"
  638. }
  639. // Use new local discovery port
  640. if cfg.Options.LocalAnnPort == 21025 {
  641. cfg.Options.LocalAnnPort = 21027
  642. }
  643. // Set MaxConflicts to unlimited
  644. for i := range cfg.Folders {
  645. cfg.Folders[i].MaxConflicts = -1
  646. }
  647. cfg.Version = 12
  648. }
  649. func convertV10V11(cfg *Configuration) {
  650. // Set minimum disk free of existing folders to 1%
  651. for i := range cfg.Folders {
  652. cfg.Folders[i].DeprecatedMinDiskFreePct = 1
  653. }
  654. cfg.Version = 11
  655. }
  656. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  657. for _, device := range devices {
  658. if device.DeviceID.Equals(myID) {
  659. return devices
  660. }
  661. }
  662. devices = append(devices, FolderDeviceConfiguration{
  663. DeviceID: myID,
  664. })
  665. return devices
  666. }
  667. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  668. count := len(devices)
  669. i := 0
  670. loop:
  671. for i < count {
  672. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  673. devices[i] = devices[count-1]
  674. count--
  675. continue loop
  676. }
  677. i++
  678. }
  679. return devices[0:count]
  680. }
  681. func ensureNoDuplicateFolderDevices(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  682. count := len(devices)
  683. i := 0
  684. seenDevices := make(map[protocol.DeviceID]bool)
  685. loop:
  686. for i < count {
  687. id := devices[i].DeviceID
  688. if _, ok := seenDevices[id]; ok {
  689. devices[i] = devices[count-1]
  690. count--
  691. continue loop
  692. }
  693. seenDevices[id] = true
  694. i++
  695. }
  696. return devices[0:count]
  697. }
  698. func ensureNoDuplicateDevices(devices []DeviceConfiguration) []DeviceConfiguration {
  699. count := len(devices)
  700. i := 0
  701. seenDevices := make(map[protocol.DeviceID]bool)
  702. loop:
  703. for i < count {
  704. id := devices[i].DeviceID
  705. if _, ok := seenDevices[id]; ok {
  706. devices[i] = devices[count-1]
  707. count--
  708. continue loop
  709. }
  710. seenDevices[id] = true
  711. i++
  712. }
  713. return devices[0:count]
  714. }
  715. func cleanSymlinks(filesystem fs.Filesystem, dir string) {
  716. if runtime.GOOS == "windows" {
  717. // We don't do symlinks on Windows. Additionally, there may
  718. // be things that look like symlinks that are not, which we
  719. // should leave alone. Deduplicated files, for example.
  720. return
  721. }
  722. filesystem.Walk(dir, func(path string, info fs.FileInfo, err error) error {
  723. if err != nil {
  724. return err
  725. }
  726. if info.IsSymlink() {
  727. l.Infoln("Removing incorrectly versioned symlink", path)
  728. filesystem.Remove(path)
  729. return fs.SkipDir
  730. }
  731. return nil
  732. })
  733. }
  734. // filterURLSchemePrefix returns the list of addresses after removing all
  735. // entries whose URL scheme matches the given prefix.
  736. func filterURLSchemePrefix(addrs []string, prefix string) []string {
  737. for i := 0; i < len(addrs); i++ {
  738. uri, err := url.Parse(addrs[i])
  739. if err != nil {
  740. continue
  741. }
  742. if strings.HasPrefix(uri.Scheme, prefix) {
  743. // Remove this entry
  744. copy(addrs[i:], addrs[i+1:])
  745. addrs = addrs[:len(addrs)-1]
  746. i--
  747. }
  748. }
  749. return addrs
  750. }
  751. // tried in succession and the first to succeed is returned. If none succeed,
  752. // a random high port is returned.
  753. func getFreePort(host string, ports ...int) (int, error) {
  754. for _, port := range ports {
  755. c, err := net.Listen("tcp", fmt.Sprintf("%s:%d", host, port))
  756. if err == nil {
  757. c.Close()
  758. return port, nil
  759. }
  760. }
  761. c, err := net.Listen("tcp", host+":0")
  762. if err != nil {
  763. return 0, err
  764. }
  765. addr := c.Addr().(*net.TCPAddr)
  766. c.Close()
  767. return addr.Port, nil
  768. }