wrapper.go 11 KB

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