wrapper.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package config
  7. import (
  8. "fmt"
  9. "os"
  10. "path/filepath"
  11. "sync/atomic"
  12. "time"
  13. "github.com/syncthing/syncthing/lib/events"
  14. "github.com/syncthing/syncthing/lib/fs"
  15. "github.com/syncthing/syncthing/lib/osutil"
  16. "github.com/syncthing/syncthing/lib/protocol"
  17. "github.com/syncthing/syncthing/lib/sync"
  18. "github.com/syncthing/syncthing/lib/util"
  19. )
  20. // The Committer interface is implemented by objects that need to know about
  21. // or have a say in configuration changes.
  22. //
  23. // When the configuration is about to be changed, VerifyConfiguration() is
  24. // called for each subscribing object, with the old and new configuration. A
  25. // nil error is returned if the new configuration is acceptable (i.e. does not
  26. // contain any errors that would prevent it from being a valid config).
  27. // Otherwise an error describing the problem is returned.
  28. //
  29. // If any subscriber returns an error from VerifyConfiguration(), the
  30. // configuration change is not committed and an error is returned to whoever
  31. // tried to commit the broken config.
  32. //
  33. // If all verification calls returns nil, CommitConfiguration() is called for
  34. // each subscribing object. The callee returns true if the new configuration
  35. // has been successfully applied, otherwise false. Any Commit() call returning
  36. // false will result in a "restart needed" response to the API/user. Note that
  37. // the new configuration will still have been applied by those who were
  38. // capable of doing so.
  39. type Committer interface {
  40. VerifyConfiguration(from, to Configuration) error
  41. CommitConfiguration(from, to Configuration) (handled bool)
  42. String() string
  43. }
  44. // Waiter allows to wait for the given config operation to complete.
  45. type Waiter interface {
  46. Wait()
  47. }
  48. type noopWaiter struct{}
  49. func (noopWaiter) Wait() {}
  50. // A wrapper around a Configuration that manages loads, saves and published
  51. // notifications of changes to registered Handlers
  52. type Wrapper struct {
  53. cfg Configuration
  54. path string
  55. deviceMap map[protocol.DeviceID]DeviceConfiguration
  56. folderMap map[string]FolderConfiguration
  57. replaces chan Configuration
  58. subs []Committer
  59. mut sync.Mutex
  60. requiresRestart uint32 // an atomic bool
  61. }
  62. // Wrap wraps an existing Configuration structure and ties it to a file on
  63. // disk.
  64. func Wrap(path string, cfg Configuration) *Wrapper {
  65. w := &Wrapper{
  66. cfg: cfg,
  67. path: path,
  68. mut: sync.NewMutex(),
  69. }
  70. w.replaces = make(chan Configuration)
  71. return w
  72. }
  73. // Load loads an existing file on disk and returns a new configuration
  74. // wrapper.
  75. func Load(path string, myID protocol.DeviceID) (*Wrapper, error) {
  76. fd, err := os.Open(path)
  77. if err != nil {
  78. return nil, err
  79. }
  80. defer fd.Close()
  81. cfg, err := ReadXML(fd, myID)
  82. if err != nil {
  83. return nil, err
  84. }
  85. return Wrap(path, cfg), nil
  86. }
  87. func (w *Wrapper) ConfigPath() string {
  88. return w.path
  89. }
  90. // Stop stops the Serve() loop. Set and Replace operations will panic after a
  91. // Stop.
  92. func (w *Wrapper) Stop() {
  93. close(w.replaces)
  94. }
  95. // Subscribe registers the given handler to be called on any future
  96. // configuration changes.
  97. func (w *Wrapper) Subscribe(c Committer) {
  98. w.mut.Lock()
  99. w.subs = append(w.subs, c)
  100. w.mut.Unlock()
  101. }
  102. // Unsubscribe de-registers the given handler from any future calls to
  103. // configuration changes
  104. func (w *Wrapper) Unsubscribe(c Committer) {
  105. w.mut.Lock()
  106. for i := range w.subs {
  107. if w.subs[i] == c {
  108. copy(w.subs[i:], w.subs[i+1:])
  109. w.subs[len(w.subs)-1] = nil
  110. w.subs = w.subs[:len(w.subs)-1]
  111. break
  112. }
  113. }
  114. w.mut.Unlock()
  115. }
  116. // RawCopy returns a copy of the currently wrapped Configuration object.
  117. func (w *Wrapper) RawCopy() Configuration {
  118. w.mut.Lock()
  119. defer w.mut.Unlock()
  120. return w.cfg.Copy()
  121. }
  122. // Replace swaps the current configuration object for the given one.
  123. func (w *Wrapper) Replace(cfg Configuration) (Waiter, error) {
  124. w.mut.Lock()
  125. defer w.mut.Unlock()
  126. return w.replaceLocked(cfg.Copy())
  127. }
  128. func (w *Wrapper) replaceLocked(to Configuration) (Waiter, error) {
  129. from := w.cfg
  130. if err := to.clean(); err != nil {
  131. return noopWaiter{}, err
  132. }
  133. for _, sub := range w.subs {
  134. l.Debugln(sub, "verifying configuration")
  135. if err := sub.VerifyConfiguration(from.Copy(), to.Copy()); err != nil {
  136. l.Debugln(sub, "rejected config:", err)
  137. return noopWaiter{}, err
  138. }
  139. }
  140. w.cfg = to
  141. w.deviceMap = nil
  142. w.folderMap = nil
  143. return w.notifyListeners(from.Copy(), to.Copy()), nil
  144. }
  145. func (w *Wrapper) notifyListeners(from, to Configuration) Waiter {
  146. wg := sync.NewWaitGroup()
  147. wg.Add(len(w.subs))
  148. for _, sub := range w.subs {
  149. go func(commiter Committer) {
  150. w.notifyListener(commiter, from, to)
  151. wg.Done()
  152. }(sub)
  153. }
  154. return wg
  155. }
  156. func (w *Wrapper) notifyListener(sub Committer, from, to Configuration) {
  157. l.Debugln(sub, "committing configuration")
  158. if !sub.CommitConfiguration(from, to) {
  159. l.Debugln(sub, "requires restart")
  160. w.setRequiresRestart()
  161. }
  162. }
  163. // Devices returns a map of devices.
  164. func (w *Wrapper) Devices() map[protocol.DeviceID]DeviceConfiguration {
  165. w.mut.Lock()
  166. defer w.mut.Unlock()
  167. if w.deviceMap == nil {
  168. w.deviceMap = make(map[protocol.DeviceID]DeviceConfiguration, len(w.cfg.Devices))
  169. for _, dev := range w.cfg.Devices {
  170. w.deviceMap[dev.DeviceID] = dev.Copy()
  171. }
  172. }
  173. return w.deviceMap
  174. }
  175. // SetDevices adds new devices to the configuration, or overwrites existing
  176. // devices with the same ID.
  177. func (w *Wrapper) SetDevices(devs []DeviceConfiguration) (Waiter, error) {
  178. w.mut.Lock()
  179. defer w.mut.Unlock()
  180. newCfg := w.cfg.Copy()
  181. var replaced bool
  182. for oldIndex := range devs {
  183. replaced = false
  184. for newIndex := range newCfg.Devices {
  185. if newCfg.Devices[newIndex].DeviceID == devs[oldIndex].DeviceID {
  186. newCfg.Devices[newIndex] = devs[oldIndex].Copy()
  187. replaced = true
  188. break
  189. }
  190. }
  191. if !replaced {
  192. newCfg.Devices = append(newCfg.Devices, devs[oldIndex].Copy())
  193. }
  194. }
  195. return w.replaceLocked(newCfg)
  196. }
  197. // SetDevice adds a new device to the configuration, or overwrites an existing
  198. // device with the same ID.
  199. func (w *Wrapper) SetDevice(dev DeviceConfiguration) (Waiter, error) {
  200. return w.SetDevices([]DeviceConfiguration{dev})
  201. }
  202. // RemoveDevice removes the device from the configuration
  203. func (w *Wrapper) RemoveDevice(id protocol.DeviceID) (Waiter, error) {
  204. w.mut.Lock()
  205. defer w.mut.Unlock()
  206. newCfg := w.cfg.Copy()
  207. for i := range newCfg.Devices {
  208. if newCfg.Devices[i].DeviceID == id {
  209. newCfg.Devices = append(newCfg.Devices[:i], newCfg.Devices[i+1:]...)
  210. return w.replaceLocked(newCfg)
  211. }
  212. }
  213. return noopWaiter{}, nil
  214. }
  215. // Folders returns a map of folders. Folder structures should not be changed,
  216. // other than for the purpose of updating via SetFolder().
  217. func (w *Wrapper) Folders() map[string]FolderConfiguration {
  218. w.mut.Lock()
  219. defer w.mut.Unlock()
  220. if w.folderMap == nil {
  221. w.folderMap = make(map[string]FolderConfiguration, len(w.cfg.Folders))
  222. for _, fld := range w.cfg.Folders {
  223. w.folderMap[fld.ID] = fld.Copy()
  224. }
  225. }
  226. return w.folderMap
  227. }
  228. // FolderList returns a slice of folders.
  229. func (w *Wrapper) FolderList() []FolderConfiguration {
  230. w.mut.Lock()
  231. defer w.mut.Unlock()
  232. return w.cfg.Copy().Folders
  233. }
  234. // SetFolder adds a new folder to the configuration, or overwrites an existing
  235. // folder with the same ID.
  236. func (w *Wrapper) SetFolder(fld FolderConfiguration) (Waiter, error) {
  237. w.mut.Lock()
  238. defer w.mut.Unlock()
  239. newCfg := w.cfg.Copy()
  240. for i := range newCfg.Folders {
  241. if newCfg.Folders[i].ID == fld.ID {
  242. newCfg.Folders[i] = fld
  243. return w.replaceLocked(newCfg)
  244. }
  245. }
  246. newCfg.Folders = append(newCfg.Folders, fld)
  247. return w.replaceLocked(newCfg)
  248. }
  249. // Options returns the current options configuration object.
  250. func (w *Wrapper) Options() OptionsConfiguration {
  251. w.mut.Lock()
  252. defer w.mut.Unlock()
  253. return w.cfg.Options.Copy()
  254. }
  255. // SetOptions replaces the current options configuration object.
  256. func (w *Wrapper) SetOptions(opts OptionsConfiguration) (Waiter, error) {
  257. w.mut.Lock()
  258. defer w.mut.Unlock()
  259. newCfg := w.cfg.Copy()
  260. newCfg.Options = opts.Copy()
  261. return w.replaceLocked(newCfg)
  262. }
  263. func (w *Wrapper) LDAP() LDAPConfiguration {
  264. w.mut.Lock()
  265. defer w.mut.Unlock()
  266. return w.cfg.LDAP.Copy()
  267. }
  268. // GUI returns the current GUI configuration object.
  269. func (w *Wrapper) GUI() GUIConfiguration {
  270. w.mut.Lock()
  271. defer w.mut.Unlock()
  272. return w.cfg.GUI.Copy()
  273. }
  274. // SetGUI replaces the current GUI configuration object.
  275. func (w *Wrapper) SetGUI(gui GUIConfiguration) (Waiter, error) {
  276. w.mut.Lock()
  277. defer w.mut.Unlock()
  278. newCfg := w.cfg.Copy()
  279. newCfg.GUI = gui.Copy()
  280. return w.replaceLocked(newCfg)
  281. }
  282. // IgnoredDevice returns whether or not connection attempts from the given
  283. // device should be silently ignored.
  284. func (w *Wrapper) IgnoredDevice(id protocol.DeviceID) bool {
  285. w.mut.Lock()
  286. defer w.mut.Unlock()
  287. for _, device := range w.cfg.IgnoredDevices {
  288. if device.ID == id {
  289. return true
  290. }
  291. }
  292. return false
  293. }
  294. // IgnoredFolder returns whether or not share attempts for the given
  295. // folder should be silently ignored.
  296. func (w *Wrapper) IgnoredFolder(device protocol.DeviceID, folder string) bool {
  297. dev, ok := w.Device(device)
  298. if !ok {
  299. return false
  300. }
  301. return dev.IgnoredFolder(folder)
  302. }
  303. // Device returns the configuration for the given device and an "ok" bool.
  304. func (w *Wrapper) Device(id protocol.DeviceID) (DeviceConfiguration, bool) {
  305. w.mut.Lock()
  306. defer w.mut.Unlock()
  307. for _, device := range w.cfg.Devices {
  308. if device.DeviceID == id {
  309. return device.Copy(), true
  310. }
  311. }
  312. return DeviceConfiguration{}, false
  313. }
  314. // Folder returns the configuration for the given folder and an "ok" bool.
  315. func (w *Wrapper) Folder(id string) (FolderConfiguration, bool) {
  316. w.mut.Lock()
  317. defer w.mut.Unlock()
  318. for _, folder := range w.cfg.Folders {
  319. if folder.ID == id {
  320. return folder.Copy(), true
  321. }
  322. }
  323. return FolderConfiguration{}, false
  324. }
  325. // Save writes the configuration to disk, and generates a ConfigSaved event.
  326. func (w *Wrapper) Save() error {
  327. w.mut.Lock()
  328. defer w.mut.Unlock()
  329. fd, err := osutil.CreateAtomic(w.path)
  330. if err != nil {
  331. l.Debugln("CreateAtomic:", err)
  332. return err
  333. }
  334. if err := w.cfg.WriteXML(fd); err != nil {
  335. l.Debugln("WriteXML:", err)
  336. fd.Close()
  337. return err
  338. }
  339. if err := fd.Close(); err != nil {
  340. l.Debugln("Close:", err)
  341. return err
  342. }
  343. events.Default.Log(events.ConfigSaved, w.cfg)
  344. return nil
  345. }
  346. func (w *Wrapper) GlobalDiscoveryServers() []string {
  347. var servers []string
  348. for _, srv := range w.Options().GlobalAnnServers {
  349. switch srv {
  350. case "default":
  351. servers = append(servers, DefaultDiscoveryServers...)
  352. case "default-v4":
  353. servers = append(servers, DefaultDiscoveryServersV4...)
  354. case "default-v6":
  355. servers = append(servers, DefaultDiscoveryServersV6...)
  356. default:
  357. servers = append(servers, srv)
  358. }
  359. }
  360. return util.UniqueStrings(servers)
  361. }
  362. func (w *Wrapper) ListenAddresses() []string {
  363. var addresses []string
  364. for _, addr := range w.Options().ListenAddresses {
  365. switch addr {
  366. case "default":
  367. addresses = append(addresses, DefaultListenAddresses...)
  368. default:
  369. addresses = append(addresses, addr)
  370. }
  371. }
  372. return util.UniqueStrings(addresses)
  373. }
  374. func (w *Wrapper) RequiresRestart() bool {
  375. return atomic.LoadUint32(&w.requiresRestart) != 0
  376. }
  377. func (w *Wrapper) setRequiresRestart() {
  378. atomic.StoreUint32(&w.requiresRestart, 1)
  379. }
  380. func (w *Wrapper) MyName() string {
  381. w.mut.Lock()
  382. myID := w.cfg.MyID
  383. w.mut.Unlock()
  384. cfg, _ := w.Device(myID)
  385. return cfg.Name
  386. }
  387. func (w *Wrapper) AddOrUpdatePendingDevice(device protocol.DeviceID, name, address string) {
  388. defer w.Save()
  389. w.mut.Lock()
  390. defer w.mut.Unlock()
  391. for i := range w.cfg.PendingDevices {
  392. if w.cfg.PendingDevices[i].ID == device {
  393. w.cfg.PendingDevices[i].Time = time.Now()
  394. w.cfg.PendingDevices[i].Name = name
  395. w.cfg.PendingDevices[i].Address = address
  396. return
  397. }
  398. }
  399. w.cfg.PendingDevices = append(w.cfg.PendingDevices, ObservedDevice{
  400. Time: time.Now(),
  401. ID: device,
  402. Name: name,
  403. Address: address,
  404. })
  405. }
  406. func (w *Wrapper) AddOrUpdatePendingFolder(id, label string, device protocol.DeviceID) {
  407. defer w.Save()
  408. w.mut.Lock()
  409. defer w.mut.Unlock()
  410. for i := range w.cfg.Devices {
  411. if w.cfg.Devices[i].DeviceID == device {
  412. for j := range w.cfg.Devices[i].PendingFolders {
  413. if w.cfg.Devices[i].PendingFolders[j].ID == id {
  414. w.cfg.Devices[i].PendingFolders[j].Label = label
  415. w.cfg.Devices[i].PendingFolders[j].Time = time.Now()
  416. return
  417. }
  418. }
  419. w.cfg.Devices[i].PendingFolders = append(w.cfg.Devices[i].PendingFolders, ObservedFolder{
  420. Time: time.Now(),
  421. ID: id,
  422. Label: label,
  423. })
  424. return
  425. }
  426. }
  427. panic("bug: adding pending folder for non-existing device")
  428. }
  429. // CheckHomeFreeSpace returns nil if the home disk has the required amount of
  430. // free space, or if home disk free space checking is disabled.
  431. func (w *Wrapper) CheckHomeFreeSpace() error {
  432. path := filepath.Dir(w.ConfigPath())
  433. if usage, err := fs.NewFilesystem(fs.FilesystemTypeBasic, path).Usage("."); err == nil {
  434. if err = checkFreeSpace(w.Options().MinHomeDiskFree, usage); err != nil {
  435. return fmt.Errorf("insufficient space on home disk (%v): %v", path, err)
  436. }
  437. }
  438. return nil
  439. }