walk.go 11 KB

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