walk.go 11 KB

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