walk_test.go 25 KB

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