platform_common.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright (C) 2022 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 fs
  7. import (
  8. "strconv"
  9. "sync"
  10. "time"
  11. "github.com/syncthing/syncthing/lib/protocol"
  12. )
  13. // unixPlatformData is used on all platforms, because apart from being the
  14. // implementation for BasicFilesystem on Unixes it's also the implementation
  15. // in fakeFS.
  16. func unixPlatformData(fs Filesystem, name string, userCache *userCache, groupCache *groupCache) (protocol.PlatformData, error) {
  17. stat, err := fs.Lstat(name)
  18. if err != nil {
  19. return protocol.PlatformData{}, err
  20. }
  21. ownerUID := stat.Owner()
  22. ownerName := ""
  23. if user := userCache.lookup(strconv.Itoa(ownerUID)); user != nil {
  24. ownerName = user.Username
  25. } else if ownerUID == 0 {
  26. // We couldn't look up a name, but UID zero should be "root". This
  27. // fixup works around the (unlikely) situation where the ownership
  28. // is 0:0 but we can't look up a name for either uid zero or gid
  29. // zero. If that were the case we'd return a zero PlatformData which
  30. // wouldn't get serialized over the wire and the other side would
  31. // assume a lack of ownership info...
  32. ownerName = "root"
  33. }
  34. groupID := stat.Group()
  35. groupName := ""
  36. if group := groupCache.lookup(strconv.Itoa(ownerUID)); group != nil {
  37. groupName = group.Name
  38. } else if groupID == 0 {
  39. groupName = "root"
  40. }
  41. return protocol.PlatformData{
  42. Unix: &protocol.UnixData{
  43. OwnerName: ownerName,
  44. GroupName: groupName,
  45. UID: ownerUID,
  46. GID: groupID,
  47. },
  48. }, nil
  49. }
  50. type valueCache[K comparable, V any] struct {
  51. validity time.Duration
  52. fill func(K) (V, error)
  53. mut sync.Mutex
  54. cache map[K]cacheEntry[V]
  55. }
  56. type cacheEntry[V any] struct {
  57. value V
  58. when time.Time
  59. }
  60. func newValueCache[K comparable, V any](validity time.Duration, fill func(K) (V, error)) *valueCache[K, V] {
  61. return &valueCache[K, V]{
  62. validity: validity,
  63. fill: fill,
  64. cache: make(map[K]cacheEntry[V]),
  65. }
  66. }
  67. func (c *valueCache[K, V]) lookup(key K) V {
  68. c.mut.Lock()
  69. defer c.mut.Unlock()
  70. if e, ok := c.cache[key]; ok && time.Since(e.when) < c.validity {
  71. return e.value
  72. }
  73. var e cacheEntry[V]
  74. if val, err := c.fill(key); err == nil {
  75. e.value = val
  76. }
  77. e.when = time.Now()
  78. c.cache[key] = e
  79. return e.value
  80. }