walk_test.go 27 KB

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