config.go 26 KB

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