folderconfiguration.go 8.6 KB

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