Optimized set_compression() to remove the per-file strdup(), strlower(),
[rsync/rsync.git] / token.c
1 /*
2    Copyright (C) Andrew Tridgell 1996
3    Copyright (C) Paul Mackerras 1996
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include "rsync.h"
21 #include "zlib/zlib.h"
22
23 extern int do_compression;
24 extern int module_id;
25 extern int def_compress_level;
26
27 static int compression_level, per_file_default_level;
28
29 /* determine the compression level based on a wildcard filename list */
30 void set_compression(char *fname)
31 {
32         static char *match_list;
33         char *s;
34
35         if (!do_compression)
36                 return;
37
38         if (!match_list) {
39                 char *t, *f = lp_dont_compress(module_id);
40                 int len = strlen(f);
41                 if (!(match_list = t = new_array(char, len + 2)))
42                         out_of_memory("set_compression");
43                 while (*f) {
44                         if (*f == ' ') {
45                                 f++;
46                                 continue;
47                         }
48                         do {
49                                 if (isupper(*(unsigned char *)f))
50                                         *t++ = tolower(*(unsigned char *)f);
51                                 else
52                                         *t++ = *f;
53                         } while (*++f != ' ' && *f);
54                         *t++ = '\0';
55                 }
56                 /* Optimize a match-string of "*". */
57                 if (t - match_list == 2 && match_list[0] == '*') {
58                         t = match_list;
59                         per_file_default_level = 0;
60                 } else
61                         per_file_default_level = def_compress_level;
62                 *t++ = '\0';
63         }
64
65         compression_level = per_file_default_level;
66
67         if (!*match_list)
68                 return;
69
70         if ((s = strrchr(fname, '/')) != NULL)
71                 fname = s + 1;
72
73         for (s = match_list; *s; s += strlen(s) + 1) {
74                 if (iwildmatch(s, fname)) {
75                         compression_level = 0;
76                         break;
77                 }
78         }
79 }
80
81 /* non-compressing recv token */
82 static int32 simple_recv_token(int f, char **data)
83 {
84         static int32 residue;
85         static char *buf;
86         int32 n;
87
88         if (!buf) {
89                 buf = new_array(char, CHUNK_SIZE);
90                 if (!buf)
91                         out_of_memory("simple_recv_token");
92         }
93
94         if (residue == 0) {
95                 int32 i = read_int(f);
96                 if (i <= 0)
97                         return i;
98                 residue = i;
99         }
100
101         *data = buf;
102         n = MIN(CHUNK_SIZE,residue);
103         residue -= n;
104         read_buf(f,buf,n);
105         return n;
106 }
107
108
109 /* non-compressing send token */
110 static void simple_send_token(int f, int32 token, struct map_struct *buf,
111                               OFF_T offset, int32 n)
112 {
113         if (n > 0) {
114                 int32 len = 0;
115                 while (len < n) {
116                         int32 n1 = MIN(CHUNK_SIZE, n-len);
117                         write_int(f, n1);
118                         write_buf(f, map_ptr(buf, offset+len, n1), n1);
119                         len += n1;
120                 }
121         }
122         /* a -2 token means to send data only and no token */
123         if (token != -2)
124                 write_int(f, -(token+1));
125 }
126
127
128 /* Flag bytes in compressed stream are encoded as follows: */
129 #define END_FLAG        0       /* that's all folks */
130 #define TOKEN_LONG      0x20    /* followed by 32-bit token number */
131 #define TOKENRUN_LONG   0x21    /* ditto with 16-bit run count */
132 #define DEFLATED_DATA   0x40    /* + 6-bit high len, then low len byte */
133 #define TOKEN_REL       0x80    /* + 6-bit relative token number */
134 #define TOKENRUN_REL    0xc0    /* ditto with 16-bit run count */
135
136 #define MAX_DATA_COUNT  16383   /* fit 14 bit count into 2 bytes with flags */
137
138 /* zlib.h says that if we want to be able to compress something in a single
139  * call, avail_out must be at least 0.1% larger than avail_in plus 12 bytes.
140  * We'll add in 0.1%+16, just to be safe (and we'll avoid floating point,
141  * to ensure that this is a compile-time value). */
142 #define AVAIL_OUT_SIZE(avail_in_size) ((avail_in_size)*1001/1000+16)
143
144 /* For coding runs of tokens */
145 static int32 last_token = -1;
146 static int32 run_start;
147 static int32 last_run_end;
148
149 /* Deflation state */
150 static z_stream tx_strm;
151
152 /* Output buffer */
153 static char *obuf;
154
155 /* We want obuf to be able to hold both MAX_DATA_COUNT+2 bytes as well as
156  * AVAIL_OUT_SIZE(CHUNK_SIZE) bytes, so make sure that it's large enough. */
157 #if MAX_DATA_COUNT+2 > AVAIL_OUT_SIZE(CHUNK_SIZE)
158 #define OBUF_SIZE       (MAX_DATA_COUNT+2)
159 #else
160 #define OBUF_SIZE       AVAIL_OUT_SIZE(CHUNK_SIZE)
161 #endif
162
163 /* Send a deflated token */
164 static void
165 send_deflated_token(int f, int32 token, struct map_struct *buf, OFF_T offset,
166                     int32 nb, int32 toklen)
167 {
168         int32 n, r;
169         static int init_done, flush_pending;
170
171         if (last_token == -1) {
172                 /* initialization */
173                 if (!init_done) {
174                         tx_strm.next_in = NULL;
175                         tx_strm.zalloc = NULL;
176                         tx_strm.zfree = NULL;
177                         if (deflateInit2(&tx_strm, compression_level,
178                                          Z_DEFLATED, -15, 8,
179                                          Z_DEFAULT_STRATEGY) != Z_OK) {
180                                 rprintf(FERROR, "compression init failed\n");
181                                 exit_cleanup(RERR_STREAMIO);
182                         }
183                         if ((obuf = new_array(char, OBUF_SIZE)) == NULL)
184                                 out_of_memory("send_deflated_token");
185                         init_done = 1;
186                 } else
187                         deflateReset(&tx_strm);
188                 last_run_end = 0;
189                 run_start = token;
190                 flush_pending = 0;
191
192         } else if (last_token == -2) {
193                 run_start = token;
194
195         } else if (nb != 0 || token != last_token + 1
196                    || token >= run_start + 65536) {
197                 /* output previous run */
198                 r = run_start - last_run_end;
199                 n = last_token - run_start;
200                 if (r >= 0 && r <= 63) {
201                         write_byte(f, (n==0? TOKEN_REL: TOKENRUN_REL) + r);
202                 } else {
203                         write_byte(f, (n==0? TOKEN_LONG: TOKENRUN_LONG));
204                         write_int(f, run_start);
205                 }
206                 if (n != 0) {
207                         write_byte(f, n);
208                         write_byte(f, n >> 8);
209                 }
210                 last_run_end = last_token;
211                 run_start = token;
212         }
213
214         last_token = token;
215
216         if (nb != 0 || flush_pending) {
217                 /* deflate the data starting at offset */
218                 int flush = Z_NO_FLUSH;
219                 tx_strm.avail_in = 0;
220                 tx_strm.avail_out = 0;
221                 do {
222                         if (tx_strm.avail_in == 0 && nb != 0) {
223                                 /* give it some more input */
224                                 n = MIN(nb, CHUNK_SIZE);
225                                 tx_strm.next_in = (Bytef *)
226                                         map_ptr(buf, offset, n);
227                                 tx_strm.avail_in = n;
228                                 nb -= n;
229                                 offset += n;
230                         }
231                         if (tx_strm.avail_out == 0) {
232                                 tx_strm.next_out = (Bytef *)(obuf + 2);
233                                 tx_strm.avail_out = MAX_DATA_COUNT;
234                                 if (flush != Z_NO_FLUSH) {
235                                         /*
236                                          * We left the last 4 bytes in the
237                                          * buffer, in case they are the
238                                          * last 4.  Move them to the front.
239                                          */
240                                         memcpy(tx_strm.next_out,
241                                                obuf+MAX_DATA_COUNT-2, 4);
242                                         tx_strm.next_out += 4;
243                                         tx_strm.avail_out -= 4;
244                                 }
245                         }
246                         if (nb == 0 && token != -2)
247                                 flush = Z_SYNC_FLUSH;
248                         r = deflate(&tx_strm, flush);
249                         if (r != Z_OK) {
250                                 rprintf(FERROR, "deflate returned %d\n", r);
251                                 exit_cleanup(RERR_STREAMIO);
252                         }
253                         if (nb == 0 || tx_strm.avail_out == 0) {
254                                 n = MAX_DATA_COUNT - tx_strm.avail_out;
255                                 if (flush != Z_NO_FLUSH) {
256                                         /*
257                                          * We have to trim off the last 4
258                                          * bytes of output when flushing
259                                          * (they are just 0, 0, ff, ff).
260                                          */
261                                         n -= 4;
262                                 }
263                                 if (n > 0) {
264                                         obuf[0] = DEFLATED_DATA + (n >> 8);
265                                         obuf[1] = n;
266                                         write_buf(f, obuf, n+2);
267                                 }
268                         }
269                 } while (nb != 0 || tx_strm.avail_out == 0);
270                 flush_pending = token == -2;
271         }
272
273         if (token == -1) {
274                 /* end of file - clean up */
275                 write_byte(f, END_FLAG);
276         } else if (token != -2) {
277                 /* Add the data in the current block to the compressor's
278                  * history and hash table. */
279                 do {
280                         /* Break up long sections in the same way that
281                          * see_deflate_token() does. */
282                         int32 n1 = toklen > 0xffff ? 0xffff : toklen;
283                         toklen -= n1;
284                         tx_strm.next_in = (Bytef *)map_ptr(buf, offset, n1);
285                         tx_strm.avail_in = n1;
286                         tx_strm.next_out = (Bytef *) obuf;
287                         tx_strm.avail_out = AVAIL_OUT_SIZE(CHUNK_SIZE);
288                         r = deflate(&tx_strm, Z_INSERT_ONLY);
289                         if (r != Z_OK || tx_strm.avail_in != 0) {
290                                 rprintf(FERROR, "deflate on token returned %d (%d bytes left)\n",
291                                         r, tx_strm.avail_in);
292                                 exit_cleanup(RERR_STREAMIO);
293                         }
294                 } while (toklen > 0);
295         }
296 }
297
298
299 /* tells us what the receiver is in the middle of doing */
300 static enum { r_init, r_idle, r_running, r_inflating, r_inflated } recv_state;
301
302 /* for inflating stuff */
303 static z_stream rx_strm;
304 static char *cbuf;
305 static char *dbuf;
306
307 /* for decoding runs of tokens */
308 static int32 rx_token;
309 static int32 rx_run;
310
311 /* Receive a deflated token and inflate it */
312 static int32 recv_deflated_token(int f, char **data)
313 {
314         static int init_done;
315         static int32 saved_flag;
316         int32 n, flag;
317         int r;
318
319         for (;;) {
320                 switch (recv_state) {
321                 case r_init:
322                         if (!init_done) {
323                                 rx_strm.next_out = NULL;
324                                 rx_strm.zalloc = NULL;
325                                 rx_strm.zfree = NULL;
326                                 if (inflateInit2(&rx_strm, -15) != Z_OK) {
327                                         rprintf(FERROR, "inflate init failed\n");
328                                         exit_cleanup(RERR_STREAMIO);
329                                 }
330                                 if (!(cbuf = new_array(char, MAX_DATA_COUNT))
331                                     || !(dbuf = new_array(char, AVAIL_OUT_SIZE(CHUNK_SIZE))))
332                                         out_of_memory("recv_deflated_token");
333                                 init_done = 1;
334                         } else {
335                                 inflateReset(&rx_strm);
336                         }
337                         recv_state = r_idle;
338                         rx_token = 0;
339                         break;
340
341                 case r_idle:
342                 case r_inflated:
343                         if (saved_flag) {
344                                 flag = saved_flag & 0xff;
345                                 saved_flag = 0;
346                         } else
347                                 flag = read_byte(f);
348                         if ((flag & 0xC0) == DEFLATED_DATA) {
349                                 n = ((flag & 0x3f) << 8) + read_byte(f);
350                                 read_buf(f, cbuf, n);
351                                 rx_strm.next_in = (Bytef *)cbuf;
352                                 rx_strm.avail_in = n;
353                                 recv_state = r_inflating;
354                                 break;
355                         }
356                         if (recv_state == r_inflated) {
357                                 /* check previous inflated stuff ended correctly */
358                                 rx_strm.avail_in = 0;
359                                 rx_strm.next_out = (Bytef *)dbuf;
360                                 rx_strm.avail_out = AVAIL_OUT_SIZE(CHUNK_SIZE);
361                                 r = inflate(&rx_strm, Z_SYNC_FLUSH);
362                                 n = AVAIL_OUT_SIZE(CHUNK_SIZE) - rx_strm.avail_out;
363                                 /*
364                                  * Z_BUF_ERROR just means no progress was
365                                  * made, i.e. the decompressor didn't have
366                                  * any pending output for us.
367                                  */
368                                 if (r != Z_OK && r != Z_BUF_ERROR) {
369                                         rprintf(FERROR, "inflate flush returned %d (%d bytes)\n",
370                                                 r, n);
371                                         exit_cleanup(RERR_STREAMIO);
372                                 }
373                                 if (n != 0 && r != Z_BUF_ERROR) {
374                                         /* have to return some more data and
375                                            save the flag for later. */
376                                         saved_flag = flag + 0x10000;
377                                         *data = dbuf;
378                                         return n;
379                                 }
380                                 /*
381                                  * At this point the decompressor should
382                                  * be expecting to see the 0, 0, ff, ff bytes.
383                                  */
384                                 if (!inflateSyncPoint(&rx_strm)) {
385                                         rprintf(FERROR, "decompressor lost sync!\n");
386                                         exit_cleanup(RERR_STREAMIO);
387                                 }
388                                 rx_strm.avail_in = 4;
389                                 rx_strm.next_in = (Bytef *)cbuf;
390                                 cbuf[0] = cbuf[1] = 0;
391                                 cbuf[2] = cbuf[3] = 0xff;
392                                 inflate(&rx_strm, Z_SYNC_FLUSH);
393                                 recv_state = r_idle;
394                         }
395                         if (flag == END_FLAG) {
396                                 /* that's all folks */
397                                 recv_state = r_init;
398                                 return 0;
399                         }
400
401                         /* here we have a token of some kind */
402                         if (flag & TOKEN_REL) {
403                                 rx_token += flag & 0x3f;
404                                 flag >>= 6;
405                         } else
406                                 rx_token = read_int(f);
407                         if (flag & 1) {
408                                 rx_run = read_byte(f);
409                                 rx_run += read_byte(f) << 8;
410                                 recv_state = r_running;
411                         }
412                         return -1 - rx_token;
413
414                 case r_inflating:
415                         rx_strm.next_out = (Bytef *)dbuf;
416                         rx_strm.avail_out = AVAIL_OUT_SIZE(CHUNK_SIZE);
417                         r = inflate(&rx_strm, Z_NO_FLUSH);
418                         n = AVAIL_OUT_SIZE(CHUNK_SIZE) - rx_strm.avail_out;
419                         if (r != Z_OK) {
420                                 rprintf(FERROR, "inflate returned %d (%d bytes)\n", r, n);
421                                 exit_cleanup(RERR_STREAMIO);
422                         }
423                         if (rx_strm.avail_in == 0)
424                                 recv_state = r_inflated;
425                         if (n != 0) {
426                                 *data = dbuf;
427                                 return n;
428                         }
429                         break;
430
431                 case r_running:
432                         ++rx_token;
433                         if (--rx_run == 0)
434                                 recv_state = r_idle;
435                         return -1 - rx_token;
436                 }
437         }
438 }
439
440 /*
441  * put the data corresponding to a token that we've just returned
442  * from recv_deflated_token into the decompressor's history buffer.
443  */
444 static void see_deflate_token(char *buf, int32 len)
445 {
446         int r;
447         int32 blklen;
448         unsigned char hdr[5];
449
450         rx_strm.avail_in = 0;
451         blklen = 0;
452         hdr[0] = 0;
453         do {
454                 if (rx_strm.avail_in == 0 && len != 0) {
455                         if (blklen == 0) {
456                                 /* Give it a fake stored-block header. */
457                                 rx_strm.next_in = (Bytef *)hdr;
458                                 rx_strm.avail_in = 5;
459                                 blklen = len;
460                                 if (blklen > 0xffff)
461                                         blklen = 0xffff;
462                                 hdr[1] = blklen;
463                                 hdr[2] = blklen >> 8;
464                                 hdr[3] = ~hdr[1];
465                                 hdr[4] = ~hdr[2];
466                         } else {
467                                 rx_strm.next_in = (Bytef *)buf;
468                                 rx_strm.avail_in = blklen;
469                                 len -= blklen;
470                                 blklen = 0;
471                         }
472                 }
473                 rx_strm.next_out = (Bytef *)dbuf;
474                 rx_strm.avail_out = AVAIL_OUT_SIZE(CHUNK_SIZE);
475                 r = inflate(&rx_strm, Z_SYNC_FLUSH);
476                 if (r != Z_OK) {
477                         rprintf(FERROR, "inflate (token) returned %d\n", r);
478                         exit_cleanup(RERR_STREAMIO);
479                 }
480         } while (len || rx_strm.avail_out == 0);
481 }
482
483 /**
484  * Transmit a verbatim buffer of length @p n followed by a token.
485  * If token == -1 then we have reached EOF
486  * If n == 0 then don't send a buffer
487  */
488 void send_token(int f, int32 token, struct map_struct *buf, OFF_T offset,
489                 int32 n, int32 toklen)
490 {
491         if (!do_compression)
492                 simple_send_token(f, token, buf, offset, n);
493         else
494                 send_deflated_token(f, token, buf, offset, n, toklen);
495 }
496
497
498 /*
499  * receive a token or buffer from the other end. If the reurn value is >0 then
500  * it is a data buffer of that length, and *data will point at the data.
501  * if the return value is -i then it represents token i-1
502  * if the return value is 0 then the end has been reached
503  */
504 int32 recv_token(int f, char **data)
505 {
506         int tok;
507
508         if (!do_compression) {
509                 tok = simple_recv_token(f,data);
510         } else {
511                 tok = recv_deflated_token(f, data);
512         }
513         return tok;
514 }
515
516 /*
517  * look at the data corresponding to a token, if necessary
518  */
519 void see_token(char *data, int32 toklen)
520 {
521         if (do_compression)
522                 see_deflate_token(data, toklen);
523 }