folderconfiguration.go 16 KB

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