walk_test.go 25 KB

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