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. 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. Invalid string `xml:"-"` // Set at runtime when there is an error, not saved
  48. Versioning VersioningConfiguration `xml:"versioning"`
  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. existingDevices[myID] = true
  233. for _, device := range cfg.Devices {
  234. existingDevices[device.DeviceID] = true
  235. }
  236. // Ensure this device is present in all relevant places
  237. myIDExists := false
  238. for _, dev := range cfg.Devices {
  239. if dev.DeviceID == myID {
  240. myIDExists = true
  241. break
  242. }
  243. }
  244. if !myIDExists {
  245. myName, _ := os.Hostname()
  246. cfg.Devices = append(cfg.Devices, DeviceConfiguration{
  247. DeviceID: myID,
  248. Name: myName,
  249. })
  250. }
  251. sort.Sort(DeviceConfigurationList(cfg.Devices))
  252. // Ensure that any loose devices are not present in the wrong places
  253. // Ensure that there are no duplicate devices
  254. for i := range cfg.Folders {
  255. cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
  256. cfg.Folders[i].Devices = ensureExistingDevices(cfg.Folders[i].Devices, existingDevices)
  257. cfg.Folders[i].Devices = ensureNoDuplicates(cfg.Folders[i].Devices)
  258. sort.Sort(FolderDeviceConfigurationList(cfg.Folders[i].Devices))
  259. }
  260. // An empty address list is equivalent to a single "dynamic" entry
  261. for i := range cfg.Devices {
  262. n := &cfg.Devices[i]
  263. if len(n.Addresses) == 0 || len(n.Addresses) == 1 && n.Addresses[0] == "" {
  264. n.Addresses = []string{"dynamic"}
  265. }
  266. }
  267. }
  268. // ChangeRequiresRestart returns true if updating the configuration requires a
  269. // complete restart.
  270. func ChangeRequiresRestart(from, to Configuration) bool {
  271. // Adding, removing or changing folders requires restart
  272. if !reflect.DeepEqual(from.Folders, to.Folders) {
  273. return true
  274. }
  275. // Removing a device requres restart
  276. toDevs := make(map[protocol.DeviceID]bool, len(from.Devices))
  277. for _, dev := range to.Devices {
  278. toDevs[dev.DeviceID] = true
  279. }
  280. for _, dev := range from.Devices {
  281. if _, ok := toDevs[dev.DeviceID]; !ok {
  282. return true
  283. }
  284. }
  285. // All of the generic options require restart
  286. if !reflect.DeepEqual(from.Options, to.Options) || !reflect.DeepEqual(from.GUI, to.GUI) {
  287. return true
  288. }
  289. return false
  290. }
  291. func convertV4V5(cfg *Configuration) {
  292. // Renamed a bunch of fields in the structs.
  293. if cfg.Deprecated_Nodes == nil {
  294. cfg.Deprecated_Nodes = []DeviceConfiguration{}
  295. }
  296. if cfg.Deprecated_Repositories == nil {
  297. cfg.Deprecated_Repositories = []FolderConfiguration{}
  298. }
  299. cfg.Devices = cfg.Deprecated_Nodes
  300. cfg.Folders = cfg.Deprecated_Repositories
  301. for i := range cfg.Folders {
  302. cfg.Folders[i].Path = cfg.Folders[i].Deprecated_Directory
  303. cfg.Folders[i].Deprecated_Directory = ""
  304. cfg.Folders[i].Devices = cfg.Folders[i].Deprecated_Nodes
  305. cfg.Folders[i].Deprecated_Nodes = nil
  306. }
  307. cfg.Deprecated_Nodes = nil
  308. cfg.Deprecated_Repositories = nil
  309. cfg.Version = 5
  310. }
  311. func convertV3V4(cfg *Configuration) {
  312. // In previous versions, rescan interval was common for each folder.
  313. // From now, it can be set independently. We have to make sure, that after upgrade
  314. // the individual rescan interval will be defined for every existing folder.
  315. for i := range cfg.Deprecated_Repositories {
  316. cfg.Deprecated_Repositories[i].RescanIntervalS = cfg.Options.Deprecated_RescanIntervalS
  317. }
  318. cfg.Options.Deprecated_RescanIntervalS = 0
  319. // In previous versions, folders held full device configurations.
  320. // Since that's the only place where device configs were in V1, we still have
  321. // to define the deprecated fields to be able to upgrade from V1 to V4.
  322. for i, folder := range cfg.Deprecated_Repositories {
  323. for j := range folder.Deprecated_Nodes {
  324. rncfg := cfg.Deprecated_Repositories[i].Deprecated_Nodes[j]
  325. rncfg.Deprecated_Name = ""
  326. rncfg.Deprecated_Addresses = nil
  327. }
  328. }
  329. cfg.Version = 4
  330. }
  331. func convertV2V3(cfg *Configuration) {
  332. // In previous versions, compression was always on. When upgrading, enable
  333. // compression on all existing new. New devices will get compression on by
  334. // default by the GUI.
  335. for i := range cfg.Deprecated_Nodes {
  336. cfg.Deprecated_Nodes[i].Compression = true
  337. }
  338. // The global discovery format and port number changed in v0.9. Having the
  339. // default announce server but old port number is guaranteed to be legacy.
  340. if cfg.Options.GlobalAnnServer == "announce.syncthing.net:22025" {
  341. cfg.Options.GlobalAnnServer = "announce.syncthing.net:22026"
  342. }
  343. cfg.Version = 3
  344. }
  345. func convertV1V2(cfg *Configuration) {
  346. // Collect the list of devices.
  347. // Replace device configs inside folders with only a reference to the
  348. // device ID. Set all folders to read only if the global read only flag is
  349. // set.
  350. var devices = map[string]FolderDeviceConfiguration{}
  351. for i, folder := range cfg.Deprecated_Repositories {
  352. cfg.Deprecated_Repositories[i].ReadOnly = cfg.Options.Deprecated_ReadOnly
  353. for j, device := range folder.Deprecated_Nodes {
  354. id := device.DeviceID.String()
  355. if _, ok := devices[id]; !ok {
  356. devices[id] = device
  357. }
  358. cfg.Deprecated_Repositories[i].Deprecated_Nodes[j] = FolderDeviceConfiguration{DeviceID: device.DeviceID}
  359. }
  360. }
  361. cfg.Options.Deprecated_ReadOnly = false
  362. // Set and sort the list of devices.
  363. for _, device := range devices {
  364. cfg.Deprecated_Nodes = append(cfg.Deprecated_Nodes, DeviceConfiguration{
  365. DeviceID: device.DeviceID,
  366. Name: device.Deprecated_Name,
  367. Addresses: device.Deprecated_Addresses,
  368. })
  369. }
  370. sort.Sort(DeviceConfigurationList(cfg.Deprecated_Nodes))
  371. // GUI
  372. cfg.GUI.Address = cfg.Options.Deprecated_GUIAddress
  373. cfg.GUI.Enabled = cfg.Options.Deprecated_GUIEnabled
  374. cfg.Options.Deprecated_GUIEnabled = false
  375. cfg.Options.Deprecated_GUIAddress = ""
  376. cfg.Version = 2
  377. }
  378. func setDefaults(data interface{}) error {
  379. s := reflect.ValueOf(data).Elem()
  380. t := s.Type()
  381. for i := 0; i < s.NumField(); i++ {
  382. f := s.Field(i)
  383. tag := t.Field(i).Tag
  384. v := tag.Get("default")
  385. if len(v) > 0 {
  386. switch f.Interface().(type) {
  387. case string:
  388. f.SetString(v)
  389. case int:
  390. i, err := strconv.ParseInt(v, 10, 64)
  391. if err != nil {
  392. return err
  393. }
  394. f.SetInt(i)
  395. case bool:
  396. f.SetBool(v == "true")
  397. case []string:
  398. // We don't do anything with string slices here. Any default
  399. // we set will be appended to by the XML decoder, so we fill
  400. // those after decoding.
  401. default:
  402. panic(f.Type())
  403. }
  404. }
  405. }
  406. return nil
  407. }
  408. // fillNilSlices sets default value on slices that are still nil.
  409. func fillNilSlices(data interface{}) error {
  410. s := reflect.ValueOf(data).Elem()
  411. t := s.Type()
  412. for i := 0; i < s.NumField(); i++ {
  413. f := s.Field(i)
  414. tag := t.Field(i).Tag
  415. v := tag.Get("default")
  416. if len(v) > 0 {
  417. switch f.Interface().(type) {
  418. case []string:
  419. if f.IsNil() {
  420. rv := reflect.MakeSlice(reflect.TypeOf([]string{}), 1, 1)
  421. rv.Index(0).SetString(v)
  422. f.Set(rv)
  423. }
  424. }
  425. }
  426. }
  427. return nil
  428. }
  429. func uniqueStrings(ss []string) []string {
  430. var m = make(map[string]bool, len(ss))
  431. for _, s := range ss {
  432. m[s] = true
  433. }
  434. var us = make([]string, 0, len(m))
  435. for k := range m {
  436. us = append(us, k)
  437. }
  438. return us
  439. }
  440. func ensureDevicePresent(devices []FolderDeviceConfiguration, myID protocol.DeviceID) []FolderDeviceConfiguration {
  441. for _, device := range devices {
  442. if device.DeviceID.Equals(myID) {
  443. return devices
  444. }
  445. }
  446. devices = append(devices, FolderDeviceConfiguration{
  447. DeviceID: myID,
  448. })
  449. return devices
  450. }
  451. func ensureExistingDevices(devices []FolderDeviceConfiguration, existingDevices map[protocol.DeviceID]bool) []FolderDeviceConfiguration {
  452. count := len(devices)
  453. i := 0
  454. loop:
  455. for i < count {
  456. if _, ok := existingDevices[devices[i].DeviceID]; !ok {
  457. devices[i] = devices[count-1]
  458. count--
  459. continue loop
  460. }
  461. i++
  462. }
  463. return devices[0:count]
  464. }
  465. func ensureNoDuplicates(devices []FolderDeviceConfiguration) []FolderDeviceConfiguration {
  466. count := len(devices)
  467. i := 0
  468. seenDevices := make(map[protocol.DeviceID]bool)
  469. loop:
  470. for i < count {
  471. id := devices[i].DeviceID
  472. if _, ok := seenDevices[id]; ok {
  473. devices[i] = devices[count-1]
  474. count--
  475. continue loop
  476. }
  477. seenDevices[id] = true
  478. i++
  479. }
  480. return devices[0:count]
  481. }
  482. type DeviceConfigurationList []DeviceConfiguration
  483. func (l DeviceConfigurationList) Less(a, b int) bool {
  484. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  485. }
  486. func (l DeviceConfigurationList) Swap(a, b int) {
  487. l[a], l[b] = l[b], l[a]
  488. }
  489. func (l DeviceConfigurationList) Len() int {
  490. return len(l)
  491. }
  492. type FolderDeviceConfigurationList []FolderDeviceConfiguration
  493. func (l FolderDeviceConfigurationList) Less(a, b int) bool {
  494. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  495. }
  496. func (l FolderDeviceConfigurationList) Swap(a, b int) {
  497. l[a], l[b] = l[b], l[a]
  498. }
  499. func (l FolderDeviceConfigurationList) Len() int {
  500. return len(l)
  501. }