folderconfiguration.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. )
  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(0o777)
  83. if build.IsWindows {
  84. // Windows has no umask so we must chose a safer set of bits to
  85. // begin with.
  86. permBits = 0o700
  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. return f.checkFilesystemPath(f.Filesystem(nil), ".")
  104. }
  105. func (f *FolderConfiguration) checkFilesystemPath(ffs fs.Filesystem, path string) error {
  106. fi, err := ffs.Stat(path)
  107. if err != nil {
  108. if !fs.IsNotExist(err) {
  109. return err
  110. }
  111. return ErrPathMissing
  112. }
  113. // Users might have the root directory as a symlink or reparse point.
  114. // Furthermore, OneDrive bullcrap uses a magic reparse point to the cloudz...
  115. // Yet it's impossible for this to happen, as filesystem adds a trailing
  116. // path separator to the root, so even if you point the filesystem at a file
  117. // Stat ends up calling stat on C:\dir\file\ which, fails with "is not a directory"
  118. // in the error check above, and we don't even get to here.
  119. if !fi.IsDir() && !fi.IsSymlink() {
  120. return ErrPathNotDirectory
  121. }
  122. _, err = ffs.Stat(filepath.Join(path, f.MarkerName))
  123. if err != nil {
  124. if !fs.IsNotExist(err) {
  125. return err
  126. }
  127. return ErrMarkerMissing
  128. }
  129. return nil
  130. }
  131. func (f *FolderConfiguration) CreateRoot() (err error) {
  132. // Directory permission bits. Will be filtered down to something
  133. // sane by umask on Unixes.
  134. permBits := fs.FileMode(0o777)
  135. if build.IsWindows {
  136. // Windows has no umask so we must chose a safer set of bits to
  137. // begin with.
  138. permBits = 0o700
  139. }
  140. filesystem := f.Filesystem(nil)
  141. if _, err = filesystem.Stat("."); fs.IsNotExist(err) {
  142. err = filesystem.MkdirAll(".", permBits)
  143. }
  144. return err
  145. }
  146. func (f FolderConfiguration) Description() string {
  147. if f.Label == "" {
  148. return f.ID
  149. }
  150. return fmt.Sprintf("%q (%s)", f.Label, f.ID)
  151. }
  152. func (f *FolderConfiguration) DeviceIDs() []protocol.DeviceID {
  153. deviceIDs := make([]protocol.DeviceID, len(f.Devices))
  154. for i, n := range f.Devices {
  155. deviceIDs[i] = n.DeviceID
  156. }
  157. return deviceIDs
  158. }
  159. func (f *FolderConfiguration) prepare(myID protocol.DeviceID, existingDevices map[protocol.DeviceID]*DeviceConfiguration) {
  160. // Ensure that
  161. // - any loose devices are not present in the wrong places
  162. // - there are no duplicate devices
  163. // - we are part of the devices
  164. // - folder is not shared in trusted mode with an untrusted device
  165. f.Devices = ensureExistingDevices(f.Devices, existingDevices)
  166. f.Devices = ensureNoDuplicateFolderDevices(f.Devices)
  167. f.Devices = ensureDevicePresent(f.Devices, myID)
  168. f.Devices = ensureNoUntrustedTrustingSharing(f, f.Devices, existingDevices)
  169. sort.Slice(f.Devices, func(a, b int) bool {
  170. return f.Devices[a].DeviceID.Compare(f.Devices[b].DeviceID) == -1
  171. })
  172. if f.RescanIntervalS > MaxRescanIntervalS {
  173. f.RescanIntervalS = MaxRescanIntervalS
  174. } else if f.RescanIntervalS < 0 {
  175. f.RescanIntervalS = 0
  176. }
  177. if f.FSWatcherDelayS <= 0 {
  178. f.FSWatcherEnabled = false
  179. f.FSWatcherDelayS = 10
  180. } else if f.FSWatcherDelayS < 0.01 {
  181. f.FSWatcherDelayS = 0.01
  182. }
  183. if f.Versioning.CleanupIntervalS > MaxRescanIntervalS {
  184. f.Versioning.CleanupIntervalS = MaxRescanIntervalS
  185. } else if f.Versioning.CleanupIntervalS < 0 {
  186. f.Versioning.CleanupIntervalS = 0
  187. }
  188. if f.WeakHashThresholdPct == 0 {
  189. f.WeakHashThresholdPct = 25
  190. }
  191. if f.MarkerName == "" {
  192. f.MarkerName = DefaultMarkerName
  193. }
  194. if f.MaxConcurrentWrites <= 0 {
  195. f.MaxConcurrentWrites = maxConcurrentWritesDefault
  196. } else if f.MaxConcurrentWrites > maxConcurrentWritesLimit {
  197. f.MaxConcurrentWrites = maxConcurrentWritesLimit
  198. }
  199. if f.Type == FolderTypeReceiveEncrypted {
  200. f.DisableTempIndexes = true
  201. f.IgnorePerms = true
  202. }
  203. }
  204. // RequiresRestartOnly returns a copy with only the attributes that require
  205. // restart on change.
  206. func (f FolderConfiguration) RequiresRestartOnly() FolderConfiguration {
  207. copy := f
  208. // Manual handling for things that are not taken care of by the tag
  209. // copier, yet should not cause a restart.
  210. blank := FolderConfiguration{}
  211. copyMatchingTag(&blank, &copy, "restart", func(v string) bool {
  212. if len(v) > 0 && v != "false" {
  213. panic(fmt.Sprintf(`unexpected tag value: %s. expected untagged or "false"`, v))
  214. }
  215. return v == "false"
  216. })
  217. return copy
  218. }
  219. func (f *FolderConfiguration) Device(device protocol.DeviceID) (FolderDeviceConfiguration, bool) {
  220. for _, dev := range f.Devices {
  221. if dev.DeviceID == device {
  222. return dev, true
  223. }
  224. }
  225. return FolderDeviceConfiguration{}, false
  226. }
  227. func (f *FolderConfiguration) SharedWith(device protocol.DeviceID) bool {
  228. _, ok := f.Device(device)
  229. return ok
  230. }
  231. func (f *FolderConfiguration) CheckAvailableSpace(req uint64) error {
  232. val := f.MinDiskFree.BaseValue()
  233. if val <= 0 {
  234. return nil
  235. }
  236. fs := f.Filesystem(nil)
  237. usage, err := fs.Usage(".")
  238. if err != nil {
  239. return nil
  240. }
  241. if err := checkAvailableSpace(req, f.MinDiskFree, usage); err != nil {
  242. return fmt.Errorf("insufficient space in folder %v (%v): %w", f.Description(), fs.URI(), err)
  243. }
  244. return nil
  245. }
  246. func (f XattrFilter) Permit(s string) bool {
  247. if len(f.Entries) == 0 {
  248. return true
  249. }
  250. for _, entry := range f.Entries {
  251. if ok, _ := path.Match(entry.Match, s); ok {
  252. return entry.Permit
  253. }
  254. }
  255. return false
  256. }
  257. func (f XattrFilter) GetMaxSingleEntrySize() int {
  258. return f.MaxSingleEntrySize
  259. }
  260. func (f XattrFilter) GetMaxTotalSize() int {
  261. return f.MaxTotalSize
  262. }