wrapper.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. evLogger events.Logger
  85. deviceMap map[protocol.DeviceID]DeviceConfiguration
  86. folderMap map[string]FolderConfiguration
  87. subs []Committer
  88. mut sync.Mutex
  89. requiresRestart uint32 // an atomic bool
  90. }
  91. func (w *wrapper) StunServers() []string {
  92. var addresses []string
  93. for _, addr := range w.cfg.Options.StunServers {
  94. switch addr {
  95. case "default":
  96. defaultPrimaryAddresses := make([]string, len(DefaultPrimaryStunServers))
  97. copy(defaultPrimaryAddresses, DefaultPrimaryStunServers)
  98. rand.Shuffle(defaultPrimaryAddresses)
  99. addresses = append(addresses, defaultPrimaryAddresses...)
  100. defaultSecondaryAddresses := make([]string, len(DefaultSecondaryStunServers))
  101. copy(defaultSecondaryAddresses, DefaultSecondaryStunServers)
  102. rand.Shuffle(defaultSecondaryAddresses)
  103. addresses = append(addresses, defaultSecondaryAddresses...)
  104. default:
  105. addresses = append(addresses, addr)
  106. }
  107. }
  108. addresses = util.UniqueTrimmedStrings(addresses)
  109. return addresses
  110. }
  111. // Wrap wraps an existing Configuration structure and ties it to a file on
  112. // disk.
  113. func Wrap(path string, cfg Configuration, evLogger events.Logger) Wrapper {
  114. w := &wrapper{
  115. cfg: cfg,
  116. path: path,
  117. evLogger: evLogger,
  118. mut: sync.NewMutex(),
  119. }
  120. return w
  121. }
  122. // Load loads an existing file on disk and returns a new configuration
  123. // wrapper.
  124. func Load(path string, myID protocol.DeviceID, evLogger events.Logger) (Wrapper, error) {
  125. fd, err := os.Open(path)
  126. if err != nil {
  127. return nil, err
  128. }
  129. defer fd.Close()
  130. cfg, err := ReadXML(fd, myID)
  131. if err != nil {
  132. return nil, err
  133. }
  134. return Wrap(path, cfg, evLogger), nil
  135. }
  136. func (w *wrapper) ConfigPath() string {
  137. return w.path
  138. }
  139. // Subscribe registers the given handler to be called on any future
  140. // configuration changes.
  141. func (w *wrapper) Subscribe(c Committer) {
  142. w.mut.Lock()
  143. w.subs = append(w.subs, c)
  144. w.mut.Unlock()
  145. }
  146. // Unsubscribe de-registers the given handler from any future calls to
  147. // configuration changes
  148. func (w *wrapper) Unsubscribe(c Committer) {
  149. w.mut.Lock()
  150. for i := range w.subs {
  151. if w.subs[i] == c {
  152. copy(w.subs[i:], w.subs[i+1:])
  153. w.subs[len(w.subs)-1] = nil
  154. w.subs = w.subs[:len(w.subs)-1]
  155. break
  156. }
  157. }
  158. w.mut.Unlock()
  159. }
  160. // RawCopy returns a copy of the currently wrapped Configuration object.
  161. func (w *wrapper) RawCopy() Configuration {
  162. w.mut.Lock()
  163. defer w.mut.Unlock()
  164. return w.cfg.Copy()
  165. }
  166. // Replace swaps the current configuration object for the given one.
  167. func (w *wrapper) Replace(cfg Configuration) (Waiter, error) {
  168. w.mut.Lock()
  169. defer w.mut.Unlock()
  170. return w.replaceLocked(cfg.Copy())
  171. }
  172. func (w *wrapper) replaceLocked(to Configuration) (Waiter, error) {
  173. from := w.cfg
  174. if err := to.clean(); err != nil {
  175. return noopWaiter{}, err
  176. }
  177. for _, sub := range w.subs {
  178. l.Debugln(sub, "verifying configuration")
  179. if err := sub.VerifyConfiguration(from.Copy(), to.Copy()); err != nil {
  180. l.Debugln(sub, "rejected config:", err)
  181. return noopWaiter{}, err
  182. }
  183. }
  184. w.cfg = to
  185. w.deviceMap = nil
  186. w.folderMap = nil
  187. return w.notifyListeners(from.Copy(), to.Copy()), nil
  188. }
  189. func (w *wrapper) notifyListeners(from, to Configuration) Waiter {
  190. wg := sync.NewWaitGroup()
  191. wg.Add(len(w.subs))
  192. for _, sub := range w.subs {
  193. go func(commiter Committer) {
  194. w.notifyListener(commiter, from, to)
  195. wg.Done()
  196. }(sub)
  197. }
  198. return wg
  199. }
  200. func (w *wrapper) notifyListener(sub Committer, from, to Configuration) {
  201. l.Debugln(sub, "committing configuration")
  202. if !sub.CommitConfiguration(from, to) {
  203. l.Debugln(sub, "requires restart")
  204. w.setRequiresRestart()
  205. }
  206. }
  207. // Devices returns a map of devices.
  208. func (w *wrapper) Devices() map[protocol.DeviceID]DeviceConfiguration {
  209. w.mut.Lock()
  210. defer w.mut.Unlock()
  211. if w.deviceMap == nil {
  212. w.deviceMap = make(map[protocol.DeviceID]DeviceConfiguration, len(w.cfg.Devices))
  213. for _, dev := range w.cfg.Devices {
  214. w.deviceMap[dev.DeviceID] = dev.Copy()
  215. }
  216. }
  217. return w.deviceMap
  218. }
  219. // SetDevices adds new devices to the configuration, or overwrites existing
  220. // devices with the same ID.
  221. func (w *wrapper) SetDevices(devs []DeviceConfiguration) (Waiter, error) {
  222. w.mut.Lock()
  223. defer w.mut.Unlock()
  224. newCfg := w.cfg.Copy()
  225. var replaced bool
  226. for oldIndex := range devs {
  227. replaced = false
  228. for newIndex := range newCfg.Devices {
  229. if newCfg.Devices[newIndex].DeviceID == devs[oldIndex].DeviceID {
  230. newCfg.Devices[newIndex] = devs[oldIndex].Copy()
  231. replaced = true
  232. break
  233. }
  234. }
  235. if !replaced {
  236. newCfg.Devices = append(newCfg.Devices, devs[oldIndex].Copy())
  237. }
  238. }
  239. return w.replaceLocked(newCfg)
  240. }
  241. // SetDevice adds a new device to the configuration, or overwrites an existing
  242. // device with the same ID.
  243. func (w *wrapper) SetDevice(dev DeviceConfiguration) (Waiter, error) {
  244. return w.SetDevices([]DeviceConfiguration{dev})
  245. }
  246. // RemoveDevice removes the device from the configuration
  247. func (w *wrapper) RemoveDevice(id protocol.DeviceID) (Waiter, error) {
  248. w.mut.Lock()
  249. defer w.mut.Unlock()
  250. newCfg := w.cfg.Copy()
  251. for i := range newCfg.Devices {
  252. if newCfg.Devices[i].DeviceID == id {
  253. newCfg.Devices = append(newCfg.Devices[:i], newCfg.Devices[i+1:]...)
  254. return w.replaceLocked(newCfg)
  255. }
  256. }
  257. return noopWaiter{}, nil
  258. }
  259. // Folders returns a map of folders. Folder structures should not be changed,
  260. // other than for the purpose of updating via SetFolder().
  261. func (w *wrapper) Folders() map[string]FolderConfiguration {
  262. w.mut.Lock()
  263. defer w.mut.Unlock()
  264. if w.folderMap == nil {
  265. w.folderMap = make(map[string]FolderConfiguration, len(w.cfg.Folders))
  266. for _, fld := range w.cfg.Folders {
  267. w.folderMap[fld.ID] = fld.Copy()
  268. }
  269. }
  270. return w.folderMap
  271. }
  272. // FolderList returns a slice of folders.
  273. func (w *wrapper) FolderList() []FolderConfiguration {
  274. w.mut.Lock()
  275. defer w.mut.Unlock()
  276. return w.cfg.Copy().Folders
  277. }
  278. // SetFolder adds a new folder to the configuration, or overwrites an existing
  279. // folder with the same ID.
  280. func (w *wrapper) SetFolder(fld FolderConfiguration) (Waiter, error) {
  281. w.mut.Lock()
  282. defer w.mut.Unlock()
  283. newCfg := w.cfg.Copy()
  284. for i := range newCfg.Folders {
  285. if newCfg.Folders[i].ID == fld.ID {
  286. newCfg.Folders[i] = fld
  287. return w.replaceLocked(newCfg)
  288. }
  289. }
  290. newCfg.Folders = append(newCfg.Folders, fld)
  291. return w.replaceLocked(newCfg)
  292. }
  293. // Options returns the current options configuration object.
  294. func (w *wrapper) Options() OptionsConfiguration {
  295. w.mut.Lock()
  296. defer w.mut.Unlock()
  297. return w.cfg.Options.Copy()
  298. }
  299. // SetOptions replaces the current options configuration object.
  300. func (w *wrapper) SetOptions(opts OptionsConfiguration) (Waiter, error) {
  301. w.mut.Lock()
  302. defer w.mut.Unlock()
  303. newCfg := w.cfg.Copy()
  304. newCfg.Options = opts.Copy()
  305. return w.replaceLocked(newCfg)
  306. }
  307. func (w *wrapper) LDAP() LDAPConfiguration {
  308. w.mut.Lock()
  309. defer w.mut.Unlock()
  310. return w.cfg.LDAP.Copy()
  311. }
  312. // GUI returns the current GUI configuration object.
  313. func (w *wrapper) GUI() GUIConfiguration {
  314. w.mut.Lock()
  315. defer w.mut.Unlock()
  316. return w.cfg.GUI.Copy()
  317. }
  318. // SetGUI replaces the current GUI configuration object.
  319. func (w *wrapper) SetGUI(gui GUIConfiguration) (Waiter, error) {
  320. w.mut.Lock()
  321. defer w.mut.Unlock()
  322. newCfg := w.cfg.Copy()
  323. newCfg.GUI = gui.Copy()
  324. return w.replaceLocked(newCfg)
  325. }
  326. // IgnoredDevice returns whether or not connection attempts from the given
  327. // device should be silently ignored.
  328. func (w *wrapper) IgnoredDevice(id protocol.DeviceID) bool {
  329. w.mut.Lock()
  330. defer w.mut.Unlock()
  331. for _, device := range w.cfg.IgnoredDevices {
  332. if device.ID == id {
  333. return true
  334. }
  335. }
  336. return false
  337. }
  338. // IgnoredFolder returns whether or not share attempts for the given
  339. // folder should be silently ignored.
  340. func (w *wrapper) IgnoredFolder(device protocol.DeviceID, folder string) bool {
  341. dev, ok := w.Device(device)
  342. if !ok {
  343. return false
  344. }
  345. return dev.IgnoredFolder(folder)
  346. }
  347. // Device returns the configuration for the given device and an "ok" bool.
  348. func (w *wrapper) Device(id protocol.DeviceID) (DeviceConfiguration, bool) {
  349. w.mut.Lock()
  350. defer w.mut.Unlock()
  351. for _, device := range w.cfg.Devices {
  352. if device.DeviceID == id {
  353. return device.Copy(), true
  354. }
  355. }
  356. return DeviceConfiguration{}, false
  357. }
  358. // Folder returns the configuration for the given folder and an "ok" bool.
  359. func (w *wrapper) Folder(id string) (FolderConfiguration, bool) {
  360. w.mut.Lock()
  361. defer w.mut.Unlock()
  362. for _, folder := range w.cfg.Folders {
  363. if folder.ID == id {
  364. return folder.Copy(), true
  365. }
  366. }
  367. return FolderConfiguration{}, false
  368. }
  369. // Save writes the configuration to disk, and generates a ConfigSaved event.
  370. func (w *wrapper) Save() error {
  371. w.mut.Lock()
  372. defer w.mut.Unlock()
  373. fd, err := osutil.CreateAtomic(w.path)
  374. if err != nil {
  375. l.Debugln("CreateAtomic:", err)
  376. return err
  377. }
  378. if err := w.cfg.WriteXML(fd); err != nil {
  379. l.Debugln("WriteXML:", err)
  380. fd.Close()
  381. return err
  382. }
  383. if err := fd.Close(); err != nil {
  384. l.Debugln("Close:", err)
  385. return err
  386. }
  387. w.evLogger.Log(events.ConfigSaved, w.cfg)
  388. return nil
  389. }
  390. func (w *wrapper) GlobalDiscoveryServers() []string {
  391. var servers []string
  392. for _, srv := range w.Options().GlobalAnnServers {
  393. switch srv {
  394. case "default":
  395. servers = append(servers, DefaultDiscoveryServers...)
  396. case "default-v4":
  397. servers = append(servers, DefaultDiscoveryServersV4...)
  398. case "default-v6":
  399. servers = append(servers, DefaultDiscoveryServersV6...)
  400. default:
  401. servers = append(servers, srv)
  402. }
  403. }
  404. return util.UniqueTrimmedStrings(servers)
  405. }
  406. func (w *wrapper) ListenAddresses() []string {
  407. var addresses []string
  408. for _, addr := range w.Options().ListenAddresses {
  409. switch addr {
  410. case "default":
  411. addresses = append(addresses, DefaultListenAddresses...)
  412. default:
  413. addresses = append(addresses, addr)
  414. }
  415. }
  416. return util.UniqueTrimmedStrings(addresses)
  417. }
  418. func (w *wrapper) RequiresRestart() bool {
  419. return atomic.LoadUint32(&w.requiresRestart) != 0
  420. }
  421. func (w *wrapper) setRequiresRestart() {
  422. atomic.StoreUint32(&w.requiresRestart, 1)
  423. }
  424. func (w *wrapper) MyName() string {
  425. w.mut.Lock()
  426. myID := w.cfg.MyID
  427. w.mut.Unlock()
  428. cfg, _ := w.Device(myID)
  429. return cfg.Name
  430. }
  431. func (w *wrapper) AddOrUpdatePendingDevice(device protocol.DeviceID, name, address string) {
  432. w.mut.Lock()
  433. defer w.mut.Unlock()
  434. for i := range w.cfg.PendingDevices {
  435. if w.cfg.PendingDevices[i].ID == device {
  436. w.cfg.PendingDevices[i].Time = time.Now().Round(time.Second)
  437. w.cfg.PendingDevices[i].Name = name
  438. w.cfg.PendingDevices[i].Address = address
  439. return
  440. }
  441. }
  442. w.cfg.PendingDevices = append(w.cfg.PendingDevices, ObservedDevice{
  443. Time: time.Now().Round(time.Second),
  444. ID: device,
  445. Name: name,
  446. Address: address,
  447. })
  448. }
  449. func (w *wrapper) AddOrUpdatePendingFolder(id, label string, device protocol.DeviceID) {
  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. }