folderconfiguration.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. "bytes"
  9. "crypto/sha256"
  10. "errors"
  11. "fmt"
  12. "path"
  13. "path/filepath"
  14. "sort"
  15. "strings"
  16. "time"
  17. "github.com/shirou/gopsutil/v4/disk"
  18. "github.com/syncthing/syncthing/lib/build"
  19. "github.com/syncthing/syncthing/lib/db"
  20. "github.com/syncthing/syncthing/lib/fs"
  21. "github.com/syncthing/syncthing/lib/protocol"
  22. )
  23. var (
  24. ErrPathNotDirectory = errors.New("folder path not a directory")
  25. ErrPathMissing = errors.New("folder path missing")
  26. ErrMarkerMissing = errors.New("folder marker missing (this indicates potential data loss, search docs/forum to get information about how to proceed)")
  27. )
  28. const (
  29. DefaultMarkerName = ".stfolder"
  30. EncryptionTokenName = "syncthing-encryption_password_token" //nolint: gosec
  31. maxConcurrentWritesDefault = 2
  32. maxConcurrentWritesLimit = 64
  33. )
  34. type FolderDeviceConfiguration struct {
  35. DeviceID protocol.DeviceID `json:"deviceID" xml:"id,attr"`
  36. IntroducedBy protocol.DeviceID `json:"introducedBy" xml:"introducedBy,attr"`
  37. EncryptionPassword string `json:"encryptionPassword" xml:"encryptionPassword"`
  38. }
  39. type FolderConfiguration struct {
  40. ID string `json:"id" xml:"id,attr" nodefault:"true"`
  41. Label string `json:"label" xml:"label,attr" restart:"false"`
  42. FilesystemType FilesystemType `json:"filesystemType" xml:"filesystemType" default:"basic"`
  43. Path string `json:"path" xml:"path,attr" default:"~"`
  44. Type FolderType `json:"type" xml:"type,attr"`
  45. Devices []FolderDeviceConfiguration `json:"devices" xml:"device"`
  46. RescanIntervalS int `json:"rescanIntervalS" xml:"rescanIntervalS,attr" default:"3600"`
  47. FSWatcherEnabled bool `json:"fsWatcherEnabled" xml:"fsWatcherEnabled,attr" default:"true"`
  48. FSWatcherDelayS float64 `json:"fsWatcherDelayS" xml:"fsWatcherDelayS,attr" default:"10"`
  49. FSWatcherTimeoutS float64 `json:"fsWatcherTimeoutS" xml:"fsWatcherTimeoutS,attr"`
  50. IgnorePerms bool `json:"ignorePerms" xml:"ignorePerms,attr"`
  51. AutoNormalize bool `json:"autoNormalize" xml:"autoNormalize,attr" default:"true"`
  52. MinDiskFree Size `json:"minDiskFree" xml:"minDiskFree" default:"1 %"`
  53. Versioning VersioningConfiguration `json:"versioning" xml:"versioning"`
  54. Copiers int `json:"copiers" xml:"copiers"`
  55. PullerMaxPendingKiB int `json:"pullerMaxPendingKiB" xml:"pullerMaxPendingKiB"`
  56. Hashers int `json:"hashers" xml:"hashers"`
  57. Order PullOrder `json:"order" xml:"order"`
  58. IgnoreDelete bool `json:"ignoreDelete" xml:"ignoreDelete"`
  59. ScanProgressIntervalS int `json:"scanProgressIntervalS" xml:"scanProgressIntervalS"`
  60. PullerPauseS int `json:"pullerPauseS" xml:"pullerPauseS"`
  61. MaxConflicts int `json:"maxConflicts" xml:"maxConflicts" default:"10"`
  62. DisableSparseFiles bool `json:"disableSparseFiles" xml:"disableSparseFiles"`
  63. DisableTempIndexes bool `json:"disableTempIndexes" xml:"disableTempIndexes"`
  64. Paused bool `json:"paused" xml:"paused"`
  65. WeakHashThresholdPct int `json:"weakHashThresholdPct" xml:"weakHashThresholdPct"`
  66. MarkerName string `json:"markerName" xml:"markerName"`
  67. CopyOwnershipFromParent bool `json:"copyOwnershipFromParent" xml:"copyOwnershipFromParent"`
  68. RawModTimeWindowS int `json:"modTimeWindowS" xml:"modTimeWindowS"`
  69. MaxConcurrentWrites int `json:"maxConcurrentWrites" xml:"maxConcurrentWrites" default:"2"`
  70. DisableFsync bool `json:"disableFsync" xml:"disableFsync"`
  71. BlockPullOrder BlockPullOrder `json:"blockPullOrder" xml:"blockPullOrder"`
  72. CopyRangeMethod CopyRangeMethod `json:"copyRangeMethod" xml:"copyRangeMethod" default:"standard"`
  73. CaseSensitiveFS bool `json:"caseSensitiveFS" xml:"caseSensitiveFS"`
  74. JunctionsAsDirs bool `json:"junctionsAsDirs" xml:"junctionsAsDirs"`
  75. SyncOwnership bool `json:"syncOwnership" xml:"syncOwnership"`
  76. SendOwnership bool `json:"sendOwnership" xml:"sendOwnership"`
  77. SyncXattrs bool `json:"syncXattrs" xml:"syncXattrs"`
  78. SendXattrs bool `json:"sendXattrs" xml:"sendXattrs"`
  79. XattrFilter XattrFilter `json:"xattrFilter" xml:"xattrFilter"`
  80. // Legacy deprecated
  81. DeprecatedReadOnly bool `json:"-" xml:"ro,attr,omitempty"` // Deprecated: Do not use.
  82. DeprecatedMinDiskFreePct float64 `json:"-" xml:"minDiskFreePct,omitempty"` // Deprecated: Do not use.
  83. DeprecatedPullers int `json:"-" xml:"pullers,omitempty"` // Deprecated: Do not use.
  84. DeprecatedScanOwnership bool `json:"-" xml:"scanOwnership,omitempty"` // Deprecated: Do not use.
  85. }
  86. // Extended attribute filter. This is a list of patterns to match (glob
  87. // style), each with an action (permit or deny). First match is used. If the
  88. // filter is empty, all strings are permitted. If the filter is non-empty,
  89. // the default action becomes deny. To counter this, you can use the "*"
  90. // pattern to match all strings at the end of the filter. There are also
  91. // limits on the size of accepted attributes.
  92. type XattrFilter struct {
  93. Entries []XattrFilterEntry `json:"entries" xml:"entry"`
  94. MaxSingleEntrySize int `json:"maxSingleEntrySize" xml:"maxSingleEntrySize" default:"1024"`
  95. MaxTotalSize int `json:"maxTotalSize" xml:"maxTotalSize" default:"4096"`
  96. }
  97. type XattrFilterEntry struct {
  98. Match string `json:"match" xml:"match,attr"`
  99. Permit bool `json:"permit" xml:"permit,attr"`
  100. }
  101. func (f FolderConfiguration) Copy() FolderConfiguration {
  102. c := f
  103. c.Devices = make([]FolderDeviceConfiguration, len(f.Devices))
  104. copy(c.Devices, f.Devices)
  105. c.Versioning = f.Versioning.Copy()
  106. return c
  107. }
  108. // Filesystem creates a filesystem for the path and options of this folder.
  109. // The fset parameter may be nil, in which case no mtime handling on top of
  110. // the filesystem is provided.
  111. func (f FolderConfiguration) Filesystem(fset *db.FileSet) fs.Filesystem {
  112. // This is intentionally not a pointer method, because things like
  113. // cfg.Folders["default"].Filesystem(nil) should be valid.
  114. opts := make([]fs.Option, 0, 3)
  115. if f.FilesystemType == FilesystemTypeBasic && f.JunctionsAsDirs {
  116. opts = append(opts, new(fs.OptionJunctionsAsDirs))
  117. }
  118. if !f.CaseSensitiveFS {
  119. opts = append(opts, new(fs.OptionDetectCaseConflicts))
  120. }
  121. if fset != nil {
  122. opts = append(opts, fset.MtimeOption())
  123. }
  124. return fs.NewFilesystem(f.FilesystemType.ToFS(), f.Path, opts...)
  125. }
  126. func (f FolderConfiguration) ModTimeWindow() time.Duration {
  127. dur := time.Duration(f.RawModTimeWindowS) * time.Second
  128. if f.RawModTimeWindowS < 1 && build.IsAndroid {
  129. if usage, err := disk.Usage(f.Filesystem(nil).URI()); err != nil {
  130. dur = 2 * time.Second
  131. l.Debugf(`Detecting FS at "%v" on android: Setting mtime window to 2s: err == "%v"`, f.Path, err)
  132. } else if strings.HasPrefix(strings.ToLower(usage.Fstype), "ext2") || strings.HasPrefix(strings.ToLower(usage.Fstype), "ext3") || strings.HasPrefix(strings.ToLower(usage.Fstype), "ext4") {
  133. l.Debugf(`Detecting FS at %v on android: Leaving mtime window at 0: usage.Fstype == "%v"`, f.Path, usage.Fstype)
  134. } else {
  135. dur = 2 * time.Second
  136. l.Debugf(`Detecting FS at "%v" on android: Setting mtime window to 2s: usage.Fstype == "%v"`, f.Path, usage.Fstype)
  137. }
  138. }
  139. return dur
  140. }
  141. func (f *FolderConfiguration) CreateMarker() error {
  142. if err := f.CheckPath(); err != ErrMarkerMissing {
  143. return err
  144. }
  145. if f.MarkerName != DefaultMarkerName {
  146. // Folder uses a non-default marker so we shouldn't mess with it.
  147. // Pretend we created it and let the subsequent health checks sort
  148. // out the actual situation.
  149. return nil
  150. }
  151. ffs := f.Filesystem(nil)
  152. // Create the marker as a directory
  153. err := ffs.Mkdir(DefaultMarkerName, 0o755)
  154. if err != nil {
  155. return err
  156. }
  157. // Create a file inside it, reducing the risk of the marker directory
  158. // being removed by automated cleanup tools.
  159. markerFile := filepath.Join(DefaultMarkerName, f.markerFilename())
  160. if err := fs.WriteFile(ffs, markerFile, f.markerContents(), 0o644); err != nil {
  161. return err
  162. }
  163. // Sync & hide the containing directory
  164. if dir, err := ffs.Open("."); err != nil {
  165. l.Debugln("folder marker: open . failed:", err)
  166. } else if err := dir.Sync(); err != nil {
  167. l.Debugln("folder marker: fsync . failed:", err)
  168. }
  169. ffs.Hide(DefaultMarkerName)
  170. return nil
  171. }
  172. func (f *FolderConfiguration) RemoveMarker() error {
  173. ffs := f.Filesystem(nil)
  174. _ = ffs.Remove(filepath.Join(DefaultMarkerName, f.markerFilename()))
  175. return ffs.Remove(DefaultMarkerName)
  176. }
  177. func (f *FolderConfiguration) markerFilename() string {
  178. h := sha256.Sum256([]byte(f.ID))
  179. return fmt.Sprintf("syncthing-folder-%x.txt", h[:3])
  180. }
  181. func (f *FolderConfiguration) markerContents() []byte {
  182. var buf bytes.Buffer
  183. buf.WriteString("# This directory is a Syncthing folder marker.\n# Do not delete.\n\n")
  184. fmt.Fprintf(&buf, "folderID: %s\n", f.ID)
  185. fmt.Fprintf(&buf, "created: %s\n", time.Now().Format(time.RFC3339))
  186. return buf.Bytes()
  187. }
  188. // CheckPath returns nil if the folder root exists and contains the marker file
  189. func (f *FolderConfiguration) CheckPath() error {
  190. return f.checkFilesystemPath(f.Filesystem(nil), ".")
  191. }
  192. func (f *FolderConfiguration) checkFilesystemPath(ffs fs.Filesystem, path string) error {
  193. fi, err := ffs.Stat(path)
  194. if err != nil {
  195. if !fs.IsNotExist(err) {
  196. return err
  197. }
  198. return ErrPathMissing
  199. }
  200. // Users might have the root directory as a symlink or reparse point.
  201. // Furthermore, OneDrive bullcrap uses a magic reparse point to the cloudz...
  202. // Yet it's impossible for this to happen, as filesystem adds a trailing
  203. // path separator to the root, so even if you point the filesystem at a file
  204. // Stat ends up calling stat on C:\dir\file\ which, fails with "is not a directory"
  205. // in the error check above, and we don't even get to here.
  206. if !fi.IsDir() && !fi.IsSymlink() {
  207. return ErrPathNotDirectory
  208. }
  209. _, err = ffs.Stat(filepath.Join(path, f.MarkerName))
  210. if err != nil {
  211. if !fs.IsNotExist(err) {
  212. return err
  213. }
  214. return ErrMarkerMissing
  215. }
  216. return nil
  217. }
  218. func (f *FolderConfiguration) CreateRoot() (err error) {
  219. // Directory permission bits. Will be filtered down to something
  220. // sane by umask on Unixes.
  221. permBits := fs.FileMode(0o777)
  222. if build.IsWindows {
  223. // Windows has no umask so we must chose a safer set of bits to
  224. // begin with.
  225. permBits = 0o700
  226. }
  227. filesystem := f.Filesystem(nil)
  228. if _, err = filesystem.Stat("."); fs.IsNotExist(err) {
  229. err = filesystem.MkdirAll(".", permBits)
  230. }
  231. return err
  232. }
  233. func (f FolderConfiguration) Description() string {
  234. if f.Label == "" {
  235. return f.ID
  236. }
  237. return fmt.Sprintf("%q (%s)", f.Label, f.ID)
  238. }
  239. func (f *FolderConfiguration) DeviceIDs() []protocol.DeviceID {
  240. deviceIDs := make([]protocol.DeviceID, len(f.Devices))
  241. for i, n := range f.Devices {
  242. deviceIDs[i] = n.DeviceID
  243. }
  244. return deviceIDs
  245. }
  246. func (f *FolderConfiguration) prepare(myID protocol.DeviceID, existingDevices map[protocol.DeviceID]*DeviceConfiguration) {
  247. // Ensure that
  248. // - any loose devices are not present in the wrong places
  249. // - there are no duplicate devices
  250. // - we are part of the devices
  251. // - folder is not shared in trusted mode with an untrusted device
  252. f.Devices = ensureExistingDevices(f.Devices, existingDevices)
  253. f.Devices = ensureNoDuplicateFolderDevices(f.Devices)
  254. f.Devices = ensureDevicePresent(f.Devices, myID)
  255. f.Devices = ensureNoUntrustedTrustingSharing(f, f.Devices, existingDevices)
  256. sort.Slice(f.Devices, func(a, b int) bool {
  257. return f.Devices[a].DeviceID.Compare(f.Devices[b].DeviceID) == -1
  258. })
  259. if f.RescanIntervalS > MaxRescanIntervalS {
  260. f.RescanIntervalS = MaxRescanIntervalS
  261. } else if f.RescanIntervalS < 0 {
  262. f.RescanIntervalS = 0
  263. }
  264. if f.FSWatcherDelayS <= 0 {
  265. f.FSWatcherEnabled = false
  266. f.FSWatcherDelayS = 10
  267. } else if f.FSWatcherDelayS < 0.01 {
  268. f.FSWatcherDelayS = 0.01
  269. }
  270. if f.Versioning.CleanupIntervalS > MaxRescanIntervalS {
  271. f.Versioning.CleanupIntervalS = MaxRescanIntervalS
  272. } else if f.Versioning.CleanupIntervalS < 0 {
  273. f.Versioning.CleanupIntervalS = 0
  274. }
  275. if f.WeakHashThresholdPct == 0 {
  276. f.WeakHashThresholdPct = 25
  277. }
  278. if f.MarkerName == "" {
  279. f.MarkerName = DefaultMarkerName
  280. }
  281. if f.MaxConcurrentWrites <= 0 {
  282. f.MaxConcurrentWrites = maxConcurrentWritesDefault
  283. } else if f.MaxConcurrentWrites > maxConcurrentWritesLimit {
  284. f.MaxConcurrentWrites = maxConcurrentWritesLimit
  285. }
  286. if f.Type == FolderTypeReceiveEncrypted {
  287. f.DisableTempIndexes = true
  288. f.IgnorePerms = true
  289. }
  290. }
  291. // RequiresRestartOnly returns a copy with only the attributes that require
  292. // restart on change.
  293. func (f FolderConfiguration) RequiresRestartOnly() FolderConfiguration {
  294. copy := f
  295. // Manual handling for things that are not taken care of by the tag
  296. // copier, yet should not cause a restart.
  297. blank := FolderConfiguration{}
  298. copyMatchingTag(&blank, &copy, "restart", func(v string) bool {
  299. if len(v) > 0 && v != "false" {
  300. panic(fmt.Sprintf(`unexpected tag value: %s. expected untagged or "false"`, v))
  301. }
  302. return v == "false"
  303. })
  304. return copy
  305. }
  306. func (f *FolderConfiguration) Device(device protocol.DeviceID) (FolderDeviceConfiguration, bool) {
  307. for _, dev := range f.Devices {
  308. if dev.DeviceID == device {
  309. return dev, true
  310. }
  311. }
  312. return FolderDeviceConfiguration{}, false
  313. }
  314. func (f *FolderConfiguration) SharedWith(device protocol.DeviceID) bool {
  315. _, ok := f.Device(device)
  316. return ok
  317. }
  318. func (f *FolderConfiguration) CheckAvailableSpace(req uint64) error {
  319. val := f.MinDiskFree.BaseValue()
  320. if val <= 0 {
  321. return nil
  322. }
  323. fs := f.Filesystem(nil)
  324. usage, err := fs.Usage(".")
  325. if err != nil {
  326. return nil //nolint: nilerr
  327. }
  328. if err := checkAvailableSpace(req, f.MinDiskFree, usage); err != nil {
  329. return fmt.Errorf("insufficient space in folder %v (%v): %w", f.Description(), fs.URI(), err)
  330. }
  331. return nil
  332. }
  333. func (f XattrFilter) Permit(s string) bool {
  334. if len(f.Entries) == 0 {
  335. return true
  336. }
  337. for _, entry := range f.Entries {
  338. if ok, _ := path.Match(entry.Match, s); ok {
  339. return entry.Permit
  340. }
  341. }
  342. return false
  343. }
  344. func (f XattrFilter) GetMaxSingleEntrySize() int {
  345. return f.MaxSingleEntrySize
  346. }
  347. func (f XattrFilter) GetMaxTotalSize() int {
  348. return f.MaxTotalSize
  349. }