2 * Routines used by the file-transfer code.
4 * Copyright (C) 1996 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2003-2020 Wayne Davison
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.
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.
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.
26 extern int do_compression;
27 extern int protocol_version;
29 extern int do_compression_level;
30 extern char *skip_compress;
33 #define Z_INSERT_ONLY Z_SYNC_FLUSH
36 static int compression_level, per_file_default_level;
39 struct suffix_tree *sibling;
40 struct suffix_tree *child;
41 char letter, word_end;
44 static char *match_list;
45 static struct suffix_tree *suftree;
47 void init_compression_level(void)
49 int min_level, max_level, def_level, off_level;
51 switch (do_compression) {
55 max_level = Z_BEST_COMPRESSION;
56 def_level = 6; /* Z_DEFAULT_COMPRESSION is -1, so set it to the real default */
57 off_level = Z_NO_COMPRESSION;
58 if (do_compression_level == Z_DEFAULT_COMPRESSION)
59 do_compression_level = def_level;
61 default: /* paranoia to prevent missing case values */
62 exit_cleanup(RERR_UNSUPPORTED);
65 if (do_compression_level == off_level) {
66 do_compression = CPRES_NONE;
70 /* We don't bother with any errors or warnings -- just make sure that the values are valid. */
71 if (do_compression_level == CLVL_NOT_SPECIFIED)
72 do_compression_level = def_level;
73 else if (do_compression_level < min_level)
74 do_compression_level = min_level;
75 else if (do_compression_level > max_level)
76 do_compression_level = max_level;
79 static void add_suffix(struct suffix_tree **prior, char ltr, const char *str)
81 struct suffix_tree *node, *newnode;
84 const char *after = strchr(str, ']');
85 /* Treat "[foo" and "[]" as having a literal '['. */
86 if (after && after++ != str+1) {
87 while ((ltr = *str++) != ']')
88 add_suffix(prior, ltr, after);
93 for (node = *prior; node; prior = &node->sibling, node = node->sibling) {
94 if (node->letter == ltr) {
96 add_suffix(&node->child, *str, str+1);
101 if (node->letter > ltr)
104 if (!(newnode = new(struct suffix_tree)))
105 out_of_memory("add_suffix");
106 newnode->sibling = node;
107 newnode->child = NULL;
108 newnode->letter = ltr;
111 add_suffix(&newnode->child, *str, str+1);
112 newnode->word_end = 0;
114 newnode->word_end = 1;
117 static void add_nocompress_suffixes(const char *str)
122 if (!(buf = new_array(char, strlen(f) + 1)))
123 out_of_memory("add_nocompress_suffixes");
137 } while (*++f != '/' && *f);
140 add_suffix(&suftree, *buf, buf+1);
146 static void init_set_compression(void)
152 add_nocompress_suffixes(skip_compress);
154 /* A non-daemon transfer skips the default suffix list if the
155 * user specified --skip-compress. */
156 if (skip_compress && module_id < 0)
159 f = lp_dont_compress(module_id);
161 if (!(match_list = t = new_array(char, strlen(f) + 2)))
162 out_of_memory("set_compression");
164 per_file_default_level = do_compression_level;
178 } while (*++f != ' ' && *f);
181 if (t - start == 1+1 && *start == '*') {
182 /* Optimize a match-string of "*". */
185 per_file_default_level = 0;
189 /* Move *.foo items into the stuffix tree. */
190 if (*start == '*' && start[1] == '.' && start[2]
191 && !strpbrk(start+2, ".?*")) {
192 add_suffix(&suftree, start[2], start+3);
199 /* determine the compression level based on a wildcard filename list */
200 void set_compression(const char *fname)
202 const struct suffix_tree *node;
210 init_set_compression();
212 compression_level = per_file_default_level;
214 if (!*match_list && !suftree)
217 if ((s = strrchr(fname, '/')) != NULL)
220 for (s = match_list; *s; s += strlen(s) + 1) {
221 if (iwildmatch(s, fname)) {
222 compression_level = 0;
227 if (!(node = suftree) || !(s = strrchr(fname, '.'))
228 || s == fname || !(ltr = *++s))
234 while (node->letter != ltr) {
235 if (node->letter > ltr)
237 if (!(node = node->sibling))
240 if ((ltr = *++s) == '\0') {
242 compression_level = 0;
245 if (!(node = node->child))
250 /* non-compressing recv token */
251 static int32 simple_recv_token(int f, char **data)
253 static int32 residue;
258 buf = new_array(char, CHUNK_SIZE);
260 out_of_memory("simple_recv_token");
264 int32 i = read_int(f);
271 n = MIN(CHUNK_SIZE,residue);
277 /* non-compressing send token */
278 static void simple_send_token(int f, int32 token, struct map_struct *buf,
279 OFF_T offset, int32 n)
284 int32 n1 = MIN(CHUNK_SIZE, n-len);
286 write_buf(f, map_ptr(buf, offset+len, n1), n1);
290 /* a -2 token means to send data only and no token */
292 write_int(f, -(token+1));
295 /* Flag bytes in compressed stream are encoded as follows: */
296 #define END_FLAG 0 /* that's all folks */
297 #define TOKEN_LONG 0x20 /* followed by 32-bit token number */
298 #define TOKENRUN_LONG 0x21 /* ditto with 16-bit run count */
299 #define DEFLATED_DATA 0x40 /* + 6-bit high len, then low len byte */
300 #define TOKEN_REL 0x80 /* + 6-bit relative token number */
301 #define TOKENRUN_REL 0xc0 /* ditto with 16-bit run count */
303 #define MAX_DATA_COUNT 16383 /* fit 14 bit count into 2 bytes with flags */
305 /* zlib.h says that if we want to be able to compress something in a single
306 * call, avail_out must be at least 0.1% larger than avail_in plus 12 bytes.
307 * We'll add in 0.1%+16, just to be safe (and we'll avoid floating point,
308 * to ensure that this is a compile-time value). */
309 #define AVAIL_OUT_SIZE(avail_in_size) ((avail_in_size)*1001/1000+16)
311 /* For coding runs of tokens */
312 static int32 last_token = -1;
313 static int32 run_start;
314 static int32 last_run_end;
316 /* Deflation state */
317 static z_stream tx_strm;
322 /* We want obuf to be able to hold both MAX_DATA_COUNT+2 bytes as well as
323 * AVAIL_OUT_SIZE(CHUNK_SIZE) bytes, so make sure that it's large enough. */
324 #if MAX_DATA_COUNT+2 > AVAIL_OUT_SIZE(CHUNK_SIZE)
325 #define OBUF_SIZE (MAX_DATA_COUNT+2)
327 #define OBUF_SIZE AVAIL_OUT_SIZE(CHUNK_SIZE)
330 /* Send a deflated token */
332 send_deflated_token(int f, int32 token, struct map_struct *buf, OFF_T offset,
333 int32 nb, int32 toklen)
335 static int init_done, flush_pending;
338 if (last_token == -1) {
341 tx_strm.next_in = NULL;
342 tx_strm.zalloc = NULL;
343 tx_strm.zfree = NULL;
344 if (deflateInit2(&tx_strm, compression_level,
346 Z_DEFAULT_STRATEGY) != Z_OK) {
347 rprintf(FERROR, "compression init failed\n");
348 exit_cleanup(RERR_PROTOCOL);
350 if ((obuf = new_array(char, OBUF_SIZE)) == NULL)
351 out_of_memory("send_deflated_token");
354 deflateReset(&tx_strm);
358 } else if (last_token == -2) {
360 } else if (nb != 0 || token != last_token + 1
361 || token >= run_start + 65536) {
362 /* output previous run */
363 r = run_start - last_run_end;
364 n = last_token - run_start;
365 if (r >= 0 && r <= 63) {
366 write_byte(f, (n==0? TOKEN_REL: TOKENRUN_REL) + r);
368 write_byte(f, (n==0? TOKEN_LONG: TOKENRUN_LONG));
369 write_int(f, run_start);
373 write_byte(f, n >> 8);
375 last_run_end = last_token;
381 if (nb != 0 || flush_pending) {
382 /* deflate the data starting at offset */
383 int flush = Z_NO_FLUSH;
384 tx_strm.avail_in = 0;
385 tx_strm.avail_out = 0;
387 if (tx_strm.avail_in == 0 && nb != 0) {
388 /* give it some more input */
389 n = MIN(nb, CHUNK_SIZE);
390 tx_strm.next_in = (Bytef *)
391 map_ptr(buf, offset, n);
392 tx_strm.avail_in = n;
396 if (tx_strm.avail_out == 0) {
397 tx_strm.next_out = (Bytef *)(obuf + 2);
398 tx_strm.avail_out = MAX_DATA_COUNT;
399 if (flush != Z_NO_FLUSH) {
401 * We left the last 4 bytes in the
402 * buffer, in case they are the
403 * last 4. Move them to the front.
405 memcpy(tx_strm.next_out,
406 obuf+MAX_DATA_COUNT-2, 4);
407 tx_strm.next_out += 4;
408 tx_strm.avail_out -= 4;
411 if (nb == 0 && token != -2)
412 flush = Z_SYNC_FLUSH;
413 r = deflate(&tx_strm, flush);
415 rprintf(FERROR, "deflate returned %d\n", r);
416 exit_cleanup(RERR_STREAMIO);
418 if (nb == 0 || tx_strm.avail_out == 0) {
419 n = MAX_DATA_COUNT - tx_strm.avail_out;
420 if (flush != Z_NO_FLUSH) {
422 * We have to trim off the last 4
423 * bytes of output when flushing
424 * (they are just 0, 0, ff, ff).
429 obuf[0] = DEFLATED_DATA + (n >> 8);
431 write_buf(f, obuf, n+2);
434 } while (nb != 0 || tx_strm.avail_out == 0);
435 flush_pending = token == -2;
439 /* end of file - clean up */
440 write_byte(f, END_FLAG);
441 } else if (token != -2 && do_compression == CPRES_ZLIB) {
442 /* Add the data in the current block to the compressor's
443 * history and hash table. */
445 /* Break up long sections in the same way that
446 * see_deflate_token() does. */
447 int32 n1 = toklen > 0xffff ? 0xffff : toklen;
449 tx_strm.next_in = (Bytef *)map_ptr(buf, offset, n1);
450 tx_strm.avail_in = n1;
451 if (protocol_version >= 31) /* Newer protocols avoid a data-duplicating bug */
453 tx_strm.next_out = (Bytef *) obuf;
454 tx_strm.avail_out = AVAIL_OUT_SIZE(CHUNK_SIZE);
455 r = deflate(&tx_strm, Z_INSERT_ONLY);
456 if (r != Z_OK || tx_strm.avail_in != 0) {
457 rprintf(FERROR, "deflate on token returned %d (%d bytes left)\n",
458 r, tx_strm.avail_in);
459 exit_cleanup(RERR_STREAMIO);
461 } while (toklen > 0);
465 /* tells us what the receiver is in the middle of doing */
466 static enum { r_init, r_idle, r_running, r_inflating, r_inflated } recv_state;
468 /* for inflating stuff */
469 static z_stream rx_strm;
473 /* for decoding runs of tokens */
474 static int32 rx_token;
477 /* Receive a deflated token and inflate it */
478 static int32 recv_deflated_token(int f, char **data)
480 static int init_done;
481 static int32 saved_flag;
486 switch (recv_state) {
489 rx_strm.next_out = NULL;
490 rx_strm.zalloc = NULL;
491 rx_strm.zfree = NULL;
492 if (inflateInit2(&rx_strm, -15) != Z_OK) {
493 rprintf(FERROR, "inflate init failed\n");
494 exit_cleanup(RERR_PROTOCOL);
496 if (!(cbuf = new_array(char, MAX_DATA_COUNT))
497 || !(dbuf = new_array(char, AVAIL_OUT_SIZE(CHUNK_SIZE))))
498 out_of_memory("recv_deflated_token");
501 inflateReset(&rx_strm);
510 flag = saved_flag & 0xff;
514 if ((flag & 0xC0) == DEFLATED_DATA) {
515 n = ((flag & 0x3f) << 8) + read_byte(f);
516 read_buf(f, cbuf, n);
517 rx_strm.next_in = (Bytef *)cbuf;
518 rx_strm.avail_in = n;
519 recv_state = r_inflating;
522 if (recv_state == r_inflated) {
523 /* check previous inflated stuff ended correctly */
524 rx_strm.avail_in = 0;
525 rx_strm.next_out = (Bytef *)dbuf;
526 rx_strm.avail_out = AVAIL_OUT_SIZE(CHUNK_SIZE);
527 r = inflate(&rx_strm, Z_SYNC_FLUSH);
528 n = AVAIL_OUT_SIZE(CHUNK_SIZE) - rx_strm.avail_out;
530 * Z_BUF_ERROR just means no progress was
531 * made, i.e. the decompressor didn't have
532 * any pending output for us.
534 if (r != Z_OK && r != Z_BUF_ERROR) {
535 rprintf(FERROR, "inflate flush returned %d (%d bytes)\n",
537 exit_cleanup(RERR_STREAMIO);
539 if (n != 0 && r != Z_BUF_ERROR) {
540 /* have to return some more data and
541 save the flag for later. */
542 saved_flag = flag + 0x10000;
547 * At this point the decompressor should
548 * be expecting to see the 0, 0, ff, ff bytes.
550 if (!inflateSyncPoint(&rx_strm)) {
551 rprintf(FERROR, "decompressor lost sync!\n");
552 exit_cleanup(RERR_STREAMIO);
554 rx_strm.avail_in = 4;
555 rx_strm.next_in = (Bytef *)cbuf;
556 cbuf[0] = cbuf[1] = 0;
557 cbuf[2] = cbuf[3] = 0xff;
558 inflate(&rx_strm, Z_SYNC_FLUSH);
561 if (flag == END_FLAG) {
562 /* that's all folks */
567 /* here we have a token of some kind */
568 if (flag & TOKEN_REL) {
569 rx_token += flag & 0x3f;
572 rx_token = read_int(f);
574 rx_run = read_byte(f);
575 rx_run += read_byte(f) << 8;
576 recv_state = r_running;
578 return -1 - rx_token;
581 rx_strm.next_out = (Bytef *)dbuf;
582 rx_strm.avail_out = AVAIL_OUT_SIZE(CHUNK_SIZE);
583 r = inflate(&rx_strm, Z_NO_FLUSH);
584 n = AVAIL_OUT_SIZE(CHUNK_SIZE) - rx_strm.avail_out;
586 rprintf(FERROR, "inflate returned %d (%d bytes)\n", r, n);
587 exit_cleanup(RERR_STREAMIO);
589 if (rx_strm.avail_in == 0)
590 recv_state = r_inflated;
601 return -1 - rx_token;
607 * put the data corresponding to a token that we've just returned
608 * from recv_deflated_token into the decompressor's history buffer.
610 static void see_deflate_token(char *buf, int32 len)
614 unsigned char hdr[5];
616 rx_strm.avail_in = 0;
620 if (rx_strm.avail_in == 0 && len != 0) {
622 /* Give it a fake stored-block header. */
623 rx_strm.next_in = (Bytef *)hdr;
624 rx_strm.avail_in = 5;
629 hdr[2] = blklen >> 8;
633 rx_strm.next_in = (Bytef *)buf;
634 rx_strm.avail_in = blklen;
635 if (protocol_version >= 31) /* Newer protocols avoid a data-duplicating bug */
641 rx_strm.next_out = (Bytef *)dbuf;
642 rx_strm.avail_out = AVAIL_OUT_SIZE(CHUNK_SIZE);
643 r = inflate(&rx_strm, Z_SYNC_FLUSH);
644 if (r != Z_OK && r != Z_BUF_ERROR) {
645 rprintf(FERROR, "inflate (token) returned %d\n", r);
646 exit_cleanup(RERR_STREAMIO);
648 } while (len || rx_strm.avail_out == 0);
652 * Transmit a verbatim buffer of length @p n followed by a token.
653 * If token == -1 then we have reached EOF
654 * If n == 0 then don't send a buffer
656 void send_token(int f, int32 token, struct map_struct *buf, OFF_T offset,
657 int32 n, int32 toklen)
660 simple_send_token(f, token, buf, offset, n);
662 send_deflated_token(f, token, buf, offset, n, toklen);
666 * receive a token or buffer from the other end. If the return value is >0 then
667 * it is a data buffer of that length, and *data will point at the data.
668 * if the return value is -i then it represents token i-1
669 * if the return value is 0 then the end has been reached
671 int32 recv_token(int f, char **data)
676 tok = simple_recv_token(f,data);
677 else /* CPRES_ZLIB & CPRES_ZLIBX */
678 tok = recv_deflated_token(f, data);
683 * look at the data corresponding to a token, if necessary
685 void see_token(char *data, int32 toklen)
687 if (do_compression == CPRES_ZLIB)
688 see_deflate_token(data, toklen);