config.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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.RawPath[len(folder.RawPath)-1] != filepath.Separator {
  313. folder.RawPath = folder.RawPath + string(filepath.Separator)
  314. }
  315. if folder.ID == "" {
  316. folder.ID = "default"
  317. }
  318. if folder.RescanIntervalS > MaxRescanIntervalS {
  319. folder.RescanIntervalS = MaxRescanIntervalS
  320. } else if folder.RescanIntervalS < 0 {
  321. folder.RescanIntervalS = 0
  322. }
  323. if seen, ok := seenFolders[folder.ID]; ok {
  324. l.Warnf("Multiple folders with ID %q; disabling", folder.ID)
  325. seen.Invalid = "duplicate folder ID"
  326. folder.Invalid = "duplicate folder ID"
  327. } else {
  328. seenFolders[folder.ID] = folder
  329. }
  330. }
  331. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  332. cfg.Options.GlobalAnnServers = uniqueStrings(cfg.Options.GlobalAnnServers)
  333. if cfg.Version < OldestHandledVersion {
  334. l.Warnf("Configuration version %d is deprecated. Attempting best effort conversion, but please verify manually.", cfg.Version)
  335. }
  336. // Upgrade configuration versions as appropriate
  337. if cfg.Version <= 5 {
  338. convertV5V6(cfg)
  339. }
  340. if cfg.Version == 6 {
  341. convertV6V7(cfg)
  342. }
  343. if cfg.Version == 7 {
  344. convertV7V8(cfg)
  345. }
  346. if cfg.Version == 8 {
  347. convertV8V9(cfg)
  348. }
  349. if cfg.Version == 9 {
  350. convertV9V10(cfg)
  351. }
  352. if cfg.Version == 10 {
  353. convertV10V11(cfg)
  354. }
  355. if cfg.Version == 11 {
  356. convertV11V12(cfg)
  357. }
  358. // Hash old cleartext passwords
  359. if len(cfg.GUI.Password) > 0 && cfg.GUI.Password[0] != '$' {
  360. hash, err := bcrypt.GenerateFromPassword([]byte(cfg.GUI.Password), 0)
  361. if err != nil {
  362. l.Warnln("bcrypting password:", err)
  363. } else {
  364. cfg.GUI.Password = string(hash)
  365. }
  366. }
  367. // Build a list of available devices
  368. existingDevices := make(map[protocol.DeviceID]bool)
  369. for _, device := range cfg.Devices {
  370. existingDevices[device.DeviceID] = true
  371. }
  372. // Ensure this device is present in the config
  373. if !existingDevices[myID] {
  374. myName, _ := os.Hostname()
  375. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  376. DeviceID: myID,
  377. Name: myName,
  378. })
  379. existingDevices[myID] = true
  380. }
  381. sort.Sort(DeviceConfigurationList(cfg.Devices))
  382. // Ensure that any loose devices are not present in the wrong places
  383. // Ensure that there are no duplicate devices
  384. // Ensure that puller settings are sane
  385. for i := range cfg.Folders {
  386. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  387. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  388. cfg.Folders[i].Devices = ensureNoDuplicates(cfg.Folders[i].Devices)
  389. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  390. }
  391. // An empty address list is equivalent to a single "dynamic" entry
  392. for i := range cfg.Devices {
  393. n := &cfg.Devices[i]
  394. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  395. n.Addresses = []string{"dynamic"}
  396. }
  397. }
  398. // Very short reconnection intervals are annoying
  399. if cfg.Options.ReconnectIntervalS < 5 {
  400. cfg.Options.ReconnectIntervalS = 5
  401. }
  402. if cfg.GUI.APIKey == "" {
  403. cfg.GUI.APIKey = randomString(32)
  404. }
  405. }
  406. // ChangeRequiresRestart returns true if updating the configuration requires a
  407. // complete restart.
  408. func ChangeRequiresRestart(from, to Configuration) bool {
  409. // Adding, removing or changing folders requires restart
  410. if !reflect.DeepEqual(from.Folders, to.Folders) {
  411. return true
  412. }
  413. // Removing a device requres restart
  414. toDevs := make(map[protocol.DeviceID]bool, len(from.Devices))
  415. for _, dev := range to.Devices {
  416. toDevs[dev.DeviceID] = true
  417. }
  418. for _, dev := range from.Devices {
  419. if _, ok := toDevs[dev.DeviceID]; !ok {
  420. return true
  421. }
  422. }
  423. // Changing usage reporting to on or off does not require a restart.
  424. to.Options.URAccepted = from.Options.URAccepted
  425. to.Options.URUniqueID = from.Options.URUniqueID
  426. // All of the generic options require restart
  427. if !reflect.DeepEqual(from.Options, to.Options) || !reflect.DeepEqual(from.GUI, to.GUI) {
  428. return true
  429. }
  430. return false
  431. }
  432. func convertV10V11(cfg *Configuration) {
  433. // Set minimum disk free of existing folders to 1%
  434. for i := range cfg.Folders {
  435. cfg.Folders[i].MinDiskFreePct = 1
  436. }
  437. cfg.Version = 11
  438. }
  439. func convertV11V12(cfg *Configuration) {
  440. // Change listen address schema
  441. for i, addr := range cfg.Options.ListenAddress {
  442. if len(addr) > 0 && !strings.HasPrefix(addr, "tcp://") {
  443. cfg.Options.ListenAddress[i] = fmt.Sprintf("tcp://%s", addr)
  444. }
  445. }
  446. for i, device := range cfg.Devices {
  447. for j, addr := range device.Addresses {
  448. if addr != "dynamic" && addr != "" {
  449. cfg.Devices[i].Addresses[j] = fmt.Sprintf("tcp://%s", addr)
  450. }
  451. }
  452. }
  453. // Use new discovery server
  454. var newDiscoServers []string
  455. var useDefault bool
  456. for _, addr := range cfg.Options.GlobalAnnServers {
  457. if addr == "udp4://announce.syncthing.net:22026" {
  458. useDefault = true
  459. } else if addr == "udp6://announce-v6.syncthing.net:22026" {
  460. useDefault = true
  461. } else {
  462. newDiscoServers = append(newDiscoServers, addr)
  463. }
  464. }
  465. if useDefault {
  466. newDiscoServers = append(newDiscoServers, "default")
  467. }
  468. cfg.Options.GlobalAnnServers = newDiscoServers
  469. // Use new multicast group
  470. if cfg.Options.LocalAnnMCAddr == "[ff32::5222]:21026" {
  471. cfg.Options.LocalAnnMCAddr = "[ff12::8384]:21027"
  472. }
  473. // Use new local discovery port
  474. if cfg.Options.LocalAnnPort == 21025 {
  475. cfg.Options.LocalAnnPort = 21027
  476. }
  477. cfg.Version = 12
  478. }
  479. func convertV9V10(cfg *Configuration) {
  480. // Enable auto normalization on existing folders.
  481. for i := range cfg.Folders {
  482. cfg.Folders[i].AutoNormalize = true
  483. }
  484. cfg.Version = 10
  485. }
  486. func convertV8V9(cfg *Configuration) {
  487. // Compression is interpreted and serialized differently, but no enforced
  488. // changes. Still need a new version number since the compression stuff
  489. // isn't understandable by earlier versions.
  490. cfg.Version = 9
  491. }
  492. func convertV7V8(cfg *Configuration) {
  493. // Add IPv6 announce server
  494. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "udp4://announce.syncthing.net:22026" {
  495. cfg.Options.GlobalAnnServers = append(cfg.Options.GlobalAnnServers, "udp6://announce-v6.syncthing.net:22026")
  496. }
  497. cfg.Version = 8
  498. }
  499. func convertV6V7(cfg *Configuration) {
  500. // Migrate announce server addresses to the new URL based format
  501. for i := range cfg.Options.GlobalAnnServers {
  502. cfg.Options.GlobalAnnServers[i] = "udp4://" + cfg.Options.GlobalAnnServers[i]
  503. }
  504. cfg.Version = 7
  505. }
  506. func convertV5V6(cfg *Configuration) {
  507. // Added ".stfolder" file at folder roots to identify mount issues
  508. // Doesn't affect the config itself, but uses config migrations to identify
  509. // the migration point.
  510. for _, folder := range Wrap("", *cfg).Folders() {
  511. // Best attempt, if it fails, it fails, the user will have to fix
  512. // it up manually, as the repo will not get started.
  513. folder.CreateMarker()
  514. }
  515. cfg.Version = 6
  516. }
  517. func setDefaults(data interface{}) error {
  518. s := reflect.ValueOf(data).Elem()
  519. t := s.Type()
  520. for i := 0; i < s.NumField(); i++ {
  521. f := s.Field(i)
  522. tag := t.Field(i).Tag
  523. v := tag.Get("default")
  524. if len(v) > 0 {
  525. switch f.Interface().(type) {
  526. case string:
  527. f.SetString(v)
  528. case int:
  529. i, err := strconv.ParseInt(v, 10, 64)
  530. if err != nil {
  531. return err
  532. }
  533. f.SetInt(i)
  534. case float64:
  535. i, err := strconv.ParseFloat(v, 64)
  536. if err != nil {
  537. return err
  538. }
  539. f.SetFloat(i)
  540. case bool:
  541. f.SetBool(v == "true")
  542. case []string:
  543. // We don't do anything with string slices here. Any default
  544. // we set will be appended to by the XML decoder, so we fill
  545. // those after decoding.
  546. default:
  547. panic(f.Type())
  548. }
  549. }
  550. }
  551. return nil
  552. }
  553. // fillNilSlices sets default value on slices that are still nil.
  554. func fillNilSlices(data interface{}) error {
  555. s := reflect.ValueOf(data).Elem()
  556. t := s.Type()
  557. for i := 0; i < s.NumField(); i++ {
  558. f := s.Field(i)
  559. tag := t.Field(i).Tag
  560. v := tag.Get("default")
  561. if len(v) > 0 {
  562. switch f.Interface().(type) {
  563. case []string:
  564. if f.IsNil() {
  565. // Treat the default as a comma separated slice
  566. vs := strings.Split(v, ",")
  567. for i := range vs {
  568. vs[i] = strings.TrimSpace(vs[i])
  569. }
  570. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), len(vs), len(vs))
  571. for i, v := range vs {
  572. rv.Index(i).SetString(v)
  573. }
  574. f.Set(rv)
  575. }
  576. }
  577. }
  578. }
  579. return nil
  580. }
  581. func uniqueStrings(ss []string) []string {
  582. var m = make(map[string]bool, len(ss))
  583. for _, s := range ss {
  584. m[strings.Trim(s, " ")] = true
  585. }
  586. var us = make([]string, 0, len(m))
  587. for k := range m {
  588. us = append(us, k)
  589. }
  590. sort.Strings(us)
  591. return us
  592. }
  593. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  594. for _, device := range devices {
  595. if device.DeviceID.Equals(myID) {
  596. return devices
  597. }
  598. }
  599. devices = append(devices, FolderDeviceConfiguration{
  600. DeviceID: myID,
  601. })
  602. return devices
  603. }
  604. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  605. count := len(devices)
  606. i := 0
  607. loop:
  608. for i < count {
  609. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  610. devices[i] = devices[count-1]
  611. count--
  612. continue loop
  613. }
  614. i++
  615. }
  616. return devices[0:count]
  617. }
  618. func ensureNoDuplicates(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  619. count := len(devices)
  620. i := 0
  621. seenDevices := make(map[protocol.DeviceID]bool)
  622. loop:
  623. for i < count {
  624. id := devices[i].DeviceID
  625. if _, ok := seenDevices[id]; ok {
  626. devices[i] = devices[count-1]
  627. count--
  628. continue loop
  629. }
  630. seenDevices[id] = true
  631. i++
  632. }
  633. return devices[0:count]
  634. }
  635. type DeviceConfigurationList []DeviceConfiguration
  636. func (l DeviceConfigurationList) Less(a, b int) bool {
  637. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  638. }
  639. func (l DeviceConfigurationList) Swap(a, b int) {
  640. l[a], l[b] = l[b], l[a]
  641. }
  642. func (l DeviceConfigurationList) Len() int {
  643. return len(l)
  644. }
  645. type FolderDeviceConfigurationList []FolderDeviceConfiguration
  646. func (l FolderDeviceConfigurationList) Less(a, b int) bool {
  647. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  648. }
  649. func (l FolderDeviceConfigurationList) Swap(a, b int) {
  650. l[a], l[b] = l[b], l[a]
  651. }
  652. func (l FolderDeviceConfigurationList) Len() int {
  653. return len(l)
  654. }
  655. // randomCharset contains the characters that can make up a randomString().
  656. const randomCharset = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
  657. // randomString returns a string of random characters (taken from
  658. // randomCharset) of the specified length.
  659. func randomString(l int) string {
  660. bs := make([]byte, l)
  661. for i := range bs {
  662. bs[i] = randomCharset[rand.Intn(len(randomCharset))]
  663. }
  664. return string(bs)
  665. }
  666. type PullOrder int
  667. const (
  668. OrderRandom PullOrder = iota // default is random
  669. OrderAlphabetic
  670. OrderSmallestFirst
  671. OrderLargestFirst
  672. OrderOldestFirst
  673. OrderNewestFirst
  674. )
  675. func (o PullOrder) String() string {
  676. switch o {
  677. case OrderRandom:
  678. return "random"
  679. case OrderAlphabetic:
  680. return "alphabetic"
  681. case OrderSmallestFirst:
  682. return "smallestFirst"
  683. case OrderLargestFirst:
  684. return "largestFirst"
  685. case OrderOldestFirst:
  686. return "oldestFirst"
  687. case OrderNewestFirst:
  688. return "newestFirst"
  689. default:
  690. return "unknown"
  691. }
  692. }
  693. func (o PullOrder) MarshalText() ([]byte, error) {
  694. return []byte(o.String()), nil
  695. }
  696. func (o *PullOrder) UnmarshalText(bs []byte) error {
  697. switch string(bs) {
  698. case "random":
  699. *o = OrderRandom
  700. case "alphabetic":
  701. *o = OrderAlphabetic
  702. case "smallestFirst":
  703. *o = OrderSmallestFirst
  704. case "largestFirst":
  705. *o = OrderLargestFirst
  706. case "oldestFirst":
  707. *o = OrderOldestFirst
  708. case "newestFirst":
  709. *o = OrderNewestFirst
  710. default:
  711. *o = OrderRandom
  712. }
  713. return nil
  714. }