Debian Codegraph @

token.c

raw symbols SCIP
1 /*
2 * Routines used by the file-transfer code.
3 *
4 * Copyright (C) 1996 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2003-2022 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 "itypes.h"
24 #include <zlib.h>
25 #ifdef SUPPORT_ZSTD
26 #include <zstd.h>
27 #endif
28 #ifdef SUPPORT_LZ4
29 #include <lz4.h>
30 #endif
31
32 extern int do_compression;
33 extern int protocol_version;
34 extern int module_id;
35 extern int do_compression_level;
36 extern int do_compression_threads;
37 extern char *skip_compress;
38
39 #ifndef Z_INSERT_ONLY
40 #define Z_INSERT_ONLY Z_SYNC_FLUSH
41 #endif
42
43 static int skip_compression_level; /* The least possible compressing for handling skip-compress files. */
44 static int per_file_default_level; /* The default level that each new file gets prior to checking its suffix. */
45
46 struct suffix_tree {
47 struct suffix_tree *sibling;
48 struct suffix_tree *child;
49 char letter, word_end;
50 };
51
52 static char *match_list;
53 static struct suffix_tree *suftree;
54
55 void init_compression_level(void)
56 {
57 int min_level, max_level, def_level, off_level;
58
59 switch (do_compression) {
60 case CPRES_NONE:
61 return;
62 case CPRES_ZLIB:
63 case CPRES_ZLIBX:
64 min_level = 1;
65 max_level = Z_BEST_COMPRESSION;
66 def_level = 6; /* Z_DEFAULT_COMPRESSION is -1, so set it to the real default */
67 off_level = skip_compression_level = Z_NO_COMPRESSION;
68 if (do_compression_level == Z_DEFAULT_COMPRESSION)
69 do_compression_level = def_level;
70 break;
71 #ifdef SUPPORT_ZSTD
72 case CPRES_ZSTD:
73 min_level = skip_compression_level = ZSTD_minCLevel();
74 max_level = ZSTD_maxCLevel();
75 def_level = ZSTD_CLEVEL_DEFAULT;
76 off_level = CLVL_NOT_SPECIFIED;
77 if (do_compression_level == 0)
78 do_compression_level = def_level;
79 break;
80 #endif
81 #ifdef SUPPORT_LZ4
82 case CPRES_LZ4:
83 min_level = skip_compression_level = 0;
84 max_level = 0;
85 def_level = 0;
86 off_level = CLVL_NOT_SPECIFIED;
87 break;
88 #endif
89 default: /* paranoia to prevent missing case values */
90 NOISY_DEATH("Unknown do_compression value");
91 }
92
93 if (do_compression_level == CLVL_NOT_SPECIFIED)
94 do_compression_level = def_level;
95 else if (do_compression_level == off_level) {
96 do_compression = CPRES_NONE;
97 return;
98 }
99
100 /* We don't bother with any errors or warnings -- just make sure that the values are valid. */
101 if (do_compression_level < min_level)
102 do_compression_level = min_level;
103 else if (do_compression_level > max_level)
104 do_compression_level = max_level;
105 }
106
107 static void add_suffix(struct suffix_tree **prior, char ltr, const char *str)
108 {
109 struct suffix_tree *node, *newnode;
110
111 if (ltr == '[') {
112 const char *after = strchr(str, ']');
113 /* Treat "[foo" and "[]" as having a literal '['. */
114 if (after && after++ != str+1) {
115 while ((ltr = *str++) != ']')
116 add_suffix(prior, ltr, after);
117 return;
118 }
119 }
120
121 for (node = *prior; node; prior = &node->sibling, node = node->sibling) {
122 if (node->letter == ltr) {
123 if (*str)
124 add_suffix(&node->child, *str, str+1);
125 else
126 node->word_end = 1;
127 return;
128 }
129 if (node->letter > ltr)
130 break;
131 }
132 newnode = new(struct suffix_tree);
133 newnode->sibling = node;
134 newnode->child = NULL;
135 newnode->letter = ltr;
136 *prior = newnode;
137 if (*str) {
138 add_suffix(&newnode->child, *str, str+1);
139 newnode->word_end = 0;
140 } else
141 newnode->word_end = 1;
142 }
143
144 static void add_nocompress_suffixes(const char *str)
145 {
146 char *buf, *t;
147 const char *f = str;
148
149 buf = new_array(char, strlen(f) + 1);
150
151 while (*f) {
152 if (*f == '/') {
153 f++;
154 continue;
155 }
156
157 t = buf;
158 do {
159 if (isUpper(f))
160 *t++ = toLower(f);
161 else
162 *t++ = *f;
163 } while (*++f != '/' && *f);
164 *t++ = '\0';
165
166 /* add_suffix() recurses once per character; an attacker-supplied
167 * --skip-compress (from our own argv OR propagated to a daemon
168 * receiver via server_options()) with one very long token
169 * exhausts the stack. Real file extensions are short -- cap
170 * the recursion depth by truncating absurd suffixes. */
171 if (t - buf > 32 + 1)
172 buf[32] = '\0';
173 add_suffix(&suftree, *buf, buf+1);
174 }
175
176 free(buf);
177 }
178
179 static void init_set_compression(void)
180 {
181 const char *f;
182 char *t, *start;
183
184 if (skip_compress)
185 add_nocompress_suffixes(skip_compress);
186
187 /* A non-daemon transfer skips the default suffix list if the
188 * user specified --skip-compress. */
189 if (skip_compress && module_id < 0)
190 f = "";
191 else
192 f = lp_dont_compress(module_id);
193
194 match_list = t = new_array(char, strlen(f) + 2);
195
196 per_file_default_level = do_compression_level;
197
198 while (*f) {
199 if (*f == ' ') {
200 f++;
201 continue;
202 }
203
204 start = t;
205 do {
206 if (isUpper(f))
207 *t++ = toLower(f);
208 else
209 *t++ = *f;
210 } while (*++f != ' ' && *f);
211 *t++ = '\0';
212
213 if (t - start == 1+1 && *start == '*') {
214 /* Optimize a match-string of "*". */
215 *match_list = '\0';
216 suftree = NULL;
217 per_file_default_level = skip_compression_level;
218 break;
219 }
220
221 /* Move *.foo items into the stuffix tree. */
222 if (*start == '*' && start[1] == '.' && start[2]
223 && !strpbrk(start+2, ".?*")) {
224 add_suffix(&suftree, start[2], start+3);
225 t = start;
226 }
227 }
228 *t++ = '\0';
229 }
230
231 /* determine the compression level based on a wildcard filename list */
232 void set_compression(const char *fname)
233 {
234 #if 0 /* No compression algorithms currently allow mid-stream changing of the level. */
235 const struct suffix_tree *node;
236 const char *s;
237 char ltr;
238 #endif
239
240 if (!do_compression)
241 return;
242
243 if (!match_list)
244 init_set_compression();
245
246 #if 0
247 compression_level = per_file_default_level;
248
249 if (!*match_list && !suftree)
250 return;
251
252 if ((s = strrchr(fname, '/')) != NULL)
253 fname = s + 1;
254
255 for (s = match_list; *s; s += strlen(s) + 1) {
256 if (iwildmatch(s, fname)) {
257 compression_level = skip_compression_level;
258 return;
259 }
260 }
261
262 if (!(node = suftree) || !(s = strrchr(fname, '.'))
263 || s == fname || !(ltr = *++s))
264 return;
265
266 while (1) {
267 if (isUpper(&ltr))
268 ltr = toLower(&ltr);
269 while (node->letter != ltr) {
270 if (node->letter > ltr)
271 return;
272 if (!(node = node->sibling))
273 return;
274 }
275 if ((ltr = *++s) == '\0') {
276 if (node->word_end)
277 compression_level = skip_compression_level;
278 return;
279 }
280 if (!(node = node->child))
281 return;
282 }
283 #else
284 (void)fname;
285 #endif
286 }
287
288 /* non-compressing recv token */
289 static int32 simple_recv_token(int f, char **data)
290 {
291 static int32 residue;
292 static char *buf;
293 int32 n;
294
295 if (!buf)
296 buf = new_array(char, CHUNK_SIZE);
297
298 if (residue == 0) {
299 int32 i = read_int(f);
300 if (i <= 0)
301 return i;
302 /* A literal run may exceed CHUNK_SIZE: some peers (e.g. the
303 * acrosync library) use a 64k block size. The loop below reads
304 * the run CHUNK_SIZE bytes at a time, so read_buf never writes
305 * past the static CHUNK_SIZE buffer regardless of i. */
306 residue = i;
307 }
308
309 *data = buf;
310 n = MIN(CHUNK_SIZE,residue);
311 residue -= n;
312 read_buf(f,buf,n);
313 return n;
314 }
315
316 /* non-compressing send token */
317 static void simple_send_token(int f, int32 token, struct map_struct *buf, OFF_T offset, int32 n)
318 {
319 if (n > 0) {
320 int32 len = 0;
321 while (len < n) {
322 int32 n1 = MIN(CHUNK_SIZE, n-len);
323 write_int(f, n1);
324 write_buf(f, map_ptr(buf, offset+len, n1), n1);
325 len += n1;
326 }
327 }
328 /* a -2 token means to send data only and no token */
329 if (token != -2)
330 write_int(f, -(token+1));
331 }
332
333 /* Flag bytes in compressed stream are encoded as follows: */
334 #define END_FLAG 0 /* that's all folks */
335 #define TOKEN_LONG 0x20 /* followed by 32-bit token number */
336 #define TOKENRUN_LONG 0x21 /* ditto with 16-bit run count */
337 #define DEFLATED_DATA 0x40 /* + 6-bit high len, then low len byte */
338 #define TOKEN_REL 0x80 /* + 6-bit relative token number */
339 #define TOKENRUN_REL 0xc0 /* ditto with 16-bit run count */
340
341 #define MAX_DATA_COUNT 16383 /* fit 14 bit count into 2 bytes with flags */
342
343 /* zlib.h says that if we want to be able to compress something in a single
344 * call, avail_out must be at least 0.1% larger than avail_in plus 12 bytes.
345 * We'll add in 0.1%+16, just to be safe (and we'll avoid floating point,
346 * to ensure that this is a compile-time value). */
347 #define AVAIL_OUT_SIZE(avail_in_size) ((avail_in_size)*1001/1000+16)
348
349 /* For coding runs of tokens */
350 static int32 last_token = -1;
351 static int32 run_start;
352 static int32 last_run_end;
353
354 /* Deflation state */
355 static z_stream tx_strm;
356
357 /* Output buffer */
358 static char *obuf;
359
360 /* We want obuf to be able to hold both MAX_DATA_COUNT+2 bytes as well as
361 * AVAIL_OUT_SIZE(CHUNK_SIZE) bytes, so make sure that it's large enough. */
362 #if MAX_DATA_COUNT+2 > AVAIL_OUT_SIZE(CHUNK_SIZE)
363 #define OBUF_SIZE (MAX_DATA_COUNT+2)
364 #else
365 #define OBUF_SIZE AVAIL_OUT_SIZE(CHUNK_SIZE)
366 #endif
367
368 /* Send a deflated token */
369 static void
370 send_deflated_token(int f, int32 token, struct map_struct *buf, OFF_T offset, int32 nb, int32 toklen)
371 {
372 static int init_done, flush_pending;
373 int32 n, r;
374
375 if (last_token == -1) {
376 /* initialization */
377 if (!init_done) {
378 tx_strm.next_in = NULL;
379 tx_strm.zalloc = NULL;
380 tx_strm.zfree = NULL;
381 if (deflateInit2(&tx_strm, per_file_default_level,
382 Z_DEFLATED, -15, 8,
383 Z_DEFAULT_STRATEGY) != Z_OK) {
384 rprintf(FERROR, "compression init failed\n");
385 exit_cleanup(RERR_PROTOCOL);
386 }
387 obuf = new_array(char, OBUF_SIZE);
388 init_done = 1;
389 } else
390 deflateReset(&tx_strm);
391 last_run_end = 0;
392 run_start = token;
393 flush_pending = 0;
394 } else if (last_token == -2) {
395 run_start = token;
396 } else if (nb != 0 || token != last_token + 1 || token >= run_start + 65536) {
397 /* output previous run */
398 r = run_start - last_run_end;
399 n = last_token - run_start;
400 if (r >= 0 && r <= 63) {
401 write_byte(f, (n==0? TOKEN_REL: TOKENRUN_REL) + r);
402 } else {
403 write_byte(f, (n==0? TOKEN_LONG: TOKENRUN_LONG));
404 write_int(f, run_start);
405 }
406 if (n != 0) {
407 write_byte(f, n);
408 write_byte(f, n >> 8);
409 }
410 last_run_end = last_token;
411 run_start = token;
412 }
413
414 last_token = token;
415
416 if (nb != 0 || flush_pending) {
417 /* deflate the data starting at offset */
418 int flush = Z_NO_FLUSH;
419 tx_strm.avail_in = 0;
420 tx_strm.avail_out = 0;
421 do {
422 if (tx_strm.avail_in == 0 && nb != 0) {
423 /* give it some more input */
424 n = MIN(nb, CHUNK_SIZE);
425 tx_strm.next_in = (Bytef *)
426 map_ptr(buf, offset, n);
427 tx_strm.avail_in = n;
428 nb -= n;
429 offset += n;
430 }
431 if (tx_strm.avail_out == 0) {
432 tx_strm.next_out = (Bytef *)(obuf + 2);
433 tx_strm.avail_out = MAX_DATA_COUNT;
434 if (flush != Z_NO_FLUSH) {
435 /*
436 * We left the last 4 bytes in the
437 * buffer, in case they are the
438 * last 4. Move them to the front.
439 */
440 memcpy(tx_strm.next_out, obuf+MAX_DATA_COUNT-2, 4);
441 tx_strm.next_out += 4;
442 tx_strm.avail_out -= 4;
443 }
444 }
445 if (nb == 0 && token != -2)
446 flush = Z_SYNC_FLUSH;
447 r = deflate(&tx_strm, flush);
448 if (r != Z_OK) {
449 rprintf(FERROR, "deflate returned %d\n", r);
450 exit_cleanup(RERR_STREAMIO);
451 }
452 if (nb == 0 || tx_strm.avail_out == 0) {
453 n = MAX_DATA_COUNT - tx_strm.avail_out;
454 if (flush != Z_NO_FLUSH) {
455 /*
456 * We have to trim off the last 4
457 * bytes of output when flushing
458 * (they are just 0, 0, ff, ff).
459 */
460 n -= 4;
461 }
462 if (n > 0) {
463 obuf[0] = DEFLATED_DATA + (n >> 8);
464 obuf[1] = n;
465 write_buf(f, obuf, n+2);
466 }
467 }
468 } while (nb != 0 || tx_strm.avail_out == 0);
469 flush_pending = token == -2;
470 }
471
472 if (token == -1) {
473 /* end of file - clean up */
474 write_byte(f, END_FLAG);
475 } else if (token != -2 && do_compression == CPRES_ZLIB) {
476 /* Add the data in the current block to the compressor's
477 * history and hash table. */
478 do {
479 /* Break up long sections in the same way that
480 * see_deflate_token() does. */
481 int32 n1 = toklen > 0xffff ? 0xffff : toklen;
482 toklen -= n1;
483 tx_strm.next_in = (Bytef *)map_ptr(buf, offset, n1);
484 tx_strm.avail_in = n1;
485 if (protocol_version >= 31) /* Newer protocols avoid a data-duplicating bug */
486 offset += n1;
487 /* With our bundled zlib's Z_INSERT_ONLY this produces no
488 * output and consumes the input in one call. A build
489 * against a system zlib lacks Z_INSERT_ONLY and falls back
490 * to Z_SYNC_FLUSH (see top of file), which emits a flush
491 * block we discard -- and for an incompressible token that
492 * block can exceed obuf. Loop, resetting the output buffer,
493 * until all the input is consumed so a large token can't
494 * overflow obuf and abort the transfer (#951). Drain until
495 * avail_out != 0 too: a full output buffer can leave pending
496 * bytes that would otherwise leak into the next real deflate
497 * send and corrupt the stream (same condition as the data loop
498 * above). The discarded output is not sent: the receiver
499 * rebuilds the matching history itself in see_deflate_token(). */
500 do {
501 tx_strm.next_out = (Bytef *) obuf;
502 tx_strm.avail_out = AVAIL_OUT_SIZE(CHUNK_SIZE);
503 r = deflate(&tx_strm, Z_INSERT_ONLY);
504 if (r != Z_OK) {
505 rprintf(FERROR, "deflate on token returned %d (%d bytes left)\n",
506 r, tx_strm.avail_in);
507 exit_cleanup(RERR_STREAMIO);
508 }
509 } while (tx_strm.avail_in != 0 || tx_strm.avail_out == 0);
510 } while (toklen > 0);
511 }
512 }
513
514 /* tells us what the receiver is in the middle of doing */
515 static enum { r_init, r_idle, r_running, r_inflating, r_inflated } recv_state;
516
517 /* for inflating stuff */
518 static z_stream rx_strm;
519 static char *cbuf;
520 static char *dbuf;
521
522 /* for decoding runs of tokens */
523 #define MAX_TOKEN_INDEX ((int32)0x7ffffffe)
524
525 static int32 rx_token;
526 static int32 rx_run;
527
528 static NORETURN void invalid_compressed_token(void)
529 {
530 rprintf(FERROR, "invalid token number in compressed stream\n");
531 exit_cleanup(RERR_PROTOCOL);
532 }
533
534 static int32 recv_compressed_token_num(int f, int32 flag)
535 {
536 if (flag & TOKEN_REL) {
537 int32 incr = flag & 0x3f;
538 if (rx_token > MAX_TOKEN_INDEX - incr)
539 invalid_compressed_token();
540 rx_token += incr;
541 flag >>= 6;
542 } else {
543 rx_token = read_int(f);
544 if (rx_token < 0 || rx_token > MAX_TOKEN_INDEX)
545 invalid_compressed_token();
546 }
547
548 if (flag & 1) {
549 rx_run = read_byte(f);
550 rx_run += read_byte(f) << 8;
551 if (rx_run <= 0 || rx_token > MAX_TOKEN_INDEX - rx_run)
552 invalid_compressed_token();
553 recv_state = r_running;
554 }
555
556 return -1 - rx_token;
557 }
558
559 static int32 recv_compressed_token_run(void)
560 {
561 if (rx_run <= 0 || rx_token >= MAX_TOKEN_INDEX)
562 invalid_compressed_token();
563 ++rx_token;
564 if (--rx_run == 0)
565 recv_state = r_idle;
566 return -1 - rx_token;
567 }
568
569 /* Receive a deflated token and inflate it */
570 static int32 recv_deflated_token(int f, char **data)
571 {
572 static int init_done;
573 static int32 saved_flag;
574 int32 n, flag;
575 int r;
576
577 for (;;) {
578 switch (recv_state) {
579 case r_init:
580 if (!init_done) {
581 rx_strm.next_out = NULL;
582 rx_strm.zalloc = NULL;
583 rx_strm.zfree = NULL;
584 if (inflateInit2(&rx_strm, -15) != Z_OK) {
585 rprintf(FERROR, "inflate init failed\n");
586 exit_cleanup(RERR_PROTOCOL);
587 }
588 cbuf = new_array(char, MAX_DATA_COUNT);
589 dbuf = new_array(char, AVAIL_OUT_SIZE(CHUNK_SIZE));
590 init_done = 1;
591 } else {
592 inflateReset(&rx_strm);
593 }
594 recv_state = r_idle;
595 rx_token = 0;
596 break;
597
598 case r_idle:
599 case r_inflated:
600 if (saved_flag) {
601 flag = saved_flag & 0xff;
602 saved_flag = 0;
603 } else
604 flag = read_byte(f);
605 if ((flag & 0xC0) == DEFLATED_DATA) {
606 n = ((flag & 0x3f) << 8) + read_byte(f);
607 read_buf(f, cbuf, n);
608 rx_strm.next_in = (Bytef *)cbuf;
609 rx_strm.avail_in = n;
610 recv_state = r_inflating;
611 break;
612 }
613 if (recv_state == r_inflated) {
614 /* check previous inflated stuff ended correctly */
615 rx_strm.avail_in = 0;
616 rx_strm.next_out = (Bytef *)dbuf;
617 rx_strm.avail_out = AVAIL_OUT_SIZE(CHUNK_SIZE);
618 r = inflate(&rx_strm, Z_SYNC_FLUSH);
619 n = AVAIL_OUT_SIZE(CHUNK_SIZE) - rx_strm.avail_out;
620 /*
621 * Z_BUF_ERROR just means no progress was
622 * made, i.e. the decompressor didn't have
623 * any pending output for us.
624 */
625 if (r != Z_OK && r != Z_BUF_ERROR) {
626 rprintf(FERROR, "inflate flush returned %d (%d bytes)\n",
627 r, n);
628 exit_cleanup(RERR_STREAMIO);
629 }
630 if (n != 0 && r != Z_BUF_ERROR) {
631 /* have to return some more data and
632 save the flag for later. */
633 saved_flag = flag + 0x10000;
634 *data = dbuf;
635 return n;
636 }
637 /*
638 * At this point the decompressor should
639 * be expecting to see the 0, 0, ff, ff bytes.
640 */
641 if (!inflateSyncPoint(&rx_strm)) {
642 rprintf(FERROR, "decompressor lost sync!\n");
643 exit_cleanup(RERR_STREAMIO);
644 }
645 rx_strm.avail_in = 4;
646 rx_strm.next_in = (Bytef *)cbuf;
647 cbuf[0] = cbuf[1] = 0;
648 cbuf[2] = cbuf[3] = (char)0xff;
649 inflate(&rx_strm, Z_SYNC_FLUSH);
650 recv_state = r_idle;
651 }
652 if (flag == END_FLAG) {
653 /* that's all folks */
654 recv_state = r_init;
655 return 0;
656 }
657
658 /* here we have a token of some kind */
659 return recv_compressed_token_num(f, flag);
660
661 case r_inflating:
662 rx_strm.next_out = (Bytef *)dbuf;
663 rx_strm.avail_out = AVAIL_OUT_SIZE(CHUNK_SIZE);
664 r = inflate(&rx_strm, Z_NO_FLUSH);
665 n = AVAIL_OUT_SIZE(CHUNK_SIZE) - rx_strm.avail_out;
666 if (r != Z_OK) {
667 rprintf(FERROR, "inflate returned %d (%d bytes)\n", r, n);
668 exit_cleanup(RERR_STREAMIO);
669 }
670 if (rx_strm.avail_in == 0)
671 recv_state = r_inflated;
672 if (n != 0) {
673 *data = dbuf;
674 return n;
675 }
676 break;
677
678 case r_running:
679 return recv_compressed_token_run();
680 }
681 }
682 }
683
684 /*
685 * put the data corresponding to a token that we've just returned
686 * from recv_deflated_token into the decompressor's history buffer.
687 */
688 static void see_deflate_token(char *buf, int32 len)
689 {
690 int r;
691 int32 blklen;
692 unsigned char hdr[5];
693
694 rx_strm.avail_in = 0;
695 blklen = 0;
696 hdr[0] = 0;
697 do {
698 if (rx_strm.avail_in == 0 && len != 0) {
699 if (blklen == 0) {
700 /* Give it a fake stored-block header. */
701 rx_strm.next_in = (Bytef *)hdr;
702 rx_strm.avail_in = 5;
703 blklen = len;
704 if (blklen > 0xffff)
705 blklen = 0xffff;
706 hdr[1] = blklen;
707 hdr[2] = blklen >> 8;
708 hdr[3] = ~hdr[1];
709 hdr[4] = ~hdr[2];
710 } else {
711 rx_strm.next_in = (Bytef *)buf;
712 rx_strm.avail_in = blklen;
713 if (protocol_version >= 31) /* Newer protocols avoid a data-duplicating bug */
714 buf += blklen;
715 len -= blklen;
716 blklen = 0;
717 }
718 }
719 rx_strm.next_out = (Bytef *)dbuf;
720 rx_strm.avail_out = AVAIL_OUT_SIZE(CHUNK_SIZE);
721 r = inflate(&rx_strm, Z_SYNC_FLUSH);
722 if (r != Z_OK && r != Z_BUF_ERROR) {
723 rprintf(FERROR, "inflate (token) returned %d\n", r);
724 exit_cleanup(RERR_STREAMIO);
725 }
726 } while (len || rx_strm.avail_out == 0);
727 }
728
729 #ifdef SUPPORT_ZSTD
730
731 static ZSTD_inBuffer zstd_in_buff;
732 static ZSTD_outBuffer zstd_out_buff;
733 static ZSTD_CCtx *zstd_cctx;
734
735 static void send_zstd_token(int f, int32 token, struct map_struct *buf, OFF_T offset, int32 nb)
736 {
737 static int comp_init_done, flush_pending;
738 ZSTD_EndDirective flush = ZSTD_e_continue;
739 int32 n, r;
740
741 /* initialization */
742 if (!comp_init_done) {
743 zstd_cctx = ZSTD_createCCtx();
744 if (!zstd_cctx) {
745 rprintf(FERROR, "compression init failed\n");
746 exit_cleanup(RERR_PROTOCOL);
747 }
748
749 obuf = new_array(char, OBUF_SIZE);
750
751 ZSTD_CCtx_setParameter(zstd_cctx, ZSTD_c_compressionLevel, do_compression_level);
752 ZSTD_CCtx_setParameter(zstd_cctx, ZSTD_c_nbWorkers, do_compression_threads);
753
754 zstd_out_buff.dst = obuf + 2;
755
756 comp_init_done = 1;
757 }
758
759 if (last_token == -1) {
760 last_run_end = 0;
761 run_start = token;
762 flush_pending = 0;
763 } else if (last_token == -2) {
764 run_start = token;
765 } else if (nb != 0 || token != last_token + 1 || token >= run_start + 65536) {
766 /* output previous run */
767 r = run_start - last_run_end;
768 n = last_token - run_start;
769
770 if (r >= 0 && r <= 63) {
771 write_byte(f, (n==0? TOKEN_REL: TOKENRUN_REL) + r);
772 } else {
773 write_byte(f, (n==0? TOKEN_LONG: TOKENRUN_LONG));
774 write_int(f, run_start);
775 }
776 if (n != 0) {
777 write_byte(f, n);
778 write_byte(f, n >> 8);
779 }
780 last_run_end = last_token;
781 run_start = token;
782 }
783
784 last_token = token;
785
786 if (nb || flush_pending) {
787
788 zstd_in_buff.src = map_ptr(buf, offset, nb);
789 zstd_in_buff.size = nb;
790 zstd_in_buff.pos = 0;
791
792 int finished;
793 do {
794 zstd_out_buff.size = MAX_DATA_COUNT;
795 zstd_out_buff.pos = 0;
796
797 /* File ended, flush */
798 if (token != -2)
799 flush = ZSTD_e_flush;
800
801 r = ZSTD_compressStream2(zstd_cctx, &zstd_out_buff, &zstd_in_buff, flush);
802 if (ZSTD_isError(r)) {
803 rprintf(FERROR, "ZSTD_compressStream returned %d\n", r);
804 exit_cleanup(RERR_STREAMIO);
805 }
806
807 /*
808 * Nothing is sent if the buffer isn't full so avoid smaller
809 * transfers. If a file is finished then we flush the internal
810 * state and send a smaller buffer so that the remote side can
811 * finish the file.
812 */
813 finished = (flush == ZSTD_e_flush) ? (r == 0) : (zstd_in_buff.pos == zstd_in_buff.size);
814
815 if (zstd_out_buff.pos != 0) {
816 n = zstd_out_buff.pos;
817
818 obuf[0] = DEFLATED_DATA + (n >> 8);
819 obuf[1] = n;
820 write_buf(f, obuf, n+2);
821 }
822 /*
823 * Loop while the input buffer isn't full consumed or the
824 * internal state isn't fully flushed.
825 */
826 } while (!finished);
827
828 flush_pending = token == -2;
829 }
830
831 if (token == -1) {
832 /* end of file - clean up */
833 write_byte(f, END_FLAG);
834 }
835 }
836
837 static ZSTD_DCtx *zstd_dctx;
838
839 static int32 recv_zstd_token(int f, char **data)
840 {
841 static int decomp_init_done;
842 static int out_buffer_size;
843 int32 n, flag;
844 int r;
845
846 if (!decomp_init_done) {
847 zstd_dctx = ZSTD_createDCtx();
848 if (!zstd_dctx) {
849 rprintf(FERROR, "ZSTD_createDStream failed\n");
850 exit_cleanup(RERR_PROTOCOL);
851 }
852
853 /* Output buffer fits two decompressed blocks */
854 out_buffer_size = ZSTD_DStreamOutSize() * 2;
855 cbuf = new_array(char, MAX_DATA_COUNT);
856 dbuf = new_array(char, out_buffer_size);
857
858 zstd_in_buff.src = cbuf;
859 zstd_out_buff.dst = dbuf;
860
861 decomp_init_done = 1;
862 }
863
864 for (;;) {
865 switch (recv_state) {
866 case r_init:
867 recv_state = r_idle;
868 rx_token = 0;
869 break;
870
871 case r_idle:
872 flag = read_byte(f);
873 if ((flag & 0xC0) == DEFLATED_DATA) {
874 n = ((flag & 0x3f) << 8) + read_byte(f);
875 read_buf(f, cbuf, n);
876
877 zstd_in_buff.size = n;
878 zstd_in_buff.pos = 0;
879
880 recv_state = r_inflating;
881 break;
882 }
883
884 if (flag == END_FLAG) {
885 /* that's all folks */
886 recv_state = r_init;
887 return 0;
888 }
889 /* here we have a token of some kind */
890 return recv_compressed_token_num(f, flag);
891
892 case r_inflated: /* zstd doesn't get into this state */
893 break;
894
895 case r_inflating:
896 zstd_out_buff.size = out_buffer_size;
897 zstd_out_buff.pos = 0;
898
899 r = ZSTD_decompressStream(zstd_dctx, &zstd_out_buff, &zstd_in_buff);
900 n = zstd_out_buff.pos;
901 if (ZSTD_isError(r)) {
902 rprintf(FERROR, "ZSTD decomp returned %d (%d bytes)\n", r, n);
903 exit_cleanup(RERR_STREAMIO);
904 }
905
906 /*
907 * If the input buffer is fully consumed and the output
908 * buffer is not full then next step is to read more
909 * data.
910 */
911 if (zstd_in_buff.size == zstd_in_buff.pos && n < out_buffer_size)
912 recv_state = r_idle;
913
914 if (n != 0) {
915 *data = dbuf;
916 return n;
917 }
918 break;
919
920 case r_running:
921 return recv_compressed_token_run();
922 }
923 }
924 }
925 #endif /* SUPPORT_ZSTD */
926
927 #ifdef SUPPORT_LZ4
928 static void
929 send_compressed_token(int f, int32 token, struct map_struct *buf, OFF_T offset, int32 nb)
930 {
931 static int init_done, flush_pending;
932 int size = MAX(LZ4_compressBound(CHUNK_SIZE), MAX_DATA_COUNT+2);
933 int32 n, r;
934
935 if (last_token == -1) {
936 if (!init_done) {
937 obuf = new_array(char, size);
938 init_done = 1;
939 }
940 last_run_end = 0;
941 run_start = token;
942 flush_pending = 0;
943 } else if (last_token == -2) {
944 run_start = token;
945 } else if (nb != 0 || token != last_token + 1 || token >= run_start + 65536) {
946 /* output previous run */
947 r = run_start - last_run_end;
948 n = last_token - run_start;
949 if (r >= 0 && r <= 63) {
950 write_byte(f, (n==0? TOKEN_REL: TOKENRUN_REL) + r);
951 } else {
952 write_byte(f, (n==0? TOKEN_LONG: TOKENRUN_LONG));
953 write_int(f, run_start);
954 }
955 if (n != 0) {
956 write_byte(f, n);
957 write_byte(f, n >> 8);
958 }
959 last_run_end = last_token;
960 run_start = token;
961 }
962
963 last_token = token;
964
965 if (nb != 0 || flush_pending) {
966 int available_in, available_out = 0;
967 const char *next_in;
968
969 do {
970 char *next_out = obuf + 2;
971
972 if (available_out == 0) {
973 available_in = MIN(nb, MAX_DATA_COUNT);
974 next_in = map_ptr(buf, offset, available_in);
975 } else
976 available_in /= 2;
977
978 available_out = LZ4_compress_default(next_in, next_out, available_in, size - 2);
979 if (!available_out) {
980 rprintf(FERROR, "compress returned %d\n", available_out);
981 exit_cleanup(RERR_STREAMIO);
982 }
983 if (available_out <= MAX_DATA_COUNT) {
984 obuf[0] = DEFLATED_DATA + (available_out >> 8);
985 obuf[1] = available_out;
986
987 write_buf(f, obuf, available_out + 2);
988
989 available_out = 0;
990 nb -= available_in;
991 offset += available_in;
992 }
993 } while (nb != 0);
994 flush_pending = token == -2;
995 }
996 if (token == -1) {
997 /* end of file - clean up */
998 write_byte(f, END_FLAG);
999 }
1000 }
1001
1002 static int32 recv_compressed_token(int f, char **data)
1003 {
1004 static int init_done;
1005 int32 n, flag;
1006 int size = MAX(LZ4_compressBound(CHUNK_SIZE), MAX_DATA_COUNT+2);
1007 static const char *next_in;
1008 static int avail_in;
1009 int avail_out;
1010
1011 for (;;) {
1012 switch (recv_state) {
1013 case r_init:
1014 if (!init_done) {
1015 cbuf = new_array(char, MAX_DATA_COUNT);
1016 dbuf = new_array(char, size);
1017 init_done = 1;
1018 }
1019 recv_state = r_idle;
1020 rx_token = 0;
1021 break;
1022
1023 case r_idle:
1024 flag = read_byte(f);
1025 if ((flag & 0xC0) == DEFLATED_DATA) {
1026 n = ((flag & 0x3f) << 8) + read_byte(f);
1027 read_buf(f, cbuf, n);
1028 next_in = (char *)cbuf;
1029 avail_in = n;
1030 recv_state = r_inflating;
1031 break;
1032 }
1033
1034 if (flag == END_FLAG) {
1035 /* that's all folks */
1036 recv_state = r_init;
1037 return 0;
1038 }
1039
1040 /* here we have a token of some kind */
1041 return recv_compressed_token_num(f, flag);
1042
1043 case r_inflating:
1044 avail_out = LZ4_decompress_safe(next_in, dbuf, avail_in, size);
1045 if (avail_out < 0) {
1046 rprintf(FERROR, "uncompress failed: %d\n", avail_out);
1047 exit_cleanup(RERR_STREAMIO);
1048 }
1049 recv_state = r_idle;
1050 *data = dbuf;
1051 return avail_out;
1052
1053 case r_inflated: /* lz4 doesn't get into this state */
1054 break;
1055
1056 case r_running:
1057 return recv_compressed_token_run();
1058 }
1059 }
1060 }
1061 #endif /* SUPPORT_LZ4 */
1062
1063 /**
1064 * Transmit a verbatim buffer of length @p n followed by a token.
1065 * If token == -1 then we have reached EOF
1066 * If n == 0 then don't send a buffer
1067 */
1068 void send_token(int f, int32 token, struct map_struct *buf, OFF_T offset,
1069 int32 n, int32 toklen)
1070 {
1071 switch (do_compression) {
1072 case CPRES_NONE:
1073 simple_send_token(f, token, buf, offset, n);
1074 break;
1075 case CPRES_ZLIB:
1076 case CPRES_ZLIBX:
1077 send_deflated_token(f, token, buf, offset, n, toklen);
1078 break;
1079 #ifdef SUPPORT_ZSTD
1080 case CPRES_ZSTD:
1081 send_zstd_token(f, token, buf, offset, n);
1082 break;
1083 #endif
1084 #ifdef SUPPORT_LZ4
1085 case CPRES_LZ4:
1086 send_compressed_token(f, token, buf, offset, n);
1087 break;
1088 #endif
1089 default:
1090 NOISY_DEATH("Unknown do_compression value");
1091 }
1092 }
1093
1094 /*
1095 * receive a token or buffer from the other end. If the return value is >0 then
1096 * it is a data buffer of that length, and *data will point at the data.
1097 * if the return value is -i then it represents token i-1
1098 * if the return value is 0 then the end has been reached
1099 */
1100 int32 recv_token(int f, char **data)
1101 {
1102 switch (do_compression) {
1103 case CPRES_NONE:
1104 return simple_recv_token(f,data);
1105 case CPRES_ZLIB:
1106 case CPRES_ZLIBX:
1107 return recv_deflated_token(f, data);
1108 #ifdef SUPPORT_ZSTD
1109 case CPRES_ZSTD:
1110 return recv_zstd_token(f, data);
1111 #endif
1112 #ifdef SUPPORT_LZ4
1113 case CPRES_LZ4:
1114 return recv_compressed_token(f, data);
1115 #endif
1116 default:
1117 NOISY_DEATH("Unknown do_compression value");
1118 }
1119 }
1120
1121 /*
1122 * look at the data corresponding to a token, if necessary
1123 */
1124 void see_token(char *data, int32 toklen)
1125 {
1126 switch (do_compression) {
1127 case CPRES_NONE:
1128 break;
1129 case CPRES_ZLIB:
1130 see_deflate_token(data, toklen);
1131 break;
1132 case CPRES_ZLIBX:
1133 break;
1134 #ifdef SUPPORT_ZSTD
1135 case CPRES_ZSTD:
1136 break;
1137 #endif
1138 #ifdef SUPPORT_LZ4
1139 case CPRES_LZ4:
1140 /*see_uncompressed_token(data, toklen);*/
1141 break;
1142 #endif
1143 default:
1144 NOISY_DEATH("Unknown do_compression value");
1145 }
1146 }