config.go 20 KB

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