walk.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. // info nil when error is not nil
  100. if info != nil && info.IsDir() {
  101. skip = filepath.SkipDir
  102. }
  103. if err != nil {
  104. if debug {
  105. l.Debugln("error:", p, info, err)
  106. }
  107. return skip
  108. }
  109. rn, err := filepath.Rel(w.Dir, p)
  110. if err != nil {
  111. if debug {
  112. l.Debugln("rel error:", p, err)
  113. }
  114. return skip
  115. }
  116. if rn == "." {
  117. return nil
  118. }
  119. if w.TempNamer != nil && w.TempNamer.IsTemporary(rn) {
  120. // A temporary file
  121. if debug {
  122. l.Debugln("temporary:", rn)
  123. }
  124. if info.Mode().IsRegular() && info.ModTime().Add(w.TempLifetime).Before(now) {
  125. os.Remove(p)
  126. if debug {
  127. l.Debugln("removing temporary:", rn, info.ModTime())
  128. }
  129. }
  130. return nil
  131. }
  132. if sn := filepath.Base(rn); sn == ".stignore" || sn == ".stfolder" ||
  133. strings.HasPrefix(rn, ".stversions") || (w.Matcher != nil && w.Matcher.Match(rn)) {
  134. // An ignored file
  135. if debug {
  136. l.Debugln("ignored:", rn)
  137. }
  138. return skip
  139. }
  140. if !utf8.ValidString(rn) {
  141. l.Warnf("File name %q is not in UTF8 encoding; skipping.", rn)
  142. return skip
  143. }
  144. var normalizedRn string
  145. if runtime.GOOS == "darwin" {
  146. // Mac OS X file names should always be NFD normalized.
  147. normalizedRn = norm.NFD.String(rn)
  148. } else {
  149. // Every other OS in the known universe uses NFC or just plain
  150. // doesn't bother to define an encoding. In our case *we* do care,
  151. // so we enforce NFC regardless.
  152. normalizedRn = norm.NFC.String(rn)
  153. }
  154. if rn != normalizedRn {
  155. // The file name was not normalized.
  156. if !w.AutoNormalize {
  157. // We're not authorized to do anything about it, so complain and skip.
  158. l.Warnf("File name %q is not in the correct UTF8 normalization form; skipping.", rn)
  159. return skip
  160. }
  161. // We will attempt to normalize it.
  162. normalizedPath := filepath.Join(w.Dir, normalizedRn)
  163. if _, err := os.Lstat(normalizedPath); os.IsNotExist(err) {
  164. // Nothing exists with the normalized filename. Good.
  165. if err = os.Rename(p, normalizedPath); err != nil {
  166. l.Infof(`Error normalizing UTF8 encoding of file "%s": %v`, rn, err)
  167. return skip
  168. }
  169. l.Infof(`Normalized UTF8 encoding of file name "%s".`, rn)
  170. } else {
  171. // There is something already in the way at the normalized
  172. // file name.
  173. l.Infof(`File "%s" has UTF8 encoding conflict with another file; ignoring.`, rn)
  174. return skip
  175. }
  176. rn = normalizedRn
  177. }
  178. // Index wise symlinks are always files, regardless of what the target
  179. // is, because symlinks carry their target path as their content.
  180. if info.Mode()&os.ModeSymlink == os.ModeSymlink {
  181. // If the target is a directory, do NOT descend down there. This
  182. // will cause files to get tracked, and removing the symlink will
  183. // as a result remove files in their real location.
  184. if !symlinks.Supported {
  185. return skip
  186. }
  187. // We always rehash symlinks as they have no modtime or
  188. // permissions. We check if they point to the old target by
  189. // checking that their existing blocks match with the blocks in
  190. // the index.
  191. target, flags, err := symlinks.Read(p)
  192. flags = flags & protocol.SymlinkTypeMask
  193. if err != nil {
  194. if debug {
  195. l.Debugln("readlink error:", p, err)
  196. }
  197. return skip
  198. }
  199. blocks, err := Blocks(strings.NewReader(target), w.BlockSize, 0)
  200. if err != nil {
  201. if debug {
  202. l.Debugln("hash link error:", p, err)
  203. }
  204. return skip
  205. }
  206. if w.CurrentFiler != nil {
  207. // A symlink is "unchanged", if
  208. // - it exists
  209. // - it wasn't deleted (because it isn't now)
  210. // - it was a symlink
  211. // - it wasn't invalid
  212. // - the symlink type (file/dir) was the same
  213. // - the block list (i.e. hash of target) was the same
  214. cf, ok := w.CurrentFiler.CurrentFile(rn)
  215. if ok && !cf.IsDeleted() && cf.IsSymlink() && !cf.IsInvalid() && SymlinkTypeEqual(flags, cf.Flags) && BlocksEqual(cf.Blocks, blocks) {
  216. return skip
  217. }
  218. }
  219. f := protocol.FileInfo{
  220. Name: rn,
  221. Version: lamport.Default.Tick(0),
  222. Flags: protocol.FlagSymlink | flags | protocol.FlagNoPermBits | 0666,
  223. Modified: 0,
  224. Blocks: blocks,
  225. }
  226. if debug {
  227. l.Debugln("symlink to hash:", p, f)
  228. }
  229. fchan <- f
  230. return skip
  231. }
  232. if info.Mode().IsDir() {
  233. if w.CurrentFiler != nil {
  234. // A directory is "unchanged", if it
  235. // - exists
  236. // - has the same permissions as previously, unless we are ignoring permissions
  237. // - was not marked deleted (since it apparently exists now)
  238. // - was a directory previously (not a file or something else)
  239. // - was not a symlink (since it's a directory now)
  240. // - was not invalid (since it looks valid now)
  241. cf, ok := w.CurrentFiler.CurrentFile(rn)
  242. permUnchanged := w.IgnorePerms || !cf.HasPermissionBits() || PermsEqual(cf.Flags, uint32(info.Mode()))
  243. if ok && permUnchanged && !cf.IsDeleted() && cf.IsDirectory() && !cf.IsSymlink() && !cf.IsInvalid() {
  244. return nil
  245. }
  246. }
  247. flags := uint32(protocol.FlagDirectory)
  248. if w.IgnorePerms {
  249. flags |= protocol.FlagNoPermBits | 0777
  250. } else {
  251. flags |= uint32(info.Mode() & maskModePerm)
  252. }
  253. f := protocol.FileInfo{
  254. Name: rn,
  255. Version: lamport.Default.Tick(0),
  256. Flags: flags,
  257. Modified: info.ModTime().Unix(),
  258. }
  259. if debug {
  260. l.Debugln("dir:", p, f)
  261. }
  262. fchan <- f
  263. return nil
  264. }
  265. if info.Mode().IsRegular() {
  266. if w.CurrentFiler != nil {
  267. // A file is "unchanged", if it
  268. // - exists
  269. // - has the same permissions as previously, unless we are ignoring permissions
  270. // - was not marked deleted (since it apparently exists now)
  271. // - had the same modification time as it has now
  272. // - was not a directory previously (since it's a file now)
  273. // - was not a symlink (since it's a file now)
  274. // - was not invalid (since it looks valid now)
  275. // - has the same size as previously
  276. cf, ok := w.CurrentFiler.CurrentFile(rn)
  277. permUnchanged := w.IgnorePerms || !cf.HasPermissionBits() || PermsEqual(cf.Flags, uint32(info.Mode()))
  278. if ok && permUnchanged && !cf.IsDeleted() && cf.Modified == info.ModTime().Unix() && !cf.IsDirectory() &&
  279. !cf.IsSymlink() && !cf.IsInvalid() && cf.Size() == info.Size() {
  280. return nil
  281. }
  282. if debug {
  283. l.Debugln("rescan:", cf, info.ModTime().Unix(), info.Mode()&os.ModePerm)
  284. }
  285. }
  286. var flags = uint32(info.Mode() & maskModePerm)
  287. if w.IgnorePerms {
  288. flags = protocol.FlagNoPermBits | 0666
  289. }
  290. f := protocol.FileInfo{
  291. Name: rn,
  292. Version: lamport.Default.Tick(0),
  293. Flags: flags,
  294. Modified: info.ModTime().Unix(),
  295. }
  296. if debug {
  297. l.Debugln("to hash:", p, f)
  298. }
  299. fchan <- f
  300. }
  301. return nil
  302. }
  303. }
  304. func checkDir(dir string) error {
  305. if info, err := os.Lstat(dir); err != nil {
  306. return err
  307. } else if !info.IsDir() {
  308. return errors.New(dir + ": not a directory")
  309. } else if debug {
  310. l.Debugln("checkDir", dir, info)
  311. }
  312. return nil
  313. }
  314. func PermsEqual(a, b uint32) bool {
  315. switch runtime.GOOS {
  316. case "windows":
  317. // There is only writeable and read only, represented for user, group
  318. // and other equally. We only compare against user.
  319. return a&0600 == b&0600
  320. default:
  321. // All bits count
  322. return a&0777 == b&0777
  323. }
  324. }
  325. // If the target is missing, Unix never knows what type of symlink it is
  326. // and Windows always knows even if there is no target.
  327. // Which means that without this special check a Unix node would be fighting
  328. // with a Windows node about whether or not the target is known.
  329. // Basically, if you don't know and someone else knows, just accept it.
  330. // The fact that you don't know means you are on Unix, and on Unix you don't
  331. // really care what the target type is. The moment you do know, and if something
  332. // doesn't match, that will propogate throught the cluster.
  333. func SymlinkTypeEqual(disk, index uint32) bool {
  334. if disk&protocol.FlagSymlinkMissingTarget != 0 && index&protocol.FlagSymlinkMissingTarget == 0 {
  335. return true
  336. }
  337. return disk&protocol.SymlinkTypeMask == index&protocol.SymlinkTypeMask
  338. }