config.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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. "sort"
  17. "strconv"
  18. "strings"
  19. "github.com/calmh/logger"
  20. "github.com/syncthing/protocol"
  21. "github.com/syncthing/syncthing/internal/osutil"
  22. "golang.org/x/crypto/bcrypt"
  23. )
  24. var l = logger.DefaultLogger
  25. const CurrentVersion = 10
  26. type Configuration struct {
  27. Version int `xml:"version,attr" json:"version"`
  28. Folders []FolderConfiguration `xml:"folder" json:"folders"`
  29. Devices []DeviceConfiguration `xml:"device" json:"devices"`
  30. GUI GUIConfiguration `xml:"gui" json:"gui"`
  31. Options OptionsConfiguration `xml:"options" json:"options"`
  32. IgnoredDevices []protocol.DeviceID `xml:"ignoredDevice" json:"ignoredDevices"`
  33. XMLName xml.Name `xml:"configuration" json:"-"`
  34. OriginalVersion int `xml:"-" json:"-"` // The version we read from disk, before any conversion
  35. Deprecated_Repositories []FolderConfiguration `xml:"repository" json:"-"`
  36. Deprecated_Nodes []DeviceConfiguration `xml:"node" json:"-"`
  37. }
  38. type FolderConfiguration struct {
  39. ID string `xml:"id,attr" json:"id"`
  40. Path string `xml:"path,attr" json:"path"`
  41. Devices []FolderDeviceConfiguration `xml:"device" json:"devices"`
  42. ReadOnly bool `xml:"ro,attr" json:"readOnly"`
  43. RescanIntervalS int `xml:"rescanIntervalS,attr" json:"rescanIntervalS"`
  44. IgnorePerms bool `xml:"ignorePerms,attr" json:"ignorePerms"`
  45. AutoNormalize bool `xml:"autoNormalize,attr" json:"autoNormalize"`
  46. Versioning VersioningConfiguration `xml:"versioning" json:"versioning"`
  47. LenientMtimes bool `xml:"lenientMtimes" json:"lenientMTimes"`
  48. Copiers int `xml:"copiers" json:"copiers"` // This defines how many files are handled concurrently.
  49. Pullers int `xml:"pullers" json:"pullers"` // Defines how many blocks are fetched at the same time, possibly between separate copier routines.
  50. Hashers int `xml:"hashers" json:"hashers"` // Less than one sets the value to the number of cores. These are CPU bound due to hashing.
  51. Invalid string `xml:"-" json:"invalid"` // Set at runtime when there is an error, not saved
  52. deviceIDs []protocol.DeviceID
  53. Deprecated_Directory string `xml:"directory,omitempty,attr" json:"-"`
  54. Deprecated_Nodes []FolderDeviceConfiguration `xml:"node" json:"-"`
  55. }
  56. func (f *FolderConfiguration) CreateMarker() error {
  57. if !f.HasMarker() {
  58. marker := filepath.Join(f.Path, ".stfolder")
  59. fd, err := os.Create(marker)
  60. if err != nil {
  61. return err
  62. }
  63. fd.Close()
  64. osutil.HideFile(marker)
  65. }
  66. return nil
  67. }
  68. func (f *FolderConfiguration) HasMarker() bool {
  69. _, err := os.Stat(filepath.Join(f.Path, ".stfolder"))
  70. if err != nil {
  71. return false
  72. }
  73. return true
  74. }
  75. func (f *FolderConfiguration) DeviceIDs() []protocol.DeviceID {
  76. if f.deviceIDs == nil {
  77. for _, n := range f.Devices {
  78. f.deviceIDs = append(f.deviceIDs, n.DeviceID)
  79. }
  80. }
  81. return f.deviceIDs
  82. }
  83. type VersioningConfiguration struct {
  84. Type string `xml:"type,attr" json:"type"`
  85. Params map[string]string `json:"params"`
  86. }
  87. type InternalVersioningConfiguration struct {
  88. Type string `xml:"type,attr,omitempty"`
  89. Params []InternalParam `xml:"param"`
  90. }
  91. type InternalParam struct {
  92. Key string `xml:"key,attr"`
  93. Val string `xml:"val,attr"`
  94. }
  95. func (c *VersioningConfiguration) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
  96. var tmp InternalVersioningConfiguration
  97. tmp.Type = c.Type
  98. for k, v := range c.Params {
  99. tmp.Params = append(tmp.Params, InternalParam{k, v})
  100. }
  101. return e.EncodeElement(tmp, start)
  102. }
  103. func (c *VersioningConfiguration) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
  104. var tmp InternalVersioningConfiguration
  105. err := d.DecodeElement(&tmp, &start)
  106. if err != nil {
  107. return err
  108. }
  109. c.Type = tmp.Type
  110. c.Params = make(map[string]string, len(tmp.Params))
  111. for _, p := range tmp.Params {
  112. c.Params[p.Key] = p.Val
  113. }
  114. return nil
  115. }
  116. type DeviceConfiguration struct {
  117. DeviceID protocol.DeviceID `xml:"id,attr" json:"deviceID"`
  118. Name string `xml:"name,attr,omitempty" json:"name"`
  119. Addresses []string `xml:"address,omitempty" json:"addresses"`
  120. Compression protocol.Compression `xml:"compression,attr" json:"compression"`
  121. CertName string `xml:"certName,attr,omitempty" json:"certName"`
  122. Introducer bool `xml:"introducer,attr" json:"introducer"`
  123. }
  124. type FolderDeviceConfiguration struct {
  125. DeviceID protocol.DeviceID `xml:"id,attr" json:"deviceID"`
  126. Deprecated_Name string `xml:"name,attr,omitempty" json:"-"`
  127. Deprecated_Addresses []string `xml:"address,omitempty" json:"-"`
  128. }
  129. type OptionsConfiguration struct {
  130. ListenAddress []string `xml:"listenAddress" json:"listenAddress" default:"0.0.0.0:22000"`
  131. GlobalAnnServers []string `xml:"globalAnnounceServer" json:"globalAnnounceServers" json:"globalAnnounceServer" default:"udp4://announce.syncthing.net:22026, udp6://announce-v6.syncthing.net:22026"`
  132. GlobalAnnEnabled bool `xml:"globalAnnounceEnabled" json:"globalAnnounceEnabled" default:"true"`
  133. LocalAnnEnabled bool `xml:"localAnnounceEnabled" json:"localAnnounceEnabled" default:"true"`
  134. LocalAnnPort int `xml:"localAnnouncePort" json:"localAnnouncePort" default:"21025"`
  135. LocalAnnMCAddr string `xml:"localAnnounceMCAddr" json:"localAnnounceMCAddr" default:"[ff32::5222]:21026"`
  136. MaxSendKbps int `xml:"maxSendKbps" json:"maxSendKbps"`
  137. MaxRecvKbps int `xml:"maxRecvKbps" json:"maxRecvKbps"`
  138. ReconnectIntervalS int `xml:"reconnectionIntervalS" json:"reconnectionIntervalS" default:"60"`
  139. StartBrowser bool `xml:"startBrowser" json:"startBrowser" default:"true"`
  140. UPnPEnabled bool `xml:"upnpEnabled" json:"upnpEnabled" default:"true"`
  141. UPnPLease int `xml:"upnpLeaseMinutes" json:"upnpLeaseMinutes" default:"0"`
  142. UPnPRenewal int `xml:"upnpRenewalMinutes" json:"upnpRenewalMinutes" default:"30"`
  143. URAccepted int `xml:"urAccepted" json:"urAccepted"` // Accepted usage reporting version; 0 for off (undecided), -1 for off (permanently)
  144. URUniqueID string `xml:"urUniqueID" json:"urUniqueId"` // Unique ID for reporting purposes, regenerated when UR is turned on.
  145. RestartOnWakeup bool `xml:"restartOnWakeup" json:"restartOnWakeup" default:"true"`
  146. AutoUpgradeIntervalH int `xml:"autoUpgradeIntervalH" json:"autoUpgradeIntervalH" default:"12"` // 0 for off
  147. KeepTemporariesH int `xml:"keepTemporariesH" json:"keepTemporariesH" default:"24"` // 0 for off
  148. CacheIgnoredFiles bool `xml:"cacheIgnoredFiles" json:"cacheIgnoredFiles" default:"true"`
  149. ProgressUpdateIntervalS int `xml:"progressUpdateIntervalS" json:"progressUpdateIntervalS" default:"5"`
  150. SymlinksEnabled bool `xml:"symlinksEnabled" json:"symlinksEnabled" default:"true"`
  151. LimitBandwidthInLan bool `xml:"limitBandwidthInLan" json:"limitBandwidthInLan" default:"false"`
  152. Deprecated_RescanIntervalS int `xml:"rescanIntervalS,omitempty" json:"-"`
  153. Deprecated_UREnabled bool `xml:"urEnabled,omitempty" json:"-"`
  154. Deprecated_URDeclined bool `xml:"urDeclined,omitempty" json:"-"`
  155. Deprecated_ReadOnly bool `xml:"readOnly,omitempty" json:"-"`
  156. Deprecated_GUIEnabled bool `xml:"guiEnabled,omitempty" json:"-"`
  157. Deprecated_GUIAddress string `xml:"guiAddress,omitempty" json:"-"`
  158. }
  159. type GUIConfiguration struct {
  160. Enabled bool `xml:"enabled,attr" json:"enabled" default:"true"`
  161. Address string `xml:"address" json:"address" default:"127.0.0.1:8080"`
  162. User string `xml:"user,omitempty" json:"user"`
  163. Password string `xml:"password,omitempty" json:"password"`
  164. UseTLS bool `xml:"tls,attr" json:"useTLS"`
  165. APIKey string `xml:"apikey,omitempty" json:"apiKey"`
  166. }
  167. func New(myID protocol.DeviceID) Configuration {
  168. var cfg Configuration
  169. cfg.Version = CurrentVersion
  170. cfg.OriginalVersion = CurrentVersion
  171. setDefaults(&cfg)
  172. setDefaults(&cfg.Options)
  173. setDefaults(&cfg.GUI)
  174. cfg.prepare(myID)
  175. return cfg
  176. }
  177. func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  178. var cfg Configuration
  179. setDefaults(&cfg)
  180. setDefaults(&cfg.Options)
  181. setDefaults(&cfg.GUI)
  182. err := xml.NewDecoder(r).Decode(&cfg)
  183. cfg.OriginalVersion = cfg.Version
  184. cfg.prepare(myID)
  185. return cfg, err
  186. }
  187. func (cfg *Configuration) WriteXML(w io.Writer) error {
  188. e := xml.NewEncoder(w)
  189. e.Indent("", " ")
  190. err := e.Encode(cfg)
  191. if err != nil {
  192. return err
  193. }
  194. _, err = w.Write([]byte("\n"))
  195. return err
  196. }
  197. func (cfg *Configuration) prepare(myID protocol.DeviceID) {
  198. fillNilSlices(&cfg.Options)
  199. // Initialize an empty slices
  200. if cfg.Folders == nil {
  201. cfg.Folders = []FolderConfiguration{}
  202. }
  203. if cfg.IgnoredDevices == nil {
  204. cfg.IgnoredDevices = []protocol.DeviceID{}
  205. }
  206. // Check for missing, bad or duplicate folder ID:s
  207. var seenFolders = map[string]*FolderConfiguration{}
  208. var uniqueCounter int
  209. for i := range cfg.Folders {
  210. folder := &cfg.Folders[i]
  211. if len(folder.Path) == 0 {
  212. folder.Invalid = "no directory configured"
  213. continue
  214. }
  215. // The reason it's done like this:
  216. // C: -> C:\ -> C:\ (issue that this is trying to fix)
  217. // C:\somedir -> C:\somedir\ -> C:\somedir
  218. // C:\somedir\ -> C:\somedir\\ -> C:\somedir
  219. // This way in the tests, we get away without OS specific separators
  220. // in the test configs.
  221. folder.Path = filepath.Dir(folder.Path + string(filepath.Separator))
  222. if folder.ID == "" {
  223. folder.ID = "default"
  224. }
  225. if seen, ok := seenFolders[folder.ID]; ok {
  226. l.Warnf("Multiple folders with ID %q; disabling", folder.ID)
  227. seen.Invalid = "duplicate folder ID"
  228. if seen.ID == folder.ID {
  229. uniqueCounter++
  230. seen.ID = fmt.Sprintf("%s~%d", folder.ID, uniqueCounter)
  231. }
  232. folder.Invalid = "duplicate folder ID"
  233. uniqueCounter++
  234. folder.ID = fmt.Sprintf("%s~%d", folder.ID, uniqueCounter)
  235. } else {
  236. seenFolders[folder.ID] = folder
  237. }
  238. }
  239. if cfg.Options.Deprecated_URDeclined {
  240. cfg.Options.URAccepted = -1
  241. cfg.Options.URUniqueID = ""
  242. }
  243. cfg.Options.Deprecated_URDeclined = false
  244. cfg.Options.Deprecated_UREnabled = false
  245. // Upgrade configuration versions as appropriate
  246. if cfg.Version == 1 {
  247. convertV1V2(cfg)
  248. }
  249. if cfg.Version == 2 {
  250. convertV2V3(cfg)
  251. }
  252. if cfg.Version == 3 {
  253. convertV3V4(cfg)
  254. }
  255. if cfg.Version == 4 {
  256. convertV4V5(cfg)
  257. }
  258. if cfg.Version == 5 {
  259. convertV5V6(cfg)
  260. }
  261. if cfg.Version == 6 {
  262. convertV6V7(cfg)
  263. }
  264. if cfg.Version == 7 {
  265. convertV7V8(cfg)
  266. }
  267. if cfg.Version == 8 {
  268. convertV8V9(cfg)
  269. }
  270. if cfg.Version == 9 {
  271. convertV9V10(cfg)
  272. }
  273. // Hash old cleartext passwords
  274. if len(cfg.GUI.Password) > 0 && cfg.GUI.Password[0] != '$' {
  275. hash, err := bcrypt.GenerateFromPassword([]byte(cfg.GUI.Password), 0)
  276. if err != nil {
  277. l.Warnln("bcrypting password:", err)
  278. } else {
  279. cfg.GUI.Password = string(hash)
  280. }
  281. }
  282. // Build a list of available devices
  283. existingDevices := make(map[protocol.DeviceID]bool)
  284. for _, device := range cfg.Devices {
  285. existingDevices[device.DeviceID] = true
  286. }
  287. // Ensure this device is present in the config
  288. if !existingDevices[myID] {
  289. myName, _ := os.Hostname()
  290. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  291. DeviceID: myID,
  292. Name: myName,
  293. })
  294. existingDevices[myID] = true
  295. }
  296. sort.Sort(DeviceConfigurationList(cfg.Devices))
  297. // Ensure that any loose devices are not present in the wrong places
  298. // Ensure that there are no duplicate devices
  299. // Ensure that puller settings are sane
  300. for i := range cfg.Folders {
  301. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  302. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  303. cfg.Folders[i].Devices = ensureNoDuplicates(cfg.Folders[i].Devices)
  304. if cfg.Folders[i].Copiers == 0 {
  305. cfg.Folders[i].Copiers = 1
  306. }
  307. if cfg.Folders[i].Pullers == 0 {
  308. cfg.Folders[i].Pullers = 16
  309. }
  310. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  311. }
  312. // An empty address list is equivalent to a single "dynamic" entry
  313. for i := range cfg.Devices {
  314. n := &cfg.Devices[i]
  315. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  316. n.Addresses = []string{"dynamic"}
  317. }
  318. }
  319. // Very short reconnection intervals are annoying
  320. if cfg.Options.ReconnectIntervalS < 5 {
  321. cfg.Options.ReconnectIntervalS = 5
  322. }
  323. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  324. cfg.Options.GlobalAnnServers = uniqueStrings(cfg.Options.GlobalAnnServers)
  325. if cfg.GUI.APIKey == "" {
  326. cfg.GUI.APIKey = randomString(32)
  327. }
  328. }
  329. // ChangeRequiresRestart returns true if updating the configuration requires a
  330. // complete restart.
  331. func ChangeRequiresRestart(from, to Configuration) bool {
  332. // Adding, removing or changing folders requires restart
  333. if !reflect.DeepEqual(from.Folders, to.Folders) {
  334. return true
  335. }
  336. // Removing a device requres restart
  337. toDevs := make(map[protocol.DeviceID]bool, len(from.Devices))
  338. for _, dev := range to.Devices {
  339. toDevs[dev.DeviceID] = true
  340. }
  341. for _, dev := range from.Devices {
  342. if _, ok := toDevs[dev.DeviceID]; !ok {
  343. return true
  344. }
  345. }
  346. // Changing usage reporting to on or off does not require a restart.
  347. to.Options.URAccepted = from.Options.URAccepted
  348. to.Options.URUniqueID = from.Options.URUniqueID
  349. // All of the generic options require restart
  350. if !reflect.DeepEqual(from.Options, to.Options) || !reflect.DeepEqual(from.GUI, to.GUI) {
  351. return true
  352. }
  353. return false
  354. }
  355. func convertV9V10(cfg *Configuration) {
  356. // Enable auto normalization on existing folders.
  357. for i := range cfg.Folders {
  358. cfg.Folders[i].AutoNormalize = true
  359. }
  360. cfg.Version = 10
  361. }
  362. func convertV8V9(cfg *Configuration) {
  363. // Compression is interpreted and serialized differently, but no enforced
  364. // changes. Still need a new version number since the compression stuff
  365. // isn't understandable by earlier versions.
  366. cfg.Version = 9
  367. }
  368. func convertV7V8(cfg *Configuration) {
  369. // Add IPv6 announce server
  370. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "udp4://announce.syncthing.net:22026" {
  371. cfg.Options.GlobalAnnServers = append(cfg.Options.GlobalAnnServers, "udp6://announce-v6.syncthing.net:22026")
  372. }
  373. cfg.Version = 8
  374. }
  375. func convertV6V7(cfg *Configuration) {
  376. // Migrate announce server addresses to the new URL based format
  377. for i := range cfg.Options.GlobalAnnServers {
  378. cfg.Options.GlobalAnnServers[i] = "udp4://" + cfg.Options.GlobalAnnServers[i]
  379. }
  380. cfg.Version = 7
  381. }
  382. func convertV5V6(cfg *Configuration) {
  383. // Added ".stfolder" file at folder roots to identify mount issues
  384. // Doesn't affect the config itself, but uses config migrations to identify
  385. // the migration point.
  386. for _, folder := range Wrap("", *cfg).Folders() {
  387. // Best attempt, if it fails, it fails, the user will have to fix
  388. // it up manually, as the repo will not get started.
  389. folder.CreateMarker()
  390. }
  391. cfg.Version = 6
  392. }
  393. func convertV4V5(cfg *Configuration) {
  394. // Renamed a bunch of fields in the structs.
  395. if cfg.Deprecated_Nodes == nil {
  396. cfg.Deprecated_Nodes = []DeviceConfiguration{}
  397. }
  398. if cfg.Deprecated_Repositories == nil {
  399. cfg.Deprecated_Repositories = []FolderConfiguration{}
  400. }
  401. cfg.Devices = cfg.Deprecated_Nodes
  402. cfg.Folders = cfg.Deprecated_Repositories
  403. for i := range cfg.Folders {
  404. cfg.Folders[i].Path = cfg.Folders[i].Deprecated_Directory
  405. cfg.Folders[i].Deprecated_Directory = ""
  406. cfg.Folders[i].Devices = cfg.Folders[i].Deprecated_Nodes
  407. cfg.Folders[i].Deprecated_Nodes = nil
  408. }
  409. cfg.Deprecated_Nodes = nil
  410. cfg.Deprecated_Repositories = nil
  411. cfg.Version = 5
  412. }
  413. func convertV3V4(cfg *Configuration) {
  414. // In previous versions, rescan interval was common for each folder.
  415. // From now, it can be set independently. We have to make sure, that after upgrade
  416. // the individual rescan interval will be defined for every existing folder.
  417. for i := range cfg.Deprecated_Repositories {
  418. cfg.Deprecated_Repositories[i].RescanIntervalS = cfg.Options.Deprecated_RescanIntervalS
  419. }
  420. cfg.Options.Deprecated_RescanIntervalS = 0
  421. // In previous versions, folders held full device configurations.
  422. // Since that's the only place where device configs were in V1, we still have
  423. // to define the deprecated fields to be able to upgrade from V1 to V4.
  424. for i, folder := range cfg.Deprecated_Repositories {
  425. for j := range folder.Deprecated_Nodes {
  426. rncfg := cfg.Deprecated_Repositories[i].Deprecated_Nodes[j]
  427. rncfg.Deprecated_Name = ""
  428. rncfg.Deprecated_Addresses = nil
  429. }
  430. }
  431. cfg.Version = 4
  432. }
  433. func convertV2V3(cfg *Configuration) {
  434. // In previous versions, compression was always on. When upgrading, enable
  435. // compression on all existing new. New devices will get compression on by
  436. // default by the GUI.
  437. for i := range cfg.Deprecated_Nodes {
  438. cfg.Deprecated_Nodes[i].Compression = protocol.CompressMetadata
  439. }
  440. // The global discovery format and port number changed in v0.9. Having the
  441. // default announce server but old port number is guaranteed to be legacy.
  442. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "announce.syncthing.net:22025" {
  443. cfg.Options.GlobalAnnServers = []string{"announce.syncthing.net:22026"}
  444. }
  445. cfg.Version = 3
  446. }
  447. func convertV1V2(cfg *Configuration) {
  448. // Collect the list of devices.
  449. // Replace device configs inside folders with only a reference to the
  450. // device ID. Set all folders to read only if the global read only flag is
  451. // set.
  452. var devices = map[string]FolderDeviceConfiguration{}
  453. for i, folder := range cfg.Deprecated_Repositories {
  454. cfg.Deprecated_Repositories[i].ReadOnly = cfg.Options.Deprecated_ReadOnly
  455. for j, device := range folder.Deprecated_Nodes {
  456. id := device.DeviceID.String()
  457. if _, ok := devices[id]; !ok {
  458. devices[id] = device
  459. }
  460. cfg.Deprecated_Repositories[i].Deprecated_Nodes[j] = FolderDeviceConfiguration{DeviceID: device.DeviceID}
  461. }
  462. }
  463. cfg.Options.Deprecated_ReadOnly = false
  464. // Set and sort the list of devices.
  465. for _, device := range devices {
  466. cfg.Deprecated_Nodes = append(cfg.Deprecated_Nodes, DeviceConfiguration{
  467. DeviceID: device.DeviceID,
  468. Name: device.Deprecated_Name,
  469. Addresses: device.Deprecated_Addresses,
  470. })
  471. }
  472. sort.Sort(DeviceConfigurationList(cfg.Deprecated_Nodes))
  473. // GUI
  474. cfg.GUI.Address = cfg.Options.Deprecated_GUIAddress
  475. cfg.GUI.Enabled = cfg.Options.Deprecated_GUIEnabled
  476. cfg.Options.Deprecated_GUIEnabled = false
  477. cfg.Options.Deprecated_GUIAddress = ""
  478. cfg.Version = 2
  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[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. }