wrapper.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. "github.com/syncthing/syncthing/lib/events"
  10. "github.com/syncthing/syncthing/lib/osutil"
  11. "github.com/syncthing/syncthing/lib/protocol"
  12. "github.com/syncthing/syncthing/lib/sync"
  13. "github.com/syncthing/syncthing/lib/util"
  14. )
  15. // The Committer interface is implemented by objects that need to know about
  16. // or have a say in configuration changes.
  17. //
  18. // When the configuration is about to be changed, VerifyConfiguration() is
  19. // called for each subscribing object, with the old and new configuration. A
  20. // nil error is returned if the new configuration is acceptable (i.e. does not
  21. // contain any errors that would prevent it from being a valid config).
  22. // Otherwise an error describing the problem is returned.
  23. //
  24. // If any subscriber returns an error from VerifyConfiguration(), the
  25. // configuration change is not committed and an error is returned to whoever
  26. // tried to commit the broken config.
  27. //
  28. // If all verification calls returns nil, CommitConfiguration() is called for
  29. // each subscribing object. The callee returns true if the new configuration
  30. // has been successfully applied, otherwise false. Any Commit() call returning
  31. // false will result in a "restart needed" response to the API/user. Note that
  32. // the new configuration will still have been applied by those who were
  33. // capable of doing so.
  34. type Committer interface {
  35. VerifyConfiguration(from, to Configuration) error
  36. CommitConfiguration(from, to Configuration) (handled bool)
  37. String() string
  38. }
  39. type CommitResponse struct {
  40. ValidationError error
  41. RequiresRestart bool
  42. }
  43. // A wrapper around a Configuration that manages loads, saves and published
  44. // notifications of changes to registered Handlers
  45. type Wrapper struct {
  46. cfg Configuration
  47. path string
  48. deviceMap map[protocol.DeviceID]DeviceConfiguration
  49. folderMap map[string]FolderConfiguration
  50. replaces chan Configuration
  51. subs []Committer
  52. mut sync.Mutex
  53. }
  54. // Wrap wraps an existing Configuration structure and ties it to a file on
  55. // disk.
  56. func Wrap(path string, cfg Configuration) *Wrapper {
  57. w := &Wrapper{
  58. cfg: cfg,
  59. path: path,
  60. mut: sync.NewMutex(),
  61. }
  62. w.replaces = make(chan Configuration)
  63. return w
  64. }
  65. // Load loads an existing file on disk and returns a new configuration
  66. // wrapper.
  67. func Load(path string, myID protocol.DeviceID) (*Wrapper, error) {
  68. fd, err := os.Open(path)
  69. if err != nil {
  70. return nil, err
  71. }
  72. defer fd.Close()
  73. cfg, err := ReadXML(fd, myID)
  74. if err != nil {
  75. return nil, err
  76. }
  77. return Wrap(path, cfg), nil
  78. }
  79. func (w *Wrapper) ConfigPath() string {
  80. return w.path
  81. }
  82. // Stop stops the Serve() loop. Set and Replace operations will panic after a
  83. // Stop.
  84. func (w *Wrapper) Stop() {
  85. close(w.replaces)
  86. }
  87. // Subscribe registers the given handler to be called on any future
  88. // configuration changes.
  89. func (w *Wrapper) Subscribe(c Committer) {
  90. w.mut.Lock()
  91. w.subs = append(w.subs, c)
  92. w.mut.Unlock()
  93. }
  94. // Unsubscribe de-registers the given handler from any future calls to
  95. // configuration changes
  96. func (w *Wrapper) Unsubscribe(c Committer) {
  97. w.mut.Lock()
  98. for i := range w.subs {
  99. if w.subs[i] == c {
  100. copy(w.subs[i:], w.subs[i+1:])
  101. w.subs[len(w.subs)-1] = nil
  102. w.subs = w.subs[:len(w.subs)-1]
  103. break
  104. }
  105. }
  106. w.mut.Unlock()
  107. }
  108. // Raw returns the currently wrapped Configuration object.
  109. func (w *Wrapper) Raw() Configuration {
  110. return w.cfg
  111. }
  112. // Replace swaps the current configuration object for the given one.
  113. func (w *Wrapper) Replace(cfg Configuration) CommitResponse {
  114. w.mut.Lock()
  115. defer w.mut.Unlock()
  116. return w.replaceLocked(cfg)
  117. }
  118. func (w *Wrapper) replaceLocked(to Configuration) CommitResponse {
  119. from := w.cfg
  120. for _, sub := range w.subs {
  121. l.Debugln(sub, "verifying configuration")
  122. if err := sub.VerifyConfiguration(from, to); err != nil {
  123. l.Debugln(sub, "rejected config:", err)
  124. return CommitResponse{
  125. ValidationError: err,
  126. }
  127. }
  128. }
  129. allOk := true
  130. for _, sub := range w.subs {
  131. l.Debugln(sub, "committing configuration")
  132. ok := sub.CommitConfiguration(from, to)
  133. if !ok {
  134. l.Debugln(sub, "requires restart")
  135. allOk = false
  136. }
  137. }
  138. w.cfg = to
  139. w.deviceMap = nil
  140. w.folderMap = nil
  141. return CommitResponse{
  142. RequiresRestart: !allOk,
  143. }
  144. }
  145. // Devices returns a map of devices. Device structures should not be changed,
  146. // other than for the purpose of updating via SetDevice().
  147. func (w *Wrapper) Devices() map[protocol.DeviceID]DeviceConfiguration {
  148. w.mut.Lock()
  149. defer w.mut.Unlock()
  150. if w.deviceMap == nil {
  151. w.deviceMap = make(map[protocol.DeviceID]DeviceConfiguration, len(w.cfg.Devices))
  152. for _, dev := range w.cfg.Devices {
  153. w.deviceMap[dev.DeviceID] = dev
  154. }
  155. }
  156. return w.deviceMap
  157. }
  158. // SetDevice adds a new device to the configuration, or overwrites an existing
  159. // device with the same ID.
  160. func (w *Wrapper) SetDevice(dev DeviceConfiguration) CommitResponse {
  161. w.mut.Lock()
  162. defer w.mut.Unlock()
  163. newCfg := w.cfg.Copy()
  164. replaced := false
  165. for i := range newCfg.Devices {
  166. if newCfg.Devices[i].DeviceID == dev.DeviceID {
  167. newCfg.Devices[i] = dev
  168. replaced = true
  169. break
  170. }
  171. }
  172. if !replaced {
  173. newCfg.Devices = append(w.cfg.Devices, dev)
  174. }
  175. return w.replaceLocked(newCfg)
  176. }
  177. // Folders returns a map of folders. Folder structures should not be changed,
  178. // other than for the purpose of updating via SetFolder().
  179. func (w *Wrapper) Folders() map[string]FolderConfiguration {
  180. w.mut.Lock()
  181. defer w.mut.Unlock()
  182. if w.folderMap == nil {
  183. w.folderMap = make(map[string]FolderConfiguration, len(w.cfg.Folders))
  184. for _, fld := range w.cfg.Folders {
  185. w.folderMap[fld.ID] = fld
  186. }
  187. }
  188. return w.folderMap
  189. }
  190. // SetFolder adds a new folder to the configuration, or overwrites an existing
  191. // folder with the same ID.
  192. func (w *Wrapper) SetFolder(fld FolderConfiguration) CommitResponse {
  193. w.mut.Lock()
  194. defer w.mut.Unlock()
  195. newCfg := w.cfg.Copy()
  196. replaced := false
  197. for i := range newCfg.Folders {
  198. if newCfg.Folders[i].ID == fld.ID {
  199. newCfg.Folders[i] = fld
  200. replaced = true
  201. break
  202. }
  203. }
  204. if !replaced {
  205. newCfg.Folders = append(w.cfg.Folders, fld)
  206. }
  207. return w.replaceLocked(newCfg)
  208. }
  209. // Options returns the current options configuration object.
  210. func (w *Wrapper) Options() OptionsConfiguration {
  211. w.mut.Lock()
  212. defer w.mut.Unlock()
  213. return w.cfg.Options
  214. }
  215. // SetOptions replaces the current options configuration object.
  216. func (w *Wrapper) SetOptions(opts OptionsConfiguration) CommitResponse {
  217. w.mut.Lock()
  218. defer w.mut.Unlock()
  219. newCfg := w.cfg.Copy()
  220. newCfg.Options = opts
  221. return w.replaceLocked(newCfg)
  222. }
  223. // GUI returns the current GUI configuration object.
  224. func (w *Wrapper) GUI() GUIConfiguration {
  225. w.mut.Lock()
  226. defer w.mut.Unlock()
  227. return w.cfg.GUI
  228. }
  229. // SetGUI replaces the current GUI configuration object.
  230. func (w *Wrapper) SetGUI(gui GUIConfiguration) CommitResponse {
  231. w.mut.Lock()
  232. defer w.mut.Unlock()
  233. newCfg := w.cfg.Copy()
  234. newCfg.GUI = gui
  235. return w.replaceLocked(newCfg)
  236. }
  237. // IgnoredDevice returns whether or not connection attempts from the given
  238. // device should be silently ignored.
  239. func (w *Wrapper) IgnoredDevice(id protocol.DeviceID) bool {
  240. w.mut.Lock()
  241. defer w.mut.Unlock()
  242. for _, device := range w.cfg.IgnoredDevices {
  243. if device == id {
  244. return true
  245. }
  246. }
  247. return false
  248. }
  249. // Save writes the configuration to disk, and generates a ConfigSaved event.
  250. func (w *Wrapper) Save() error {
  251. fd, err := osutil.CreateAtomic(w.path, 0600)
  252. if err != nil {
  253. return err
  254. }
  255. if err := w.cfg.WriteXML(fd); err != nil {
  256. fd.Close()
  257. return err
  258. }
  259. if err := fd.Close(); err != nil {
  260. return err
  261. }
  262. events.Default.Log(events.ConfigSaved, w.cfg)
  263. return nil
  264. }
  265. func (w *Wrapper) GlobalDiscoveryServers() []string {
  266. var servers []string
  267. for _, srv := range w.cfg.Options.GlobalAnnServers {
  268. switch srv {
  269. case "default":
  270. servers = append(servers, DefaultDiscoveryServers...)
  271. case "default-v4":
  272. servers = append(servers, DefaultDiscoveryServersV4...)
  273. case "default-v6":
  274. servers = append(servers, DefaultDiscoveryServersV6...)
  275. default:
  276. servers = append(servers, srv)
  277. }
  278. }
  279. return util.UniqueStrings(servers)
  280. }
  281. func (w *Wrapper) ListenAddresses() []string {
  282. var addresses []string
  283. for _, addr := range w.cfg.Options.ListenAddresses {
  284. switch addr {
  285. case "default":
  286. addresses = append(addresses, DefaultListenAddresses...)
  287. default:
  288. addresses = append(addresses, addr)
  289. }
  290. }
  291. return util.UniqueStrings(addresses)
  292. }