walk.go 12 KB

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