config.go 20 KB

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