walk_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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 https://mozilla.org/MPL/2.0/.
  6. package scanner
  7. import (
  8. "bytes"
  9. "context"
  10. "crypto/rand"
  11. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "os"
  15. "path/filepath"
  16. "runtime"
  17. rdebug "runtime/debug"
  18. "sort"
  19. "sync"
  20. "testing"
  21. "github.com/d4l3k/messagediff"
  22. "github.com/syncthing/syncthing/lib/fs"
  23. "github.com/syncthing/syncthing/lib/ignore"
  24. "github.com/syncthing/syncthing/lib/osutil"
  25. "github.com/syncthing/syncthing/lib/protocol"
  26. "github.com/syncthing/syncthing/lib/sha256"
  27. "golang.org/x/text/unicode/norm"
  28. )
  29. type testfile struct {
  30. name string
  31. length int64
  32. hash string
  33. }
  34. type testfileList []testfile
  35. var testdata = testfileList{
  36. {"afile", 4, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"},
  37. {"dir1", 128, ""},
  38. {filepath.Join("dir1", "dfile"), 5, "49ae93732fcf8d63fe1cce759664982dbd5b23161f007dba8561862adc96d063"},
  39. {"dir2", 128, ""},
  40. {filepath.Join("dir2", "cfile"), 4, "bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c"},
  41. {"excludes", 37, "df90b52f0c55dba7a7a940affe482571563b1ac57bd5be4d8a0291e7de928e06"},
  42. {"further-excludes", 5, "7eb0a548094fa6295f7fd9200d69973e5f5ec5c04f2a86d998080ac43ecf89f1"},
  43. }
  44. func init() {
  45. // This test runs the risk of entering infinite recursion if it fails.
  46. // Limit the stack size to 10 megs to crash early in that case instead of
  47. // potentially taking down the box...
  48. rdebug.SetMaxStack(10 * 1 << 20)
  49. }
  50. func TestWalkSub(t *testing.T) {
  51. ignores := ignore.New(fs.NewFilesystem(fs.FilesystemTypeBasic, "."))
  52. err := ignores.Load("testdata/.stignore")
  53. if err != nil {
  54. t.Fatal(err)
  55. }
  56. fchan := Walk(context.TODO(), Config{
  57. Filesystem: fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata"),
  58. Subs: []string{"dir2"},
  59. BlockSize: 128 * 1024,
  60. Matcher: ignores,
  61. Hashers: 2,
  62. })
  63. var files []protocol.FileInfo
  64. for f := range fchan {
  65. files = append(files, f)
  66. }
  67. // The directory contains two files, where one is ignored from a higher
  68. // level. We should see only the directory and one of the files.
  69. if len(files) != 2 {
  70. t.Fatalf("Incorrect length %d != 2", len(files))
  71. }
  72. if files[0].Name != "dir2" {
  73. t.Errorf("Incorrect file %v != dir2", files[0])
  74. }
  75. if files[1].Name != filepath.Join("dir2", "cfile") {
  76. t.Errorf("Incorrect file %v != dir2/cfile", files[1])
  77. }
  78. }
  79. func TestWalk(t *testing.T) {
  80. ignores := ignore.New(fs.NewFilesystem(fs.FilesystemTypeBasic, "."))
  81. err := ignores.Load("testdata/.stignore")
  82. if err != nil {
  83. t.Fatal(err)
  84. }
  85. t.Log(ignores)
  86. fchan := Walk(context.TODO(), Config{
  87. Filesystem: fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata"),
  88. BlockSize: 128 * 1024,
  89. Matcher: ignores,
  90. Hashers: 2,
  91. })
  92. var tmp []protocol.FileInfo
  93. for f := range fchan {
  94. tmp = append(tmp, f)
  95. }
  96. sort.Sort(fileList(tmp))
  97. files := fileList(tmp).testfiles()
  98. if diff, equal := messagediff.PrettyDiff(testdata, files); !equal {
  99. t.Errorf("Walk returned unexpected data. Diff:\n%s", diff)
  100. }
  101. }
  102. func TestVerify(t *testing.T) {
  103. blocksize := 16
  104. // data should be an even multiple of blocksize long
  105. data := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut e")
  106. buf := bytes.NewBuffer(data)
  107. progress := newByteCounter()
  108. defer progress.Close()
  109. blocks, err := Blocks(context.TODO(), buf, blocksize, -1, progress, false)
  110. if err != nil {
  111. t.Fatal(err)
  112. }
  113. if exp := len(data) / blocksize; len(blocks) != exp {
  114. t.Fatalf("Incorrect number of blocks %d != %d", len(blocks), exp)
  115. }
  116. if int64(len(data)) != progress.Total() {
  117. t.Fatalf("Incorrect counter value %d != %d", len(data), progress.Total())
  118. }
  119. buf = bytes.NewBuffer(data)
  120. err = verify(buf, blocksize, blocks)
  121. t.Log(err)
  122. if err != nil {
  123. t.Fatal("Unexpected verify failure", err)
  124. }
  125. buf = bytes.NewBuffer(append(data, '\n'))
  126. err = verify(buf, blocksize, blocks)
  127. t.Log(err)
  128. if err == nil {
  129. t.Fatal("Unexpected verify success")
  130. }
  131. buf = bytes.NewBuffer(data[:len(data)-1])
  132. err = verify(buf, blocksize, blocks)
  133. t.Log(err)
  134. if err == nil {
  135. t.Fatal("Unexpected verify success")
  136. }
  137. data[42] = 42
  138. buf = bytes.NewBuffer(data)
  139. err = verify(buf, blocksize, blocks)
  140. t.Log(err)
  141. if err == nil {
  142. t.Fatal("Unexpected verify success")
  143. }
  144. }
  145. func TestNormalization(t *testing.T) {
  146. if runtime.GOOS == "darwin" {
  147. t.Skip("Normalization test not possible on darwin")
  148. return
  149. }
  150. os.RemoveAll("testdata/normalization")
  151. defer os.RemoveAll("testdata/normalization")
  152. tests := []string{
  153. "0-A", // ASCII A -- accepted
  154. "1-\xC3\x84", // NFC 'Ä' -- conflicts with the entry below, accepted
  155. "1-\x41\xCC\x88", // NFD 'Ä' -- conflicts with the entry above, ignored
  156. "2-\xC3\x85", // NFC 'Å' -- accepted
  157. "3-\x41\xCC\x83", // NFD 'Ã' -- converted to NFC
  158. "4-\xE2\x98\x95", // U+2615 HOT BEVERAGE (☕) -- accepted
  159. "5-\xCD\xE2", // EUC-CN "wài" (外) -- ignored (not UTF8)
  160. }
  161. numInvalid := 2
  162. if runtime.GOOS == "windows" {
  163. // On Windows, in case 5 the character gets replaced with a
  164. // replacement character \xEF\xBF\xBD at the point it's written to disk,
  165. // which means it suddenly becomes valid (sort of).
  166. numInvalid--
  167. }
  168. numValid := len(tests) - numInvalid
  169. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, ".")
  170. for _, s1 := range tests {
  171. // Create a directory for each of the interesting strings above
  172. if err := fs.MkdirAll(filepath.Join("testdata/normalization", s1), 0755); err != nil {
  173. t.Fatal(err)
  174. }
  175. for _, s2 := range tests {
  176. // Within each dir, create a file with each of the interesting
  177. // file names. Ensure that the file doesn't exist when it's
  178. // created. This detects and fails if there's file name
  179. // normalization stuff at the filesystem level.
  180. if fd, err := fs.OpenFile(filepath.Join("testdata/normalization", s1, s2), os.O_CREATE|os.O_EXCL, 0644); err != nil {
  181. t.Fatal(err)
  182. } else {
  183. fd.Write([]byte("test"))
  184. fd.Close()
  185. }
  186. }
  187. }
  188. // We can normalize a directory name, but we can't descend into it in the
  189. // same pass due to how filepath.Walk works. So we run the scan twice to
  190. // make sure it all gets done. In production, things will be correct
  191. // eventually...
  192. _, err := walkDir(fs, "testdata/normalization")
  193. if err != nil {
  194. t.Fatal(err)
  195. }
  196. tmp, err := walkDir(fs, "testdata/normalization")
  197. if err != nil {
  198. t.Fatal(err)
  199. }
  200. files := fileList(tmp).testfiles()
  201. // We should have one file per combination, plus the directories
  202. // themselves, plus the "testdata/normalization" directory
  203. expectedNum := numValid*numValid + numValid + 1
  204. if len(files) != expectedNum {
  205. t.Errorf("Expected %d files, got %d", expectedNum, len(files))
  206. }
  207. // The file names should all be in NFC form.
  208. for _, f := range files {
  209. t.Logf("%q (% x) %v", f.name, f.name, norm.NFC.IsNormalString(f.name))
  210. if !norm.NFC.IsNormalString(f.name) {
  211. t.Errorf("File name %q is not NFC normalized", f.name)
  212. }
  213. }
  214. }
  215. func TestIssue1507(t *testing.T) {
  216. w := &walker{}
  217. c := make(chan protocol.FileInfo, 100)
  218. fn := w.walkAndHashFiles(context.TODO(), c, c)
  219. fn("", nil, protocol.ErrClosed)
  220. }
  221. func TestWalkSymlinkUnix(t *testing.T) {
  222. if runtime.GOOS == "windows" {
  223. t.Skip("skipping unsupported symlink test")
  224. return
  225. }
  226. // Create a folder with a symlink in it
  227. os.RemoveAll("_symlinks")
  228. os.Mkdir("_symlinks", 0755)
  229. defer os.RemoveAll("_symlinks")
  230. os.Symlink("../testdata", "_symlinks/link")
  231. for _, path := range []string{".", "link"} {
  232. // Scan it
  233. files, _ := walkDir(fs.NewFilesystem(fs.FilesystemTypeBasic, "_symlinks"), path)
  234. // Verify that we got one symlink and with the correct attributes
  235. if len(files) != 1 {
  236. t.Errorf("expected 1 symlink, not %d", len(files))
  237. }
  238. if len(files[0].Blocks) != 0 {
  239. t.Errorf("expected zero blocks for symlink, not %d", len(files[0].Blocks))
  240. }
  241. if files[0].SymlinkTarget != "../testdata" {
  242. t.Errorf("expected symlink to have target destination, not %q", files[0].SymlinkTarget)
  243. }
  244. }
  245. }
  246. func TestWalkSymlinkWindows(t *testing.T) {
  247. if runtime.GOOS != "windows" {
  248. t.Skip("skipping unsupported symlink test")
  249. }
  250. // Create a folder with a symlink in it
  251. os.RemoveAll("_symlinks")
  252. os.Mkdir("_symlinks", 0755)
  253. defer os.RemoveAll("_symlinks")
  254. if err := osutil.DebugSymlinkForTestsOnly("../testdata", "_symlinks/link"); err != nil {
  255. // Probably we require permissions we don't have.
  256. t.Skip(err)
  257. }
  258. for _, path := range []string{".", "link"} {
  259. // Scan it
  260. files, _ := walkDir(fs.NewFilesystem(fs.FilesystemTypeBasic, "_symlinks"), path)
  261. // Verify that we got zero symlinks
  262. if len(files) != 0 {
  263. t.Errorf("expected zero symlinks, not %d", len(files))
  264. }
  265. }
  266. }
  267. func TestWalkRootSymlink(t *testing.T) {
  268. // Create a folder with a symlink in it
  269. tmp, err := ioutil.TempDir("", "")
  270. if err != nil {
  271. t.Fatal(err)
  272. }
  273. defer os.RemoveAll(tmp)
  274. link := tmp + "/link"
  275. dest, _ := filepath.Abs("testdata/dir1")
  276. if err := osutil.DebugSymlinkForTestsOnly(dest, link); err != nil {
  277. if runtime.GOOS == "windows" {
  278. // Probably we require permissions we don't have.
  279. t.Skip("Need admin permissions or developer mode to run symlink test on Windows: " + err.Error())
  280. } else {
  281. t.Fatal(err)
  282. }
  283. }
  284. // Scan it
  285. files, err := walkDir(fs.NewFilesystem(fs.FilesystemTypeBasic, link), ".")
  286. if err != nil {
  287. t.Fatal("Expected no error when root folder path is provided via a symlink: " + err.Error())
  288. }
  289. // Verify that we got two files
  290. if len(files) != 2 {
  291. t.Errorf("expected two files, not %d", len(files))
  292. }
  293. }
  294. func walkDir(fs fs.Filesystem, dir string) ([]protocol.FileInfo, error) {
  295. fchan := Walk(context.TODO(), Config{
  296. Filesystem: fs,
  297. Subs: []string{dir},
  298. BlockSize: 128 * 1024,
  299. AutoNormalize: true,
  300. Hashers: 2,
  301. })
  302. var tmp []protocol.FileInfo
  303. for f := range fchan {
  304. tmp = append(tmp, f)
  305. }
  306. sort.Sort(fileList(tmp))
  307. return tmp, nil
  308. }
  309. type fileList []protocol.FileInfo
  310. func (l fileList) Len() int {
  311. return len(l)
  312. }
  313. func (l fileList) Less(a, b int) bool {
  314. return l[a].Name < l[b].Name
  315. }
  316. func (l fileList) Swap(a, b int) {
  317. l[a], l[b] = l[b], l[a]
  318. }
  319. func (l fileList) testfiles() testfileList {
  320. testfiles := make(testfileList, len(l))
  321. for i, f := range l {
  322. if len(f.Blocks) > 1 {
  323. panic("simple test case stuff only supports a single block per file")
  324. }
  325. testfiles[i] = testfile{name: f.Name, length: f.FileSize()}
  326. if len(f.Blocks) == 1 {
  327. testfiles[i].hash = fmt.Sprintf("%x", f.Blocks[0].Hash)
  328. }
  329. }
  330. return testfiles
  331. }
  332. func (l testfileList) String() string {
  333. var b bytes.Buffer
  334. b.WriteString("{\n")
  335. for _, f := range l {
  336. fmt.Fprintf(&b, " %s (%d bytes): %s\n", f.name, f.length, f.hash)
  337. }
  338. b.WriteString("}")
  339. return b.String()
  340. }
  341. var initOnce sync.Once
  342. const (
  343. testdataSize = 17 << 20
  344. testdataName = "_random.data"
  345. )
  346. func BenchmarkHashFile(b *testing.B) {
  347. initOnce.Do(initTestFile)
  348. b.ResetTimer()
  349. for i := 0; i < b.N; i++ {
  350. if _, err := HashFile(context.TODO(), fs.NewFilesystem(fs.FilesystemTypeBasic, ""), testdataName, protocol.BlockSize, nil, true); err != nil {
  351. b.Fatal(err)
  352. }
  353. }
  354. b.SetBytes(testdataSize)
  355. b.ReportAllocs()
  356. }
  357. func initTestFile() {
  358. fd, err := os.Create(testdataName)
  359. if err != nil {
  360. panic(err)
  361. }
  362. lr := io.LimitReader(rand.Reader, testdataSize)
  363. if _, err := io.Copy(fd, lr); err != nil {
  364. panic(err)
  365. }
  366. if err := fd.Close(); err != nil {
  367. panic(err)
  368. }
  369. }
  370. func TestStopWalk(t *testing.T) {
  371. // Create tree that is 100 levels deep, with each level containing 100
  372. // files (each 1 MB) and 100 directories (in turn containing 100 files
  373. // and 100 directories, etc). That is, in total > 100^100 files and as
  374. // many directories. It'll take a while to scan, giving us time to
  375. // cancel it and make sure the scan stops.
  376. // Use an errorFs as the backing fs for the rest of the interface
  377. // The way we get it is a bit hacky tho.
  378. errorFs := fs.NewFilesystem(fs.FilesystemType(-1), ".")
  379. fs := fs.NewWalkFilesystem(&infiniteFS{errorFs, 100, 100, 1e6})
  380. const numHashers = 4
  381. ctx, cancel := context.WithCancel(context.Background())
  382. fchan := Walk(ctx, Config{
  383. Filesystem: fs,
  384. BlockSize: 128 * 1024,
  385. Hashers: numHashers,
  386. ProgressTickIntervalS: -1, // Don't attempt to build the full list of files before starting to scan...
  387. })
  388. // Receive a few entries to make sure the walker is up and running,
  389. // scanning both files and dirs. Do some quick sanity tests on the
  390. // returned file entries to make sure we are not just reading crap from
  391. // a closed channel or something.
  392. dirs := 0
  393. files := 0
  394. for {
  395. f := <-fchan
  396. t.Log("Scanned", f)
  397. if f.IsDirectory() {
  398. if len(f.Name) == 0 || f.Permissions == 0 {
  399. t.Error("Bad directory entry", f)
  400. }
  401. dirs++
  402. } else {
  403. if len(f.Name) == 0 || len(f.Blocks) == 0 || f.Permissions == 0 {
  404. t.Error("Bad file entry", f)
  405. }
  406. files++
  407. }
  408. if dirs > 5 && files > 5 {
  409. break
  410. }
  411. }
  412. // Cancel the walker.
  413. cancel()
  414. // Empty out any waiting entries and wait for the channel to close.
  415. // Count them, they should be zero or very few - essentially, each
  416. // hasher has the choice of returning a fully handled entry or
  417. // cancelling, but they should not start on another item.
  418. extra := 0
  419. for range fchan {
  420. extra++
  421. }
  422. t.Log("Extra entries:", extra)
  423. if extra > numHashers {
  424. t.Error("unexpected extra entries received after cancel")
  425. }
  426. }
  427. func TestIssue4799(t *testing.T) {
  428. tmp, err := ioutil.TempDir("", "")
  429. if err != nil {
  430. t.Fatal(err)
  431. }
  432. defer os.RemoveAll(tmp)
  433. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, tmp)
  434. fd, err := fs.Create("foo")
  435. if err != nil {
  436. t.Fatal(err)
  437. }
  438. fd.Close()
  439. files, err := walkDir(fs, "/foo")
  440. if err != nil {
  441. t.Fatal(err)
  442. }
  443. if len(files) != 1 || files[0].Name != "foo" {
  444. t.Error(`Received unexpected file infos when walking "/foo"`, files)
  445. }
  446. }
  447. // Verify returns nil or an error describing the mismatch between the block
  448. // list and actual reader contents
  449. func verify(r io.Reader, blocksize int, blocks []protocol.BlockInfo) error {
  450. hf := sha256.New()
  451. // A 32k buffer is used for copying into the hash function.
  452. buf := make([]byte, 32<<10)
  453. for i, block := range blocks {
  454. lr := &io.LimitedReader{R: r, N: int64(blocksize)}
  455. _, err := io.CopyBuffer(hf, lr, buf)
  456. if err != nil {
  457. return err
  458. }
  459. hash := hf.Sum(nil)
  460. hf.Reset()
  461. if !bytes.Equal(hash, block.Hash) {
  462. return fmt.Errorf("hash mismatch %x != %x for block %d", hash, block.Hash, i)
  463. }
  464. }
  465. // We should have reached the end now
  466. bs := make([]byte, 1)
  467. n, err := r.Read(bs)
  468. if n != 0 || err != io.EOF {
  469. return fmt.Errorf("file continues past end of blocks")
  470. }
  471. return nil
  472. }