folderconfiguration.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. "encoding/json"
  11. "encoding/xml"
  12. "errors"
  13. "fmt"
  14. "log/slog"
  15. "path"
  16. "path/filepath"
  17. "slices"
  18. "strings"
  19. "time"
  20. "github.com/shirou/gopsutil/v4/disk"
  21. "github.com/syncthing/syncthing/lib/build"
  22. "github.com/syncthing/syncthing/lib/fs"
  23. "github.com/syncthing/syncthing/lib/protocol"
  24. "github.com/syncthing/syncthing/lib/structutil"
  25. )
  26. var (
  27. ErrPathNotDirectory = errors.New("folder path not a directory")
  28. ErrPathMissing = errors.New("folder path missing")
  29. ErrMarkerMissing = errors.New("folder marker missing (this indicates potential data loss, search docs/forum to get information about how to proceed)")
  30. )
  31. const (
  32. DefaultMarkerName = ".stfolder"
  33. EncryptionTokenName = "syncthing-encryption_password_token" //nolint: gosec
  34. maxConcurrentWritesDefault = 16
  35. maxConcurrentWritesLimit = 256
  36. )
  37. type FolderDeviceConfiguration struct {
  38. DeviceID protocol.DeviceID `json:"deviceID" xml:"id,attr"`
  39. IntroducedBy protocol.DeviceID `json:"introducedBy" xml:"introducedBy,attr"`
  40. EncryptionPassword string `json:"encryptionPassword" xml:"encryptionPassword"`
  41. }
  42. type FolderConfiguration struct {
  43. ID string `json:"id" xml:"id,attr" nodefault:"true"`
  44. Label string `json:"label" xml:"label,attr" restart:"false"`
  45. FilesystemType FilesystemType `json:"filesystemType" xml:"filesystemType" default:"basic"`
  46. Path string `json:"path" xml:"path,attr"`
  47. Type FolderType `json:"type" xml:"type,attr"`
  48. Devices []FolderDeviceConfiguration `json:"devices" xml:"device"`
  49. RescanIntervalS int `json:"rescanIntervalS" xml:"rescanIntervalS,attr" default:"3600"`
  50. FSWatcherEnabled bool `json:"fsWatcherEnabled" xml:"fsWatcherEnabled,attr" default:"true"`
  51. FSWatcherDelayS float64 `json:"fsWatcherDelayS" xml:"fsWatcherDelayS,attr" default:"10"`
  52. FSWatcherTimeoutS float64 `json:"fsWatcherTimeoutS" xml:"fsWatcherTimeoutS,attr"`
  53. IgnorePerms bool `json:"ignorePerms" xml:"ignorePerms,attr"`
  54. AutoNormalize bool `json:"autoNormalize" xml:"autoNormalize,attr" default:"true"`
  55. MinDiskFree Size `json:"minDiskFree" xml:"minDiskFree" default:"1 %"`
  56. Versioning VersioningConfiguration `json:"versioning" xml:"versioning"`
  57. Copiers int `json:"copiers" xml:"copiers"`
  58. PullerMaxPendingKiB int `json:"pullerMaxPendingKiB" xml:"pullerMaxPendingKiB"`
  59. Hashers int `json:"hashers" xml:"hashers"`
  60. Order PullOrder `json:"order" xml:"order"`
  61. IgnoreDelete bool `json:"ignoreDelete" xml:"ignoreDelete"`
  62. ScanProgressIntervalS int `json:"scanProgressIntervalS" xml:"scanProgressIntervalS"`
  63. PullerPauseS int `json:"pullerPauseS" xml:"pullerPauseS"`
  64. PullerDelayS float64 `json:"pullerDelayS" xml:"pullerDelayS" default:"1"`
  65. MaxConflicts int `json:"maxConflicts" xml:"maxConflicts" default:"10"`
  66. DisableSparseFiles bool `json:"disableSparseFiles" xml:"disableSparseFiles"`
  67. Paused bool `json:"paused" xml:"paused"`
  68. MarkerName string `json:"markerName" xml:"markerName"`
  69. CopyOwnershipFromParent bool `json:"copyOwnershipFromParent" xml:"copyOwnershipFromParent"`
  70. RawModTimeWindowS int `json:"modTimeWindowS" xml:"modTimeWindowS"`
  71. MaxConcurrentWrites int `json:"maxConcurrentWrites" xml:"maxConcurrentWrites" default:"0"`
  72. DisableFsync bool `json:"disableFsync" xml:"disableFsync"`
  73. BlockPullOrder BlockPullOrder `json:"blockPullOrder" xml:"blockPullOrder"`
  74. CopyRangeMethod CopyRangeMethod `json:"copyRangeMethod" xml:"copyRangeMethod" default:"standard"`
  75. CaseSensitiveFS bool `json:"caseSensitiveFS" xml:"caseSensitiveFS"`
  76. JunctionsAsDirs bool `json:"junctionsAsDirs" xml:"junctionsAsDirs"`
  77. SyncOwnership bool `json:"syncOwnership" xml:"syncOwnership"`
  78. SendOwnership bool `json:"sendOwnership" xml:"sendOwnership"`
  79. SyncXattrs bool `json:"syncXattrs" xml:"syncXattrs"`
  80. SendXattrs bool `json:"sendXattrs" xml:"sendXattrs"`
  81. XattrFilter XattrFilter `json:"xattrFilter" xml:"xattrFilter"`
  82. // Legacy deprecated
  83. DeprecatedReadOnly bool `json:"-" xml:"ro,attr,omitempty"` // Deprecated: Do not use.
  84. DeprecatedMinDiskFreePct float64 `json:"-" xml:"minDiskFreePct,omitempty"` // Deprecated: Do not use.
  85. DeprecatedPullers int `json:"-" xml:"pullers,omitempty"` // Deprecated: Do not use.
  86. DeprecatedScanOwnership bool `json:"-" xml:"scanOwnership,omitempty"` // Deprecated: Do not use.
  87. }
  88. // Extended attribute filter. This is a list of patterns to match (glob
  89. // style), each with an action (permit or deny). First match is used. If the
  90. // filter is empty, all strings are permitted. If the filter is non-empty,
  91. // the default action becomes deny. To counter this, you can use the "*"
  92. // pattern to match all strings at the end of the filter. There are also
  93. // limits on the size of accepted attributes.
  94. type XattrFilter struct {
  95. Entries []XattrFilterEntry `json:"entries" xml:"entry"`
  96. MaxSingleEntrySize int `json:"maxSingleEntrySize" xml:"maxSingleEntrySize" default:"1024"`
  97. MaxTotalSize int `json:"maxTotalSize" xml:"maxTotalSize" default:"4096"`
  98. }
  99. type XattrFilterEntry struct {
  100. Match string `json:"match" xml:"match,attr"`
  101. Permit bool `json:"permit" xml:"permit,attr"`
  102. }
  103. func (f FolderConfiguration) Copy() FolderConfiguration {
  104. c := f
  105. c.Devices = make([]FolderDeviceConfiguration, len(f.Devices))
  106. copy(c.Devices, f.Devices)
  107. c.Versioning = f.Versioning.Copy()
  108. return c
  109. }
  110. // Filesystem creates a filesystem for the path and options of this folder.
  111. // The fset parameter may be nil, in which case no mtime handling on top of
  112. // the filesystem is provided.
  113. func (f FolderConfiguration) Filesystem(extraOpts ...fs.Option) fs.Filesystem {
  114. // This is intentionally not a pointer method, because things like
  115. // cfg.Folders["default"].Filesystem(nil) should be valid.
  116. var opts []fs.Option
  117. if f.FilesystemType == FilesystemTypeBasic && f.JunctionsAsDirs {
  118. opts = append(opts, new(fs.OptionJunctionsAsDirs))
  119. }
  120. if !f.CaseSensitiveFS {
  121. opts = append(opts, new(fs.OptionDetectCaseConflicts))
  122. }
  123. opts = append(opts, extraOpts...)
  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().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()
  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()
  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(), ".")
  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()
  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) LogAttr() slog.Attr {
  240. if f.Label == "" || f.Label == f.ID {
  241. return slog.Group("folder", slog.String("id", f.ID), slog.String("type", f.Type.String()))
  242. }
  243. return slog.Group("folder", slog.String("label", f.Label), slog.String("id", f.ID), slog.String("type", f.Type.String()))
  244. }
  245. func (f *FolderConfiguration) DeviceIDs() []protocol.DeviceID {
  246. deviceIDs := make([]protocol.DeviceID, len(f.Devices))
  247. for i, n := range f.Devices {
  248. deviceIDs[i] = n.DeviceID
  249. }
  250. return deviceIDs
  251. }
  252. func (f *FolderConfiguration) prepare(myID protocol.DeviceID, existingDevices map[protocol.DeviceID]*DeviceConfiguration) {
  253. // Ensure that
  254. // - any loose devices are not present in the wrong places
  255. // - there are no duplicate devices
  256. // - we are part of the devices
  257. // - folder is not shared in trusted mode with an untrusted device
  258. f.Devices = ensureExistingDevices(f.Devices, existingDevices)
  259. f.Devices = ensureNoDuplicateFolderDevices(f.Devices)
  260. f.Devices = ensureDevicePresent(f.Devices, myID)
  261. f.Devices = ensureNoUntrustedTrustingSharing(f, f.Devices, existingDevices)
  262. slices.SortFunc(f.Devices, func(a, b FolderDeviceConfiguration) int {
  263. return a.DeviceID.Compare(b.DeviceID)
  264. })
  265. if f.RescanIntervalS > MaxRescanIntervalS {
  266. f.RescanIntervalS = MaxRescanIntervalS
  267. } else if f.RescanIntervalS < 0 {
  268. f.RescanIntervalS = 0
  269. }
  270. if f.FSWatcherDelayS <= 0 {
  271. f.FSWatcherEnabled = false
  272. f.FSWatcherDelayS = 10
  273. } else if f.FSWatcherDelayS < 0.01 {
  274. f.FSWatcherDelayS = 0.01
  275. }
  276. if f.Versioning.CleanupIntervalS > MaxRescanIntervalS {
  277. f.Versioning.CleanupIntervalS = MaxRescanIntervalS
  278. } else if f.Versioning.CleanupIntervalS < 0 {
  279. f.Versioning.CleanupIntervalS = 0
  280. }
  281. if f.MarkerName == "" {
  282. f.MarkerName = DefaultMarkerName
  283. }
  284. if f.MaxConcurrentWrites <= 0 {
  285. f.MaxConcurrentWrites = maxConcurrentWritesDefault
  286. } else if f.MaxConcurrentWrites > maxConcurrentWritesLimit {
  287. f.MaxConcurrentWrites = maxConcurrentWritesLimit
  288. }
  289. if f.Type == FolderTypeReceiveEncrypted {
  290. f.IgnorePerms = true
  291. }
  292. }
  293. // RequiresRestartOnly returns a copy with only the attributes that require
  294. // restart on change.
  295. func (f FolderConfiguration) RequiresRestartOnly() FolderConfiguration {
  296. copy := f
  297. // Manual handling for things that are not taken care of by the tag
  298. // copier, yet should not cause a restart.
  299. blank := FolderConfiguration{}
  300. copyMatchingTag(&blank, &copy, "restart", func(v string) bool {
  301. if len(v) > 0 && v != "false" {
  302. panic(fmt.Sprintf(`unexpected tag value: %s. expected untagged or "false"`, v))
  303. }
  304. return v == "false"
  305. })
  306. return copy
  307. }
  308. func (f *FolderConfiguration) Device(device protocol.DeviceID) (FolderDeviceConfiguration, bool) {
  309. for _, dev := range f.Devices {
  310. if dev.DeviceID == device {
  311. return dev, true
  312. }
  313. }
  314. return FolderDeviceConfiguration{}, false
  315. }
  316. func (f *FolderConfiguration) SharedWith(device protocol.DeviceID) bool {
  317. _, ok := f.Device(device)
  318. return ok
  319. }
  320. func (f *FolderConfiguration) CheckAvailableSpace(req uint64) error {
  321. val := f.MinDiskFree.BaseValue()
  322. if val <= 0 {
  323. return nil
  324. }
  325. fs := f.Filesystem()
  326. usage, err := fs.Usage(".")
  327. if err != nil {
  328. return nil //nolint: nilerr
  329. }
  330. if err := checkAvailableSpace(req, f.MinDiskFree, usage); err != nil {
  331. return fmt.Errorf("insufficient space in folder %v (%v): %w", f.Description(), fs.URI(), err)
  332. }
  333. return nil
  334. }
  335. func (f XattrFilter) Permit(s string) bool {
  336. if len(f.Entries) == 0 {
  337. return true
  338. }
  339. for _, entry := range f.Entries {
  340. if ok, _ := path.Match(entry.Match, s); ok {
  341. return entry.Permit
  342. }
  343. }
  344. return false
  345. }
  346. func (f XattrFilter) GetMaxSingleEntrySize() int {
  347. return f.MaxSingleEntrySize
  348. }
  349. func (f XattrFilter) GetMaxTotalSize() int {
  350. return f.MaxTotalSize
  351. }
  352. func (f *FolderConfiguration) UnmarshalJSON(data []byte) error {
  353. structutil.SetDefaults(f)
  354. // avoid recursing into this method
  355. type noCustomUnmarshal FolderConfiguration
  356. ptr := (*noCustomUnmarshal)(f)
  357. return json.Unmarshal(data, ptr)
  358. }
  359. func (f *FolderConfiguration) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
  360. structutil.SetDefaults(f)
  361. // avoid recursing into this method
  362. type noCustomUnmarshal FolderConfiguration
  363. ptr := (*noCustomUnmarshal)(f)
  364. return d.DecodeElement(ptr, &start)
  365. }