wrapper.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 http://mozilla.org/MPL/2.0/.
  6. package config
  7. import (
  8. "os"
  9. "sync/atomic"
  10. "github.com/syncthing/syncthing/lib/events"
  11. "github.com/syncthing/syncthing/lib/osutil"
  12. "github.com/syncthing/syncthing/lib/protocol"
  13. "github.com/syncthing/syncthing/lib/sync"
  14. "github.com/syncthing/syncthing/lib/util"
  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. // A wrapper around a Configuration that manages loads, saves and published
  41. // notifications of changes to registered Handlers
  42. type Wrapper struct {
  43. cfg Configuration
  44. path string
  45. deviceMap map[protocol.DeviceID]DeviceConfiguration
  46. folderMap map[string]FolderConfiguration
  47. replaces chan Configuration
  48. subs []Committer
  49. mut sync.Mutex
  50. requiresRestart uint32 // an atomic bool
  51. }
  52. // Wrap wraps an existing Configuration structure and ties it to a file on
  53. // disk.
  54. func Wrap(path string, cfg Configuration) *Wrapper {
  55. w := &Wrapper{
  56. cfg: cfg,
  57. path: path,
  58. mut: sync.NewMutex(),
  59. }
  60. w.replaces = make(chan Configuration)
  61. return w
  62. }
  63. // Load loads an existing file on disk and returns a new configuration
  64. // wrapper.
  65. func Load(path string, myID protocol.DeviceID) (*Wrapper, error) {
  66. fd, err := os.Open(path)
  67. if err != nil {
  68. return nil, err
  69. }
  70. defer fd.Close()
  71. cfg, err := ReadXML(fd, myID)
  72. if err != nil {
  73. return nil, err
  74. }
  75. return Wrap(path, cfg), nil
  76. }
  77. func (w *Wrapper) ConfigPath() string {
  78. return w.path
  79. }
  80. // Stop stops the Serve() loop. Set and Replace operations will panic after a
  81. // Stop.
  82. func (w *Wrapper) Stop() {
  83. close(w.replaces)
  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. // Raw returns the currently wrapped Configuration object.
  107. func (w *Wrapper) Raw() Configuration {
  108. return w.cfg
  109. }
  110. // Replace swaps the current configuration object for the given one.
  111. func (w *Wrapper) Replace(cfg Configuration) error {
  112. w.mut.Lock()
  113. defer w.mut.Unlock()
  114. return w.replaceLocked(cfg)
  115. }
  116. func (w *Wrapper) replaceLocked(to Configuration) error {
  117. from := w.cfg
  118. if err := to.clean(); err != nil {
  119. return err
  120. }
  121. for _, sub := range w.subs {
  122. l.Debugln(sub, "verifying configuration")
  123. if err := sub.VerifyConfiguration(from, to); err != nil {
  124. l.Debugln(sub, "rejected config:", err)
  125. return err
  126. }
  127. }
  128. w.cfg = to
  129. w.deviceMap = nil
  130. w.folderMap = nil
  131. w.notifyListeners(from, to)
  132. return nil
  133. }
  134. func (w *Wrapper) notifyListeners(from, to Configuration) {
  135. for _, sub := range w.subs {
  136. go w.notifyListener(sub, from, to)
  137. }
  138. }
  139. func (w *Wrapper) notifyListener(sub Committer, from, to Configuration) {
  140. l.Debugln(sub, "committing configuration")
  141. if !sub.CommitConfiguration(from, to) {
  142. l.Debugln(sub, "requires restart")
  143. w.setRequiresRestart()
  144. }
  145. }
  146. // Devices returns a map of devices. Device structures should not be changed,
  147. // other than for the purpose of updating via SetDevice().
  148. func (w *Wrapper) Devices() map[protocol.DeviceID]DeviceConfiguration {
  149. w.mut.Lock()
  150. defer w.mut.Unlock()
  151. if w.deviceMap == nil {
  152. w.deviceMap = make(map[protocol.DeviceID]DeviceConfiguration, len(w.cfg.Devices))
  153. for _, dev := range w.cfg.Devices {
  154. w.deviceMap[dev.DeviceID] = dev
  155. }
  156. }
  157. return w.deviceMap
  158. }
  159. // SetDevice adds a new device to the configuration, or overwrites an existing
  160. // device with the same ID.
  161. func (w *Wrapper) SetDevice(dev DeviceConfiguration) error {
  162. w.mut.Lock()
  163. defer w.mut.Unlock()
  164. newCfg := w.cfg.Copy()
  165. replaced := false
  166. for i := range newCfg.Devices {
  167. if newCfg.Devices[i].DeviceID == dev.DeviceID {
  168. newCfg.Devices[i] = dev
  169. replaced = true
  170. break
  171. }
  172. }
  173. if !replaced {
  174. newCfg.Devices = append(w.cfg.Devices, dev)
  175. }
  176. return w.replaceLocked(newCfg)
  177. }
  178. // Folders returns a map of folders. Folder structures should not be changed,
  179. // other than for the purpose of updating via SetFolder().
  180. func (w *Wrapper) Folders() map[string]FolderConfiguration {
  181. w.mut.Lock()
  182. defer w.mut.Unlock()
  183. if w.folderMap == nil {
  184. w.folderMap = make(map[string]FolderConfiguration, len(w.cfg.Folders))
  185. for _, fld := range w.cfg.Folders {
  186. w.folderMap[fld.ID] = fld
  187. }
  188. }
  189. return w.folderMap
  190. }
  191. // SetFolder adds a new folder to the configuration, or overwrites an existing
  192. // folder with the same ID.
  193. func (w *Wrapper) SetFolder(fld FolderConfiguration) error {
  194. w.mut.Lock()
  195. defer w.mut.Unlock()
  196. newCfg := w.cfg.Copy()
  197. replaced := false
  198. for i := range newCfg.Folders {
  199. if newCfg.Folders[i].ID == fld.ID {
  200. newCfg.Folders[i] = fld
  201. replaced = true
  202. break
  203. }
  204. }
  205. if !replaced {
  206. newCfg.Folders = append(w.cfg.Folders, fld)
  207. }
  208. return w.replaceLocked(newCfg)
  209. }
  210. // Options returns the current options configuration object.
  211. func (w *Wrapper) Options() OptionsConfiguration {
  212. w.mut.Lock()
  213. defer w.mut.Unlock()
  214. return w.cfg.Options
  215. }
  216. // SetOptions replaces the current options configuration object.
  217. func (w *Wrapper) SetOptions(opts OptionsConfiguration) error {
  218. w.mut.Lock()
  219. defer w.mut.Unlock()
  220. newCfg := w.cfg.Copy()
  221. newCfg.Options = opts
  222. return w.replaceLocked(newCfg)
  223. }
  224. // GUI returns the current GUI configuration object.
  225. func (w *Wrapper) GUI() GUIConfiguration {
  226. w.mut.Lock()
  227. defer w.mut.Unlock()
  228. return w.cfg.GUI
  229. }
  230. // SetGUI replaces the current GUI configuration object.
  231. func (w *Wrapper) SetGUI(gui GUIConfiguration) error {
  232. w.mut.Lock()
  233. defer w.mut.Unlock()
  234. newCfg := w.cfg.Copy()
  235. newCfg.GUI = gui
  236. return w.replaceLocked(newCfg)
  237. }
  238. // IgnoredDevice returns whether or not connection attempts from the given
  239. // device should be silently ignored.
  240. func (w *Wrapper) IgnoredDevice(id protocol.DeviceID) bool {
  241. w.mut.Lock()
  242. defer w.mut.Unlock()
  243. for _, device := range w.cfg.IgnoredDevices {
  244. if device == id {
  245. return true
  246. }
  247. }
  248. return false
  249. }
  250. // Device returns the configuration for the given device and an "ok" bool.
  251. func (w *Wrapper) Device(id protocol.DeviceID) (DeviceConfiguration, bool) {
  252. w.mut.Lock()
  253. defer w.mut.Unlock()
  254. for _, device := range w.cfg.Devices {
  255. if device.DeviceID == id {
  256. return device, true
  257. }
  258. }
  259. return DeviceConfiguration{}, false
  260. }
  261. // Save writes the configuration to disk, and generates a ConfigSaved event.
  262. func (w *Wrapper) Save() error {
  263. fd, err := osutil.CreateAtomic(w.path, 0600)
  264. if err != nil {
  265. return err
  266. }
  267. if err := w.cfg.WriteXML(fd); err != nil {
  268. fd.Close()
  269. return err
  270. }
  271. if err := fd.Close(); err != nil {
  272. return err
  273. }
  274. events.Default.Log(events.ConfigSaved, w.cfg)
  275. return nil
  276. }
  277. func (w *Wrapper) GlobalDiscoveryServers() []string {
  278. var servers []string
  279. for _, srv := range w.cfg.Options.GlobalAnnServers {
  280. switch srv {
  281. case "default":
  282. servers = append(servers, DefaultDiscoveryServers...)
  283. case "default-v4":
  284. servers = append(servers, DefaultDiscoveryServersV4...)
  285. case "default-v6":
  286. servers = append(servers, DefaultDiscoveryServersV6...)
  287. default:
  288. servers = append(servers, srv)
  289. }
  290. }
  291. return util.UniqueStrings(servers)
  292. }
  293. func (w *Wrapper) ListenAddresses() []string {
  294. var addresses []string
  295. for _, addr := range w.cfg.Options.ListenAddresses {
  296. switch addr {
  297. case "default":
  298. addresses = append(addresses, DefaultListenAddresses...)
  299. default:
  300. addresses = append(addresses, addr)
  301. }
  302. }
  303. return util.UniqueStrings(addresses)
  304. }
  305. func (w *Wrapper) RequiresRestart() bool {
  306. return atomic.LoadUint32(&w.requiresRestart) != 0
  307. }
  308. func (w *Wrapper) setRequiresRestart() {
  309. atomic.StoreUint32(&w.requiresRestart, 1)
  310. }