wrapper.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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)
  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, to); 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, to), 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.Copy(), to.Copy())
  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. Device structures should not be changed,
  162. // other than for the purpose of updating via SetDevice().
  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
  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]
  186. replaced = true
  187. break
  188. }
  189. }
  190. if !replaced {
  191. newCfg.Devices = append(newCfg.Devices, devs[oldIndex])
  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. removed := false
  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. removed = true
  211. break
  212. }
  213. }
  214. if !removed {
  215. return noopWaiter{}, nil
  216. }
  217. return w.replaceLocked(newCfg)
  218. }
  219. // Folders returns a map of folders. Folder structures should not be changed,
  220. // other than for the purpose of updating via SetFolder().
  221. func (w *Wrapper) Folders() map[string]FolderConfiguration {
  222. w.mut.Lock()
  223. defer w.mut.Unlock()
  224. if w.folderMap == nil {
  225. w.folderMap = make(map[string]FolderConfiguration, len(w.cfg.Folders))
  226. for _, fld := range w.cfg.Folders {
  227. w.folderMap[fld.ID] = fld
  228. }
  229. }
  230. return w.folderMap
  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. replaced := false
  239. for i := range newCfg.Folders {
  240. if newCfg.Folders[i].ID == fld.ID {
  241. newCfg.Folders[i] = fld
  242. replaced = true
  243. break
  244. }
  245. }
  246. if !replaced {
  247. newCfg.Folders = append(w.cfg.Folders, fld)
  248. }
  249. return w.replaceLocked(newCfg)
  250. }
  251. // Options returns the current options configuration object.
  252. func (w *Wrapper) Options() OptionsConfiguration {
  253. w.mut.Lock()
  254. defer w.mut.Unlock()
  255. return w.cfg.Options
  256. }
  257. // SetOptions replaces the current options configuration object.
  258. func (w *Wrapper) SetOptions(opts OptionsConfiguration) (Waiter, error) {
  259. w.mut.Lock()
  260. defer w.mut.Unlock()
  261. newCfg := w.cfg.Copy()
  262. newCfg.Options = opts
  263. return w.replaceLocked(newCfg)
  264. }
  265. // GUI returns the current GUI configuration object.
  266. func (w *Wrapper) GUI() GUIConfiguration {
  267. w.mut.Lock()
  268. defer w.mut.Unlock()
  269. return w.cfg.GUI
  270. }
  271. // SetGUI replaces the current GUI configuration object.
  272. func (w *Wrapper) SetGUI(gui GUIConfiguration) (Waiter, error) {
  273. w.mut.Lock()
  274. defer w.mut.Unlock()
  275. newCfg := w.cfg.Copy()
  276. newCfg.GUI = gui
  277. return w.replaceLocked(newCfg)
  278. }
  279. // IgnoredDevice returns whether or not connection attempts from the given
  280. // device should be silently ignored.
  281. func (w *Wrapper) IgnoredDevice(id protocol.DeviceID) bool {
  282. w.mut.Lock()
  283. defer w.mut.Unlock()
  284. for _, device := range w.cfg.IgnoredDevices {
  285. if device == id {
  286. return true
  287. }
  288. }
  289. return false
  290. }
  291. // IgnoredFolder returns whether or not share attempts for the given
  292. // folder should be silently ignored.
  293. func (w *Wrapper) IgnoredFolder(folder string) bool {
  294. w.mut.Lock()
  295. defer w.mut.Unlock()
  296. for _, nfolder := range w.cfg.IgnoredFolders {
  297. if folder == nfolder {
  298. return true
  299. }
  300. }
  301. return false
  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, 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, 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. fd, err := osutil.CreateAtomic(w.path)
  328. if err != nil {
  329. l.Debugln("CreateAtomic:", err)
  330. return err
  331. }
  332. if err := w.cfg.WriteXML(fd); err != nil {
  333. l.Debugln("WriteXML:", err)
  334. fd.Close()
  335. return err
  336. }
  337. if err := fd.Close(); err != nil {
  338. l.Debugln("Close:", err)
  339. return err
  340. }
  341. events.Default.Log(events.ConfigSaved, w.cfg)
  342. return nil
  343. }
  344. func (w *Wrapper) GlobalDiscoveryServers() []string {
  345. var servers []string
  346. for _, srv := range w.cfg.Options.GlobalAnnServers {
  347. switch srv {
  348. case "default":
  349. servers = append(servers, DefaultDiscoveryServers...)
  350. case "default-v4":
  351. servers = append(servers, DefaultDiscoveryServersV4...)
  352. case "default-v6":
  353. servers = append(servers, DefaultDiscoveryServersV6...)
  354. default:
  355. servers = append(servers, srv)
  356. }
  357. }
  358. return util.UniqueStrings(servers)
  359. }
  360. func (w *Wrapper) ListenAddresses() []string {
  361. var addresses []string
  362. for _, addr := range w.cfg.Options.ListenAddresses {
  363. switch addr {
  364. case "default":
  365. addresses = append(addresses, DefaultListenAddresses...)
  366. default:
  367. addresses = append(addresses, addr)
  368. }
  369. }
  370. return util.UniqueStrings(addresses)
  371. }
  372. func (w *Wrapper) RequiresRestart() bool {
  373. return atomic.LoadUint32(&w.requiresRestart) != 0
  374. }
  375. func (w *Wrapper) setRequiresRestart() {
  376. atomic.StoreUint32(&w.requiresRestart, 1)
  377. }
  378. func (w *Wrapper) MyName() string {
  379. w.mut.Lock()
  380. myID := w.cfg.MyID
  381. w.mut.Unlock()
  382. cfg, _ := w.Device(myID)
  383. return cfg.Name
  384. }
  385. // CheckHomeFreeSpace returns nil if the home disk has the required amount of
  386. // free space, or if home disk free space checking is disabled.
  387. func (w *Wrapper) CheckHomeFreeSpace() error {
  388. return checkFreeSpace(w.Options().MinHomeDiskFree, fs.NewFilesystem(fs.FilesystemTypeBasic, filepath.Dir(w.ConfigPath())))
  389. }