config.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  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 http://mozilla.org/MPL/2.0/.
  6. // Package config implements reading and writing of the syncthing configuration file.
  7. package config
  8. import (
  9. "encoding/xml"
  10. "fmt"
  11. "io"
  12. "math/rand"
  13. "os"
  14. "path/filepath"
  15. "reflect"
  16. "runtime"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "github.com/syncthing/protocol"
  21. "github.com/syncthing/syncthing/lib/osutil"
  22. "golang.org/x/crypto/bcrypt"
  23. )
  24. const (
  25. OldestHandledVersion = 5
  26. CurrentVersion = 12
  27. MaxRescanIntervalS = 365 * 24 * 60 * 60
  28. )
  29. var (
  30. // DefaultDiscoveryServers should be substituted when the configuration
  31. // contains <globalAnnounceServer>default</globalAnnounceServer>. This is
  32. // done by the "consumer" of the configuration, as we don't want these
  33. // saved to the config.
  34. DefaultDiscoveryServers = []string{
  35. "https://discovery-v4-1.syncthing.net/?id=SR7AARM-TCBUZ5O-VFAXY4D-CECGSDE-3Q6IZ4G-XG7AH75-OBIXJQV-QJ6NLQA", // 194.126.249.5, Sweden
  36. "https://discovery-v4-2.syncthing.net/?id=AQEHEO2-XOS7QRA-X2COH5K-PO6OPVA-EWOSEGO-KZFMD32-XJ4ZV46-CUUVKAS", // 45.55.230.38, USA
  37. "https://discovery-v4-3.syncthing.net/?id=7WT2BVR-FX62ZOW-TNVVW25-6AHFJGD-XEXQSBW-VO3MPL2-JBTLL4T-P4572Q4", // 128.199.95.124, Singapore
  38. "https://discovery-v6-1.syncthing.net/?id=SR7AARM-TCBUZ5O-VFAXY4D-CECGSDE-3Q6IZ4G-XG7AH75-OBIXJQV-QJ6NLQA", // 2001:470:28:4d6::5, Sweden
  39. "https://discovery-v6-2.syncthing.net/?id=AQEHEO2-XOS7QRA-X2COH5K-PO6OPVA-EWOSEGO-KZFMD32-XJ4ZV46-CUUVKAS", // 2604:a880:800:10::182:a001, USA
  40. "https://discovery-v6-3.syncthing.net/?id=7WT2BVR-FX62ZOW-TNVVW25-6AHFJGD-XEXQSBW-VO3MPL2-JBTLL4T-P4572Q4", // 2400:6180:0:d0::d9:d001, Singapore
  41. }
  42. )
  43. type Configuration struct {
  44. Version int `xml:"version,attr" json:"version"`
  45. Folders []FolderConfiguration `xml:"folder" json:"folders"`
  46. Devices []DeviceConfiguration `xml:"device" json:"devices"`
  47. GUI GUIConfiguration `xml:"gui" json:"gui"`
  48. Options OptionsConfiguration `xml:"options" json:"options"`
  49. IgnoredDevices []protocol.DeviceID `xml:"ignoredDevice" json:"ignoredDevices"`
  50. XMLName xml.Name `xml:"configuration" json:"-"`
  51. OriginalVersion int `xml:"-" json:"-"` // The version we read from disk, before any conversion
  52. }
  53. func (cfg Configuration) Copy() Configuration {
  54. newCfg := cfg
  55. // Deep copy FolderConfigurations
  56. newCfg.Folders = make([]FolderConfiguration, len(cfg.Folders))
  57. for i := range newCfg.Folders {
  58. newCfg.Folders[i] = cfg.Folders[i].Copy()
  59. }
  60. // Deep copy DeviceConfigurations
  61. newCfg.Devices = make([]DeviceConfiguration, len(cfg.Devices))
  62. for i := range newCfg.Devices {
  63. newCfg.Devices[i] = cfg.Devices[i].Copy()
  64. }
  65. newCfg.Options = cfg.Options.Copy()
  66. // DeviceIDs are values
  67. newCfg.IgnoredDevices = make([]protocol.DeviceID, len(cfg.IgnoredDevices))
  68. copy(newCfg.IgnoredDevices, cfg.IgnoredDevices)
  69. return newCfg
  70. }
  71. type FolderConfiguration struct {
  72. ID string `xml:"id,attr" json:"id"`
  73. RawPath string `xml:"path,attr" json:"path"`
  74. Devices []FolderDeviceConfiguration `xml:"device" json:"devices"`
  75. ReadOnly bool `xml:"ro,attr" json:"readOnly"`
  76. RescanIntervalS int `xml:"rescanIntervalS,attr" json:"rescanIntervalS"`
  77. IgnorePerms bool `xml:"ignorePerms,attr" json:"ignorePerms"`
  78. AutoNormalize bool `xml:"autoNormalize,attr" json:"autoNormalize"`
  79. MinDiskFreePct float64 `xml:"minDiskFreePct" json:"minDiskFreePct"`
  80. Versioning VersioningConfiguration `xml:"versioning" json:"versioning"`
  81. Copiers int `xml:"copiers" json:"copiers"` // This defines how many files are handled concurrently.
  82. Pullers int `xml:"pullers" json:"pullers"` // Defines how many blocks are fetched at the same time, possibly between separate copier routines.
  83. Hashers int `xml:"hashers" json:"hashers"` // Less than one sets the value to the number of cores. These are CPU bound due to hashing.
  84. Order PullOrder `xml:"order" json:"order"`
  85. IgnoreDelete bool `xml:"ignoreDelete" json:"ignoreDelete"`
  86. ScanProgressIntervalS int `xml:"scanProgressInterval" json:"scanProgressInterval"` // Set to a negative value to disable. Value of 0 will get replaced with value of 2 (default value)
  87. Invalid string `xml:"-" json:"invalid"` // Set at runtime when there is an error, not saved
  88. }
  89. func (f FolderConfiguration) Copy() FolderConfiguration {
  90. c := f
  91. c.Devices = make([]FolderDeviceConfiguration, len(f.Devices))
  92. copy(c.Devices, f.Devices)
  93. return c
  94. }
  95. func (f FolderConfiguration) Path() string {
  96. // This is intentionally not a pointer method, because things like
  97. // cfg.Folders["default"].Path() should be valid.
  98. // Attempt tilde expansion; leave unchanged in case of error
  99. if path, err := osutil.ExpandTilde(f.RawPath); err == nil {
  100. f.RawPath = path
  101. }
  102. // Attempt absolutification; leave unchanged in case of error
  103. if !filepath.IsAbs(f.RawPath) {
  104. // Abs() looks like a fairly expensive syscall on Windows, while
  105. // IsAbs() is a whole bunch of string mangling. I think IsAbs() may be
  106. // somewhat faster in the general case, hence the outer if...
  107. if path, err := filepath.Abs(f.RawPath); err == nil {
  108. f.RawPath = path
  109. }
  110. }
  111. // Attempt to enable long filename support on Windows. We may still not
  112. // have an absolute path here if the previous steps failed.
  113. if runtime.GOOS == "windows" && filepath.IsAbs(f.RawPath) && !strings.HasPrefix(f.RawPath, `\\`) {
  114. return `\\?\` + f.RawPath
  115. }
  116. return f.RawPath
  117. }
  118. func (f *FolderConfiguration) CreateMarker() error {
  119. if !f.HasMarker() {
  120. marker := filepath.Join(f.Path(), ".stfolder")
  121. fd, err := os.Create(marker)
  122. if err != nil {
  123. return err
  124. }
  125. fd.Close()
  126. osutil.HideFile(marker)
  127. }
  128. return nil
  129. }
  130. func (f *FolderConfiguration) HasMarker() bool {
  131. _, err := os.Stat(filepath.Join(f.Path(), ".stfolder"))
  132. if err != nil {
  133. return false
  134. }
  135. return true
  136. }
  137. func (f *FolderConfiguration) DeviceIDs() []protocol.DeviceID {
  138. deviceIDs := make([]protocol.DeviceID, len(f.Devices))
  139. for i, n := range f.Devices {
  140. deviceIDs[i] = n.DeviceID
  141. }
  142. return deviceIDs
  143. }
  144. type VersioningConfiguration struct {
  145. Type string `xml:"type,attr" json:"type"`
  146. Params map[string]string `json:"params"`
  147. }
  148. type InternalVersioningConfiguration struct {
  149. Type string `xml:"type,attr,omitempty"`
  150. Params []InternalParam `xml:"param"`
  151. }
  152. type InternalParam struct {
  153. Key string `xml:"key,attr"`
  154. Val string `xml:"val,attr"`
  155. }
  156. func (c *VersioningConfiguration) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
  157. var tmp InternalVersioningConfiguration
  158. tmp.Type = c.Type
  159. for k, v := range c.Params {
  160. tmp.Params = append(tmp.Params, InternalParam{k, v})
  161. }
  162. return e.EncodeElement(tmp, start)
  163. }
  164. func (c *VersioningConfiguration) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
  165. var tmp InternalVersioningConfiguration
  166. err := d.DecodeElement(&tmp, &start)
  167. if err != nil {
  168. return err
  169. }
  170. c.Type = tmp.Type
  171. c.Params = make(map[string]string, len(tmp.Params))
  172. for _, p := range tmp.Params {
  173. c.Params[p.Key] = p.Val
  174. }
  175. return nil
  176. }
  177. type DeviceConfiguration struct {
  178. DeviceID protocol.DeviceID `xml:"id,attr" json:"deviceID"`
  179. Name string `xml:"name,attr,omitempty" json:"name"`
  180. Addresses []string `xml:"address,omitempty" json:"addresses"`
  181. Compression protocol.Compression `xml:"compression,attr" json:"compression"`
  182. CertName string `xml:"certName,attr,omitempty" json:"certName"`
  183. Introducer bool `xml:"introducer,attr" json:"introducer"`
  184. }
  185. func (orig DeviceConfiguration) Copy() DeviceConfiguration {
  186. c := orig
  187. c.Addresses = make([]string, len(orig.Addresses))
  188. copy(c.Addresses, orig.Addresses)
  189. return c
  190. }
  191. type FolderDeviceConfiguration struct {
  192. DeviceID protocol.DeviceID `xml:"id,attr" json:"deviceID"`
  193. }
  194. type OptionsConfiguration struct {
  195. ListenAddress []string `xml:"listenAddress" json:"listenAddress" default:"tcp://0.0.0.0:22000"`
  196. GlobalAnnServers []string `xml:"globalAnnounceServer" json:"globalAnnounceServers" json:"globalAnnounceServer" default:"default"`
  197. GlobalAnnEnabled bool `xml:"globalAnnounceEnabled" json:"globalAnnounceEnabled" default:"true"`
  198. LocalAnnEnabled bool `xml:"localAnnounceEnabled" json:"localAnnounceEnabled" default:"true"`
  199. LocalAnnPort int `xml:"localAnnouncePort" json:"localAnnouncePort" default:"21027"`
  200. LocalAnnMCAddr string `xml:"localAnnounceMCAddr" json:"localAnnounceMCAddr" default:"[ff12::8384]:21027"`
  201. RelayServers []string `xml:"relayServer" json:"relayServers" default:"dynamic+https://relays.syncthing.net"`
  202. MaxSendKbps int `xml:"maxSendKbps" json:"maxSendKbps"`
  203. MaxRecvKbps int `xml:"maxRecvKbps" json:"maxRecvKbps"`
  204. ReconnectIntervalS int `xml:"reconnectionIntervalS" json:"reconnectionIntervalS" default:"60"`
  205. RelaysEnabled bool `xml:"relaysEnabled" json:"relaysEnabled" default:"true"`
  206. RelayReconnectIntervalM int `xml:"relayReconnectIntervalM" json:"relayReconnectIntervalM" default:"10"`
  207. RelayWithoutGlobalAnn bool `xml:"relayWithoutGlobalAnn" json:"relayWithoutGlobalAnn" default:"false"`
  208. StartBrowser bool `xml:"startBrowser" json:"startBrowser" default:"true"`
  209. UPnPEnabled bool `xml:"upnpEnabled" json:"upnpEnabled" default:"true"`
  210. UPnPLeaseM int `xml:"upnpLeaseMinutes" json:"upnpLeaseMinutes" default:"60"`
  211. UPnPRenewalM int `xml:"upnpRenewalMinutes" json:"upnpRenewalMinutes" default:"30"`
  212. UPnPTimeoutS int `xml:"upnpTimeoutSeconds" json:"upnpTimeoutSeconds" default:"10"`
  213. URAccepted int `xml:"urAccepted" json:"urAccepted"` // Accepted usage reporting version; 0 for off (undecided), -1 for off (permanently)
  214. URUniqueID string `xml:"urUniqueID" json:"urUniqueId"` // Unique ID for reporting purposes, regenerated when UR is turned on.
  215. URURL string `xml:"urURL" json:"urURL" default:"https://data.syncthing.net/newdata"`
  216. URPostInsecurely bool `xml:"urPostInsecurely" json:"urPostInsecurely" default:"false"` // For testing
  217. URInitialDelayS int `xml:"urInitialDelayS" json:"urInitialDelayS" default:"1800"`
  218. RestartOnWakeup bool `xml:"restartOnWakeup" json:"restartOnWakeup" default:"true"`
  219. AutoUpgradeIntervalH int `xml:"autoUpgradeIntervalH" json:"autoUpgradeIntervalH" default:"12"` // 0 for off
  220. KeepTemporariesH int `xml:"keepTemporariesH" json:"keepTemporariesH" default:"24"` // 0 for off
  221. CacheIgnoredFiles bool `xml:"cacheIgnoredFiles" json:"cacheIgnoredFiles" default:"true"`
  222. ProgressUpdateIntervalS int `xml:"progressUpdateIntervalS" json:"progressUpdateIntervalS" default:"5"`
  223. SymlinksEnabled bool `xml:"symlinksEnabled" json:"symlinksEnabled" default:"true"`
  224. LimitBandwidthInLan bool `xml:"limitBandwidthInLan" json:"limitBandwidthInLan" default:"false"`
  225. DatabaseBlockCacheMiB int `xml:"databaseBlockCacheMiB" json:"databaseBlockCacheMiB" default:"0"`
  226. PingTimeoutS int `xml:"pingTimeoutS" json:"pingTimeoutS" default:"30"`
  227. PingIdleTimeS int `xml:"pingIdleTimeS" json:"pingIdleTimeS" default:"60"`
  228. MinHomeDiskFreePct float64 `xml:"minHomeDiskFreePct" json:"minHomeDiskFreePct" default:"1"`
  229. ReleasesURL string `xml:"releasesURL" json:"releasesURL" default:"https://api.github.com/repos/syncthing/syncthing/releases?per_page=30"`
  230. AlwaysLocalNets []string `xml:"alwaysLocalNet" json:"alwaysLocalNets"`
  231. }
  232. func (orig OptionsConfiguration) Copy() OptionsConfiguration {
  233. c := orig
  234. c.ListenAddress = make([]string, len(orig.ListenAddress))
  235. copy(c.ListenAddress, orig.ListenAddress)
  236. c.GlobalAnnServers = make([]string, len(orig.GlobalAnnServers))
  237. copy(c.GlobalAnnServers, orig.GlobalAnnServers)
  238. return c
  239. }
  240. type GUIConfiguration struct {
  241. Enabled bool `xml:"enabled,attr" json:"enabled" default:"true"`
  242. Address string `xml:"address" json:"address" default:"127.0.0.1:8384"`
  243. User string `xml:"user,omitempty" json:"user"`
  244. Password string `xml:"password,omitempty" json:"password"`
  245. UseTLS bool `xml:"tls,attr" json:"useTLS"`
  246. APIKey string `xml:"apikey,omitempty" json:"apiKey"`
  247. }
  248. func New(myID protocol.DeviceID) Configuration {
  249. var cfg Configuration
  250. cfg.Version = CurrentVersion
  251. cfg.OriginalVersion = CurrentVersion
  252. setDefaults(&cfg)
  253. setDefaults(&cfg.Options)
  254. setDefaults(&cfg.GUI)
  255. cfg.prepare(myID)
  256. return cfg
  257. }
  258. func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  259. var cfg Configuration
  260. setDefaults(&cfg)
  261. setDefaults(&cfg.Options)
  262. setDefaults(&cfg.GUI)
  263. err := xml.NewDecoder(r).Decode(&cfg)
  264. cfg.OriginalVersion = cfg.Version
  265. cfg.prepare(myID)
  266. return cfg, err
  267. }
  268. func (cfg *Configuration) WriteXML(w io.Writer) error {
  269. e := xml.NewEncoder(w)
  270. e.Indent("", " ")
  271. err := e.Encode(cfg)
  272. if err != nil {
  273. return err
  274. }
  275. _, err = w.Write([]byte("\n"))
  276. return err
  277. }
  278. func (cfg *Configuration) prepare(myID protocol.DeviceID) {
  279. fillNilSlices(&cfg.Options)
  280. // Initialize an empty slices
  281. if cfg.Folders == nil {
  282. cfg.Folders = []FolderConfiguration{}
  283. }
  284. if cfg.IgnoredDevices == nil {
  285. cfg.IgnoredDevices = []protocol.DeviceID{}
  286. }
  287. // Check for missing, bad or duplicate folder ID:s
  288. var seenFolders = map[string]*FolderConfiguration{}
  289. for i := range cfg.Folders {
  290. folder := &cfg.Folders[i]
  291. if len(folder.RawPath) == 0 {
  292. folder.Invalid = "no directory configured"
  293. continue
  294. }
  295. // The reason it's done like this:
  296. // C: -> C:\ -> C:\ (issue that this is trying to fix)
  297. // C:\somedir -> C:\somedir\ -> C:\somedir
  298. // C:\somedir\ -> C:\somedir\\ -> C:\somedir
  299. // This way in the tests, we get away without OS specific separators
  300. // in the test configs.
  301. folder.RawPath = filepath.Dir(folder.RawPath + string(filepath.Separator))
  302. if folder.ID == "" {
  303. folder.ID = "default"
  304. }
  305. if folder.RescanIntervalS > MaxRescanIntervalS {
  306. folder.RescanIntervalS = MaxRescanIntervalS
  307. } else if folder.RescanIntervalS < 0 {
  308. folder.RescanIntervalS = 0
  309. }
  310. if seen, ok := seenFolders[folder.ID]; ok {
  311. l.Warnf("Multiple folders with ID %q; disabling", folder.ID)
  312. seen.Invalid = "duplicate folder ID"
  313. folder.Invalid = "duplicate folder ID"
  314. } else {
  315. seenFolders[folder.ID] = folder
  316. }
  317. }
  318. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  319. cfg.Options.GlobalAnnServers = uniqueStrings(cfg.Options.GlobalAnnServers)
  320. if cfg.Version < OldestHandledVersion {
  321. l.Warnf("Configuration version %d is deprecated. Attempting best effort conversion, but please verify manually.", cfg.Version)
  322. }
  323. // Upgrade configuration versions as appropriate
  324. if cfg.Version <= 5 {
  325. convertV5V6(cfg)
  326. }
  327. if cfg.Version == 6 {
  328. convertV6V7(cfg)
  329. }
  330. if cfg.Version == 7 {
  331. convertV7V8(cfg)
  332. }
  333. if cfg.Version == 8 {
  334. convertV8V9(cfg)
  335. }
  336. if cfg.Version == 9 {
  337. convertV9V10(cfg)
  338. }
  339. if cfg.Version == 10 {
  340. convertV10V11(cfg)
  341. }
  342. if cfg.Version == 11 {
  343. convertV11V12(cfg)
  344. }
  345. // Hash old cleartext passwords
  346. if len(cfg.GUI.Password) > 0 && cfg.GUI.Password[0] != '$' {
  347. hash, err := bcrypt.GenerateFromPassword([]byte(cfg.GUI.Password), 0)
  348. if err != nil {
  349. l.Warnln("bcrypting password:", err)
  350. } else {
  351. cfg.GUI.Password = string(hash)
  352. }
  353. }
  354. // Build a list of available devices
  355. existingDevices := make(map[protocol.DeviceID]bool)
  356. for _, device := range cfg.Devices {
  357. existingDevices[device.DeviceID] = true
  358. }
  359. // Ensure this device is present in the config
  360. if !existingDevices[myID] {
  361. myName, _ := os.Hostname()
  362. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  363. DeviceID: myID,
  364. Name: myName,
  365. })
  366. existingDevices[myID] = true
  367. }
  368. sort.Sort(DeviceConfigurationList(cfg.Devices))
  369. // Ensure that any loose devices are not present in the wrong places
  370. // Ensure that there are no duplicate devices
  371. // Ensure that puller settings are sane
  372. for i := range cfg.Folders {
  373. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  374. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  375. cfg.Folders[i].Devices = ensureNoDuplicates(cfg.Folders[i].Devices)
  376. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  377. }
  378. // An empty address list is equivalent to a single "dynamic" entry
  379. for i := range cfg.Devices {
  380. n := &cfg.Devices[i]
  381. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  382. n.Addresses = []string{"dynamic"}
  383. }
  384. }
  385. // Very short reconnection intervals are annoying
  386. if cfg.Options.ReconnectIntervalS < 5 {
  387. cfg.Options.ReconnectIntervalS = 5
  388. }
  389. if cfg.GUI.APIKey == "" {
  390. cfg.GUI.APIKey = randomString(32)
  391. }
  392. }
  393. // ChangeRequiresRestart returns true if updating the configuration requires a
  394. // complete restart.
  395. func ChangeRequiresRestart(from, to Configuration) bool {
  396. // Adding, removing or changing folders requires restart
  397. if !reflect.DeepEqual(from.Folders, to.Folders) {
  398. return true
  399. }
  400. // Removing a device requres restart
  401. toDevs := make(map[protocol.DeviceID]bool, len(from.Devices))
  402. for _, dev := range to.Devices {
  403. toDevs[dev.DeviceID] = true
  404. }
  405. for _, dev := range from.Devices {
  406. if _, ok := toDevs[dev.DeviceID]; !ok {
  407. return true
  408. }
  409. }
  410. // Changing usage reporting to on or off does not require a restart.
  411. to.Options.URAccepted = from.Options.URAccepted
  412. to.Options.URUniqueID = from.Options.URUniqueID
  413. // All of the generic options require restart
  414. if !reflect.DeepEqual(from.Options, to.Options) || !reflect.DeepEqual(from.GUI, to.GUI) {
  415. return true
  416. }
  417. return false
  418. }
  419. func convertV10V11(cfg *Configuration) {
  420. // Set minimum disk free of existing folders to 1%
  421. for i := range cfg.Folders {
  422. cfg.Folders[i].MinDiskFreePct = 1
  423. }
  424. cfg.Version = 11
  425. }
  426. func convertV11V12(cfg *Configuration) {
  427. // Change listen address schema
  428. for i, addr := range cfg.Options.ListenAddress {
  429. if len(addr) > 0 && !strings.HasPrefix(addr, "tcp://") {
  430. cfg.Options.ListenAddress[i] = fmt.Sprintf("tcp://%s", addr)
  431. }
  432. }
  433. for i, device := range cfg.Devices {
  434. for j, addr := range device.Addresses {
  435. if addr != "dynamic" && addr != "" {
  436. cfg.Devices[i].Addresses[j] = fmt.Sprintf("tcp://%s", addr)
  437. }
  438. }
  439. }
  440. // Use new discovery server
  441. var newDiscoServers []string
  442. var useDefault bool
  443. for _, addr := range cfg.Options.GlobalAnnServers {
  444. if addr == "udp4://announce.syncthing.net:22026" {
  445. useDefault = true
  446. } else if addr == "udp6://announce-v6.syncthing.net:22026" {
  447. useDefault = true
  448. } else {
  449. newDiscoServers = append(newDiscoServers, addr)
  450. }
  451. }
  452. if useDefault {
  453. newDiscoServers = append(newDiscoServers, "default")
  454. }
  455. cfg.Options.GlobalAnnServers = newDiscoServers
  456. // Use new multicast group
  457. if cfg.Options.LocalAnnMCAddr == "[ff32::5222]:21026" {
  458. cfg.Options.LocalAnnMCAddr = "[ff12::8384]:21027"
  459. }
  460. // Use new local discovery port
  461. if cfg.Options.LocalAnnPort == 21025 {
  462. cfg.Options.LocalAnnPort = 21027
  463. }
  464. cfg.Version = 12
  465. }
  466. func convertV9V10(cfg *Configuration) {
  467. // Enable auto normalization on existing folders.
  468. for i := range cfg.Folders {
  469. cfg.Folders[i].AutoNormalize = true
  470. }
  471. cfg.Version = 10
  472. }
  473. func convertV8V9(cfg *Configuration) {
  474. // Compression is interpreted and serialized differently, but no enforced
  475. // changes. Still need a new version number since the compression stuff
  476. // isn't understandable by earlier versions.
  477. cfg.Version = 9
  478. }
  479. func convertV7V8(cfg *Configuration) {
  480. // Add IPv6 announce server
  481. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "udp4://announce.syncthing.net:22026" {
  482. cfg.Options.GlobalAnnServers = append(cfg.Options.GlobalAnnServers, "udp6://announce-v6.syncthing.net:22026")
  483. }
  484. cfg.Version = 8
  485. }
  486. func convertV6V7(cfg *Configuration) {
  487. // Migrate announce server addresses to the new URL based format
  488. for i := range cfg.Options.GlobalAnnServers {
  489. cfg.Options.GlobalAnnServers[i] = "udp4://" + cfg.Options.GlobalAnnServers[i]
  490. }
  491. cfg.Version = 7
  492. }
  493. func convertV5V6(cfg *Configuration) {
  494. // Added ".stfolder" file at folder roots to identify mount issues
  495. // Doesn't affect the config itself, but uses config migrations to identify
  496. // the migration point.
  497. for _, folder := range Wrap("", *cfg).Folders() {
  498. // Best attempt, if it fails, it fails, the user will have to fix
  499. // it up manually, as the repo will not get started.
  500. folder.CreateMarker()
  501. }
  502. cfg.Version = 6
  503. }
  504. func setDefaults(data interface{}) error {
  505. s := reflect.ValueOf(data).Elem()
  506. t := s.Type()
  507. for i := 0; i < s.NumField(); i++ {
  508. f := s.Field(i)
  509. tag := t.Field(i).Tag
  510. v := tag.Get("default")
  511. if len(v) > 0 {
  512. switch f.Interface().(type) {
  513. case string:
  514. f.SetString(v)
  515. case int:
  516. i, err := strconv.ParseInt(v, 10, 64)
  517. if err != nil {
  518. return err
  519. }
  520. f.SetInt(i)
  521. case float64:
  522. i, err := strconv.ParseFloat(v, 64)
  523. if err != nil {
  524. return err
  525. }
  526. f.SetFloat(i)
  527. case bool:
  528. f.SetBool(v == "true")
  529. case []string:
  530. // We don't do anything with string slices here. Any default
  531. // we set will be appended to by the XML decoder, so we fill
  532. // those after decoding.
  533. default:
  534. panic(f.Type())
  535. }
  536. }
  537. }
  538. return nil
  539. }
  540. // fillNilSlices sets default value on slices that are still nil.
  541. func fillNilSlices(data interface{}) error {
  542. s := reflect.ValueOf(data).Elem()
  543. t := s.Type()
  544. for i := 0; i < s.NumField(); i++ {
  545. f := s.Field(i)
  546. tag := t.Field(i).Tag
  547. v := tag.Get("default")
  548. if len(v) > 0 {
  549. switch f.Interface().(type) {
  550. case []string:
  551. if f.IsNil() {
  552. // Treat the default as a comma separated slice
  553. vs := strings.Split(v, ",")
  554. for i := range vs {
  555. vs[i] = strings.TrimSpace(vs[i])
  556. }
  557. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), len(vs), len(vs))
  558. for i, v := range vs {
  559. rv.Index(i).SetString(v)
  560. }
  561. f.Set(rv)
  562. }
  563. }
  564. }
  565. }
  566. return nil
  567. }
  568. func uniqueStrings(ss []string) []string {
  569. var m = make(map[string]bool, len(ss))
  570. for _, s := range ss {
  571. m[strings.Trim(s, " ")] = true
  572. }
  573. var us = make([]string, 0, len(m))
  574. for k := range m {
  575. us = append(us, k)
  576. }
  577. sort.Strings(us)
  578. return us
  579. }
  580. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  581. for _, device := range devices {
  582. if device.DeviceID.Equals(myID) {
  583. return devices
  584. }
  585. }
  586. devices = append(devices, FolderDeviceConfiguration{
  587. DeviceID: myID,
  588. })
  589. return devices
  590. }
  591. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  592. count := len(devices)
  593. i := 0
  594. loop:
  595. for i < count {
  596. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  597. devices[i] = devices[count-1]
  598. count--
  599. continue loop
  600. }
  601. i++
  602. }
  603. return devices[0:count]
  604. }
  605. func ensureNoDuplicates(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  606. count := len(devices)
  607. i := 0
  608. seenDevices := make(map[protocol.DeviceID]bool)
  609. loop:
  610. for i < count {
  611. id := devices[i].DeviceID
  612. if _, ok := seenDevices[id]; ok {
  613. devices[i] = devices[count-1]
  614. count--
  615. continue loop
  616. }
  617. seenDevices[id] = true
  618. i++
  619. }
  620. return devices[0:count]
  621. }
  622. type DeviceConfigurationList []DeviceConfiguration
  623. func (l DeviceConfigurationList) Less(a, b int) bool {
  624. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  625. }
  626. func (l DeviceConfigurationList) Swap(a, b int) {
  627. l[a], l[b] = l[b], l[a]
  628. }
  629. func (l DeviceConfigurationList) Len() int {
  630. return len(l)
  631. }
  632. type FolderDeviceConfigurationList []FolderDeviceConfiguration
  633. func (l FolderDeviceConfigurationList) Less(a, b int) bool {
  634. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  635. }
  636. func (l FolderDeviceConfigurationList) Swap(a, b int) {
  637. l[a], l[b] = l[b], l[a]
  638. }
  639. func (l FolderDeviceConfigurationList) Len() int {
  640. return len(l)
  641. }
  642. // randomCharset contains the characters that can make up a randomString().
  643. const randomCharset = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
  644. // randomString returns a string of random characters (taken from
  645. // randomCharset) of the specified length.
  646. func randomString(l int) string {
  647. bs := make([]byte, l)
  648. for i := range bs {
  649. bs[i] = randomCharset[rand.Intn(len(randomCharset))]
  650. }
  651. return string(bs)
  652. }
  653. type PullOrder int
  654. const (
  655. OrderRandom PullOrder = iota // default is random
  656. OrderAlphabetic
  657. OrderSmallestFirst
  658. OrderLargestFirst
  659. OrderOldestFirst
  660. OrderNewestFirst
  661. )
  662. func (o PullOrder) String() string {
  663. switch o {
  664. case OrderRandom:
  665. return "random"
  666. case OrderAlphabetic:
  667. return "alphabetic"
  668. case OrderSmallestFirst:
  669. return "smallestFirst"
  670. case OrderLargestFirst:
  671. return "largestFirst"
  672. case OrderOldestFirst:
  673. return "oldestFirst"
  674. case OrderNewestFirst:
  675. return "newestFirst"
  676. default:
  677. return "unknown"
  678. }
  679. }
  680. func (o PullOrder) MarshalText() ([]byte, error) {
  681. return []byte(o.String()), nil
  682. }
  683. func (o *PullOrder) UnmarshalText(bs []byte) error {
  684. switch string(bs) {
  685. case "random":
  686. *o = OrderRandom
  687. case "alphabetic":
  688. *o = OrderAlphabetic
  689. case "smallestFirst":
  690. *o = OrderSmallestFirst
  691. case "largestFirst":
  692. *o = OrderLargestFirst
  693. case "oldestFirst":
  694. *o = OrderOldestFirst
  695. case "newestFirst":
  696. *o = OrderNewestFirst
  697. default:
  698. *o = OrderRandom
  699. }
  700. return nil
  701. }