walk.go 15 KB

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