folderconfiguration.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. "errors"
  9. "fmt"
  10. "runtime"
  11. "sort"
  12. "strings"
  13. "time"
  14. "github.com/shirou/gopsutil/v3/disk"
  15. "github.com/syncthing/syncthing/lib/fs"
  16. "github.com/syncthing/syncthing/lib/protocol"
  17. "github.com/syncthing/syncthing/lib/util"
  18. )
  19. var (
  20. ErrPathNotDirectory = errors.New("folder path not a directory")
  21. ErrPathMissing = errors.New("folder path missing")
  22. ErrMarkerMissing = errors.New("folder marker missing (this indicates potential data loss, search docs/forum to get information about how to proceed)")
  23. )
  24. const (
  25. DefaultMarkerName = ".stfolder"
  26. EncryptionTokenName = "syncthing-encryption_password_token"
  27. maxConcurrentWritesDefault = 2
  28. maxConcurrentWritesLimit = 64
  29. )
  30. func (f FolderConfiguration) Copy() FolderConfiguration {
  31. c := f
  32. c.Devices = make([]FolderDeviceConfiguration, len(f.Devices))
  33. copy(c.Devices, f.Devices)
  34. c.Versioning = f.Versioning.Copy()
  35. return c
  36. }
  37. func (f FolderConfiguration) Filesystem() fs.Filesystem {
  38. // This is intentionally not a pointer method, because things like
  39. // cfg.Folders["default"].Filesystem() should be valid.
  40. var opts []fs.Option
  41. if f.FilesystemType == fs.FilesystemTypeBasic && f.JunctionsAsDirs {
  42. opts = append(opts, new(fs.OptionJunctionsAsDirs))
  43. }
  44. filesystem := fs.NewFilesystem(f.FilesystemType, f.Path, opts...)
  45. if !f.CaseSensitiveFS {
  46. filesystem = fs.NewCaseFilesystem(filesystem)
  47. }
  48. return filesystem
  49. }
  50. func (f FolderConfiguration) ModTimeWindow() time.Duration {
  51. dur := time.Duration(f.RawModTimeWindowS) * time.Second
  52. if f.RawModTimeWindowS < 1 && runtime.GOOS == "android" {
  53. if usage, err := disk.Usage(f.Filesystem().URI()); err != nil {
  54. dur = 2 * time.Second
  55. l.Debugf(`Detecting FS at "%v" on android: Setting mtime window to 2s: err == "%v"`, f.Path, err)
  56. } else if strings.HasPrefix(strings.ToLower(usage.Fstype), "ext2") || strings.HasPrefix(strings.ToLower(usage.Fstype), "ext3") || strings.HasPrefix(strings.ToLower(usage.Fstype), "ext4") {
  57. l.Debugf(`Detecting FS at %v on android: Leaving mtime window at 0: usage.Fstype == "%v"`, f.Path, usage.Fstype)
  58. } else {
  59. dur = 2 * time.Second
  60. l.Debugf(`Detecting FS at "%v" on android: Setting mtime window to 2s: usage.Fstype == "%v"`, f.Path, usage.Fstype)
  61. }
  62. }
  63. return dur
  64. }
  65. func (f *FolderConfiguration) CreateMarker() error {
  66. if err := f.CheckPath(); err != ErrMarkerMissing {
  67. return err
  68. }
  69. if f.MarkerName != DefaultMarkerName {
  70. // Folder uses a non-default marker so we shouldn't mess with it.
  71. // Pretend we created it and let the subsequent health checks sort
  72. // out the actual situation.
  73. return nil
  74. }
  75. permBits := fs.FileMode(0777)
  76. if runtime.GOOS == "windows" {
  77. // Windows has no umask so we must chose a safer set of bits to
  78. // begin with.
  79. permBits = 0700
  80. }
  81. fs := f.Filesystem()
  82. err := fs.Mkdir(DefaultMarkerName, permBits)
  83. if err != nil {
  84. return err
  85. }
  86. if dir, err := fs.Open("."); err != nil {
  87. l.Debugln("folder marker: open . failed:", err)
  88. } else if err := dir.Sync(); err != nil {
  89. l.Debugln("folder marker: fsync . failed:", err)
  90. }
  91. fs.Hide(DefaultMarkerName)
  92. return nil
  93. }
  94. // CheckPath returns nil if the folder root exists and contains the marker file
  95. func (f *FolderConfiguration) CheckPath() error {
  96. fi, err := f.Filesystem().Stat(".")
  97. if err != nil {
  98. if !fs.IsNotExist(err) {
  99. return err
  100. }
  101. return ErrPathMissing
  102. }
  103. // Users might have the root directory as a symlink or reparse point.
  104. // Furthermore, OneDrive bullcrap uses a magic reparse point to the cloudz...
  105. // Yet it's impossible for this to happen, as filesystem adds a trailing
  106. // path separator to the root, so even if you point the filesystem at a file
  107. // Stat ends up calling stat on C:\dir\file\ which, fails with "is not a directory"
  108. // in the error check above, and we don't even get to here.
  109. if !fi.IsDir() && !fi.IsSymlink() {
  110. return ErrPathNotDirectory
  111. }
  112. _, err = f.Filesystem().Stat(f.MarkerName)
  113. if err != nil {
  114. if !fs.IsNotExist(err) {
  115. return err
  116. }
  117. return ErrMarkerMissing
  118. }
  119. return nil
  120. }
  121. func (f *FolderConfiguration) CreateRoot() (err error) {
  122. // Directory permission bits. Will be filtered down to something
  123. // sane by umask on Unixes.
  124. permBits := fs.FileMode(0777)
  125. if runtime.GOOS == "windows" {
  126. // Windows has no umask so we must chose a safer set of bits to
  127. // begin with.
  128. permBits = 0700
  129. }
  130. filesystem := f.Filesystem()
  131. if _, err = filesystem.Stat("."); fs.IsNotExist(err) {
  132. err = filesystem.MkdirAll(".", permBits)
  133. }
  134. return err
  135. }
  136. func (f FolderConfiguration) Description() string {
  137. if f.Label == "" {
  138. return f.ID
  139. }
  140. return fmt.Sprintf("%q (%s)", f.Label, f.ID)
  141. }
  142. func (f *FolderConfiguration) DeviceIDs() []protocol.DeviceID {
  143. deviceIDs := make([]protocol.DeviceID, len(f.Devices))
  144. for i, n := range f.Devices {
  145. deviceIDs[i] = n.DeviceID
  146. }
  147. return deviceIDs
  148. }
  149. func (f *FolderConfiguration) prepare(myID protocol.DeviceID, existingDevices map[protocol.DeviceID]bool) {
  150. // Ensure that
  151. // - any loose devices are not present in the wrong places
  152. // - there are no duplicate devices
  153. // - we are part of the devices
  154. f.Devices = ensureExistingDevices(f.Devices, existingDevices)
  155. f.Devices = ensureNoDuplicateFolderDevices(f.Devices)
  156. f.Devices = ensureDevicePresent(f.Devices, myID)
  157. sort.Slice(f.Devices, func(a, b int) bool {
  158. return f.Devices[a].DeviceID.Compare(f.Devices[b].DeviceID) == -1
  159. })
  160. if f.RescanIntervalS > MaxRescanIntervalS {
  161. f.RescanIntervalS = MaxRescanIntervalS
  162. } else if f.RescanIntervalS < 0 {
  163. f.RescanIntervalS = 0
  164. }
  165. if f.FSWatcherDelayS <= 0 {
  166. f.FSWatcherEnabled = false
  167. f.FSWatcherDelayS = 10
  168. }
  169. if f.Versioning.CleanupIntervalS > MaxRescanIntervalS {
  170. f.Versioning.CleanupIntervalS = MaxRescanIntervalS
  171. } else if f.Versioning.CleanupIntervalS < 0 {
  172. f.Versioning.CleanupIntervalS = 0
  173. }
  174. if f.WeakHashThresholdPct == 0 {
  175. f.WeakHashThresholdPct = 25
  176. }
  177. if f.MarkerName == "" {
  178. f.MarkerName = DefaultMarkerName
  179. }
  180. if f.MaxConcurrentWrites <= 0 {
  181. f.MaxConcurrentWrites = maxConcurrentWritesDefault
  182. } else if f.MaxConcurrentWrites > maxConcurrentWritesLimit {
  183. f.MaxConcurrentWrites = maxConcurrentWritesLimit
  184. }
  185. if f.Type == FolderTypeReceiveEncrypted {
  186. f.DisableTempIndexes = true
  187. f.IgnorePerms = true
  188. }
  189. }
  190. // RequiresRestartOnly returns a copy with only the attributes that require
  191. // restart on change.
  192. func (f FolderConfiguration) RequiresRestartOnly() FolderConfiguration {
  193. copy := f
  194. // Manual handling for things that are not taken care of by the tag
  195. // copier, yet should not cause a restart.
  196. blank := FolderConfiguration{}
  197. util.CopyMatchingTag(&blank, &copy, "restart", func(v string) bool {
  198. if len(v) > 0 && v != "false" {
  199. panic(fmt.Sprintf(`unexpected tag value: %s. expected untagged or "false"`, v))
  200. }
  201. return v == "false"
  202. })
  203. return copy
  204. }
  205. func (f *FolderConfiguration) Device(device protocol.DeviceID) (FolderDeviceConfiguration, bool) {
  206. for _, dev := range f.Devices {
  207. if dev.DeviceID == device {
  208. return dev, true
  209. }
  210. }
  211. return FolderDeviceConfiguration{}, false
  212. }
  213. func (f *FolderConfiguration) SharedWith(device protocol.DeviceID) bool {
  214. _, ok := f.Device(device)
  215. return ok
  216. }
  217. func (f *FolderConfiguration) CheckAvailableSpace(req uint64) error {
  218. val := f.MinDiskFree.BaseValue()
  219. if val <= 0 {
  220. return nil
  221. }
  222. fs := f.Filesystem()
  223. usage, err := fs.Usage(".")
  224. if err != nil {
  225. return nil
  226. }
  227. if err := checkAvailableSpace(req, f.MinDiskFree, usage); err != nil {
  228. return fmt.Errorf("insufficient space in folder %v (%v): %w", f.Description(), fs.URI(), err)
  229. }
  230. return nil
  231. }