wrapper.go 13 KB

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