]> granicus.if.org Git - apache/blob - modules/filters/mod_deflate.c
Housekeeping: keep track of size even in the edge-case where validation
[apache] / modules / filters / mod_deflate.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * mod_deflate.c: Perform deflate content-encoding on the fly
19  *
20  * Written by Ian Holsman, Justin Erenkrantz, and Nick Kew
21  */
22
23 /*
24  * Portions of this software are based upon zlib code by Jean-loup Gailly
25  * (zlib functions gz_open and gzwrite, check_header)
26  */
27
28 /* zlib flags */
29 #define ASCII_FLAG   0x01 /* bit 0 set: file probably ascii text */
30 #define HEAD_CRC     0x02 /* bit 1 set: header CRC present */
31 #define EXTRA_FIELD  0x04 /* bit 2 set: extra field present */
32 #define ORIG_NAME    0x08 /* bit 3 set: original file name present */
33 #define COMMENT      0x10 /* bit 4 set: file comment present */
34 #define RESERVED     0xE0 /* bits 5..7: reserved */
35
36
37 #include "httpd.h"
38 #include "http_config.h"
39 #include "http_log.h"
40 #include "apr_strings.h"
41 #include "apr_general.h"
42 #include "util_filter.h"
43 #include "apr_buckets.h"
44 #include "http_request.h"
45 #define APR_WANT_STRFUNC
46 #include "apr_want.h"
47
48 #include "zlib.h"
49
50 static const char deflateFilterName[] = "DEFLATE";
51 module AP_MODULE_DECLARE_DATA deflate_module;
52
53 typedef struct deflate_filter_config_t
54 {
55     int windowSize;
56     int memlevel;
57     int compressionlevel;
58     apr_size_t bufferSize;
59     char *note_ratio_name;
60     char *note_input_name;
61     char *note_output_name;
62 } deflate_filter_config;
63
64 /* RFC 1952 Section 2.3 defines the gzip header:
65  *
66  * +---+---+---+---+---+---+---+---+---+---+
67  * |ID1|ID2|CM |FLG|     MTIME     |XFL|OS |
68  * +---+---+---+---+---+---+---+---+---+---+
69  */
70 static const char gzip_header[10] =
71 { '\037', '\213', Z_DEFLATED, 0,
72   0, 0, 0, 0, /* mtime */
73   0, 0x03 /* Unix OS_CODE */
74 };
75
76 /* magic header */
77 static const char deflate_magic[2] = { '\037', '\213' };
78
79 /* windowsize is negative to suppress Zlib header */
80 #define DEFAULT_COMPRESSION Z_DEFAULT_COMPRESSION
81 #define DEFAULT_WINDOWSIZE -15
82 #define DEFAULT_MEMLEVEL 9
83 #define DEFAULT_BUFFERSIZE 8096
84
85 /* Outputs a long in LSB order to the given file
86  * only the bottom 4 bits are required for the deflate file format.
87  */
88 static void putLong(unsigned char *string, unsigned long x)
89 {
90     string[0] = (unsigned char)(x & 0xff);
91     string[1] = (unsigned char)((x & 0xff00) >> 8);
92     string[2] = (unsigned char)((x & 0xff0000) >> 16);
93     string[3] = (unsigned char)((x & 0xff000000) >> 24);
94 }
95
96 /* Inputs a string and returns a long.
97  */
98 static unsigned long getLong(unsigned char *string)
99 {
100     return ((unsigned long)string[0])
101           | (((unsigned long)string[1]) << 8)
102           | (((unsigned long)string[2]) << 16)
103           | (((unsigned long)string[3]) << 24);
104 }
105
106 static void *create_deflate_server_config(apr_pool_t *p, server_rec *s)
107 {
108     deflate_filter_config *c = apr_pcalloc(p, sizeof *c);
109
110     c->memlevel   = DEFAULT_MEMLEVEL;
111     c->windowSize = DEFAULT_WINDOWSIZE;
112     c->bufferSize = DEFAULT_BUFFERSIZE;
113     c->compressionlevel = DEFAULT_COMPRESSION;
114
115     return c;
116 }
117
118 static const char *deflate_set_window_size(cmd_parms *cmd, void *dummy,
119                                            const char *arg)
120 {
121     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
122                                                     &deflate_module);
123     int i;
124
125     i = atoi(arg);
126
127     if (i < 1 || i > 15)
128         return "DeflateWindowSize must be between 1 and 15";
129
130     c->windowSize = i * -1;
131
132     return NULL;
133 }
134
135 static const char *deflate_set_buffer_size(cmd_parms *cmd, void *dummy,
136                                            const char *arg)
137 {
138     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
139                                                     &deflate_module);
140     int n = atoi(arg);
141
142     if (n <= 0) {
143         return "DeflateBufferSize should be positive";
144     }
145
146     c->bufferSize = (apr_size_t)n;
147
148     return NULL;
149 }
150 static const char *deflate_set_note(cmd_parms *cmd, void *dummy,
151                                     const char *arg1, const char *arg2)
152 {
153     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
154                                                     &deflate_module);
155
156     if (arg2 == NULL) {
157         c->note_ratio_name = apr_pstrdup(cmd->pool, arg1);
158     }
159     else if (!strcasecmp(arg1, "ratio")) {
160         c->note_ratio_name = apr_pstrdup(cmd->pool, arg2);
161     }
162     else if (!strcasecmp(arg1, "input")) {
163         c->note_input_name = apr_pstrdup(cmd->pool, arg2);
164     }
165     else if (!strcasecmp(arg1, "output")) {
166         c->note_output_name = apr_pstrdup(cmd->pool, arg2);
167     }
168     else {
169         return apr_psprintf(cmd->pool, "Unknown note type %s", arg1);
170     }
171
172     return NULL;
173 }
174
175 static const char *deflate_set_memlevel(cmd_parms *cmd, void *dummy,
176                                         const char *arg)
177 {
178     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
179                                                     &deflate_module);
180     int i;
181
182     i = atoi(arg);
183
184     if (i < 1 || i > 9)
185         return "DeflateMemLevel must be between 1 and 9";
186
187     c->memlevel = i;
188
189     return NULL;
190 }
191
192 static const char *deflate_set_compressionlevel(cmd_parms *cmd, void *dummy,
193                                         const char *arg)
194 {
195     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
196                                                     &deflate_module);
197     int i;
198
199     i = atoi(arg);
200
201     if (i < 1 || i > 9)
202         return "Compression Level must be between 1 and 9";
203
204     c->compressionlevel = i;
205
206     return NULL;
207 }
208
209 typedef struct deflate_ctx_t
210 {
211     z_stream stream;
212     unsigned char *buffer;
213     unsigned long crc;
214     apr_bucket_brigade *bb, *proc_bb;
215     int (*libz_end_func)(z_streamp);
216     unsigned char *validation_buffer;
217     apr_size_t validation_buffer_length;
218 } deflate_ctx;
219
220 /* Number of validation bytes (CRC and length) after the compressed data */
221 #define VALIDATION_SIZE 8
222 /* Do not update ctx->crc, see comment in flush_libz_buffer */
223 #define NO_UPDATE_CRC 0
224 /* Do update ctx->crc, see comment in flush_libz_buffer */
225 #define UPDATE_CRC 1
226
227 static int flush_libz_buffer(deflate_ctx *ctx, deflate_filter_config *c,
228                              struct apr_bucket_alloc_t *bucket_alloc,
229                              int (*libz_func)(z_streamp, int), int flush,
230                              int crc)
231 {
232     int zRC = Z_OK;
233     int done = 0;
234     unsigned int deflate_len;
235     apr_bucket *b;
236
237     for (;;) {
238          deflate_len = c->bufferSize - ctx->stream.avail_out;
239
240          if (deflate_len != 0) {
241              /*
242               * Do we need to update ctx->crc? Usually this is the case for
243               * inflate action where we need to do a crc on the output, whereas
244               * in the deflate case we need to do a crc on the input
245               */
246              if (crc) {
247                  ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer,
248                                   deflate_len);
249              }
250              b = apr_bucket_heap_create((char *)ctx->buffer,
251                                         deflate_len, NULL,
252                                         bucket_alloc);
253              APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
254              ctx->stream.next_out = ctx->buffer;
255              ctx->stream.avail_out = c->bufferSize;
256          }
257
258          if (done)
259              break;
260
261          zRC = libz_func(&ctx->stream, flush);
262
263          /*
264           * We can ignore Z_BUF_ERROR because:
265           * When we call libz_func we can assume that
266           *
267           * - avail_in is zero (due to the surrounding code that calls
268           *   flush_libz_buffer)
269           * - avail_out is non zero due to our actions some lines above
270           *
271           * So the only reason for Z_BUF_ERROR is that the internal libz
272           * buffers are now empty and thus we called libz_func one time
273           * too often. This does not hurt. It simply says that we are done.
274           */
275          if (zRC == Z_BUF_ERROR) {
276              zRC = Z_OK;
277              break;
278          }
279
280          done = (ctx->stream.avail_out != 0 || zRC == Z_STREAM_END);
281
282          if (zRC != Z_OK && zRC != Z_STREAM_END)
283              break;
284     }
285     return zRC;
286 }
287
288 static apr_status_t deflate_ctx_cleanup(void *data)
289 {
290     deflate_ctx *ctx = (deflate_ctx *)data;
291
292     if (ctx)
293         ctx->libz_end_func(&ctx->stream);
294     return APR_SUCCESS;
295 }
296
297 static apr_status_t deflate_out_filter(ap_filter_t *f,
298                                        apr_bucket_brigade *bb)
299 {
300     apr_bucket *e;
301     request_rec *r = f->r;
302     deflate_ctx *ctx = f->ctx;
303     int zRC;
304     deflate_filter_config *c;
305
306     /* Do nothing if asked to filter nothing. */
307     if (APR_BRIGADE_EMPTY(bb)) {
308         return ap_pass_brigade(f->next, bb);
309     }
310
311     c = ap_get_module_config(r->server->module_config,
312                              &deflate_module);
313
314     /* If we don't have a context, we need to ensure that it is okay to send
315      * the deflated content.  If we have a context, that means we've done
316      * this before and we liked it.
317      * This could be not so nice if we always fail.  But, if we succeed,
318      * we're in better shape.
319      */
320     if (!ctx) {
321         char *token;
322         const char *encoding;
323
324         /* only work on main request/no subrequests */
325         if (r->main != NULL) {
326             ap_remove_output_filter(f);
327             return ap_pass_brigade(f->next, bb);
328         }
329
330         /* some browsers might have problems, so set no-gzip
331          * (with browsermatch) for them
332          */
333         if (apr_table_get(r->subprocess_env, "no-gzip")) {
334             ap_remove_output_filter(f);
335             return ap_pass_brigade(f->next, bb);
336         }
337
338         /* Some browsers might have problems with content types
339          * other than text/html, so set gzip-only-text/html
340          * (with browsermatch) for them
341          */
342         if (r->content_type == NULL
343              || strncmp(r->content_type, "text/html", 9)) {
344             const char *env_value = apr_table_get(r->subprocess_env,
345                                                   "gzip-only-text/html");
346             if ( env_value && (strcmp(env_value,"1") == 0) ) {
347                 ap_remove_output_filter(f);
348                 return ap_pass_brigade(f->next, bb);
349             }
350         }
351
352         /* Let's see what our current Content-Encoding is.
353          * If it's already encoded, don't compress again.
354          * (We could, but let's not.)
355          */
356         encoding = apr_table_get(r->headers_out, "Content-Encoding");
357         if (encoding) {
358             const char *err_enc;
359
360             err_enc = apr_table_get(r->err_headers_out, "Content-Encoding");
361             if (err_enc) {
362                 encoding = apr_pstrcat(r->pool, encoding, ",", err_enc, NULL);
363             }
364         }
365         else {
366             encoding = apr_table_get(r->err_headers_out, "Content-Encoding");
367         }
368
369         if (r->content_encoding) {
370             encoding = encoding ? apr_pstrcat(r->pool, encoding, ",",
371                                               r->content_encoding, NULL)
372                                 : r->content_encoding;
373         }
374
375         if (encoding) {
376             const char *tmp = encoding;
377
378             token = ap_get_token(r->pool, &tmp, 0);
379             while (token && *token) {
380                 /* stolen from mod_negotiation: */
381                 if (strcmp(token, "identity") && strcmp(token, "7bit") &&
382                     strcmp(token, "8bit") && strcmp(token, "binary")) {
383
384                     ap_remove_output_filter(f);
385                     return ap_pass_brigade(f->next, bb);
386                 }
387
388                 /* Otherwise, skip token */
389                 if (*tmp) {
390                     ++tmp;
391                 }
392                 token = (*tmp) ? ap_get_token(r->pool, &tmp, 0) : NULL;
393             }
394         }
395
396         /* Even if we don't accept this request based on it not having
397          * the Accept-Encoding, we need to note that we were looking
398          * for this header and downstream proxies should be aware of that.
399          */
400         apr_table_mergen(r->headers_out, "Vary", "Accept-Encoding");
401
402         /* force-gzip will just force it out regardless if the browser
403          * can actually do anything with it.
404          */
405         if (!apr_table_get(r->subprocess_env, "force-gzip")) {
406             const char *accepts;
407             /* if they don't have the line, then they can't play */
408             accepts = apr_table_get(r->headers_in, "Accept-Encoding");
409             if (accepts == NULL) {
410                 ap_remove_output_filter(f);
411                 return ap_pass_brigade(f->next, bb);
412             }
413
414             token = ap_get_token(r->pool, &accepts, 0);
415             while (token && token[0] && strcasecmp(token, "gzip")) {
416                 /* skip parameters, XXX: ;q=foo evaluation? */
417                 while (*accepts == ';') {
418                     ++accepts;
419                     token = ap_get_token(r->pool, &accepts, 1);
420                 }
421
422                 /* retrieve next token */
423                 if (*accepts == ',') {
424                     ++accepts;
425                 }
426                 token = (*accepts) ? ap_get_token(r->pool, &accepts, 0) : NULL;
427             }
428
429             /* No acceptable token found. */
430             if (token == NULL || token[0] == '\0') {
431                 ap_remove_output_filter(f);
432                 return ap_pass_brigade(f->next, bb);
433             }
434         }
435
436         /* For a 304 or 204 response there is no entity included in
437          * the response and hence nothing to deflate. */
438         if (r->status == HTTP_NOT_MODIFIED || r->status == HTTP_NO_CONTENT) {
439             ap_remove_output_filter(f);
440             return ap_pass_brigade(f->next, bb);
441         }
442
443         /* We're cool with filtering this. */
444         ctx = f->ctx = apr_pcalloc(r->pool, sizeof(*ctx));
445         ctx->bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
446         ctx->buffer = apr_palloc(r->pool, c->bufferSize);
447         ctx->libz_end_func = deflateEnd;
448
449         zRC = deflateInit2(&ctx->stream, c->compressionlevel, Z_DEFLATED,
450                            c->windowSize, c->memlevel,
451                            Z_DEFAULT_STRATEGY);
452
453         if (zRC != Z_OK) {
454             deflateEnd(&ctx->stream);
455             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
456                           "unable to init Zlib: "
457                           "deflateInit2 returned %d: URL %s",
458                           zRC, r->uri);
459             /*
460              * Remove ourselves as it does not make sense to return:
461              * We are not able to init libz and pass data down the chain
462              * uncompressed.
463              */
464             ap_remove_output_filter(f);
465             return ap_pass_brigade(f->next, bb);
466         }
467         /*
468          * Register a cleanup function to ensure that we cleanup the internal
469          * libz resources.
470          */
471         apr_pool_cleanup_register(r->pool, ctx, deflate_ctx_cleanup,
472                                   apr_pool_cleanup_null);
473
474         /* add immortal gzip header */
475         e = apr_bucket_immortal_create(gzip_header, sizeof gzip_header,
476                                        f->c->bucket_alloc);
477         APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
478
479         /* If the entire Content-Encoding is "identity", we can replace it. */
480         if (!encoding || !strcasecmp(encoding, "identity")) {
481             apr_table_setn(r->headers_out, "Content-Encoding", "gzip");
482         }
483         else {
484             apr_table_mergen(r->headers_out, "Content-Encoding", "gzip");
485         }
486         apr_table_unset(r->headers_out, "Content-Length");
487
488         /* initialize deflate output buffer */
489         ctx->stream.next_out = ctx->buffer;
490         ctx->stream.avail_out = c->bufferSize;
491     }
492
493     while (!APR_BRIGADE_EMPTY(bb))
494     {
495         const char *data;
496         apr_bucket *b;
497         apr_size_t len;
498
499         e = APR_BRIGADE_FIRST(bb);
500
501         if (APR_BUCKET_IS_EOS(e)) {
502             char *buf;
503
504             ctx->stream.avail_in = 0; /* should be zero already anyway */
505             /* flush the remaining data from the zlib buffers */
506             flush_libz_buffer(ctx, c, f->c->bucket_alloc, deflate, Z_FINISH,
507                               NO_UPDATE_CRC);
508
509             buf = apr_palloc(r->pool, VALIDATION_SIZE);
510             putLong((unsigned char *)&buf[0], ctx->crc);
511             putLong((unsigned char *)&buf[4], ctx->stream.total_in);
512
513             b = apr_bucket_pool_create(buf, VALIDATION_SIZE, r->pool,
514                                        f->c->bucket_alloc);
515             APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
516             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
517                           "Zlib: Compressed %ld to %ld : URL %s",
518                           ctx->stream.total_in, ctx->stream.total_out, r->uri);
519
520             /* leave notes for logging */
521             if (c->note_input_name) {
522                 apr_table_setn(r->notes, c->note_input_name,
523                                (ctx->stream.total_in > 0)
524                                 ? apr_off_t_toa(r->pool,
525                                                 ctx->stream.total_in)
526                                 : "-");
527             }
528
529             if (c->note_output_name) {
530                 apr_table_setn(r->notes, c->note_output_name,
531                                (ctx->stream.total_in > 0)
532                                 ? apr_off_t_toa(r->pool,
533                                                 ctx->stream.total_out)
534                                 : "-");
535             }
536
537             if (c->note_ratio_name) {
538                 apr_table_setn(r->notes, c->note_ratio_name,
539                                (ctx->stream.total_in > 0)
540                                 ? apr_itoa(r->pool,
541                                            (int)(ctx->stream.total_out
542                                                  * 100
543                                                  / ctx->stream.total_in))
544                                 : "-");
545             }
546
547             deflateEnd(&ctx->stream);
548             /* No need for cleanup any longer */
549             apr_pool_cleanup_kill(r->pool, ctx, deflate_ctx_cleanup);
550
551             /* Remove EOS from the old list, and insert into the new. */
552             APR_BUCKET_REMOVE(e);
553             APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
554
555             /* Okay, we've seen the EOS.
556              * Time to pass it along down the chain.
557              */
558             return ap_pass_brigade(f->next, ctx->bb);
559         }
560
561         if (APR_BUCKET_IS_FLUSH(e)) {
562             apr_status_t rv;
563
564             /* flush the remaining data from the zlib buffers */
565             zRC = flush_libz_buffer(ctx, c, f->c->bucket_alloc, deflate,
566                                     Z_SYNC_FLUSH, NO_UPDATE_CRC);
567             if (zRC != Z_OK) {
568                 return APR_EGENERAL;
569             }
570
571             /* Remove flush bucket from old brigade anf insert into the new. */
572             APR_BUCKET_REMOVE(e);
573             APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
574             rv = ap_pass_brigade(f->next, ctx->bb);
575             if (rv != APR_SUCCESS) {
576                 return rv;
577             }
578             continue;
579         }
580
581         /* read */
582         apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
583
584         /* This crc32 function is from zlib. */
585         ctx->crc = crc32(ctx->crc, (const Bytef *)data, len);
586
587         /* write */
588         ctx->stream.next_in = (unsigned char *)data; /* We just lost const-ness,
589                                                       * but we'll just have to
590                                                       * trust zlib */
591         ctx->stream.avail_in = len;
592
593         while (ctx->stream.avail_in != 0) {
594             if (ctx->stream.avail_out == 0) {
595                 apr_status_t rv;
596
597                 ctx->stream.next_out = ctx->buffer;
598                 len = c->bufferSize - ctx->stream.avail_out;
599
600                 b = apr_bucket_heap_create((char *)ctx->buffer, len,
601                                            NULL, f->c->bucket_alloc);
602                 APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
603                 ctx->stream.avail_out = c->bufferSize;
604                 /* Send what we have right now to the next filter. */
605                 rv = ap_pass_brigade(f->next, ctx->bb);
606                 if (rv != APR_SUCCESS) {
607                     return rv;
608                 }
609             }
610
611             zRC = deflate(&(ctx->stream), Z_NO_FLUSH);
612
613             if (zRC != Z_OK) {
614                 return APR_EGENERAL;
615             }
616         }
617
618         apr_bucket_delete(e);
619     }
620
621     apr_brigade_cleanup(bb);
622     return APR_SUCCESS;
623 }
624
625 /* This is the deflate input filter (inflates).  */
626 static apr_status_t deflate_in_filter(ap_filter_t *f,
627                                       apr_bucket_brigade *bb,
628                                       ap_input_mode_t mode,
629                                       apr_read_type_e block,
630                                       apr_off_t readbytes)
631 {
632     apr_bucket *bkt;
633     request_rec *r = f->r;
634     deflate_ctx *ctx = f->ctx;
635     int zRC;
636     apr_status_t rv;
637     deflate_filter_config *c;
638
639     /* just get out of the way of things we don't want. */
640     if (mode != AP_MODE_READBYTES) {
641         return ap_get_brigade(f->next, bb, mode, block, readbytes);
642     }
643
644     c = ap_get_module_config(r->server->module_config, &deflate_module);
645
646     if (!ctx) {
647         int found = 0;
648         char *token, deflate_hdr[10];
649         const char *encoding;
650         apr_size_t len;
651
652         /* only work on main request/no subrequests */
653         if (!ap_is_initial_req(r)) {
654             ap_remove_input_filter(f);
655             return ap_get_brigade(f->next, bb, mode, block, readbytes);
656         }
657
658         /* Let's see what our current Content-Encoding is.
659          * If gzip is present, don't gzip again.  (We could, but let's not.)
660          */
661         encoding = apr_table_get(r->headers_in, "Content-Encoding");
662         if (encoding) {
663             const char *tmp = encoding;
664
665             token = ap_get_token(r->pool, &tmp, 0);
666             while (token && token[0]) {
667                 if (!strcasecmp(token, "gzip")) {
668                     found = 1;
669                     break;
670                 }
671                 /* Otherwise, skip token */
672                 tmp++;
673                 token = ap_get_token(r->pool, &tmp, 0);
674             }
675         }
676
677         if (found == 0) {
678             ap_remove_input_filter(f);
679             return ap_get_brigade(f->next, bb, mode, block, readbytes);
680         }
681
682         f->ctx = ctx = apr_pcalloc(f->r->pool, sizeof(*ctx));
683         ctx->bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
684         ctx->proc_bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
685         ctx->buffer = apr_palloc(r->pool, c->bufferSize);
686
687         rv = ap_get_brigade(f->next, ctx->bb, AP_MODE_READBYTES, block, 10);
688         if (rv != APR_SUCCESS) {
689             return rv;
690         }
691
692         len = 10;
693         rv = apr_brigade_flatten(ctx->bb, deflate_hdr, &len);
694         if (rv != APR_SUCCESS) {
695             return rv;
696         }
697
698         /* We didn't get the magic bytes. */
699         if (len != 10 ||
700             deflate_hdr[0] != deflate_magic[0] ||
701             deflate_hdr[1] != deflate_magic[1]) {
702             return APR_EGENERAL;
703         }
704
705         /* We can't handle flags for now. */
706         if (deflate_hdr[3] != 0) {
707             return APR_EGENERAL;
708         }
709
710         zRC = inflateInit2(&ctx->stream, c->windowSize);
711
712         if (zRC != Z_OK) {
713             f->ctx = NULL;
714             inflateEnd(&ctx->stream);
715             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
716                           "unable to init Zlib: "
717                           "inflateInit2 returned %d: URL %s",
718                           zRC, r->uri);
719             ap_remove_input_filter(f);
720             return ap_get_brigade(f->next, bb, mode, block, readbytes);
721         }
722
723         /* initialize deflate output buffer */
724         ctx->stream.next_out = ctx->buffer;
725         ctx->stream.avail_out = c->bufferSize;
726
727         apr_brigade_cleanup(ctx->bb);
728     }
729
730     if (APR_BRIGADE_EMPTY(ctx->proc_bb)) {
731         rv = ap_get_brigade(f->next, ctx->bb, mode, block, readbytes);
732
733         if (rv != APR_SUCCESS) {
734             /* What about APR_EAGAIN errors? */
735             inflateEnd(&ctx->stream);
736             return rv;
737         }
738
739         for (bkt = APR_BRIGADE_FIRST(ctx->bb);
740              bkt != APR_BRIGADE_SENTINEL(ctx->bb);
741              bkt = APR_BUCKET_NEXT(bkt))
742         {
743             const char *data;
744             apr_size_t len;
745
746             /* If we actually see the EOS, that means we screwed up! */
747             if (APR_BUCKET_IS_EOS(bkt)) {
748                 inflateEnd(&ctx->stream);
749                 return APR_EGENERAL;
750             }
751
752             if (APR_BUCKET_IS_FLUSH(bkt)) {
753                 apr_bucket *tmp_heap;
754                 zRC = inflate(&(ctx->stream), Z_SYNC_FLUSH);
755                 if (zRC != Z_OK) {
756                     inflateEnd(&ctx->stream);
757                     return APR_EGENERAL;
758                 }
759
760                 ctx->stream.next_out = ctx->buffer;
761                 len = c->bufferSize - ctx->stream.avail_out;
762
763                 ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
764                 tmp_heap = apr_bucket_heap_create((char *)ctx->buffer, len,
765                                                  NULL, f->c->bucket_alloc);
766                 APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, tmp_heap);
767                 ctx->stream.avail_out = c->bufferSize;
768
769                 /* Move everything to the returning brigade. */
770                 APR_BUCKET_REMOVE(bkt);
771                 APR_BRIGADE_CONCAT(bb, ctx->bb);
772                 break;
773             }
774
775             /* read */
776             apr_bucket_read(bkt, &data, &len, APR_BLOCK_READ);
777
778             /* pass through zlib inflate. */
779             ctx->stream.next_in = (unsigned char *)data;
780             ctx->stream.avail_in = len;
781
782             zRC = Z_OK;
783
784             while (ctx->stream.avail_in != 0) {
785                 if (ctx->stream.avail_out == 0) {
786                     apr_bucket *tmp_heap;
787                     ctx->stream.next_out = ctx->buffer;
788                     len = c->bufferSize - ctx->stream.avail_out;
789
790                     ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
791                     tmp_heap = apr_bucket_heap_create((char *)ctx->buffer, len,
792                                                       NULL, f->c->bucket_alloc);
793                     APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, tmp_heap);
794                     ctx->stream.avail_out = c->bufferSize;
795                 }
796
797                 zRC = inflate(&ctx->stream, Z_NO_FLUSH);
798
799                 if (zRC == Z_STREAM_END) {
800                     break;
801                 }
802
803                 if (zRC != Z_OK) {
804                     inflateEnd(&ctx->stream);
805                     return APR_EGENERAL;
806                 }
807             }
808             if (zRC == Z_STREAM_END) {
809                 apr_bucket *tmp_heap, *eos;
810
811                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
812                               "Zlib: Inflated %ld to %ld : URL %s",
813                               ctx->stream.total_in, ctx->stream.total_out,
814                               r->uri);
815
816                 len = c->bufferSize - ctx->stream.avail_out;
817
818                 ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
819                 tmp_heap = apr_bucket_heap_create((char *)ctx->buffer, len,
820                                                   NULL, f->c->bucket_alloc);
821                 APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, tmp_heap);
822                 ctx->stream.avail_out = c->bufferSize;
823
824                 /* Is the remaining 8 bytes already in the avail stream? */
825                 if (ctx->stream.avail_in >= 8) {
826                     unsigned long compCRC, compLen;
827                     compCRC = getLong(ctx->stream.next_in);
828                     if (ctx->crc != compCRC) {
829                         inflateEnd(&ctx->stream);
830                         return APR_EGENERAL;
831                     }
832                     ctx->stream.next_in += 4;
833                     compLen = getLong(ctx->stream.next_in);
834                     if (ctx->stream.total_out != compLen) {
835                         inflateEnd(&ctx->stream);
836                         return APR_EGENERAL;
837                     }
838                 }
839                 else {
840                     /* FIXME: We need to grab the 8 verification bytes
841                      * from the wire! */
842                     inflateEnd(&ctx->stream);
843                     return APR_EGENERAL;
844                 }
845
846                 inflateEnd(&ctx->stream);
847
848                 eos = apr_bucket_eos_create(f->c->bucket_alloc);
849                 APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, eos);
850                 break;
851             }
852
853         }
854         apr_brigade_cleanup(ctx->bb);
855     }
856
857     /* If we are about to return nothing for a 'blocking' read and we have
858      * some data in our zlib buffer, flush it out so we can return something.
859      */
860     if (block == APR_BLOCK_READ &&
861         APR_BRIGADE_EMPTY(ctx->proc_bb) &&
862         ctx->stream.avail_out < c->bufferSize) {
863         apr_bucket *tmp_heap;
864         apr_size_t len;
865         ctx->stream.next_out = ctx->buffer;
866         len = c->bufferSize - ctx->stream.avail_out;
867
868         ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
869         tmp_heap = apr_bucket_heap_create((char *)ctx->buffer, len,
870                                           NULL, f->c->bucket_alloc);
871         APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, tmp_heap);
872         ctx->stream.avail_out = c->bufferSize;
873     }
874
875     if (!APR_BRIGADE_EMPTY(ctx->proc_bb)) {
876         apr_bucket_brigade *newbb;
877
878         /* May return APR_INCOMPLETE which is fine by us. */
879         apr_brigade_partition(ctx->proc_bb, readbytes, &bkt);
880
881         newbb = apr_brigade_split(ctx->proc_bb, bkt);
882         APR_BRIGADE_CONCAT(bb, ctx->proc_bb);
883         APR_BRIGADE_CONCAT(ctx->proc_bb, newbb);
884     }
885
886     return APR_SUCCESS;
887 }
888
889
890 /* Filter to inflate for a content-transforming proxy.  */
891 static apr_status_t inflate_out_filter(ap_filter_t *f,
892                                       apr_bucket_brigade *bb)
893 {
894     int zlib_method;
895     int zlib_flags;
896     int inflate_init = 1;
897     apr_bucket *e;
898     request_rec *r = f->r;
899     deflate_ctx *ctx = f->ctx;
900     int zRC;
901     apr_status_t rv;
902     deflate_filter_config *c;
903
904     /* Do nothing if asked to filter nothing. */
905     if (APR_BRIGADE_EMPTY(bb)) {
906         return ap_pass_brigade(f->next, bb);
907     }
908
909     c = ap_get_module_config(r->server->module_config, &deflate_module);
910
911     if (!ctx) {
912         int found = 0;
913         char *token;
914         const char *encoding;
915
916         /* only work on main request/no subrequests */
917         if (!ap_is_initial_req(r)) {
918             ap_remove_output_filter(f);
919             return ap_pass_brigade(f->next, bb);
920         }
921
922         /*
923          * Let's see what our current Content-Encoding is.
924          * Only inflate if gzip is present.
925          */
926         encoding = apr_table_get(r->headers_out, "Content-Encoding");
927         if (encoding) {
928             const char *tmp = encoding;
929
930             token = ap_get_token(r->pool, &tmp, 0);
931             while (token && token[0]) {
932                 if (!strcasecmp(token, "gzip")) {
933                     found = 1;
934                     break;
935                 }
936                 /* Otherwise, skip token */
937                 tmp++;
938                 token = ap_get_token(r->pool, &tmp, 0);
939             }
940         }
941
942         if (found == 0) {
943             ap_remove_output_filter(f);
944             return ap_pass_brigade(f->next, bb);
945         }
946         apr_table_unset(r->headers_out, "Content-Encoding");
947
948         /* No need to inflate HEAD or 204/304 */
949         if (APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(bb))) {
950             ap_remove_output_filter(f);
951             return ap_pass_brigade(f->next, bb);
952         }
953
954
955         f->ctx = ctx = apr_pcalloc(f->r->pool, sizeof(*ctx));
956         ctx->bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
957         ctx->buffer = apr_palloc(r->pool, c->bufferSize);
958         ctx->libz_end_func = inflateEnd;
959         ctx->validation_buffer = NULL;
960         ctx->validation_buffer_length = 0;
961
962         zRC = inflateInit2(&ctx->stream, c->windowSize);
963
964         if (zRC != Z_OK) {
965             f->ctx = NULL;
966             inflateEnd(&ctx->stream);
967             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
968                           "unable to init Zlib: "
969                           "inflateInit2 returned %d: URL %s",
970                           zRC, r->uri);
971             /*
972              * Remove ourselves as it does not make sense to return:
973              * We are not able to init libz and pass data down the chain
974              * compressed.
975              */
976             ap_remove_output_filter(f);
977             return ap_pass_brigade(f->next, bb);
978         }
979
980         /*
981          * Register a cleanup function to ensure that we cleanup the internal
982          * libz resources.
983          */
984         apr_pool_cleanup_register(r->pool, ctx, deflate_ctx_cleanup,
985                                   apr_pool_cleanup_null);
986
987         apr_table_unset(r->headers_out, "Content-Length");
988
989         /* initialize inflate output buffer */
990         ctx->stream.next_out = ctx->buffer;
991         ctx->stream.avail_out = c->bufferSize;
992
993         inflate_init = 0;
994     }
995
996     while (!APR_BRIGADE_EMPTY(bb))
997     {
998         const char *data;
999         apr_bucket *b;
1000         apr_size_t len;
1001
1002         e = APR_BRIGADE_FIRST(bb);
1003
1004         if (APR_BUCKET_IS_EOS(e)) {
1005             /*
1006              * We are really done now. Ensure that we never return here, even
1007              * if a second EOS bucket falls down the chain. Thus remove
1008              * ourselves.
1009              */
1010             ap_remove_output_filter(f);
1011             /* should be zero already anyway */
1012             ctx->stream.avail_in = 0;
1013             /*
1014              * Flush the remaining data from the zlib buffers. It is correct
1015              * to use Z_SYNC_FLUSH in this case and not Z_FINISH as in the
1016              * deflate case. In the inflate case Z_FINISH requires to have a
1017              * large enough output buffer to put ALL data in otherwise it
1018              * fails, whereas in the deflate case you can empty a filled output
1019              * buffer and call it again until no more output can be created.
1020              */
1021             flush_libz_buffer(ctx, c, f->c->bucket_alloc, inflate, Z_SYNC_FLUSH,
1022                               UPDATE_CRC);
1023             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1024                           "Zlib: Inflated %ld to %ld : URL %s",
1025                           ctx->stream.total_in, ctx->stream.total_out, r->uri);
1026
1027             if (ctx->validation_buffer_length == VALIDATION_SIZE) {
1028                 unsigned long compCRC, compLen;
1029                 compCRC = getLong(ctx->validation_buffer);
1030                 if (ctx->crc != compCRC) {
1031                     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1032                                   "Zlib: Checksum of inflated stream invalid");
1033                     return APR_EGENERAL;
1034                 }
1035                 ctx->validation_buffer += VALIDATION_SIZE / 2;
1036                 compLen = getLong(ctx->validation_buffer);
1037                 if (ctx->stream.total_out != compLen) {
1038                     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1039                                   "Zlib: Length of inflated stream invalid");
1040                     return APR_EGENERAL;
1041                 }
1042             }
1043             else {
1044                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1045                               "Zlib: Validation bytes not present");
1046                 return APR_EGENERAL;
1047             }
1048
1049             inflateEnd(&ctx->stream);
1050             /* No need for cleanup any longer */
1051             apr_pool_cleanup_kill(r->pool, ctx, deflate_ctx_cleanup);
1052
1053             /* Remove EOS from the old list, and insert into the new. */
1054             APR_BUCKET_REMOVE(e);
1055             APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
1056
1057             /*
1058              * Okay, we've seen the EOS.
1059              * Time to pass it along down the chain.
1060              */
1061             return ap_pass_brigade(f->next, ctx->bb);
1062         }
1063
1064         if (APR_BUCKET_IS_FLUSH(e)) {
1065             apr_status_t rv;
1066
1067             /* flush the remaining data from the zlib buffers */
1068             zRC = flush_libz_buffer(ctx, c, f->c->bucket_alloc, inflate,
1069                                     Z_SYNC_FLUSH, UPDATE_CRC);
1070             if (zRC != Z_OK) {
1071                 return APR_EGENERAL;
1072             }
1073
1074             /* Remove flush bucket from old brigade anf insert into the new. */
1075             APR_BUCKET_REMOVE(e);
1076             APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
1077             rv = ap_pass_brigade(f->next, ctx->bb);
1078             if (rv != APR_SUCCESS) {
1079                 return rv;
1080             }
1081             continue;
1082         }
1083
1084         /* read */
1085         apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
1086
1087         /* first bucket contains zlib header */
1088         if (!inflate_init++) {
1089             if (len < 10) {
1090                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1091                               "Insufficient data for inflate");
1092                 return APR_EGENERAL;
1093             }
1094             else  {
1095                 zlib_method = data[2];
1096                 zlib_flags = data[3];
1097                 if (zlib_method != Z_DEFLATED) {
1098                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1099                                   "inflate: data not deflated!");
1100                     ap_remove_output_filter(f);
1101                     return ap_pass_brigade(f->next, bb);
1102                 }
1103                 if (data[0] != deflate_magic[0] ||
1104                     data[1] != deflate_magic[1] ||
1105                     (zlib_flags & RESERVED) != 0) {
1106                         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1107                                       "inflate: bad header");
1108                     return APR_EGENERAL ;
1109                 }
1110                 data += 10 ;
1111                 len -= 10 ;
1112            }
1113            if (zlib_flags & EXTRA_FIELD) {
1114                unsigned int bytes = (unsigned int)(data[0]);
1115                bytes += ((unsigned int)(data[1])) << 8;
1116                bytes += 2;
1117                if (len < bytes) {
1118                    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1119                                  "inflate: extra field too big (not "
1120                                  "supported)");
1121                    return APR_EGENERAL;
1122                }
1123                data += bytes;
1124                len -= bytes;
1125            }
1126            if (zlib_flags & ORIG_NAME) {
1127                while (len-- && *data++);
1128            }
1129            if (zlib_flags & COMMENT) {
1130                while (len-- && *data++);
1131            }
1132            if (zlib_flags & HEAD_CRC) {
1133                 len -= 2;
1134                 data += 2;
1135            }
1136         }
1137
1138         /* pass through zlib inflate. */
1139         ctx->stream.next_in = (unsigned char *)data;
1140         ctx->stream.avail_in = len;
1141
1142         if (ctx->validation_buffer) {
1143             if (ctx->validation_buffer_length < VALIDATION_SIZE) {
1144                 apr_size_t copy_size;
1145
1146                 copy_size = VALIDATION_SIZE - ctx->validation_buffer_length;
1147                 if (copy_size > ctx->stream.avail_in)
1148                     copy_size = ctx->stream.avail_in;
1149                 memcpy(ctx->validation_buffer + ctx->validation_buffer_length,
1150                        ctx->stream.next_in, copy_size);
1151                 /* Saved copy_size bytes */
1152                 ctx->stream.avail_in -= copy_size;
1153                 ctx->validation_buffer_length += copy_size;
1154             }
1155             if (ctx->stream.avail_in) {
1156                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1157                               "Zlib: %d bytes of garbage at the end of "
1158                               "compressed stream.", ctx->stream.avail_in);
1159                 /*
1160                  * There is nothing worth consuming for zlib left, because it is
1161                  * either garbage data or the data has been copied to the
1162                  * validation buffer (processing validation data is no business
1163                  * for zlib). So set ctx->stream.avail_in to zero to indicate
1164                  * this to the following while loop.
1165                  */
1166                 ctx->stream.avail_in = 0;
1167             }
1168         }
1169
1170         zRC = Z_OK;
1171
1172         while (ctx->stream.avail_in != 0) {
1173             if (ctx->stream.avail_out == 0) {
1174
1175                 ctx->stream.next_out = ctx->buffer;
1176                 len = c->bufferSize - ctx->stream.avail_out;
1177
1178                 ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
1179                 b = apr_bucket_heap_create((char *)ctx->buffer, len,
1180                                            NULL, f->c->bucket_alloc);
1181                 APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
1182                 ctx->stream.avail_out = c->bufferSize;
1183                 /* Send what we have right now to the next filter. */
1184                 rv = ap_pass_brigade(f->next, ctx->bb);
1185                 if (rv != APR_SUCCESS) {
1186                     return rv;
1187                 }
1188             }
1189
1190             zRC = inflate(&ctx->stream, Z_NO_FLUSH);
1191
1192             if (zRC == Z_STREAM_END) {
1193                 /*
1194                  * We have inflated all data. Now try to capture the
1195                  * validation bytes. We may not have them all available
1196                  * right now, but capture what is there.
1197                  */
1198                 ctx->validation_buffer = apr_pcalloc(f->r->pool,
1199                                                      VALIDATION_SIZE);
1200                 if (ctx->stream.avail_in > VALIDATION_SIZE) {
1201                     ctx->validation_buffer_length = VALIDATION_SIZE;
1202                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1203                                   "Zlib: %d bytes of garbage at the end of "
1204                                   "compressed stream.",
1205                                   ctx->stream.avail_in - VALIDATION_SIZE);
1206                 } else if (ctx->stream.avail_in > 0) {
1207                            ctx->validation_buffer_length = ctx->stream.avail_in;
1208                 }
1209                 if (ctx->validation_buffer_length)
1210                     memcpy(ctx->validation_buffer, ctx->stream.next_in,
1211                            ctx->validation_buffer_length);
1212                 break;
1213             }
1214
1215             if (zRC != Z_OK) {
1216                 return APR_EGENERAL;
1217             }
1218         }
1219
1220         apr_bucket_delete(e);
1221     }
1222
1223     apr_brigade_cleanup(bb);
1224     return APR_SUCCESS;
1225 }
1226
1227 #define PROTO_FLAGS AP_FILTER_PROTO_CHANGE|AP_FILTER_PROTO_CHANGE_LENGTH
1228 static void register_hooks(apr_pool_t *p)
1229 {
1230     ap_register_output_filter(deflateFilterName, deflate_out_filter, NULL,
1231                               AP_FTYPE_CONTENT_SET);
1232     ap_register_output_filter("INFLATE", inflate_out_filter, NULL,
1233                               AP_FTYPE_RESOURCE-1);
1234     ap_register_input_filter(deflateFilterName, deflate_in_filter, NULL,
1235                               AP_FTYPE_CONTENT_SET);
1236 }
1237
1238 static const command_rec deflate_filter_cmds[] = {
1239     AP_INIT_TAKE12("DeflateFilterNote", deflate_set_note, NULL, RSRC_CONF,
1240                   "Set a note to report on compression ratio"),
1241     AP_INIT_TAKE1("DeflateWindowSize", deflate_set_window_size, NULL,
1242                   RSRC_CONF, "Set the Deflate window size (1-15)"),
1243     AP_INIT_TAKE1("DeflateBufferSize", deflate_set_buffer_size, NULL, RSRC_CONF,
1244                   "Set the Deflate Buffer Size"),
1245     AP_INIT_TAKE1("DeflateMemLevel", deflate_set_memlevel, NULL, RSRC_CONF,
1246                   "Set the Deflate Memory Level (1-9)"),
1247     AP_INIT_TAKE1("DeflateCompressionLevel", deflate_set_compressionlevel, NULL, RSRC_CONF,
1248                   "Set the Deflate Compression Level (1-9)"),
1249     {NULL}
1250 };
1251
1252 module AP_MODULE_DECLARE_DATA deflate_module = {
1253     STANDARD20_MODULE_STUFF,
1254     NULL,                         /* dir config creater */
1255     NULL,                         /* dir merger --- default is to override */
1256     create_deflate_server_config, /* server config */
1257     NULL,                         /* merge server config */
1258     deflate_filter_cmds,          /* command table */
1259     register_hooks                /* register hooks */
1260 };