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