config.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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/protocol"
  29. "github.com/syncthing/syncthing/internal/osutil"
  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. // The reason it's done like this:
  222. // C: -> C:\ -> C:\ (issue that this is trying to fix)
  223. // C:\somedir -> C:\somedir\ -> C:\somedir
  224. // C:\somedir\ -> C:\somedir\\ -> C:\somedir
  225. // This way in the tests, we get away without OS specific separators
  226. // in the test configs.
  227. folder.Path = filepath.Dir(folder.Path + string(filepath.Separator))
  228. if folder.ID == "" {
  229. folder.ID = "default"
  230. }
  231. if seen, ok := seenFolders[folder.ID]; ok {
  232. l.Warnf("Multiple folders with ID %q; disabling", folder.ID)
  233. seen.Invalid = "duplicate folder ID"
  234. if seen.ID == folder.ID {
  235. uniqueCounter++
  236. seen.ID = fmt.Sprintf("%s~%d", folder.ID, uniqueCounter)
  237. }
  238. folder.Invalid = "duplicate folder ID"
  239. uniqueCounter++
  240. folder.ID = fmt.Sprintf("%s~%d", folder.ID, uniqueCounter)
  241. } else {
  242. seenFolders[folder.ID] = folder
  243. }
  244. }
  245. if cfg.Options.Deprecated_URDeclined {
  246. cfg.Options.URAccepted = -1
  247. cfg.Options.URUniqueID = ""
  248. }
  249. cfg.Options.Deprecated_URDeclined = false
  250. cfg.Options.Deprecated_UREnabled = false
  251. // Upgrade to v1 configuration if appropriate
  252. if cfg.Version == 1 {
  253. convertV1V2(cfg)
  254. }
  255. // Upgrade to v3 configuration if appropriate
  256. if cfg.Version == 2 {
  257. convertV2V3(cfg)
  258. }
  259. // Upgrade to v4 configuration if appropriate
  260. if cfg.Version == 3 {
  261. convertV3V4(cfg)
  262. }
  263. // Upgrade to v5 configuration if appropriate
  264. if cfg.Version == 4 {
  265. convertV4V5(cfg)
  266. }
  267. // Upgrade to v6 configuration if appropriate
  268. if cfg.Version == 5 {
  269. convertV5V6(cfg)
  270. }
  271. // Upgrade to v7 configuration if appropriate
  272. if cfg.Version == 6 {
  273. convertV6V7(cfg)
  274. }
  275. // Hash old cleartext passwords
  276. if len(cfg.GUI.Password) > 0 && cfg.GUI.Password[0] != '$' {
  277. hash, err := bcrypt.GenerateFromPassword([]byte(cfg.GUI.Password), 0)
  278. if err != nil {
  279. l.Warnln("bcrypting password:", err)
  280. } else {
  281. cfg.GUI.Password = string(hash)
  282. }
  283. }
  284. // Build a list of available devices
  285. existingDevices := make(map[protocol.DeviceID]bool)
  286. for _, device := range cfg.Devices {
  287. existingDevices[device.DeviceID] = true
  288. }
  289. // Ensure this device is present in the config
  290. if !existingDevices[myID] {
  291. myName, _ := os.Hostname()
  292. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  293. DeviceID: myID,
  294. Name: myName,
  295. })
  296. existingDevices[myID] = true
  297. }
  298. sort.Sort(DeviceConfigurationList(cfg.Devices))
  299. // Ensure that any loose devices are not present in the wrong places
  300. // Ensure that there are no duplicate devices
  301. // Ensure that puller settings are sane
  302. for i := range cfg.Folders {
  303. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  304. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  305. cfg.Folders[i].Devices = ensureNoDuplicates(cfg.Folders[i].Devices)
  306. if cfg.Folders[i].Copiers == 0 {
  307. cfg.Folders[i].Copiers = 1
  308. }
  309. if cfg.Folders[i].Pullers == 0 {
  310. cfg.Folders[i].Pullers = 16
  311. }
  312. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  313. }
  314. // An empty address list is equivalent to a single "dynamic" entry
  315. for i := range cfg.Devices {
  316. n := &cfg.Devices[i]
  317. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  318. n.Addresses = []string{"dynamic"}
  319. }
  320. }
  321. cfg.Options.ListenAddress = uniqueStrings(cfg.Options.ListenAddress)
  322. cfg.Options.GlobalAnnServers = uniqueStrings(cfg.Options.GlobalAnnServers)
  323. if cfg.GUI.APIKey == "" {
  324. cfg.GUI.APIKey = randomString(32)
  325. }
  326. }
  327. // ChangeRequiresRestart returns true if updating the configuration requires a
  328. // complete restart.
  329. func ChangeRequiresRestart(from, to Configuration) bool {
  330. // Adding, removing or changing folders requires restart
  331. if !reflect.DeepEqual(from.Folders, to.Folders) {
  332. return true
  333. }
  334. // Removing a device requres restart
  335. toDevs := make(map[protocol.DeviceID]bool, len(from.Devices))
  336. for _, dev := range to.Devices {
  337. toDevs[dev.DeviceID] = true
  338. }
  339. for _, dev := range from.Devices {
  340. if _, ok := toDevs[dev.DeviceID]; !ok {
  341. return true
  342. }
  343. }
  344. // Changing usage reporting to on or off does not require a restart.
  345. to.Options.URAccepted = from.Options.URAccepted
  346. to.Options.URUniqueID = from.Options.URUniqueID
  347. // All of the generic options require restart
  348. if !reflect.DeepEqual(from.Options, to.Options) || !reflect.DeepEqual(from.GUI, to.GUI) {
  349. return true
  350. }
  351. return false
  352. }
  353. func convertV6V7(cfg *Configuration) {
  354. // Migrate announce server addresses to the new URL based format
  355. for i := range cfg.Options.GlobalAnnServers {
  356. cfg.Options.GlobalAnnServers[i] = "udp4://" + cfg.Options.GlobalAnnServers[i]
  357. }
  358. cfg.Version = 7
  359. }
  360. func convertV5V6(cfg *Configuration) {
  361. // Added ".stfolder" file at folder roots to identify mount issues
  362. // Doesn't affect the config itself, but uses config migrations to identify
  363. // the migration point.
  364. for _, folder := range Wrap("", *cfg).Folders() {
  365. // Best attempt, if it fails, it fails, the user will have to fix
  366. // it up manually, as the repo will not get started.
  367. folder.CreateMarker()
  368. }
  369. cfg.Version = 6
  370. }
  371. func convertV4V5(cfg *Configuration) {
  372. // Renamed a bunch of fields in the structs.
  373. if cfg.Deprecated_Nodes == nil {
  374. cfg.Deprecated_Nodes = []DeviceConfiguration{}
  375. }
  376. if cfg.Deprecated_Repositories == nil {
  377. cfg.Deprecated_Repositories = []FolderConfiguration{}
  378. }
  379. cfg.Devices = cfg.Deprecated_Nodes
  380. cfg.Folders = cfg.Deprecated_Repositories
  381. for i := range cfg.Folders {
  382. cfg.Folders[i].Path = cfg.Folders[i].Deprecated_Directory
  383. cfg.Folders[i].Deprecated_Directory = ""
  384. cfg.Folders[i].Devices = cfg.Folders[i].Deprecated_Nodes
  385. cfg.Folders[i].Deprecated_Nodes = nil
  386. }
  387. cfg.Deprecated_Nodes = nil
  388. cfg.Deprecated_Repositories = nil
  389. cfg.Version = 5
  390. }
  391. func convertV3V4(cfg *Configuration) {
  392. // In previous versions, rescan interval was common for each folder.
  393. // From now, it can be set independently. We have to make sure, that after upgrade
  394. // the individual rescan interval will be defined for every existing folder.
  395. for i := range cfg.Deprecated_Repositories {
  396. cfg.Deprecated_Repositories[i].RescanIntervalS = cfg.Options.Deprecated_RescanIntervalS
  397. }
  398. cfg.Options.Deprecated_RescanIntervalS = 0
  399. // In previous versions, folders held full device configurations.
  400. // Since that's the only place where device configs were in V1, we still have
  401. // to define the deprecated fields to be able to upgrade from V1 to V4.
  402. for i, folder := range cfg.Deprecated_Repositories {
  403. for j := range folder.Deprecated_Nodes {
  404. rncfg := cfg.Deprecated_Repositories[i].Deprecated_Nodes[j]
  405. rncfg.Deprecated_Name = ""
  406. rncfg.Deprecated_Addresses = nil
  407. }
  408. }
  409. cfg.Version = 4
  410. }
  411. func convertV2V3(cfg *Configuration) {
  412. // In previous versions, compression was always on. When upgrading, enable
  413. // compression on all existing new. New devices will get compression on by
  414. // default by the GUI.
  415. for i := range cfg.Deprecated_Nodes {
  416. cfg.Deprecated_Nodes[i].Compression = true
  417. }
  418. // The global discovery format and port number changed in v0.9. Having the
  419. // default announce server but old port number is guaranteed to be legacy.
  420. if len(cfg.Options.GlobalAnnServers) == 1 && cfg.Options.GlobalAnnServers[0] == "announce.syncthing.net:22025" {
  421. cfg.Options.GlobalAnnServers = []string{"announce.syncthing.net:22026"}
  422. }
  423. cfg.Version = 3
  424. }
  425. func convertV1V2(cfg *Configuration) {
  426. // Collect the list of devices.
  427. // Replace device configs inside folders with only a reference to the
  428. // device ID. Set all folders to read only if the global read only flag is
  429. // set.
  430. var devices = map[string]FolderDeviceConfiguration{}
  431. for i, folder := range cfg.Deprecated_Repositories {
  432. cfg.Deprecated_Repositories[i].ReadOnly = cfg.Options.Deprecated_ReadOnly
  433. for j, device := range folder.Deprecated_Nodes {
  434. id := device.DeviceID.String()
  435. if _, ok := devices[id]; !ok {
  436. devices[id] = device
  437. }
  438. cfg.Deprecated_Repositories[i].Deprecated_Nodes[j] = FolderDeviceConfiguration{DeviceID: device.DeviceID}
  439. }
  440. }
  441. cfg.Options.Deprecated_ReadOnly = false
  442. // Set and sort the list of devices.
  443. for _, device := range devices {
  444. cfg.Deprecated_Nodes = append(cfg.Deprecated_Nodes, DeviceConfiguration{
  445. DeviceID: device.DeviceID,
  446. Name: device.Deprecated_Name,
  447. Addresses: device.Deprecated_Addresses,
  448. })
  449. }
  450. sort.Sort(DeviceConfigurationList(cfg.Deprecated_Nodes))
  451. // GUI
  452. cfg.GUI.Address = cfg.Options.Deprecated_GUIAddress
  453. cfg.GUI.Enabled = cfg.Options.Deprecated_GUIEnabled
  454. cfg.Options.Deprecated_GUIEnabled = false
  455. cfg.Options.Deprecated_GUIAddress = ""
  456. cfg.Version = 2
  457. }
  458. func setDefaults(data interface{}) error {
  459. s := reflect.ValueOf(data).Elem()
  460. t := s.Type()
  461. for i := 0; i < s.NumField(); i++ {
  462. f := s.Field(i)
  463. tag := t.Field(i).Tag
  464. v := tag.Get("default")
  465. if len(v) > 0 {
  466. switch f.Interface().(type) {
  467. case string:
  468. f.SetString(v)
  469. case int:
  470. i, err := strconv.ParseInt(v, 10, 64)
  471. if err != nil {
  472. return err
  473. }
  474. f.SetInt(i)
  475. case bool:
  476. f.SetBool(v == "true")
  477. case []string:
  478. // We don't do anything with string slices here. Any default
  479. // we set will be appended to by the XML decoder, so we fill
  480. // those after decoding.
  481. default:
  482. panic(f.Type())
  483. }
  484. }
  485. }
  486. return nil
  487. }
  488. // fillNilSlices sets default value on slices that are still nil.
  489. func fillNilSlices(data interface{}) error {
  490. s := reflect.ValueOf(data).Elem()
  491. t := s.Type()
  492. for i := 0; i < s.NumField(); i++ {
  493. f := s.Field(i)
  494. tag := t.Field(i).Tag
  495. v := tag.Get("default")
  496. if len(v) > 0 {
  497. switch f.Interface().(type) {
  498. case []string:
  499. if f.IsNil() {
  500. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), 1, 1)
  501. rv.Index(0).SetString(v)
  502. f.Set(rv)
  503. }
  504. }
  505. }
  506. }
  507. return nil
  508. }
  509. func uniqueStrings(ss []string) []string {
  510. var m = make(map[string]bool, len(ss))
  511. for _, s := range ss {
  512. m[s] = true
  513. }
  514. var us = make([]string, 0, len(m))
  515. for k := range m {
  516. us = append(us, k)
  517. }
  518. return us
  519. }
  520. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  521. for _, device := range devices {
  522. if device.DeviceID.Equals(myID) {
  523. return devices
  524. }
  525. }
  526. devices = append(devices, FolderDeviceConfiguration{
  527. DeviceID: myID,
  528. })
  529. return devices
  530. }
  531. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  532. count := len(devices)
  533. i := 0
  534. loop:
  535. for i < count {
  536. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  537. devices[i] = devices[count-1]
  538. count--
  539. continue loop
  540. }
  541. i++
  542. }
  543. return devices[0:count]
  544. }
  545. func ensureNoDuplicates(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  546. count := len(devices)
  547. i := 0
  548. seenDevices := make(map[protocol.DeviceID]bool)
  549. loop:
  550. for i < count {
  551. id := devices[i].DeviceID
  552. if _, ok := seenDevices[id]; ok {
  553. devices[i] = devices[count-1]
  554. count--
  555. continue loop
  556. }
  557. seenDevices[id] = true
  558. i++
  559. }
  560. return devices[0:count]
  561. }
  562. type DeviceConfigurationList []DeviceConfiguration
  563. func (l DeviceConfigurationList) Less(a, b int) bool {
  564. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  565. }
  566. func (l DeviceConfigurationList) Swap(a, b int) {
  567. l[a], l[b] = l[b], l[a]
  568. }
  569. func (l DeviceConfigurationList) Len() int {
  570. return len(l)
  571. }
  572. type FolderDeviceConfigurationList []FolderDeviceConfiguration
  573. func (l FolderDeviceConfigurationList) Less(a, b int) bool {
  574. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  575. }
  576. func (l FolderDeviceConfigurationList) Swap(a, b int) {
  577. l[a], l[b] = l[b], l[a]
  578. }
  579. func (l FolderDeviceConfigurationList) Len() int {
  580. return len(l)
  581. }
  582. // randomCharset contains the characters that can make up a randomString().
  583. const randomCharset = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
  584. // randomString returns a string of random characters (taken from
  585. // randomCharset) of the specified length.
  586. func randomString(l int) string {
  587. bs := make([]byte, l)
  588. for i := range bs {
  589. bs[i] = randomCharset[rand.Intn(len(randomCharset))]
  590. }
  591. return string(bs)
  592. }