walk_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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/events"
  23. "github.com/syncthing/syncthing/lib/fs"
  24. "github.com/syncthing/syncthing/lib/ignore"
  25. "github.com/syncthing/syncthing/lib/osutil"
  26. "github.com/syncthing/syncthing/lib/protocol"
  27. "github.com/syncthing/syncthing/lib/sha256"
  28. "golang.org/x/text/unicode/norm"
  29. )
  30. type testfile struct {
  31. name string
  32. length int64
  33. hash string
  34. }
  35. type testfileList []testfile
  36. var testFs fs.Filesystem
  37. var testdata = testfileList{
  38. {"afile", 4, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"},
  39. {"dir1", 128, ""},
  40. {filepath.Join("dir1", "dfile"), 5, "49ae93732fcf8d63fe1cce759664982dbd5b23161f007dba8561862adc96d063"},
  41. {"dir2", 128, ""},
  42. {filepath.Join("dir2", "cfile"), 4, "bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c"},
  43. {"excludes", 37, "df90b52f0c55dba7a7a940affe482571563b1ac57bd5be4d8a0291e7de928e06"},
  44. {"further-excludes", 5, "7eb0a548094fa6295f7fd9200d69973e5f5ec5c04f2a86d998080ac43ecf89f1"},
  45. }
  46. func init() {
  47. // This test runs the risk of entering infinite recursion if it fails.
  48. // Limit the stack size to 10 megs to crash early in that case instead of
  49. // potentially taking down the box...
  50. rdebug.SetMaxStack(10 * 1 << 20)
  51. testFs = fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata")
  52. }
  53. func TestWalkSub(t *testing.T) {
  54. ignores := ignore.New(testFs)
  55. err := ignores.Load(".stignore")
  56. if err != nil {
  57. t.Fatal(err)
  58. }
  59. cfg := testConfig()
  60. cfg.Subs = []string{"dir2"}
  61. cfg.Matcher = ignores
  62. fchan := Walk(context.TODO(), cfg)
  63. var files []protocol.FileInfo
  64. for f := range fchan {
  65. if f.Err != nil {
  66. t.Errorf("Error while scanning %v: %v", f.Err, f.Path)
  67. }
  68. files = append(files, f.File)
  69. }
  70. // The directory contains two files, where one is ignored from a higher
  71. // level. We should see only the directory and one of the files.
  72. if len(files) != 2 {
  73. t.Fatalf("Incorrect length %d != 2", len(files))
  74. }
  75. if files[0].Name != "dir2" {
  76. t.Errorf("Incorrect file %v != dir2", files[0])
  77. }
  78. if files[1].Name != filepath.Join("dir2", "cfile") {
  79. t.Errorf("Incorrect file %v != dir2/cfile", files[1])
  80. }
  81. }
  82. func TestWalk(t *testing.T) {
  83. ignores := ignore.New(testFs)
  84. err := ignores.Load(".stignore")
  85. if err != nil {
  86. t.Fatal(err)
  87. }
  88. t.Log(ignores)
  89. cfg := testConfig()
  90. cfg.Matcher = ignores
  91. fchan := Walk(context.TODO(), cfg)
  92. var tmp []protocol.FileInfo
  93. for f := range fchan {
  94. if f.Err != nil {
  95. t.Errorf("Error while scanning %v: %v", f.Err, f.Path)
  96. }
  97. tmp = append(tmp, f.File)
  98. }
  99. sort.Sort(fileList(tmp))
  100. files := fileList(tmp).testfiles()
  101. if diff, equal := messagediff.PrettyDiff(testdata, files); !equal {
  102. t.Errorf("Walk returned unexpected data. Diff:\n%s", diff)
  103. }
  104. }
  105. func TestVerify(t *testing.T) {
  106. blocksize := 16
  107. // data should be an even multiple of blocksize long
  108. data := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut e")
  109. buf := bytes.NewBuffer(data)
  110. progress := newByteCounter()
  111. defer progress.Close()
  112. blocks, err := Blocks(context.TODO(), buf, blocksize, -1, progress, false)
  113. if err != nil {
  114. t.Fatal(err)
  115. }
  116. if exp := len(data) / blocksize; len(blocks) != exp {
  117. t.Fatalf("Incorrect number of blocks %d != %d", len(blocks), exp)
  118. }
  119. if int64(len(data)) != progress.Total() {
  120. t.Fatalf("Incorrect counter value %d != %d", len(data), progress.Total())
  121. }
  122. buf = bytes.NewBuffer(data)
  123. err = verify(buf, blocksize, blocks)
  124. t.Log(err)
  125. if err != nil {
  126. t.Fatal("Unexpected verify failure", err)
  127. }
  128. buf = bytes.NewBuffer(append(data, '\n'))
  129. err = verify(buf, blocksize, blocks)
  130. t.Log(err)
  131. if err == nil {
  132. t.Fatal("Unexpected verify success")
  133. }
  134. buf = bytes.NewBuffer(data[:len(data)-1])
  135. err = verify(buf, blocksize, blocks)
  136. t.Log(err)
  137. if err == nil {
  138. t.Fatal("Unexpected verify success")
  139. }
  140. data[42] = 42
  141. buf = bytes.NewBuffer(data)
  142. err = verify(buf, blocksize, blocks)
  143. t.Log(err)
  144. if err == nil {
  145. t.Fatal("Unexpected verify success")
  146. }
  147. }
  148. func TestNormalization(t *testing.T) {
  149. if runtime.GOOS == "darwin" {
  150. t.Skip("Normalization test not possible on darwin")
  151. return
  152. }
  153. os.RemoveAll("testdata/normalization")
  154. defer os.RemoveAll("testdata/normalization")
  155. tests := []string{
  156. "0-A", // ASCII A -- accepted
  157. "1-\xC3\x84", // NFC 'Ä' -- conflicts with the entry below, accepted
  158. "1-\x41\xCC\x88", // NFD 'Ä' -- conflicts with the entry above, ignored
  159. "2-\xC3\x85", // NFC 'Å' -- accepted
  160. "3-\x41\xCC\x83", // NFD 'Ã' -- converted to NFC
  161. "4-\xE2\x98\x95", // U+2615 HOT BEVERAGE (☕) -- accepted
  162. "5-\xCD\xE2", // EUC-CN "wài" (外) -- ignored (not UTF8)
  163. }
  164. numInvalid := 2
  165. if runtime.GOOS == "windows" {
  166. // On Windows, in case 5 the character gets replaced with a
  167. // replacement character \xEF\xBF\xBD at the point it's written to disk,
  168. // which means it suddenly becomes valid (sort of).
  169. numInvalid--
  170. }
  171. numValid := len(tests) - numInvalid
  172. for _, s1 := range tests {
  173. // Create a directory for each of the interesting strings above
  174. if err := testFs.MkdirAll(filepath.Join("normalization", s1), 0755); err != nil {
  175. t.Fatal(err)
  176. }
  177. for _, s2 := range tests {
  178. // Within each dir, create a file with each of the interesting
  179. // file names. Ensure that the file doesn't exist when it's
  180. // created. This detects and fails if there's file name
  181. // normalization stuff at the filesystem level.
  182. if fd, err := testFs.OpenFile(filepath.Join("normalization", s1, s2), os.O_CREATE|os.O_EXCL, 0644); err != nil {
  183. t.Fatal(err)
  184. } else {
  185. fd.Write([]byte("test"))
  186. fd.Close()
  187. }
  188. }
  189. }
  190. // We can normalize a directory name, but we can't descend into it in the
  191. // same pass due to how filepath.Walk works. So we run the scan twice to
  192. // make sure it all gets done. In production, things will be correct
  193. // eventually...
  194. walkDir(testFs, "normalization", nil, nil, 0)
  195. tmp := walkDir(testFs, "normalization", nil, nil, 0)
  196. files := fileList(tmp).testfiles()
  197. // We should have one file per combination, plus the directories
  198. // themselves, plus the "testdata/normalization" directory
  199. expectedNum := numValid*numValid + numValid + 1
  200. if len(files) != expectedNum {
  201. t.Errorf("Expected %d files, got %d", expectedNum, len(files))
  202. }
  203. // The file names should all be in NFC form.
  204. for _, f := range files {
  205. t.Logf("%q (% x) %v", f.name, f.name, norm.NFC.IsNormalString(f.name))
  206. if !norm.NFC.IsNormalString(f.name) {
  207. t.Errorf("File name %q is not NFC normalized", f.name)
  208. }
  209. }
  210. }
  211. func TestIssue1507(t *testing.T) {
  212. w := &walker{}
  213. w.Matcher = ignore.New(w.Filesystem)
  214. h := make(chan protocol.FileInfo, 100)
  215. f := make(chan ScanResult, 100)
  216. fn := w.walkAndHashFiles(context.TODO(), h, f)
  217. fn("", nil, protocol.ErrClosed)
  218. }
  219. func TestWalkSymlinkUnix(t *testing.T) {
  220. if runtime.GOOS == "windows" {
  221. t.Skip("skipping unsupported symlink test")
  222. return
  223. }
  224. // Create a folder with a symlink in it
  225. os.RemoveAll("_symlinks")
  226. os.Mkdir("_symlinks", 0755)
  227. defer os.RemoveAll("_symlinks")
  228. os.Symlink("../testdata", "_symlinks/link")
  229. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, "_symlinks")
  230. for _, path := range []string{".", "link"} {
  231. // Scan it
  232. files := walkDir(fs, path, nil, nil, 0)
  233. // Verify that we got one symlink and with the correct attributes
  234. if len(files) != 1 {
  235. t.Errorf("expected 1 symlink, not %d", len(files))
  236. }
  237. if len(files[0].Blocks) != 0 {
  238. t.Errorf("expected zero blocks for symlink, not %d", len(files[0].Blocks))
  239. }
  240. if files[0].SymlinkTarget != "../testdata" {
  241. t.Errorf("expected symlink to have target destination, not %q", files[0].SymlinkTarget)
  242. }
  243. }
  244. }
  245. func TestWalkSymlinkWindows(t *testing.T) {
  246. if runtime.GOOS != "windows" {
  247. t.Skip("skipping unsupported symlink test")
  248. }
  249. // Create a folder with a symlink in it
  250. name := "_symlinks-win"
  251. os.RemoveAll(name)
  252. os.Mkdir(name, 0755)
  253. defer os.RemoveAll(name)
  254. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, name)
  255. if err := osutil.DebugSymlinkForTestsOnly("../testdata", "_symlinks/link"); err != nil {
  256. // Probably we require permissions we don't have.
  257. t.Skip(err)
  258. }
  259. for _, path := range []string{".", "link"} {
  260. // Scan it
  261. files := walkDir(fs, path, nil, nil, 0)
  262. // Verify that we got zero symlinks
  263. if len(files) != 0 {
  264. t.Errorf("expected zero symlinks, not %d", len(files))
  265. }
  266. }
  267. }
  268. func TestWalkRootSymlink(t *testing.T) {
  269. // Create a folder with a symlink in it
  270. tmp, err := ioutil.TempDir("", "")
  271. if err != nil {
  272. t.Fatal(err)
  273. }
  274. defer os.RemoveAll(tmp)
  275. link := filepath.Join(tmp, "link")
  276. dest, _ := filepath.Abs("testdata/dir1")
  277. if err := osutil.DebugSymlinkForTestsOnly(dest, link); err != nil {
  278. if runtime.GOOS == "windows" {
  279. // Probably we require permissions we don't have.
  280. t.Skip("Need admin permissions or developer mode to run symlink test on Windows: " + err.Error())
  281. } else {
  282. t.Fatal(err)
  283. }
  284. }
  285. // Scan root with symlink at FS root
  286. files := walkDir(fs.NewFilesystem(fs.FilesystemTypeBasic, link), ".", nil, nil, 0)
  287. // Verify that we got two files
  288. if len(files) != 2 {
  289. t.Errorf("expected two files, not %d", len(files))
  290. }
  291. // Scan symlink below FS root
  292. files = walkDir(fs.NewFilesystem(fs.FilesystemTypeBasic, tmp), "link", nil, nil, 0)
  293. // Verify that we got the one symlink, except on windows
  294. if runtime.GOOS == "windows" {
  295. if len(files) != 0 {
  296. t.Errorf("expected no files, not %d", len(files))
  297. }
  298. } else if len(files) != 1 {
  299. t.Errorf("expected one file, not %d", len(files))
  300. }
  301. // Scan path below symlink
  302. files = walkDir(fs.NewFilesystem(fs.FilesystemTypeBasic, tmp), filepath.Join("link", "cfile"), nil, nil, 0)
  303. // Verify that we get nothing
  304. if len(files) != 0 {
  305. t.Errorf("expected no files, not %d", len(files))
  306. }
  307. }
  308. func TestBlocksizeHysteresis(t *testing.T) {
  309. // Verify that we select the right block size in the presence of old
  310. // file information.
  311. if testing.Short() {
  312. t.Skip("long and hard test")
  313. }
  314. sf := fs.NewWalkFilesystem(&singleFileFS{
  315. name: "testfile.dat",
  316. filesize: 500 << 20, // 500 MiB
  317. })
  318. current := make(fakeCurrentFiler)
  319. runTest := func(expectedBlockSize int) {
  320. files := walkDir(sf, ".", current, nil, 0)
  321. if len(files) != 1 {
  322. t.Fatalf("expected one file, not %d", len(files))
  323. }
  324. if s := files[0].BlockSize(); s != expectedBlockSize {
  325. t.Fatalf("incorrect block size %d != expected %d", s, expectedBlockSize)
  326. }
  327. }
  328. // Scan with no previous knowledge. We should get a 512 KiB block size.
  329. runTest(512 << 10)
  330. // Scan on the assumption that previous size was 256 KiB. Retain 256 KiB
  331. // block size.
  332. current["testfile.dat"] = protocol.FileInfo{
  333. Name: "testfile.dat",
  334. Size: 500 << 20,
  335. RawBlockSize: 256 << 10,
  336. }
  337. runTest(256 << 10)
  338. // Scan on the assumption that previous size was 1 MiB. Retain 1 MiB
  339. // block size.
  340. current["testfile.dat"] = protocol.FileInfo{
  341. Name: "testfile.dat",
  342. Size: 500 << 20,
  343. RawBlockSize: 1 << 20,
  344. }
  345. runTest(1 << 20)
  346. // Scan on the assumption that previous size was 128 KiB. Move to 512
  347. // KiB because the difference is large.
  348. current["testfile.dat"] = protocol.FileInfo{
  349. Name: "testfile.dat",
  350. Size: 500 << 20,
  351. RawBlockSize: 128 << 10,
  352. }
  353. runTest(512 << 10)
  354. // Scan on the assumption that previous size was 2 MiB. Move to 512
  355. // KiB because the difference is large.
  356. current["testfile.dat"] = protocol.FileInfo{
  357. Name: "testfile.dat",
  358. Size: 500 << 20,
  359. RawBlockSize: 2 << 20,
  360. }
  361. runTest(512 << 10)
  362. }
  363. func TestWalkReceiveOnly(t *testing.T) {
  364. sf := fs.NewWalkFilesystem(&singleFileFS{
  365. name: "testfile.dat",
  366. filesize: 1024,
  367. })
  368. current := make(fakeCurrentFiler)
  369. // Initial scan, no files in the CurrentFiler. Should pick up the file and
  370. // set the ReceiveOnly flag on it, because that's the flag we give the
  371. // walker to set.
  372. files := walkDir(sf, ".", current, nil, protocol.FlagLocalReceiveOnly)
  373. if len(files) != 1 {
  374. t.Fatal("Should have scanned one file")
  375. }
  376. if files[0].LocalFlags != protocol.FlagLocalReceiveOnly {
  377. t.Fatal("Should have set the ReceiveOnly flag")
  378. }
  379. // Update the CurrentFiler and scan again. It should not return
  380. // anything, because the file has not changed. This verifies that the
  381. // ReceiveOnly flag is properly ignored and doesn't trigger a rescan
  382. // every time.
  383. cur := files[0]
  384. current[cur.Name] = cur
  385. files = walkDir(sf, ".", current, nil, protocol.FlagLocalReceiveOnly)
  386. if len(files) != 0 {
  387. t.Fatal("Should not have scanned anything")
  388. }
  389. // Now pretend the file was previously ignored instead. We should pick up
  390. // the difference in flags and set just the LocalReceive flags.
  391. cur.LocalFlags = protocol.FlagLocalIgnored
  392. current[cur.Name] = cur
  393. files = walkDir(sf, ".", current, nil, protocol.FlagLocalReceiveOnly)
  394. if len(files) != 1 {
  395. t.Fatal("Should have scanned one file")
  396. }
  397. if files[0].LocalFlags != protocol.FlagLocalReceiveOnly {
  398. t.Fatal("Should have set the ReceiveOnly flag")
  399. }
  400. }
  401. func walkDir(fs fs.Filesystem, dir string, cfiler CurrentFiler, matcher *ignore.Matcher, localFlags uint32) []protocol.FileInfo {
  402. cfg := testConfig()
  403. cfg.Filesystem = fs
  404. cfg.Subs = []string{dir}
  405. cfg.AutoNormalize = true
  406. cfg.CurrentFiler = cfiler
  407. cfg.Matcher = matcher
  408. cfg.LocalFlags = localFlags
  409. fchan := Walk(context.TODO(), cfg)
  410. var tmp []protocol.FileInfo
  411. for f := range fchan {
  412. if f.Err == nil {
  413. tmp = append(tmp, f.File)
  414. }
  415. }
  416. sort.Sort(fileList(tmp))
  417. return tmp
  418. }
  419. type fileList []protocol.FileInfo
  420. func (l fileList) Len() int {
  421. return len(l)
  422. }
  423. func (l fileList) Less(a, b int) bool {
  424. return l[a].Name < l[b].Name
  425. }
  426. func (l fileList) Swap(a, b int) {
  427. l[a], l[b] = l[b], l[a]
  428. }
  429. func (l fileList) testfiles() testfileList {
  430. testfiles := make(testfileList, len(l))
  431. for i, f := range l {
  432. if len(f.Blocks) > 1 {
  433. panic("simple test case stuff only supports a single block per file")
  434. }
  435. testfiles[i] = testfile{name: f.Name, length: f.FileSize()}
  436. if len(f.Blocks) == 1 {
  437. testfiles[i].hash = fmt.Sprintf("%x", f.Blocks[0].Hash)
  438. }
  439. }
  440. return testfiles
  441. }
  442. func (l testfileList) String() string {
  443. var b bytes.Buffer
  444. b.WriteString("{\n")
  445. for _, f := range l {
  446. fmt.Fprintf(&b, " %s (%d bytes): %s\n", f.name, f.length, f.hash)
  447. }
  448. b.WriteString("}")
  449. return b.String()
  450. }
  451. var initOnce sync.Once
  452. const (
  453. testdataSize = 17 << 20
  454. testdataName = "_random.data"
  455. )
  456. func BenchmarkHashFile(b *testing.B) {
  457. initOnce.Do(initTestFile)
  458. b.ResetTimer()
  459. for i := 0; i < b.N; i++ {
  460. if _, err := HashFile(context.TODO(), fs.NewFilesystem(fs.FilesystemTypeBasic, ""), testdataName, protocol.MinBlockSize, nil, true); err != nil {
  461. b.Fatal(err)
  462. }
  463. }
  464. b.SetBytes(testdataSize)
  465. b.ReportAllocs()
  466. }
  467. func initTestFile() {
  468. fd, err := os.Create(testdataName)
  469. if err != nil {
  470. panic(err)
  471. }
  472. lr := io.LimitReader(rand.Reader, testdataSize)
  473. if _, err := io.Copy(fd, lr); err != nil {
  474. panic(err)
  475. }
  476. if err := fd.Close(); err != nil {
  477. panic(err)
  478. }
  479. }
  480. func TestStopWalk(t *testing.T) {
  481. // Create tree that is 100 levels deep, with each level containing 100
  482. // files (each 1 MB) and 100 directories (in turn containing 100 files
  483. // and 100 directories, etc). That is, in total > 100^100 files and as
  484. // many directories. It'll take a while to scan, giving us time to
  485. // cancel it and make sure the scan stops.
  486. // Use an errorFs as the backing fs for the rest of the interface
  487. // The way we get it is a bit hacky tho.
  488. errorFs := fs.NewFilesystem(fs.FilesystemType(-1), ".")
  489. fs := fs.NewWalkFilesystem(&infiniteFS{errorFs, 100, 100, 1e6})
  490. const numHashers = 4
  491. ctx, cancel := context.WithCancel(context.Background())
  492. cfg := testConfig()
  493. cfg.Filesystem = fs
  494. cfg.Hashers = numHashers
  495. cfg.ProgressTickIntervalS = -1 // Don't attempt to build the full list of files before starting to scan...
  496. fchan := Walk(ctx, cfg)
  497. // Receive a few entries to make sure the walker is up and running,
  498. // scanning both files and dirs. Do some quick sanity tests on the
  499. // returned file entries to make sure we are not just reading crap from
  500. // a closed channel or something.
  501. dirs := 0
  502. files := 0
  503. for {
  504. res := <-fchan
  505. if res.Err != nil {
  506. t.Errorf("Error while scanning %v: %v", res.Err, res.Path)
  507. }
  508. f := res.File
  509. t.Log("Scanned", f)
  510. if f.IsDirectory() {
  511. if len(f.Name) == 0 || f.Permissions == 0 {
  512. t.Error("Bad directory entry", f)
  513. }
  514. dirs++
  515. } else {
  516. if len(f.Name) == 0 || len(f.Blocks) == 0 || f.Permissions == 0 {
  517. t.Error("Bad file entry", f)
  518. }
  519. files++
  520. }
  521. if dirs > 5 && files > 5 {
  522. break
  523. }
  524. }
  525. // Cancel the walker.
  526. cancel()
  527. // Empty out any waiting entries and wait for the channel to close.
  528. // Count them, they should be zero or very few - essentially, each
  529. // hasher has the choice of returning a fully handled entry or
  530. // cancelling, but they should not start on another item.
  531. extra := 0
  532. for range fchan {
  533. extra++
  534. }
  535. t.Log("Extra entries:", extra)
  536. if extra > numHashers {
  537. t.Error("unexpected extra entries received after cancel")
  538. }
  539. }
  540. func TestIssue4799(t *testing.T) {
  541. tmp, err := ioutil.TempDir("", "")
  542. if err != nil {
  543. t.Fatal(err)
  544. }
  545. defer os.RemoveAll(tmp)
  546. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, tmp)
  547. fd, err := fs.Create("foo")
  548. if err != nil {
  549. t.Fatal(err)
  550. }
  551. fd.Close()
  552. files := walkDir(fs, "/foo", nil, nil, 0)
  553. if len(files) != 1 || files[0].Name != "foo" {
  554. t.Error(`Received unexpected file infos when walking "/foo"`, files)
  555. }
  556. }
  557. func TestRecurseInclude(t *testing.T) {
  558. stignore := `
  559. !/dir1/cfile
  560. !efile
  561. !ffile
  562. *
  563. `
  564. ignores := ignore.New(testFs, ignore.WithCache(true))
  565. if err := ignores.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  566. t.Fatal(err)
  567. }
  568. files := walkDir(testFs, ".", nil, ignores, 0)
  569. expected := []string{
  570. filepath.Join("dir1"),
  571. filepath.Join("dir1", "cfile"),
  572. filepath.Join("dir2"),
  573. filepath.Join("dir2", "dir21"),
  574. filepath.Join("dir2", "dir21", "dir22"),
  575. filepath.Join("dir2", "dir21", "dir22", "dir23"),
  576. filepath.Join("dir2", "dir21", "dir22", "dir23", "efile"),
  577. filepath.Join("dir2", "dir21", "dir22", "efile"),
  578. filepath.Join("dir2", "dir21", "dir22", "efile", "efile"),
  579. filepath.Join("dir2", "dir21", "dira"),
  580. filepath.Join("dir2", "dir21", "dira", "efile"),
  581. filepath.Join("dir2", "dir21", "dira", "ffile"),
  582. filepath.Join("dir2", "dir21", "efile"),
  583. filepath.Join("dir2", "dir21", "efile", "ign"),
  584. filepath.Join("dir2", "dir21", "efile", "ign", "efile"),
  585. }
  586. if len(files) != len(expected) {
  587. t.Fatalf("Got %d files %v, expected %d files at %v", len(files), files, len(expected), expected)
  588. }
  589. for i := range files {
  590. if files[i].Name != expected[i] {
  591. t.Errorf("Got %v, expected file at %v", files[i], expected[i])
  592. }
  593. }
  594. }
  595. func TestIssue4841(t *testing.T) {
  596. tmp, err := ioutil.TempDir("", "")
  597. if err != nil {
  598. t.Fatal(err)
  599. }
  600. defer os.RemoveAll(tmp)
  601. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, tmp)
  602. fd, err := fs.Create("foo")
  603. if err != nil {
  604. panic(err)
  605. }
  606. fd.Close()
  607. cfg := testConfig()
  608. cfg.Filesystem = fs
  609. cfg.AutoNormalize = true
  610. cfg.CurrentFiler = fakeCurrentFiler{"foo": {
  611. Name: "foo",
  612. Type: protocol.FileInfoTypeFile,
  613. LocalFlags: protocol.FlagLocalIgnored,
  614. Version: protocol.Vector{}.Update(1),
  615. }}
  616. cfg.ShortID = protocol.LocalDeviceID.Short()
  617. fchan := Walk(context.TODO(), cfg)
  618. var files []protocol.FileInfo
  619. for f := range fchan {
  620. if f.Err != nil {
  621. t.Errorf("Error while scanning %v: %v", f.Err, f.Path)
  622. }
  623. files = append(files, f.File)
  624. }
  625. sort.Sort(fileList(files))
  626. if len(files) != 1 {
  627. t.Fatalf("Expected 1 file, got %d: %v", len(files), files)
  628. }
  629. if expected := (protocol.Vector{}.Update(protocol.LocalDeviceID.Short())); !files[0].Version.Equal(expected) {
  630. t.Fatalf("Expected Version == %v, got %v", expected, files[0].Version)
  631. }
  632. }
  633. // TestNotExistingError reproduces https://github.com/syncthing/syncthing/issues/5385
  634. func TestNotExistingError(t *testing.T) {
  635. sub := "notExisting"
  636. if _, err := testFs.Lstat(sub); !fs.IsNotExist(err) {
  637. t.Fatalf("Lstat returned error %v, while nothing should exist there.", err)
  638. }
  639. cfg := testConfig()
  640. cfg.Subs = []string{sub}
  641. fchan := Walk(context.TODO(), cfg)
  642. for f := range fchan {
  643. t.Fatalf("Expected no result from scan, got %v", f)
  644. }
  645. }
  646. func TestSkipIgnoredDirs(t *testing.T) {
  647. tmp, err := ioutil.TempDir("", "")
  648. if err != nil {
  649. t.Fatal(err)
  650. }
  651. defer os.RemoveAll(tmp)
  652. fss := fs.NewFilesystem(fs.FilesystemTypeBasic, tmp)
  653. name := "foo/ignored"
  654. err = fss.MkdirAll(name, 0777)
  655. if err != nil {
  656. t.Fatal(err)
  657. }
  658. stat, err := fss.Lstat(name)
  659. if err != nil {
  660. t.Fatal(err)
  661. }
  662. w := &walker{}
  663. pats := ignore.New(fss, ignore.WithCache(true))
  664. stignore := `
  665. /foo/ign*
  666. !/f*
  667. *
  668. `
  669. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  670. t.Fatal(err)
  671. }
  672. if !pats.SkipIgnoredDirs() {
  673. t.Error("SkipIgnoredDirs should be true")
  674. }
  675. w.Matcher = pats
  676. fn := w.walkAndHashFiles(context.Background(), nil, nil)
  677. if err := fn(name, stat, nil); err != fs.SkipDir {
  678. t.Errorf("Expected %v, got %v", fs.SkipDir, err)
  679. }
  680. }
  681. // Verify returns nil or an error describing the mismatch between the block
  682. // list and actual reader contents
  683. func verify(r io.Reader, blocksize int, blocks []protocol.BlockInfo) error {
  684. hf := sha256.New()
  685. // A 32k buffer is used for copying into the hash function.
  686. buf := make([]byte, 32<<10)
  687. for i, block := range blocks {
  688. lr := &io.LimitedReader{R: r, N: int64(blocksize)}
  689. _, err := io.CopyBuffer(hf, lr, buf)
  690. if err != nil {
  691. return err
  692. }
  693. hash := hf.Sum(nil)
  694. hf.Reset()
  695. if !bytes.Equal(hash, block.Hash) {
  696. return fmt.Errorf("hash mismatch %x != %x for block %d", hash, block.Hash, i)
  697. }
  698. }
  699. // We should have reached the end now
  700. bs := make([]byte, 1)
  701. n, err := r.Read(bs)
  702. if n != 0 || err != io.EOF {
  703. return fmt.Errorf("file continues past end of blocks")
  704. }
  705. return nil
  706. }
  707. type fakeCurrentFiler map[string]protocol.FileInfo
  708. func (fcf fakeCurrentFiler) CurrentFile(name string) (protocol.FileInfo, bool) {
  709. f, ok := fcf[name]
  710. return f, ok
  711. }
  712. func testConfig() Config {
  713. evLogger := events.NewLogger()
  714. go evLogger.Serve()
  715. return Config{
  716. Filesystem: testFs,
  717. Hashers: 2,
  718. EventLogger: evLogger,
  719. }
  720. }