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