folderconfiguration.go 7.8 KB

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