wrapper.go 14 KB

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