wrapper.go 14 KB

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