config.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  320. cfg.Options.GlobalAnnServers = uniqueStrings(cfg.Options.GlobalAnnServers)
  321. if cfg.GUI.APIKey == "" {
  322. cfg.GUI.APIKey = randomString(32)
  323. }
  324. }
  325. // ChangeRequiresRestart returns true if updating the configuration requires a
  326. // complete restart.
  327. func ChangeRequiresRestart(from, to Configuration) bool {
  328. // Adding, removing or changing folders requires restart
  329. if !reflect.DeepEqual(from.Folders, to.Folders) {
  330. return true
  331. }
  332. // Removing a device requres restart
  333. toDevs := make(map[protocol.DeviceID]bool, len(from.Devices))
  334. for _, dev := range to.Devices {
  335. toDevs[dev.DeviceID] = true
  336. }
  337. for _, dev := range from.Devices {
  338. if _, ok := toDevs[dev.DeviceID]; !ok {
  339. return true
  340. }
  341. }
  342. // Changing usage reporting to on or off does not require a restart.
  343. to.Options.URAccepted = from.Options.URAccepted
  344. to.Options.URUniqueID = from.Options.URUniqueID
  345. // All of the generic options require restart
  346. if !reflect.DeepEqual(from.Options, to.Options) || !reflect.DeepEqual(from.GUI, to.GUI) {
  347. return true
  348. }
  349. return false
  350. }
  351. func convertV9V10(cfg *Configuration) {
  352. // Enable auto normalization on existing folders.
  353. for i := range cfg.Folders {
  354. cfg.Folders[i].AutoNormalize = true
  355. }
  356. cfg.Version = 10
  357. }
  358. func convertV8V9(cfg *Configuration) {
  359. // Compression is interpreted and serialized differently, but no enforced
  360. // changes. Still need a new version number since the compression stuff
  361. // isn't understandable by earlier versions.
  362. cfg.Version = 9
  363. }
  364. func convertV7V8(cfg *Configuration) {
  365. // Add IPv6 announce server
  366. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "udp4://announce.syncthing.net:22026" {
  367. cfg.Options.GlobalAnnServers = append(cfg.Options.GlobalAnnServers, "udp6://announce-v6.syncthing.net:22026")
  368. }
  369. cfg.Version = 8
  370. }
  371. func convertV6V7(cfg *Configuration) {
  372. // Migrate announce server addresses to the new URL based format
  373. for i := range cfg.Options.GlobalAnnServers {
  374. cfg.Options.GlobalAnnServers[i] = "udp4://" + cfg.Options.GlobalAnnServers[i]
  375. }
  376. cfg.Version = 7
  377. }
  378. func convertV5V6(cfg *Configuration) {
  379. // Added ".stfolder" file at folder roots to identify mount issues
  380. // Doesn't affect the config itself, but uses config migrations to identify
  381. // the migration point.
  382. for _, folder := range Wrap("", *cfg).Folders() {
  383. // Best attempt, if it fails, it fails, the user will have to fix
  384. // it up manually, as the repo will not get started.
  385. folder.CreateMarker()
  386. }
  387. cfg.Version = 6
  388. }
  389. func convertV4V5(cfg *Configuration) {
  390. // Renamed a bunch of fields in the structs.
  391. if cfg.Deprecated_Nodes == nil {
  392. cfg.Deprecated_Nodes = []DeviceConfiguration{}
  393. }
  394. if cfg.Deprecated_Repositories == nil {
  395. cfg.Deprecated_Repositories = []FolderConfiguration{}
  396. }
  397. cfg.Devices = cfg.Deprecated_Nodes
  398. cfg.Folders = cfg.Deprecated_Repositories
  399. for i := range cfg.Folders {
  400. cfg.Folders[i].Path = cfg.Folders[i].Deprecated_Directory
  401. cfg.Folders[i].Deprecated_Directory = ""
  402. cfg.Folders[i].Devices = cfg.Folders[i].Deprecated_Nodes
  403. cfg.Folders[i].Deprecated_Nodes = nil
  404. }
  405. cfg.Deprecated_Nodes = nil
  406. cfg.Deprecated_Repositories = nil
  407. cfg.Version = 5
  408. }
  409. func convertV3V4(cfg *Configuration) {
  410. // In previous versions, rescan interval was common for each folder.
  411. // From now, it can be set independently. We have to make sure, that after upgrade
  412. // the individual rescan interval will be defined for every existing folder.
  413. for i := range cfg.Deprecated_Repositories {
  414. cfg.Deprecated_Repositories[i].RescanIntervalS = cfg.Options.Deprecated_RescanIntervalS
  415. }
  416. cfg.Options.Deprecated_RescanIntervalS = 0
  417. // In previous versions, folders held full device configurations.
  418. // Since that's the only place where device configs were in V1, we still have
  419. // to define the deprecated fields to be able to upgrade from V1 to V4.
  420. for i, folder := range cfg.Deprecated_Repositories {
  421. for j := range folder.Deprecated_Nodes {
  422. rncfg := cfg.Deprecated_Repositories[i].Deprecated_Nodes[j]
  423. rncfg.Deprecated_Name = ""
  424. rncfg.Deprecated_Addresses = nil
  425. }
  426. }
  427. cfg.Version = 4
  428. }
  429. func convertV2V3(cfg *Configuration) {
  430. // In previous versions, compression was always on. When upgrading, enable
  431. // compression on all existing new. New devices will get compression on by
  432. // default by the GUI.
  433. for i := range cfg.Deprecated_Nodes {
  434. cfg.Deprecated_Nodes[i].Compression = protocol.CompressMetadata
  435. }
  436. // The global discovery format and port number changed in v0.9. Having the
  437. // default announce server but old port number is guaranteed to be legacy.
  438. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "announce.syncthing.net:22025" {
  439. cfg.Options.GlobalAnnServers = []string{"announce.syncthing.net:22026"}
  440. }
  441. cfg.Version = 3
  442. }
  443. func convertV1V2(cfg *Configuration) {
  444. // Collect the list of devices.
  445. // Replace device configs inside folders with only a reference to the
  446. // device ID. Set all folders to read only if the global read only flag is
  447. // set.
  448. var devices = map[string]FolderDeviceConfiguration{}
  449. for i, folder := range cfg.Deprecated_Repositories {
  450. cfg.Deprecated_Repositories[i].ReadOnly = cfg.Options.Deprecated_ReadOnly
  451. for j, device := range folder.Deprecated_Nodes {
  452. id := device.DeviceID.String()
  453. if _, ok := devices[id]; !ok {
  454. devices[id] = device
  455. }
  456. cfg.Deprecated_Repositories[i].Deprecated_Nodes[j] = FolderDeviceConfiguration{DeviceID: device.DeviceID}
  457. }
  458. }
  459. cfg.Options.Deprecated_ReadOnly = false
  460. // Set and sort the list of devices.
  461. for _, device := range devices {
  462. cfg.Deprecated_Nodes = append(cfg.Deprecated_Nodes, DeviceConfiguration{
  463. DeviceID: device.DeviceID,
  464. Name: device.Deprecated_Name,
  465. Addresses: device.Deprecated_Addresses,
  466. })
  467. }
  468. sort.Sort(DeviceConfigurationList(cfg.Deprecated_Nodes))
  469. // GUI
  470. cfg.GUI.Address = cfg.Options.Deprecated_GUIAddress
  471. cfg.GUI.Enabled = cfg.Options.Deprecated_GUIEnabled
  472. cfg.Options.Deprecated_GUIEnabled = false
  473. cfg.Options.Deprecated_GUIAddress = ""
  474. cfg.Version = 2
  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[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. }