walk_test.go 23 KB

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