1
0

walk_test.go 26 KB

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