folderconfiguration.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. "sort"
  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 = 2
  34. maxConcurrentWritesLimit = 64
  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. DisableTempIndexes bool `json:"disableTempIndexes" xml:"disableTempIndexes"`
  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:"2"`
  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) 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.MarkerName == "" {
  276. f.MarkerName = DefaultMarkerName
  277. }
  278. if f.MaxConcurrentWrites <= 0 {
  279. f.MaxConcurrentWrites = maxConcurrentWritesDefault
  280. } else if f.MaxConcurrentWrites > maxConcurrentWritesLimit {
  281. f.MaxConcurrentWrites = maxConcurrentWritesLimit
  282. }
  283. if f.Type == FolderTypeReceiveEncrypted {
  284. f.DisableTempIndexes = true
  285. f.IgnorePerms = true
  286. }
  287. }
  288. // RequiresRestartOnly returns a copy with only the attributes that require
  289. // restart on change.
  290. func (f FolderConfiguration) RequiresRestartOnly() FolderConfiguration {
  291. copy := f
  292. // Manual handling for things that are not taken care of by the tag
  293. // copier, yet should not cause a restart.
  294. blank := FolderConfiguration{}
  295. copyMatchingTag(&blank, &copy, "restart", func(v string) bool {
  296. if len(v) > 0 && v != "false" {
  297. panic(fmt.Sprintf(`unexpected tag value: %s. expected untagged or "false"`, v))
  298. }
  299. return v == "false"
  300. })
  301. return copy
  302. }
  303. func (f *FolderConfiguration) Device(device protocol.DeviceID) (FolderDeviceConfiguration, bool) {
  304. for _, dev := range f.Devices {
  305. if dev.DeviceID == device {
  306. return dev, true
  307. }
  308. }
  309. return FolderDeviceConfiguration{}, false
  310. }
  311. func (f *FolderConfiguration) SharedWith(device protocol.DeviceID) bool {
  312. _, ok := f.Device(device)
  313. return ok
  314. }
  315. func (f *FolderConfiguration) CheckAvailableSpace(req uint64) error {
  316. val := f.MinDiskFree.BaseValue()
  317. if val <= 0 {
  318. return nil
  319. }
  320. fs := f.Filesystem()
  321. usage, err := fs.Usage(".")
  322. if err != nil {
  323. return nil //nolint: nilerr
  324. }
  325. if err := checkAvailableSpace(req, f.MinDiskFree, usage); err != nil {
  326. return fmt.Errorf("insufficient space in folder %v (%v): %w", f.Description(), fs.URI(), err)
  327. }
  328. return nil
  329. }
  330. func (f XattrFilter) Permit(s string) bool {
  331. if len(f.Entries) == 0 {
  332. return true
  333. }
  334. for _, entry := range f.Entries {
  335. if ok, _ := path.Match(entry.Match, s); ok {
  336. return entry.Permit
  337. }
  338. }
  339. return false
  340. }
  341. func (f XattrFilter) GetMaxSingleEntrySize() int {
  342. return f.MaxSingleEntrySize
  343. }
  344. func (f XattrFilter) GetMaxTotalSize() int {
  345. return f.MaxTotalSize
  346. }
  347. func (f *FolderConfiguration) UnmarshalJSON(data []byte) error {
  348. structutil.SetDefaults(f)
  349. // avoid recursing into this method
  350. type noCustomUnmarshal FolderConfiguration
  351. ptr := (*noCustomUnmarshal)(f)
  352. return json.Unmarshal(data, ptr)
  353. }
  354. func (f *FolderConfiguration) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
  355. structutil.SetDefaults(f)
  356. // avoid recursing into this method
  357. type noCustomUnmarshal FolderConfiguration
  358. ptr := (*noCustomUnmarshal)(f)
  359. return d.DecodeElement(ptr, &start)
  360. }