config.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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:"21025"`
  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. cfg.Version = 12
  437. }
  438. func convertV9V10(cfg *Configuration) {
  439. // Enable auto normalization on existing folders.
  440. for i := range cfg.Folders {
  441. cfg.Folders[i].AutoNormalize = true
  442. }
  443. cfg.Version = 10
  444. }
  445. func convertV8V9(cfg *Configuration) {
  446. // Compression is interpreted and serialized differently, but no enforced
  447. // changes. Still need a new version number since the compression stuff
  448. // isn't understandable by earlier versions.
  449. cfg.Version = 9
  450. }
  451. func convertV7V8(cfg *Configuration) {
  452. // Add IPv6 announce server
  453. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "udp4://announce.syncthing.net:22026" {
  454. cfg.Options.GlobalAnnServers = append(cfg.Options.GlobalAnnServers, "udp6://announce-v6.syncthing.net:22026")
  455. }
  456. cfg.Version = 8
  457. }
  458. func convertV6V7(cfg *Configuration) {
  459. // Migrate announce server addresses to the new URL based format
  460. for i := range cfg.Options.GlobalAnnServers {
  461. cfg.Options.GlobalAnnServers[i] = "udp4://" + cfg.Options.GlobalAnnServers[i]
  462. }
  463. cfg.Version = 7
  464. }
  465. func convertV5V6(cfg *Configuration) {
  466. // Added ".stfolder" file at folder roots to identify mount issues
  467. // Doesn't affect the config itself, but uses config migrations to identify
  468. // the migration point.
  469. for _, folder := range Wrap("", *cfg).Folders() {
  470. // Best attempt, if it fails, it fails, the user will have to fix
  471. // it up manually, as the repo will not get started.
  472. folder.CreateMarker()
  473. }
  474. cfg.Version = 6
  475. }
  476. func setDefaults(data interface{}) error {
  477. s := reflect.ValueOf(data).Elem()
  478. t := s.Type()
  479. for i := 0; i < s.NumField(); i++ {
  480. f := s.Field(i)
  481. tag := t.Field(i).Tag
  482. v := tag.Get("default")
  483. if len(v) > 0 {
  484. switch f.Interface().(type) {
  485. case string:
  486. f.SetString(v)
  487. case int:
  488. i, err := strconv.ParseInt(v, 10, 64)
  489. if err != nil {
  490. return err
  491. }
  492. f.SetInt(i)
  493. case bool:
  494. f.SetBool(v == "true")
  495. case []string:
  496. // We don't do anything with string slices here. Any default
  497. // we set will be appended to by the XML decoder, so we fill
  498. // those after decoding.
  499. default:
  500. panic(f.Type())
  501. }
  502. }
  503. }
  504. return nil
  505. }
  506. // fillNilSlices sets default value on slices that are still nil.
  507. func fillNilSlices(data interface{}) error {
  508. s := reflect.ValueOf(data).Elem()
  509. t := s.Type()
  510. for i := 0; i < s.NumField(); i++ {
  511. f := s.Field(i)
  512. tag := t.Field(i).Tag
  513. v := tag.Get("default")
  514. if len(v) > 0 {
  515. switch f.Interface().(type) {
  516. case []string:
  517. if f.IsNil() {
  518. // Treat the default as a comma separated slice
  519. vs := strings.Split(v, ",")
  520. for i := range vs {
  521. vs[i] = strings.TrimSpace(vs[i])
  522. }
  523. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), len(vs), len(vs))
  524. for i, v := range vs {
  525. rv.Index(i).SetString(v)
  526. }
  527. f.Set(rv)
  528. }
  529. }
  530. }
  531. }
  532. return nil
  533. }
  534. func uniqueStrings(ss []string) []string {
  535. var m = make(map[string]bool, len(ss))
  536. for _, s := range ss {
  537. m[strings.Trim(s, " ")] = true
  538. }
  539. var us = make([]string, 0, len(m))
  540. for k := range m {
  541. us = append(us, k)
  542. }
  543. sort.Strings(us)
  544. return us
  545. }
  546. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  547. for _, device := range devices {
  548. if device.DeviceID.Equals(myID) {
  549. return devices
  550. }
  551. }
  552. devices = append(devices, FolderDeviceConfiguration{
  553. DeviceID: myID,
  554. })
  555. return devices
  556. }
  557. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  558. count := len(devices)
  559. i := 0
  560. loop:
  561. for i < count {
  562. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  563. devices[i] = devices[count-1]
  564. count--
  565. continue loop
  566. }
  567. i++
  568. }
  569. return devices[0:count]
  570. }
  571. func ensureNoDuplicates(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  572. count := len(devices)
  573. i := 0
  574. seenDevices := make(map[protocol.DeviceID]bool)
  575. loop:
  576. for i < count {
  577. id := devices[i].DeviceID
  578. if _, ok := seenDevices[id]; ok {
  579. devices[i] = devices[count-1]
  580. count--
  581. continue loop
  582. }
  583. seenDevices[id] = true
  584. i++
  585. }
  586. return devices[0:count]
  587. }
  588. type DeviceConfigurationList []DeviceConfiguration
  589. func (l DeviceConfigurationList) Less(a, b int) bool {
  590. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  591. }
  592. func (l DeviceConfigurationList) Swap(a, b int) {
  593. l[a], l[b] = l[b], l[a]
  594. }
  595. func (l DeviceConfigurationList) Len() int {
  596. return len(l)
  597. }
  598. type FolderDeviceConfigurationList []FolderDeviceConfiguration
  599. func (l FolderDeviceConfigurationList) Less(a, b int) bool {
  600. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  601. }
  602. func (l FolderDeviceConfigurationList) Swap(a, b int) {
  603. l[a], l[b] = l[b], l[a]
  604. }
  605. func (l FolderDeviceConfigurationList) Len() int {
  606. return len(l)
  607. }
  608. // randomCharset contains the characters that can make up a randomString().
  609. const randomCharset = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
  610. // randomString returns a string of random characters (taken from
  611. // randomCharset) of the specified length.
  612. func randomString(l int) string {
  613. bs := make([]byte, l)
  614. for i := range bs {
  615. bs[i] = randomCharset[rand.Intn(len(randomCharset))]
  616. }
  617. return string(bs)
  618. }
  619. type PullOrder int
  620. const (
  621. OrderRandom PullOrder = iota // default is random
  622. OrderAlphabetic
  623. OrderSmallestFirst
  624. OrderLargestFirst
  625. OrderOldestFirst
  626. OrderNewestFirst
  627. )
  628. func (o PullOrder) String() string {
  629. switch o {
  630. case OrderRandom:
  631. return "random"
  632. case OrderAlphabetic:
  633. return "alphabetic"
  634. case OrderSmallestFirst:
  635. return "smallestFirst"
  636. case OrderLargestFirst:
  637. return "largestFirst"
  638. case OrderOldestFirst:
  639. return "oldestFirst"
  640. case OrderNewestFirst:
  641. return "newestFirst"
  642. default:
  643. return "unknown"
  644. }
  645. }
  646. func (o PullOrder) MarshalText() ([]byte, error) {
  647. return []byte(o.String()), nil
  648. }
  649. func (o *PullOrder) UnmarshalText(bs []byte) error {
  650. switch string(bs) {
  651. case "random":
  652. *o = OrderRandom
  653. case "alphabetic":
  654. *o = OrderAlphabetic
  655. case "smallestFirst":
  656. *o = OrderSmallestFirst
  657. case "largestFirst":
  658. *o = OrderLargestFirst
  659. case "oldestFirst":
  660. *o = OrderOldestFirst
  661. case "newestFirst":
  662. *o = OrderNewestFirst
  663. default:
  664. *o = OrderRandom
  665. }
  666. return nil
  667. }