walk.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 http://mozilla.org/MPL/2.0/.
  6. package scanner
  7. import (
  8. "errors"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "strings"
  13. "sync/atomic"
  14. "time"
  15. "unicode/utf8"
  16. "github.com/syncthing/syncthing/lib/db"
  17. "github.com/syncthing/syncthing/lib/events"
  18. "github.com/syncthing/syncthing/lib/osutil"
  19. "github.com/syncthing/syncthing/lib/protocol"
  20. "github.com/syncthing/syncthing/lib/symlinks"
  21. "golang.org/x/text/unicode/norm"
  22. )
  23. var maskModePerm os.FileMode
  24. func init() {
  25. if runtime.GOOS == "windows" {
  26. // There is no user/group/others in Windows' read-only
  27. // attribute, and all "w" bits are set in os.FileInfo
  28. // if the file is not read-only. Do not send these
  29. // group/others-writable bits to other devices in order to
  30. // avoid unexpected world-writable files on other platforms.
  31. maskModePerm = os.ModePerm & 0755
  32. } else {
  33. maskModePerm = os.ModePerm
  34. }
  35. }
  36. type Walker struct {
  37. // Folder for which the walker has been created
  38. Folder string
  39. // Dir is the base directory for the walk
  40. Dir string
  41. // Limit walking to these paths within Dir, or no limit if Sub is empty
  42. Subs []string
  43. // BlockSize controls the size of the block used when hashing.
  44. BlockSize int
  45. // If Matcher is not nil, it is used to identify files to ignore which were specified by the user.
  46. Matcher IgnoreMatcher
  47. // If TempNamer is not nil, it is used to ignore temporary files when walking.
  48. TempNamer TempNamer
  49. // Number of hours to keep temporary files for
  50. TempLifetime time.Duration
  51. // If CurrentFiler is not nil, it is queried for the current file before rescanning.
  52. CurrentFiler CurrentFiler
  53. // If MtimeRepo is not nil, it is used to provide mtimes on systems that don't support setting arbirtary mtimes.
  54. MtimeRepo *db.VirtualMtimeRepo
  55. // If IgnorePerms is true, changes to permission bits will not be
  56. // detected. Scanned files will get zero permission bits and the
  57. // NoPermissionBits flag set.
  58. IgnorePerms bool
  59. // When AutoNormalize is set, file names that are in UTF8 but incorrect
  60. // normalization form will be corrected.
  61. AutoNormalize bool
  62. // Number of routines to use for hashing
  63. Hashers int
  64. // Our vector clock id
  65. ShortID uint64
  66. // Optional progress tick interval which defines how often FolderScanProgress
  67. // events are emitted. Negative number means disabled.
  68. ProgressTickIntervalS int
  69. }
  70. type TempNamer interface {
  71. // Temporary returns a temporary name for the filed referred to by filepath.
  72. TempName(path string) string
  73. // IsTemporary returns true if path refers to the name of temporary file.
  74. IsTemporary(path string) bool
  75. }
  76. type CurrentFiler interface {
  77. // CurrentFile returns the file as seen at last scan.
  78. CurrentFile(name string) (protocol.FileInfo, bool)
  79. }
  80. type IgnoreMatcher interface {
  81. // Match returns true if the file should be ignored.
  82. Match(filename string) bool
  83. }
  84. // Walk returns the list of files found in the local folder by scanning the
  85. // file system. Files are blockwise hashed.
  86. func (w *Walker) Walk() (chan protocol.FileInfo, error) {
  87. l.Debugln("Walk", w.Dir, w.Subs, w.BlockSize, w.Matcher)
  88. err := checkDir(w.Dir)
  89. if err != nil {
  90. return nil, err
  91. }
  92. toHashChan := make(chan protocol.FileInfo)
  93. finishedChan := make(chan protocol.FileInfo)
  94. // A routine which walks the filesystem tree, and sends files which have
  95. // been modified to the counter routine.
  96. go func() {
  97. hashFiles := w.walkAndHashFiles(toHashChan, finishedChan)
  98. if len(w.Subs) == 0 {
  99. filepath.Walk(w.Dir, hashFiles)
  100. } else {
  101. for _, sub := range w.Subs {
  102. filepath.Walk(filepath.Join(w.Dir, sub), hashFiles)
  103. }
  104. }
  105. close(toHashChan)
  106. }()
  107. // We're not required to emit scan progress events, just kick off hashers,
  108. // and feed inputs directly from the walker.
  109. if w.ProgressTickIntervalS < 0 {
  110. newParallelHasher(w.Dir, w.BlockSize, w.Hashers, finishedChan, toHashChan, nil, nil)
  111. return finishedChan, nil
  112. }
  113. // Defaults to every 2 seconds.
  114. if w.ProgressTickIntervalS == 0 {
  115. w.ProgressTickIntervalS = 2
  116. }
  117. ticker := time.NewTicker(time.Duration(w.ProgressTickIntervalS) * time.Second)
  118. // We need to emit progress events, hence we create a routine which buffers
  119. // the list of files to be hashed, counts the total number of
  120. // bytes to hash, and once no more files need to be hashed (chan gets closed),
  121. // start a routine which periodically emits FolderScanProgress events,
  122. // until a stop signal is sent by the parallel hasher.
  123. // Parallel hasher is stopped by this routine when we close the channel over
  124. // which it receives the files we ask it to hash.
  125. go func() {
  126. var filesToHash []protocol.FileInfo
  127. var total, progress int64
  128. for file := range toHashChan {
  129. filesToHash = append(filesToHash, file)
  130. total += int64(file.CachedSize)
  131. }
  132. realToHashChan := make(chan protocol.FileInfo)
  133. done := make(chan struct{})
  134. newParallelHasher(w.Dir, w.BlockSize, w.Hashers, finishedChan, realToHashChan, &progress, done)
  135. // A routine which actually emits the FolderScanProgress events
  136. // every w.ProgressTicker ticks, until the hasher routines terminate.
  137. go func() {
  138. for {
  139. select {
  140. case <-done:
  141. l.Debugln("Walk progress done", w.Dir, w.Subs, w.BlockSize, w.Matcher)
  142. ticker.Stop()
  143. return
  144. case <-ticker.C:
  145. current := atomic.LoadInt64(&progress)
  146. l.Debugf("Walk %s %s current progress %d/%d (%d%%)", w.Dir, w.Subs, current, total, current*100/total)
  147. events.Default.Log(events.FolderScanProgress, map[string]interface{}{
  148. "folder": w.Folder,
  149. "current": current,
  150. "total": total,
  151. })
  152. }
  153. }
  154. }()
  155. for _, file := range filesToHash {
  156. l.Debugln("real to hash:", file.Name)
  157. realToHashChan <- file
  158. }
  159. close(realToHashChan)
  160. }()
  161. return finishedChan, nil
  162. }
  163. func (w *Walker) walkAndHashFiles(fchan, dchan chan protocol.FileInfo) filepath.WalkFunc {
  164. now := time.Now()
  165. return func(p string, info os.FileInfo, err error) error {
  166. // Return value used when we are returning early and don't want to
  167. // process the item. For directories, this means do-not-descend.
  168. var skip error // nil
  169. // info nil when error is not nil
  170. if info != nil && info.IsDir() {
  171. skip = filepath.SkipDir
  172. }
  173. if err != nil {
  174. l.Debugln("error:", p, info, err)
  175. return skip
  176. }
  177. rn, err := filepath.Rel(w.Dir, p)
  178. if err != nil {
  179. l.Debugln("rel error:", p, err)
  180. return skip
  181. }
  182. if rn == "." {
  183. return nil
  184. }
  185. mtime := info.ModTime()
  186. if w.MtimeRepo != nil {
  187. mtime = w.MtimeRepo.GetMtime(rn, mtime)
  188. }
  189. if w.TempNamer != nil && w.TempNamer.IsTemporary(rn) {
  190. // A temporary file
  191. l.Debugln("temporary:", rn)
  192. if info.Mode().IsRegular() && mtime.Add(w.TempLifetime).Before(now) {
  193. os.Remove(p)
  194. l.Debugln("removing temporary:", rn, mtime)
  195. }
  196. return nil
  197. }
  198. if sn := filepath.Base(rn); sn == ".stignore" || sn == ".stfolder" ||
  199. strings.HasPrefix(rn, ".stversions") || (w.Matcher != nil && w.Matcher.Match(rn)) {
  200. // An ignored file
  201. l.Debugln("ignored:", rn)
  202. return skip
  203. }
  204. if !utf8.ValidString(rn) {
  205. l.Warnf("File name %q is not in UTF8 encoding; skipping.", rn)
  206. return skip
  207. }
  208. var normalizedRn string
  209. if runtime.GOOS == "darwin" {
  210. // Mac OS X file names should always be NFD normalized.
  211. normalizedRn = norm.NFD.String(rn)
  212. } else {
  213. // Every other OS in the known universe uses NFC or just plain
  214. // doesn't bother to define an encoding. In our case *we* do care,
  215. // so we enforce NFC regardless.
  216. normalizedRn = norm.NFC.String(rn)
  217. }
  218. if rn != normalizedRn {
  219. // The file name was not normalized.
  220. if !w.AutoNormalize {
  221. // We're not authorized to do anything about it, so complain and skip.
  222. l.Warnf("File name %q is not in the correct UTF8 normalization form; skipping.", rn)
  223. return skip
  224. }
  225. // We will attempt to normalize it.
  226. normalizedPath := filepath.Join(w.Dir, normalizedRn)
  227. if _, err := osutil.Lstat(normalizedPath); os.IsNotExist(err) {
  228. // Nothing exists with the normalized filename. Good.
  229. if err = os.Rename(p, normalizedPath); err != nil {
  230. l.Infof(`Error normalizing UTF8 encoding of file "%s": %v`, rn, err)
  231. return skip
  232. }
  233. l.Infof(`Normalized UTF8 encoding of file name "%s".`, rn)
  234. } else {
  235. // There is something already in the way at the normalized
  236. // file name.
  237. l.Infof(`File "%s" has UTF8 encoding conflict with another file; ignoring.`, rn)
  238. return skip
  239. }
  240. rn = normalizedRn
  241. }
  242. var cf protocol.FileInfo
  243. var ok bool
  244. // Index wise symlinks are always files, regardless of what the target
  245. // is, because symlinks carry their target path as their content.
  246. if info.Mode()&os.ModeSymlink == os.ModeSymlink {
  247. // If the target is a directory, do NOT descend down there. This
  248. // will cause files to get tracked, and removing the symlink will
  249. // as a result remove files in their real location.
  250. if !symlinks.Supported {
  251. return skip
  252. }
  253. // We always rehash symlinks as they have no modtime or
  254. // permissions. We check if they point to the old target by
  255. // checking that their existing blocks match with the blocks in
  256. // the index.
  257. target, targetType, err := symlinks.Read(p)
  258. if err != nil {
  259. l.Debugln("readlink error:", p, err)
  260. return skip
  261. }
  262. blocks, err := Blocks(strings.NewReader(target), w.BlockSize, 0, nil)
  263. if err != nil {
  264. l.Debugln("hash link error:", p, err)
  265. return skip
  266. }
  267. if w.CurrentFiler != nil {
  268. // A symlink is "unchanged", if
  269. // - it exists
  270. // - it wasn't deleted (because it isn't now)
  271. // - it was a symlink
  272. // - it wasn't invalid
  273. // - the symlink type (file/dir) was the same
  274. // - the block list (i.e. hash of target) was the same
  275. cf, ok = w.CurrentFiler.CurrentFile(rn)
  276. if ok && !cf.IsDeleted() && cf.IsSymlink() && !cf.IsInvalid() && SymlinkTypeEqual(targetType, cf) && BlocksEqual(cf.Blocks, blocks) {
  277. return skip
  278. }
  279. }
  280. f := protocol.FileInfo{
  281. Name: rn,
  282. Version: cf.Version.Update(w.ShortID),
  283. Flags: uint32(protocol.FlagSymlink | protocol.FlagNoPermBits | 0666 | SymlinkFlags(targetType)),
  284. Modified: 0,
  285. Blocks: blocks,
  286. }
  287. l.Debugln("symlink changedb:", p, f)
  288. dchan <- f
  289. return skip
  290. }
  291. if info.Mode().IsDir() {
  292. if w.CurrentFiler != nil {
  293. // A directory is "unchanged", if it
  294. // - exists
  295. // - has the same permissions as previously, unless we are ignoring permissions
  296. // - was not marked deleted (since it apparently exists now)
  297. // - was a directory previously (not a file or something else)
  298. // - was not a symlink (since it's a directory now)
  299. // - was not invalid (since it looks valid now)
  300. cf, ok = w.CurrentFiler.CurrentFile(rn)
  301. permUnchanged := w.IgnorePerms || !cf.HasPermissionBits() || PermsEqual(cf.Flags, uint32(info.Mode()))
  302. if ok && permUnchanged && !cf.IsDeleted() && cf.IsDirectory() && !cf.IsSymlink() && !cf.IsInvalid() {
  303. return nil
  304. }
  305. }
  306. flags := uint32(protocol.FlagDirectory)
  307. if w.IgnorePerms {
  308. flags |= protocol.FlagNoPermBits | 0777
  309. } else {
  310. flags |= uint32(info.Mode() & maskModePerm)
  311. }
  312. f := protocol.FileInfo{
  313. Name: rn,
  314. Version: cf.Version.Update(w.ShortID),
  315. Flags: flags,
  316. Modified: mtime.Unix(),
  317. }
  318. l.Debugln("dir:", p, f)
  319. dchan <- f
  320. return nil
  321. }
  322. if info.Mode().IsRegular() {
  323. curMode := uint32(info.Mode())
  324. if runtime.GOOS == "windows" && osutil.IsWindowsExecutable(rn) {
  325. curMode |= 0111
  326. }
  327. if w.CurrentFiler != nil {
  328. // A file is "unchanged", if it
  329. // - exists
  330. // - has the same permissions as previously, unless we are ignoring permissions
  331. // - was not marked deleted (since it apparently exists now)
  332. // - had the same modification time as it has now
  333. // - was not a directory previously (since it's a file now)
  334. // - was not a symlink (since it's a file now)
  335. // - was not invalid (since it looks valid now)
  336. // - has the same size as previously
  337. cf, ok = w.CurrentFiler.CurrentFile(rn)
  338. permUnchanged := w.IgnorePerms || !cf.HasPermissionBits() || PermsEqual(cf.Flags, curMode)
  339. if ok && permUnchanged && !cf.IsDeleted() && cf.Modified == mtime.Unix() && !cf.IsDirectory() &&
  340. !cf.IsSymlink() && !cf.IsInvalid() && cf.Size() == info.Size() {
  341. return nil
  342. }
  343. l.Debugln("rescan:", cf, mtime.Unix(), info.Mode()&os.ModePerm)
  344. }
  345. var flags = curMode & uint32(maskModePerm)
  346. if w.IgnorePerms {
  347. flags = protocol.FlagNoPermBits | 0666
  348. }
  349. f := protocol.FileInfo{
  350. Name: rn,
  351. Version: cf.Version.Update(w.ShortID),
  352. Flags: flags,
  353. Modified: mtime.Unix(),
  354. CachedSize: info.Size(),
  355. }
  356. l.Debugln("to hash:", p, f)
  357. fchan <- f
  358. }
  359. return nil
  360. }
  361. }
  362. func checkDir(dir string) error {
  363. if info, err := osutil.Lstat(dir); err != nil {
  364. return err
  365. } else if !info.IsDir() {
  366. return errors.New(dir + ": not a directory")
  367. } else {
  368. l.Debugln("checkDir", dir, info)
  369. }
  370. return nil
  371. }
  372. func PermsEqual(a, b uint32) bool {
  373. switch runtime.GOOS {
  374. case "windows":
  375. // There is only writeable and read only, represented for user, group
  376. // and other equally. We only compare against user.
  377. return a&0600 == b&0600
  378. default:
  379. // All bits count
  380. return a&0777 == b&0777
  381. }
  382. }
  383. func SymlinkTypeEqual(disk symlinks.TargetType, f protocol.FileInfo) bool {
  384. // If the target is missing, Unix never knows what type of symlink it is
  385. // and Windows always knows even if there is no target. Which means that
  386. // without this special check a Unix node would be fighting with a Windows
  387. // node about whether or not the target is known. Basically, if you don't
  388. // know and someone else knows, just accept it. The fact that you don't
  389. // know means you are on Unix, and on Unix you don't really care what the
  390. // target type is. The moment you do know, and if something doesn't match,
  391. // that will propagate through the cluster.
  392. switch disk {
  393. case symlinks.TargetUnknown:
  394. return true
  395. case symlinks.TargetDirectory:
  396. return f.IsDirectory() && f.Flags&protocol.FlagSymlinkMissingTarget == 0
  397. case symlinks.TargetFile:
  398. return !f.IsDirectory() && f.Flags&protocol.FlagSymlinkMissingTarget == 0
  399. }
  400. panic("unknown symlink TargetType")
  401. }
  402. func SymlinkFlags(t symlinks.TargetType) uint32 {
  403. switch t {
  404. case symlinks.TargetFile:
  405. return 0
  406. case symlinks.TargetDirectory:
  407. return protocol.FlagDirectory
  408. case symlinks.TargetUnknown:
  409. return protocol.FlagSymlinkMissingTarget
  410. }
  411. panic("unknown symlink TargetType")
  412. }