config.go 17 KB

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