folderconfiguration.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. "errors"
  9. "fmt"
  10. "path"
  11. "sort"
  12. "strings"
  13. "time"
  14. "github.com/shirou/gopsutil/v3/disk"
  15. "github.com/syncthing/syncthing/lib/build"
  16. "github.com/syncthing/syncthing/lib/db"
  17. "github.com/syncthing/syncthing/lib/fs"
  18. "github.com/syncthing/syncthing/lib/protocol"
  19. "github.com/syncthing/syncthing/lib/util"
  20. )
  21. var (
  22. ErrPathNotDirectory = errors.New("folder path not a directory")
  23. ErrPathMissing = errors.New("folder path missing")
  24. ErrMarkerMissing = errors.New("folder marker missing (this indicates potential data loss, search docs/forum to get information about how to proceed)")
  25. )
  26. const (
  27. DefaultMarkerName = ".stfolder"
  28. EncryptionTokenName = "syncthing-encryption_password_token"
  29. maxConcurrentWritesDefault = 2
  30. maxConcurrentWritesLimit = 64
  31. )
  32. func (f FolderConfiguration) Copy() FolderConfiguration {
  33. c := f
  34. c.Devices = make([]FolderDeviceConfiguration, len(f.Devices))
  35. copy(c.Devices, f.Devices)
  36. c.Versioning = f.Versioning.Copy()
  37. return c
  38. }
  39. // Filesystem creates a filesystem for the path and options of this folder.
  40. // The fset parameter may be nil, in which case no mtime handling on top of
  41. // the filesystem is provided.
  42. func (f FolderConfiguration) Filesystem(fset *db.FileSet) fs.Filesystem {
  43. // This is intentionally not a pointer method, because things like
  44. // cfg.Folders["default"].Filesystem(nil) should be valid.
  45. opts := make([]fs.Option, 0, 3)
  46. if f.FilesystemType == fs.FilesystemTypeBasic && f.JunctionsAsDirs {
  47. opts = append(opts, new(fs.OptionJunctionsAsDirs))
  48. }
  49. if !f.CaseSensitiveFS {
  50. opts = append(opts, new(fs.OptionDetectCaseConflicts))
  51. }
  52. if fset != nil {
  53. opts = append(opts, fset.MtimeOption())
  54. }
  55. return fs.NewFilesystem(f.FilesystemType, f.Path, opts...)
  56. }
  57. func (f FolderConfiguration) ModTimeWindow() time.Duration {
  58. dur := time.Duration(f.RawModTimeWindowS) * time.Second
  59. if f.RawModTimeWindowS < 1 && build.IsAndroid {
  60. if usage, err := disk.Usage(f.Filesystem(nil).URI()); err != nil {
  61. dur = 2 * time.Second
  62. l.Debugf(`Detecting FS at "%v" on android: Setting mtime window to 2s: err == "%v"`, f.Path, err)
  63. } else if strings.HasPrefix(strings.ToLower(usage.Fstype), "ext2") || strings.HasPrefix(strings.ToLower(usage.Fstype), "ext3") || strings.HasPrefix(strings.ToLower(usage.Fstype), "ext4") {
  64. l.Debugf(`Detecting FS at %v on android: Leaving mtime window at 0: usage.Fstype == "%v"`, f.Path, usage.Fstype)
  65. } else {
  66. dur = 2 * time.Second
  67. l.Debugf(`Detecting FS at "%v" on android: Setting mtime window to 2s: usage.Fstype == "%v"`, f.Path, usage.Fstype)
  68. }
  69. }
  70. return dur
  71. }
  72. func (f *FolderConfiguration) CreateMarker() error {
  73. if err := f.CheckPath(); err != ErrMarkerMissing {
  74. return err
  75. }
  76. if f.MarkerName != DefaultMarkerName {
  77. // Folder uses a non-default marker so we shouldn't mess with it.
  78. // Pretend we created it and let the subsequent health checks sort
  79. // out the actual situation.
  80. return nil
  81. }
  82. permBits := fs.FileMode(0777)
  83. if build.IsWindows {
  84. // Windows has no umask so we must chose a safer set of bits to
  85. // begin with.
  86. permBits = 0700
  87. }
  88. fs := f.Filesystem(nil)
  89. err := fs.Mkdir(DefaultMarkerName, permBits)
  90. if err != nil {
  91. return err
  92. }
  93. if dir, err := fs.Open("."); err != nil {
  94. l.Debugln("folder marker: open . failed:", err)
  95. } else if err := dir.Sync(); err != nil {
  96. l.Debugln("folder marker: fsync . failed:", err)
  97. }
  98. fs.Hide(DefaultMarkerName)
  99. return nil
  100. }
  101. // CheckPath returns nil if the folder root exists and contains the marker file
  102. func (f *FolderConfiguration) CheckPath() error {
  103. fi, err := f.Filesystem(nil).Stat(".")
  104. if err != nil {
  105. if !fs.IsNotExist(err) {
  106. return err
  107. }
  108. return ErrPathMissing
  109. }
  110. // Users might have the root directory as a symlink or reparse point.
  111. // Furthermore, OneDrive bullcrap uses a magic reparse point to the cloudz...
  112. // Yet it's impossible for this to happen, as filesystem adds a trailing
  113. // path separator to the root, so even if you point the filesystem at a file
  114. // Stat ends up calling stat on C:\dir\file\ which, fails with "is not a directory"
  115. // in the error check above, and we don't even get to here.
  116. if !fi.IsDir() && !fi.IsSymlink() {
  117. return ErrPathNotDirectory
  118. }
  119. _, err = f.Filesystem(nil).Stat(f.MarkerName)
  120. if err != nil {
  121. if !fs.IsNotExist(err) {
  122. return err
  123. }
  124. return ErrMarkerMissing
  125. }
  126. return nil
  127. }
  128. func (f *FolderConfiguration) CreateRoot() (err error) {
  129. // Directory permission bits. Will be filtered down to something
  130. // sane by umask on Unixes.
  131. permBits := fs.FileMode(0777)
  132. if build.IsWindows {
  133. // Windows has no umask so we must chose a safer set of bits to
  134. // begin with.
  135. permBits = 0700
  136. }
  137. filesystem := f.Filesystem(nil)
  138. if _, err = filesystem.Stat("."); fs.IsNotExist(err) {
  139. err = filesystem.MkdirAll(".", permBits)
  140. }
  141. return err
  142. }
  143. func (f FolderConfiguration) Description() string {
  144. if f.Label == "" {
  145. return f.ID
  146. }
  147. return fmt.Sprintf("%q (%s)", f.Label, f.ID)
  148. }
  149. func (f *FolderConfiguration) DeviceIDs() []protocol.DeviceID {
  150. deviceIDs := make([]protocol.DeviceID, len(f.Devices))
  151. for i, n := range f.Devices {
  152. deviceIDs[i] = n.DeviceID
  153. }
  154. return deviceIDs
  155. }
  156. func (f *FolderConfiguration) prepare(myID protocol.DeviceID, existingDevices map[protocol.DeviceID]bool) {
  157. // Ensure that
  158. // - any loose devices are not present in the wrong places
  159. // - there are no duplicate devices
  160. // - we are part of the devices
  161. f.Devices = ensureExistingDevices(f.Devices, existingDevices)
  162. f.Devices = ensureNoDuplicateFolderDevices(f.Devices)
  163. f.Devices = ensureDevicePresent(f.Devices, myID)
  164. sort.Slice(f.Devices, func(a, b int) bool {
  165. return f.Devices[a].DeviceID.Compare(f.Devices[b].DeviceID) == -1
  166. })
  167. if f.RescanIntervalS > MaxRescanIntervalS {
  168. f.RescanIntervalS = MaxRescanIntervalS
  169. } else if f.RescanIntervalS < 0 {
  170. f.RescanIntervalS = 0
  171. }
  172. if f.FSWatcherDelayS <= 0 {
  173. f.FSWatcherEnabled = false
  174. f.FSWatcherDelayS = 10
  175. }
  176. if f.Versioning.CleanupIntervalS > MaxRescanIntervalS {
  177. f.Versioning.CleanupIntervalS = MaxRescanIntervalS
  178. } else if f.Versioning.CleanupIntervalS < 0 {
  179. f.Versioning.CleanupIntervalS = 0
  180. }
  181. if f.WeakHashThresholdPct == 0 {
  182. f.WeakHashThresholdPct = 25
  183. }
  184. if f.MarkerName == "" {
  185. f.MarkerName = DefaultMarkerName
  186. }
  187. if f.MaxConcurrentWrites <= 0 {
  188. f.MaxConcurrentWrites = maxConcurrentWritesDefault
  189. } else if f.MaxConcurrentWrites > maxConcurrentWritesLimit {
  190. f.MaxConcurrentWrites = maxConcurrentWritesLimit
  191. }
  192. if f.Type == FolderTypeReceiveEncrypted {
  193. f.DisableTempIndexes = true
  194. f.IgnorePerms = true
  195. }
  196. }
  197. // RequiresRestartOnly returns a copy with only the attributes that require
  198. // restart on change.
  199. func (f FolderConfiguration) RequiresRestartOnly() FolderConfiguration {
  200. copy := f
  201. // Manual handling for things that are not taken care of by the tag
  202. // copier, yet should not cause a restart.
  203. blank := FolderConfiguration{}
  204. util.CopyMatchingTag(&blank, &copy, "restart", func(v string) bool {
  205. if len(v) > 0 && v != "false" {
  206. panic(fmt.Sprintf(`unexpected tag value: %s. expected untagged or "false"`, v))
  207. }
  208. return v == "false"
  209. })
  210. return copy
  211. }
  212. func (f *FolderConfiguration) Device(device protocol.DeviceID) (FolderDeviceConfiguration, bool) {
  213. for _, dev := range f.Devices {
  214. if dev.DeviceID == device {
  215. return dev, true
  216. }
  217. }
  218. return FolderDeviceConfiguration{}, false
  219. }
  220. func (f *FolderConfiguration) SharedWith(device protocol.DeviceID) bool {
  221. _, ok := f.Device(device)
  222. return ok
  223. }
  224. func (f *FolderConfiguration) CheckAvailableSpace(req uint64) error {
  225. val := f.MinDiskFree.BaseValue()
  226. if val <= 0 {
  227. return nil
  228. }
  229. fs := f.Filesystem(nil)
  230. usage, err := fs.Usage(".")
  231. if err != nil {
  232. return nil
  233. }
  234. if err := checkAvailableSpace(req, f.MinDiskFree, usage); err != nil {
  235. return fmt.Errorf("insufficient space in folder %v (%v): %w", f.Description(), fs.URI(), err)
  236. }
  237. return nil
  238. }
  239. func (f XattrFilter) Permit(s string) bool {
  240. if len(f.Entries) == 0 {
  241. return true
  242. }
  243. for _, entry := range f.Entries {
  244. if ok, _ := path.Match(entry.Match, s); ok {
  245. return entry.Permit
  246. }
  247. }
  248. return false
  249. }
  250. func (f XattrFilter) GetMaxSingleEntrySize() int {
  251. return f.MaxSingleEntrySize
  252. }
  253. func (f XattrFilter) GetMaxTotalSize() int {
  254. return f.MaxTotalSize
  255. }