folderconfiguration.go 15 KB

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