wrapper.go 13 KB

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