1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2002 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * (zlib functions gz_open and gzwrite)
59 * mod_deflate.c: Perform deflate transfer-encoding on the fly
61 * Written by Ian Holsman (IanH@apache.org)
66 #include "http_config.h"
68 #include "apr_strings.h"
69 #include "apr_general.h"
70 #include "util_filter.h"
71 #include "apr_buckets.h"
72 #include "http_request.h"
79 /* As part of the encoding process, we must send what our OS_CODE is
80 * (or so it seems based on what I can tell of how gzip encoding works).
82 * zutil.h is not always included with zlib distributions (it is a private
83 * header), so this is straight from zlib 1.1.3's zutil.h.
89 #ifdef WIN32 /* Window 95 & Windows NT */
93 #if defined(VAXC) || defined(VMS)
101 #if defined(ATARI) || defined(atarist)
105 #if defined(MACOS) || defined(TARGET_OS_MAC)
109 #ifdef __50SERIES /* Prime/PRIMOS */
118 #define OS_CODE 0x03 /* assume Unix */
122 static const char deflateFilterName[] = "DEFLATE";
123 module AP_MODULE_DECLARE_DATA deflate_module;
125 typedef struct deflate_filter_config_t
131 } deflate_filter_config;
133 /* windowsize is negative to suppress Zlib header */
134 #define DEFAULT_WINDOWSIZE -15
135 #define DEFAULT_MEMLEVEL 9
136 #define DEFAULT_BUFFERSIZE 8096
138 /* Outputs a long in LSB order to the given file
139 * only the bottom 4 bits are required for the deflate file format.
141 static void putLong(char *string, unsigned long x)
144 for (n = 0; n < 4; n++) {
145 string[n] = (int) (x & 0xff);
150 static void *create_deflate_server_config(apr_pool_t *p, server_rec *s)
152 deflate_filter_config *c = apr_pcalloc(p, sizeof *c);
154 c->memlevel = DEFAULT_MEMLEVEL;
155 c->windowSize = DEFAULT_WINDOWSIZE;
156 c->bufferSize = DEFAULT_BUFFERSIZE;
161 static const char *deflate_set_window_size(cmd_parms *cmd, void *dummy,
164 deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
171 return "DeflateWindowSize must be between 1 and 15";
173 c->windowSize = i * -1;
178 static const char *deflate_set_buffer_size(cmd_parms *cmd, void *dummy,
181 deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
184 c->bufferSize = atoi(arg);
186 if (c->bufferSize <= 0) {
187 return "DeflateBufferSize should be positive";
192 static const char *deflate_set_note(cmd_parms *cmd, void *dummy,
195 deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
197 c->noteName = apr_pstrdup(cmd->pool, arg);
202 static const char *deflate_set_memlevel(cmd_parms *cmd, void *dummy,
205 deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
212 return "DeflateMemLevel must be between 1 and 9";
220 static int deflate_magic[2] = { 0x1f, 0x8b };
222 typedef struct deflate_ctx_t
225 unsigned char *buffer;
227 apr_bucket_brigade *bb;
230 static apr_status_t deflate_out_filter(ap_filter_t *f,
231 apr_bucket_brigade *bb)
234 request_rec *r = f->r;
235 deflate_ctx *ctx = f->ctx;
237 deflate_filter_config *c = ap_get_module_config(r->server->module_config,
240 /* If we don't have a context, we need to ensure that it is okay to send
241 * the deflated content. If we have a context, that means we've done
242 * this before and we liked it.
243 * This could be not so nice if we always fail. But, if we succeed,
244 * we're in better shape.
248 const char *encoding, *accepts;
250 /* only work on main request/no subrequests */
252 ap_remove_output_filter(f);
253 return ap_pass_brigade(f->next, bb);
256 /* some browsers might have problems, so set no-gzip
257 * (with browsermatch) for them
259 if (apr_table_get(r->subprocess_env, "no-gzip")) {
260 ap_remove_output_filter(f);
261 return ap_pass_brigade(f->next, bb);
264 /* Some browsers might have problems with content types
265 * other than text/html, so set gzip-only-text/html
266 * (with browsermatch) for them
268 if ((r->content_type == NULL
269 || strncmp(r->content_type, "text/html", 9))
270 && apr_table_get(r->subprocess_env, "gzip-only-text/html")) {
271 ap_remove_output_filter(f);
272 return ap_pass_brigade(f->next, bb);
275 /* Let's see what our current Content-Encoding is.
276 * If gzip is present, don't gzip again. (We could, but let's not.)
278 encoding = apr_table_get(r->headers_out, "Content-Encoding");
280 const char *tmp = encoding;
282 token = ap_get_token(r->pool, &tmp, 0);
283 while (token && token[0]) {
284 if (!strcasecmp(token, "gzip")) {
285 ap_remove_output_filter(f);
286 return ap_pass_brigade(f->next, bb);
288 /* Otherwise, skip token */
290 token = ap_get_token(r->pool, &tmp, 0);
294 /* if they don't have the line, then they can't play */
295 accepts = apr_table_get(r->headers_in, "Accept-Encoding");
296 if (accepts == NULL) {
297 ap_remove_output_filter(f);
298 return ap_pass_brigade(f->next, bb);
301 token = ap_get_token(r->pool, &accepts, 0);
302 while (token && token[0] && strcasecmp(token, "gzip")) {
305 token = ap_get_token(r->pool, &accepts, 0);
308 /* No acceptable token found. */
309 if (token == NULL || token[0] == '\0') {
310 ap_remove_output_filter(f);
311 return ap_pass_brigade(f->next, bb);
314 /* We're cool with filtering this. */
315 ctx = f->ctx = apr_pcalloc(r->pool, sizeof(*ctx));
316 ctx->bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
317 ctx->buffer = apr_palloc(r->pool, c->bufferSize);
319 zRC = deflateInit2(&ctx->stream, Z_BEST_SPEED, Z_DEFLATED,
320 c->windowSize, c->memlevel,
325 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
326 "unable to init Zlib: "
327 "deflateInit2 returned %d: URL %s",
329 return ap_pass_brigade(f->next, bb);
332 buf = apr_psprintf(r->pool, "%c%c%c%c%c%c%c%c%c%c", deflate_magic[0],
333 deflate_magic[1], Z_DEFLATED, 0 /* flags */ , 0, 0,
334 0, 0 /* time */ , 0 /* xflags */ , OS_CODE);
335 e = apr_bucket_pool_create(buf, 10, r->pool, f->c->bucket_alloc);
336 APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
338 /* If the entire Content-Encoding is "identity", we can replace it. */
339 if (!encoding || !strcasecmp(encoding, "identity")) {
340 apr_table_setn(r->headers_out, "Content-Encoding", "gzip");
343 apr_table_mergen(r->headers_out, "Content-Encoding", "gzip");
345 apr_table_setn(r->headers_out, "Vary", "Accept-Encoding");
346 apr_table_unset(r->headers_out, "Content-Length");
349 /* initialize deflate output buffer */
350 ctx->stream.next_out = ctx->buffer;
351 ctx->stream.avail_out = c->bufferSize;
353 APR_BRIGADE_FOREACH(e, bb) {
360 if (APR_BUCKET_IS_EOS(e)) {
362 char crc_array[4], len_array[4];
363 unsigned int deflate_len;
365 ctx->stream.avail_in = 0; /* should be zero already anyway */
367 deflate_len = c->bufferSize - ctx->stream.avail_out;
369 if (deflate_len != 0) {
370 b = apr_bucket_heap_create((char *)ctx->buffer,
373 APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
374 ctx->stream.next_out = ctx->buffer;
375 ctx->stream.avail_out = c->bufferSize;
382 zRC = deflate(&ctx->stream, Z_FINISH);
384 if (deflate_len == 0 && zRC == Z_BUF_ERROR) {
388 done = (ctx->stream.avail_out != 0 || zRC == Z_STREAM_END);
390 if (zRC != Z_OK && zRC != Z_STREAM_END) {
395 putLong(crc_array, ctx->crc);
396 putLong(len_array, ctx->stream.total_in);
398 p = buf = apr_palloc(r->pool, 8);
408 b = apr_bucket_pool_create(buf, 8, r->pool, f->c->bucket_alloc);
409 APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
410 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
411 "Zlib: Compressed %ld to %ld : URL %s",
412 ctx->stream.total_in, ctx->stream.total_out, r->uri);
415 if (ctx->stream.total_in > 0) {
418 total = ctx->stream.total_out * 100 / ctx->stream.total_in;
420 apr_table_setn(r->notes, c->noteName,
421 apr_itoa(r->pool, total));
424 apr_table_setn(r->notes, c->noteName, "-");
428 deflateEnd(&ctx->stream);
430 /* Remove EOS from the old list, and insert into the new. */
431 APR_BUCKET_REMOVE(e);
432 APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
434 /* Okay, we've seen the EOS.
435 * Time to pass it along down the chain.
437 return ap_pass_brigade(f->next, ctx->bb);
440 if (APR_BUCKET_IS_FLUSH(e)) {
442 zRC = deflate(&(ctx->stream), Z_SYNC_FLUSH);
447 ctx->stream.next_out = ctx->buffer;
448 len = c->bufferSize - ctx->stream.avail_out;
450 b = apr_bucket_heap_create((char *)ctx->buffer, len,
451 NULL, f->c->bucket_alloc);
452 APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
453 ctx->stream.avail_out = c->bufferSize;
455 bkt = apr_bucket_flush_create(f->c->bucket_alloc);
456 APR_BRIGADE_INSERT_TAIL(ctx->bb, bkt);
457 ap_pass_brigade(f->next, ctx->bb);
462 apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
464 /* This crc32 function is from zlib. */
465 ctx->crc = crc32(ctx->crc, (const Bytef *)data, len);
468 ctx->stream.next_in = (unsigned char *)data; /* We just lost const-ness,
469 * but we'll just have to
471 ctx->stream.avail_in = len;
473 while (ctx->stream.avail_in != 0) {
474 if (ctx->stream.avail_out == 0) {
475 ctx->stream.next_out = ctx->buffer;
476 len = c->bufferSize - ctx->stream.avail_out;
478 b = apr_bucket_heap_create((char *)ctx->buffer, len,
479 NULL, f->c->bucket_alloc);
480 APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
481 ctx->stream.avail_out = c->bufferSize;
484 zRC = deflate(&(ctx->stream), Z_NO_FLUSH);
491 apr_brigade_destroy(bb);
495 static void register_hooks(apr_pool_t *p)
497 ap_register_output_filter(deflateFilterName, deflate_out_filter,
498 AP_FTYPE_CONTENT_SET);
501 static const command_rec deflate_filter_cmds[] = {
502 AP_INIT_TAKE1("DeflateFilterNote", deflate_set_note, NULL, RSRC_CONF,
503 "Set a note to report on compression ratio"),
504 AP_INIT_TAKE1("DeflateWindowSize", deflate_set_window_size, NULL,
505 RSRC_CONF, "Set the Deflate window size (1-15)"),
506 AP_INIT_TAKE1("DeflateBufferSize", deflate_set_buffer_size, NULL, RSRC_CONF,
507 "Set the Deflate Buffer Size"),
508 AP_INIT_TAKE1("DeflateMemLevel", deflate_set_memlevel, NULL, RSRC_CONF,
509 "Set the Deflate Memory Level (1-9)"),
513 module AP_MODULE_DECLARE_DATA deflate_module = {
514 STANDARD20_MODULE_STUFF,
515 NULL, /* dir config creater */
516 NULL, /* dir merger --- default is to override */
517 create_deflate_server_config, /* server config */
518 NULL, /* merge server config */
519 deflate_filter_cmds, /* command table */
520 register_hooks /* register hooks */