walk_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. "os"
  14. "path/filepath"
  15. "runtime"
  16. rdebug "runtime/debug"
  17. "sort"
  18. "sync"
  19. "testing"
  20. "github.com/d4l3k/messagediff"
  21. "github.com/syncthing/syncthing/lib/fs"
  22. "github.com/syncthing/syncthing/lib/ignore"
  23. "github.com/syncthing/syncthing/lib/protocol"
  24. "golang.org/x/text/unicode/norm"
  25. )
  26. type testfile struct {
  27. name string
  28. length int64
  29. hash string
  30. }
  31. type testfileList []testfile
  32. var testdata = testfileList{
  33. {"afile", 4, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"},
  34. {"dir1", 128, ""},
  35. {filepath.Join("dir1", "dfile"), 5, "49ae93732fcf8d63fe1cce759664982dbd5b23161f007dba8561862adc96d063"},
  36. {"dir2", 128, ""},
  37. {filepath.Join("dir2", "cfile"), 4, "bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c"},
  38. {"excludes", 37, "df90b52f0c55dba7a7a940affe482571563b1ac57bd5be4d8a0291e7de928e06"},
  39. {"further-excludes", 5, "7eb0a548094fa6295f7fd9200d69973e5f5ec5c04f2a86d998080ac43ecf89f1"},
  40. }
  41. func init() {
  42. // This test runs the risk of entering infinite recursion if it fails.
  43. // Limit the stack size to 10 megs to crash early in that case instead of
  44. // potentially taking down the box...
  45. rdebug.SetMaxStack(10 * 1 << 20)
  46. }
  47. func TestWalkSub(t *testing.T) {
  48. ignores := ignore.New(fs.NewFilesystem(fs.FilesystemTypeBasic, "."))
  49. err := ignores.Load("testdata/.stignore")
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. fchan, err := Walk(context.TODO(), Config{
  54. Filesystem: fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata"),
  55. Subs: []string{"dir2"},
  56. BlockSize: 128 * 1024,
  57. Matcher: ignores,
  58. Hashers: 2,
  59. })
  60. var files []protocol.FileInfo
  61. for f := range fchan {
  62. files = append(files, f)
  63. }
  64. if err != nil {
  65. t.Fatal(err)
  66. }
  67. // The directory contains two files, where one is ignored from a higher
  68. // level. We should see only the directory and one of the files.
  69. if len(files) != 2 {
  70. t.Fatalf("Incorrect length %d != 2", len(files))
  71. }
  72. if files[0].Name != "dir2" {
  73. t.Errorf("Incorrect file %v != dir2", files[0])
  74. }
  75. if files[1].Name != filepath.Join("dir2", "cfile") {
  76. t.Errorf("Incorrect file %v != dir2/cfile", files[1])
  77. }
  78. }
  79. func TestWalk(t *testing.T) {
  80. ignores := ignore.New(fs.NewFilesystem(fs.FilesystemTypeBasic, "."))
  81. err := ignores.Load("testdata/.stignore")
  82. if err != nil {
  83. t.Fatal(err)
  84. }
  85. t.Log(ignores)
  86. fchan, err := Walk(context.TODO(), Config{
  87. Filesystem: fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata"),
  88. BlockSize: 128 * 1024,
  89. Matcher: ignores,
  90. Hashers: 2,
  91. })
  92. if err != nil {
  93. t.Fatal(err)
  94. }
  95. var tmp []protocol.FileInfo
  96. for f := range fchan {
  97. tmp = append(tmp, f)
  98. }
  99. sort.Sort(fileList(tmp))
  100. files := fileList(tmp).testfiles()
  101. if diff, equal := messagediff.PrettyDiff(testdata, files); !equal {
  102. t.Errorf("Walk returned unexpected data. Diff:\n%s", diff)
  103. }
  104. }
  105. func TestWalkError(t *testing.T) {
  106. _, err := Walk(context.TODO(), Config{
  107. Filesystem: fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata-missing"),
  108. BlockSize: 128 * 1024,
  109. Hashers: 2,
  110. })
  111. if err == nil {
  112. t.Error("no error from missing directory")
  113. }
  114. _, err = Walk(context.TODO(), Config{
  115. Filesystem: fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata/bar"),
  116. BlockSize: 128 * 1024,
  117. })
  118. if err == nil {
  119. t.Error("no error from non-directory")
  120. }
  121. }
  122. func TestVerify(t *testing.T) {
  123. blocksize := 16
  124. // data should be an even multiple of blocksize long
  125. data := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut e")
  126. buf := bytes.NewBuffer(data)
  127. progress := newByteCounter()
  128. defer progress.Close()
  129. blocks, err := Blocks(context.TODO(), buf, blocksize, -1, progress, false)
  130. if err != nil {
  131. t.Fatal(err)
  132. }
  133. if exp := len(data) / blocksize; len(blocks) != exp {
  134. t.Fatalf("Incorrect number of blocks %d != %d", len(blocks), exp)
  135. }
  136. if int64(len(data)) != progress.Total() {
  137. t.Fatalf("Incorrect counter value %d != %d", len(data), progress.Total())
  138. }
  139. buf = bytes.NewBuffer(data)
  140. err = Verify(buf, blocksize, blocks)
  141. t.Log(err)
  142. if err != nil {
  143. t.Fatal("Unexpected verify failure", err)
  144. }
  145. buf = bytes.NewBuffer(append(data, '\n'))
  146. err = Verify(buf, blocksize, blocks)
  147. t.Log(err)
  148. if err == nil {
  149. t.Fatal("Unexpected verify success")
  150. }
  151. buf = bytes.NewBuffer(data[:len(data)-1])
  152. err = Verify(buf, blocksize, blocks)
  153. t.Log(err)
  154. if err == nil {
  155. t.Fatal("Unexpected verify success")
  156. }
  157. data[42] = 42
  158. buf = bytes.NewBuffer(data)
  159. err = Verify(buf, blocksize, blocks)
  160. t.Log(err)
  161. if err == nil {
  162. t.Fatal("Unexpected verify success")
  163. }
  164. }
  165. func TestNormalization(t *testing.T) {
  166. if runtime.GOOS == "darwin" {
  167. t.Skip("Normalization test not possible on darwin")
  168. return
  169. }
  170. os.RemoveAll("testdata/normalization")
  171. defer os.RemoveAll("testdata/normalization")
  172. tests := []string{
  173. "0-A", // ASCII A -- accepted
  174. "1-\xC3\x84", // NFC 'Ä' -- conflicts with the entry below, accepted
  175. "1-\x41\xCC\x88", // NFD 'Ä' -- conflicts with the entry above, ignored
  176. "2-\xC3\x85", // NFC 'Å' -- accepted
  177. "3-\x41\xCC\x83", // NFD 'Ã' -- converted to NFC
  178. "4-\xE2\x98\x95", // U+2615 HOT BEVERAGE (☕) -- accepted
  179. "5-\xCD\xE2", // EUC-CN "wài" (外) -- ignored (not UTF8)
  180. }
  181. numInvalid := 2
  182. if runtime.GOOS == "windows" {
  183. // On Windows, in case 5 the character gets replaced with a
  184. // replacement character \xEF\xBF\xBD at the point it's written to disk,
  185. // which means it suddenly becomes valid (sort of).
  186. numInvalid--
  187. }
  188. numValid := len(tests) - numInvalid
  189. fs := fs.NewFilesystem(fs.FilesystemTypeBasic, ".")
  190. for _, s1 := range tests {
  191. // Create a directory for each of the interesting strings above
  192. if err := fs.MkdirAll(filepath.Join("testdata/normalization", s1), 0755); err != nil {
  193. t.Fatal(err)
  194. }
  195. for _, s2 := range tests {
  196. // Within each dir, create a file with each of the interesting
  197. // file names. Ensure that the file doesn't exist when it's
  198. // created. This detects and fails if there's file name
  199. // normalization stuff at the filesystem level.
  200. if fd, err := fs.OpenFile(filepath.Join("testdata/normalization", s1, s2), os.O_CREATE|os.O_EXCL, 0644); err != nil {
  201. t.Fatal(err)
  202. } else {
  203. fd.Write([]byte("test"))
  204. fd.Close()
  205. }
  206. }
  207. }
  208. // We can normalize a directory name, but we can't descend into it in the
  209. // same pass due to how filepath.Walk works. So we run the scan twice to
  210. // make sure it all gets done. In production, things will be correct
  211. // eventually...
  212. _, err := walkDir(fs, "testdata/normalization")
  213. if err != nil {
  214. t.Fatal(err)
  215. }
  216. tmp, err := walkDir(fs, "testdata/normalization")
  217. if err != nil {
  218. t.Fatal(err)
  219. }
  220. files := fileList(tmp).testfiles()
  221. // We should have one file per combination, plus the directories
  222. // themselves
  223. expectedNum := numValid*numValid + numValid
  224. if len(files) != expectedNum {
  225. t.Errorf("Expected %d files, got %d", expectedNum, len(files))
  226. }
  227. // The file names should all be in NFC form.
  228. for _, f := range files {
  229. t.Logf("%q (% x) %v", f.name, f.name, norm.NFC.IsNormalString(f.name))
  230. if !norm.NFC.IsNormalString(f.name) {
  231. t.Errorf("File name %q is not NFC normalized", f.name)
  232. }
  233. }
  234. }
  235. func TestIssue1507(t *testing.T) {
  236. w := &walker{}
  237. c := make(chan protocol.FileInfo, 100)
  238. fn := w.walkAndHashFiles(context.TODO(), c, c)
  239. fn("", nil, protocol.ErrClosed)
  240. }
  241. func TestWalkSymlinkUnix(t *testing.T) {
  242. if runtime.GOOS == "windows" {
  243. t.Skip("skipping unsupported symlink test")
  244. return
  245. }
  246. // Create a folder with a symlink in it
  247. os.RemoveAll("_symlinks")
  248. defer os.RemoveAll("_symlinks")
  249. os.Mkdir("_symlinks", 0755)
  250. os.Symlink("destination", "_symlinks/link")
  251. // Scan it
  252. fchan, err := Walk(context.TODO(), Config{
  253. Filesystem: fs.NewFilesystem(fs.FilesystemTypeBasic, "_symlinks"),
  254. BlockSize: 128 * 1024,
  255. })
  256. if err != nil {
  257. t.Fatal(err)
  258. }
  259. var files []protocol.FileInfo
  260. for f := range fchan {
  261. files = append(files, f)
  262. }
  263. // Verify that we got one symlink and with the correct attributes
  264. if len(files) != 1 {
  265. t.Errorf("expected 1 symlink, not %d", len(files))
  266. }
  267. if len(files[0].Blocks) != 0 {
  268. t.Errorf("expected zero blocks for symlink, not %d", len(files[0].Blocks))
  269. }
  270. if files[0].SymlinkTarget != "destination" {
  271. t.Errorf("expected symlink to have target destination, not %q", files[0].SymlinkTarget)
  272. }
  273. }
  274. func TestWalkSymlinkWindows(t *testing.T) {
  275. if runtime.GOOS != "windows" {
  276. t.Skip("skipping unsupported symlink test")
  277. }
  278. // Create a folder with a symlink in it
  279. os.RemoveAll("_symlinks")
  280. defer os.RemoveAll("_symlinks")
  281. os.Mkdir("_symlinks", 0755)
  282. if err := os.Symlink("destination", "_symlinks/link"); err != nil {
  283. // Probably we require permissions we don't have.
  284. t.Skip(err)
  285. }
  286. // Scan it
  287. fchan, err := Walk(context.TODO(), Config{
  288. Filesystem: fs.NewFilesystem(fs.FilesystemTypeBasic, "_symlinks"),
  289. BlockSize: 128 * 1024,
  290. })
  291. if err != nil {
  292. t.Fatal(err)
  293. }
  294. var files []protocol.FileInfo
  295. for f := range fchan {
  296. files = append(files, f)
  297. }
  298. // Verify that we got zero symlinks
  299. if len(files) != 0 {
  300. t.Errorf("expected zero symlinks, not %d", len(files))
  301. }
  302. }
  303. func walkDir(fs fs.Filesystem, dir string) ([]protocol.FileInfo, error) {
  304. fchan, err := Walk(context.TODO(), Config{
  305. Filesystem: fs,
  306. Subs: []string{dir},
  307. BlockSize: 128 * 1024,
  308. AutoNormalize: true,
  309. Hashers: 2,
  310. })
  311. if err != nil {
  312. return nil, err
  313. }
  314. var tmp []protocol.FileInfo
  315. for f := range fchan {
  316. tmp = append(tmp, f)
  317. }
  318. sort.Sort(fileList(tmp))
  319. return tmp, nil
  320. }
  321. type fileList []protocol.FileInfo
  322. func (l fileList) Len() int {
  323. return len(l)
  324. }
  325. func (l fileList) Less(a, b int) bool {
  326. return l[a].Name < l[b].Name
  327. }
  328. func (l fileList) Swap(a, b int) {
  329. l[a], l[b] = l[b], l[a]
  330. }
  331. func (l fileList) testfiles() testfileList {
  332. testfiles := make(testfileList, len(l))
  333. for i, f := range l {
  334. if len(f.Blocks) > 1 {
  335. panic("simple test case stuff only supports a single block per file")
  336. }
  337. testfiles[i] = testfile{name: f.Name, length: f.FileSize()}
  338. if len(f.Blocks) == 1 {
  339. testfiles[i].hash = fmt.Sprintf("%x", f.Blocks[0].Hash)
  340. }
  341. }
  342. return testfiles
  343. }
  344. func (l testfileList) String() string {
  345. var b bytes.Buffer
  346. b.WriteString("{\n")
  347. for _, f := range l {
  348. fmt.Fprintf(&b, " %s (%d bytes): %s\n", f.name, f.length, f.hash)
  349. }
  350. b.WriteString("}")
  351. return b.String()
  352. }
  353. var initOnce sync.Once
  354. const (
  355. testdataSize = 17 << 20
  356. testdataName = "_random.data"
  357. )
  358. func BenchmarkHashFile(b *testing.B) {
  359. initOnce.Do(initTestFile)
  360. b.ResetTimer()
  361. for i := 0; i < b.N; i++ {
  362. if _, err := HashFile(context.TODO(), fs.NewFilesystem(fs.FilesystemTypeBasic, ""), testdataName, protocol.BlockSize, nil, true); err != nil {
  363. b.Fatal(err)
  364. }
  365. }
  366. b.SetBytes(testdataSize)
  367. b.ReportAllocs()
  368. }
  369. func initTestFile() {
  370. fd, err := os.Create(testdataName)
  371. if err != nil {
  372. panic(err)
  373. }
  374. lr := io.LimitReader(rand.Reader, testdataSize)
  375. if _, err := io.Copy(fd, lr); err != nil {
  376. panic(err)
  377. }
  378. if err := fd.Close(); err != nil {
  379. panic(err)
  380. }
  381. }
  382. func TestStopWalk(t *testing.T) {
  383. // Create tree that is 100 levels deep, with each level containing 100
  384. // files (each 1 MB) and 100 directories (in turn containing 100 files
  385. // and 100 directories, etc). That is, in total > 100^100 files and as
  386. // many directories. It'll take a while to scan, giving us time to
  387. // cancel it and make sure the scan stops.
  388. // Use an errorFs as the backing fs for the rest of the interface
  389. // The way we get it is a bit hacky tho.
  390. errorFs := fs.NewFilesystem(fs.FilesystemType(-1), ".")
  391. fs := fs.NewWalkFilesystem(&infiniteFS{errorFs, 100, 100, 1e6})
  392. const numHashers = 4
  393. ctx, cancel := context.WithCancel(context.Background())
  394. fchan, err := Walk(ctx, Config{
  395. Filesystem: fs,
  396. BlockSize: 128 * 1024,
  397. Hashers: numHashers,
  398. ProgressTickIntervalS: -1, // Don't attempt to build the full list of files before starting to scan...
  399. })
  400. if err != nil {
  401. t.Fatal(err)
  402. }
  403. // Receive a few entries to make sure the walker is up and running,
  404. // scanning both files and dirs. Do some quick sanity tests on the
  405. // returned file entries to make sure we are not just reading crap from
  406. // a closed channel or something.
  407. dirs := 0
  408. files := 0
  409. for {
  410. f := <-fchan
  411. t.Log("Scanned", f)
  412. if f.IsDirectory() {
  413. if len(f.Name) == 0 || f.Permissions == 0 {
  414. t.Error("Bad directory entry", f)
  415. }
  416. dirs++
  417. } else {
  418. if len(f.Name) == 0 || len(f.Blocks) == 0 || f.Permissions == 0 {
  419. t.Error("Bad file entry", f)
  420. }
  421. files++
  422. }
  423. if dirs > 5 && files > 5 {
  424. break
  425. }
  426. }
  427. // Cancel the walker.
  428. cancel()
  429. // Empty out any waiting entries and wait for the channel to close.
  430. // Count them, they should be zero or very few - essentially, each
  431. // hasher has the choice of returning a fully handled entry or
  432. // cancelling, but they should not start on another item.
  433. extra := 0
  434. for range fchan {
  435. extra++
  436. }
  437. t.Log("Extra entries:", extra)
  438. if extra > numHashers {
  439. t.Error("unexpected extra entries received after cancel")
  440. }
  441. }