folderconfiguration.go 7.4 KB

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