-
Notifications
You must be signed in to change notification settings - Fork 3
/
rsync.go
413 lines (365 loc) · 9.45 KB
/
rsync.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// RSync/RDiff implementation.
//
// Algorithm found at: http://www.samba.org/~tridge/phd_thesis.pdf
//
// Definitions
//
// Source: The final content.
// Target: The content to be made into final content.
// Signature: The sequence of hashes used to identify the content.
package rsync
import (
"bytes"
"hash"
"io"
"sync"
"github.com/minio/highwayhash"
)
var magicHighwayHash256Key = []byte("\x4b\xe7\x34\xfa\x8e\x23\x8a\xcd\x26\x3e\x83\xe6\xbb\x96\x85\x52\x04\x0f\x93\x5d\xa3\x9f\x44\x14\x97\xe0\x9d\x13\x22\xde\x36\xa0")
// If no BlockSize is specified in the RSync instance, this value is used.
const DefaultBlockSize = 1024 * 6
const DefaultMaxDataOp = DefaultBlockSize * 10
// Internal constant used in rolling checksum.
const _M = 1 << 16
// Operation Types.
type OpType byte
const (
OpBlock OpType = iota
OpData
OpHash
OpBlockRange
)
// Instruction to mutate target to align to source.
type Operation struct {
Type OpType
BlockIndex uint64
BlockIndexEnd uint64
Data []byte
}
// Signature hash item generated from target.
type BlockHash struct {
Index uint64
StrongHash []byte
WeakHash uint32
}
// Write signatures as they are generated.
type SignatureWriter func(bl BlockHash) error
type OperationWriter func(op Operation) error
// Properties to use while working with the rsync algorithm.
// A single RSync should not be used concurrently as it may contain
// internal buffers and hash sums.
type RSync struct {
BlockSize int
MaxDataOp int
// If this is nil a HighwayHash is used.
Hasher hash.Hash
once sync.Once
buffer []byte
}
func (r *RSync) initialize() {
if r.BlockSize <= 0 {
r.BlockSize = DefaultBlockSize
}
if r.MaxDataOp <= 0 {
r.MaxDataOp = DefaultMaxDataOp
}
if r.Hasher == nil {
r.Hasher, _ = highwayhash.New(magicHighwayHash256Key)
}
minBufferSize := (r.BlockSize * 2) + (r.MaxDataOp)
if len(r.buffer) < minBufferSize {
r.buffer = make([]byte, minBufferSize)
}
}
// If the target length is known the number of hashes in the
// signature can be determined.
func (r *RSync) BlockHashCount(targetLength int) (count int) {
r.once.Do(r.initialize)
count = (targetLength / r.BlockSize)
if targetLength%r.BlockSize != 0 {
count++
}
return
}
// Calculate the signature of target.
func (r *RSync) CreateSignature(target io.Reader, sw SignatureWriter) error {
r.once.Do(r.initialize)
var err error
var n int
buffer := r.buffer
var block []byte
loop := true
var index uint64
for loop {
n, err = io.ReadAtLeast(target, buffer, r.BlockSize)
if err != nil {
// n == 0.
if err == io.EOF {
return nil
}
if err != io.ErrUnexpectedEOF {
return err
}
// n > 0.
loop = false
}
block = buffer[:n]
weak, _, _ := βhash(block)
err = sw(BlockHash{
StrongHash: r.uniqueHash(block),
WeakHash: weak,
Index: index,
})
if err != nil {
return err
}
index++
}
return nil
}
// Apply the difference to the target.
func (r *RSync) ApplyDelta(alignedTarget io.Writer, target io.ReadSeeker, ops chan Operation) error {
r.once.Do(r.initialize)
var block []byte
buffer := r.buffer
writeBlock := func(op Operation) error {
if _, err := target.Seek(int64(r.BlockSize*int(op.BlockIndex)), 0); err != nil {
return err
}
n, err := io.ReadAtLeast(target, buffer, r.BlockSize)
if err != nil && err != io.ErrUnexpectedEOF {
return err
}
block = buffer[:n]
if _, err = alignedTarget.Write(block); err != nil {
return err
}
return nil
}
for op := range ops {
switch op.Type {
case OpBlockRange:
for i := op.BlockIndex; i <= op.BlockIndexEnd; i++ {
if err := writeBlock(Operation{
Type: OpBlock,
BlockIndex: i,
}); err != nil {
if err == io.EOF {
break
}
return err
}
}
case OpBlock:
if err := writeBlock(op); err != nil {
if err == io.EOF {
break
}
return err
}
case OpData:
if _, err := alignedTarget.Write(op.Data); err != nil {
return err
}
}
}
return nil
}
// Create the operation list to mutate the target signature into the source.
// Any data operation from the OperationWriter must have the data copied out
// within the span of the function; the data buffer underlying the operation
// data is reused. The sourceSum create a complete hash sum of the source if
// present.
func (r *RSync) CreateDelta(source io.Reader, signature []BlockHash, ops OperationWriter) (err error) {
r.once.Do(r.initialize)
buffer := r.buffer
// A single β hashes may correlate with a many unique hashes.
hashLookup := make(map[uint32][]BlockHash, len(signature))
for _, h := range signature {
key := h.WeakHash
hashLookup[key] = append(hashLookup[key], h)
}
type section struct {
tail int
head int
}
var data, sum section
var n, validTo int
var αPop, αPush, β, β1, β2 uint32
var blockIndex uint64
var rolling, lastRun, foundHash bool
// Store the previous non-data operation for combining.
var prevOp *Operation
// Send the last operation if there is one waiting.
defer func() {
if prevOp == nil {
return
}
err = ops(*prevOp)
prevOp = nil
}()
// Combine OpBlock into OpBlockRange. To do this store the previous
// non-data operation and determine if it can be extended.
enqueue := func(op Operation) (err error) {
switch op.Type {
case OpBlock:
if prevOp != nil {
switch prevOp.Type {
case OpBlock:
if prevOp.BlockIndex+1 == op.BlockIndex {
prevOp = &Operation{
Type: OpBlockRange,
BlockIndex: prevOp.BlockIndex,
BlockIndexEnd: op.BlockIndex,
}
return
}
case OpBlockRange:
if prevOp.BlockIndexEnd+1 == op.BlockIndex {
prevOp.BlockIndexEnd = op.BlockIndex
return
}
}
err = ops(*prevOp)
if err != nil {
return
}
prevOp = nil
}
prevOp = &op
case OpData:
// Never save a data operation, as it would corrupt the buffer.
if prevOp != nil {
err = ops(*prevOp)
if err != nil {
return
}
}
err = ops(op)
if err != nil {
return
}
prevOp = nil
}
return
}
for !lastRun {
// Determine if the buffer should be extended.
if sum.tail+r.BlockSize > validTo {
// Determine if the buffer should be wrapped.
if validTo+r.BlockSize > len(buffer) {
// Before wrapping the buffer, send any trailing data off.
if data.tail < data.head {
err = enqueue(Operation{Type: OpData, Data: buffer[data.tail:data.head]})
if err != nil {
return err
}
}
// Wrap the buffer.
l := validTo - sum.tail
copy(buffer[:l], buffer[sum.tail:validTo])
// Reset indexes.
validTo = l
sum.tail = 0
data.head = 0
data.tail = 0
}
n, err = io.ReadAtLeast(source, buffer[validTo:validTo+r.BlockSize], r.BlockSize)
validTo += n
if err != nil {
if err != io.EOF && err != io.ErrUnexpectedEOF {
return err
}
lastRun = true
data.head = validTo
}
}
// Set the hash sum window head. Must either be a block size
// or be at the end of the buffer.
sum.head = min(sum.tail+r.BlockSize, validTo)
// Compute the rolling hash.
if !rolling {
β, β1, β2 = βhash(buffer[sum.tail:sum.head])
rolling = true
} else {
αPush = uint32(buffer[sum.head-1])
β1 = (β1 - αPop + αPush) % _M
β2 = (β2 - uint32(sum.head-sum.tail)*αPop + β1) % _M
β = β1 + _M*β2
}
// Determine if there is a hash match.
foundHash = false
if hh, ok := hashLookup[β]; ok && !lastRun {
blockIndex, foundHash = findUniqueHash(hh, r.uniqueHash(buffer[sum.tail:sum.head]))
}
// Send data off if there is data available and a hash is found (so the buffer before it
// must be flushed first), or the data chunk size has reached it's maximum size (for buffer
// allocation purposes) or to flush the end of the data.
if data.tail < data.head && (foundHash || data.head-data.tail >= r.MaxDataOp || lastRun) {
err = enqueue(Operation{Type: OpData, Data: buffer[data.tail:data.head]})
if err != nil {
return err
}
data.tail = data.head
}
if foundHash {
err = enqueue(Operation{Type: OpBlock, BlockIndex: blockIndex})
if err != nil {
return err
}
rolling = false
sum.tail += r.BlockSize
// There is prior knowledge that any available data
// buffered will have already been sent. Thus we can
// assume data.head and data.tail are the same.
// May trigger "data wrap".
data.head = sum.tail
data.tail = sum.tail
} else {
// The following is for the next loop iteration, so don't try to calculate if last.
if !lastRun && rolling {
αPop = uint32(buffer[sum.tail])
}
sum.tail++
// May trigger "data wrap".
data.head = sum.tail
}
}
return nil
}
// Use a more unique way to identify a set of bytes.
func (r *RSync) uniqueHash(v []byte) []byte {
r.Hasher.Reset()
r.Hasher.Write(v)
return r.Hasher.Sum(nil)
}
// Searches for a given strong hash among all strong hashes in this bucket.
func findUniqueHash(hh []BlockHash, hashValue []byte) (uint64, bool) {
if len(hashValue) == 0 {
return 0, false
}
for _, block := range hh {
if bytes.Equal(block.StrongHash, hashValue) {
return block.Index, true
}
}
return 0, false
}
// Use a faster way to identify a set of bytes.
func βhash(block []byte) (β uint32, β1 uint32, β2 uint32) {
var a, b uint32
for i, val := range block {
a += uint32(val)
b += (uint32(len(block)-1) - uint32(i) + 1) * uint32(val)
}
β = (a % _M) + (_M * (b % _M))
β1 = a % _M
β2 = b % _M
return
}
func min(a, b int) int {
if a < b {
return a
}
return b
}