config.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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. 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.
  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. if cfg.Folders[i].Finishers == 0 {
  306. cfg.Folders[i].Finishers = 1
  307. }
  308. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  309. }
  310. // An empty address list is equivalent to a single "dynamic" entry
  311. for i := range cfg.Devices {
  312. n := &cfg.Devices[i]
  313. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  314. n.Addresses = []string{"dynamic"}
  315. }
  316. }
  317. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  318. cfg.Options.GlobalAnnServers = uniqueStrings(cfg.Options.GlobalAnnServers)
  319. if cfg.GUI.APIKey == "" {
  320. cfg.GUI.APIKey = randomString(32)
  321. }
  322. }
  323. // ChangeRequiresRestart returns true if updating the configuration requires a
  324. // complete restart.
  325. func ChangeRequiresRestart(from, to Configuration) bool {
  326. // Adding, removing or changing folders requires restart
  327. if !reflect.DeepEqual(from.Folders, to.Folders) {
  328. return true
  329. }
  330. // Removing a device requres restart
  331. toDevs := make(map[protocol.DeviceID]bool, len(from.Devices))
  332. for _, dev := range to.Devices {
  333. toDevs[dev.DeviceID] = true
  334. }
  335. for _, dev := range from.Devices {
  336. if _, ok := toDevs[dev.DeviceID]; !ok {
  337. return true
  338. }
  339. }
  340. // Changing usage reporting to on or off does not require a restart.
  341. to.Options.URAccepted = from.Options.URAccepted
  342. to.Options.URUniqueID = from.Options.URUniqueID
  343. // All of the generic options require restart
  344. if !reflect.DeepEqual(from.Options, to.Options) || !reflect.DeepEqual(from.GUI, to.GUI) {
  345. return true
  346. }
  347. return false
  348. }
  349. func convertV6V7(cfg *Configuration) {
  350. // Migrate announce server addresses to the new URL based format
  351. for i := range cfg.Options.GlobalAnnServers {
  352. cfg.Options.GlobalAnnServers[i] = "udp4://" + cfg.Options.GlobalAnnServers[i]
  353. }
  354. cfg.Version = 7
  355. }
  356. func convertV5V6(cfg *Configuration) {
  357. // Added ".stfolder" file at folder roots to identify mount issues
  358. // Doesn't affect the config itself, but uses config migrations to identify
  359. // the migration point.
  360. for _, folder := range Wrap("", *cfg).Folders() {
  361. // Best attempt, if it fails, it fails, the user will have to fix
  362. // it up manually, as the repo will not get started.
  363. folder.CreateMarker()
  364. }
  365. cfg.Version = 6
  366. }
  367. func convertV4V5(cfg *Configuration) {
  368. // Renamed a bunch of fields in the structs.
  369. if cfg.Deprecated_Nodes == nil {
  370. cfg.Deprecated_Nodes = []DeviceConfiguration{}
  371. }
  372. if cfg.Deprecated_Repositories == nil {
  373. cfg.Deprecated_Repositories = []FolderConfiguration{}
  374. }
  375. cfg.Devices = cfg.Deprecated_Nodes
  376. cfg.Folders = cfg.Deprecated_Repositories
  377. for i := range cfg.Folders {
  378. cfg.Folders[i].Path = cfg.Folders[i].Deprecated_Directory
  379. cfg.Folders[i].Deprecated_Directory = ""
  380. cfg.Folders[i].Devices = cfg.Folders[i].Deprecated_Nodes
  381. cfg.Folders[i].Deprecated_Nodes = nil
  382. }
  383. cfg.Deprecated_Nodes = nil
  384. cfg.Deprecated_Repositories = nil
  385. cfg.Version = 5
  386. }
  387. func convertV3V4(cfg *Configuration) {
  388. // In previous versions, rescan interval was common for each folder.
  389. // From now, it can be set independently. We have to make sure, that after upgrade
  390. // the individual rescan interval will be defined for every existing folder.
  391. for i := range cfg.Deprecated_Repositories {
  392. cfg.Deprecated_Repositories[i].RescanIntervalS = cfg.Options.Deprecated_RescanIntervalS
  393. }
  394. cfg.Options.Deprecated_RescanIntervalS = 0
  395. // In previous versions, folders held full device configurations.
  396. // Since that's the only place where device configs were in V1, we still have
  397. // to define the deprecated fields to be able to upgrade from V1 to V4.
  398. for i, folder := range cfg.Deprecated_Repositories {
  399. for j := range folder.Deprecated_Nodes {
  400. rncfg := cfg.Deprecated_Repositories[i].Deprecated_Nodes[j]
  401. rncfg.Deprecated_Name = ""
  402. rncfg.Deprecated_Addresses = nil
  403. }
  404. }
  405. cfg.Version = 4
  406. }
  407. func convertV2V3(cfg *Configuration) {
  408. // In previous versions, compression was always on. When upgrading, enable
  409. // compression on all existing new. New devices will get compression on by
  410. // default by the GUI.
  411. for i := range cfg.Deprecated_Nodes {
  412. cfg.Deprecated_Nodes[i].Compression = true
  413. }
  414. // The global discovery format and port number changed in v0.9. Having the
  415. // default announce server but old port number is guaranteed to be legacy.
  416. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "announce.syncthing.net:22025" {
  417. cfg.Options.GlobalAnnServers = []string{"announce.syncthing.net:22026"}
  418. }
  419. cfg.Version = 3
  420. }
  421. func convertV1V2(cfg *Configuration) {
  422. // Collect the list of devices.
  423. // Replace device configs inside folders with only a reference to the
  424. // device ID. Set all folders to read only if the global read only flag is
  425. // set.
  426. var devices = map[string]FolderDeviceConfiguration{}
  427. for i, folder := range cfg.Deprecated_Repositories {
  428. cfg.Deprecated_Repositories[i].ReadOnly = cfg.Options.Deprecated_ReadOnly
  429. for j, device := range folder.Deprecated_Nodes {
  430. id := device.DeviceID.String()
  431. if _, ok := devices[id]; !ok {
  432. devices[id] = device
  433. }
  434. cfg.Deprecated_Repositories[i].Deprecated_Nodes[j] = FolderDeviceConfiguration{DeviceID: device.DeviceID}
  435. }
  436. }
  437. cfg.Options.Deprecated_ReadOnly = false
  438. // Set and sort the list of devices.
  439. for _, device := range devices {
  440. cfg.Deprecated_Nodes = append(cfg.Deprecated_Nodes, DeviceConfiguration{
  441. DeviceID: device.DeviceID,
  442. Name: device.Deprecated_Name,
  443. Addresses: device.Deprecated_Addresses,
  444. })
  445. }
  446. sort.Sort(DeviceConfigurationList(cfg.Deprecated_Nodes))
  447. // GUI
  448. cfg.GUI.Address = cfg.Options.Deprecated_GUIAddress
  449. cfg.GUI.Enabled = cfg.Options.Deprecated_GUIEnabled
  450. cfg.Options.Deprecated_GUIEnabled = false
  451. cfg.Options.Deprecated_GUIAddress = ""
  452. cfg.Version = 2
  453. }
  454. func setDefaults(data interface{}) error {
  455. s := reflect.ValueOf(data).Elem()
  456. t := s.Type()
  457. for i := 0; i < s.NumField(); i++ {
  458. f := s.Field(i)
  459. tag := t.Field(i).Tag
  460. v := tag.Get("default")
  461. if len(v) > 0 {
  462. switch f.Interface().(type) {
  463. case string:
  464. f.SetString(v)
  465. case int:
  466. i, err := strconv.ParseInt(v, 10, 64)
  467. if err != nil {
  468. return err
  469. }
  470. f.SetInt(i)
  471. case bool:
  472. f.SetBool(v == "true")
  473. case []string:
  474. // We don't do anything with string slices here. Any default
  475. // we set will be appended to by the XML decoder, so we fill
  476. // those after decoding.
  477. default:
  478. panic(f.Type())
  479. }
  480. }
  481. }
  482. return nil
  483. }
  484. // fillNilSlices sets default value on slices that are still nil.
  485. func fillNilSlices(data interface{}) error {
  486. s := reflect.ValueOf(data).Elem()
  487. t := s.Type()
  488. for i := 0; i < s.NumField(); i++ {
  489. f := s.Field(i)
  490. tag := t.Field(i).Tag
  491. v := tag.Get("default")
  492. if len(v) > 0 {
  493. switch f.Interface().(type) {
  494. case []string:
  495. if f.IsNil() {
  496. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), 1, 1)
  497. rv.Index(0).SetString(v)
  498. f.Set(rv)
  499. }
  500. }
  501. }
  502. }
  503. return nil
  504. }
  505. func uniqueStrings(ss []string) []string {
  506. var m = make(map[string]bool, len(ss))
  507. for _, s := range ss {
  508. m[s] = true
  509. }
  510. var us = make([]string, 0, len(m))
  511. for k := range m {
  512. us = append(us, k)
  513. }
  514. return us
  515. }
  516. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  517. for _, device := range devices {
  518. if device.DeviceID.Equals(myID) {
  519. return devices
  520. }
  521. }
  522. devices = append(devices, FolderDeviceConfiguration{
  523. DeviceID: myID,
  524. })
  525. return devices
  526. }
  527. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  528. count := len(devices)
  529. i := 0
  530. loop:
  531. for i < count {
  532. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  533. devices[i] = devices[count-1]
  534. count--
  535. continue loop
  536. }
  537. i++
  538. }
  539. return devices[0:count]
  540. }
  541. func ensureNoDuplicates(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  542. count := len(devices)
  543. i := 0
  544. seenDevices := make(map[protocol.DeviceID]bool)
  545. loop:
  546. for i < count {
  547. id := devices[i].DeviceID
  548. if _, ok := seenDevices[id]; ok {
  549. devices[i] = devices[count-1]
  550. count--
  551. continue loop
  552. }
  553. seenDevices[id] = true
  554. i++
  555. }
  556. return devices[0:count]
  557. }
  558. type DeviceConfigurationList []DeviceConfiguration
  559. func (l DeviceConfigurationList) Less(a, b int) bool {
  560. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  561. }
  562. func (l DeviceConfigurationList) Swap(a, b int) {
  563. l[a], l[b] = l[b], l[a]
  564. }
  565. func (l DeviceConfigurationList) Len() int {
  566. return len(l)
  567. }
  568. type FolderDeviceConfigurationList []FolderDeviceConfiguration
  569. func (l FolderDeviceConfigurationList) Less(a, b int) bool {
  570. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  571. }
  572. func (l FolderDeviceConfigurationList) Swap(a, b int) {
  573. l[a], l[b] = l[b], l[a]
  574. }
  575. func (l FolderDeviceConfigurationList) Len() int {
  576. return len(l)
  577. }
  578. // randomCharset contains the characters that can make up a randomString().
  579. const randomCharset = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
  580. // randomString returns a string of random characters (taken from
  581. // randomCharset) of the specified length.
  582. func randomString(l int) string {
  583. bs := make([]byte, l)
  584. for i := range bs {
  585. bs[i] = randomCharset[rand.Intn(len(randomCharset))]
  586. }
  587. return string(bs)
  588. }