walk_test.go 23 KB

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