walk_test.go 25 KB

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