walk.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. "time"
  14. "unicode/utf8"
  15. "github.com/syncthing/protocol"
  16. "github.com/syncthing/syncthing/internal/ignore"
  17. "github.com/syncthing/syncthing/internal/lamport"
  18. "github.com/syncthing/syncthing/internal/symlinks"
  19. "golang.org/x/text/unicode/norm"
  20. )
  21. var maskModePerm os.FileMode
  22. func init() {
  23. if runtime.GOOS == "windows" {
  24. // There is no user/group/others in Windows' read-only
  25. // attribute, and all "w" bits are set in os.FileInfo
  26. // if the file is not read-only. Do not send these
  27. // group/others-writable bits to other devices in order to
  28. // avoid unexpected world-writable files on other platforms.
  29. maskModePerm = os.ModePerm & 0755
  30. } else {
  31. maskModePerm = os.ModePerm
  32. }
  33. }
  34. type Walker struct {
  35. // Dir is the base directory for the walk
  36. Dir string
  37. // Limit walking to this path within Dir, or no limit if Sub is blank
  38. Sub string
  39. // BlockSize controls the size of the block used when hashing.
  40. BlockSize int
  41. // If Matcher is not nil, it is used to identify files to ignore which were specified by the user.
  42. Matcher *ignore.Matcher
  43. // If TempNamer is not nil, it is used to ignore tempory files when walking.
  44. TempNamer TempNamer
  45. // Number of hours to keep temporary files for
  46. TempLifetime time.Duration
  47. // If CurrentFiler is not nil, it is queried for the current file before rescanning.
  48. CurrentFiler CurrentFiler
  49. // If IgnorePerms is true, changes to permission bits will not be
  50. // detected. Scanned files will get zero permission bits and the
  51. // NoPermissionBits flag set.
  52. IgnorePerms bool
  53. // When AutoNormalize is set, file names that are in UTF8 but incorrect
  54. // normalization form will be corrected.
  55. AutoNormalize bool
  56. // Number of routines to use for hashing
  57. Hashers int
  58. }
  59. type TempNamer interface {
  60. // Temporary returns a temporary name for the filed referred to by filepath.
  61. TempName(path string) string
  62. // IsTemporary returns true if path refers to the name of temporary file.
  63. IsTemporary(path string) bool
  64. }
  65. type CurrentFiler interface {
  66. // CurrentFile returns the file as seen at last scan.
  67. CurrentFile(name string) (protocol.FileInfo, bool)
  68. }
  69. // Walk returns the list of files found in the local folder by scanning the
  70. // file system. Files are blockwise hashed.
  71. func (w *Walker) Walk() (chan protocol.FileInfo, error) {
  72. if debug {
  73. l.Debugln("Walk", w.Dir, w.Sub, w.BlockSize, w.Matcher)
  74. }
  75. err := checkDir(w.Dir)
  76. if err != nil {
  77. return nil, err
  78. }
  79. workers := w.Hashers
  80. if workers < 1 {
  81. workers = runtime.NumCPU()
  82. }
  83. files := make(chan protocol.FileInfo)
  84. hashedFiles := make(chan protocol.FileInfo)
  85. newParallelHasher(w.Dir, w.BlockSize, workers, hashedFiles, files)
  86. go func() {
  87. hashFiles := w.walkAndHashFiles(files)
  88. filepath.Walk(filepath.Join(w.Dir, w.Sub), hashFiles)
  89. close(files)
  90. }()
  91. return hashedFiles, nil
  92. }
  93. func (w *Walker) walkAndHashFiles(fchan chan protocol.FileInfo) filepath.WalkFunc {
  94. now := time.Now()
  95. return func(p string, info os.FileInfo, err error) error {
  96. // Return value used when we are returning early and don't want to
  97. // process the item. For directories, this means do-not-descend.
  98. var skip error // nil
  99. if info.IsDir() {
  100. skip = filepath.SkipDir
  101. }
  102. if err != nil {
  103. if debug {
  104. l.Debugln("error:", p, info, err)
  105. }
  106. return skip
  107. }
  108. rn, err := filepath.Rel(w.Dir, p)
  109. if err != nil {
  110. if debug {
  111. l.Debugln("rel error:", p, err)
  112. }
  113. return skip
  114. }
  115. if rn == "." {
  116. return nil
  117. }
  118. if w.TempNamer != nil && w.TempNamer.IsTemporary(rn) {
  119. // A temporary file
  120. if debug {
  121. l.Debugln("temporary:", rn)
  122. }
  123. if info.Mode().IsRegular() && info.ModTime().Add(w.TempLifetime).Before(now) {
  124. os.Remove(p)
  125. if debug {
  126. l.Debugln("removing temporary:", rn, info.ModTime())
  127. }
  128. }
  129. return nil
  130. }
  131. if sn := filepath.Base(rn); sn == ".stignore" || sn == ".stfolder" ||
  132. strings.HasPrefix(rn, ".stversions") || (w.Matcher != nil && w.Matcher.Match(rn)) {
  133. // An ignored file
  134. if debug {
  135. l.Debugln("ignored:", rn)
  136. }
  137. return skip
  138. }
  139. if !utf8.ValidString(rn) {
  140. l.Warnf("File name %q is not in UTF8 encoding; skipping.", rn)
  141. return skip
  142. }
  143. var normalizedRn string
  144. if runtime.GOOS == "darwin" {
  145. // Mac OS X file names should always be NFD normalized.
  146. normalizedRn = norm.NFD.String(rn)
  147. } else {
  148. // Every other OS in the known universe uses NFC or just plain
  149. // doesn't bother to define an encoding. In our case *we* do care,
  150. // so we enforce NFC regardless.
  151. normalizedRn = norm.NFC.String(rn)
  152. }
  153. if rn != normalizedRn {
  154. // The file name was not normalized.
  155. if !w.AutoNormalize {
  156. // We're not authorized to do anything about it, so complain and skip.
  157. l.Warnf("File name %q is not in the correct UTF8 normalization form; skipping.", rn)
  158. return skip
  159. }
  160. // We will attempt to normalize it.
  161. normalizedPath := filepath.Join(w.Dir, normalizedRn)
  162. if _, err := os.Lstat(normalizedPath); os.IsNotExist(err) {
  163. // Nothing exists with the normalized filename. Good.
  164. if err = os.Rename(p, normalizedPath); err != nil {
  165. l.Infof(`Error normalizing UTF8 encoding of file "%s": %v`, rn, err)
  166. return skip
  167. }
  168. l.Infof(`Normalized UTF8 encoding of file name "%s".`, rn)
  169. } else {
  170. // There is something already in the way at the normalized
  171. // file name.
  172. l.Infof(`File "%s" has UTF8 encoding conflict with another file; ignoring.`, rn)
  173. return skip
  174. }
  175. rn = normalizedRn
  176. }
  177. // Index wise symlinks are always files, regardless of what the target
  178. // is, because symlinks carry their target path as their content.
  179. if info.Mode()&os.ModeSymlink == os.ModeSymlink {
  180. // If the target is a directory, do NOT descend down there. This
  181. // will cause files to get tracked, and removing the symlink will
  182. // as a result remove files in their real location.
  183. if !symlinks.Supported {
  184. return skip
  185. }
  186. // We always rehash symlinks as they have no modtime or
  187. // permissions. We check if they point to the old target by
  188. // checking that their existing blocks match with the blocks in
  189. // the index.
  190. target, flags, err := symlinks.Read(p)
  191. flags = flags & protocol.SymlinkTypeMask
  192. if err != nil {
  193. if debug {
  194. l.Debugln("readlink error:", p, err)
  195. }
  196. return skip
  197. }
  198. blocks, err := Blocks(strings.NewReader(target), w.BlockSize, 0)
  199. if err != nil {
  200. if debug {
  201. l.Debugln("hash link error:", p, err)
  202. }
  203. return skip
  204. }
  205. if w.CurrentFiler != nil {
  206. // A symlink is "unchanged", if
  207. // - it exists
  208. // - it wasn't deleted (because it isn't now)
  209. // - it was a symlink
  210. // - it wasn't invalid
  211. // - the symlink type (file/dir) was the same
  212. // - the block list (i.e. hash of target) was the same
  213. cf, ok := w.CurrentFiler.CurrentFile(rn)
  214. if ok && !cf.IsDeleted() && cf.IsSymlink() && !cf.IsInvalid() && SymlinkTypeEqual(flags, cf.Flags) && BlocksEqual(cf.Blocks, blocks) {
  215. return skip
  216. }
  217. }
  218. f := protocol.FileInfo{
  219. Name: rn,
  220. Version: lamport.Default.Tick(0),
  221. Flags: protocol.FlagSymlink | flags | protocol.FlagNoPermBits | 0666,
  222. Modified: 0,
  223. Blocks: blocks,
  224. }
  225. if debug {
  226. l.Debugln("symlink to hash:", p, f)
  227. }
  228. fchan <- f
  229. return skip
  230. }
  231. if info.Mode().IsDir() {
  232. if w.CurrentFiler != nil {
  233. // A directory is "unchanged", if it
  234. // - exists
  235. // - has the same permissions as previously, unless we are ignoring permissions
  236. // - was not marked deleted (since it apparently exists now)
  237. // - was a directory previously (not a file or something else)
  238. // - was not a symlink (since it's a directory now)
  239. // - was not invalid (since it looks valid now)
  240. cf, ok := w.CurrentFiler.CurrentFile(rn)
  241. permUnchanged := w.IgnorePerms || !cf.HasPermissionBits() || PermsEqual(cf.Flags, uint32(info.Mode()))
  242. if ok && permUnchanged && !cf.IsDeleted() && cf.IsDirectory() && !cf.IsSymlink() && !cf.IsInvalid() {
  243. return nil
  244. }
  245. }
  246. flags := uint32(protocol.FlagDirectory)
  247. if w.IgnorePerms {
  248. flags |= protocol.FlagNoPermBits | 0777
  249. } else {
  250. flags |= uint32(info.Mode() & maskModePerm)
  251. }
  252. f := protocol.FileInfo{
  253. Name: rn,
  254. Version: lamport.Default.Tick(0),
  255. Flags: flags,
  256. Modified: info.ModTime().Unix(),
  257. }
  258. if debug {
  259. l.Debugln("dir:", p, f)
  260. }
  261. fchan <- f
  262. return nil
  263. }
  264. if info.Mode().IsRegular() {
  265. if w.CurrentFiler != nil {
  266. // A file is "unchanged", if it
  267. // - exists
  268. // - has the same permissions as previously, unless we are ignoring permissions
  269. // - was not marked deleted (since it apparently exists now)
  270. // - had the same modification time as it has now
  271. // - was not a directory previously (since it's a file now)
  272. // - was not a symlink (since it's a file now)
  273. // - was not invalid (since it looks valid now)
  274. // - has the same size as previously
  275. cf, ok := w.CurrentFiler.CurrentFile(rn)
  276. permUnchanged := w.IgnorePerms || !cf.HasPermissionBits() || PermsEqual(cf.Flags, uint32(info.Mode()))
  277. if ok && permUnchanged && !cf.IsDeleted() && cf.Modified == info.ModTime().Unix() && !cf.IsDirectory() &&
  278. !cf.IsSymlink() && !cf.IsInvalid() && cf.Size() == info.Size() {
  279. return nil
  280. }
  281. if debug {
  282. l.Debugln("rescan:", cf, info.ModTime().Unix(), info.Mode()&os.ModePerm)
  283. }
  284. }
  285. var flags = uint32(info.Mode() & maskModePerm)
  286. if w.IgnorePerms {
  287. flags = protocol.FlagNoPermBits | 0666
  288. }
  289. f := protocol.FileInfo{
  290. Name: rn,
  291. Version: lamport.Default.Tick(0),
  292. Flags: flags,
  293. Modified: info.ModTime().Unix(),
  294. }
  295. if debug {
  296. l.Debugln("to hash:", p, f)
  297. }
  298. fchan <- f
  299. }
  300. return nil
  301. }
  302. }
  303. func checkDir(dir string) error {
  304. if info, err := os.Lstat(dir); err != nil {
  305. return err
  306. } else if !info.IsDir() {
  307. return errors.New(dir + ": not a directory")
  308. } else if debug {
  309. l.Debugln("checkDir", dir, info)
  310. }
  311. return nil
  312. }
  313. func PermsEqual(a, b uint32) bool {
  314. switch runtime.GOOS {
  315. case "windows":
  316. // There is only writeable and read only, represented for user, group
  317. // and other equally. We only compare against user.
  318. return a&0600 == b&0600
  319. default:
  320. // All bits count
  321. return a&0777 == b&0777
  322. }
  323. }
  324. // If the target is missing, Unix never knows what type of symlink it is
  325. // and Windows always knows even if there is no target.
  326. // Which means that without this special check a Unix node would be fighting
  327. // with a Windows node about whether or not the target is known.
  328. // Basically, if you don't know and someone else knows, just accept it.
  329. // The fact that you don't know means you are on Unix, and on Unix you don't
  330. // really care what the target type is. The moment you do know, and if something
  331. // doesn't match, that will propogate throught the cluster.
  332. func SymlinkTypeEqual(disk, index uint32) bool {
  333. if disk&protocol.FlagSymlinkMissingTarget != 0 && index&protocol.FlagSymlinkMissingTarget == 0 {
  334. return true
  335. }
  336. return disk&protocol.SymlinkTypeMask == index&protocol.SymlinkTypeMask
  337. }