Debian Codegraph @

match.c

raw symbols SCIP
1 /*
2 * Block matching used by the file-transfer code.
3 *
4 * Copyright (C) 1996 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2003-2023 Wayne Davison
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, visit the http://fsf.org website.
20 */
21
22 #include "rsync.h"
23 #include "inums.h"
24
25 extern int checksum_seed;
26 extern int append_mode;
27
28 extern struct name_num_item *xfer_sum_nni;
29 extern int xfer_sum_len;
30
31 int updating_basis_file;
32 char sender_file_sum[MAX_DIGEST_LEN];
33
34 static int false_alarms;
35 static int hash_hits;
36 static int matches;
37 static int64 data_transfer;
38
39 static int total_false_alarms;
40 static int total_hash_hits;
41 static int total_matches;
42
43 extern struct stats stats;
44
45 #define TRADITIONAL_TABLESIZE (1<<16)
46
47 /* The maximum number of same-weak-checksum candidates we will compare
48 * against at a single file offset before giving up and rolling forward a
49 * byte. A weak checksum that collides thousands of times (very common in
50 * disk/VM images, which contain large runs of identical blocks) would
51 * otherwise turn hash_search()'s inner loop into an O(file_size *
52 * chain_length) scan, pegging a CPU at 100% for hours with no apparent
53 * progress (issue #217).
54 *
55 * Concretely, a synthetic 40000-block basis whose blocks all share one weak
56 * checksum took ~18.4s to sync a 60KB source on a modern x86_64 box before
57 * this cap and ~0.7s after it -- and the unbounded cost grows with the
58 * square of the file size, which is what produced the multi-hour "hangs"
59 * reported against real multi-GB images.
60 *
61 * Capping the per-offset work keeps the search bounded; any block we skip
62 * over is simply sent as literal data, so the result is always correct --
63 * only the transfer size is (slightly) affected. This is purely a
64 * sender-side search limit: it changes no checksum, emitted byte, or
65 * protocol field, so a capped sender interoperates with any receiver. */
66 #ifndef MAX_CHAIN_LEN
67 #define MAX_CHAIN_LEN 1024
68 #endif
69
70 static uint32 tablesize;
71 static int32 *hash_table;
72
73 #define SUM2HASH2(s1,s2) (((s1) + (s2)) & 0xFFFF)
74 #define SUM2HASH(sum) SUM2HASH2((sum)&0xFFFF,(sum)>>16)
75
76 #define BIG_SUM2HASH(sum) ((sum)%tablesize)
77
78 static void build_hash_table(struct sum_struct *s)
79 {
80 static uint32 alloc_size;
81 int32 i;
82
83 /* Dynamically calculate the hash table size so that the hash load
84 * for big files is about 80%. A number greater than the traditional
85 * size must be odd or s2 will not be able to span the entire set. */
86 tablesize = (uint32)(s->count/8) * 10 + 11;
87 if (tablesize < TRADITIONAL_TABLESIZE)
88 tablesize = TRADITIONAL_TABLESIZE;
89 if (tablesize > alloc_size || tablesize < alloc_size - 16*1024) {
90 if (hash_table)
91 free(hash_table);
92 hash_table = new_array(int32, tablesize);
93 alloc_size = tablesize;
94 }
95
96 memset(hash_table, 0xFF, tablesize * sizeof hash_table[0]);
97
98 if (tablesize == TRADITIONAL_TABLESIZE) {
99 for (i = 0; i < s->count; i++) {
100 uint32 t = SUM2HASH(s->sums[i].sum1);
101 s->sums[i].chain = hash_table[t];
102 hash_table[t] = i;
103 }
104 } else {
105 for (i = 0; i < s->count; i++) {
106 uint32 t = BIG_SUM2HASH(s->sums[i].sum1);
107 s->sums[i].chain = hash_table[t];
108 hash_table[t] = i;
109 }
110 }
111 }
112
113
114 static OFF_T last_match;
115
116
117 /* Transmit a literal and/or match token.
118 *
119 * This delightfully-named function is called either when we find a
120 * match and need to transmit all the unmatched data leading up to it,
121 * or when we get bored of accumulating literal data and just need to
122 * transmit it. As a result of this second case, it is called even if
123 * we have not matched at all!
124 *
125 * If i >= 0, the number of a matched token. If < 0, indicates we have
126 * only literal data. A -1 will send a 0-token-int too, and a -2 sends
127 * only literal data, w/o any token-int. */
128 static void matched(int f, struct sum_struct *s, struct map_struct *buf, OFF_T offset, int32 i)
129 {
130 int32 n = (int32)(offset - last_match); /* max value: block_size (int32) */
131 int32 j;
132
133 if (DEBUG_GTE(DELTASUM, 2) && i >= 0) {
134 rprintf(FINFO,
135 "match at %s last_match=%s j=%d len=%ld n=%ld\n",
136 big_num(offset), big_num(last_match), i,
137 (long)s->sums[i].len, (long)n);
138 }
139
140 send_token(f, i, buf, last_match, n, i < 0 ? 0 : s->sums[i].len);
141 data_transfer += n;
142
143 if (i >= 0) {
144 stats.matched_data += s->sums[i].len;
145 n += s->sums[i].len;
146 }
147
148 for (j = 0; j < n; j += CHUNK_SIZE) {
149 int32 n1 = MIN(CHUNK_SIZE, n - j);
150 sum_update(map_ptr(buf, last_match + j, n1), n1);
151 }
152
153 if (i >= 0)
154 last_match = offset + s->sums[i].len;
155 else
156 last_match = offset;
157
158 if (buf && INFO_GTE(PROGRESS, 1))
159 show_progress(last_match, buf->file_size);
160 }
161
162
163 static void hash_search(int f,struct sum_struct *s,
164 struct map_struct *buf, OFF_T len)
165 {
166 OFF_T offset, aligned_offset, end;
167 int32 k, want_i, aligned_i, backup;
168 char sum2[MAX_DIGEST_LEN];
169 uint32 s1, s2, sum;
170 int more;
171 schar *map;
172
173 // prevent possible memory leaks
174 memset(sum2, 0, sizeof sum2);
175
176 /* want_i is used to encourage adjacent matches, allowing the RLL
177 * coding of the output to work more efficiently. */
178 want_i = 0;
179
180 if (DEBUG_GTE(DELTASUM, 2)) {
181 rprintf(FINFO, "hash search b=%ld len=%s\n",
182 (long)s->blength, big_num(len));
183 }
184
185 k = (int32)MIN(len, (OFF_T)s->blength);
186
187 map = (schar *)map_ptr(buf, 0, k);
188
189 sum = get_checksum1((char *)map, k);
190 s1 = sum & 0xFFFF;
191 s2 = sum >> 16;
192 if (DEBUG_GTE(DELTASUM, 3))
193 rprintf(FINFO, "sum=%.8x k=%ld\n", sum, (long)k);
194
195 offset = aligned_offset = aligned_i = 0;
196
197 end = len + 1 - s->sums[s->count-1].len;
198
199 if (DEBUG_GTE(DELTASUM, 3)) {
200 rprintf(FINFO, "hash search s->blength=%ld len=%s count=%s\n",
201 (long)s->blength, big_num(len), big_num(s->count));
202 }
203
204 do {
205 int done_csum2 = 0;
206 uint32 hash_entry;
207 int32 i, *prev;
208 int32 chain_len = 0;
209
210 if (DEBUG_GTE(DELTASUM, 4)) {
211 rprintf(FINFO, "offset=%s sum=%04x%04x\n",
212 big_num(offset), s2 & 0xFFFF, s1 & 0xFFFF);
213 }
214
215 if (tablesize == TRADITIONAL_TABLESIZE) {
216 hash_entry = SUM2HASH2(s1,s2);
217 if ((i = hash_table[hash_entry]) < 0)
218 goto null_hash;
219 sum = (s1 & 0xffff) | (s2 << 16);
220 } else {
221 sum = (s1 & 0xffff) | (s2 << 16);
222 hash_entry = BIG_SUM2HASH(sum);
223 if ((i = hash_table[hash_entry]) < 0)
224 goto null_hash;
225 }
226 prev = &hash_table[hash_entry];
227
228 hash_hits++;
229 do {
230 int32 l;
231
232 /* When updating in-place, the chunk's offset must be
233 * either >= our offset or identical data at that offset.
234 * Remove any bypassed entries that we can never use. */
235 if (updating_basis_file && s->sums[i].offset < offset
236 && !(s->sums[i].flags & SUMFLG_SAME_OFFSET)) {
237 *prev = s->sums[i].chain;
238 continue;
239 }
240 prev = &s->sums[i].chain;
241
242 if (sum != s->sums[i].sum1)
243 continue;
244
245 /* Bound the work spent on a single pathological hash
246 * bucket. If this weak checksum matches more than
247 * MAX_CHAIN_LEN records, stop scanning and treat this
248 * offset as a non-match (issue #217). The skipped data
249 * is sent literally, never corrupted. */
250 if (++chain_len > MAX_CHAIN_LEN)
251 break;
252
253 /* also make sure the two blocks are the same length */
254 l = (int32)MIN((OFF_T)s->blength, len-offset);
255 if (l != s->sums[i].len)
256 continue;
257
258 if (DEBUG_GTE(DELTASUM, 3)) {
259 rprintf(FINFO,
260 "potential match at %s i=%ld sum=%08x\n",
261 big_num(offset), (long)i, sum);
262 }
263
264 if (!done_csum2) {
265 map = (schar *)map_ptr(buf,offset,l);
266 get_checksum2((char *)map,l,sum2);
267 done_csum2 = 1;
268 }
269
270 if (memcmp(sum2, sum2_at(s, i), s->s2length) != 0) {
271 false_alarms++;
272 continue;
273 }
274
275 /* When updating in-place, the best possible match is
276 * one with an identical offset, so we prefer that over
277 * the adjacent want_i optimization. */
278 if (updating_basis_file) {
279 /* All the generator's chunks start at blength boundaries. */
280 while (aligned_offset < offset) {
281 aligned_offset += s->blength;
282 aligned_i++;
283 }
284 if ((offset == aligned_offset
285 || (sum == 0 && l == s->blength && aligned_offset + l <= len))
286 && aligned_i < s->count) {
287 if (i != aligned_i) {
288 if (sum != s->sums[aligned_i].sum1
289 || l != s->sums[aligned_i].len
290 || memcmp(sum2, sum2_at(s, aligned_i), s->s2length) != 0)
291 goto check_want_i;
292 i = aligned_i;
293 }
294 if (offset != aligned_offset) {
295 /* We've matched some zeros in a spot that is also zeros
296 * further along in the basis file, if we find zeros ahead
297 * in the sender's file, we'll output enough literal data
298 * to re-align with the basis file, and get back to seeking
299 * instead of writing. */
300 backup = (int32)(aligned_offset - last_match);
301 if (backup < 0)
302 backup = 0;
303 map = (schar *)map_ptr(buf, aligned_offset - backup, l + backup)
304 + backup;
305 sum = get_checksum1((char *)map, l);
306 if (sum != s->sums[i].sum1)
307 goto check_want_i;
308 get_checksum2((char *)map, l, sum2);
309 if (memcmp(sum2, sum2_at(s, i), s->s2length) != 0)
310 goto check_want_i;
311 /* OK, we have a re-alignment match. Bump the offset
312 * forward to the new match point. */
313 offset = aligned_offset;
314 }
315 /* This identical chunk is in the same spot in the old and new file. */
316 s->sums[i].flags |= SUMFLG_SAME_OFFSET;
317 want_i = i;
318 }
319 }
320
321 check_want_i:
322 /* we've found a match, but now check to see
323 * if want_i can hint at a better match. */
324 if (i != want_i && want_i < s->count
325 && (!updating_basis_file || s->sums[want_i].offset >= offset
326 || s->sums[want_i].flags & SUMFLG_SAME_OFFSET)
327 && sum == s->sums[want_i].sum1
328 && l == s->sums[want_i].len
329 && memcmp(sum2, sum2_at(s, want_i), s->s2length) == 0) {
330 /* we've found an adjacent match - the RLL coder
331 * will be happy */
332 i = want_i;
333 }
334 want_i = i + 1;
335
336 matched(f,s,buf,offset,i);
337 offset += s->sums[i].len - 1;
338 k = (int32)MIN((OFF_T)s->blength, len-offset);
339 map = (schar *)map_ptr(buf, offset, k);
340 sum = get_checksum1((char *)map, k);
341 s1 = sum & 0xFFFF;
342 s2 = sum >> 16;
343 matches++;
344 break;
345 } while ((i = s->sums[i].chain) >= 0);
346
347 null_hash:
348 backup = (int32)(offset - last_match);
349 /* We sometimes read 1 byte prior to last_match... */
350 if (backup < 0)
351 backup = 0;
352
353 /* Trim off the first byte from the checksum */
354 more = offset + k < len;
355 map = (schar *)map_ptr(buf, offset - backup, k + more + backup) + backup;
356 s1 -= map[0] + CHAR_OFFSET;
357 s2 -= k * (map[0]+CHAR_OFFSET);
358
359 /* Add on the next byte (if there is one) to the checksum */
360 if (more) {
361 s1 += map[k] + CHAR_OFFSET;
362 s2 += s1;
363 } else
364 --k;
365
366 /* By matching early we avoid re-reading the
367 data 3 times in the case where a token
368 match comes a long way after last
369 match. The 3 reads are caused by the
370 running match, the checksum update and the
371 literal send. */
372 if (backup >= s->blength+CHUNK_SIZE && end-offset > CHUNK_SIZE)
373 matched(f, s, buf, offset - s->blength, -2);
374 } while (++offset < end);
375
376 matched(f, s, buf, len, -1);
377 map_ptr(buf, len-1, 1);
378 }
379
380
381 /**
382 * Scan through a origin file, looking for sections that match
383 * checksums from the generator, and transmit either literal or token
384 * data.
385 *
386 * Also calculates the MD4 checksum of the whole file, using the md
387 * accumulator. This is transmitted with the file as protection
388 * against corruption on the wire.
389 *
390 * @param s Checksums received from the generator. If <tt>s->count ==
391 * 0</tt>, then there are actually no checksums for this file.
392 *
393 * @param len Length of the file to send.
394 **/
395 void match_sums(int f, struct sum_struct *s, struct map_struct *buf, OFF_T len)
396 {
397 last_match = 0;
398 false_alarms = 0;
399 hash_hits = 0;
400 matches = 0;
401 data_transfer = 0;
402
403 sum_init(xfer_sum_nni, checksum_seed);
404
405 if (append_mode > 0) {
406 if (s->flength > len) {
407 /* A hostile or confused peer can claim a verified-prefix
408 * length that exceeds what we have on disk -- including
409 * for an empty local file, where buf is NULL and the
410 * map_ptr() calls below would dereference it. Clamp to
411 * what we can actually read. */
412 s->flength = len;
413 }
414 if (append_mode == 2) {
415 OFF_T j = 0;
416 for (j = CHUNK_SIZE; j < s->flength; j += CHUNK_SIZE) {
417 if (buf && INFO_GTE(PROGRESS, 1))
418 show_progress(last_match, buf->file_size);
419 sum_update(map_ptr(buf, last_match, CHUNK_SIZE),
420 CHUNK_SIZE);
421 last_match = j;
422 }
423 if (last_match < s->flength) {
424 int32 n = (int32)(s->flength - last_match);
425 if (buf && INFO_GTE(PROGRESS, 1))
426 show_progress(last_match, buf->file_size);
427 sum_update(map_ptr(buf, last_match, n), n);
428 }
429 }
430 last_match = s->flength;
431 s->count = 0;
432 }
433
434 if (len > 0 && s->count > 0) {
435 build_hash_table(s);
436
437 if (DEBUG_GTE(DELTASUM, 2))
438 rprintf(FINFO,"built hash table\n");
439
440 hash_search(f, s, buf, len);
441
442 if (DEBUG_GTE(DELTASUM, 2))
443 rprintf(FINFO,"done hash search\n");
444 } else {
445 OFF_T j;
446 /* by doing this in pieces we avoid too many seeks */
447 for (j = last_match + CHUNK_SIZE; j < len; j += CHUNK_SIZE)
448 matched(f, s, buf, j, -2);
449 matched(f, s, buf, len, -1);
450 }
451
452 sum_end(sender_file_sum);
453
454 /* If we had a read error, send a bad checksum. We use all bits
455 * off as long as the checksum doesn't happen to be that, in
456 * which case we turn the last 0 bit into a 1. */
457 if (buf && buf->status != 0) {
458 int i;
459 for (i = 0; i < xfer_sum_len && sender_file_sum[i] == 0; i++) {}
460 memset(sender_file_sum, 0, xfer_sum_len);
461 if (i == xfer_sum_len)
462 sender_file_sum[i-1]++;
463 }
464
465 if (DEBUG_GTE(DELTASUM, 2))
466 rprintf(FINFO,"sending file_sum\n");
467 write_buf(f, sender_file_sum, xfer_sum_len);
468
469 if (DEBUG_GTE(DELTASUM, 2)) {
470 rprintf(FINFO, "false_alarms=%d hash_hits=%d matches=%d\n",
471 false_alarms, hash_hits, matches);
472 }
473
474 total_hash_hits += hash_hits;
475 total_false_alarms += false_alarms;
476 total_matches += matches;
477 stats.literal_data += data_transfer;
478 }
479
480 void match_report(void)
481 {
482 if (!DEBUG_GTE(DELTASUM, 1))
483 return;
484
485 rprintf(FINFO,
486 "total: matches=%d hash_hits=%d false_alarms=%d data=%s\n",
487 total_matches, total_hash_hits, total_false_alarms,
488 big_num(stats.literal_data));
489 }