walk_test.go 27 KB

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