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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * mod_deflate.c: Perform deflate content-encoding on the fly
20 * Written by Ian Holsman, Justin Erenkrantz, and Nick Kew
24 * Portions of this software are based upon zlib code by Jean-loup Gailly
25 * (zlib functions gz_open and gzwrite, check_header)
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 */
38 #include "http_config.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
52 #include <limits.h> /* for INT_MAX */
54 static const char deflateFilterName[] = "DEFLATE";
55 module AP_MODULE_DECLARE_DATA deflate_module;
57 #define AP_DEFLATE_ETAG_ADDSUFFIX 0
58 #define AP_DEFLATE_ETAG_NOCHANGE 1
59 #define AP_DEFLATE_ETAG_REMOVE 2
61 typedef struct deflate_filter_config_t
66 apr_size_t bufferSize;
67 char *note_ratio_name;
68 char *note_input_name;
69 char *note_output_name;
71 } deflate_filter_config;
73 /* RFC 1952 Section 2.3 defines the gzip header:
75 * +---+---+---+---+---+---+---+---+---+---+
76 * |ID1|ID2|CM |FLG| MTIME |XFL|OS |
77 * +---+---+---+---+---+---+---+---+---+---+
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 */
86 static const char deflate_magic[2] = { '\037', '\213' };
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
94 static APR_OPTIONAL_FN_TYPE(ssl_var_lookup) *mod_deflate_ssl_var = NULL;
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.
100 static int check_gzip(request_rec *r, apr_table_t *hdrs1, apr_table_t *hdrs2)
103 apr_table_t *hdrs = hdrs1;
104 const char *encoding = apr_table_get(hdrs, "Content-Encoding");
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");
111 encoding = r->content_encoding;
115 if (encoding && *encoding) {
117 /* check the usual/simple case first */
118 if (!strcasecmp(encoding, "gzip")
119 || !strcasecmp(encoding, "x-gzip")) {
122 apr_table_unset(hdrs, "Content-Encoding");
125 r->content_encoding = NULL;
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
132 char *new_encoding = apr_pstrdup(r->pool, encoding);
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")) {
141 apr_table_unset(hdrs, "Content-Encoding");
144 r->content_encoding = NULL;
147 break; /* seen all tokens */
149 for (ptr=token+1; apr_isspace(*ptr); ++ptr);
150 if (!strcasecmp(ptr, "gzip")
151 || !strcasecmp(ptr, "x-gzip")) {
154 apr_table_setn(hdrs, "Content-Encoding", new_encoding);
157 r->content_encoding = new_encoding;
161 else if (!ptr[0] || !strcasecmp(ptr, "identity")) {
163 continue; /* strip the token and find the next one */
165 break; /* found a non-identity token */
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.
175 if (hdrs && r->content_encoding) {
176 r->content_encoding = apr_table_get(hdrs, "Content-Encoding");
181 /* Outputs a long in LSB order to the given file
182 * only the bottom 4 bits are required for the deflate file format.
184 static void putLong(unsigned char *string, unsigned long x)
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);
192 /* Inputs a string and returns a long.
194 static unsigned long getLong(unsigned char *string)
196 return ((unsigned long)string[0])
197 | (((unsigned long)string[1]) << 8)
198 | (((unsigned long)string[2]) << 16)
199 | (((unsigned long)string[3]) << 24);
202 static void *create_deflate_server_config(apr_pool_t *p, server_rec *s)
204 deflate_filter_config *c = apr_pcalloc(p, sizeof *c);
206 c->memlevel = DEFAULT_MEMLEVEL;
207 c->windowSize = DEFAULT_WINDOWSIZE;
208 c->bufferSize = DEFAULT_BUFFERSIZE;
209 c->compressionlevel = DEFAULT_COMPRESSION;
214 static const char *deflate_set_window_size(cmd_parms *cmd, void *dummy,
217 deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
224 return "DeflateWindowSize must be between 1 and 15";
226 c->windowSize = i * -1;
231 static const char *deflate_set_buffer_size(cmd_parms *cmd, void *dummy,
234 deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
239 return "DeflateBufferSize should be positive";
242 c->bufferSize = (apr_size_t)n;
246 static const char *deflate_set_note(cmd_parms *cmd, void *dummy,
247 const char *arg1, const char *arg2)
249 deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
253 c->note_ratio_name = apr_pstrdup(cmd->pool, arg1);
255 else if (!strcasecmp(arg1, "ratio")) {
256 c->note_ratio_name = apr_pstrdup(cmd->pool, arg2);
258 else if (!strcasecmp(arg1, "input")) {
259 c->note_input_name = apr_pstrdup(cmd->pool, arg2);
261 else if (!strcasecmp(arg1, "output")) {
262 c->note_output_name = apr_pstrdup(cmd->pool, arg2);
265 return apr_psprintf(cmd->pool, "Unknown note type %s", arg1);
271 static const char *deflate_set_memlevel(cmd_parms *cmd, void *dummy,
274 deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
281 return "DeflateMemLevel must be between 1 and 9";
288 static const char *deflate_set_etag(cmd_parms *cmd, void *dummy,
291 deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
294 if (!strcasecmp(arg, "NoChange")) {
295 c->etag_opt = AP_DEFLATE_ETAG_NOCHANGE;
297 else if (!strcasecmp(arg, "AddSuffix")) {
298 c->etag_opt = AP_DEFLATE_ETAG_ADDSUFFIX;
300 else if (!strcasecmp(arg, "Remove")) {
301 c->etag_opt = AP_DEFLATE_ETAG_REMOVE;
304 return "DeflateAlterETAG accepts only 'NoChange', 'AddSuffix', and 'Remove'";
311 static const char *deflate_set_compressionlevel(cmd_parms *cmd, void *dummy,
314 deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
321 return "Compression Level must be between 1 and 9";
323 c->compressionlevel = i;
328 typedef struct deflate_ctx_t
331 unsigned char *buffer;
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;
340 unsigned int consume_pos,
342 unsigned int filter_init:1;
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 */
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,
360 unsigned int deflate_len;
364 deflate_len = c->bufferSize - ctx->stream.avail_out;
366 if (deflate_len != 0) {
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
373 ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer,
376 b = apr_bucket_heap_create((char *)ctx->buffer,
379 APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
380 ctx->stream.next_out = ctx->buffer;
381 ctx->stream.avail_out = c->bufferSize;
387 zRC = libz_func(&ctx->stream, flush);
390 * We can ignore Z_BUF_ERROR because:
391 * When we call libz_func we can assume that
393 * - avail_in is zero (due to the surrounding code that calls
395 * - avail_out is non zero due to our actions some lines above
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.
401 if (zRC == Z_BUF_ERROR) {
406 done = (ctx->stream.avail_out != 0 || zRC == Z_STREAM_END);
408 if (zRC != Z_OK && zRC != Z_STREAM_END)
414 static apr_status_t deflate_ctx_cleanup(void *data)
416 deflate_ctx *ctx = (deflate_ctx *)data;
419 ctx->libz_end_func(&ctx->stream);
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
429 static void deflate_check_etag(request_rec *r, const char *transform, int etag_opt)
431 const char *etag = apr_table_get(r->headers_out, "ETag");
434 if (etag_opt == AP_DEFLATE_ETAG_REMOVE) {
435 apr_table_unset(r->headers_out, "ETag");
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);
444 char *e = d + etaglen - 1;
445 const char *s = etag;
447 for (; d < e; ++d, ++s) {
448 *d = *s; /* copy etag to newtag up to last quote */
450 *d++ = '-'; /* append dash to newtag */
452 e = d + transformlen;
453 for (; d < e; ++d, ++s) {
454 *d = *s; /* copy transform to newtag */
456 *d++ = '"'; /* append quote to newtag */
457 *d = '\0'; /* null terminate newtag */
459 apr_table_setn(r->headers_out, "ETag", newtag);
464 static int have_ssl_compression(request_rec *r)
467 if (mod_deflate_ssl_var == NULL)
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)
476 static apr_status_t deflate_out_filter(ap_filter_t *f,
477 apr_bucket_brigade *bb)
480 request_rec *r = f->r;
481 deflate_ctx *ctx = f->ctx;
483 apr_size_t len = 0, blen;
485 deflate_filter_config *c;
487 /* Do nothing if asked to filter nothing. */
488 if (APR_BRIGADE_EMPTY(bb)) {
492 c = ap_get_module_config(r->server->module_config,
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.
503 const char *encoding;
505 if (have_ssl_compression(r)) {
506 ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
507 "Compression enabled at SSL level; not compressing "
509 ap_remove_output_filter(f);
510 return ap_pass_brigade(f->next, bb);
513 /* We have checked above that bb is not empty */
514 e = APR_BRIGADE_LAST(bb);
515 if (APR_BUCKET_IS_EOS(e)) {
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".
524 e = APR_BRIGADE_FIRST(bb);
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);
534 if (APR_BUCKET_IS_METADATA(e)) {
535 e = APR_BUCKET_NEXT(e);
539 rc = apr_bucket_read(e, &data, &blen, APR_BLOCK_READ);
540 if (rc != APR_SUCCESS)
543 /* 50 is for Content-Encoding and Vary headers and ETag suffix */
544 if (len > sizeof(gzip_header) + VALIDATION_SIZE + 50)
547 e = APR_BUCKET_NEXT(e);
551 ctx = f->ctx = apr_pcalloc(r->pool, sizeof(*ctx));
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.
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")
563 if (APLOG_R_IS_LEVEL(r, APLOG_TRACE1)) {
565 (r->main != NULL) ? "subrequest" :
566 (r->status == HTTP_NO_CONTENT) ? "no content" :
567 apr_table_get(r->subprocess_env, "no-gzip") ? "no-gzip" :
569 ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
570 "Not compressing (%s)", reason);
572 ap_remove_output_filter(f);
573 return ap_pass_brigade(f->next, bb);
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
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);
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.)
596 encoding = apr_table_get(r->headers_out, "Content-Encoding");
600 err_enc = apr_table_get(r->err_headers_out, "Content-Encoding");
602 encoding = apr_pstrcat(r->pool, encoding, ",", err_enc, NULL);
606 encoding = apr_table_get(r->err_headers_out, "Content-Encoding");
609 if (r->content_encoding) {
610 encoding = encoding ? apr_pstrcat(r->pool, encoding, ",",
611 r->content_encoding, NULL)
612 : r->content_encoding;
616 const char *tmp = encoding;
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 "
626 ap_remove_output_filter(f);
627 return ap_pass_brigade(f->next, bb);
630 /* Otherwise, skip token */
634 token = (*tmp) ? ap_get_token(r->pool, &tmp, 0) : NULL;
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.
642 apr_table_mergen(r->headers_out, "Vary", "Accept-Encoding");
644 /* force-gzip will just force it out regardless if the browser
645 * can actually do anything with it.
647 if (!apr_table_get(r->subprocess_env, "force-gzip")) {
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);
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 == ';') {
661 ap_get_token(r->pool, &accepts, 1);
664 /* retrieve next token */
665 if (*accepts == ',') {
668 token = (*accepts) ? ap_get_token(r->pool, &accepts, 0) : NULL;
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);
680 ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
681 "Forcing compression (force-gzip set)");
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).
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;
694 zRC = deflateInit2(&ctx->stream, c->compressionlevel, Z_DEFLATED,
695 c->windowSize, c->memlevel,
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",
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
709 ap_remove_output_filter(f);
710 return ap_pass_brigade(f->next, bb);
713 * Register a cleanup function to ensure that we cleanup the internal
716 apr_pool_cleanup_register(r->pool, ctx, deflate_ctx_cleanup,
717 apr_pool_cleanup_null);
719 /* Set the filter init flag so subsequent invocations know we are
722 ctx->filter_init = 1;
726 * Zlib initialization worked, so we can now change the important
727 * content metadata before sending the response out.
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");
735 apr_table_mergen(r->headers_out, "Content-Encoding", "gzip");
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,
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);
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);
754 /* add immortal gzip header */
755 e = apr_bucket_immortal_create(gzip_header, sizeof gzip_header,
757 APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
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.
766 return ap_pass_brigade(f->next, bb);
769 while (!APR_BRIGADE_EMPTY(bb))
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.
781 if (r->header_only && r->bytes_sent) {
782 ap_remove_output_filter(f);
783 return ap_pass_brigade(f->next, bb);
786 e = APR_BRIGADE_FIRST(bb);
788 if (APR_BUCKET_IS_EOS(e)) {
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,
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);
800 b = apr_bucket_pool_create(buf, VALIDATION_SIZE, r->pool,
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);
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)
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)
824 if (c->note_ratio_name) {
825 apr_table_setn(r->notes, c->note_ratio_name,
826 (ctx->stream.total_in > 0)
828 (int)(ctx->stream.total_out
830 / ctx->stream.total_in))
834 deflateEnd(&ctx->stream);
835 /* No need for cleanup any longer */
836 apr_pool_cleanup_kill(r->pool, ctx, deflate_ctx_cleanup);
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);
842 /* Okay, we've seen the EOS.
843 * Time to pass it along down the chain.
845 return ap_pass_brigade(f->next, ctx->bb);
848 if (APR_BUCKET_IS_FLUSH(e)) {
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);
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);
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) {
871 if (APR_BUCKET_IS_METADATA(e)) {
873 * Remove meta data bucket from old brigade and insert into the
876 APR_BUCKET_REMOVE(e);
877 APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
882 apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
884 apr_bucket_delete(e);
888 apr_bucket_split(e, INT_MAX);
889 apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
892 /* This crc32 function is from zlib. */
893 ctx->crc = crc32(ctx->crc, (const Bytef *)data, len);
896 ctx->stream.next_in = (unsigned char *)data; /* We just lost const-ness,
897 * but we'll just have to
899 ctx->stream.avail_in = len;
901 while (ctx->stream.avail_in != 0) {
902 if (ctx->stream.avail_out == 0) {
905 ctx->stream.next_out = ctx->buffer;
906 len = c->bufferSize - ctx->stream.avail_out;
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) {
919 zRC = deflate(&(ctx->stream), Z_NO_FLUSH);
922 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01386)
923 "Zlib error %d deflating data (%s)", zRC,
929 apr_bucket_delete(e);
932 apr_brigade_cleanup(bb);
936 static apr_status_t consume_zlib_flags(deflate_ctx *ctx,
937 const char **data, apr_size_t *len)
939 if ((ctx->zlib_flags & EXTRA_FIELD)) {
940 /* Consume 2 bytes length prefixed data. */
941 if (ctx->consume_pos == 0) {
943 return APR_INCOMPLETE;
945 ctx->consume_len = (unsigned int)**data;
950 if (ctx->consume_pos == 1) {
952 return APR_INCOMPLETE;
954 ctx->consume_len += ((unsigned int)**data) << 8;
959 if (*len < ctx->consume_len) {
960 ctx->consume_len -= *len;
962 return APR_INCOMPLETE;
964 *data += ctx->consume_len;
965 *len -= ctx->consume_len;
967 ctx->consume_len = ctx->consume_pos = 0;
968 ctx->zlib_flags &= ~EXTRA_FIELD;
971 if ((ctx->zlib_flags & ORIG_NAME)) {
972 /* Consume nul terminated string. */
973 while (*len && **data) {
978 return APR_INCOMPLETE;
984 ctx->zlib_flags &= ~ORIG_NAME;
987 if ((ctx->zlib_flags & COMMENT)) {
988 /* Consume nul terminated string. */
989 while (*len && **data) {
994 return APR_INCOMPLETE;
1000 ctx->zlib_flags &= ~COMMENT;
1003 if ((ctx->zlib_flags & HEAD_CRC)) {
1004 /* Consume CRC16 (2 octets). */
1005 if (ctx->consume_pos == 0) {
1007 return APR_INCOMPLETE;
1014 return APR_INCOMPLETE;
1019 ctx->consume_pos = 0;
1020 ctx->zlib_flags &= ~HEAD_CRC;
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)
1034 request_rec *r = f->r;
1035 deflate_ctx *ctx = f->ctx;
1038 deflate_filter_config *c;
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);
1045 c = ap_get_module_config(r->server->module_config, &deflate_module);
1047 if (!ctx || ctx->header_len < sizeof(ctx->header)) {
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);
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);
1063 /* Check whether request body is gzipped.
1065 * If it is, we're transforming the contents, invalidating
1066 * some request headers including Content-Encoding.
1068 * If not, we just remove ourself.
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);
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);
1082 apr_brigade_cleanup(ctx->bb);
1084 len = sizeof(ctx->header) - ctx->header_len;
1085 rv = ap_get_brigade(f->next, ctx->bb, AP_MODE_READBYTES, block,
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).
1092 if (rv != APR_SUCCESS || APR_BRIGADE_EMPTY(ctx->bb)) {
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.
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;
1108 APR_BUCKET_REMOVE(bkt);
1109 APR_BRIGADE_INSERT_TAIL(bb, bkt);
1110 ap_remove_input_filter(f);
1114 rv = apr_brigade_flatten(ctx->bb,
1115 ctx->header + ctx->header_len, &len);
1116 if (rv != APR_SUCCESS) {
1119 if (len && !ctx->header_len) {
1120 apr_table_unset(r->headers_in, "Content-Length");
1121 apr_table_unset(r->headers_in, "Content-MD5");
1123 ctx->header_len += len;
1125 } while (ctx->header_len < sizeof(ctx->header));
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;
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;
1142 zRC = inflateInit2(&ctx->stream, c->windowSize);
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",
1151 ap_remove_input_filter(f);
1152 return ap_get_brigade(f->next, bb, mode, block, readbytes);
1155 /* initialize deflate output buffer */
1156 ctx->stream.next_out = ctx->buffer;
1157 ctx->stream.avail_out = c->bufferSize;
1159 apr_brigade_cleanup(ctx->bb);
1162 if (APR_BRIGADE_EMPTY(ctx->proc_bb)) {
1163 rv = ap_get_brigade(f->next, ctx->bb, mode, block, readbytes);
1165 /* Don't terminate on EAGAIN (or success with an empty brigade in
1166 * non-blocking mode), just return focus.
1168 if (block == APR_NONBLOCK_READ
1169 && (APR_STATUS_IS_EAGAIN(rv)
1170 || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(ctx->bb)))) {
1173 if (rv != APR_SUCCESS) {
1174 inflateEnd(&ctx->stream);
1178 for (bkt = APR_BRIGADE_FIRST(ctx->bb);
1179 bkt != APR_BRIGADE_SENTINEL(ctx->bb);
1180 bkt = APR_BUCKET_NEXT(bkt))
1185 if (APR_BUCKET_IS_EOS(bkt)) {
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;
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);
1200 if (APR_BUCKET_IS_FLUSH(bkt)) {
1201 apr_bucket *tmp_heap;
1202 zRC = inflate(&(ctx->stream), Z_SYNC_FLUSH);
1204 inflateEnd(&ctx->stream);
1205 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01391)
1206 "Zlib error %d inflating data (%s)", zRC,
1208 return APR_EGENERAL;
1211 ctx->stream.next_out = ctx->buffer;
1212 len = c->bufferSize - ctx->stream.avail_out;
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;
1220 /* Move everything to the returning brigade. */
1221 APR_BUCKET_REMOVE(bkt);
1222 APR_BRIGADE_CONCAT(bb, ctx->bb);
1226 /* sanity check - data after completed compressed body and before eos? */
1228 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02482)
1229 "Encountered extra data after compressed data");
1230 return APR_EGENERAL;
1234 apr_bucket_read(bkt, &data, &len, APR_BLOCK_READ);
1238 if (len > INT_MAX) {
1239 apr_bucket_split(bkt, INT_MAX);
1240 apr_bucket_read(bkt, &data, &len, APR_BLOCK_READ);
1243 if (ctx->zlib_flags) {
1244 rv = consume_zlib_flags(ctx, &data, &len);
1245 if (rv == APR_SUCCESS) {
1246 ctx->zlib_flags = 0;
1253 /* pass through zlib inflate. */
1254 ctx->stream.next_in = (unsigned char *)data;
1255 ctx->stream.avail_in = (int)len;
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;
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;
1273 zRC = inflate(&ctx->stream, Z_NO_FLUSH);
1275 if (zRC == Z_STREAM_END) {
1276 ctx->validation_buffer = apr_pcalloc(r->pool,
1278 ctx->validation_buffer_length = 0;
1283 inflateEnd(&ctx->stream);
1284 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01392)
1285 "Zlib error %d inflating data (%s)", zRC,
1287 return APR_EGENERAL;
1292 if (ctx->validation_buffer) {
1293 apr_bucket *tmp_heap;
1294 apr_size_t avail, valid;
1295 unsigned char *buf = ctx->validation_buffer;
1297 avail = ctx->stream.avail_in;
1298 valid = (apr_size_t)VALIDATION_SIZE -
1299 ctx->validation_buffer_length;
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.
1306 if (avail < valid) {
1307 memcpy(buf + ctx->validation_buffer_length,
1308 ctx->stream.next_in, avail);
1309 ctx->validation_buffer_length += avail;
1312 memcpy(buf + ctx->validation_buffer_length,
1313 ctx->stream.next_in, valid);
1314 ctx->validation_buffer_length += valid;
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,
1321 len = c->bufferSize - ctx->stream.avail_out;
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;
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;
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;
1350 inflateEnd(&ctx->stream);
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;
1363 apr_brigade_cleanup(ctx->bb);
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.
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;
1374 ctx->stream.next_out = ctx->buffer;
1375 len = c->bufferSize - ctx->stream.avail_out;
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;
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);
1389 APR_BRIGADE_CONCAT(bb, ctx->proc_bb);
1390 apr_brigade_split_ex(bb, bkt, ctx->proc_bb);
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)
1403 request_rec *r = f->r;
1404 deflate_ctx *ctx = f->ctx;
1407 deflate_filter_config *c;
1409 /* Do nothing if asked to filter nothing. */
1410 if (APR_BRIGADE_EMPTY(bb)) {
1414 c = ap_get_module_config(r->server->module_config, &deflate_module);
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.
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)
1428 ap_remove_output_filter(f);
1429 return ap_pass_brigade(f->next, bb);
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.
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);
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);
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;
1456 zRC = inflateInit2(&ctx->stream, c->windowSize);
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",
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
1470 ap_remove_output_filter(f);
1471 return ap_pass_brigade(f->next, bb);
1475 * Register a cleanup function to ensure that we cleanup the internal
1478 apr_pool_cleanup_register(r->pool, ctx, deflate_ctx_cleanup,
1479 apr_pool_cleanup_null);
1481 /* initialize inflate output buffer */
1482 ctx->stream.next_out = ctx->buffer;
1483 ctx->stream.avail_out = c->bufferSize;
1486 while (!APR_BRIGADE_EMPTY(bb))
1492 e = APR_BRIGADE_FIRST(bb);
1494 if (APR_BUCKET_IS_EOS(e)) {
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
1500 ap_remove_output_filter(f);
1501 /* should be zero already anyway */
1502 ctx->stream.avail_in = 0;
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.
1511 flush_libz_buffer(ctx, c, f->c->bucket_alloc, inflate, Z_SYNC_FLUSH,
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);
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;
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;
1535 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01401)
1536 "Zlib: Validation bytes not present");
1537 return APR_EGENERAL;
1540 inflateEnd(&ctx->stream);
1541 /* No need for cleanup any longer */
1542 apr_pool_cleanup_kill(r->pool, ctx, deflate_ctx_cleanup);
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);
1549 * Okay, we've seen the EOS.
1550 * Time to pass it along down the chain.
1552 return ap_pass_brigade(f->next, ctx->bb);
1555 if (APR_BUCKET_IS_FLUSH(e)) {
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,
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;
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) {
1584 if (APR_BUCKET_IS_METADATA(e)) {
1586 * Remove meta data bucket from old brigade and insert into the
1589 APR_BUCKET_REMOVE(e);
1590 APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
1595 apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
1597 apr_bucket_delete(e);
1600 if (len > INT_MAX) {
1601 apr_bucket_split(e, INT_MAX);
1602 apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
1605 /* first bucket contains zlib header */
1606 if (ctx->header_len < sizeof(ctx->header)) {
1609 rem = sizeof(ctx->header) - ctx->header_len;
1611 memcpy(ctx->header + ctx->header_len, data, len);
1612 ctx->header_len += len;
1613 apr_bucket_delete(e);
1616 memcpy(ctx->header + ctx->header_len, data, rem);
1617 ctx->header_len += rem;
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);
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 ;
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",
1638 return APR_EGENERAL;
1642 apr_bucket_delete(e);
1649 if (ctx->zlib_flags) {
1650 rv = consume_zlib_flags(ctx, &data, &len);
1651 if (rv == APR_SUCCESS) {
1652 ctx->zlib_flags = 0;
1655 apr_bucket_delete(e);
1660 /* pass through zlib inflate. */
1661 ctx->stream.next_in = (unsigned char *)data;
1662 ctx->stream.avail_in = len;
1664 if (ctx->validation_buffer) {
1665 if (ctx->validation_buffer_length < VALIDATION_SIZE) {
1666 apr_size_t copy_size;
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;
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);
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.
1688 ctx->stream.avail_in = 0;
1692 while (ctx->stream.avail_in != 0) {
1693 if (ctx->stream.avail_out == 0) {
1695 ctx->stream.next_out = ctx->buffer;
1696 len = c->bufferSize - ctx->stream.avail_out;
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) {
1710 zRC = inflate(&ctx->stream, Z_NO_FLUSH);
1712 if (zRC == Z_STREAM_END) {
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.
1718 ctx->validation_buffer = apr_pcalloc(f->r->pool,
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;
1729 if (ctx->validation_buffer_length)
1730 memcpy(ctx->validation_buffer, ctx->stream.next_in,
1731 ctx->validation_buffer_length);
1736 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01409)
1737 "Zlib error %d inflating data (%s)", zRC,
1739 return APR_EGENERAL;
1743 apr_bucket_delete(e);
1746 apr_brigade_cleanup(bb);
1750 static int mod_deflate_post_config(apr_pool_t *pconf, apr_pool_t *plog,
1751 apr_pool_t *ptemp, server_rec *s)
1753 mod_deflate_ssl_var = APR_RETRIEVE_OPTIONAL_FN(ssl_var_lookup);
1758 #define PROTO_FLAGS AP_FILTER_PROTO_CHANGE|AP_FILTER_PROTO_CHANGE_LENGTH
1759 static void register_hooks(apr_pool_t *p)
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);
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'"),
1787 /* zlib can be built with #define deflate z_deflate */
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 */