config.go 19 KB

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