config.go 21 KB

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