config.go 20 KB

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