folderconfiguration.go 15 KB

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