wrapper.go 12 KB

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