]> granicus.if.org Git - apache/blob - modules/filters/mod_deflate.c
Implement flushing support for mod_deflate.
[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     int bufferSize;
130     char *noteName;
131 } deflate_filter_config;
132
133 /* windowsize is negative to suppress Zlib header */
134 #define DEFAULT_WINDOWSIZE -15
135 #define DEFAULT_MEMLEVEL 9
136 #define DEFAULT_BUFFERSIZE 8096
137
138 /* Outputs a long in LSB order to the given file
139  * only the bottom 4 bits are required for the deflate file format.
140  */
141 static void putLong(char *string, unsigned long x)
142 {
143     int n;
144     for (n = 0; n < 4; n++) {
145         string[n] = (int) (x & 0xff);
146         x >>= 8;
147     }
148 }
149
150 static void *create_deflate_server_config(apr_pool_t *p, server_rec *s)
151 {
152     deflate_filter_config *c = apr_pcalloc(p, sizeof *c);
153
154     c->memlevel   = DEFAULT_MEMLEVEL;
155     c->windowSize = DEFAULT_WINDOWSIZE;
156     c->bufferSize = DEFAULT_BUFFERSIZE;
157
158     return c;
159 }
160
161 static const char *deflate_set_window_size(cmd_parms *cmd, void *dummy,
162                                            const char *arg)
163 {
164     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
165                                                     &deflate_module);
166     int i;
167
168     i = atoi(arg);
169
170     if (i < 1 || i > 15)
171         return "DeflateWindowSize must be between 1 and 15";
172
173     c->windowSize = i * -1;
174
175     return NULL;
176 }
177
178 static const char *deflate_set_buffer_size(cmd_parms *cmd, void *dummy,
179                                            const char *arg)
180 {
181     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
182                                                     &deflate_module);
183
184     c->bufferSize = atoi(arg);
185
186     if (c->bufferSize <= 0) {
187         return "DeflateBufferSize should be positive";
188     }
189
190     return NULL;
191 }
192 static const char *deflate_set_note(cmd_parms *cmd, void *dummy,
193                                     const char *arg)
194 {
195     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
196                                                     &deflate_module);
197     c->noteName = apr_pstrdup(cmd->pool, arg);
198
199     return NULL;
200 }
201
202 static const char *deflate_set_memlevel(cmd_parms *cmd, void *dummy,
203                                         const char *arg)
204 {
205     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
206                                                     &deflate_module);
207     int i;
208
209     i = atoi(arg);
210
211     if (i < 1 || i > 9)
212         return "DeflateMemLevel must be between 1 and 9";
213
214     c->memlevel = i;
215
216     return NULL;
217 }
218
219 /* magic header */
220 static int deflate_magic[2] = { 0x1f, 0x8b };
221
222 typedef struct deflate_ctx_t
223 {
224     z_stream stream;
225     unsigned char *buffer;
226     unsigned long crc;
227     apr_bucket_brigade *bb;
228 } deflate_ctx;
229
230 static apr_status_t deflate_out_filter(ap_filter_t *f,
231                                        apr_bucket_brigade *bb)
232 {
233     apr_bucket *e;
234     request_rec *r = f->r;
235     deflate_ctx *ctx = f->ctx;
236     int zRC;
237     deflate_filter_config *c = ap_get_module_config(r->server->module_config,
238                                                     &deflate_module);
239
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.
245      */
246     if (!ctx) {
247         char *buf, *token;
248         const char *encoding, *accepts;
249
250         /* only work on main request/no subrequests */
251         if (r->main) {
252             ap_remove_output_filter(f);
253             return ap_pass_brigade(f->next, bb);
254         }
255
256         /* some browsers might have problems, so set no-gzip
257          * (with browsermatch) for them
258          */
259         if (apr_table_get(r->subprocess_env, "no-gzip")) {
260             ap_remove_output_filter(f);
261             return ap_pass_brigade(f->next, bb);
262         }
263
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
267          */
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);
273         }
274
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.)
277          */
278         encoding = apr_table_get(r->headers_out, "Content-Encoding");
279         if (encoding) {
280             const char *tmp = encoding;
281
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);                        
287                 }
288                 /* Otherwise, skip token */
289                 tmp++;
290                 token = ap_get_token(r->pool, &tmp, 0);
291             }
292         }
293
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);
299         }
300
301         token = ap_get_token(r->pool, &accepts, 0);
302         while (token && token[0] && strcasecmp(token, "gzip")) {
303             /* skip token */
304             accepts++;
305             token = ap_get_token(r->pool, &accepts, 0);
306         }
307
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);
312         }
313
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);
318
319         zRC = deflateInit2(&ctx->stream, Z_BEST_SPEED, Z_DEFLATED,
320                            c->windowSize, c->memlevel,
321                            Z_DEFAULT_STRATEGY);
322
323         if (zRC != Z_OK) {
324             f->ctx = NULL;
325             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
326                           "unable to init Zlib: "
327                           "deflateInit2 returned %d: URL %s",
328                           zRC, r->uri);
329             return ap_pass_brigade(f->next, bb);
330         }
331
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);
337
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");
341         }
342         else {
343             apr_table_mergen(r->headers_out, "Content-Encoding", "gzip");
344         }
345         apr_table_setn(r->headers_out, "Vary", "Accept-Encoding");
346         apr_table_unset(r->headers_out, "Content-Length");
347     }
348     
349     /* initialize deflate output buffer */
350     ctx->stream.next_out = ctx->buffer;
351     ctx->stream.avail_out = c->bufferSize;
352
353     APR_BRIGADE_FOREACH(e, bb) {
354         const char *data;
355         apr_bucket *b;
356         apr_size_t len;
357
358         int done = 0;
359
360         if (APR_BUCKET_IS_EOS(e)) {
361             char *buf, *p;
362             char crc_array[4], len_array[4];
363             unsigned int deflate_len;
364
365             ctx->stream.avail_in = 0; /* should be zero already anyway */
366             for (;;) {
367                 deflate_len = c->bufferSize - ctx->stream.avail_out;
368
369                 if (deflate_len != 0) {
370                     b = apr_bucket_heap_create((char *)ctx->buffer,
371                                                deflate_len, NULL,
372                                                f->c->bucket_alloc);
373                     APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
374                     ctx->stream.next_out = ctx->buffer;
375                     ctx->stream.avail_out = c->bufferSize;
376                 }
377
378                 if (done) {
379                     break;
380                 }
381
382                 zRC = deflate(&ctx->stream, Z_FINISH);
383
384                 if (deflate_len == 0 && zRC == Z_BUF_ERROR) {
385                     zRC = Z_OK;
386                 }
387
388                 done = (ctx->stream.avail_out != 0 || zRC == Z_STREAM_END);
389
390                 if (zRC != Z_OK && zRC != Z_STREAM_END) {
391                     break;
392                 }
393             }
394
395             putLong(crc_array, ctx->crc);
396             putLong(len_array, ctx->stream.total_in);
397
398             p = buf = apr_palloc(r->pool, 8);
399             *p++ = crc_array[0];
400             *p++ = crc_array[1];
401             *p++ = crc_array[2];
402             *p++ = crc_array[3];
403             *p++ = len_array[0];
404             *p++ = len_array[1];
405             *p++ = len_array[2];
406             *p++ = len_array[3];
407
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);
413
414             if (c->noteName) {
415                 if (ctx->stream.total_in > 0) {
416                     int total;
417
418                     total = ctx->stream.total_out * 100 / ctx->stream.total_in;
419
420                     apr_table_setn(r->notes, c->noteName,
421                                    apr_itoa(r->pool, total));
422                 }
423                 else {
424                     apr_table_setn(r->notes, c->noteName, "-");
425                 }
426             }
427
428             deflateEnd(&ctx->stream);
429
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);
433
434             /* Okay, we've seen the EOS.
435              * Time to pass it along down the chain.
436              */
437             return ap_pass_brigade(f->next, ctx->bb);
438         }
439
440         if (APR_BUCKET_IS_FLUSH(e)) {
441             apr_bucket *bkt;
442             zRC = deflate(&(ctx->stream), Z_SYNC_FLUSH);
443             if (zRC != Z_OK) {
444                 return APR_EGENERAL;
445             }
446
447             ctx->stream.next_out = ctx->buffer;
448             len = c->bufferSize - ctx->stream.avail_out;
449
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;
454
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);
458             continue;
459         }
460
461         /* read */
462         apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
463
464         /* This crc32 function is from zlib. */
465         ctx->crc = crc32(ctx->crc, (const Bytef *)data, len);
466
467         /* write */
468         ctx->stream.next_in = (unsigned char *)data; /* We just lost const-ness,
469                                                       * but we'll just have to
470                                                       * trust zlib */
471         ctx->stream.avail_in = len;
472
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;
477
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;
482             }
483
484             zRC = deflate(&(ctx->stream), Z_NO_FLUSH);
485
486             if (zRC != Z_OK)
487                 return APR_EGENERAL;
488         }
489     }
490
491     apr_brigade_destroy(bb);
492     return APR_SUCCESS;
493 }
494
495 static void register_hooks(apr_pool_t *p)
496 {
497     ap_register_output_filter(deflateFilterName, deflate_out_filter,
498                               AP_FTYPE_CONTENT_SET);
499 }
500
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)"),
510     {NULL}
511 };
512
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 */
521 };