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