]> granicus.if.org Git - apache/blob - modules/filters/mod_deflate.c
If we determine that we shouldn't be involved in this request, remove
[apache] / modules / filters / mod_deflate.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2002 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
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
17  *    distribution.
18  *
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.
25  *
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.
30  *
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.
34  *
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
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
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/>.
53  *
54  * Portions of this software are based upon public domain software
55  * (zlib functions gz_open and gzwrite)
56  */
57
58 /*
59  * mod_deflate.c: Perform deflate transfer-encoding on the fly
60  *
61  * Written by Ian Holsman (IanH@apache.org)
62  *
63  */
64
65 #include "httpd.h"
66 #include "http_config.h"
67 #include "http_log.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"
73
74 #include "zlib.h"
75
76 #ifdef HAVE_ZUTIL_H
77 #include "zutil.h"
78 #else
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).
81  *
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.
84  */
85 #ifdef OS2
86 #define OS_CODE  0x06
87 #endif
88
89 #ifdef WIN32 /* Window 95 & Windows NT */
90 #define OS_CODE  0x0b
91 #endif
92
93 #if defined(VAXC) || defined(VMS)
94 #define OS_CODE  0x02
95 #endif
96
97 #ifdef AMIGA
98 #define OS_CODE  0x01
99 #endif
100
101 #if defined(ATARI) || defined(atarist)
102 #define OS_CODE  0x05
103 #endif
104
105 #if defined(MACOS) || defined(TARGET_OS_MAC)
106 #define OS_CODE  0x07
107 #endif
108
109 #ifdef __50SERIES /* Prime/PRIMOS */
110 #define OS_CODE  0x0F
111 #endif
112
113 #ifdef TOPS20
114 #define OS_CODE  0x0a
115 #endif
116
117 #ifndef OS_CODE
118 #define OS_CODE  0x03  /* assume Unix */
119 #endif
120 #endif
121
122 static const char deflateFilterName[] = "DEFLATE";
123 module AP_MODULE_DECLARE_DATA deflate_module;
124
125 typedef struct deflate_filter_config_t
126 {
127     int windowSize;
128     int memlevel;
129     char *noteName;
130 } deflate_filter_config;
131
132 /* windowsize is negative to suppress Zlib header */
133 #define DEFAULT_WINDOWSIZE -15
134 #define DEFAULT_MEMLEVEL 9
135 #define FILTER_BUFSIZE 8096
136
137 /* Outputs a long in LSB order to the given file
138  * only the bottom 4 bits are required for the deflate file format.
139  */
140 static void putLong(char *string, unsigned long x)
141 {
142     int n;
143     for (n = 0; n < 4; n++) {
144         string[n] = (int) (x & 0xff);
145         x >>= 8;
146     }
147 }
148
149 static void *create_deflate_server_config(apr_pool_t *p, server_rec *s)
150 {
151     deflate_filter_config *c = apr_pcalloc(p, sizeof *c);
152
153     c->memlevel   = DEFAULT_MEMLEVEL;
154     c->windowSize = DEFAULT_WINDOWSIZE;
155
156     return c;
157 }
158
159 static const char *deflate_set_window_size(cmd_parms *cmd, void *dummy,
160                                            const char *arg)
161 {
162     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
163                                                     &deflate_module);
164     int i;
165
166     i = atoi(arg);
167
168     if (i < 1 || i > 15)
169         return "DeflateWindowSize must be between 1 and 15";
170
171     c->windowSize = i * -1;
172
173     return NULL;
174 }
175
176 static const char *deflate_set_note(cmd_parms *cmd, void *dummy,
177                                     const char *arg)
178 {
179     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
180                                                     &deflate_module);
181     c->noteName = apr_pstrdup(cmd->pool, arg);
182
183     return NULL;
184 }
185
186 static const char *deflate_set_memlevel(cmd_parms *cmd, void *dummy,
187                                         const char *arg)
188 {
189     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
190                                                     &deflate_module);
191     int i;
192
193     i = atoi(arg);
194
195     if (i < 1 || i > 9)
196         return "DeflateMemLevel must be between 1 and 9";
197
198     c->memlevel = i;
199
200     return NULL;
201 }
202
203 /* magic header */
204 static int deflate_magic[2] = { 0x1f, 0x8b };
205
206 typedef struct deflate_ctx_t
207 {
208     z_stream stream;
209     unsigned char buffer[FILTER_BUFSIZE];
210     unsigned long crc;
211     apr_bucket_brigade *bb;
212 } deflate_ctx;
213
214 static apr_status_t deflate_out_filter(ap_filter_t *f,
215                                        apr_bucket_brigade *bb)
216 {
217     apr_bucket *e;
218     const char *accepts;
219     request_rec *r = f->r;
220     deflate_ctx *ctx = f->ctx;
221     char *token = NULL;
222     int zRC;
223     deflate_filter_config *c = ap_get_module_config(r->server->module_config,
224                                                     &deflate_module);
225
226     /* If we don't have a context, we need to ensure that it is okay to send
227      * the deflated content.  If we have a context, that means we've done
228      * this before and we liked it.
229      * This could be not so nice if we always fail.  But, if we succeed,
230      * we're in better shape.
231      */
232     if (!ctx) {
233         char *buf;
234
235         /* only work on main request/no subrequests */
236         if (r->main) {
237             ap_remove_output_filter(f);
238             return ap_pass_brigade(f->next, bb);
239         }
240
241         /* some browsers might have problems, so set no-gzip
242          * (with browsermatch) for them
243          */
244         if (apr_table_get(r->subprocess_env, "no-gzip")) {
245             ap_remove_output_filter(f);
246             return ap_pass_brigade(f->next, bb);
247         }
248
249         /* Some browsers might have problems with content types
250          * other than text/html, so set gzip-only-text/html
251          * (with browsermatch) for them
252          */
253         if ((r->content_type == NULL
254              || strncmp(r->content_type, "text/html", 9))
255             && apr_table_get(r->subprocess_env, "gzip-only-text/html")) {
256             ap_remove_output_filter(f);
257             return ap_pass_brigade(f->next, bb);
258         }
259
260         /* if they don't have the line, then they can't play */
261         accepts = apr_table_get(r->headers_in, "Accept-Encoding");
262         if (accepts == NULL) {
263             ap_remove_output_filter(f);
264             return ap_pass_brigade(f->next, bb);
265         }
266
267         token = ap_get_token(r->pool, &accepts, 0);
268         while (token && token[0] && strcmp(token, "gzip")) {
269             /* skip token */
270             accepts++;
271             token = ap_get_token(r->pool, &accepts, 0);
272         }
273
274         /* No acceptable token found. */
275         if (token == NULL || token[0] == '\0') {
276             ap_remove_output_filter(f);
277             return ap_pass_brigade(f->next, bb);
278         }
279
280         /* We're cool with filtering this. */
281         ctx = f->ctx = apr_pcalloc(r->pool, sizeof(*ctx));
282         ctx->bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
283 /*
284         ctx->stream.zalloc = (alloc_func) 0;
285         ctx->stream.zfree = (free_func) 0;
286         ctx->stream.opaque = (voidpf) 0;
287         ctx->crc = 0L;
288 */
289         zRC = deflateInit2(&ctx->stream, Z_BEST_SPEED, Z_DEFLATED,
290                            c->windowSize, c->memlevel,
291                            Z_DEFAULT_STRATEGY);
292
293         if (zRC != Z_OK) {
294             f->ctx = NULL;
295             ap_log_rerror(APLOG_MARK, APLOG_ERR | APLOG_NOERRNO, 0, r,
296                           "unable to init Zlib: "
297                           "deflateInit2 returned %d: URL %s",
298                           zRC, r->uri);
299             return ap_pass_brigade(f->next, bb);
300         }
301
302         buf = apr_psprintf(r->pool, "%c%c%c%c%c%c%c%c%c%c", deflate_magic[0],
303                            deflate_magic[1], Z_DEFLATED, 0 /* flags */ , 0, 0,
304                            0, 0 /* time */ , 0 /* xflags */ , OS_CODE);
305         e = apr_bucket_pool_create(buf, 10, r->pool, f->c->bucket_alloc);
306         APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
307
308         apr_table_setn(r->headers_out, "Content-Encoding", "gzip");
309         apr_table_setn(r->headers_out, "Vary", "Accept-Encoding");
310         apr_table_unset(r->headers_out, "Content-Length");
311     }
312
313     APR_BRIGADE_FOREACH(e, bb) {
314         const char *data;
315         apr_bucket *b;
316         apr_size_t len;
317
318         int done = 0;
319
320         if (APR_BUCKET_IS_EOS(e)) {
321             char *buf, *p;
322             char crc_array[4], len_array[4];
323             unsigned int deflate_len;
324
325             ctx->stream.avail_in = 0; /* should be zero already anyway */
326             for (;;) {
327                 deflate_len = FILTER_BUFSIZE - ctx->stream.avail_out;
328
329                 if (deflate_len != 0) {
330                     b = apr_bucket_heap_create((char *)ctx->buffer,
331                                                deflate_len, NULL,
332                                                f->c->bucket_alloc);
333                     APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
334                     ctx->stream.next_out = ctx->buffer;
335                     ctx->stream.avail_out = FILTER_BUFSIZE;
336                 }
337
338                 if (done) {
339                     break;
340                 }
341
342                 zRC = deflate(&ctx->stream, Z_FINISH);
343
344                 if (deflate_len == 0 && zRC == Z_BUF_ERROR) {
345                     zRC = Z_OK;
346                 }
347
348                 done = (ctx->stream.avail_out != 0 || zRC == Z_STREAM_END);
349
350                 if (zRC != Z_OK && zRC != Z_STREAM_END) {
351                     break;
352                 }
353             }
354
355             putLong(crc_array, ctx->crc);
356             putLong(len_array, ctx->stream.total_in);
357
358             p = buf = apr_palloc(r->pool, 8);
359             *p++ = crc_array[0];
360             *p++ = crc_array[1];
361             *p++ = crc_array[2];
362             *p++ = crc_array[3];
363             *p++ = len_array[0];
364             *p++ = len_array[1];
365             *p++ = len_array[2];
366             *p++ = len_array[3];
367
368             b = apr_bucket_pool_create(buf, 8, r->pool, f->c->bucket_alloc);
369             APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
370             ap_log_rerror(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r,
371                           "Zlib: Compressed %ld to %ld : URL %s",
372                           ctx->stream.total_in, ctx->stream.total_out, r->uri);
373
374             if (c->noteName) {
375                 if (ctx->stream.total_in > 0) {
376                     int total;
377
378                     total = ctx->stream.total_out * 100 / ctx->stream.total_in;
379
380                     apr_table_setn(r->notes, c->noteName,
381                                    apr_itoa(r->pool, total));
382                 }
383                 else {
384                     apr_table_setn(r->notes, c->noteName, "-");
385                 }
386             }
387
388             deflateEnd(&ctx->stream);
389
390             /* Remove EOS from the old list, and insert into the new. */
391             APR_BUCKET_REMOVE(e);
392             APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
393
394             /* Okay, we've seen the EOS.
395              * Time to pass it along down the chain.
396              */
397             return ap_pass_brigade(f->next, ctx->bb);
398         }
399
400         if (APR_BUCKET_IS_FLUSH(e)) {
401             /* XXX FIX: do we need the Content-Size set, or can we stream?
402              * we should be able to stream
403              */
404
405             /* Ignore flush buckets for the moment.. we can't stream as we
406              * need the size ;(
407              */
408             continue;
409         }
410
411         /* read */
412         apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
413
414         /* This crc32 function is from zlib. */
415         ctx->crc = crc32(ctx->crc, (const Bytef *)data, len);
416
417         /* write */
418         ctx->stream.next_in = (unsigned char *)data; /* We just lost const-ness,
419                                                       * but we'll just have to
420                                                       * trust zlib */
421         ctx->stream.avail_in = len;
422         ctx->stream.next_out = ctx->buffer;
423         ctx->stream.avail_out = FILTER_BUFSIZE;
424
425         while (ctx->stream.avail_in != 0) {
426             if (ctx->stream.avail_out == 0) {
427                 ctx->stream.next_out = ctx->buffer;
428                 len = FILTER_BUFSIZE - ctx->stream.avail_out;
429
430                 b = apr_bucket_heap_create((char *)ctx->buffer, len,
431                                            NULL, f->c->bucket_alloc);
432                 APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
433                 ctx->stream.avail_out = FILTER_BUFSIZE;
434             }
435
436             zRC = deflate(&(ctx->stream), Z_NO_FLUSH);
437
438             if (zRC != Z_OK)
439                 return APR_EGENERAL;
440         }
441     }
442
443     apr_brigade_destroy(bb);
444     return APR_SUCCESS;
445 }
446
447 static void register_hooks(apr_pool_t *p)
448 {
449     ap_register_output_filter(deflateFilterName, deflate_out_filter,
450                               AP_FTYPE_CONTENT_SET);
451 }
452
453 static const command_rec deflate_filter_cmds[] = {
454     AP_INIT_TAKE1("DeflateFilterNote", deflate_set_note, NULL, RSRC_CONF,
455                   "Set a note to report on compression ratio"),
456     AP_INIT_TAKE1("DeflateWindowSize", deflate_set_window_size, NULL,
457                   RSRC_CONF, "Set the Deflate window size (1-15)"),
458     AP_INIT_TAKE1("DeflateMemLevel", deflate_set_memlevel, NULL, RSRC_CONF,
459                   "Set the Deflate Memory Level (1-9)"),
460     {NULL}
461 };
462
463 module AP_MODULE_DECLARE_DATA deflate_module = {
464     STANDARD20_MODULE_STUFF,
465     NULL,                         /* dir config creater */
466     NULL,                         /* dir merger --- default is to override */
467     create_deflate_server_config, /* server config */
468     NULL,                         /* merge server config */
469     deflate_filter_cmds,          /* command table */
470     register_hooks                /* register hooks */
471 };