walk_test.go 26 KB

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