walk.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. package scanner
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path/filepath"
  12. "runtime"
  13. "strings"
  14. "code.google.com/p/go.text/unicode/norm"
  15. "github.com/calmh/syncthing/lamport"
  16. "github.com/calmh/syncthing/protocol"
  17. )
  18. type Walker struct {
  19. // Dir is the base directory for the walk
  20. Dir string
  21. // BlockSize controls the size of the block used when hashing.
  22. BlockSize int
  23. // If IgnoreFile is not empty, it is the name used for the file that holds ignore patterns.
  24. IgnoreFile string
  25. // If TempNamer is not nil, it is used to ignore tempory files when walking.
  26. TempNamer TempNamer
  27. // If CurrentFiler is not nil, it is queried for the current file before rescanning.
  28. CurrentFiler CurrentFiler
  29. // If Suppressor is not nil, it is queried for supression of modified files.
  30. // Suppressed files will be returned with empty metadata and the Suppressed flag set.
  31. // Requires CurrentFiler to be set.
  32. Suppressor Suppressor
  33. // If IgnorePerms is true, changes to permission bits will not be
  34. // detected. Scanned files will get zero permission bits and the
  35. // NoPermissionBits flag set.
  36. IgnorePerms bool
  37. }
  38. type TempNamer interface {
  39. // Temporary returns a temporary name for the filed referred to by filepath.
  40. TempName(path string) string
  41. // IsTemporary returns true if path refers to the name of temporary file.
  42. IsTemporary(path string) bool
  43. }
  44. type Suppressor interface {
  45. // Supress returns true if the update to the named file should be ignored.
  46. Suppress(name string, fi os.FileInfo) (bool, bool)
  47. }
  48. type CurrentFiler interface {
  49. // CurrentFile returns the file as seen at last scan.
  50. CurrentFile(name string) protocol.FileInfo
  51. }
  52. // Walk returns the list of files found in the local repository by scanning the
  53. // file system. Files are blockwise hashed.
  54. func (w *Walker) Walk() (chan protocol.FileInfo, map[string][]string, error) {
  55. if debug {
  56. l.Debugln("Walk", w.Dir, w.BlockSize, w.IgnoreFile)
  57. }
  58. err := checkDir(w.Dir)
  59. if err != nil {
  60. return nil, nil, err
  61. }
  62. ignore := make(map[string][]string)
  63. files := make(chan protocol.FileInfo)
  64. hashedFiles := make(chan protocol.FileInfo)
  65. newParallelHasher(w.Dir, w.BlockSize, runtime.NumCPU(), hashedFiles, files)
  66. hashFiles := w.walkAndHashFiles(files, ignore)
  67. go func() {
  68. filepath.Walk(w.Dir, w.loadIgnoreFiles(w.Dir, ignore))
  69. filepath.Walk(w.Dir, hashFiles)
  70. close(files)
  71. }()
  72. return hashedFiles, ignore, nil
  73. }
  74. // CleanTempFiles removes all files that match the temporary filename pattern.
  75. func (w *Walker) CleanTempFiles() {
  76. filepath.Walk(w.Dir, w.cleanTempFile)
  77. }
  78. func (w *Walker) loadIgnoreFiles(dir string, ign map[string][]string) filepath.WalkFunc {
  79. return func(p string, info os.FileInfo, err error) error {
  80. if err != nil {
  81. return nil
  82. }
  83. rn, err := filepath.Rel(dir, p)
  84. if err != nil {
  85. return nil
  86. }
  87. if pn, sn := filepath.Split(rn); sn == w.IgnoreFile {
  88. pn := filepath.Clean(pn)
  89. bs, _ := ioutil.ReadFile(p)
  90. lines := bytes.Split(bs, []byte("\n"))
  91. var patterns []string
  92. for _, line := range lines {
  93. lineStr := strings.TrimSpace(string(line))
  94. if len(lineStr) > 0 {
  95. patterns = append(patterns, lineStr)
  96. }
  97. }
  98. ign[pn] = patterns
  99. }
  100. return nil
  101. }
  102. }
  103. func (w *Walker) walkAndHashFiles(fchan chan protocol.FileInfo, ign map[string][]string) filepath.WalkFunc {
  104. return func(p string, info os.FileInfo, err error) error {
  105. if err != nil {
  106. if debug {
  107. l.Debugln("error:", p, info, err)
  108. }
  109. return nil
  110. }
  111. rn, err := filepath.Rel(w.Dir, p)
  112. if err != nil {
  113. if debug {
  114. l.Debugln("rel error:", p, err)
  115. }
  116. return nil
  117. }
  118. if rn == "." {
  119. return nil
  120. }
  121. if w.TempNamer != nil && w.TempNamer.IsTemporary(rn) {
  122. // A temporary file
  123. if debug {
  124. l.Debugln("temporary:", rn)
  125. }
  126. return nil
  127. }
  128. if sn := filepath.Base(rn); sn == w.IgnoreFile || sn == ".stversions" || w.ignoreFile(ign, rn) {
  129. // An ignored file
  130. if debug {
  131. l.Debugln("ignored:", rn)
  132. }
  133. if info.IsDir() {
  134. return filepath.SkipDir
  135. }
  136. return nil
  137. }
  138. if (runtime.GOOS == "linux" || runtime.GOOS == "windows") && !norm.NFC.IsNormalString(rn) {
  139. l.Warnf("File %q contains non-NFC UTF-8 sequences and cannot be synced. Consider renaming.", rn)
  140. return nil
  141. }
  142. if info.Mode().IsDir() {
  143. if w.CurrentFiler != nil {
  144. cf := w.CurrentFiler.CurrentFile(rn)
  145. permUnchanged := w.IgnorePerms || !protocol.HasPermissionBits(cf.Flags) || PermsEqual(cf.Flags, uint32(info.Mode()))
  146. if !protocol.IsDeleted(cf.Flags) && protocol.IsDirectory(cf.Flags) && permUnchanged {
  147. return nil
  148. }
  149. }
  150. var flags uint32 = protocol.FlagDirectory
  151. if w.IgnorePerms {
  152. flags |= protocol.FlagNoPermBits | 0777
  153. } else {
  154. flags |= uint32(info.Mode() & os.ModePerm)
  155. }
  156. f := protocol.FileInfo{
  157. Name: rn,
  158. Version: lamport.Default.Tick(0),
  159. Flags: flags,
  160. Modified: info.ModTime().Unix(),
  161. }
  162. if debug {
  163. l.Debugln("dir:", f)
  164. }
  165. fchan <- f
  166. return nil
  167. }
  168. if info.Mode().IsRegular() {
  169. if w.CurrentFiler != nil {
  170. cf := w.CurrentFiler.CurrentFile(rn)
  171. permUnchanged := w.IgnorePerms || !protocol.HasPermissionBits(cf.Flags) || PermsEqual(cf.Flags, uint32(info.Mode()))
  172. if !protocol.IsDeleted(cf.Flags) && cf.Modified == info.ModTime().Unix() && permUnchanged {
  173. return nil
  174. }
  175. if w.Suppressor != nil {
  176. if cur, prev := w.Suppressor.Suppress(rn, info); cur && !prev {
  177. l.Infof("Changes to %q are being temporarily suppressed because it changes too frequently.", p)
  178. cf.Flags |= protocol.FlagInvalid
  179. cf.Version = lamport.Default.Tick(cf.Version)
  180. cf.LocalVersion = 0
  181. if debug {
  182. l.Debugln("suppressed:", cf)
  183. }
  184. fchan <- cf
  185. return nil
  186. } else if prev && !cur {
  187. l.Infof("Changes to %q are no longer suppressed.", p)
  188. }
  189. }
  190. if debug {
  191. l.Debugln("rescan:", cf, info.ModTime().Unix(), info.Mode()&os.ModePerm)
  192. }
  193. }
  194. var flags = uint32(info.Mode() & os.ModePerm)
  195. if w.IgnorePerms {
  196. flags = protocol.FlagNoPermBits | 0666
  197. }
  198. fchan <- protocol.FileInfo{
  199. Name: rn,
  200. Version: lamport.Default.Tick(0),
  201. Flags: flags,
  202. Modified: info.ModTime().Unix(),
  203. }
  204. }
  205. return nil
  206. }
  207. }
  208. func (w *Walker) cleanTempFile(path string, info os.FileInfo, err error) error {
  209. if err != nil {
  210. return err
  211. }
  212. if info.Mode()&os.ModeType == 0 && w.TempNamer.IsTemporary(path) {
  213. os.Remove(path)
  214. }
  215. return nil
  216. }
  217. func (w *Walker) ignoreFile(patterns map[string][]string, file string) bool {
  218. first, last := filepath.Split(file)
  219. for prefix, pats := range patterns {
  220. if prefix == "." || prefix == first || strings.HasPrefix(first, fmt.Sprintf("%s%c", prefix, os.PathSeparator)) {
  221. for _, pattern := range pats {
  222. if match, _ := filepath.Match(pattern, last); match {
  223. return true
  224. }
  225. }
  226. }
  227. }
  228. return false
  229. }
  230. func checkDir(dir string) error {
  231. if info, err := os.Lstat(dir); err != nil {
  232. return err
  233. } else if !info.IsDir() {
  234. return errors.New(dir + ": not a directory")
  235. } else if debug {
  236. l.Debugln("checkDir", dir, info)
  237. }
  238. return nil
  239. }
  240. func PermsEqual(a, b uint32) bool {
  241. switch runtime.GOOS {
  242. case "windows":
  243. // There is only writeable and read only, represented for user, group
  244. // and other equally. We only compare against user.
  245. return a&0600 == b&0600
  246. default:
  247. // All bits count
  248. return a&0777 == b&0777
  249. }
  250. }