config.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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 = 9
  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" default:"60"`
  44. IgnorePerms bool `xml:"ignorePerms,attr" json:"ignorePerms"`
  45. AutoNormalize bool `xml:"autoNormalize,attr" json:"autoNormalize" default:"true"`
  46. Versioning VersioningConfiguration `xml:"versioning" json:"versioning"`
  47. LenientMtimes bool `xml:"lenientMtimes" json:"lenientMTimes"`
  48. Copiers int `xml:"copiers" json:"copiers" default:"1"` // This defines how many files are handled concurrently.
  49. Pullers int `xml:"pullers" json:"pullers" default:"16"` // Defines how many blocks are fetched at the same time, possibly between separate copier routines.
  50. Hashers int `xml:"hashers" json:"hashers" default:"0"` // 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. // Hash old cleartext passwords
  271. if len(cfg.GUI.Password) > 0 && cfg.GUI.Password[0] != '$' {
  272. hash, err := bcrypt.GenerateFromPassword([]byte(cfg.GUI.Password), 0)
  273. if err != nil {
  274. l.Warnln("bcrypting password:", err)
  275. } else {
  276. cfg.GUI.Password = string(hash)
  277. }
  278. }
  279. // Build a list of available devices
  280. existingDevices := make(map[protocol.DeviceID]bool)
  281. for _, device := range cfg.Devices {
  282. existingDevices[device.DeviceID] = true
  283. }
  284. // Ensure this device is present in the config
  285. if !existingDevices[myID] {
  286. myName, _ := os.Hostname()
  287. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  288. DeviceID: myID,
  289. Name: myName,
  290. })
  291. existingDevices[myID] = true
  292. }
  293. sort.Sort(DeviceConfigurationList(cfg.Devices))
  294. // Ensure that any loose devices are not present in the wrong places
  295. // Ensure that there are no duplicate devices
  296. // Ensure that puller settings are sane
  297. for i := range cfg.Folders {
  298. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  299. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  300. cfg.Folders[i].Devices = ensureNoDuplicates(cfg.Folders[i].Devices)
  301. if cfg.Folders[i].Copiers == 0 {
  302. cfg.Folders[i].Copiers = 1
  303. }
  304. if cfg.Folders[i].Pullers == 0 {
  305. cfg.Folders[i].Pullers = 16
  306. }
  307. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  308. }
  309. // An empty address list is equivalent to a single "dynamic" entry
  310. for i := range cfg.Devices {
  311. n := &cfg.Devices[i]
  312. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  313. n.Addresses = []string{"dynamic"}
  314. }
  315. }
  316. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  317. cfg.Options.GlobalAnnServers = uniqueStrings(cfg.Options.GlobalAnnServers)
  318. if cfg.GUI.APIKey == "" {
  319. cfg.GUI.APIKey = randomString(32)
  320. }
  321. }
  322. // ChangeRequiresRestart returns true if updating the configuration requires a
  323. // complete restart.
  324. func ChangeRequiresRestart(from, to Configuration) bool {
  325. // Adding, removing or changing folders requires restart
  326. if !reflect.DeepEqual(from.Folders, to.Folders) {
  327. return true
  328. }
  329. // Removing a device requres restart
  330. toDevs := make(map[protocol.DeviceID]bool, len(from.Devices))
  331. for _, dev := range to.Devices {
  332. toDevs[dev.DeviceID] = true
  333. }
  334. for _, dev := range from.Devices {
  335. if _, ok := toDevs[dev.DeviceID]; !ok {
  336. return true
  337. }
  338. }
  339. // Changing usage reporting to on or off does not require a restart.
  340. to.Options.URAccepted = from.Options.URAccepted
  341. to.Options.URUniqueID = from.Options.URUniqueID
  342. // All of the generic options require restart
  343. if !reflect.DeepEqual(from.Options, to.Options) || !reflect.DeepEqual(from.GUI, to.GUI) {
  344. return true
  345. }
  346. return false
  347. }
  348. func convertV8V9(cfg *Configuration) {
  349. // Compression is interpreted and serialized differently, but no enforced
  350. // changes. Still need a new version number since the compression stuff
  351. // isn't understandable by earlier versions.
  352. cfg.Version = 9
  353. }
  354. func convertV7V8(cfg *Configuration) {
  355. // Add IPv6 announce server
  356. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "udp4://announce.syncthing.net:22026" {
  357. cfg.Options.GlobalAnnServers = append(cfg.Options.GlobalAnnServers, "udp6://announce-v6.syncthing.net:22026")
  358. }
  359. cfg.Version = 8
  360. }
  361. func convertV6V7(cfg *Configuration) {
  362. // Migrate announce server addresses to the new URL based format
  363. for i := range cfg.Options.GlobalAnnServers {
  364. cfg.Options.GlobalAnnServers[i] = "udp4://" + cfg.Options.GlobalAnnServers[i]
  365. }
  366. cfg.Version = 7
  367. }
  368. func convertV5V6(cfg *Configuration) {
  369. // Added ".stfolder" file at folder roots to identify mount issues
  370. // Doesn't affect the config itself, but uses config migrations to identify
  371. // the migration point.
  372. for _, folder := range Wrap("", *cfg).Folders() {
  373. // Best attempt, if it fails, it fails, the user will have to fix
  374. // it up manually, as the repo will not get started.
  375. folder.CreateMarker()
  376. }
  377. cfg.Version = 6
  378. }
  379. func convertV4V5(cfg *Configuration) {
  380. // Renamed a bunch of fields in the structs.
  381. if cfg.Deprecated_Nodes == nil {
  382. cfg.Deprecated_Nodes = []DeviceConfiguration{}
  383. }
  384. if cfg.Deprecated_Repositories == nil {
  385. cfg.Deprecated_Repositories = []FolderConfiguration{}
  386. }
  387. cfg.Devices = cfg.Deprecated_Nodes
  388. cfg.Folders = cfg.Deprecated_Repositories
  389. for i := range cfg.Folders {
  390. cfg.Folders[i].Path = cfg.Folders[i].Deprecated_Directory
  391. cfg.Folders[i].Deprecated_Directory = ""
  392. cfg.Folders[i].Devices = cfg.Folders[i].Deprecated_Nodes
  393. cfg.Folders[i].Deprecated_Nodes = nil
  394. }
  395. cfg.Deprecated_Nodes = nil
  396. cfg.Deprecated_Repositories = nil
  397. cfg.Version = 5
  398. }
  399. func convertV3V4(cfg *Configuration) {
  400. // In previous versions, rescan interval was common for each folder.
  401. // From now, it can be set independently. We have to make sure, that after upgrade
  402. // the individual rescan interval will be defined for every existing folder.
  403. for i := range cfg.Deprecated_Repositories {
  404. cfg.Deprecated_Repositories[i].RescanIntervalS = cfg.Options.Deprecated_RescanIntervalS
  405. }
  406. cfg.Options.Deprecated_RescanIntervalS = 0
  407. // In previous versions, folders held full device configurations.
  408. // Since that's the only place where device configs were in V1, we still have
  409. // to define the deprecated fields to be able to upgrade from V1 to V4.
  410. for i, folder := range cfg.Deprecated_Repositories {
  411. for j := range folder.Deprecated_Nodes {
  412. rncfg := cfg.Deprecated_Repositories[i].Deprecated_Nodes[j]
  413. rncfg.Deprecated_Name = ""
  414. rncfg.Deprecated_Addresses = nil
  415. }
  416. }
  417. cfg.Version = 4
  418. }
  419. func convertV2V3(cfg *Configuration) {
  420. // In previous versions, compression was always on. When upgrading, enable
  421. // compression on all existing new. New devices will get compression on by
  422. // default by the GUI.
  423. for i := range cfg.Deprecated_Nodes {
  424. cfg.Deprecated_Nodes[i].Compression = protocol.CompressMetadata
  425. }
  426. // The global discovery format and port number changed in v0.9. Having the
  427. // default announce server but old port number is guaranteed to be legacy.
  428. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "announce.syncthing.net:22025" {
  429. cfg.Options.GlobalAnnServers = []string{"announce.syncthing.net:22026"}
  430. }
  431. cfg.Version = 3
  432. }
  433. func convertV1V2(cfg *Configuration) {
  434. // Collect the list of devices.
  435. // Replace device configs inside folders with only a reference to the
  436. // device ID. Set all folders to read only if the global read only flag is
  437. // set.
  438. var devices = map[string]FolderDeviceConfiguration{}
  439. for i, folder := range cfg.Deprecated_Repositories {
  440. cfg.Deprecated_Repositories[i].ReadOnly = cfg.Options.Deprecated_ReadOnly
  441. for j, device := range folder.Deprecated_Nodes {
  442. id := device.DeviceID.String()
  443. if _, ok := devices[id]; !ok {
  444. devices[id] = device
  445. }
  446. cfg.Deprecated_Repositories[i].Deprecated_Nodes[j] = FolderDeviceConfiguration{DeviceID: device.DeviceID}
  447. }
  448. }
  449. cfg.Options.Deprecated_ReadOnly = false
  450. // Set and sort the list of devices.
  451. for _, device := range devices {
  452. cfg.Deprecated_Nodes = append(cfg.Deprecated_Nodes, DeviceConfiguration{
  453. DeviceID: device.DeviceID,
  454. Name: device.Deprecated_Name,
  455. Addresses: device.Deprecated_Addresses,
  456. })
  457. }
  458. sort.Sort(DeviceConfigurationList(cfg.Deprecated_Nodes))
  459. // GUI
  460. cfg.GUI.Address = cfg.Options.Deprecated_GUIAddress
  461. cfg.GUI.Enabled = cfg.Options.Deprecated_GUIEnabled
  462. cfg.Options.Deprecated_GUIEnabled = false
  463. cfg.Options.Deprecated_GUIAddress = ""
  464. cfg.Version = 2
  465. }
  466. func setDefaults(data interface{}) error {
  467. s := reflect.ValueOf(data).Elem()
  468. t := s.Type()
  469. for i := 0; i < s.NumField(); i++ {
  470. f := s.Field(i)
  471. tag := t.Field(i).Tag
  472. v := tag.Get("default")
  473. if len(v) > 0 {
  474. switch f.Interface().(type) {
  475. case string:
  476. f.SetString(v)
  477. case int:
  478. i, err := strconv.ParseInt(v, 10, 64)
  479. if err != nil {
  480. return err
  481. }
  482. f.SetInt(i)
  483. case bool:
  484. f.SetBool(v == "true")
  485. case []string:
  486. // We don't do anything with string slices here. Any default
  487. // we set will be appended to by the XML decoder, so we fill
  488. // those after decoding.
  489. default:
  490. panic(f.Type())
  491. }
  492. }
  493. }
  494. return nil
  495. }
  496. // fillNilSlices sets default value on slices that are still nil.
  497. func fillNilSlices(data interface{}) error {
  498. s := reflect.ValueOf(data).Elem()
  499. t := s.Type()
  500. for i := 0; i < s.NumField(); i++ {
  501. f := s.Field(i)
  502. tag := t.Field(i).Tag
  503. v := tag.Get("default")
  504. if len(v) > 0 {
  505. switch f.Interface().(type) {
  506. case []string:
  507. if f.IsNil() {
  508. // Treat the default as a comma separated slice
  509. vs := strings.Split(v, ",")
  510. for i := range vs {
  511. vs[i] = strings.TrimSpace(vs[i])
  512. }
  513. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), len(vs), len(vs))
  514. for i, v := range vs {
  515. rv.Index(i).SetString(v)
  516. }
  517. f.Set(rv)
  518. }
  519. }
  520. }
  521. }
  522. return nil
  523. }
  524. func uniqueStrings(ss []string) []string {
  525. var m = make(map[string]bool, len(ss))
  526. for _, s := range ss {
  527. m[s] = true
  528. }
  529. var us = make([]string, 0, len(m))
  530. for k := range m {
  531. us = append(us, k)
  532. }
  533. sort.Strings(us)
  534. return us
  535. }
  536. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  537. for _, device := range devices {
  538. if device.DeviceID.Equals(myID) {
  539. return devices
  540. }
  541. }
  542. devices = append(devices, FolderDeviceConfiguration{
  543. DeviceID: myID,
  544. })
  545. return devices
  546. }
  547. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  548. count := len(devices)
  549. i := 0
  550. loop:
  551. for i < count {
  552. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  553. devices[i] = devices[count-1]
  554. count--
  555. continue loop
  556. }
  557. i++
  558. }
  559. return devices[0:count]
  560. }
  561. func ensureNoDuplicates(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  562. count := len(devices)
  563. i := 0
  564. seenDevices := make(map[protocol.DeviceID]bool)
  565. loop:
  566. for i < count {
  567. id := devices[i].DeviceID
  568. if _, ok := seenDevices[id]; ok {
  569. devices[i] = devices[count-1]
  570. count--
  571. continue loop
  572. }
  573. seenDevices[id] = true
  574. i++
  575. }
  576. return devices[0:count]
  577. }
  578. type DeviceConfigurationList []DeviceConfiguration
  579. func (l DeviceConfigurationList) Less(a, b int) bool {
  580. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  581. }
  582. func (l DeviceConfigurationList) Swap(a, b int) {
  583. l[a], l[b] = l[b], l[a]
  584. }
  585. func (l DeviceConfigurationList) Len() int {
  586. return len(l)
  587. }
  588. type FolderDeviceConfigurationList []FolderDeviceConfiguration
  589. func (l FolderDeviceConfigurationList) Less(a, b int) bool {
  590. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  591. }
  592. func (l FolderDeviceConfigurationList) Swap(a, b int) {
  593. l[a], l[b] = l[b], l[a]
  594. }
  595. func (l FolderDeviceConfigurationList) Len() int {
  596. return len(l)
  597. }
  598. // randomCharset contains the characters that can make up a randomString().
  599. const randomCharset = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
  600. // randomString returns a string of random characters (taken from
  601. // randomCharset) of the specified length.
  602. func randomString(l int) string {
  603. bs := make([]byte, l)
  604. for i := range bs {
  605. bs[i] = randomCharset[rand.Intn(len(randomCharset))]
  606. }
  607. return string(bs)
  608. }