walk_test.go 23 KB

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