config.go 26 KB

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