walk_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "os"
  15. "path/filepath"
  16. "runtime"
  17. rdebug "runtime/debug"
  18. "sort"
  19. "sync"
  20. "testing"
  21. "github.com/d4l3k/messagediff"
  22. "github.com/syncthing/syncthing/lib/fs"
  23. "github.com/syncthing/syncthing/lib/ignore"
  24. "github.com/syncthing/syncthing/lib/osutil"
  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. var testFs fs.Filesystem
  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. testFs = fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata")
  51. }
  52. func TestWalkSub(t *testing.T) {
  53. ignores := ignore.New(testFs)
  54. err := ignores.Load(".stignore")
  55. if err != nil {
  56. t.Fatal(err)
  57. }
  58. fchan := Walk(context.TODO(), Config{
  59. Filesystem: testFs,
  60. Subs: []string{"dir2"},
  61. Matcher: ignores,
  62. Hashers: 2,
  63. })
  64. var files []protocol.FileInfo
  65. for f := range fchan {
  66. files = append(files, f)
  67. }
  68. // The directory contains two files, where one is ignored from a higher
  69. // level. We should see only the directory and one of the files.
  70. if len(files) != 2 {
  71. t.Fatalf("Incorrect length %d != 2", len(files))
  72. }
  73. if files[0].Name != "dir2" {
  74. t.Errorf("Incorrect file %v != dir2", files[0])
  75. }
  76. if files[1].Name != filepath.Join("dir2", "cfile") {
  77. t.Errorf("Incorrect file %v != dir2/cfile", files[1])
  78. }
  79. }
  80. func TestWalk(t *testing.T) {
  81. ignores := ignore.New(testFs)
  82. err := ignores.Load(".stignore")
  83. if err != nil {
  84. t.Fatal(err)
  85. }
  86. t.Log(ignores)
  87. fchan := Walk(context.TODO(), Config{
  88. Filesystem: testFs,
  89. Matcher: ignores,
  90. Hashers: 2,
  91. })
  92. var tmp []protocol.FileInfo
  93. for f := range fchan {
  94. tmp = append(tmp, f)
  95. }
  96. sort.Sort(fileList(tmp))
  97. files := fileList(tmp).testfiles()
  98. if diff, equal := messagediff.PrettyDiff(testdata, files); !equal {
  99. t.Errorf("Walk returned unexpected data. Diff:\n%s", diff)
  100. }
  101. }
  102. func TestVerify(t *testing.T) {
  103. blocksize := 16
  104. // data should be an even multiple of blocksize long
  105. data := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut e")
  106. buf := bytes.NewBuffer(data)
  107. progress := newByteCounter()
  108. defer progress.Close()
  109. blocks, err := Blocks(context.TODO(), buf, blocksize, -1, progress, false)
  110. if err != nil {
  111. t.Fatal(err)
  112. }
  113. if exp := len(data) / blocksize; len(blocks) != exp {
  114. t.Fatalf("Incorrect number of blocks %d != %d", len(blocks), exp)
  115. }
  116. if int64(len(data)) != progress.Total() {
  117. t.Fatalf("Incorrect counter value %d != %d", len(data), progress.Total())
  118. }
  119. buf = bytes.NewBuffer(data)
  120. err = verify(buf, blocksize, blocks)
  121. t.Log(err)
  122. if err != nil {
  123. t.Fatal("Unexpected verify failure", err)
  124. }
  125. buf = bytes.NewBuffer(append(data, '\n'))
  126. err = verify(buf, blocksize, blocks)
  127. t.Log(err)
  128. if err == nil {
  129. t.Fatal("Unexpected verify success")
  130. }
  131. buf = bytes.NewBuffer(data[:len(data)-1])
  132. err = verify(buf, blocksize, blocks)
  133. t.Log(err)
  134. if err == nil {
  135. t.Fatal("Unexpected verify success")
  136. }
  137. data[42] = 42
  138. buf = bytes.NewBuffer(data)
  139. err = verify(buf, blocksize, blocks)
  140. t.Log(err)
  141. if err == nil {
  142. t.Fatal("Unexpected verify success")
  143. }
  144. }
  145. func TestNormalization(t *testing.T) {
  146. if runtime.GOOS == "darwin" {
  147. t.Skip("Normalization test not possible on darwin")
  148. return
  149. }
  150. os.RemoveAll("testdata/normalization")
  151. defer os.RemoveAll("testdata/normalization")
  152. tests := []string{
  153. "0-A", // ASCII A -- accepted
  154. "1-\xC3\x84", // NFC 'Ä' -- conflicts with the entry below, accepted
  155. "1-\x41\xCC\x88", // NFD 'Ä' -- conflicts with the entry above, ignored
  156. "2-\xC3\x85", // NFC 'Å' -- accepted
  157. "3-\x41\xCC\x83", // NFD 'Ã' -- converted to NFC
  158. "4-\xE2\x98\x95", // U+2615 HOT BEVERAGE (☕) -- accepted
  159. "5-\xCD\xE2", // EUC-CN "wài" (外) -- ignored (not UTF8)
  160. }
  161. numInvalid := 2
  162. if runtime.GOOS == "windows" {
  163. // On Windows, in case 5 the character gets replaced with a
  164. // replacement character \xEF\xBF\xBD at the point it's written to disk,
  165. // which means it suddenly becomes valid (sort of).
  166. numInvalid--
  167. }
  168. numValid := len(tests) - numInvalid
  169. for _, s1 := range tests {
  170. // Create a directory for each of the interesting strings above
  171. if err := testFs.MkdirAll(filepath.Join("normalization", s1), 0755); err != nil {
  172. t.Fatal(err)
  173. }
  174. for _, s2 := range tests {
  175. // Within each dir, create a file with each of the interesting
  176. // file names. Ensure that the file doesn't exist when it's
  177. // created. This detects and fails if there's file name
  178. // normalization stuff at the filesystem level.
  179. if fd, err := testFs.OpenFile(filepath.Join("normalization", s1, s2), os.O_CREATE|os.O_EXCL, 0644); err != nil {
  180. t.Fatal(err)
  181. } else {
  182. fd.Write([]byte("test"))
  183. fd.Close()
  184. }
  185. }
  186. }
  187. // We can normalize a directory name, but we can't descend into it in the
  188. // same pass due to how filepath.Walk works. So we run the scan twice to
  189. // make sure it all gets done. In production, things will be correct
  190. // eventually...
  191. walkDir(testFs, "normalization", nil, nil)
  192. tmp := walkDir(testFs, "normalization", nil, nil)
  193. files := fileList(tmp).testfiles()
  194. // We should have one file per combination, plus the directories
  195. // themselves, plus the "testdata/normalization" directory
  196. expectedNum := numValid*numValid + numValid + 1
  197. if len(files) != expectedNum {
  198. t.Errorf("Expected %d files, got %d", expectedNum, len(files))
  199. }
  200. // The file names should all be in NFC form.
  201. for _, f := range files {
  202. t.Logf("%q (% x) %v", f.name, f.name, norm.NFC.IsNormalString(f.name))
  203. if !norm.NFC.IsNormalString(f.name) {
  204. t.Errorf("File name %q is not NFC normalized", f.name)
  205. }
  206. }
  207. }
  208. func TestIssue1507(t *testing.T) {
  209. w := &walker{}
  210. c := make(chan protocol.FileInfo, 100)
  211. fn := w.walkAndHashFiles(context.TODO(), c, c)
  212. fn("", nil, protocol.ErrClosed)
  213. }
  214. func TestWalkSymlinkUnix(t *testing.T) {
  215. if runtime.GOOS == "windows" {
  216. t.Skip("skipping unsupported symlink test")
  217. return
  218. }
  219. // Create a folder with a symlink in it
  220. os.RemoveAll("_symlinks")
  221. os.Mkdir("_symlinks", 0755)
  222. defer os.RemoveAll("_symlinks")
  223. os.Symlink("../testdata", "_symlinks/link")
  224. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, "_symlinks")
  225. for _, path := range []string{".", "link"} {
  226. // Scan it
  227. files := walkDir(fs, path, nil, nil)
  228. // Verify that we got one symlink and with the correct attributes
  229. if len(files) != 1 {
  230. t.Errorf("expected 1 symlink, not %d", len(files))
  231. }
  232. if len(files[0].Blocks) != 0 {
  233. t.Errorf("expected zero blocks for symlink, not %d", len(files[0].Blocks))
  234. }
  235. if files[0].SymlinkTarget != "../testdata" {
  236. t.Errorf("expected symlink to have target destination, not %q", files[0].SymlinkTarget)
  237. }
  238. }
  239. }
  240. func TestWalkSymlinkWindows(t *testing.T) {
  241. if runtime.GOOS != "windows" {
  242. t.Skip("skipping unsupported symlink test")
  243. }
  244. // Create a folder with a symlink in it
  245. name := "_symlinks-win"
  246. os.RemoveAll(name)
  247. os.Mkdir(name, 0755)
  248. defer os.RemoveAll(name)
  249. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, name)
  250. if err := osutil.DebugSymlinkForTestsOnly("../testdata", "_symlinks/link"); err != nil {
  251. // Probably we require permissions we don't have.
  252. t.Skip(err)
  253. }
  254. for _, path := range []string{".", "link"} {
  255. // Scan it
  256. files := walkDir(fs, path, nil, nil)
  257. // Verify that we got zero symlinks
  258. if len(files) != 0 {
  259. t.Errorf("expected zero symlinks, not %d", len(files))
  260. }
  261. }
  262. }
  263. func TestWalkRootSymlink(t *testing.T) {
  264. // Create a folder with a symlink in it
  265. tmp, err := ioutil.TempDir("", "")
  266. if err != nil {
  267. t.Fatal(err)
  268. }
  269. defer os.RemoveAll(tmp)
  270. link := tmp + "/link"
  271. dest, _ := filepath.Abs("testdata/dir1")
  272. if err := osutil.DebugSymlinkForTestsOnly(dest, link); err != nil {
  273. if runtime.GOOS == "windows" {
  274. // Probably we require permissions we don't have.
  275. t.Skip("Need admin permissions or developer mode to run symlink test on Windows: " + err.Error())
  276. } else {
  277. t.Fatal(err)
  278. }
  279. }
  280. // Scan it
  281. files := walkDir(fs.NewFilesystem(fs.FilesystemTypeBasic, link), ".", nil, nil)
  282. // Verify that we got two files
  283. if len(files) != 2 {
  284. t.Errorf("expected two files, not %d", len(files))
  285. }
  286. }
  287. func TestBlocksizeHysteresis(t *testing.T) {
  288. // Verify that we select the right block size in the presence of old
  289. // file information.
  290. sf := fs.NewWalkFilesystem(&singleFileFS{
  291. name: "testfile.dat",
  292. filesize: 500 << 20, // 500 MiB
  293. })
  294. current := make(fakeCurrentFiler)
  295. runTest := func(expectedBlockSize int) {
  296. files := walkDir(sf, ".", current, nil)
  297. if len(files) != 1 {
  298. t.Fatalf("expected one file, not %d", len(files))
  299. }
  300. if s := files[0].BlockSize(); s != expectedBlockSize {
  301. t.Fatalf("incorrect block size %d != expected %d", s, expectedBlockSize)
  302. }
  303. }
  304. // Scan with no previous knowledge. We should get a 512 KiB block size.
  305. runTest(512 << 10)
  306. // Scan on the assumption that previous size was 256 KiB. Retain 256 KiB
  307. // block size.
  308. current["testfile.dat"] = protocol.FileInfo{
  309. Name: "testfile.dat",
  310. Size: 500 << 20,
  311. RawBlockSize: 256 << 10,
  312. }
  313. runTest(256 << 10)
  314. // Scan on the assumption that previous size was 1 MiB. Retain 1 MiB
  315. // block size.
  316. current["testfile.dat"] = protocol.FileInfo{
  317. Name: "testfile.dat",
  318. Size: 500 << 20,
  319. RawBlockSize: 1 << 20,
  320. }
  321. runTest(1 << 20)
  322. // Scan on the assumption that previous size was 128 KiB. Move to 512
  323. // KiB because the difference is large.
  324. current["testfile.dat"] = protocol.FileInfo{
  325. Name: "testfile.dat",
  326. Size: 500 << 20,
  327. RawBlockSize: 128 << 10,
  328. }
  329. runTest(512 << 10)
  330. // Scan on the assumption that previous size was 2 MiB. Move to 512
  331. // KiB because the difference is large.
  332. current["testfile.dat"] = protocol.FileInfo{
  333. Name: "testfile.dat",
  334. Size: 500 << 20,
  335. RawBlockSize: 2 << 20,
  336. }
  337. runTest(512 << 10)
  338. }
  339. func walkDir(fs fs.Filesystem, dir string, cfiler CurrentFiler, matcher *ignore.Matcher) []protocol.FileInfo {
  340. fchan := Walk(context.TODO(), Config{
  341. Filesystem: fs,
  342. Subs: []string{dir},
  343. AutoNormalize: true,
  344. Hashers: 2,
  345. UseLargeBlocks: true,
  346. CurrentFiler: cfiler,
  347. Matcher: matcher,
  348. })
  349. var tmp []protocol.FileInfo
  350. for f := range fchan {
  351. tmp = append(tmp, f)
  352. }
  353. sort.Sort(fileList(tmp))
  354. return tmp
  355. }
  356. type fileList []protocol.FileInfo
  357. func (l fileList) Len() int {
  358. return len(l)
  359. }
  360. func (l fileList) Less(a, b int) bool {
  361. return l[a].Name < l[b].Name
  362. }
  363. func (l fileList) Swap(a, b int) {
  364. l[a], l[b] = l[b], l[a]
  365. }
  366. func (l fileList) testfiles() testfileList {
  367. testfiles := make(testfileList, len(l))
  368. for i, f := range l {
  369. if len(f.Blocks) > 1 {
  370. panic("simple test case stuff only supports a single block per file")
  371. }
  372. testfiles[i] = testfile{name: f.Name, length: f.FileSize()}
  373. if len(f.Blocks) == 1 {
  374. testfiles[i].hash = fmt.Sprintf("%x", f.Blocks[0].Hash)
  375. }
  376. }
  377. return testfiles
  378. }
  379. func (l testfileList) String() string {
  380. var b bytes.Buffer
  381. b.WriteString("{\n")
  382. for _, f := range l {
  383. fmt.Fprintf(&b, " %s (%d bytes): %s\n", f.name, f.length, f.hash)
  384. }
  385. b.WriteString("}")
  386. return b.String()
  387. }
  388. var initOnce sync.Once
  389. const (
  390. testdataSize = 17 << 20
  391. testdataName = "_random.data"
  392. )
  393. func BenchmarkHashFile(b *testing.B) {
  394. initOnce.Do(initTestFile)
  395. b.ResetTimer()
  396. for i := 0; i < b.N; i++ {
  397. if _, err := HashFile(context.TODO(), fs.NewFilesystem(fs.FilesystemTypeBasic, ""), testdataName, protocol.MinBlockSize, nil, true); err != nil {
  398. b.Fatal(err)
  399. }
  400. }
  401. b.SetBytes(testdataSize)
  402. b.ReportAllocs()
  403. }
  404. func initTestFile() {
  405. fd, err := os.Create(testdataName)
  406. if err != nil {
  407. panic(err)
  408. }
  409. lr := io.LimitReader(rand.Reader, testdataSize)
  410. if _, err := io.Copy(fd, lr); err != nil {
  411. panic(err)
  412. }
  413. if err := fd.Close(); err != nil {
  414. panic(err)
  415. }
  416. }
  417. func TestStopWalk(t *testing.T) {
  418. // Create tree that is 100 levels deep, with each level containing 100
  419. // files (each 1 MB) and 100 directories (in turn containing 100 files
  420. // and 100 directories, etc). That is, in total > 100^100 files and as
  421. // many directories. It'll take a while to scan, giving us time to
  422. // cancel it and make sure the scan stops.
  423. // Use an errorFs as the backing fs for the rest of the interface
  424. // The way we get it is a bit hacky tho.
  425. errorFs := fs.NewFilesystem(fs.FilesystemType(-1), ".")
  426. fs := fs.NewWalkFilesystem(&infiniteFS{errorFs, 100, 100, 1e6})
  427. const numHashers = 4
  428. ctx, cancel := context.WithCancel(context.Background())
  429. fchan := Walk(ctx, Config{
  430. Filesystem: fs,
  431. Hashers: numHashers,
  432. ProgressTickIntervalS: -1, // Don't attempt to build the full list of files before starting to scan...
  433. })
  434. // Receive a few entries to make sure the walker is up and running,
  435. // scanning both files and dirs. Do some quick sanity tests on the
  436. // returned file entries to make sure we are not just reading crap from
  437. // a closed channel or something.
  438. dirs := 0
  439. files := 0
  440. for {
  441. f := <-fchan
  442. t.Log("Scanned", f)
  443. if f.IsDirectory() {
  444. if len(f.Name) == 0 || f.Permissions == 0 {
  445. t.Error("Bad directory entry", f)
  446. }
  447. dirs++
  448. } else {
  449. if len(f.Name) == 0 || len(f.Blocks) == 0 || f.Permissions == 0 {
  450. t.Error("Bad file entry", f)
  451. }
  452. files++
  453. }
  454. if dirs > 5 && files > 5 {
  455. break
  456. }
  457. }
  458. // Cancel the walker.
  459. cancel()
  460. // Empty out any waiting entries and wait for the channel to close.
  461. // Count them, they should be zero or very few - essentially, each
  462. // hasher has the choice of returning a fully handled entry or
  463. // cancelling, but they should not start on another item.
  464. extra := 0
  465. for range fchan {
  466. extra++
  467. }
  468. t.Log("Extra entries:", extra)
  469. if extra > numHashers {
  470. t.Error("unexpected extra entries received after cancel")
  471. }
  472. }
  473. func TestIssue4799(t *testing.T) {
  474. tmp, err := ioutil.TempDir("", "")
  475. if err != nil {
  476. t.Fatal(err)
  477. }
  478. defer os.RemoveAll(tmp)
  479. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, tmp)
  480. fd, err := fs.Create("foo")
  481. if err != nil {
  482. t.Fatal(err)
  483. }
  484. fd.Close()
  485. files := walkDir(fs, "/foo", nil, nil)
  486. if len(files) != 1 || files[0].Name != "foo" {
  487. t.Error(`Received unexpected file infos when walking "/foo"`, files)
  488. }
  489. }
  490. func TestRecurseInclude(t *testing.T) {
  491. stignore := `
  492. !/dir1/cfile
  493. !efile
  494. !ffile
  495. *
  496. `
  497. ignores := ignore.New(testFs, ignore.WithCache(true))
  498. if err := ignores.Parse(bytes.NewBufferString(stignore), ".stignore"); err != nil {
  499. t.Fatal(err)
  500. }
  501. files := walkDir(testFs, ".", nil, ignores)
  502. expected := []string{
  503. filepath.Join("dir1"),
  504. filepath.Join("dir1", "cfile"),
  505. filepath.Join("dir2"),
  506. filepath.Join("dir2", "dir21"),
  507. filepath.Join("dir2", "dir21", "dir22"),
  508. filepath.Join("dir2", "dir21", "dir22", "dir23"),
  509. filepath.Join("dir2", "dir21", "dir22", "dir23", "efile"),
  510. filepath.Join("dir2", "dir21", "dir22", "efile"),
  511. filepath.Join("dir2", "dir21", "dir22", "efile", "efile"),
  512. filepath.Join("dir2", "dir21", "dira"),
  513. filepath.Join("dir2", "dir21", "dira", "efile"),
  514. filepath.Join("dir2", "dir21", "dira", "ffile"),
  515. filepath.Join("dir2", "dir21", "efile"),
  516. filepath.Join("dir2", "dir21", "efile", "ign"),
  517. filepath.Join("dir2", "dir21", "efile", "ign", "efile"),
  518. }
  519. if len(files) != len(expected) {
  520. t.Fatalf("Got %d files %v, expected %d files at %v", len(files), files, len(expected), expected)
  521. }
  522. for i := range files {
  523. if files[i].Name != expected[i] {
  524. t.Errorf("Got %v, expected file at %v", files[i], expected[i])
  525. }
  526. }
  527. }
  528. func TestIssue4841(t *testing.T) {
  529. tmp, err := ioutil.TempDir("", "")
  530. if err != nil {
  531. t.Fatal(err)
  532. }
  533. defer os.RemoveAll(tmp)
  534. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, tmp)
  535. fd, err := fs.Create("foo")
  536. if err != nil {
  537. panic(err)
  538. }
  539. fd.Close()
  540. fchan := Walk(context.TODO(), Config{
  541. Filesystem: fs,
  542. Subs: nil,
  543. AutoNormalize: true,
  544. Hashers: 2,
  545. CurrentFiler: fakeCurrentFiler{
  546. "foo": {
  547. Name: "foo",
  548. Type: protocol.FileInfoTypeFile,
  549. Invalid: true,
  550. Version: protocol.Vector{}.Update(1),
  551. },
  552. },
  553. ShortID: protocol.LocalDeviceID.Short(),
  554. })
  555. var files []protocol.FileInfo
  556. for f := range fchan {
  557. files = append(files, f)
  558. }
  559. sort.Sort(fileList(files))
  560. if len(files) != 1 {
  561. t.Fatalf("Expected 1 file, got %d: %v", len(files), files)
  562. }
  563. if expected := (protocol.Vector{}.Update(protocol.LocalDeviceID.Short())); !files[0].Version.Equal(expected) {
  564. t.Fatalf("Expected Version == %v, got %v", expected, files[0].Version)
  565. }
  566. }
  567. // Verify returns nil or an error describing the mismatch between the block
  568. // list and actual reader contents
  569. func verify(r io.Reader, blocksize int, blocks []protocol.BlockInfo) error {
  570. hf := sha256.New()
  571. // A 32k buffer is used for copying into the hash function.
  572. buf := make([]byte, 32<<10)
  573. for i, block := range blocks {
  574. lr := &io.LimitedReader{R: r, N: int64(blocksize)}
  575. _, err := io.CopyBuffer(hf, lr, buf)
  576. if err != nil {
  577. return err
  578. }
  579. hash := hf.Sum(nil)
  580. hf.Reset()
  581. if !bytes.Equal(hash, block.Hash) {
  582. return fmt.Errorf("hash mismatch %x != %x for block %d", hash, block.Hash, i)
  583. }
  584. }
  585. // We should have reached the end now
  586. bs := make([]byte, 1)
  587. n, err := r.Read(bs)
  588. if n != 0 || err != io.EOF {
  589. return fmt.Errorf("file continues past end of blocks")
  590. }
  591. return nil
  592. }
  593. type fakeCurrentFiler map[string]protocol.FileInfo
  594. func (fcf fakeCurrentFiler) CurrentFile(name string) (protocol.FileInfo, bool) {
  595. f, ok := fcf[name]
  596. return f, ok
  597. }