walk_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  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 := t.TempDir()
  325. testFs := fs.NewFilesystem(testFsType, tmp)
  326. link := "link"
  327. dest, _ := filepath.Abs("testdata/dir1")
  328. destFs := fs.NewFilesystem(testFsType, dest)
  329. if err := fs.DebugSymlinkForTestsOnly(destFs, testFs, ".", "link"); err != nil {
  330. if runtime.GOOS == "windows" {
  331. // Probably we require permissions we don't have.
  332. t.Skip("Need admin permissions or developer mode to run symlink test on Windows: " + err.Error())
  333. } else {
  334. t.Fatal(err)
  335. }
  336. }
  337. // Scan root with symlink at FS root
  338. files := walkDir(fs.NewFilesystem(testFsType, filepath.Join(testFs.URI(), link)), ".", nil, nil, 0)
  339. // Verify that we got two files
  340. if len(files) != 2 {
  341. t.Fatalf("expected two files, not %d", len(files))
  342. }
  343. // Scan symlink below FS root
  344. files = walkDir(testFs, "link", nil, nil, 0)
  345. // Verify that we got the one symlink, except on windows
  346. if runtime.GOOS == "windows" {
  347. if len(files) != 0 {
  348. t.Errorf("expected no files, not %d", len(files))
  349. }
  350. } else if len(files) != 1 {
  351. t.Errorf("expected one file, not %d", len(files))
  352. }
  353. // Scan path below symlink
  354. files = walkDir(fs.NewFilesystem(testFsType, tmp), filepath.Join("link", "cfile"), nil, nil, 0)
  355. // Verify that we get nothing
  356. if len(files) != 0 {
  357. t.Errorf("expected no files, not %d", len(files))
  358. }
  359. }
  360. func TestBlocksizeHysteresis(t *testing.T) {
  361. // Verify that we select the right block size in the presence of old
  362. // file information.
  363. if testing.Short() {
  364. t.Skip("long and hard test")
  365. }
  366. sf := fs.NewWalkFilesystem(&singleFileFS{
  367. name: "testfile.dat",
  368. filesize: 500 << 20, // 500 MiB
  369. })
  370. current := make(fakeCurrentFiler)
  371. runTest := func(expectedBlockSize int) {
  372. files := walkDir(sf, ".", current, nil, 0)
  373. if len(files) != 1 {
  374. t.Fatalf("expected one file, not %d", len(files))
  375. }
  376. if s := files[0].BlockSize(); s != expectedBlockSize {
  377. t.Fatalf("incorrect block size %d != expected %d", s, expectedBlockSize)
  378. }
  379. }
  380. // Scan with no previous knowledge. We should get a 512 KiB block size.
  381. runTest(512 << 10)
  382. // Scan on the assumption that previous size was 256 KiB. Retain 256 KiB
  383. // block size.
  384. current["testfile.dat"] = protocol.FileInfo{
  385. Name: "testfile.dat",
  386. Size: 500 << 20,
  387. RawBlockSize: 256 << 10,
  388. }
  389. runTest(256 << 10)
  390. // Scan on the assumption that previous size was 1 MiB. Retain 1 MiB
  391. // block size.
  392. current["testfile.dat"] = protocol.FileInfo{
  393. Name: "testfile.dat",
  394. Size: 500 << 20,
  395. RawBlockSize: 1 << 20,
  396. }
  397. runTest(1 << 20)
  398. // Scan on the assumption that previous size was 128 KiB. Move to 512
  399. // KiB because the difference is large.
  400. current["testfile.dat"] = protocol.FileInfo{
  401. Name: "testfile.dat",
  402. Size: 500 << 20,
  403. RawBlockSize: 128 << 10,
  404. }
  405. runTest(512 << 10)
  406. // Scan on the assumption that previous size was 2 MiB. Move to 512
  407. // KiB because the difference is large.
  408. current["testfile.dat"] = protocol.FileInfo{
  409. Name: "testfile.dat",
  410. Size: 500 << 20,
  411. RawBlockSize: 2 << 20,
  412. }
  413. runTest(512 << 10)
  414. }
  415. func TestWalkReceiveOnly(t *testing.T) {
  416. sf := fs.NewWalkFilesystem(&singleFileFS{
  417. name: "testfile.dat",
  418. filesize: 1024,
  419. })
  420. current := make(fakeCurrentFiler)
  421. // Initial scan, no files in the CurrentFiler. Should pick up the file and
  422. // set the ReceiveOnly flag on it, because that's the flag we give the
  423. // walker to set.
  424. files := walkDir(sf, ".", current, nil, protocol.FlagLocalReceiveOnly)
  425. if len(files) != 1 {
  426. t.Fatal("Should have scanned one file")
  427. }
  428. if files[0].LocalFlags != protocol.FlagLocalReceiveOnly {
  429. t.Fatal("Should have set the ReceiveOnly flag")
  430. }
  431. // Update the CurrentFiler and scan again. It should not return
  432. // anything, because the file has not changed. This verifies that the
  433. // ReceiveOnly flag is properly ignored and doesn't trigger a rescan
  434. // every time.
  435. cur := files[0]
  436. current[cur.Name] = cur
  437. files = walkDir(sf, ".", current, nil, protocol.FlagLocalReceiveOnly)
  438. if len(files) != 0 {
  439. t.Fatal("Should not have scanned anything")
  440. }
  441. // Now pretend the file was previously ignored instead. We should pick up
  442. // the difference in flags and set just the LocalReceive flags.
  443. cur.LocalFlags = protocol.FlagLocalIgnored
  444. current[cur.Name] = cur
  445. files = walkDir(sf, ".", current, nil, protocol.FlagLocalReceiveOnly)
  446. if len(files) != 1 {
  447. t.Fatal("Should have scanned one file")
  448. }
  449. if files[0].LocalFlags != protocol.FlagLocalReceiveOnly {
  450. t.Fatal("Should have set the ReceiveOnly flag")
  451. }
  452. }
  453. func walkDir(fs fs.Filesystem, dir string, cfiler CurrentFiler, matcher *ignore.Matcher, localFlags uint32) []protocol.FileInfo {
  454. cfg, cancel := testConfig()
  455. defer cancel()
  456. cfg.Filesystem = fs
  457. cfg.Subs = []string{dir}
  458. cfg.AutoNormalize = true
  459. cfg.CurrentFiler = cfiler
  460. cfg.Matcher = matcher
  461. cfg.LocalFlags = localFlags
  462. fchan := Walk(context.TODO(), cfg)
  463. var tmp []protocol.FileInfo
  464. for f := range fchan {
  465. if f.Err == nil {
  466. tmp = append(tmp, f.File)
  467. }
  468. }
  469. sort.Sort(fileList(tmp))
  470. return tmp
  471. }
  472. type fileList []protocol.FileInfo
  473. func (l fileList) Len() int {
  474. return len(l)
  475. }
  476. func (l fileList) Less(a, b int) bool {
  477. return l[a].Name < l[b].Name
  478. }
  479. func (l fileList) Swap(a, b int) {
  480. l[a], l[b] = l[b], l[a]
  481. }
  482. func (l fileList) testfiles() testfileList {
  483. testfiles := make(testfileList, len(l))
  484. for i, f := range l {
  485. if len(f.Blocks) > 1 {
  486. panic("simple test case stuff only supports a single block per file")
  487. }
  488. testfiles[i] = testfile{name: f.Name, length: f.FileSize()}
  489. if len(f.Blocks) == 1 {
  490. testfiles[i].hash = fmt.Sprintf("%x", f.Blocks[0].Hash)
  491. }
  492. }
  493. return testfiles
  494. }
  495. func (l testfileList) String() string {
  496. var b bytes.Buffer
  497. b.WriteString("{\n")
  498. for _, f := range l {
  499. fmt.Fprintf(&b, " %s (%d bytes): %s\n", f.name, f.length, f.hash)
  500. }
  501. b.WriteString("}")
  502. return b.String()
  503. }
  504. var initOnce sync.Once
  505. const (
  506. testdataSize = 17<<20 + 1
  507. testdataName = "_random.data"
  508. )
  509. func BenchmarkHashFile(b *testing.B) {
  510. initOnce.Do(initTestFile)
  511. b.ResetTimer()
  512. for i := 0; i < b.N; i++ {
  513. if _, err := HashFile(context.TODO(), fs.NewFilesystem(testFsType, ""), testdataName, protocol.MinBlockSize, nil, true); err != nil {
  514. b.Fatal(err)
  515. }
  516. }
  517. b.SetBytes(testdataSize)
  518. b.ReportAllocs()
  519. }
  520. func initTestFile() {
  521. fd, err := os.Create(testdataName)
  522. if err != nil {
  523. panic(err)
  524. }
  525. lr := io.LimitReader(rand.Reader, testdataSize)
  526. if _, err := io.Copy(fd, lr); err != nil {
  527. panic(err)
  528. }
  529. if err := fd.Close(); err != nil {
  530. panic(err)
  531. }
  532. }
  533. func TestStopWalk(t *testing.T) {
  534. // Create tree that is 100 levels deep, with each level containing 100
  535. // files (each 1 MB) and 100 directories (in turn containing 100 files
  536. // and 100 directories, etc). That is, in total > 100^100 files and as
  537. // many directories. It'll take a while to scan, giving us time to
  538. // cancel it and make sure the scan stops.
  539. // Use an errorFs as the backing fs for the rest of the interface
  540. // The way we get it is a bit hacky tho.
  541. errorFs := fs.NewFilesystem(fs.FilesystemType(-1), ".")
  542. fs := fs.NewWalkFilesystem(&infiniteFS{errorFs, 100, 100, 1e6})
  543. const numHashers = 4
  544. ctx, cancel := context.WithCancel(context.Background())
  545. cfg, cfgCancel := testConfig()
  546. defer cfgCancel()
  547. cfg.Filesystem = fs
  548. cfg.Hashers = numHashers
  549. cfg.ProgressTickIntervalS = -1 // Don't attempt to build the full list of files before starting to scan...
  550. fchan := Walk(ctx, cfg)
  551. // Receive a few entries to make sure the walker is up and running,
  552. // scanning both files and dirs. Do some quick sanity tests on the
  553. // returned file entries to make sure we are not just reading crap from
  554. // a closed channel or something.
  555. dirs := 0
  556. files := 0
  557. for {
  558. res := <-fchan
  559. if res.Err != nil {
  560. t.Errorf("Error while scanning %v: %v", res.Err, res.Path)
  561. }
  562. f := res.File
  563. t.Log("Scanned", f)
  564. if f.IsDirectory() {
  565. if len(f.Name) == 0 || f.Permissions == 0 {
  566. t.Error("Bad directory entry", f)
  567. }
  568. dirs++
  569. } else {
  570. if len(f.Name) == 0 || len(f.Blocks) == 0 || f.Permissions == 0 {
  571. t.Error("Bad file entry", f)
  572. }
  573. files++
  574. }
  575. if dirs > 5 && files > 5 {
  576. break
  577. }
  578. }
  579. // Cancel the walker.
  580. cancel()
  581. // Empty out any waiting entries and wait for the channel to close.
  582. // Count them, they should be zero or very few - essentially, each
  583. // hasher has the choice of returning a fully handled entry or
  584. // cancelling, but they should not start on another item.
  585. extra := 0
  586. for range fchan {
  587. extra++
  588. }
  589. t.Log("Extra entries:", extra)
  590. if extra > numHashers {
  591. t.Error("unexpected extra entries received after cancel")
  592. }
  593. }
  594. func TestIssue4799(t *testing.T) {
  595. tmp := t.TempDir()
  596. fs := fs.NewFilesystem(testFsType, tmp)
  597. fd, err := fs.Create("foo")
  598. if err != nil {
  599. t.Fatal(err)
  600. }
  601. fd.Close()
  602. files := walkDir(fs, "/foo", nil, nil, 0)
  603. if len(files) != 1 || files[0].Name != "foo" {
  604. t.Error(`Received unexpected file infos when walking "/foo"`, files)
  605. }
  606. }
  607. func TestRecurseInclude(t *testing.T) {
  608. stignore := `
  609. !/dir1/cfile
  610. !efile
  611. !ffile
  612. *
  613. `
  614. ignores := ignore.New(testFs, ignore.WithCache(true))
  615. if err := ignores.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  616. t.Fatal(err)
  617. }
  618. files := walkDir(testFs, ".", nil, ignores, 0)
  619. expected := []string{
  620. filepath.Join("dir1"),
  621. filepath.Join("dir1", "cfile"),
  622. filepath.Join("dir2"),
  623. filepath.Join("dir2", "dir21"),
  624. filepath.Join("dir2", "dir21", "dir22"),
  625. filepath.Join("dir2", "dir21", "dir22", "dir23"),
  626. filepath.Join("dir2", "dir21", "dir22", "dir23", "efile"),
  627. filepath.Join("dir2", "dir21", "dir22", "efile"),
  628. filepath.Join("dir2", "dir21", "dir22", "efile", "efile"),
  629. filepath.Join("dir2", "dir21", "dira"),
  630. filepath.Join("dir2", "dir21", "dira", "efile"),
  631. filepath.Join("dir2", "dir21", "dira", "ffile"),
  632. filepath.Join("dir2", "dir21", "efile"),
  633. filepath.Join("dir2", "dir21", "efile", "ign"),
  634. filepath.Join("dir2", "dir21", "efile", "ign", "efile"),
  635. }
  636. if len(files) != len(expected) {
  637. t.Fatalf("Got %d files %v, expected %d files at %v", len(files), files, len(expected), expected)
  638. }
  639. for i := range files {
  640. if files[i].Name != expected[i] {
  641. t.Errorf("Got %v, expected file at %v", files[i], expected[i])
  642. }
  643. }
  644. }
  645. func TestIssue4841(t *testing.T) {
  646. tmp := t.TempDir()
  647. fs := fs.NewFilesystem(testFsType, tmp)
  648. fd, err := fs.Create("foo")
  649. if err != nil {
  650. panic(err)
  651. }
  652. fd.Close()
  653. cfg, cancel := testConfig()
  654. defer cancel()
  655. cfg.Filesystem = fs
  656. cfg.AutoNormalize = true
  657. cfg.CurrentFiler = fakeCurrentFiler{"foo": {
  658. Name: "foo",
  659. Type: protocol.FileInfoTypeFile,
  660. LocalFlags: protocol.FlagLocalIgnored,
  661. Version: protocol.Vector{}.Update(1),
  662. }}
  663. cfg.ShortID = protocol.LocalDeviceID.Short()
  664. fchan := Walk(context.TODO(), cfg)
  665. var files []protocol.FileInfo
  666. for f := range fchan {
  667. if f.Err != nil {
  668. t.Errorf("Error while scanning %v: %v", f.Err, f.Path)
  669. }
  670. files = append(files, f.File)
  671. }
  672. sort.Sort(fileList(files))
  673. if len(files) != 1 {
  674. t.Fatalf("Expected 1 file, got %d: %v", len(files), files)
  675. }
  676. if expected := (protocol.Vector{}.Update(protocol.LocalDeviceID.Short())); !files[0].Version.Equal(expected) {
  677. t.Fatalf("Expected Version == %v, got %v", expected, files[0].Version)
  678. }
  679. }
  680. // TestNotExistingError reproduces https://github.com/syncthing/syncthing/issues/5385
  681. func TestNotExistingError(t *testing.T) {
  682. sub := "notExisting"
  683. if _, err := testFs.Lstat(sub); !fs.IsNotExist(err) {
  684. t.Fatalf("Lstat returned error %v, while nothing should exist there.", err)
  685. }
  686. cfg, cancel := testConfig()
  687. defer cancel()
  688. cfg.Subs = []string{sub}
  689. fchan := Walk(context.TODO(), cfg)
  690. for f := range fchan {
  691. t.Fatalf("Expected no result from scan, got %v", f)
  692. }
  693. }
  694. func TestSkipIgnoredDirs(t *testing.T) {
  695. fss := fs.NewFilesystem(fs.FilesystemTypeFake, "")
  696. name := "foo/ignored"
  697. err := fss.MkdirAll(name, 0777)
  698. if err != nil {
  699. t.Fatal(err)
  700. }
  701. stat, err := fss.Lstat(name)
  702. if err != nil {
  703. t.Fatal(err)
  704. }
  705. w := &walker{}
  706. pats := ignore.New(fss, ignore.WithCache(true))
  707. stignore := `
  708. /foo/ign*
  709. !/f*
  710. *
  711. `
  712. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  713. t.Fatal(err)
  714. }
  715. if !pats.SkipIgnoredDirs() {
  716. t.Error("SkipIgnoredDirs should be true")
  717. }
  718. w.Matcher = pats
  719. fn := w.walkAndHashFiles(context.Background(), nil, nil)
  720. if err := fn(name, stat, nil); err != fs.SkipDir {
  721. t.Errorf("Expected %v, got %v", fs.SkipDir, err)
  722. }
  723. }
  724. // https://github.com/syncthing/syncthing/issues/6487
  725. func TestIncludedSubdir(t *testing.T) {
  726. fss := fs.NewFilesystem(fs.FilesystemTypeFake, "")
  727. name := filepath.Clean("foo/bar/included")
  728. err := fss.MkdirAll(name, 0777)
  729. if err != nil {
  730. t.Fatal(err)
  731. }
  732. pats := ignore.New(fss, ignore.WithCache(true))
  733. stignore := `
  734. !/foo/bar
  735. *
  736. `
  737. if err := pats.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  738. t.Fatal(err)
  739. }
  740. fchan := Walk(context.TODO(), Config{
  741. CurrentFiler: make(fakeCurrentFiler),
  742. Filesystem: fss,
  743. Matcher: pats,
  744. })
  745. found := false
  746. for f := range fchan {
  747. if f.Err != nil {
  748. t.Fatalf("Error while scanning %v: %v", f.Err, f.Path)
  749. }
  750. if f.File.IsIgnored() {
  751. t.Error("File is ignored:", f.File.Name)
  752. }
  753. if f.File.Name == name {
  754. found = true
  755. }
  756. }
  757. if !found {
  758. t.Errorf("File not present in scan results")
  759. }
  760. }
  761. // Verify returns nil or an error describing the mismatch between the block
  762. // list and actual reader contents
  763. func verify(r io.Reader, blocksize int, blocks []protocol.BlockInfo) error {
  764. hf := sha256.New()
  765. // A 32k buffer is used for copying into the hash function.
  766. buf := make([]byte, 32<<10)
  767. for i, block := range blocks {
  768. lr := &io.LimitedReader{R: r, N: int64(blocksize)}
  769. _, err := io.CopyBuffer(hf, lr, buf)
  770. if err != nil {
  771. return err
  772. }
  773. hash := hf.Sum(nil)
  774. hf.Reset()
  775. if !bytes.Equal(hash, block.Hash) {
  776. return fmt.Errorf("hash mismatch %x != %x for block %d", hash, block.Hash, i)
  777. }
  778. }
  779. // We should have reached the end now
  780. bs := make([]byte, 1)
  781. n, err := r.Read(bs)
  782. if n != 0 || err != io.EOF {
  783. return errors.New("file continues past end of blocks")
  784. }
  785. return nil
  786. }
  787. type fakeCurrentFiler map[string]protocol.FileInfo
  788. func (fcf fakeCurrentFiler) CurrentFile(name string) (protocol.FileInfo, bool) {
  789. f, ok := fcf[name]
  790. return f, ok
  791. }
  792. func testConfig() (Config, context.CancelFunc) {
  793. evLogger := events.NewLogger()
  794. ctx, cancel := context.WithCancel(context.Background())
  795. go evLogger.Serve(ctx)
  796. return Config{
  797. Filesystem: testFs,
  798. Hashers: 2,
  799. EventLogger: evLogger,
  800. }, cancel
  801. }