wrapper.go 12 KB

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