]> granicus.if.org Git - apache/blob - modules/filters/mod_deflate.c
55fe883501394118b1be454c15c1c9f3f7004dd9
[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_lib.h"
41 #include "apr_strings.h"
42 #include "apr_general.h"
43 #include "util_filter.h"
44 #include "apr_buckets.h"
45 #include "http_request.h"
46 #define APR_WANT_STRFUNC
47 #include "apr_want.h"
48 #include "mod_ssl.h"
49
50 #include "zlib.h"
51
52 #include <limits.h>     /* for INT_MAX */
53
54 static const char deflateFilterName[] = "DEFLATE";
55 module AP_MODULE_DECLARE_DATA deflate_module;
56
57 #define AP_DEFLATE_ETAG_ADDSUFFIX 0
58 #define AP_DEFLATE_ETAG_NOCHANGE  1
59 #define AP_DEFLATE_ETAG_REMOVE    2
60
61 typedef struct deflate_filter_config_t
62 {
63     int windowSize;
64     int memlevel;
65     int compressionlevel;
66     apr_size_t bufferSize;
67     char *note_ratio_name;
68     char *note_input_name;
69     char *note_output_name;
70     int etag_opt;
71 } deflate_filter_config;
72
73 /* RFC 1952 Section 2.3 defines the gzip header:
74  *
75  * +---+---+---+---+---+---+---+---+---+---+
76  * |ID1|ID2|CM |FLG|     MTIME     |XFL|OS |
77  * +---+---+---+---+---+---+---+---+---+---+
78  */
79 static const char gzip_header[10] =
80 { '\037', '\213', Z_DEFLATED, 0,
81   0, 0, 0, 0, /* mtime */
82   0, 0x03 /* Unix OS_CODE */
83 };
84
85 /* magic header */
86 static const char deflate_magic[2] = { '\037', '\213' };
87
88 /* windowsize is negative to suppress Zlib header */
89 #define DEFAULT_COMPRESSION Z_DEFAULT_COMPRESSION
90 #define DEFAULT_WINDOWSIZE -15
91 #define DEFAULT_MEMLEVEL 9
92 #define DEFAULT_BUFFERSIZE 8096
93
94 static APR_OPTIONAL_FN_TYPE(ssl_var_lookup) *mod_deflate_ssl_var = NULL;
95
96 /* Check whether a request is gzipped, so we can un-gzip it.
97  * If a request has multiple encodings, we need the gzip
98  * to be the outermost non-identity encoding.
99  */
100 static int check_gzip(request_rec *r, apr_table_t *hdrs1, apr_table_t *hdrs2)
101 {
102     int found = 0;
103     apr_table_t *hdrs = hdrs1;
104     const char *encoding = apr_table_get(hdrs, "Content-Encoding");
105
106     if (!encoding && (hdrs2 != NULL)) {
107         /* the output filter has two tables and a content_encoding to check */
108         encoding = apr_table_get(hdrs2, "Content-Encoding");
109         hdrs = hdrs2;
110         if (!encoding) {
111             encoding = r->content_encoding;
112             hdrs = NULL;
113         }
114     }
115     if (encoding && *encoding) {
116
117         /* check the usual/simple case first */
118         if (!strcasecmp(encoding, "gzip")
119             || !strcasecmp(encoding, "x-gzip")) {
120             found = 1;
121             if (hdrs) {
122                 apr_table_unset(hdrs, "Content-Encoding");
123             }
124             else {
125                 r->content_encoding = NULL;
126             }
127         }
128         else if (ap_strchr_c(encoding, ',') != NULL) {
129             /* If the outermost encoding isn't gzip, there's nowt
130              * we can do.  So only check the last non-identity token
131              */
132             char *new_encoding = apr_pstrdup(r->pool, encoding);
133             char *ptr;
134             for(;;) {
135                 char *token = ap_strrchr(new_encoding, ',');
136                 if (!token) {        /* gzip:identity or other:identity */
137                     if (!strcasecmp(new_encoding, "gzip")
138                         || !strcasecmp(new_encoding, "x-gzip")) {
139                         found = 1;
140                         if (hdrs) {
141                             apr_table_unset(hdrs, "Content-Encoding");
142                         }
143                         else {
144                             r->content_encoding = NULL;
145                         }
146                     }
147                     break; /* seen all tokens */
148                 }
149                 for (ptr=token+1; apr_isspace(*ptr); ++ptr);
150                 if (!strcasecmp(ptr, "gzip")
151                     || !strcasecmp(ptr, "x-gzip")) {
152                     *token = '\0';
153                     if (hdrs) {
154                         apr_table_setn(hdrs, "Content-Encoding", new_encoding);
155                     }
156                     else {
157                         r->content_encoding = new_encoding;
158                     }
159                     found = 1;
160                 }
161                 else if (!ptr[0] || !strcasecmp(ptr, "identity")) {
162                     *token = '\0';
163                     continue; /* strip the token and find the next one */
164                 }
165                 break; /* found a non-identity token */
166             }
167         }
168     }
169     /*
170      * If we have dealt with the headers above but content_encoding was set
171      * before sync it with the new value in the hdrs table as
172      * r->content_encoding takes precedence later on in the http_header_filter
173      * and hence would destroy what we have just set in the hdrs table.
174      */
175     if (hdrs && r->content_encoding) {
176         r->content_encoding = apr_table_get(hdrs, "Content-Encoding");
177     }
178     return found;
179 }
180
181 /* Outputs a long in LSB order to the given file
182  * only the bottom 4 bits are required for the deflate file format.
183  */
184 static void putLong(unsigned char *string, unsigned long x)
185 {
186     string[0] = (unsigned char)(x & 0xff);
187     string[1] = (unsigned char)((x & 0xff00) >> 8);
188     string[2] = (unsigned char)((x & 0xff0000) >> 16);
189     string[3] = (unsigned char)((x & 0xff000000) >> 24);
190 }
191
192 /* Inputs a string and returns a long.
193  */
194 static unsigned long getLong(unsigned char *string)
195 {
196     return ((unsigned long)string[0])
197           | (((unsigned long)string[1]) << 8)
198           | (((unsigned long)string[2]) << 16)
199           | (((unsigned long)string[3]) << 24);
200 }
201
202 static void *create_deflate_server_config(apr_pool_t *p, server_rec *s)
203 {
204     deflate_filter_config *c = apr_pcalloc(p, sizeof *c);
205
206     c->memlevel   = DEFAULT_MEMLEVEL;
207     c->windowSize = DEFAULT_WINDOWSIZE;
208     c->bufferSize = DEFAULT_BUFFERSIZE;
209     c->compressionlevel = DEFAULT_COMPRESSION;
210
211     return c;
212 }
213
214 static const char *deflate_set_window_size(cmd_parms *cmd, void *dummy,
215                                            const char *arg)
216 {
217     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
218                                                     &deflate_module);
219     int i;
220
221     i = atoi(arg);
222
223     if (i < 1 || i > 15)
224         return "DeflateWindowSize must be between 1 and 15";
225
226     c->windowSize = i * -1;
227
228     return NULL;
229 }
230
231 static const char *deflate_set_buffer_size(cmd_parms *cmd, void *dummy,
232                                            const char *arg)
233 {
234     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
235                                                     &deflate_module);
236     int n = atoi(arg);
237
238     if (n <= 0) {
239         return "DeflateBufferSize should be positive";
240     }
241
242     c->bufferSize = (apr_size_t)n;
243
244     return NULL;
245 }
246 static const char *deflate_set_note(cmd_parms *cmd, void *dummy,
247                                     const char *arg1, const char *arg2)
248 {
249     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
250                                                     &deflate_module);
251
252     if (arg2 == NULL) {
253         c->note_ratio_name = apr_pstrdup(cmd->pool, arg1);
254     }
255     else if (!strcasecmp(arg1, "ratio")) {
256         c->note_ratio_name = apr_pstrdup(cmd->pool, arg2);
257     }
258     else if (!strcasecmp(arg1, "input")) {
259         c->note_input_name = apr_pstrdup(cmd->pool, arg2);
260     }
261     else if (!strcasecmp(arg1, "output")) {
262         c->note_output_name = apr_pstrdup(cmd->pool, arg2);
263     }
264     else {
265         return apr_psprintf(cmd->pool, "Unknown note type %s", arg1);
266     }
267
268     return NULL;
269 }
270
271 static const char *deflate_set_memlevel(cmd_parms *cmd, void *dummy,
272                                         const char *arg)
273 {
274     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
275                                                     &deflate_module);
276     int i;
277
278     i = atoi(arg);
279
280     if (i < 1 || i > 9)
281         return "DeflateMemLevel must be between 1 and 9";
282
283     c->memlevel = i;
284
285     return NULL;
286 }
287
288 static const char *deflate_set_etag(cmd_parms *cmd, void *dummy,
289                                         const char *arg)
290 {
291     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
292                                                     &deflate_module);
293
294     if (!strcasecmp(arg, "NoChange")) { 
295       c->etag_opt = AP_DEFLATE_ETAG_NOCHANGE;
296     }
297     else if (!strcasecmp(arg, "AddSuffix")) { 
298       c->etag_opt = AP_DEFLATE_ETAG_ADDSUFFIX;
299     }
300     else if (!strcasecmp(arg, "Remove")) { 
301       c->etag_opt = AP_DEFLATE_ETAG_REMOVE;
302     }
303     else { 
304         return "DeflateAlterETAG accepts only 'NoChange', 'AddSuffix', and 'Remove'";
305     }
306
307     return NULL;
308 }
309
310
311 static const char *deflate_set_compressionlevel(cmd_parms *cmd, void *dummy,
312                                         const char *arg)
313 {
314     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
315                                                     &deflate_module);
316     int i;
317
318     i = atoi(arg);
319
320     if (i < 1 || i > 9)
321         return "Compression Level must be between 1 and 9";
322
323     c->compressionlevel = i;
324
325     return NULL;
326 }
327
328 typedef struct deflate_ctx_t
329 {
330     z_stream stream;
331     unsigned char *buffer;
332     unsigned long crc;
333     apr_bucket_brigade *bb, *proc_bb;
334     int (*libz_end_func)(z_streamp);
335     unsigned char *validation_buffer;
336     apr_size_t validation_buffer_length;
337     char header[10]; // sizeof(gzip_header)
338     apr_size_t header_len;
339     int zlib_flags;
340     unsigned int consume_pos,
341                  consume_len;
342     unsigned int filter_init:1;
343     unsigned int done:1;
344 } deflate_ctx;
345
346 /* Number of validation bytes (CRC and length) after the compressed data */
347 #define VALIDATION_SIZE 8
348 /* Do not update ctx->crc, see comment in flush_libz_buffer */
349 #define NO_UPDATE_CRC 0
350 /* Do update ctx->crc, see comment in flush_libz_buffer */
351 #define UPDATE_CRC 1
352
353 static int flush_libz_buffer(deflate_ctx *ctx, deflate_filter_config *c,
354                              struct apr_bucket_alloc_t *bucket_alloc,
355                              int (*libz_func)(z_streamp, int), int flush,
356                              int crc)
357 {
358     int zRC = Z_OK;
359     int done = 0;
360     unsigned int deflate_len;
361     apr_bucket *b;
362
363     for (;;) {
364          deflate_len = c->bufferSize - ctx->stream.avail_out;
365
366          if (deflate_len != 0) {
367              /*
368               * Do we need to update ctx->crc? Usually this is the case for
369               * inflate action where we need to do a crc on the output, whereas
370               * in the deflate case we need to do a crc on the input
371               */
372              if (crc) {
373                  ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer,
374                                   deflate_len);
375              }
376              b = apr_bucket_heap_create((char *)ctx->buffer,
377                                         deflate_len, NULL,
378                                         bucket_alloc);
379              APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
380              ctx->stream.next_out = ctx->buffer;
381              ctx->stream.avail_out = c->bufferSize;
382          }
383
384          if (done)
385              break;
386
387          zRC = libz_func(&ctx->stream, flush);
388
389          /*
390           * We can ignore Z_BUF_ERROR because:
391           * When we call libz_func we can assume that
392           *
393           * - avail_in is zero (due to the surrounding code that calls
394           *   flush_libz_buffer)
395           * - avail_out is non zero due to our actions some lines above
396           *
397           * So the only reason for Z_BUF_ERROR is that the internal libz
398           * buffers are now empty and thus we called libz_func one time
399           * too often. This does not hurt. It simply says that we are done.
400           */
401          if (zRC == Z_BUF_ERROR) {
402              zRC = Z_OK;
403              break;
404          }
405
406          done = (ctx->stream.avail_out != 0 || zRC == Z_STREAM_END);
407
408          if (zRC != Z_OK && zRC != Z_STREAM_END)
409              break;
410     }
411     return zRC;
412 }
413
414 static apr_status_t deflate_ctx_cleanup(void *data)
415 {
416     deflate_ctx *ctx = (deflate_ctx *)data;
417
418     if (ctx)
419         ctx->libz_end_func(&ctx->stream);
420     return APR_SUCCESS;
421 }
422
423 /* ETag must be unique among the possible representations, so a change
424  * to content-encoding requires a corresponding change to the ETag.
425  * This routine appends -transform (e.g., -gzip) to the entity-tag
426  * value inside the double-quotes if an ETag has already been set
427  * and its value already contains double-quotes. PR 39727
428  */
429 static void deflate_check_etag(request_rec *r, const char *transform, int etag_opt)
430 {
431     const char *etag = apr_table_get(r->headers_out, "ETag");
432     apr_size_t etaglen;
433
434     if (etag_opt == AP_DEFLATE_ETAG_REMOVE) { 
435         apr_table_unset(r->headers_out, "ETag");
436         return;
437     }
438
439     if ((etag && ((etaglen = strlen(etag)) > 2))) {
440         if (etag[etaglen - 1] == '"') {
441             apr_size_t transformlen = strlen(transform);
442             char *newtag = apr_palloc(r->pool, etaglen + transformlen + 2);
443             char *d = newtag;
444             char *e = d + etaglen - 1;
445             const char *s = etag;
446
447             for (; d < e; ++d, ++s) {
448                 *d = *s;          /* copy etag to newtag up to last quote */
449             }
450             *d++ = '-';           /* append dash to newtag */
451             s = transform;
452             e = d + transformlen;
453             for (; d < e; ++d, ++s) {
454                 *d = *s;          /* copy transform to newtag */
455             }
456             *d++ = '"';           /* append quote to newtag */
457             *d   = '\0';          /* null terminate newtag */
458
459             apr_table_setn(r->headers_out, "ETag", newtag);
460         }
461     }
462 }
463
464 static int have_ssl_compression(request_rec *r)
465 {
466     const char *comp;
467     if (mod_deflate_ssl_var == NULL)
468         return 0;
469     comp = mod_deflate_ssl_var(r->pool, r->server, r->connection, r,
470                                "SSL_COMPRESS_METHOD");
471     if (comp == NULL || *comp == '\0' || strcmp(comp, "NULL") == 0)
472         return 0;
473     return 1;
474 }
475
476 static apr_status_t deflate_out_filter(ap_filter_t *f,
477                                        apr_bucket_brigade *bb)
478 {
479     apr_bucket *e;
480     request_rec *r = f->r;
481     deflate_ctx *ctx = f->ctx;
482     int zRC;
483     apr_size_t len = 0, blen;
484     const char *data;
485     deflate_filter_config *c;
486
487     /* Do nothing if asked to filter nothing. */
488     if (APR_BRIGADE_EMPTY(bb)) {
489         return APR_SUCCESS;
490     }
491
492     c = ap_get_module_config(r->server->module_config,
493                              &deflate_module);
494
495     /* If we don't have a context, we need to ensure that it is okay to send
496      * the deflated content.  If we have a context, that means we've done
497      * this before and we liked it.
498      * This could be not so nice if we always fail.  But, if we succeed,
499      * we're in better shape.
500      */
501     if (!ctx) {
502         char *token;
503         const char *encoding;
504
505         if (have_ssl_compression(r)) {
506             ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
507                           "Compression enabled at SSL level; not compressing "
508                           "at HTTP level.");
509             ap_remove_output_filter(f);
510             return ap_pass_brigade(f->next, bb);
511         }
512
513         /* We have checked above that bb is not empty */
514         e = APR_BRIGADE_LAST(bb);
515         if (APR_BUCKET_IS_EOS(e)) {
516             /*
517              * If we already know the size of the response, we can skip
518              * compression on responses smaller than the compression overhead.
519              * However, if we compress, we must initialize deflate_out before
520              * calling ap_pass_brigade() for the first time.  Otherwise the
521              * headers will be sent to the client without
522              * "Content-Encoding: gzip".
523              */
524             e = APR_BRIGADE_FIRST(bb);
525             while (1) {
526                 apr_status_t rc;
527                 if (APR_BUCKET_IS_EOS(e)) {
528                     ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
529                                   "Not compressing very small response of %"
530                                   APR_SIZE_T_FMT " bytes", len);
531                     ap_remove_output_filter(f);
532                     return ap_pass_brigade(f->next, bb);
533                 }
534                 if (APR_BUCKET_IS_METADATA(e)) {
535                     e = APR_BUCKET_NEXT(e);
536                     continue;
537                 }
538
539                 rc = apr_bucket_read(e, &data, &blen, APR_BLOCK_READ);
540                 if (rc != APR_SUCCESS)
541                     return rc;
542                 len += blen;
543                 /* 50 is for Content-Encoding and Vary headers and ETag suffix */
544                 if (len > sizeof(gzip_header) + VALIDATION_SIZE + 50)
545                     break;
546
547                 e = APR_BUCKET_NEXT(e);
548             }
549         }
550
551         ctx = f->ctx = apr_pcalloc(r->pool, sizeof(*ctx));
552
553         /*
554          * Only work on main request, not subrequests,
555          * that are not a 204 response with no content
556          * and are not tagged with the no-gzip env variable
557          * and not a partial response to a Range request.
558          */
559         if ((r->main != NULL) || (r->status == HTTP_NO_CONTENT) ||
560             apr_table_get(r->subprocess_env, "no-gzip") ||
561             apr_table_get(r->headers_out, "Content-Range")
562            ) {
563             if (APLOG_R_IS_LEVEL(r, APLOG_TRACE1)) {
564                 const char *reason =
565                     (r->main != NULL)                           ? "subrequest" :
566                     (r->status == HTTP_NO_CONTENT)              ? "no content" :
567                     apr_table_get(r->subprocess_env, "no-gzip") ? "no-gzip" :
568                     "content-range";
569                 ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
570                               "Not compressing (%s)", reason);
571             }
572             ap_remove_output_filter(f);
573             return ap_pass_brigade(f->next, bb);
574         }
575
576         /* Some browsers might have problems with content types
577          * other than text/html, so set gzip-only-text/html
578          * (with browsermatch) for them
579          */
580         if (r->content_type == NULL
581              || strncmp(r->content_type, "text/html", 9)) {
582             const char *env_value = apr_table_get(r->subprocess_env,
583                                                   "gzip-only-text/html");
584             if ( env_value && (strcmp(env_value,"1") == 0) ) {
585                 ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
586                               "Not compressing, (gzip-only-text/html)");
587                 ap_remove_output_filter(f);
588                 return ap_pass_brigade(f->next, bb);
589             }
590         }
591
592         /* Let's see what our current Content-Encoding is.
593          * If it's already encoded, don't compress again.
594          * (We could, but let's not.)
595          */
596         encoding = apr_table_get(r->headers_out, "Content-Encoding");
597         if (encoding) {
598             const char *err_enc;
599
600             err_enc = apr_table_get(r->err_headers_out, "Content-Encoding");
601             if (err_enc) {
602                 encoding = apr_pstrcat(r->pool, encoding, ",", err_enc, NULL);
603             }
604         }
605         else {
606             encoding = apr_table_get(r->err_headers_out, "Content-Encoding");
607         }
608
609         if (r->content_encoding) {
610             encoding = encoding ? apr_pstrcat(r->pool, encoding, ",",
611                                               r->content_encoding, NULL)
612                                 : r->content_encoding;
613         }
614
615         if (encoding) {
616             const char *tmp = encoding;
617
618             token = ap_get_token(r->pool, &tmp, 0);
619             while (token && *token) {
620                 /* stolen from mod_negotiation: */
621                 if (strcmp(token, "identity") && strcmp(token, "7bit") &&
622                     strcmp(token, "8bit") && strcmp(token, "binary")) {
623                     ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
624                                   "Not compressing (content-encoding already "
625                                   " set: %s)", token);
626                     ap_remove_output_filter(f);
627                     return ap_pass_brigade(f->next, bb);
628                 }
629
630                 /* Otherwise, skip token */
631                 if (*tmp) {
632                     ++tmp;
633                 }
634                 token = (*tmp) ? ap_get_token(r->pool, &tmp, 0) : NULL;
635             }
636         }
637
638         /* Even if we don't accept this request based on it not having
639          * the Accept-Encoding, we need to note that we were looking
640          * for this header and downstream proxies should be aware of that.
641          */
642         apr_table_mergen(r->headers_out, "Vary", "Accept-Encoding");
643
644         /* force-gzip will just force it out regardless if the browser
645          * can actually do anything with it.
646          */
647         if (!apr_table_get(r->subprocess_env, "force-gzip")) {
648             const char *accepts;
649             /* if they don't have the line, then they can't play */
650             accepts = apr_table_get(r->headers_in, "Accept-Encoding");
651             if (accepts == NULL) {
652                 ap_remove_output_filter(f);
653                 return ap_pass_brigade(f->next, bb);
654             }
655
656             token = ap_get_token(r->pool, &accepts, 0);
657             while (token && token[0] && strcasecmp(token, "gzip")) {
658                 /* skip parameters, XXX: ;q=foo evaluation? */
659                 while (*accepts == ';') {
660                     ++accepts;
661                     ap_get_token(r->pool, &accepts, 1);
662                 }
663
664                 /* retrieve next token */
665                 if (*accepts == ',') {
666                     ++accepts;
667                 }
668                 token = (*accepts) ? ap_get_token(r->pool, &accepts, 0) : NULL;
669             }
670
671             /* No acceptable token found. */
672             if (token == NULL || token[0] == '\0') {
673                 ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
674                               "Not compressing (no Accept-Encoding: gzip)");
675                 ap_remove_output_filter(f);
676                 return ap_pass_brigade(f->next, bb);
677             }
678         }
679         else {
680             ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
681                           "Forcing compression (force-gzip set)");
682         }
683
684         /* At this point we have decided to filter the content. Let's try to
685          * to initialize zlib (except for 304 responses, where we will only
686          * send out the headers).
687          */
688
689         if (r->status != HTTP_NOT_MODIFIED) {
690             ctx->bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
691             ctx->buffer = apr_palloc(r->pool, c->bufferSize);
692             ctx->libz_end_func = deflateEnd;
693
694             zRC = deflateInit2(&ctx->stream, c->compressionlevel, Z_DEFLATED,
695                                c->windowSize, c->memlevel,
696                                Z_DEFAULT_STRATEGY);
697
698             if (zRC != Z_OK) {
699                 deflateEnd(&ctx->stream);
700                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01383)
701                               "unable to init Zlib: "
702                               "deflateInit2 returned %d: URL %s",
703                               zRC, r->uri);
704                 /*
705                  * Remove ourselves as it does not make sense to return:
706                  * We are not able to init libz and pass data down the chain
707                  * uncompressed.
708                  */
709                 ap_remove_output_filter(f);
710                 return ap_pass_brigade(f->next, bb);
711             }
712             /*
713              * Register a cleanup function to ensure that we cleanup the internal
714              * libz resources.
715              */
716             apr_pool_cleanup_register(r->pool, ctx, deflate_ctx_cleanup,
717                                       apr_pool_cleanup_null);
718
719             /* Set the filter init flag so subsequent invocations know we are
720              * active.
721              */
722             ctx->filter_init = 1;
723         }
724
725         /*
726          * Zlib initialization worked, so we can now change the important
727          * content metadata before sending the response out.
728          */
729
730         /* If the entire Content-Encoding is "identity", we can replace it. */
731         if (!encoding || !strcasecmp(encoding, "identity")) {
732             apr_table_setn(r->headers_out, "Content-Encoding", "gzip");
733         }
734         else {
735             apr_table_mergen(r->headers_out, "Content-Encoding", "gzip");
736         }
737         /* Fix r->content_encoding if it was set before */
738         if (r->content_encoding) {
739             r->content_encoding = apr_table_get(r->headers_out,
740                                                 "Content-Encoding");
741         }
742         apr_table_unset(r->headers_out, "Content-Length");
743         apr_table_unset(r->headers_out, "Content-MD5");
744         if (c->etag_opt != AP_DEFLATE_ETAG_NOCHANGE) {  
745             deflate_check_etag(r, "gzip", c->etag_opt);
746         }
747
748         /* For a 304 response, only change the headers */
749         if (r->status == HTTP_NOT_MODIFIED) {
750             ap_remove_output_filter(f);
751             return ap_pass_brigade(f->next, bb);
752         }
753
754         /* add immortal gzip header */
755         e = apr_bucket_immortal_create(gzip_header, sizeof gzip_header,
756                                        f->c->bucket_alloc);
757         APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
758
759         /* initialize deflate output buffer */
760         ctx->stream.next_out = ctx->buffer;
761         ctx->stream.avail_out = c->bufferSize;
762     } else if (!ctx->filter_init) {
763         /* Hmm.  We've run through the filter init before as we have a ctx,
764          * but we never initialized.  We probably have a dangling ref.  Bail.
765          */
766         return ap_pass_brigade(f->next, bb);
767     }
768
769     while (!APR_BRIGADE_EMPTY(bb))
770     {
771         apr_bucket *b;
772
773         /*
774          * Optimization: If we are a HEAD request and bytes_sent is not zero
775          * it means that we have passed the content-length filter once and
776          * have more data to sent. This means that the content-length filter
777          * could not determine our content-length for the response to the
778          * HEAD request anyway (the associated GET request would deliver the
779          * body in chunked encoding) and we can stop compressing.
780          */
781         if (r->header_only && r->bytes_sent) {
782             ap_remove_output_filter(f);
783             return ap_pass_brigade(f->next, bb);
784         }
785
786         e = APR_BRIGADE_FIRST(bb);
787
788         if (APR_BUCKET_IS_EOS(e)) {
789             char *buf;
790
791             ctx->stream.avail_in = 0; /* should be zero already anyway */
792             /* flush the remaining data from the zlib buffers */
793             flush_libz_buffer(ctx, c, f->c->bucket_alloc, deflate, Z_FINISH,
794                               NO_UPDATE_CRC);
795
796             buf = apr_palloc(r->pool, VALIDATION_SIZE);
797             putLong((unsigned char *)&buf[0], ctx->crc);
798             putLong((unsigned char *)&buf[4], ctx->stream.total_in);
799
800             b = apr_bucket_pool_create(buf, VALIDATION_SIZE, r->pool,
801                                        f->c->bucket_alloc);
802             APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
803             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01384)
804                           "Zlib: Compressed %ld to %ld : URL %s",
805                           ctx->stream.total_in, ctx->stream.total_out, r->uri);
806
807             /* leave notes for logging */
808             if (c->note_input_name) {
809                 apr_table_setn(r->notes, c->note_input_name,
810                                (ctx->stream.total_in > 0)
811                                 ? apr_off_t_toa(r->pool,
812                                                 ctx->stream.total_in)
813                                 : "-");
814             }
815
816             if (c->note_output_name) {
817                 apr_table_setn(r->notes, c->note_output_name,
818                                (ctx->stream.total_in > 0)
819                                 ? apr_off_t_toa(r->pool,
820                                                 ctx->stream.total_out)
821                                 : "-");
822             }
823
824             if (c->note_ratio_name) {
825                 apr_table_setn(r->notes, c->note_ratio_name,
826                                (ctx->stream.total_in > 0)
827                                 ? apr_itoa(r->pool,
828                                            (int)(ctx->stream.total_out
829                                                  * 100
830                                                  / ctx->stream.total_in))
831                                 : "-");
832             }
833
834             deflateEnd(&ctx->stream);
835             /* No need for cleanup any longer */
836             apr_pool_cleanup_kill(r->pool, ctx, deflate_ctx_cleanup);
837
838             /* Remove EOS from the old list, and insert into the new. */
839             APR_BUCKET_REMOVE(e);
840             APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
841
842             /* Okay, we've seen the EOS.
843              * Time to pass it along down the chain.
844              */
845             return ap_pass_brigade(f->next, ctx->bb);
846         }
847
848         if (APR_BUCKET_IS_FLUSH(e)) {
849             apr_status_t rv;
850
851             /* flush the remaining data from the zlib buffers */
852             zRC = flush_libz_buffer(ctx, c, f->c->bucket_alloc, deflate,
853                                     Z_SYNC_FLUSH, NO_UPDATE_CRC);
854             if (zRC != Z_OK) {
855                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01385)
856                               "Zlib error %d flushing zlib output buffer (%s)",
857                               zRC, ctx->stream.msg);
858                 return APR_EGENERAL;
859             }
860
861             /* Remove flush bucket from old brigade anf insert into the new. */
862             APR_BUCKET_REMOVE(e);
863             APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
864             rv = ap_pass_brigade(f->next, ctx->bb);
865             if (rv != APR_SUCCESS) {
866                 return rv;
867             }
868             continue;
869         }
870
871         if (APR_BUCKET_IS_METADATA(e)) {
872             /*
873              * Remove meta data bucket from old brigade and insert into the
874              * new.
875              */
876             APR_BUCKET_REMOVE(e);
877             APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
878             continue;
879         }
880
881         /* read */
882         apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
883         if (!len) {
884             apr_bucket_delete(e);
885             continue;
886         }
887         if (len > INT_MAX) {
888             apr_bucket_split(e, INT_MAX);
889             apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
890         }
891
892         /* This crc32 function is from zlib. */
893         ctx->crc = crc32(ctx->crc, (const Bytef *)data, len);
894
895         /* write */
896         ctx->stream.next_in = (unsigned char *)data; /* We just lost const-ness,
897                                                       * but we'll just have to
898                                                       * trust zlib */
899         ctx->stream.avail_in = len;
900
901         while (ctx->stream.avail_in != 0) {
902             if (ctx->stream.avail_out == 0) {
903                 apr_status_t rv;
904
905                 ctx->stream.next_out = ctx->buffer;
906                 len = c->bufferSize - ctx->stream.avail_out;
907
908                 b = apr_bucket_heap_create((char *)ctx->buffer, len,
909                                            NULL, f->c->bucket_alloc);
910                 APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
911                 ctx->stream.avail_out = c->bufferSize;
912                 /* Send what we have right now to the next filter. */
913                 rv = ap_pass_brigade(f->next, ctx->bb);
914                 if (rv != APR_SUCCESS) {
915                     return rv;
916                 }
917             }
918
919             zRC = deflate(&(ctx->stream), Z_NO_FLUSH);
920
921             if (zRC != Z_OK) {
922                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01386)
923                               "Zlib error %d deflating data (%s)", zRC,
924                               ctx->stream.msg);
925                 return APR_EGENERAL;
926             }
927         }
928
929         apr_bucket_delete(e);
930     }
931
932     apr_brigade_cleanup(bb);
933     return APR_SUCCESS;
934 }
935
936 static apr_status_t consume_zlib_flags(deflate_ctx *ctx,
937                                        const char **data, apr_size_t *len)
938 {
939     if ((ctx->zlib_flags & EXTRA_FIELD)) {
940         /* Consume 2 bytes length prefixed data. */
941         if (ctx->consume_pos == 0) {
942             if (!*len) {
943                 return APR_INCOMPLETE;
944             }
945             ctx->consume_len = (unsigned int)**data;
946             ctx->consume_pos++;
947             ++*data;
948             --*len;
949         }
950         if (ctx->consume_pos == 1) {
951             if (!*len) {
952                 return APR_INCOMPLETE;
953             }
954             ctx->consume_len += ((unsigned int)**data) << 8;
955             ctx->consume_pos++;
956             ++*data;
957             --*len;
958         }
959         if (*len < ctx->consume_len) {
960             ctx->consume_len -= *len;
961             *len = 0;
962             return APR_INCOMPLETE;
963         }
964         *data += ctx->consume_len;
965         *len -= ctx->consume_len;
966
967         ctx->consume_len = ctx->consume_pos = 0;
968         ctx->zlib_flags &= ~EXTRA_FIELD;
969     }
970
971     if ((ctx->zlib_flags & ORIG_NAME)) {
972         /* Consume nul terminated string. */
973         while (*len && **data) {
974             ++*data;
975             --*len;
976         }
977         if (!*len) {
978             return APR_INCOMPLETE;
979         }
980         /* .. and nul. */
981         ++*data;
982         --*len;
983
984         ctx->zlib_flags &= ~ORIG_NAME;
985     }
986
987     if ((ctx->zlib_flags & COMMENT)) {
988         /* Consume nul terminated string. */
989         while (*len && **data) {
990             ++*data;
991             --*len;
992         }
993         if (!*len) {
994             return APR_INCOMPLETE;
995         }
996         /* .. and nul. */
997         ++*data;
998         --*len;
999
1000         ctx->zlib_flags &= ~COMMENT;
1001     }
1002
1003     if ((ctx->zlib_flags & HEAD_CRC)) {
1004         /* Consume CRC16 (2 octets). */
1005         if (ctx->consume_pos == 0) {
1006             if (!*len) {
1007                 return APR_INCOMPLETE;
1008             }
1009             ctx->consume_pos++;
1010             ++*data;
1011             --*len;
1012         }
1013         if (!*len) {
1014             return APR_INCOMPLETE;
1015         }
1016         ++*data;
1017         --*len;
1018         
1019         ctx->consume_pos = 0;
1020         ctx->zlib_flags &= ~HEAD_CRC;
1021     }
1022
1023     return APR_SUCCESS;
1024 }
1025
1026 /* This is the deflate input filter (inflates).  */
1027 static apr_status_t deflate_in_filter(ap_filter_t *f,
1028                                       apr_bucket_brigade *bb,
1029                                       ap_input_mode_t mode,
1030                                       apr_read_type_e block,
1031                                       apr_off_t readbytes)
1032 {
1033     apr_bucket *bkt;
1034     request_rec *r = f->r;
1035     deflate_ctx *ctx = f->ctx;
1036     int zRC;
1037     apr_status_t rv;
1038     deflate_filter_config *c;
1039
1040     /* just get out of the way of things we don't want. */
1041     if (mode != AP_MODE_READBYTES) {
1042         return ap_get_brigade(f->next, bb, mode, block, readbytes);
1043     }
1044
1045     c = ap_get_module_config(r->server->module_config, &deflate_module);
1046
1047     if (!ctx || ctx->header_len < sizeof(ctx->header)) {
1048         apr_size_t len;
1049
1050         if (!ctx) {
1051             /* only work on main request/no subrequests */
1052             if (!ap_is_initial_req(r)) {
1053                 ap_remove_input_filter(f);
1054                 return ap_get_brigade(f->next, bb, mode, block, readbytes);
1055             }
1056
1057             /* We can't operate on Content-Ranges */
1058             if (apr_table_get(r->headers_in, "Content-Range") != NULL) {
1059                 ap_remove_input_filter(f);
1060                 return ap_get_brigade(f->next, bb, mode, block, readbytes);
1061             }
1062
1063             /* Check whether request body is gzipped.
1064              *
1065              * If it is, we're transforming the contents, invalidating
1066              * some request headers including Content-Encoding.
1067              *
1068              * If not, we just remove ourself.
1069              */
1070             if (check_gzip(r, r->headers_in, NULL) == 0) {
1071                 ap_remove_input_filter(f);
1072                 return ap_get_brigade(f->next, bb, mode, block, readbytes);
1073             }
1074
1075             f->ctx = ctx = apr_pcalloc(f->r->pool, sizeof(*ctx));
1076             ctx->bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
1077             ctx->proc_bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
1078             ctx->buffer = apr_palloc(r->pool, c->bufferSize);
1079         }
1080
1081         do {
1082             apr_brigade_cleanup(ctx->bb);
1083
1084             len = sizeof(ctx->header) - ctx->header_len;
1085             rv = ap_get_brigade(f->next, ctx->bb, AP_MODE_READBYTES, block,
1086                                 len);
1087
1088             /* ap_get_brigade may return success with an empty brigade for
1089              * a non-blocking read which would block (an empty brigade for
1090              * a blocking read is an issue which is simply forwarded here).
1091              */
1092             if (rv != APR_SUCCESS || APR_BRIGADE_EMPTY(ctx->bb)) {
1093                 return rv;
1094             }
1095
1096             /* zero length body? step aside */
1097             bkt = APR_BRIGADE_FIRST(ctx->bb);
1098             if (APR_BUCKET_IS_EOS(bkt)) {
1099                 if (ctx->header_len) {
1100                     /* If the header was (partially) read it's an error, this
1101                      * is not a gzip Content-Encoding, as claimed.
1102                      */
1103                     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO()
1104                                   "Encountered premature end-of-stream while "
1105                                   "reading inflate header");
1106                     return APR_EGENERAL;
1107                 }
1108                 APR_BUCKET_REMOVE(bkt);
1109                 APR_BRIGADE_INSERT_TAIL(bb, bkt);
1110                 ap_remove_input_filter(f);
1111                 return APR_SUCCESS;
1112             }
1113
1114             rv = apr_brigade_flatten(ctx->bb,
1115                                      ctx->header + ctx->header_len, &len);
1116             if (rv != APR_SUCCESS) {
1117                 return rv;
1118             }
1119             if (len && !ctx->header_len) {
1120                 apr_table_unset(r->headers_in, "Content-Length");
1121                 apr_table_unset(r->headers_in, "Content-MD5");
1122             }
1123             ctx->header_len += len;
1124
1125         } while (ctx->header_len < sizeof(ctx->header));
1126
1127         /* We didn't get the magic bytes. */
1128         if (ctx->header[0] != deflate_magic[0] ||
1129             ctx->header[1] != deflate_magic[1]) {
1130             ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01387)
1131                           "Zlib: Invalid header");
1132             return APR_EGENERAL;
1133         }
1134
1135         ctx->zlib_flags = ctx->header[3];
1136         if ((ctx->zlib_flags & RESERVED)) {
1137             ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01388)
1138                           "Zlib: Invalid flags %02x", ctx->zlib_flags);
1139             return APR_EGENERAL;
1140         }
1141
1142         zRC = inflateInit2(&ctx->stream, c->windowSize);
1143
1144         if (zRC != Z_OK) {
1145             f->ctx = NULL;
1146             inflateEnd(&ctx->stream);
1147             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01389)
1148                           "unable to init Zlib: "
1149                           "inflateInit2 returned %d: URL %s",
1150                           zRC, r->uri);
1151             ap_remove_input_filter(f);
1152             return ap_get_brigade(f->next, bb, mode, block, readbytes);
1153         }
1154
1155         /* initialize deflate output buffer */
1156         ctx->stream.next_out = ctx->buffer;
1157         ctx->stream.avail_out = c->bufferSize;
1158
1159         apr_brigade_cleanup(ctx->bb);
1160     }
1161
1162     if (APR_BRIGADE_EMPTY(ctx->proc_bb)) {
1163         rv = ap_get_brigade(f->next, ctx->bb, mode, block, readbytes);
1164
1165         /* Don't terminate on EAGAIN (or success with an empty brigade in
1166          * non-blocking mode), just return focus.
1167          */
1168         if (block == APR_NONBLOCK_READ
1169                 && (APR_STATUS_IS_EAGAIN(rv)
1170                     || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(ctx->bb)))) {
1171             return rv;
1172         }
1173         if (rv != APR_SUCCESS) {
1174             inflateEnd(&ctx->stream);
1175             return rv;
1176         }
1177
1178         for (bkt = APR_BRIGADE_FIRST(ctx->bb);
1179              bkt != APR_BRIGADE_SENTINEL(ctx->bb);
1180              bkt = APR_BUCKET_NEXT(bkt))
1181         {
1182             const char *data;
1183             apr_size_t len;
1184
1185             if (APR_BUCKET_IS_EOS(bkt)) {
1186                 if (!ctx->done) {
1187                     inflateEnd(&ctx->stream);
1188                     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02481)
1189                                   "Encountered premature end-of-stream while inflating");
1190                     return APR_EGENERAL;
1191                 }
1192
1193                 /* Move everything to the returning brigade. */
1194                 APR_BUCKET_REMOVE(bkt);
1195                 APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, bkt);
1196                 ap_remove_input_filter(f);
1197                 break;
1198             }
1199
1200             if (APR_BUCKET_IS_FLUSH(bkt)) {
1201                 apr_bucket *tmp_heap;
1202                 zRC = inflate(&(ctx->stream), Z_SYNC_FLUSH);
1203                 if (zRC != Z_OK) {
1204                     inflateEnd(&ctx->stream);
1205                     ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01391)
1206                                   "Zlib error %d inflating data (%s)", zRC,
1207                                   ctx->stream.msg);
1208                     return APR_EGENERAL;
1209                 }
1210
1211                 ctx->stream.next_out = ctx->buffer;
1212                 len = c->bufferSize - ctx->stream.avail_out;
1213
1214                 ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
1215                 tmp_heap = apr_bucket_heap_create((char *)ctx->buffer, len,
1216                                                  NULL, f->c->bucket_alloc);
1217                 APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, tmp_heap);
1218                 ctx->stream.avail_out = c->bufferSize;
1219
1220                 /* Move everything to the returning brigade. */
1221                 APR_BUCKET_REMOVE(bkt);
1222                 APR_BRIGADE_CONCAT(bb, ctx->bb);
1223                 break;
1224             }
1225
1226             /* sanity check - data after completed compressed body and before eos? */
1227             if (ctx->done) {
1228                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02482)
1229                               "Encountered extra data after compressed data");
1230                 return APR_EGENERAL;
1231             }
1232
1233             /* read */
1234             apr_bucket_read(bkt, &data, &len, APR_BLOCK_READ);
1235             if (!len) {
1236                 continue;
1237             }
1238             if (len > INT_MAX) {
1239                 apr_bucket_split(bkt, INT_MAX);
1240                 apr_bucket_read(bkt, &data, &len, APR_BLOCK_READ);
1241             }
1242
1243             if (ctx->zlib_flags) {
1244                 rv = consume_zlib_flags(ctx, &data, &len);
1245                 if (rv == APR_SUCCESS) {
1246                     ctx->zlib_flags = 0;
1247                 }
1248                 if (!len) {
1249                     continue;
1250                 }
1251             }
1252
1253             /* pass through zlib inflate. */
1254             ctx->stream.next_in = (unsigned char *)data;
1255             ctx->stream.avail_in = (int)len;
1256
1257             zRC = Z_OK;
1258
1259             if (!ctx->validation_buffer) {
1260                 while (ctx->stream.avail_in != 0) {
1261                     if (ctx->stream.avail_out == 0) {
1262                         apr_bucket *tmp_heap;
1263                         ctx->stream.next_out = ctx->buffer;
1264                         len = c->bufferSize - ctx->stream.avail_out;
1265
1266                         ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
1267                         tmp_heap = apr_bucket_heap_create((char *)ctx->buffer, len,
1268                                                           NULL, f->c->bucket_alloc);
1269                         APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, tmp_heap);
1270                         ctx->stream.avail_out = c->bufferSize;
1271                     }
1272
1273                     zRC = inflate(&ctx->stream, Z_NO_FLUSH);
1274
1275                     if (zRC == Z_STREAM_END) {
1276                         ctx->validation_buffer = apr_pcalloc(r->pool,
1277                                                              VALIDATION_SIZE);
1278                         ctx->validation_buffer_length = 0;
1279                         break;
1280                     }
1281
1282                     if (zRC != Z_OK) {
1283                         inflateEnd(&ctx->stream);
1284                         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01392)
1285                                       "Zlib error %d inflating data (%s)", zRC,
1286                                       ctx->stream.msg);
1287                         return APR_EGENERAL;
1288                     }
1289                 }
1290             }
1291
1292             if (ctx->validation_buffer) {
1293                 apr_bucket *tmp_heap;
1294                 apr_size_t avail, valid;
1295                 unsigned char *buf = ctx->validation_buffer;
1296
1297                 avail = ctx->stream.avail_in;
1298                 valid = (apr_size_t)VALIDATION_SIZE -
1299                          ctx->validation_buffer_length;
1300
1301                 /*
1302                  * We have inflated all data. Now try to capture the
1303                  * validation bytes. We may not have them all available
1304                  * right now, but capture what is there.
1305                  */
1306                 if (avail < valid) {
1307                     memcpy(buf + ctx->validation_buffer_length,
1308                            ctx->stream.next_in, avail);
1309                     ctx->validation_buffer_length += avail;
1310                     continue;
1311                 }
1312                 memcpy(buf + ctx->validation_buffer_length,
1313                        ctx->stream.next_in, valid);
1314                 ctx->validation_buffer_length += valid;
1315
1316                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01393)
1317                               "Zlib: Inflated %ld to %ld : URL %s",
1318                               ctx->stream.total_in, ctx->stream.total_out,
1319                               r->uri);
1320
1321                 len = c->bufferSize - ctx->stream.avail_out;
1322
1323                 ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
1324                 tmp_heap = apr_bucket_heap_create((char *)ctx->buffer, len,
1325                                                   NULL, f->c->bucket_alloc);
1326                 APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, tmp_heap);
1327                 ctx->stream.avail_out = c->bufferSize;
1328
1329                 {
1330                     unsigned long compCRC, compLen;
1331                     compCRC = getLong(buf);
1332                     if (ctx->crc != compCRC) {
1333                         inflateEnd(&ctx->stream);
1334                         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01394)
1335                                       "Zlib: CRC error inflating data");
1336                         return APR_EGENERAL;
1337                     }
1338                     compLen = getLong(buf + VALIDATION_SIZE / 2);
1339                     /* gzip stores original size only as 4 byte value */
1340                     if ((ctx->stream.total_out & 0xFFFFFFFF) != compLen) {
1341                         inflateEnd(&ctx->stream);
1342                         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01395)
1343                                       "Zlib: Length %ld of inflated data does "
1344                                       "not match expected value %ld",
1345                                       ctx->stream.total_out, compLen);
1346                         return APR_EGENERAL;
1347                     }
1348                 }
1349
1350                 inflateEnd(&ctx->stream);
1351
1352                 ctx->done = 1;
1353
1354                 /* Did we have trailing data behind the closing 8 bytes? */
1355                 if (avail > valid) {
1356                     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02485)
1357                                   "Encountered extra data after compressed data");
1358                     return APR_EGENERAL;
1359                 }
1360             }
1361
1362         }
1363         apr_brigade_cleanup(ctx->bb);
1364     }
1365
1366     /* If we are about to return nothing for a 'blocking' read and we have
1367      * some data in our zlib buffer, flush it out so we can return something.
1368      */
1369     if (block == APR_BLOCK_READ &&
1370         APR_BRIGADE_EMPTY(ctx->proc_bb) &&
1371         ctx->stream.avail_out < c->bufferSize) {
1372         apr_bucket *tmp_heap;
1373         apr_size_t len;
1374         ctx->stream.next_out = ctx->buffer;
1375         len = c->bufferSize - ctx->stream.avail_out;
1376
1377         ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
1378         tmp_heap = apr_bucket_heap_create((char *)ctx->buffer, len,
1379                                           NULL, f->c->bucket_alloc);
1380         APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, tmp_heap);
1381         ctx->stream.avail_out = c->bufferSize;
1382     }
1383
1384     if (!APR_BRIGADE_EMPTY(ctx->proc_bb)) {
1385         if (apr_brigade_partition(ctx->proc_bb, readbytes, &bkt) == APR_INCOMPLETE) {
1386             APR_BRIGADE_CONCAT(bb, ctx->proc_bb);
1387         }
1388         else {
1389             APR_BRIGADE_CONCAT(bb, ctx->proc_bb);
1390             apr_brigade_split_ex(bb, bkt, ctx->proc_bb);
1391         }
1392     }
1393
1394     return APR_SUCCESS;
1395 }
1396
1397
1398 /* Filter to inflate for a content-transforming proxy.  */
1399 static apr_status_t inflate_out_filter(ap_filter_t *f,
1400                                       apr_bucket_brigade *bb)
1401 {
1402     apr_bucket *e;
1403     request_rec *r = f->r;
1404     deflate_ctx *ctx = f->ctx;
1405     int zRC;
1406     apr_status_t rv;
1407     deflate_filter_config *c;
1408
1409     /* Do nothing if asked to filter nothing. */
1410     if (APR_BRIGADE_EMPTY(bb)) {
1411         return APR_SUCCESS;
1412     }
1413
1414     c = ap_get_module_config(r->server->module_config, &deflate_module);
1415
1416     if (!ctx) {
1417
1418         /*
1419          * Only work on main request, not subrequests,
1420          * that are not a 204 response with no content
1421          * and not a partial response to a Range request,
1422          * and only when Content-Encoding ends in gzip.
1423          */
1424         if (!ap_is_initial_req(r) || (r->status == HTTP_NO_CONTENT) ||
1425             (apr_table_get(r->headers_out, "Content-Range") != NULL) ||
1426             (check_gzip(r, r->headers_out, r->err_headers_out) == 0)
1427            ) {
1428             ap_remove_output_filter(f);
1429             return ap_pass_brigade(f->next, bb);
1430         }
1431
1432         /*
1433          * At this point we have decided to filter the content, so change
1434          * important content metadata before sending any response out.
1435          * Content-Encoding was already reset by the check_gzip() call.
1436          */
1437         apr_table_unset(r->headers_out, "Content-Length");
1438         apr_table_unset(r->headers_out, "Content-MD5");
1439         if (c->etag_opt != AP_DEFLATE_ETAG_NOCHANGE) {
1440             deflate_check_etag(r, "gunzip", c->etag_opt);
1441         }
1442
1443         /* For a 304 response, only change the headers */
1444         if (r->status == HTTP_NOT_MODIFIED) {
1445             ap_remove_output_filter(f);
1446             return ap_pass_brigade(f->next, bb);
1447         }
1448
1449         f->ctx = ctx = apr_pcalloc(f->r->pool, sizeof(*ctx));
1450         ctx->bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
1451         ctx->buffer = apr_palloc(r->pool, c->bufferSize);
1452         ctx->libz_end_func = inflateEnd;
1453         ctx->validation_buffer = NULL;
1454         ctx->validation_buffer_length = 0;
1455
1456         zRC = inflateInit2(&ctx->stream, c->windowSize);
1457
1458         if (zRC != Z_OK) {
1459             f->ctx = NULL;
1460             inflateEnd(&ctx->stream);
1461             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01397)
1462                           "unable to init Zlib: "
1463                           "inflateInit2 returned %d: URL %s",
1464                           zRC, r->uri);
1465             /*
1466              * Remove ourselves as it does not make sense to return:
1467              * We are not able to init libz and pass data down the chain
1468              * compressed.
1469              */
1470             ap_remove_output_filter(f);
1471             return ap_pass_brigade(f->next, bb);
1472         }
1473
1474         /*
1475          * Register a cleanup function to ensure that we cleanup the internal
1476          * libz resources.
1477          */
1478         apr_pool_cleanup_register(r->pool, ctx, deflate_ctx_cleanup,
1479                                   apr_pool_cleanup_null);
1480
1481         /* initialize inflate output buffer */
1482         ctx->stream.next_out = ctx->buffer;
1483         ctx->stream.avail_out = c->bufferSize;
1484     }
1485
1486     while (!APR_BRIGADE_EMPTY(bb))
1487     {
1488         const char *data;
1489         apr_bucket *b;
1490         apr_size_t len;
1491
1492         e = APR_BRIGADE_FIRST(bb);
1493
1494         if (APR_BUCKET_IS_EOS(e)) {
1495             /*
1496              * We are really done now. Ensure that we never return here, even
1497              * if a second EOS bucket falls down the chain. Thus remove
1498              * ourselves.
1499              */
1500             ap_remove_output_filter(f);
1501             /* should be zero already anyway */
1502             ctx->stream.avail_in = 0;
1503             /*
1504              * Flush the remaining data from the zlib buffers. It is correct
1505              * to use Z_SYNC_FLUSH in this case and not Z_FINISH as in the
1506              * deflate case. In the inflate case Z_FINISH requires to have a
1507              * large enough output buffer to put ALL data in otherwise it
1508              * fails, whereas in the deflate case you can empty a filled output
1509              * buffer and call it again until no more output can be created.
1510              */
1511             flush_libz_buffer(ctx, c, f->c->bucket_alloc, inflate, Z_SYNC_FLUSH,
1512                               UPDATE_CRC);
1513             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01398)
1514                           "Zlib: Inflated %ld to %ld : URL %s",
1515                           ctx->stream.total_in, ctx->stream.total_out, r->uri);
1516
1517             if (ctx->validation_buffer_length == VALIDATION_SIZE) {
1518                 unsigned long compCRC, compLen;
1519                 compCRC = getLong(ctx->validation_buffer);
1520                 if (ctx->crc != compCRC) {
1521                     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01399)
1522                                   "Zlib: Checksum of inflated stream invalid");
1523                     return APR_EGENERAL;
1524                 }
1525                 ctx->validation_buffer += VALIDATION_SIZE / 2;
1526                 compLen = getLong(ctx->validation_buffer);
1527                 /* gzip stores original size only as 4 byte value */
1528                 if ((ctx->stream.total_out & 0xFFFFFFFF) != compLen) {
1529                     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01400)
1530                                   "Zlib: Length of inflated stream invalid");
1531                     return APR_EGENERAL;
1532                 }
1533             }
1534             else {
1535                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01401)
1536                               "Zlib: Validation bytes not present");
1537                 return APR_EGENERAL;
1538             }
1539
1540             inflateEnd(&ctx->stream);
1541             /* No need for cleanup any longer */
1542             apr_pool_cleanup_kill(r->pool, ctx, deflate_ctx_cleanup);
1543
1544             /* Remove EOS from the old list, and insert into the new. */
1545             APR_BUCKET_REMOVE(e);
1546             APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
1547
1548             /*
1549              * Okay, we've seen the EOS.
1550              * Time to pass it along down the chain.
1551              */
1552             return ap_pass_brigade(f->next, ctx->bb);
1553         }
1554
1555         if (APR_BUCKET_IS_FLUSH(e)) {
1556             apr_status_t rv;
1557
1558             /* flush the remaining data from the zlib buffers */
1559             zRC = flush_libz_buffer(ctx, c, f->c->bucket_alloc, inflate,
1560                                     Z_SYNC_FLUSH, UPDATE_CRC);
1561             if (zRC == Z_STREAM_END) {
1562                 if (ctx->validation_buffer == NULL) {
1563                     ctx->validation_buffer = apr_pcalloc(f->r->pool,
1564                                                          VALIDATION_SIZE);
1565                 }
1566             }
1567             else if (zRC != Z_OK) {
1568                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01402)
1569                               "Zlib error %d flushing inflate buffer (%s)",
1570                               zRC, ctx->stream.msg);
1571                 return APR_EGENERAL;
1572             }
1573
1574             /* Remove flush bucket from old brigade anf insert into the new. */
1575             APR_BUCKET_REMOVE(e);
1576             APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
1577             rv = ap_pass_brigade(f->next, ctx->bb);
1578             if (rv != APR_SUCCESS) {
1579                 return rv;
1580             }
1581             continue;
1582         }
1583
1584         if (APR_BUCKET_IS_METADATA(e)) {
1585             /*
1586              * Remove meta data bucket from old brigade and insert into the
1587              * new.
1588              */
1589             APR_BUCKET_REMOVE(e);
1590             APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
1591             continue;
1592         }
1593
1594         /* read */
1595         apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
1596         if (!len) {
1597             apr_bucket_delete(e);
1598             continue;
1599         }
1600         if (len > INT_MAX) {
1601             apr_bucket_split(e, INT_MAX);
1602             apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
1603         }
1604
1605         /* first bucket contains zlib header */
1606         if (ctx->header_len < sizeof(ctx->header)) {
1607             apr_size_t rem;
1608
1609             rem = sizeof(ctx->header) - ctx->header_len;
1610             if (len < rem) {
1611                 memcpy(ctx->header + ctx->header_len, data, len);
1612                 ctx->header_len += len;
1613                 apr_bucket_delete(e);
1614                 continue;
1615             }
1616             memcpy(ctx->header + ctx->header_len, data, rem);
1617             ctx->header_len += rem;
1618             {
1619                 int zlib_method;
1620                 zlib_method = ctx->header[2];
1621                 if (zlib_method != Z_DEFLATED) {
1622                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01404)
1623                                   "inflate: data not deflated!");
1624                     ap_remove_output_filter(f);
1625                     return ap_pass_brigade(f->next, bb);
1626                 }
1627                 if (ctx->header[0] != deflate_magic[0] ||
1628                     ctx->header[1] != deflate_magic[1]) {
1629                         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01405)
1630                                       "inflate: bad header");
1631                     return APR_EGENERAL ;
1632                 }
1633                 ctx->zlib_flags = ctx->header[3];
1634                 if ((ctx->zlib_flags & RESERVED)) {
1635                     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO()
1636                                   "inflate: bad flags %02x",
1637                                   ctx->zlib_flags);
1638                     return APR_EGENERAL;
1639                 }
1640             }
1641             if (len == rem) {
1642                 apr_bucket_delete(e);
1643                 continue;
1644             }
1645             data += rem;
1646             len -= rem;
1647         }
1648
1649         if (ctx->zlib_flags) {
1650             rv = consume_zlib_flags(ctx, &data, &len);
1651             if (rv == APR_SUCCESS) {
1652                 ctx->zlib_flags = 0;
1653             }
1654             if (!len) {
1655                 apr_bucket_delete(e);
1656                 continue;
1657             }
1658         }
1659
1660         /* pass through zlib inflate. */
1661         ctx->stream.next_in = (unsigned char *)data;
1662         ctx->stream.avail_in = len;
1663
1664         if (ctx->validation_buffer) {
1665             if (ctx->validation_buffer_length < VALIDATION_SIZE) {
1666                 apr_size_t copy_size;
1667
1668                 copy_size = VALIDATION_SIZE - ctx->validation_buffer_length;
1669                 if (copy_size > ctx->stream.avail_in)
1670                     copy_size = ctx->stream.avail_in;
1671                 memcpy(ctx->validation_buffer + ctx->validation_buffer_length,
1672                        ctx->stream.next_in, copy_size);
1673                 /* Saved copy_size bytes */
1674                 ctx->stream.avail_in -= copy_size;
1675                 ctx->validation_buffer_length += copy_size;
1676             }
1677             if (ctx->stream.avail_in) {
1678                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01407)
1679                               "Zlib: %d bytes of garbage at the end of "
1680                               "compressed stream.", ctx->stream.avail_in);
1681                 /*
1682                  * There is nothing worth consuming for zlib left, because it is
1683                  * either garbage data or the data has been copied to the
1684                  * validation buffer (processing validation data is no business
1685                  * for zlib). So set ctx->stream.avail_in to zero to indicate
1686                  * this to the following while loop.
1687                  */
1688                 ctx->stream.avail_in = 0;
1689             }
1690         }
1691
1692         while (ctx->stream.avail_in != 0) {
1693             if (ctx->stream.avail_out == 0) {
1694
1695                 ctx->stream.next_out = ctx->buffer;
1696                 len = c->bufferSize - ctx->stream.avail_out;
1697
1698                 ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
1699                 b = apr_bucket_heap_create((char *)ctx->buffer, len,
1700                                            NULL, f->c->bucket_alloc);
1701                 APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
1702                 ctx->stream.avail_out = c->bufferSize;
1703                 /* Send what we have right now to the next filter. */
1704                 rv = ap_pass_brigade(f->next, ctx->bb);
1705                 if (rv != APR_SUCCESS) {
1706                     return rv;
1707                 }
1708             }
1709
1710             zRC = inflate(&ctx->stream, Z_NO_FLUSH);
1711
1712             if (zRC == Z_STREAM_END) {
1713                 /*
1714                  * We have inflated all data. Now try to capture the
1715                  * validation bytes. We may not have them all available
1716                  * right now, but capture what is there.
1717                  */
1718                 ctx->validation_buffer = apr_pcalloc(f->r->pool,
1719                                                      VALIDATION_SIZE);
1720                 if (ctx->stream.avail_in > VALIDATION_SIZE) {
1721                     ctx->validation_buffer_length = VALIDATION_SIZE;
1722                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01408)
1723                                   "Zlib: %d bytes of garbage at the end of "
1724                                   "compressed stream.",
1725                                   ctx->stream.avail_in - VALIDATION_SIZE);
1726                 } else if (ctx->stream.avail_in > 0) {
1727                            ctx->validation_buffer_length = ctx->stream.avail_in;
1728                 }
1729                 if (ctx->validation_buffer_length)
1730                     memcpy(ctx->validation_buffer, ctx->stream.next_in,
1731                            ctx->validation_buffer_length);
1732                 break;
1733             }
1734
1735             if (zRC != Z_OK) {
1736                 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01409)
1737                               "Zlib error %d inflating data (%s)", zRC,
1738                               ctx->stream.msg);
1739                 return APR_EGENERAL;
1740             }
1741         }
1742
1743         apr_bucket_delete(e);
1744     }
1745
1746     apr_brigade_cleanup(bb);
1747     return APR_SUCCESS;
1748 }
1749
1750 static int mod_deflate_post_config(apr_pool_t *pconf, apr_pool_t *plog,
1751                                    apr_pool_t *ptemp, server_rec *s)
1752 {
1753     mod_deflate_ssl_var = APR_RETRIEVE_OPTIONAL_FN(ssl_var_lookup);
1754     return OK;
1755 }
1756
1757
1758 #define PROTO_FLAGS AP_FILTER_PROTO_CHANGE|AP_FILTER_PROTO_CHANGE_LENGTH
1759 static void register_hooks(apr_pool_t *p)
1760 {
1761     ap_register_output_filter(deflateFilterName, deflate_out_filter, NULL,
1762                               AP_FTYPE_CONTENT_SET);
1763     ap_register_output_filter("INFLATE", inflate_out_filter, NULL,
1764                               AP_FTYPE_RESOURCE-1);
1765     ap_register_input_filter(deflateFilterName, deflate_in_filter, NULL,
1766                               AP_FTYPE_CONTENT_SET);
1767     ap_hook_post_config(mod_deflate_post_config, NULL, NULL, APR_HOOK_MIDDLE);
1768 }
1769
1770 static const command_rec deflate_filter_cmds[] = {
1771     AP_INIT_TAKE12("DeflateFilterNote", deflate_set_note, NULL, RSRC_CONF,
1772                   "Set a note to report on compression ratio"),
1773     AP_INIT_TAKE1("DeflateWindowSize", deflate_set_window_size, NULL,
1774                   RSRC_CONF, "Set the Deflate window size (1-15)"),
1775     AP_INIT_TAKE1("DeflateBufferSize", deflate_set_buffer_size, NULL, RSRC_CONF,
1776                   "Set the Deflate Buffer Size"),
1777     AP_INIT_TAKE1("DeflateMemLevel", deflate_set_memlevel, NULL, RSRC_CONF,
1778                   "Set the Deflate Memory Level (1-9)"),
1779     AP_INIT_TAKE1("DeflateCompressionLevel", deflate_set_compressionlevel, NULL, RSRC_CONF,
1780                   "Set the Deflate Compression Level (1-9)"),
1781     AP_INIT_TAKE1("DeflateAlterEtag", deflate_set_etag, NULL, RSRC_CONF,
1782                   "Set how mod_deflate should modify ETAG response headers: 'AddSuffix' (default), 'NoChange' (2.2.x behavior), 'Remove'"),
1783  
1784     {NULL}
1785 };
1786
1787 /* zlib can be built with #define deflate z_deflate */
1788 #ifdef deflate
1789 #undef deflate
1790 #endif
1791 AP_DECLARE_MODULE(deflate) = {
1792     STANDARD20_MODULE_STUFF,
1793     NULL,                         /* dir config creater */
1794     NULL,                         /* dir merger --- default is to override */
1795     create_deflate_server_config, /* server config */
1796     NULL,                         /* merge server config */
1797     deflate_filter_cmds,          /* command table */
1798     register_hooks                /* register hooks */
1799 };