blocks.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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/syncthing/syncthing/internal/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, sizehint int64) ([]protocol.BlockInfo, error) {
  15. var blocks []protocol.BlockInfo
  16. if sizehint > 0 {
  17. blocks = make([]protocol.BlockInfo, 0, int(sizehint/int64(blocksize)))
  18. }
  19. var offset int64
  20. hf := sha256.New()
  21. for {
  22. lr := &io.LimitedReader{R: r, N: int64(blocksize)}
  23. n, err := io.Copy(hf, lr)
  24. if err != nil {
  25. return nil, err
  26. }
  27. if n == 0 {
  28. break
  29. }
  30. b := protocol.BlockInfo{
  31. Size: uint32(n),
  32. Offset: offset,
  33. Hash: hf.Sum(nil),
  34. }
  35. blocks = append(blocks, b)
  36. offset += int64(n)
  37. hf.Reset()
  38. }
  39. if len(blocks) == 0 {
  40. // Empty file
  41. blocks = append(blocks, protocol.BlockInfo{
  42. Offset: 0,
  43. Size: 0,
  44. Hash: sha256OfNothing,
  45. })
  46. }
  47. return blocks, nil
  48. }
  49. // BlockDiff returns lists of common and missing (to transform src into tgt)
  50. // blocks. Both block lists must have been created with the same block size.
  51. func BlockDiff(src, tgt []protocol.BlockInfo) (have, need []protocol.BlockInfo) {
  52. if len(tgt) == 0 && len(src) != 0 {
  53. return nil, nil
  54. }
  55. // Set the Offset field on each target block
  56. var offset int64
  57. for i := range tgt {
  58. tgt[i].Offset = offset
  59. offset += int64(tgt[i].Size)
  60. }
  61. if len(tgt) != 0 && len(src) == 0 {
  62. // Copy the entire file
  63. return nil, tgt
  64. }
  65. for i := range tgt {
  66. if i >= len(src) || bytes.Compare(tgt[i].Hash, src[i].Hash) != 0 {
  67. // Copy differing block
  68. need = append(need, tgt[i])
  69. } else {
  70. have = append(have, tgt[i])
  71. }
  72. }
  73. return have, need
  74. }