config.go 17 KB

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