wrapper.go 15 KB

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