blocks.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. package scanner
  5. import (
  6. "bytes"
  7. "crypto/sha256"
  8. "io"
  9. "github.com/calmh/syncthing/protocol"
  10. )
  11. const StandardBlockSize = 128 * 1024
  12. var sha256OfNothing = []uint8{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}
  13. // Blocks returns the blockwise hash of the reader.
  14. func Blocks(r io.Reader, blocksize int) ([]protocol.BlockInfo, error) {
  15. var blocks []protocol.BlockInfo
  16. var offset int64
  17. for {
  18. lr := &io.LimitedReader{R: r, N: int64(blocksize)}
  19. hf := sha256.New()
  20. n, err := io.Copy(hf, lr)
  21. if err != nil {
  22. return nil, err
  23. }
  24. if n == 0 {
  25. break
  26. }
  27. b := protocol.BlockInfo{
  28. Size: uint32(n),
  29. Offset: offset,
  30. Hash: hf.Sum(nil),
  31. }
  32. blocks = append(blocks, b)
  33. offset += int64(n)
  34. }
  35. if len(blocks) == 0 {
  36. // Empty file
  37. blocks = append(blocks, protocol.BlockInfo{
  38. Offset: 0,
  39. Size: 0,
  40. Hash: sha256OfNothing,
  41. })
  42. }
  43. return blocks, nil
  44. }
  45. // BlockDiff returns lists of common and missing (to transform src into tgt)
  46. // blocks. Both block lists must have been created with the same block size.
  47. func BlockDiff(src, tgt []protocol.BlockInfo) (have, need []protocol.BlockInfo) {
  48. if len(tgt) == 0 && len(src) != 0 {
  49. return nil, nil
  50. }
  51. // Set the Offset field on each target block
  52. var offset int64
  53. for i := range tgt {
  54. tgt[i].Offset = offset
  55. offset += int64(tgt[i].Size)
  56. }
  57. if len(tgt) != 0 && len(src) == 0 {
  58. // Copy the entire file
  59. return nil, tgt
  60. }
  61. for i := range tgt {
  62. if i >= len(src) || bytes.Compare(tgt[i].Hash, src[i].Hash) != 0 {
  63. // Copy differing block
  64. need = append(need, tgt[i])
  65. } else {
  66. have = append(have, tgt[i])
  67. }
  68. }
  69. return have, need
  70. }