config.go 24 KB

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