walk.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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/protocol"
  17. "github.com/syncthing/syncthing/lib/db"
  18. "github.com/syncthing/syncthing/lib/events"
  19. "github.com/syncthing/syncthing/lib/osutil"
  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. if debug {
  88. l.Debugln("Walk", w.Dir, w.Subs, w.BlockSize, w.Matcher)
  89. }
  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)
  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
  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)
  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. if debug {
  144. l.Debugln("Walk progress done", w.Dir, w.Subs, w.BlockSize, w.Matcher)
  145. }
  146. ticker.Stop()
  147. return
  148. case <-ticker.C:
  149. current := atomic.LoadInt64(&progress)
  150. if debug {
  151. l.Debugf("Walk %s %s current progress %d/%d (%d%%)", w.Dir, w.Subs, current, total, current*100/total)
  152. }
  153. events.Default.Log(events.FolderScanProgress, map[string]interface{}{
  154. "folder": w.Folder,
  155. "current": current,
  156. "total": total,
  157. })
  158. }
  159. }
  160. }()
  161. for _, file := range filesToHash {
  162. if debug {
  163. l.Debugln("real to hash:", file.Name)
  164. }
  165. realToHashChan <- file
  166. }
  167. close(realToHashChan)
  168. }()
  169. return finishedChan, nil
  170. }
  171. func (w *Walker) walkAndHashFiles(fchan, dchan chan protocol.FileInfo) filepath.WalkFunc {
  172. now := time.Now()
  173. return func(p string, info os.FileInfo, err error) error {
  174. // Return value used when we are returning early and don't want to
  175. // process the item. For directories, this means do-not-descend.
  176. var skip error // nil
  177. // info nil when error is not nil
  178. if info != nil && info.IsDir() {
  179. skip = filepath.SkipDir
  180. }
  181. if err != nil {
  182. if debug {
  183. l.Debugln("error:", p, info, err)
  184. }
  185. return skip
  186. }
  187. rn, err := filepath.Rel(w.Dir, p)
  188. if err != nil {
  189. if debug {
  190. l.Debugln("rel error:", p, err)
  191. }
  192. return skip
  193. }
  194. if rn == "." {
  195. return nil
  196. }
  197. mtime := info.ModTime()
  198. if w.MtimeRepo != nil {
  199. mtime = w.MtimeRepo.GetMtime(rn, mtime)
  200. }
  201. if w.TempNamer != nil && w.TempNamer.IsTemporary(rn) {
  202. // A temporary file
  203. if debug {
  204. l.Debugln("temporary:", rn)
  205. }
  206. if info.Mode().IsRegular() && mtime.Add(w.TempLifetime).Before(now) {
  207. os.Remove(p)
  208. if debug {
  209. l.Debugln("removing temporary:", rn, mtime)
  210. }
  211. }
  212. return nil
  213. }
  214. if sn := filepath.Base(rn); sn == ".stignore" || sn == ".stfolder" ||
  215. strings.HasPrefix(rn, ".stversions") || (w.Matcher != nil && w.Matcher.Match(rn)) {
  216. // An ignored file
  217. if debug {
  218. l.Debugln("ignored:", rn)
  219. }
  220. return skip
  221. }
  222. if !utf8.ValidString(rn) {
  223. l.Warnf("File name %q is not in UTF8 encoding; skipping.", rn)
  224. return skip
  225. }
  226. var normalizedRn string
  227. if runtime.GOOS == "darwin" {
  228. // Mac OS X file names should always be NFD normalized.
  229. normalizedRn = norm.NFD.String(rn)
  230. } else {
  231. // Every other OS in the known universe uses NFC or just plain
  232. // doesn't bother to define an encoding. In our case *we* do care,
  233. // so we enforce NFC regardless.
  234. normalizedRn = norm.NFC.String(rn)
  235. }
  236. if rn != normalizedRn {
  237. // The file name was not normalized.
  238. if !w.AutoNormalize {
  239. // We're not authorized to do anything about it, so complain and skip.
  240. l.Warnf("File name %q is not in the correct UTF8 normalization form; skipping.", rn)
  241. return skip
  242. }
  243. // We will attempt to normalize it.
  244. normalizedPath := filepath.Join(w.Dir, normalizedRn)
  245. if _, err := osutil.Lstat(normalizedPath); os.IsNotExist(err) {
  246. // Nothing exists with the normalized filename. Good.
  247. if err = os.Rename(p, normalizedPath); err != nil {
  248. l.Infof(`Error normalizing UTF8 encoding of file "%s": %v`, rn, err)
  249. return skip
  250. }
  251. l.Infof(`Normalized UTF8 encoding of file name "%s".`, rn)
  252. } else {
  253. // There is something already in the way at the normalized
  254. // file name.
  255. l.Infof(`File "%s" has UTF8 encoding conflict with another file; ignoring.`, rn)
  256. return skip
  257. }
  258. rn = normalizedRn
  259. }
  260. var cf protocol.FileInfo
  261. var ok bool
  262. // Index wise symlinks are always files, regardless of what the target
  263. // is, because symlinks carry their target path as their content.
  264. if info.Mode()&os.ModeSymlink == os.ModeSymlink {
  265. // If the target is a directory, do NOT descend down there. This
  266. // will cause files to get tracked, and removing the symlink will
  267. // as a result remove files in their real location.
  268. if !symlinks.Supported {
  269. return skip
  270. }
  271. // We always rehash symlinks as they have no modtime or
  272. // permissions. We check if they point to the old target by
  273. // checking that their existing blocks match with the blocks in
  274. // the index.
  275. target, flags, err := symlinks.Read(p)
  276. flags = flags & protocol.SymlinkTypeMask
  277. if err != nil {
  278. if debug {
  279. l.Debugln("readlink error:", p, err)
  280. }
  281. return skip
  282. }
  283. blocks, err := Blocks(strings.NewReader(target), w.BlockSize, 0, nil)
  284. if err != nil {
  285. if debug {
  286. l.Debugln("hash link error:", p, err)
  287. }
  288. return skip
  289. }
  290. if w.CurrentFiler != nil {
  291. // A symlink is "unchanged", if
  292. // - it exists
  293. // - it wasn't deleted (because it isn't now)
  294. // - it was a symlink
  295. // - it wasn't invalid
  296. // - the symlink type (file/dir) was the same
  297. // - the block list (i.e. hash of target) was the same
  298. cf, ok = w.CurrentFiler.CurrentFile(rn)
  299. if ok && !cf.IsDeleted() && cf.IsSymlink() && !cf.IsInvalid() && SymlinkTypeEqual(flags, cf.Flags) && BlocksEqual(cf.Blocks, blocks) {
  300. return skip
  301. }
  302. }
  303. f := protocol.FileInfo{
  304. Name: rn,
  305. Version: cf.Version.Update(w.ShortID),
  306. Flags: protocol.FlagSymlink | flags | protocol.FlagNoPermBits | 0666,
  307. Modified: 0,
  308. Blocks: blocks,
  309. }
  310. if debug {
  311. l.Debugln("symlink changedb:", p, f)
  312. }
  313. dchan <- f
  314. return skip
  315. }
  316. if info.Mode().IsDir() {
  317. if w.CurrentFiler != nil {
  318. // A directory is "unchanged", if it
  319. // - exists
  320. // - has the same permissions as previously, unless we are ignoring permissions
  321. // - was not marked deleted (since it apparently exists now)
  322. // - was a directory previously (not a file or something else)
  323. // - was not a symlink (since it's a directory now)
  324. // - was not invalid (since it looks valid now)
  325. cf, ok = w.CurrentFiler.CurrentFile(rn)
  326. permUnchanged := w.IgnorePerms || !cf.HasPermissionBits() || PermsEqual(cf.Flags, uint32(info.Mode()))
  327. if ok && permUnchanged && !cf.IsDeleted() && cf.IsDirectory() && !cf.IsSymlink() && !cf.IsInvalid() {
  328. return nil
  329. }
  330. }
  331. flags := uint32(protocol.FlagDirectory)
  332. if w.IgnorePerms {
  333. flags |= protocol.FlagNoPermBits | 0777
  334. } else {
  335. flags |= uint32(info.Mode() & maskModePerm)
  336. }
  337. f := protocol.FileInfo{
  338. Name: rn,
  339. Version: cf.Version.Update(w.ShortID),
  340. Flags: flags,
  341. Modified: mtime.Unix(),
  342. }
  343. if debug {
  344. l.Debugln("dir:", p, f)
  345. }
  346. dchan <- f
  347. return nil
  348. }
  349. if info.Mode().IsRegular() {
  350. curMode := uint32(info.Mode())
  351. if runtime.GOOS == "windows" && osutil.IsWindowsExecutable(rn) {
  352. curMode |= 0111
  353. }
  354. if w.CurrentFiler != nil {
  355. // A file is "unchanged", if it
  356. // - exists
  357. // - has the same permissions as previously, unless we are ignoring permissions
  358. // - was not marked deleted (since it apparently exists now)
  359. // - had the same modification time as it has now
  360. // - was not a directory previously (since it's a file now)
  361. // - was not a symlink (since it's a file now)
  362. // - was not invalid (since it looks valid now)
  363. // - has the same size as previously
  364. cf, ok = w.CurrentFiler.CurrentFile(rn)
  365. permUnchanged := w.IgnorePerms || !cf.HasPermissionBits() || PermsEqual(cf.Flags, curMode)
  366. if ok && permUnchanged && !cf.IsDeleted() && cf.Modified == mtime.Unix() && !cf.IsDirectory() &&
  367. !cf.IsSymlink() && !cf.IsInvalid() && cf.Size() == info.Size() {
  368. return nil
  369. }
  370. if debug {
  371. l.Debugln("rescan:", cf, mtime.Unix(), info.Mode()&os.ModePerm)
  372. }
  373. }
  374. var flags = curMode & uint32(maskModePerm)
  375. if w.IgnorePerms {
  376. flags = protocol.FlagNoPermBits | 0666
  377. }
  378. f := protocol.FileInfo{
  379. Name: rn,
  380. Version: cf.Version.Update(w.ShortID),
  381. Flags: flags,
  382. Modified: mtime.Unix(),
  383. CachedSize: info.Size(),
  384. }
  385. if debug {
  386. l.Debugln("to hash:", p, f)
  387. }
  388. fchan <- f
  389. }
  390. return nil
  391. }
  392. }
  393. func checkDir(dir string) error {
  394. if info, err := osutil.Lstat(dir); err != nil {
  395. return err
  396. } else if !info.IsDir() {
  397. return errors.New(dir + ": not a directory")
  398. } else if debug {
  399. l.Debugln("checkDir", dir, info)
  400. }
  401. return nil
  402. }
  403. func PermsEqual(a, b uint32) bool {
  404. switch runtime.GOOS {
  405. case "windows":
  406. // There is only writeable and read only, represented for user, group
  407. // and other equally. We only compare against user.
  408. return a&0600 == b&0600
  409. default:
  410. // All bits count
  411. return a&0777 == b&0777
  412. }
  413. }
  414. func SymlinkTypeEqual(disk, index uint32) bool {
  415. // If the target is missing, Unix never knows what type of symlink it is
  416. // and Windows always knows even if there is no target. Which means that
  417. // without this special check a Unix node would be fighting with a Windows
  418. // node about whether or not the target is known. Basically, if you don't
  419. // know and someone else knows, just accept it. The fact that you don't
  420. // know means you are on Unix, and on Unix you don't really care what the
  421. // target type is. The moment you do know, and if something doesn't match,
  422. // that will propagate through the cluster.
  423. if disk&protocol.FlagSymlinkMissingTarget != 0 && index&protocol.FlagSymlinkMissingTarget == 0 {
  424. return true
  425. }
  426. return disk&protocol.SymlinkTypeMask == index&protocol.SymlinkTypeMask
  427. }