walk.go 6.9 KB

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