Fixed a problem where we might not have enough room to compress
[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 static int compression_level = Z_DEFAULT_COMPRESSION;
25
26 /* determine the compression level based on a wildcard filename list */
27 void set_compression(char *fname)
28 {
29         extern int module_id;
30         char *dont;
31         char *tok;
32
33         if (!do_compression) return;
34
35         compression_level = Z_DEFAULT_COMPRESSION;
36         dont = lp_dont_compress(module_id);
37
38         if (!dont || !*dont) return;
39
40         if ((dont[0] == '*') && (!dont[1])) {
41                 /* an optimization to skip the rest of this routine */
42                 compression_level = 0;
43                 return;
44         }
45
46         dont = strdup(dont);
47         fname = strdup(fname);
48         if (!dont || !fname) return;
49
50         strlower(dont);
51         strlower(fname);
52
53         for (tok=strtok(dont," ");tok;tok=strtok(NULL," ")) {
54                 if (fnmatch(tok, fname, 0) == 0) {
55                         compression_level = 0;
56                         break;
57                 }
58         }
59         free(dont);
60         free(fname);
61 }
62
63 /* non-compressing recv token */
64 static int simple_recv_token(int f,char **data)
65 {
66         static int residue;
67         static char *buf;
68         int n;
69
70         if (!buf) {
71                 buf = (char *)malloc(CHUNK_SIZE);
72                 if (!buf) out_of_memory("simple_recv_token");
73         }
74
75         if (residue == 0) {
76                 int i = read_int(f);
77                 if (i <= 0) return i;
78                 residue = i;
79         }
80
81         *data = buf;
82         n = MIN(CHUNK_SIZE,residue);
83         residue -= n;
84         read_buf(f,buf,n);
85         return n;
86 }
87
88
89 /* non-compressing send token */
90 static void simple_send_token(int f,int token,
91                               struct map_struct *buf,OFF_T offset,int n)
92 {
93         extern int write_batch; /* dw */
94         int hold_int; /* dw */
95
96         if (n > 0) {
97                 int l = 0;
98                 while (l < n) {
99                         int n1 = MIN(CHUNK_SIZE,n-l);
100                         write_int(f,n1);
101                         write_buf(f,map_ptr(buf,offset+l,n1),n1);
102                         if (write_batch) {
103                             write_batch_delta_file( (char *) &n1, sizeof(int) );
104                             write_batch_delta_file(map_ptr(buf,offset+l,n1),n1);
105                         }
106                         l += n1;
107                 }
108         }
109         /* a -2 token means to send data only and no token */
110         if (token != -2) {
111                 write_int(f,-(token+1));
112                 if (write_batch) {
113                     hold_int = -(token+1);
114                     write_batch_delta_file( (char *) &hold_int, sizeof(int) );
115                 }
116         }
117 }
118
119
120 /* Flag bytes in compressed stream are encoded as follows: */
121 #define END_FLAG        0       /* that's all folks */
122 #define TOKEN_LONG      0x20    /* followed by 32-bit token number */
123 #define TOKENRUN_LONG   0x21    /* ditto with 16-bit run count */
124 #define DEFLATED_DATA   0x40    /* + 6-bit high len, then low len byte */
125 #define TOKEN_REL       0x80    /* + 6-bit relative token number */
126 #define TOKENRUN_REL    0xc0    /* ditto with 16-bit run count */
127
128 #define MAX_DATA_COUNT  16383   /* fit 14 bit count into 2 bytes with flags */
129
130 /* For coding runs of tokens */
131 static int last_token = -1;
132 static int run_start;
133 static int last_run_end;
134
135 /* Deflation state */
136 static z_stream tx_strm;
137
138 /* Output buffer */
139 static char *obuf;
140 static int obuf_size;
141
142 /* Send a deflated token */
143 static void
144 send_deflated_token(int f, int token,
145                     struct map_struct *buf, OFF_T offset, int nb, int toklen)
146 {
147         int n, r;
148         static int init_done, flush_pending;
149         extern int write_batch;  /* dw */
150         char temp_byte;   /* dw */
151
152         if (last_token == -1) {
153                 /* initialization */
154                 if (!init_done) {
155                         tx_strm.next_in = NULL;
156                         tx_strm.zalloc = NULL;
157                         tx_strm.zfree = NULL;
158                         if (deflateInit2(&tx_strm, compression_level,
159                                          Z_DEFLATED, -15, 8,
160                                          Z_DEFAULT_STRATEGY) != Z_OK) {
161                                 rprintf(FERROR, "compression init failed\n");
162                                 exit_cleanup(RERR_STREAMIO);
163                         }
164 #if MAX_DATA_COUNT+2 > CHUNK_SIZE+128 /* this shouldn't ever happen... */
165                         obuf_size = MAX_DATA_COUNT+2;
166 #else
167                         obuf_size = CHUNK_SIZE+128;
168 #endif
169                         if ((obuf = malloc(obuf_size)) == NULL)
170                                 out_of_memory("send_deflated_token");
171                         init_done = 1;
172                 } else
173                         deflateReset(&tx_strm);
174                 last_run_end = 0;
175                 run_start = token;
176                 flush_pending = 0;
177
178         } else if (last_token == -2) {
179                 run_start = token;
180
181         } else if (nb != 0 || token != last_token + 1
182                    || token >= run_start + 65536) {
183                 /* output previous run */
184                 r = run_start - last_run_end;
185                 n = last_token - run_start;
186                 if (r >= 0 && r <= 63) {
187                         write_byte(f, (n==0? TOKEN_REL: TOKENRUN_REL) + r);
188                         if (write_batch) { /* dw */
189                             temp_byte = (char)( (n==0? TOKEN_REL: TOKENRUN_REL) + r);
190                             write_batch_delta_file(&temp_byte,sizeof(char));
191                         }
192                 } else {
193                         write_byte(f, (n==0? TOKEN_LONG: TOKENRUN_LONG));
194                         write_int(f, run_start);
195                         if (write_batch) { /* dw */
196                             temp_byte = (char)(n==0? TOKEN_LONG: TOKENRUN_LONG);
197                             write_batch_delta_file(&temp_byte,sizeof(temp_byte));
198                             write_batch_delta_file((char *)&run_start,sizeof(run_start));
199                         }
200                 }
201                 if (n != 0) {
202                         write_byte(f, n);
203                         write_byte(f, n >> 8);
204                         if (write_batch) { /* dw */
205                             write_batch_delta_file((char *)&n,sizeof(char));
206                             temp_byte = (char) n >> 8;
207                             write_batch_delta_file(&temp_byte,sizeof(temp_byte));
208                         }
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                                         if (write_batch) /* dw */
268                                             write_batch_delta_file(obuf,n+2);
269                                 }
270                         }
271                 } while (nb != 0 || tx_strm.avail_out == 0);
272                 flush_pending = token == -2;
273         }
274
275         if (token == -1) {
276                 /* end of file - clean up */
277                 write_byte(f, END_FLAG);
278                 if (write_batch) { /* dw */
279                     temp_byte = END_FLAG;
280                     write_batch_delta_file((char *)&temp_byte,sizeof(temp_byte));
281                 }
282
283         } else if (token != -2) {
284                 /* add the data in the current block to the compressor's
285                    history and hash table */
286                 tx_strm.next_in = (Bytef *) map_ptr(buf, offset, toklen);
287                 tx_strm.avail_in = toklen;
288                 tx_strm.next_out = (Bytef *) obuf;
289                 tx_strm.avail_out = obuf_size;
290                 r = deflate(&tx_strm, Z_INSERT_ONLY);
291                 if (r != Z_OK || tx_strm.avail_in != 0) {
292                         rprintf(FERROR, "deflate on token returned %d (%d bytes left)\n",
293                                 r, tx_strm.avail_in);
294                         exit_cleanup(RERR_STREAMIO);
295                 }
296         }
297 }
298
299
300 /* tells us what the receiver is in the middle of doing */
301 static enum { r_init, r_idle, r_running, r_inflating, r_inflated } recv_state;
302
303 /* for inflating stuff */
304 static z_stream rx_strm;
305 static char *cbuf;
306 static char *dbuf;
307
308 /* for decoding runs of tokens */
309 static int rx_token;
310 static int rx_run;
311
312 /* Receive a deflated token and inflate it */
313 static int
314 recv_deflated_token(int f, char **data)
315 {
316         int n, r, flag;
317         static int init_done;
318         static int saved_flag;
319
320         for (;;) {
321                 switch (recv_state) {
322                 case r_init:
323                         if (!init_done) {
324                                 rx_strm.next_out = NULL;
325                                 rx_strm.zalloc = NULL;
326                                 rx_strm.zfree = NULL;
327                                 if (inflateInit2(&rx_strm, -15) != Z_OK) {
328                                         rprintf(FERROR, "inflate init failed\n");
329                                         exit_cleanup(RERR_STREAMIO);
330                                 }
331                                 if ((cbuf = malloc(MAX_DATA_COUNT)) == NULL
332                                     || (dbuf = malloc(CHUNK_SIZE)) == NULL)
333                                         out_of_memory("recv_deflated_token");
334                                 init_done = 1;
335                         } else {
336                                 inflateReset(&rx_strm);
337                         }
338                         recv_state = r_idle;
339                         rx_token = 0;
340                         break;
341
342                 case r_idle:
343                 case r_inflated:
344                         if (saved_flag) {
345                                 flag = saved_flag & 0xff;
346                                 saved_flag = 0;
347                         } else
348                                 flag = read_byte(f);
349                         if ((flag & 0xC0) == DEFLATED_DATA) {
350                                 n = ((flag & 0x3f) << 8) + read_byte(f);
351                                 read_buf(f, cbuf, n);
352                                 rx_strm.next_in = (Bytef *)cbuf;
353                                 rx_strm.avail_in = n;
354                                 recv_state = r_inflating;
355                                 break;
356                         }
357                         if (recv_state == r_inflated) {
358                                 /* check previous inflated stuff ended correctly */
359                                 rx_strm.avail_in = 0;
360                                 rx_strm.next_out = (Bytef *)dbuf;
361                                 rx_strm.avail_out = CHUNK_SIZE;
362                                 r = inflate(&rx_strm, Z_SYNC_FLUSH);
363                                 n = CHUNK_SIZE - rx_strm.avail_out;
364                                 /*
365                                  * Z_BUF_ERROR just means no progress was
366                                  * made, i.e. the decompressor didn't have
367                                  * any pending output for us.
368                                  */
369                                 if (r != Z_OK && r != Z_BUF_ERROR) {
370                                         rprintf(FERROR, "inflate flush returned %d (%d bytes)\n",
371                                                 r, n);
372                                         exit_cleanup(RERR_STREAMIO);
373                                 }
374                                 if (n != 0 && r != Z_BUF_ERROR) {
375                                         /* have to return some more data and
376                                            save the flag for later. */
377                                         saved_flag = flag + 0x10000;
378                                         *data = dbuf;
379                                         return n;
380                                 }
381                                 /*
382                                  * At this point the decompressor should
383                                  * be expecting to see the 0, 0, ff, ff bytes.
384                                  */
385                                 if (!inflateSyncPoint(&rx_strm)) {
386                                         rprintf(FERROR, "decompressor lost sync!\n");
387                                         exit_cleanup(RERR_STREAMIO);
388                                 }
389                                 rx_strm.avail_in = 4;
390                                 rx_strm.next_in = (Bytef *)cbuf;
391                                 cbuf[0] = cbuf[1] = 0;
392                                 cbuf[2] = cbuf[3] = 0xff;
393                                 inflate(&rx_strm, Z_SYNC_FLUSH);
394                                 recv_state = r_idle;
395                         }
396                         if (flag == END_FLAG) {
397                                 /* that's all folks */
398                                 recv_state = r_init;
399                                 return 0;
400                         }
401
402                         /* here we have a token of some kind */
403                         if (flag & TOKEN_REL) {
404                                 rx_token += flag & 0x3f;
405                                 flag >>= 6;
406                         } else
407                                 rx_token = read_int(f);
408                         if (flag & 1) {
409                                 rx_run = read_byte(f);
410                                 rx_run += read_byte(f) << 8;
411                                 recv_state = r_running;
412                         }
413                         return -1 - rx_token;
414
415                 case r_inflating:
416                         rx_strm.next_out = (Bytef *)dbuf;
417                         rx_strm.avail_out = CHUNK_SIZE;
418                         r = inflate(&rx_strm, Z_NO_FLUSH);
419                         n = CHUNK_SIZE - rx_strm.avail_out;
420                         if (r != Z_OK) {
421                                 rprintf(FERROR, "inflate returned %d (%d bytes)\n", r, n);
422                                 exit_cleanup(RERR_STREAMIO);
423                         }
424                         if (rx_strm.avail_in == 0)
425                                 recv_state = r_inflated;
426                         if (n != 0) {
427                                 *data = dbuf;
428                                 return n;
429                         }
430                         break;
431
432                 case r_running:
433                         ++rx_token;
434                         if (--rx_run == 0)
435                                 recv_state = r_idle;
436                         return -1 - rx_token;
437                 }
438         }
439 }
440
441 /*
442  * put the data corresponding to a token that we've just returned
443  * from recv_deflated_token into the decompressor's history buffer.
444  */
445 static void see_deflate_token(char *buf, int len)
446 {
447         int r, 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 = 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,int token,struct map_struct *buf,OFF_T offset,
489                 int n,int 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 /*
500  * receive a token or buffer from the other end. If the reurn value is >0 then
501  * it is a data buffer of that length, and *data will point at the data.
502  * if the return value is -i then it represents token i-1
503  * if the return value is 0 then the end has been reached
504  */
505 int recv_token(int f,char **data)
506 {
507         int tok;
508
509         if (!do_compression) {
510                 tok = simple_recv_token(f,data);
511         } else {
512                 tok = recv_deflated_token(f, data);
513         }
514         return tok;
515 }
516
517 /*
518  * look at the data corresponding to a token, if necessary
519  */
520 void see_token(char *data, int toklen)
521 {
522         if (do_compression)
523                 see_deflate_token(data, toklen);
524 }