xref: /freebsd/usr.sbin/ppp/deflate.c (revision 6e8394b8baa7d5d9153ab90de6824bcd19b3b4e1)
1 /*-
2  * Copyright (c) 1997 Brian Somers <brian@Awfulhak.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  *	$Id: deflate.c,v 1.13 1999/05/08 11:06:25 brian Exp $
27  */
28 
29 #include <sys/types.h>
30 
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <termios.h>
34 #include <zlib.h>
35 
36 #include "defs.h"
37 #include "mbuf.h"
38 #include "log.h"
39 #include "timer.h"
40 #include "lqr.h"
41 #include "hdlc.h"
42 #include "fsm.h"
43 #include "lcp.h"
44 #include "ccp.h"
45 #include "deflate.h"
46 
47 /* Our state */
48 struct deflate_state {
49     u_short seqno;
50     int uncomp_rec;
51     int winsize;
52     z_stream cx;
53 };
54 
55 static char garbage[10];
56 static u_char EMPTY_BLOCK[4] = { 0x00, 0x00, 0xff, 0xff };
57 
58 #define DEFLATE_CHUNK_LEN 1600		/* Allocate mbufs this size */
59 
60 static void
61 DeflateResetOutput(void *v)
62 {
63   struct deflate_state *state = (struct deflate_state *)v;
64 
65   state->seqno = 0;
66   state->uncomp_rec = 0;
67   deflateReset(&state->cx);
68   log_Printf(LogCCP, "Deflate: Output channel reset\n");
69 }
70 
71 static struct mbuf *
72 DeflateOutput(void *v, struct ccp *ccp, struct link *l, int pri, u_short *proto,
73               struct mbuf *mp)
74 {
75   struct deflate_state *state = (struct deflate_state *)v;
76   u_char *wp, *rp;
77   int olen, ilen, len, res, flush;
78   struct mbuf *mo_head, *mo, *mi_head, *mi;
79 
80   ilen = mbuf_Length(mp);
81   log_Printf(LogDEBUG, "DeflateOutput: Proto %02x (%d bytes)\n", *proto, ilen);
82   log_DumpBp(LogDEBUG, "DeflateOutput: Compress packet:", mp);
83 
84   /* Stuff the protocol in front of the input */
85   mi_head = mi = mbuf_Alloc(2, MB_CCPOUT);
86   mi->next = mp;
87   rp = MBUF_CTOP(mi);
88   if (*proto < 0x100) {			/* Compress the protocol */
89     rp[0] = *proto & 0377;
90     mi->cnt = 1;
91   } else {				/* Don't compress the protocol */
92     rp[0] = *proto >> 8;
93     rp[1] = *proto & 0377;
94     mi->cnt = 2;
95   }
96 
97   /* Allocate the initial output mbuf */
98   mo_head = mo = mbuf_Alloc(DEFLATE_CHUNK_LEN, MB_CCPOUT);
99   mo->cnt = 2;
100   wp = MBUF_CTOP(mo);
101   *wp++ = state->seqno >> 8;
102   *wp++ = state->seqno & 0377;
103   log_Printf(LogDEBUG, "DeflateOutput: Seq %d\n", state->seqno);
104   state->seqno++;
105 
106   /* Set up the deflation context */
107   state->cx.next_out = wp;
108   state->cx.avail_out = DEFLATE_CHUNK_LEN - 2;
109   state->cx.next_in = MBUF_CTOP(mi);
110   state->cx.avail_in = mi->cnt;
111   flush = Z_NO_FLUSH;
112 
113   olen = 0;
114   while (1) {
115     if ((res = deflate(&state->cx, flush)) != Z_OK) {
116       if (res == Z_STREAM_END)
117         break;			/* Done */
118       log_Printf(LogWARN, "DeflateOutput: deflate returned %d (%s)\n",
119                 res, state->cx.msg ? state->cx.msg : "");
120       mbuf_Free(mo_head);
121       mbuf_FreeSeg(mi_head);
122       state->seqno--;
123       return mp;		/* Our dictionary's probably dead now :-( */
124     }
125 
126     if (flush == Z_SYNC_FLUSH && state->cx.avail_out != 0)
127       break;
128 
129     if (state->cx.avail_in == 0 && mi->next != NULL) {
130       mi = mi->next;
131       state->cx.next_in = MBUF_CTOP(mi);
132       state->cx.avail_in = mi->cnt;
133       if (mi->next == NULL)
134         flush = Z_SYNC_FLUSH;
135     }
136 
137     if (state->cx.avail_out == 0) {
138       mo->next = mbuf_Alloc(DEFLATE_CHUNK_LEN, MB_CCPOUT);
139       olen += (mo->cnt = DEFLATE_CHUNK_LEN);
140       mo = mo->next;
141       mo->cnt = 0;
142       state->cx.next_out = MBUF_CTOP(mo);
143       state->cx.avail_out = DEFLATE_CHUNK_LEN;
144     }
145   }
146 
147   olen += (mo->cnt = DEFLATE_CHUNK_LEN - state->cx.avail_out);
148   olen -= 4;		/* exclude the trailing EMPTY_BLOCK */
149 
150   /*
151    * If the output packet (including seqno and excluding the EMPTY_BLOCK)
152    * got bigger, send the original.
153    */
154   if (olen >= ilen) {
155     mbuf_Free(mo_head);
156     mbuf_FreeSeg(mi_head);
157     log_Printf(LogDEBUG, "DeflateOutput: %d => %d: Uncompressible (0x%04x)\n",
158               ilen, olen, *proto);
159     ccp->uncompout += ilen;
160     ccp->compout += ilen;	/* We measure this stuff too */
161     return mp;
162   }
163 
164   mbuf_Free(mi_head);
165 
166   /*
167    * Lose the last four bytes of our output.
168    * XXX: We should probably assert that these are the same as the
169    *      contents of EMPTY_BLOCK.
170    */
171   for (mo = mo_head, len = mo->cnt; len < olen; mo = mo->next, len += mo->cnt)
172     ;
173   mo->cnt -= len - olen;
174   if (mo->next != NULL) {
175     mbuf_Free(mo->next);
176     mo->next = NULL;
177   }
178 
179   ccp->uncompout += ilen;
180   ccp->compout += olen;
181 
182   log_Printf(LogDEBUG, "DeflateOutput: %d => %d bytes, proto 0x%04x\n",
183             ilen, olen, *proto);
184 
185   *proto = ccp_Proto(ccp);
186   return mo_head;
187 }
188 
189 static void
190 DeflateResetInput(void *v)
191 {
192   struct deflate_state *state = (struct deflate_state *)v;
193 
194   state->seqno = 0;
195   state->uncomp_rec = 0;
196   inflateReset(&state->cx);
197   log_Printf(LogCCP, "Deflate: Input channel reset\n");
198 }
199 
200 static struct mbuf *
201 DeflateInput(void *v, struct ccp *ccp, u_short *proto, struct mbuf *mi)
202 {
203   struct deflate_state *state = (struct deflate_state *)v;
204   struct mbuf *mo, *mo_head, *mi_head;
205   u_char *wp;
206   int ilen, olen;
207   int seq, flush, res, first;
208   u_char hdr[2];
209 
210   log_DumpBp(LogDEBUG, "DeflateInput: Decompress packet:", mi);
211   mi_head = mi = mbuf_Read(mi, hdr, 2);
212   ilen = 2;
213 
214   /* Check the sequence number. */
215   seq = (hdr[0] << 8) + hdr[1];
216   log_Printf(LogDEBUG, "DeflateInput: Seq %d\n", seq);
217   if (seq != state->seqno) {
218     if (seq <= state->uncomp_rec)
219       /*
220        * So the peer's started at zero again - fine !  If we're wrong,
221        * inflate() will fail.  This is better than getting into a loop
222        * trying to get a ResetReq to a busy sender.
223        */
224       state->seqno = seq;
225     else {
226       log_Printf(LogCCP, "DeflateInput: Seq error: Got %d, expected %d\n",
227                 seq, state->seqno);
228       mbuf_Free(mi_head);
229       ccp_SendResetReq(&ccp->fsm);
230       return NULL;
231     }
232   }
233   state->seqno++;
234   state->uncomp_rec = 0;
235 
236   /* Allocate an output mbuf */
237   mo_head = mo = mbuf_Alloc(DEFLATE_CHUNK_LEN, MB_CCPIN);
238 
239   /* Our proto starts with 0 if it's compressed */
240   wp = MBUF_CTOP(mo);
241   wp[0] = '\0';
242 
243   /*
244    * We set avail_out to 1 initially so we can look at the first
245    * byte of the output and decide whether we have a compressed
246    * proto field.
247    */
248   state->cx.next_in = MBUF_CTOP(mi);
249   state->cx.avail_in = mi->cnt;
250   state->cx.next_out = wp + 1;
251   state->cx.avail_out = 1;
252   ilen += mi->cnt;
253 
254   flush = mi->next ? Z_NO_FLUSH : Z_SYNC_FLUSH;
255   first = 1;
256   olen = 0;
257 
258   while (1) {
259     if ((res = inflate(&state->cx, flush)) != Z_OK) {
260       if (res == Z_STREAM_END)
261         break;			/* Done */
262       log_Printf(LogCCP, "DeflateInput: inflate returned %d (%s)\n",
263                 res, state->cx.msg ? state->cx.msg : "");
264       mbuf_Free(mo_head);
265       mbuf_Free(mi);
266       ccp_SendResetReq(&ccp->fsm);
267       return NULL;
268     }
269 
270     if (flush == Z_SYNC_FLUSH && state->cx.avail_out != 0)
271       break;
272 
273     if (state->cx.avail_in == 0 && mi && (mi = mbuf_FreeSeg(mi)) != NULL) {
274       /* underflow */
275       state->cx.next_in = MBUF_CTOP(mi);
276       ilen += (state->cx.avail_in = mi->cnt);
277       if (mi->next == NULL)
278         flush = Z_SYNC_FLUSH;
279     }
280 
281     if (state->cx.avail_out == 0) {
282       /* overflow */
283       if (first) {
284         if (!(wp[1] & 1)) {
285           /* 2 byte proto, shuffle it back in output */
286           wp[0] = wp[1];
287           state->cx.next_out--;
288           state->cx.avail_out = DEFLATE_CHUNK_LEN-1;
289         } else
290           state->cx.avail_out = DEFLATE_CHUNK_LEN-2;
291         first = 0;
292       } else {
293         olen += (mo->cnt = DEFLATE_CHUNK_LEN);
294         mo->next = mbuf_Alloc(DEFLATE_CHUNK_LEN, MB_CCPIN);
295         mo = mo->next;
296         state->cx.next_out = MBUF_CTOP(mo);
297         state->cx.avail_out = DEFLATE_CHUNK_LEN;
298       }
299     }
300   }
301 
302   if (mi != NULL)
303     mbuf_Free(mi);
304 
305   if (first) {
306     log_Printf(LogCCP, "DeflateInput: Length error\n");
307     mbuf_Free(mo_head);
308     ccp_SendResetReq(&ccp->fsm);
309     return NULL;
310   }
311 
312   olen += (mo->cnt = DEFLATE_CHUNK_LEN - state->cx.avail_out);
313 
314   *proto = ((u_short)wp[0] << 8) | wp[1];
315   mo_head->offset += 2;
316   mo_head->cnt -= 2;
317   olen -= 2;
318 
319   ccp->compin += ilen;
320   ccp->uncompin += olen;
321 
322   log_Printf(LogDEBUG, "DeflateInput: %d => %d bytes, proto 0x%04x\n",
323             ilen, olen, *proto);
324 
325   /*
326    * Simulate an EMPTY_BLOCK so that our dictionary stays in sync.
327    * The peer will have silently removed this!
328    */
329   state->cx.next_out = garbage;
330   state->cx.avail_out = sizeof garbage;
331   state->cx.next_in = EMPTY_BLOCK;
332   state->cx.avail_in = sizeof EMPTY_BLOCK;
333   inflate(&state->cx, Z_SYNC_FLUSH);
334 
335   return mo_head;
336 }
337 
338 static void
339 DeflateDictSetup(void *v, struct ccp *ccp, u_short proto, struct mbuf *mi)
340 {
341   struct deflate_state *state = (struct deflate_state *)v;
342   int res, flush, expect_error;
343   u_char *rp;
344   struct mbuf *mi_head;
345   short len;
346 
347   log_Printf(LogDEBUG, "DeflateDictSetup: Got seq %d\n", state->seqno);
348 
349   /*
350    * Stuff an ``uncompressed data'' block header followed by the
351    * protocol in front of the input
352    */
353   mi_head = mbuf_Alloc(7, MB_CCPOUT);
354   mi_head->next = mi;
355   len = mbuf_Length(mi);
356   mi = mi_head;
357   rp = MBUF_CTOP(mi);
358   if (proto < 0x100) {			/* Compress the protocol */
359     rp[5] = proto & 0377;
360     mi->cnt = 6;
361     len++;
362   } else {				/* Don't compress the protocol */
363     rp[5] = proto >> 8;
364     rp[6] = proto & 0377;
365     mi->cnt = 7;
366     len += 2;
367   }
368   rp[0] = 0x80;				/* BITS: 100xxxxx */
369   rp[1] = len & 0377;			/* The length */
370   rp[2] = len >> 8;
371   rp[3] = (~len) & 0377;		/* One's compliment of the length */
372   rp[4] = (~len) >> 8;
373 
374   state->cx.next_in = rp;
375   state->cx.avail_in = mi->cnt;
376   state->cx.next_out = garbage;
377   state->cx.avail_out = sizeof garbage;
378   flush = Z_NO_FLUSH;
379   expect_error = 0;
380 
381   while (1) {
382     if ((res = inflate(&state->cx, flush)) != Z_OK) {
383       if (res == Z_STREAM_END)
384         break;			/* Done */
385       if (expect_error && res == Z_BUF_ERROR)
386         break;
387       log_Printf(LogCCP, "DeflateDictSetup: inflate returned %d (%s)\n",
388                 res, state->cx.msg ? state->cx.msg : "");
389       log_Printf(LogCCP, "DeflateDictSetup: avail_in %d, avail_out %d\n",
390                 state->cx.avail_in, state->cx.avail_out);
391       ccp_SendResetReq(&ccp->fsm);
392       mbuf_FreeSeg(mi_head);		/* lose our allocated ``head'' buf */
393       return;
394     }
395 
396     if (flush == Z_SYNC_FLUSH && state->cx.avail_out != 0)
397       break;
398 
399     if (state->cx.avail_in == 0 && mi && (mi = mi->next) != NULL) {
400       /* underflow */
401       state->cx.next_in = MBUF_CTOP(mi);
402       state->cx.avail_in = mi->cnt;
403       if (mi->next == NULL)
404         flush = Z_SYNC_FLUSH;
405     }
406 
407     if (state->cx.avail_out == 0) {
408       if (state->cx.avail_in == 0)
409         /*
410          * This seems to be a bug in libz !  If inflate() finished
411          * with 0 avail_in and 0 avail_out *and* this is the end of
412          * our input *and* inflate() *has* actually written all the
413          * output it's going to, it *doesn't* return Z_STREAM_END !
414          * When we subsequently call it with no more input, it gives
415          * us Z_BUF_ERROR :-(  It seems pretty safe to ignore this
416          * error (the dictionary seems to stay in sync).  In the worst
417          * case, we'll drop the next compressed packet and do a
418          * CcpReset() then.
419          */
420         expect_error = 1;
421       /* overflow */
422       state->cx.next_out = garbage;
423       state->cx.avail_out = sizeof garbage;
424     }
425   }
426 
427   ccp->compin += len;
428   ccp->uncompin += len;
429 
430   state->seqno++;
431   state->uncomp_rec++;
432   mbuf_FreeSeg(mi_head);		/* lose our allocated ``head'' buf */
433 }
434 
435 static const char *
436 DeflateDispOpts(struct lcp_opt *o)
437 {
438   static char disp[7];		/* Must be used immediately */
439 
440   sprintf(disp, "win %d", (o->data[0]>>4) + 8);
441   return disp;
442 }
443 
444 static void
445 DeflateInitOptsOutput(struct lcp_opt *o, const struct ccp_config *cfg)
446 {
447   o->len = 4;
448   o->data[0] = ((cfg->deflate.out.winsize - 8) << 4) + 8;
449   o->data[1] = '\0';
450 }
451 
452 static int
453 DeflateSetOptsOutput(struct lcp_opt *o)
454 {
455   if (o->len != 4 || (o->data[0] & 15) != 8 || o->data[1] != '\0')
456     return MODE_REJ;
457 
458   if ((o->data[0] >> 4) + 8 > 15) {
459     o->data[0] = ((15 - 8) << 4) + 8;
460     return MODE_NAK;
461   }
462 
463   return MODE_ACK;
464 }
465 
466 static int
467 DeflateSetOptsInput(struct lcp_opt *o, const struct ccp_config *cfg)
468 {
469   int want;
470 
471   if (o->len != 4 || (o->data[0] & 15) != 8 || o->data[1] != '\0')
472     return MODE_REJ;
473 
474   want = (o->data[0] >> 4) + 8;
475   if (cfg->deflate.in.winsize == 0) {
476     if (want < 8 || want > 15) {
477       o->data[0] = ((15 - 8) << 4) + 8;
478     }
479   } else if (want != cfg->deflate.in.winsize) {
480     o->data[0] = ((cfg->deflate.in.winsize - 8) << 4) + 8;
481     return MODE_NAK;
482   }
483 
484   return MODE_ACK;
485 }
486 
487 static void *
488 DeflateInitInput(struct lcp_opt *o)
489 {
490   struct deflate_state *state;
491 
492   state = (struct deflate_state *)malloc(sizeof(struct deflate_state));
493   if (state != NULL) {
494     state->winsize = (o->data[0] >> 4) + 8;
495     state->cx.zalloc = NULL;
496     state->cx.opaque = NULL;
497     state->cx.zfree = NULL;
498     state->cx.next_out = NULL;
499     if (inflateInit2(&state->cx, -state->winsize) == Z_OK)
500       DeflateResetInput(state);
501     else {
502       free(state);
503       state = NULL;
504     }
505   }
506 
507   return state;
508 }
509 
510 static void *
511 DeflateInitOutput(struct lcp_opt *o)
512 {
513   struct deflate_state *state;
514 
515   state = (struct deflate_state *)malloc(sizeof(struct deflate_state));
516   if (state != NULL) {
517     state->winsize = (o->data[0] >> 4) + 8;
518     state->cx.zalloc = NULL;
519     state->cx.opaque = NULL;
520     state->cx.zfree = NULL;
521     state->cx.next_in = NULL;
522     if (deflateInit2(&state->cx, Z_DEFAULT_COMPRESSION, 8,
523                      -state->winsize, 8, Z_DEFAULT_STRATEGY) == Z_OK)
524       DeflateResetOutput(state);
525     else {
526       free(state);
527       state = NULL;
528     }
529   }
530 
531   return state;
532 }
533 
534 static void
535 DeflateTermInput(void *v)
536 {
537   struct deflate_state *state = (struct deflate_state *)v;
538 
539   inflateEnd(&state->cx);
540   free(state);
541 }
542 
543 static void
544 DeflateTermOutput(void *v)
545 {
546   struct deflate_state *state = (struct deflate_state *)v;
547 
548   deflateEnd(&state->cx);
549   free(state);
550 }
551 
552 const struct ccp_algorithm PppdDeflateAlgorithm = {
553   TY_PPPD_DEFLATE,	/* pppd (wrongly) expects this ``type'' field */
554   CCP_NEG_DEFLATE24,
555   DeflateDispOpts,
556   {
557     DeflateSetOptsInput,
558     DeflateInitInput,
559     DeflateTermInput,
560     DeflateResetInput,
561     DeflateInput,
562     DeflateDictSetup
563   },
564   {
565     DeflateInitOptsOutput,
566     DeflateSetOptsOutput,
567     DeflateInitOutput,
568     DeflateTermOutput,
569     DeflateResetOutput,
570     DeflateOutput
571   },
572 };
573 
574 const struct ccp_algorithm DeflateAlgorithm = {
575   TY_DEFLATE,		/* rfc 1979 */
576   CCP_NEG_DEFLATE,
577   DeflateDispOpts,
578   {
579     DeflateSetOptsInput,
580     DeflateInitInput,
581     DeflateTermInput,
582     DeflateResetInput,
583     DeflateInput,
584     DeflateDictSetup
585   },
586   {
587     DeflateInitOptsOutput,
588     DeflateSetOptsOutput,
589     DeflateInitOutput,
590     DeflateTermOutput,
591     DeflateResetOutput,
592     DeflateOutput
593   },
594 };
595