walk.go 7.4 KB

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