wrapper.go 12 KB

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