config.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. // Package config implements reading and writing of the syncthing configuration file.
  16. package config
  17. import (
  18. "encoding/xml"
  19. "fmt"
  20. "io"
  21. "math/rand"
  22. "os"
  23. "path/filepath"
  24. "reflect"
  25. "sort"
  26. "strconv"
  27. "strings"
  28. "github.com/calmh/logger"
  29. "github.com/syncthing/protocol"
  30. "github.com/syncthing/syncthing/internal/osutil"
  31. "golang.org/x/crypto/bcrypt"
  32. )
  33. var l = logger.DefaultLogger
  34. const CurrentVersion = 9
  35. type Configuration struct {
  36. Version int `xml:"version,attr" json:"version"`
  37. Folders []FolderConfiguration `xml:"folder" json:"folders"`
  38. Devices []DeviceConfiguration `xml:"device" json:"devices"`
  39. GUI GUIConfiguration `xml:"gui" json:"gui"`
  40. Options OptionsConfiguration `xml:"options" json:"options"`
  41. IgnoredDevices []protocol.DeviceID `xml:"ignoredDevice" json:"ignoredDevices"`
  42. XMLName xml.Name `xml:"configuration" json:"-"`
  43. OriginalVersion int `xml:"-" json:"-"` // The version we read from disk, before any conversion
  44. Deprecated_Repositories []FolderConfiguration `xml:"repository" json:"-"`
  45. Deprecated_Nodes []DeviceConfiguration `xml:"node" json:"-"`
  46. }
  47. type FolderConfiguration struct {
  48. ID string `xml:"id,attr" json:"id"`
  49. Path string `xml:"path,attr" json:"path"`
  50. Devices []FolderDeviceConfiguration `xml:"device" json:"devices"`
  51. ReadOnly bool `xml:"ro,attr" json:"readOnly"`
  52. RescanIntervalS int `xml:"rescanIntervalS,attr" json:"rescanIntervalS" default:"60"`
  53. IgnorePerms bool `xml:"ignorePerms,attr" json:"ignorePerms"`
  54. Versioning VersioningConfiguration `xml:"versioning" json:"versioning"`
  55. LenientMtimes bool `xml:"lenientMtimes" json:"lenientMTimes"`
  56. Copiers int `xml:"copiers" json:"copiers" default:"1"` // This defines how many files are handled concurrently.
  57. Pullers int `xml:"pullers" json:"pullers" default:"16"` // Defines how many blocks are fetched at the same time, possibly between separate copier routines.
  58. 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.
  59. Invalid string `xml:"-" json:"invalid"` // Set at runtime when there is an error, not saved
  60. deviceIDs []protocol.DeviceID
  61. Deprecated_Directory string `xml:"directory,omitempty,attr" json:"-"`
  62. Deprecated_Nodes []FolderDeviceConfiguration `xml:"node" json:"-"`
  63. }
  64. func (f *FolderConfiguration) CreateMarker() error {
  65. if !f.HasMarker() {
  66. marker := filepath.Join(f.Path, ".stfolder")
  67. fd, err := os.Create(marker)
  68. if err != nil {
  69. return err
  70. }
  71. fd.Close()
  72. osutil.HideFile(marker)
  73. }
  74. return nil
  75. }
  76. func (f *FolderConfiguration) HasMarker() bool {
  77. _, err := os.Stat(filepath.Join(f.Path, ".stfolder"))
  78. if err != nil {
  79. return false
  80. }
  81. return true
  82. }
  83. func (f *FolderConfiguration) DeviceIDs() []protocol.DeviceID {
  84. if f.deviceIDs == nil {
  85. for _, n := range f.Devices {
  86. f.deviceIDs = append(f.deviceIDs, n.DeviceID)
  87. }
  88. }
  89. return f.deviceIDs
  90. }
  91. type VersioningConfiguration struct {
  92. Type string `xml:"type,attr" json:"type"`
  93. Params map[string]string `json:"params"`
  94. }
  95. type InternalVersioningConfiguration struct {
  96. Type string `xml:"type,attr,omitempty"`
  97. Params []InternalParam `xml:"param"`
  98. }
  99. type InternalParam struct {
  100. Key string `xml:"key,attr"`
  101. Val string `xml:"val,attr"`
  102. }
  103. func (c *VersioningConfiguration) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
  104. var tmp InternalVersioningConfiguration
  105. tmp.Type = c.Type
  106. for k, v := range c.Params {
  107. tmp.Params = append(tmp.Params, InternalParam{k, v})
  108. }
  109. return e.EncodeElement(tmp, start)
  110. }
  111. func (c *VersioningConfiguration) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
  112. var tmp InternalVersioningConfiguration
  113. err := d.DecodeElement(&tmp, &start)
  114. if err != nil {
  115. return err
  116. }
  117. c.Type = tmp.Type
  118. c.Params = make(map[string]string, len(tmp.Params))
  119. for _, p := range tmp.Params {
  120. c.Params[p.Key] = p.Val
  121. }
  122. return nil
  123. }
  124. type DeviceConfiguration struct {
  125. DeviceID protocol.DeviceID `xml:"id,attr" json:"deviceID"`
  126. Name string `xml:"name,attr,omitempty" json:"name"`
  127. Addresses []string `xml:"address,omitempty" json:"addresses"`
  128. Compression protocol.Compression `xml:"compression,attr" json:"compression"`
  129. CertName string `xml:"certName,attr,omitempty" json:"certName"`
  130. Introducer bool `xml:"introducer,attr" json:"introducer"`
  131. }
  132. type FolderDeviceConfiguration struct {
  133. DeviceID protocol.DeviceID `xml:"id,attr" json:"deviceID"`
  134. Deprecated_Name string `xml:"name,attr,omitempty" json:"-"`
  135. Deprecated_Addresses []string `xml:"address,omitempty" json:"-"`
  136. }
  137. type OptionsConfiguration struct {
  138. ListenAddress []string `xml:"listenAddress" json:"listenAddress" default:"0.0.0.0:22000"`
  139. GlobalAnnServers []string `xml:"globalAnnounceServer" json:"globalAnnounceServers" json:"globalAnnounceServer" default:"udp4://announce.syncthing.net:22026, udp6://announce-v6.syncthing.net:22026"`
  140. GlobalAnnEnabled bool `xml:"globalAnnounceEnabled" json:"globalAnnounceEnabled" default:"true"`
  141. LocalAnnEnabled bool `xml:"localAnnounceEnabled" json:"localAnnounceEnabled" default:"true"`
  142. LocalAnnPort int `xml:"localAnnouncePort" json:"localAnnouncePort" default:"21025"`
  143. LocalAnnMCAddr string `xml:"localAnnounceMCAddr" json:"localAnnounceMCAddr" default:"[ff32::5222]:21026"`
  144. MaxSendKbps int `xml:"maxSendKbps" json:"maxSendKbps"`
  145. MaxRecvKbps int `xml:"maxRecvKbps" json:"maxRecvKbps"`
  146. ReconnectIntervalS int `xml:"reconnectionIntervalS" json:"reconnectionIntervalS" default:"60"`
  147. StartBrowser bool `xml:"startBrowser" json:"startBrowser" default:"true"`
  148. UPnPEnabled bool `xml:"upnpEnabled" json:"upnpEnabled" default:"true"`
  149. UPnPLease int `xml:"upnpLeaseMinutes" json:"upnpLeaseMinutes" default:"0"`
  150. UPnPRenewal int `xml:"upnpRenewalMinutes" json:"upnpRenewalMinutes" default:"30"`
  151. URAccepted int `xml:"urAccepted" json:"urAccepted"` // Accepted usage reporting version; 0 for off (undecided), -1 for off (permanently)
  152. URUniqueID string `xml:"urUniqueID" json:"urUniqueId"` // Unique ID for reporting purposes, regenerated when UR is turned on.
  153. RestartOnWakeup bool `xml:"restartOnWakeup" json:"restartOnWakeup" default:"true"`
  154. AutoUpgradeIntervalH int `xml:"autoUpgradeIntervalH" json:"autoUpgradeIntervalH" default:"12"` // 0 for off
  155. KeepTemporariesH int `xml:"keepTemporariesH" json:"keepTemporariesH" default:"24"` // 0 for off
  156. CacheIgnoredFiles bool `xml:"cacheIgnoredFiles" json:"cacheIgnoredFiles" default:"true"`
  157. ProgressUpdateIntervalS int `xml:"progressUpdateIntervalS" json:"progressUpdateIntervalS" default:"5"`
  158. SymlinksEnabled bool `xml:"symlinksEnabled" json:"symlinksEnabled" default:"true"`
  159. LimitBandwidthInLan bool `xml:"limitBandwidthInLan" json:"limitBandwidthInLan" default:"false"`
  160. Deprecated_RescanIntervalS int `xml:"rescanIntervalS,omitempty" json:"-"`
  161. Deprecated_UREnabled bool `xml:"urEnabled,omitempty" json:"-"`
  162. Deprecated_URDeclined bool `xml:"urDeclined,omitempty" json:"-"`
  163. Deprecated_ReadOnly bool `xml:"readOnly,omitempty" json:"-"`
  164. Deprecated_GUIEnabled bool `xml:"guiEnabled,omitempty" json:"-"`
  165. Deprecated_GUIAddress string `xml:"guiAddress,omitempty" json:"-"`
  166. }
  167. type GUIConfiguration struct {
  168. Enabled bool `xml:"enabled,attr" json:"enabled" default:"true"`
  169. Address string `xml:"address" json:"address" default:"127.0.0.1:8080"`
  170. User string `xml:"user,omitempty" json:"user"`
  171. Password string `xml:"password,omitempty" json:"password"`
  172. UseTLS bool `xml:"tls,attr" json:"useTLS"`
  173. APIKey string `xml:"apikey,omitempty" json:"apiKey"`
  174. }
  175. func New(myID protocol.DeviceID) Configuration {
  176. var cfg Configuration
  177. cfg.Version = CurrentVersion
  178. cfg.OriginalVersion = CurrentVersion
  179. setDefaults(&cfg)
  180. setDefaults(&cfg.Options)
  181. setDefaults(&cfg.GUI)
  182. cfg.prepare(myID)
  183. return cfg
  184. }
  185. func ReadXML(r io.Reader, myID protocol.DeviceID) (Configuration, error) {
  186. var cfg Configuration
  187. setDefaults(&cfg)
  188. setDefaults(&cfg.Options)
  189. setDefaults(&cfg.GUI)
  190. err := xml.NewDecoder(r).Decode(&cfg)
  191. cfg.OriginalVersion = cfg.Version
  192. cfg.prepare(myID)
  193. return cfg, err
  194. }
  195. func (cfg *Configuration) WriteXML(w io.Writer) error {
  196. e := xml.NewEncoder(w)
  197. e.Indent("", " ")
  198. err := e.Encode(cfg)
  199. if err != nil {
  200. return err
  201. }
  202. _, err = w.Write([]byte("\n"))
  203. return err
  204. }
  205. func (cfg *Configuration) prepare(myID protocol.DeviceID) {
  206. fillNilSlices(&cfg.Options)
  207. // Initialize an empty slices
  208. if cfg.Folders == nil {
  209. cfg.Folders = []FolderConfiguration{}
  210. }
  211. if cfg.IgnoredDevices == nil {
  212. cfg.IgnoredDevices = []protocol.DeviceID{}
  213. }
  214. // Check for missing, bad or duplicate folder ID:s
  215. var seenFolders = map[string]*FolderConfiguration{}
  216. var uniqueCounter int
  217. for i := range cfg.Folders {
  218. folder := &cfg.Folders[i]
  219. if len(folder.Path) == 0 {
  220. folder.Invalid = "no directory configured"
  221. continue
  222. }
  223. // The reason it's done like this:
  224. // C: -> C:\ -> C:\ (issue that this is trying to fix)
  225. // C:\somedir -> C:\somedir\ -> C:\somedir
  226. // C:\somedir\ -> C:\somedir\\ -> C:\somedir
  227. // This way in the tests, we get away without OS specific separators
  228. // in the test configs.
  229. folder.Path = filepath.Dir(folder.Path + string(filepath.Separator))
  230. if folder.ID == "" {
  231. folder.ID = "default"
  232. }
  233. if seen, ok := seenFolders[folder.ID]; ok {
  234. l.Warnf("Multiple folders with ID %q; disabling", folder.ID)
  235. seen.Invalid = "duplicate folder ID"
  236. if seen.ID == folder.ID {
  237. uniqueCounter++
  238. seen.ID = fmt.Sprintf("%s~%d", folder.ID, uniqueCounter)
  239. }
  240. folder.Invalid = "duplicate folder ID"
  241. uniqueCounter++
  242. folder.ID = fmt.Sprintf("%s~%d", folder.ID, uniqueCounter)
  243. } else {
  244. seenFolders[folder.ID] = folder
  245. }
  246. }
  247. if cfg.Options.Deprecated_URDeclined {
  248. cfg.Options.URAccepted = -1
  249. cfg.Options.URUniqueID = ""
  250. }
  251. cfg.Options.Deprecated_URDeclined = false
  252. cfg.Options.Deprecated_UREnabled = false
  253. // Upgrade configuration versions as appropriate
  254. if cfg.Version == 1 {
  255. convertV1V2(cfg)
  256. }
  257. if cfg.Version == 2 {
  258. convertV2V3(cfg)
  259. }
  260. if cfg.Version == 3 {
  261. convertV3V4(cfg)
  262. }
  263. if cfg.Version == 4 {
  264. convertV4V5(cfg)
  265. }
  266. if cfg.Version == 5 {
  267. convertV5V6(cfg)
  268. }
  269. if cfg.Version == 6 {
  270. convertV6V7(cfg)
  271. }
  272. if cfg.Version == 7 {
  273. convertV7V8(cfg)
  274. }
  275. if cfg.Version == 8 {
  276. convertV8V9(cfg)
  277. }
  278. // Hash old cleartext passwords
  279. if len(cfg.GUI.Password) > 0 && cfg.GUI.Password[0] != '$' {
  280. hash, err := bcrypt.GenerateFromPassword([]byte(cfg.GUI.Password), 0)
  281. if err != nil {
  282. l.Warnln("bcrypting password:", err)
  283. } else {
  284. cfg.GUI.Password = string(hash)
  285. }
  286. }
  287. // Build a list of available devices
  288. existingDevices := make(map[protocol.DeviceID]bool)
  289. for _, device := range cfg.Devices {
  290. existingDevices[device.DeviceID] = true
  291. }
  292. // Ensure this device is present in the config
  293. if !existingDevices[myID] {
  294. myName, _ := os.Hostname()
  295. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  296. DeviceID: myID,
  297. Name: myName,
  298. })
  299. existingDevices[myID] = true
  300. }
  301. sort.Sort(DeviceConfigurationList(cfg.Devices))
  302. // Ensure that any loose devices are not present in the wrong places
  303. // Ensure that there are no duplicate devices
  304. // Ensure that puller settings are sane
  305. for i := range cfg.Folders {
  306. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  307. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  308. cfg.Folders[i].Devices = ensureNoDuplicates(cfg.Folders[i].Devices)
  309. if cfg.Folders[i].Copiers == 0 {
  310. cfg.Folders[i].Copiers = 1
  311. }
  312. if cfg.Folders[i].Pullers == 0 {
  313. cfg.Folders[i].Pullers = 16
  314. }
  315. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  316. }
  317. // An empty address list is equivalent to a single "dynamic" entry
  318. for i := range cfg.Devices {
  319. n := &cfg.Devices[i]
  320. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  321. n.Addresses = []string{"dynamic"}
  322. }
  323. }
  324. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  325. cfg.Options.GlobalAnnServers = uniqueStrings(cfg.Options.GlobalAnnServers)
  326. if cfg.GUI.APIKey == "" {
  327. cfg.GUI.APIKey = randomString(32)
  328. }
  329. }
  330. // ChangeRequiresRestart returns true if updating the configuration requires a
  331. // complete restart.
  332. func ChangeRequiresRestart(from, to Configuration) bool {
  333. // Adding, removing or changing folders requires restart
  334. if !reflect.DeepEqual(from.Folders, to.Folders) {
  335. return true
  336. }
  337. // Removing a device requres restart
  338. toDevs := make(map[protocol.DeviceID]bool, len(from.Devices))
  339. for _, dev := range to.Devices {
  340. toDevs[dev.DeviceID] = true
  341. }
  342. for _, dev := range from.Devices {
  343. if _, ok := toDevs[dev.DeviceID]; !ok {
  344. return true
  345. }
  346. }
  347. // Changing usage reporting to on or off does not require a restart.
  348. to.Options.URAccepted = from.Options.URAccepted
  349. to.Options.URUniqueID = from.Options.URUniqueID
  350. // All of the generic options require restart
  351. if !reflect.DeepEqual(from.Options, to.Options) || !reflect.DeepEqual(from.GUI, to.GUI) {
  352. return true
  353. }
  354. return false
  355. }
  356. func convertV8V9(cfg *Configuration) {
  357. // Compression is interpreted and serialized differently, but no enforced
  358. // changes. Still need a new version number since the compression stuff
  359. // isn't understandable by earlier versions.
  360. cfg.Version = 9
  361. }
  362. func convertV7V8(cfg *Configuration) {
  363. // Add IPv6 announce server
  364. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "udp4://announce.syncthing.net:22026" {
  365. cfg.Options.GlobalAnnServers = append(cfg.Options.GlobalAnnServers, "udp6://announce-v6.syncthing.net:22026")
  366. }
  367. cfg.Version = 8
  368. }
  369. func convertV6V7(cfg *Configuration) {
  370. // Migrate announce server addresses to the new URL based format
  371. for i := range cfg.Options.GlobalAnnServers {
  372. cfg.Options.GlobalAnnServers[i] = "udp4://" + cfg.Options.GlobalAnnServers[i]
  373. }
  374. cfg.Version = 7
  375. }
  376. func convertV5V6(cfg *Configuration) {
  377. // Added ".stfolder" file at folder roots to identify mount issues
  378. // Doesn't affect the config itself, but uses config migrations to identify
  379. // the migration point.
  380. for _, folder := range Wrap("", *cfg).Folders() {
  381. // Best attempt, if it fails, it fails, the user will have to fix
  382. // it up manually, as the repo will not get started.
  383. folder.CreateMarker()
  384. }
  385. cfg.Version = 6
  386. }
  387. func convertV4V5(cfg *Configuration) {
  388. // Renamed a bunch of fields in the structs.
  389. if cfg.Deprecated_Nodes == nil {
  390. cfg.Deprecated_Nodes = []DeviceConfiguration{}
  391. }
  392. if cfg.Deprecated_Repositories == nil {
  393. cfg.Deprecated_Repositories = []FolderConfiguration{}
  394. }
  395. cfg.Devices = cfg.Deprecated_Nodes
  396. cfg.Folders = cfg.Deprecated_Repositories
  397. for i := range cfg.Folders {
  398. cfg.Folders[i].Path = cfg.Folders[i].Deprecated_Directory
  399. cfg.Folders[i].Deprecated_Directory = ""
  400. cfg.Folders[i].Devices = cfg.Folders[i].Deprecated_Nodes
  401. cfg.Folders[i].Deprecated_Nodes = nil
  402. }
  403. cfg.Deprecated_Nodes = nil
  404. cfg.Deprecated_Repositories = nil
  405. cfg.Version = 5
  406. }
  407. func convertV3V4(cfg *Configuration) {
  408. // In previous versions, rescan interval was common for each folder.
  409. // From now, it can be set independently. We have to make sure, that after upgrade
  410. // the individual rescan interval will be defined for every existing folder.
  411. for i := range cfg.Deprecated_Repositories {
  412. cfg.Deprecated_Repositories[i].RescanIntervalS = cfg.Options.Deprecated_RescanIntervalS
  413. }
  414. cfg.Options.Deprecated_RescanIntervalS = 0
  415. // In previous versions, folders held full device configurations.
  416. // Since that's the only place where device configs were in V1, we still have
  417. // to define the deprecated fields to be able to upgrade from V1 to V4.
  418. for i, folder := range cfg.Deprecated_Repositories {
  419. for j := range folder.Deprecated_Nodes {
  420. rncfg := cfg.Deprecated_Repositories[i].Deprecated_Nodes[j]
  421. rncfg.Deprecated_Name = ""
  422. rncfg.Deprecated_Addresses = nil
  423. }
  424. }
  425. cfg.Version = 4
  426. }
  427. func convertV2V3(cfg *Configuration) {
  428. // In previous versions, compression was always on. When upgrading, enable
  429. // compression on all existing new. New devices will get compression on by
  430. // default by the GUI.
  431. for i := range cfg.Deprecated_Nodes {
  432. cfg.Deprecated_Nodes[i].Compression = protocol.CompressMetadata
  433. }
  434. // The global discovery format and port number changed in v0.9. Having the
  435. // default announce server but old port number is guaranteed to be legacy.
  436. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "announce.syncthing.net:22025" {
  437. cfg.Options.GlobalAnnServers = []string{"announce.syncthing.net:22026"}
  438. }
  439. cfg.Version = 3
  440. }
  441. func convertV1V2(cfg *Configuration) {
  442. // Collect the list of devices.
  443. // Replace device configs inside folders with only a reference to the
  444. // device ID. Set all folders to read only if the global read only flag is
  445. // set.
  446. var devices = map[string]FolderDeviceConfiguration{}
  447. for i, folder := range cfg.Deprecated_Repositories {
  448. cfg.Deprecated_Repositories[i].ReadOnly = cfg.Options.Deprecated_ReadOnly
  449. for j, device := range folder.Deprecated_Nodes {
  450. id := device.DeviceID.String()
  451. if _, ok := devices[id]; !ok {
  452. devices[id] = device
  453. }
  454. cfg.Deprecated_Repositories[i].Deprecated_Nodes[j] = FolderDeviceConfiguration{DeviceID: device.DeviceID}
  455. }
  456. }
  457. cfg.Options.Deprecated_ReadOnly = false
  458. // Set and sort the list of devices.
  459. for _, device := range devices {
  460. cfg.Deprecated_Nodes = append(cfg.Deprecated_Nodes, DeviceConfiguration{
  461. DeviceID: device.DeviceID,
  462. Name: device.Deprecated_Name,
  463. Addresses: device.Deprecated_Addresses,
  464. })
  465. }
  466. sort.Sort(DeviceConfigurationList(cfg.Deprecated_Nodes))
  467. // GUI
  468. cfg.GUI.Address = cfg.Options.Deprecated_GUIAddress
  469. cfg.GUI.Enabled = cfg.Options.Deprecated_GUIEnabled
  470. cfg.Options.Deprecated_GUIEnabled = false
  471. cfg.Options.Deprecated_GUIAddress = ""
  472. cfg.Version = 2
  473. }
  474. func setDefaults(data interface{}) error {
  475. s := reflect.ValueOf(data).Elem()
  476. t := s.Type()
  477. for i := 0; i < s.NumField(); i++ {
  478. f := s.Field(i)
  479. tag := t.Field(i).Tag
  480. v := tag.Get("default")
  481. if len(v) > 0 {
  482. switch f.Interface().(type) {
  483. case string:
  484. f.SetString(v)
  485. case int:
  486. i, err := strconv.ParseInt(v, 10, 64)
  487. if err != nil {
  488. return err
  489. }
  490. f.SetInt(i)
  491. case bool:
  492. f.SetBool(v == "true")
  493. case []string:
  494. // We don't do anything with string slices here. Any default
  495. // we set will be appended to by the XML decoder, so we fill
  496. // those after decoding.
  497. default:
  498. panic(f.Type())
  499. }
  500. }
  501. }
  502. return nil
  503. }
  504. // fillNilSlices sets default value on slices that are still nil.
  505. func fillNilSlices(data interface{}) error {
  506. s := reflect.ValueOf(data).Elem()
  507. t := s.Type()
  508. for i := 0; i < s.NumField(); i++ {
  509. f := s.Field(i)
  510. tag := t.Field(i).Tag
  511. v := tag.Get("default")
  512. if len(v) > 0 {
  513. switch f.Interface().(type) {
  514. case []string:
  515. if f.IsNil() {
  516. // Treat the default as a comma separated slice
  517. vs := strings.Split(v, ",")
  518. for i := range vs {
  519. vs[i] = strings.TrimSpace(vs[i])
  520. }
  521. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), len(vs), len(vs))
  522. for i, v := range vs {
  523. rv.Index(i).SetString(v)
  524. }
  525. f.Set(rv)
  526. }
  527. }
  528. }
  529. }
  530. return nil
  531. }
  532. func uniqueStrings(ss []string) []string {
  533. var m = make(map[string]bool, len(ss))
  534. for _, s := range ss {
  535. m[s] = true
  536. }
  537. var us = make([]string, 0, len(m))
  538. for k := range m {
  539. us = append(us, k)
  540. }
  541. sort.Strings(us)
  542. return us
  543. }
  544. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  545. for _, device := range devices {
  546. if device.DeviceID.Equals(myID) {
  547. return devices
  548. }
  549. }
  550. devices = append(devices, FolderDeviceConfiguration{
  551. DeviceID: myID,
  552. })
  553. return devices
  554. }
  555. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  556. count := len(devices)
  557. i := 0
  558. loop:
  559. for i < count {
  560. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  561. devices[i] = devices[count-1]
  562. count--
  563. continue loop
  564. }
  565. i++
  566. }
  567. return devices[0:count]
  568. }
  569. func ensureNoDuplicates(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  570. count := len(devices)
  571. i := 0
  572. seenDevices := make(map[protocol.DeviceID]bool)
  573. loop:
  574. for i < count {
  575. id := devices[i].DeviceID
  576. if _, ok := seenDevices[id]; ok {
  577. devices[i] = devices[count-1]
  578. count--
  579. continue loop
  580. }
  581. seenDevices[id] = true
  582. i++
  583. }
  584. return devices[0:count]
  585. }
  586. type DeviceConfigurationList []DeviceConfiguration
  587. func (l DeviceConfigurationList) Less(a, b int) bool {
  588. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  589. }
  590. func (l DeviceConfigurationList) Swap(a, b int) {
  591. l[a], l[b] = l[b], l[a]
  592. }
  593. func (l DeviceConfigurationList) Len() int {
  594. return len(l)
  595. }
  596. type FolderDeviceConfigurationList []FolderDeviceConfiguration
  597. func (l FolderDeviceConfigurationList) Less(a, b int) bool {
  598. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  599. }
  600. func (l FolderDeviceConfigurationList) Swap(a, b int) {
  601. l[a], l[b] = l[b], l[a]
  602. }
  603. func (l FolderDeviceConfigurationList) Len() int {
  604. return len(l)
  605. }
  606. // randomCharset contains the characters that can make up a randomString().
  607. const randomCharset = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
  608. // randomString returns a string of random characters (taken from
  609. // randomCharset) of the specified length.
  610. func randomString(l int) string {
  611. bs := make([]byte, l)
  612. for i := range bs {
  613. bs[i] = randomCharset[rand.Intn(len(randomCharset))]
  614. }
  615. return string(bs)
  616. }