]> granicus.if.org Git - apache/blob - modules/filters/mod_deflate.c
2c22bb55747ecc5497943962b6beb276d698fa66
[apache] / modules / filters / mod_deflate.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * mod_deflate.c: Perform deflate content-encoding on the fly
19  *
20  * Written by Ian Holsman, Justin Erenkrantz, and Nick Kew
21  */
22
23 /*
24  * Portions of this software are based upon zlib code by Jean-loup Gailly
25  * (zlib functions gz_open and gzwrite, check_header)
26  */
27
28 /* zlib flags */
29 #define ASCII_FLAG   0x01 /* bit 0 set: file probably ascii text */
30 #define HEAD_CRC     0x02 /* bit 1 set: header CRC present */
31 #define EXTRA_FIELD  0x04 /* bit 2 set: extra field present */
32 #define ORIG_NAME    0x08 /* bit 3 set: original file name present */
33 #define COMMENT      0x10 /* bit 4 set: file comment present */
34 #define RESERVED     0xE0 /* bits 5..7: reserved */
35
36
37 #include "httpd.h"
38 #include "http_config.h"
39 #include "http_log.h"
40 #include "apr_strings.h"
41 #include "apr_general.h"
42 #include "util_filter.h"
43 #include "apr_buckets.h"
44 #include "http_request.h"
45 #define APR_WANT_STRFUNC
46 #include "apr_want.h"
47
48 #include "zlib.h"
49
50 static const char deflateFilterName[] = "DEFLATE";
51 module AP_MODULE_DECLARE_DATA deflate_module;
52
53 typedef struct deflate_filter_config_t
54 {
55     int windowSize;
56     int memlevel;
57     int compressionlevel;
58     apr_size_t bufferSize;
59     char *note_ratio_name;
60     char *note_input_name;
61     char *note_output_name;
62 } deflate_filter_config;
63
64 /* RFC 1952 Section 2.3 defines the gzip header:
65  *
66  * +---+---+---+---+---+---+---+---+---+---+
67  * |ID1|ID2|CM |FLG|     MTIME     |XFL|OS |
68  * +---+---+---+---+---+---+---+---+---+---+
69  */
70 static const char gzip_header[10] =
71 { '\037', '\213', Z_DEFLATED, 0,
72   0, 0, 0, 0, /* mtime */
73   0, 0x03 /* Unix OS_CODE */
74 };
75
76 /* magic header */
77 static const char deflate_magic[2] = { '\037', '\213' };
78
79 /* windowsize is negative to suppress Zlib header */
80 #define DEFAULT_COMPRESSION Z_DEFAULT_COMPRESSION
81 #define DEFAULT_WINDOWSIZE -15
82 #define DEFAULT_MEMLEVEL 9
83 #define DEFAULT_BUFFERSIZE 8096
84
85 /* Outputs a long in LSB order to the given file
86  * only the bottom 4 bits are required for the deflate file format.
87  */
88 static void putLong(unsigned char *string, unsigned long x)
89 {
90     string[0] = (unsigned char)(x & 0xff);
91     string[1] = (unsigned char)((x & 0xff00) >> 8);
92     string[2] = (unsigned char)((x & 0xff0000) >> 16);
93     string[3] = (unsigned char)((x & 0xff000000) >> 24);
94 }
95
96 /* Inputs a string and returns a long.
97  */
98 static unsigned long getLong(unsigned char *string)
99 {
100     return ((unsigned long)string[0])
101           | (((unsigned long)string[1]) << 8)
102           | (((unsigned long)string[2]) << 16)
103           | (((unsigned long)string[3]) << 24);
104 }
105
106 static void *create_deflate_server_config(apr_pool_t *p, server_rec *s)
107 {
108     deflate_filter_config *c = apr_pcalloc(p, sizeof *c);
109
110     c->memlevel   = DEFAULT_MEMLEVEL;
111     c->windowSize = DEFAULT_WINDOWSIZE;
112     c->bufferSize = DEFAULT_BUFFERSIZE;
113     c->compressionlevel = DEFAULT_COMPRESSION;
114
115     return c;
116 }
117
118 static const char *deflate_set_window_size(cmd_parms *cmd, void *dummy,
119                                            const char *arg)
120 {
121     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
122                                                     &deflate_module);
123     int i;
124
125     i = atoi(arg);
126
127     if (i < 1 || i > 15)
128         return "DeflateWindowSize must be between 1 and 15";
129
130     c->windowSize = i * -1;
131
132     return NULL;
133 }
134
135 static const char *deflate_set_buffer_size(cmd_parms *cmd, void *dummy,
136                                            const char *arg)
137 {
138     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
139                                                     &deflate_module);
140     int n = atoi(arg);
141
142     if (n <= 0) {
143         return "DeflateBufferSize should be positive";
144     }
145
146     c->bufferSize = (apr_size_t)n;
147
148     return NULL;
149 }
150 static const char *deflate_set_note(cmd_parms *cmd, void *dummy,
151                                     const char *arg1, const char *arg2)
152 {
153     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
154                                                     &deflate_module);
155
156     if (arg2 == NULL) {
157         c->note_ratio_name = apr_pstrdup(cmd->pool, arg1);
158     }
159     else if (!strcasecmp(arg1, "ratio")) {
160         c->note_ratio_name = apr_pstrdup(cmd->pool, arg2);
161     }
162     else if (!strcasecmp(arg1, "input")) {
163         c->note_input_name = apr_pstrdup(cmd->pool, arg2);
164     }
165     else if (!strcasecmp(arg1, "output")) {
166         c->note_output_name = apr_pstrdup(cmd->pool, arg2);
167     }
168     else {
169         return apr_psprintf(cmd->pool, "Unknown note type %s", arg1);
170     }
171
172     return NULL;
173 }
174
175 static const char *deflate_set_memlevel(cmd_parms *cmd, void *dummy,
176                                         const char *arg)
177 {
178     deflate_filter_config *c = ap_get_module_config(cmd->server->module_config,
179                                                     &deflate_module);
180     int i;
181
182     i = atoi(arg);
183
184     if (i < 1 || i > 9)
185         return "DeflateMemLevel must be between 1 and 9";
186
187     c->memlevel = i;
188
189     return NULL;
190 }
191
192 static const char *deflate_set_compressionlevel(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     int i;
198
199     i = atoi(arg);
200
201     if (i < 1 || i > 9)
202         return "Compression Level must be between 1 and 9";
203
204     c->compressionlevel = i;
205
206     return NULL;
207 }
208
209 typedef struct deflate_ctx_t
210 {
211     z_stream stream;
212     unsigned char *buffer;
213     unsigned long crc;
214     apr_bucket_brigade *bb, *proc_bb;
215 } deflate_ctx;
216
217 static int flush_libz_buffer(deflate_ctx *ctx, deflate_filter_config *c,
218                              struct apr_bucket_alloc_t *bucket_alloc,
219                              int (*libz_func)(z_streamp, int), int flush)
220 {
221     int zRC;
222     int done = 0;
223     unsigned int deflate_len;
224     apr_bucket *b;
225
226     for (;;) {
227          deflate_len = c->bufferSize - ctx->stream.avail_out;
228
229          if (deflate_len != 0) {
230              b = apr_bucket_heap_create((char *)ctx->buffer,
231                                         deflate_len, NULL,
232                                         bucket_alloc);
233              APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
234              ctx->stream.next_out = ctx->buffer;
235              ctx->stream.avail_out = c->bufferSize;
236          }
237
238          if (done)
239              break;
240
241          zRC = libz_func(&ctx->stream, flush);
242
243          if (deflate_len == 0 && zRC == Z_BUF_ERROR)
244              zRC = Z_OK;
245
246          done = (ctx->stream.avail_out != 0 || zRC == Z_STREAM_END);
247
248          if (zRC != Z_OK && zRC != Z_STREAM_END)
249              break;
250     }
251     return zRC;
252 }
253
254 static apr_status_t deflate_out_filter(ap_filter_t *f,
255                                        apr_bucket_brigade *bb)
256 {
257     apr_bucket *e;
258     request_rec *r = f->r;
259     deflate_ctx *ctx = f->ctx;
260     int zRC;
261     deflate_filter_config *c = ap_get_module_config(r->server->module_config,
262                                                     &deflate_module);
263
264     /* Do nothing if asked to filter nothing. */
265     if (APR_BRIGADE_EMPTY(bb)) {
266         return APR_SUCCESS;
267     }
268
269     /* If we don't have a context, we need to ensure that it is okay to send
270      * the deflated content.  If we have a context, that means we've done
271      * this before and we liked it.
272      * This could be not so nice if we always fail.  But, if we succeed,
273      * we're in better shape.
274      */
275     if (!ctx) {
276         char *token;
277         const char *encoding;
278
279         /* only work on main request/no subrequests */
280         if (r->main != NULL) {
281             ap_remove_output_filter(f);
282             return ap_pass_brigade(f->next, bb);
283         }
284
285         /* some browsers might have problems, so set no-gzip
286          * (with browsermatch) for them
287          */
288         if (apr_table_get(r->subprocess_env, "no-gzip")) {
289             ap_remove_output_filter(f);
290             return ap_pass_brigade(f->next, bb);
291         }
292
293         /* Some browsers might have problems with content types
294          * other than text/html, so set gzip-only-text/html
295          * (with browsermatch) for them
296          */
297         if (r->content_type == NULL
298              || strncmp(r->content_type, "text/html", 9)) {
299             const char *env_value = apr_table_get(r->subprocess_env,
300                                                   "gzip-only-text/html");
301             if ( env_value && (strcmp(env_value,"1") == 0) ) {
302                 ap_remove_output_filter(f);
303                 return ap_pass_brigade(f->next, bb);
304             }
305         }
306
307         /* Let's see what our current Content-Encoding is.
308          * If it's already encoded, don't compress again.
309          * (We could, but let's not.)
310          */
311         encoding = apr_table_get(r->headers_out, "Content-Encoding");
312         if (encoding) {
313             const char *err_enc;
314
315             err_enc = apr_table_get(r->err_headers_out, "Content-Encoding");
316             if (err_enc) {
317                 encoding = apr_pstrcat(r->pool, encoding, ",", err_enc, NULL);
318             }
319         }
320         else {
321             encoding = apr_table_get(r->err_headers_out, "Content-Encoding");
322         }
323
324         if (r->content_encoding) {
325             encoding = encoding ? apr_pstrcat(r->pool, encoding, ",",
326                                               r->content_encoding, NULL)
327                                 : r->content_encoding;
328         }
329
330         if (encoding) {
331             const char *tmp = encoding;
332
333             token = ap_get_token(r->pool, &tmp, 0);
334             while (token && *token) {
335                 /* stolen from mod_negotiation: */
336                 if (strcmp(token, "identity") && strcmp(token, "7bit") &&
337                     strcmp(token, "8bit") && strcmp(token, "binary")) {
338
339                     ap_remove_output_filter(f);
340                     return ap_pass_brigade(f->next, bb);
341                 }
342
343                 /* Otherwise, skip token */
344                 if (*tmp) {
345                     ++tmp;
346                 }
347                 token = (*tmp) ? ap_get_token(r->pool, &tmp, 0) : NULL;
348             }
349         }
350
351         /* Even if we don't accept this request based on it not having
352          * the Accept-Encoding, we need to note that we were looking
353          * for this header and downstream proxies should be aware of that.
354          */
355         apr_table_mergen(r->headers_out, "Vary", "Accept-Encoding");
356
357         /* force-gzip will just force it out regardless if the browser
358          * can actually do anything with it.
359          */
360         if (!apr_table_get(r->subprocess_env, "force-gzip")) {
361             const char *accepts;
362             /* if they don't have the line, then they can't play */
363             accepts = apr_table_get(r->headers_in, "Accept-Encoding");
364             if (accepts == NULL) {
365                 ap_remove_output_filter(f);
366                 return ap_pass_brigade(f->next, bb);
367             }
368
369             token = ap_get_token(r->pool, &accepts, 0);
370             while (token && token[0] && strcasecmp(token, "gzip")) {
371                 /* skip parameters, XXX: ;q=foo evaluation? */
372                 while (*accepts == ';') {
373                     ++accepts;
374                     token = ap_get_token(r->pool, &accepts, 1);
375                 }
376
377                 /* retrieve next token */
378                 if (*accepts == ',') {
379                     ++accepts;
380                 }
381                 token = (*accepts) ? ap_get_token(r->pool, &accepts, 0) : NULL;
382             }
383
384             /* No acceptable token found. */
385             if (token == NULL || token[0] == '\0') {
386                 ap_remove_output_filter(f);
387                 return ap_pass_brigade(f->next, bb);
388             }
389         }
390
391         /* For a 304 or 204 response there is no entity included in
392          * the response and hence nothing to deflate. */
393         if (r->status == HTTP_NOT_MODIFIED || r->status == HTTP_NO_CONTENT) {
394             ap_remove_output_filter(f);
395             return ap_pass_brigade(f->next, bb);
396         }
397
398         /* We're cool with filtering this. */
399         ctx = f->ctx = apr_pcalloc(r->pool, sizeof(*ctx));
400         ctx->bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
401         ctx->buffer = apr_palloc(r->pool, c->bufferSize);
402
403         zRC = deflateInit2(&ctx->stream, c->compressionlevel, Z_DEFLATED,
404                            c->windowSize, c->memlevel,
405                            Z_DEFAULT_STRATEGY);
406
407         if (zRC != Z_OK) {
408             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
409                           "unable to init Zlib: "
410                           "deflateInit2 returned %d: URL %s",
411                           zRC, r->uri);
412             /*
413              * Remove ourselves as it does not make sense to return:
414              * We are not able to init libz and pass data down the chain
415              * uncompressed.
416              */
417             ap_remove_output_filter(f);
418             return ap_pass_brigade(f->next, bb);
419         }
420
421         /* add immortal gzip header */
422         e = apr_bucket_immortal_create(gzip_header, sizeof gzip_header,
423                                        f->c->bucket_alloc);
424         APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
425
426         /* If the entire Content-Encoding is "identity", we can replace it. */
427         if (!encoding || !strcasecmp(encoding, "identity")) {
428             apr_table_setn(r->headers_out, "Content-Encoding", "gzip");
429         }
430         else {
431             apr_table_mergen(r->headers_out, "Content-Encoding", "gzip");
432         }
433         apr_table_unset(r->headers_out, "Content-Length");
434
435         /* initialize deflate output buffer */
436         ctx->stream.next_out = ctx->buffer;
437         ctx->stream.avail_out = c->bufferSize;
438     }
439
440     while (!APR_BRIGADE_EMPTY(bb))
441     {
442         const char *data;
443         apr_bucket *b;
444         apr_size_t len;
445
446         e = APR_BRIGADE_FIRST(bb);
447
448         if (APR_BUCKET_IS_EOS(e)) {
449             char *buf;
450
451             ctx->stream.avail_in = 0; /* should be zero already anyway */
452             /* flush the remaining data from the zlib buffers */
453             flush_libz_buffer(ctx, c, f->c->bucket_alloc, deflate, Z_FINISH);
454
455             buf = apr_palloc(r->pool, 8);
456             putLong((unsigned char *)&buf[0], ctx->crc);
457             putLong((unsigned char *)&buf[4], ctx->stream.total_in);
458
459             b = apr_bucket_pool_create(buf, 8, r->pool, f->c->bucket_alloc);
460             APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
461             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
462                           "Zlib: Compressed %ld to %ld : URL %s",
463                           ctx->stream.total_in, ctx->stream.total_out, r->uri);
464
465             /* leave notes for logging */
466             if (c->note_input_name) {
467                 apr_table_setn(r->notes, c->note_input_name,
468                                (ctx->stream.total_in > 0)
469                                 ? apr_off_t_toa(r->pool,
470                                                 ctx->stream.total_in)
471                                 : "-");
472             }
473
474             if (c->note_output_name) {
475                 apr_table_setn(r->notes, c->note_output_name,
476                                (ctx->stream.total_in > 0)
477                                 ? apr_off_t_toa(r->pool,
478                                                 ctx->stream.total_out)
479                                 : "-");
480             }
481
482             if (c->note_ratio_name) {
483                 apr_table_setn(r->notes, c->note_ratio_name,
484                                (ctx->stream.total_in > 0)
485                                 ? apr_itoa(r->pool,
486                                            (int)(ctx->stream.total_out
487                                                  * 100
488                                                  / ctx->stream.total_in))
489                                 : "-");
490             }
491
492             deflateEnd(&ctx->stream);
493
494             /* Remove EOS from the old list, and insert into the new. */
495             APR_BUCKET_REMOVE(e);
496             APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
497
498             /* Okay, we've seen the EOS.
499              * Time to pass it along down the chain.
500              */
501             return ap_pass_brigade(f->next, ctx->bb);
502         }
503
504         if (APR_BUCKET_IS_FLUSH(e)) {
505             apr_status_t rv;
506
507             /* flush the remaining data from the zlib buffers */
508             zRC = flush_libz_buffer(ctx, c, f->c->bucket_alloc, deflate,
509                                     Z_SYNC_FLUSH);
510             if (zRC != Z_OK) {
511                 /*
512                  * Things screwed up. It is likely that we never return into
513                  * this filter, so clean libz's internal structures to avoid a
514                  * possible memory leak.
515                  */
516                 deflateEnd(&ctx->stream);
517                 /* Remove ourselves to ensure that we really NEVER come back */
518                 ap_remove_output_filter(f);
519                 return APR_EGENERAL;
520             }
521
522             /* Remove flush bucket from old brigade anf insert into the new. */
523             APR_BUCKET_REMOVE(e);
524             APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
525             rv = ap_pass_brigade(f->next, ctx->bb);
526             if (rv != APR_SUCCESS) {
527                 /*
528                  * Things screwed up. It is likely that we never return into
529                  * this filter, so clean libz's internal structures to avoid a
530                  * possible memory leak.
531                  */
532                 deflateEnd(&ctx->stream);
533                 /* Remove ourselves to ensure that we really NEVER come back */
534                 ap_remove_output_filter(f);
535                 return rv;
536             }
537             continue;
538         }
539
540         /* read */
541         apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
542
543         /* This crc32 function is from zlib. */
544         ctx->crc = crc32(ctx->crc, (const Bytef *)data, len);
545
546         /* write */
547         ctx->stream.next_in = (unsigned char *)data; /* We just lost const-ness,
548                                                       * but we'll just have to
549                                                       * trust zlib */
550         ctx->stream.avail_in = len;
551
552         while (ctx->stream.avail_in != 0) {
553             if (ctx->stream.avail_out == 0) {
554                 apr_status_t rv;
555
556                 ctx->stream.next_out = ctx->buffer;
557                 len = c->bufferSize - ctx->stream.avail_out;
558
559                 b = apr_bucket_heap_create((char *)ctx->buffer, len,
560                                            NULL, f->c->bucket_alloc);
561                 APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
562                 ctx->stream.avail_out = c->bufferSize;
563                 /* Send what we have right now to the next filter. */
564                 rv = ap_pass_brigade(f->next, ctx->bb);
565                 if (rv != APR_SUCCESS) {
566                     /*
567                      * Things screwed up. It is likely that we never return into
568                      * this filter, so clean libz's internal structures to avoid a
569                      * possible memory leak.
570                      */
571                     deflateEnd(&ctx->stream);
572                     /* Remove ourselves to ensure that we really NEVER come back */
573                     ap_remove_output_filter(f);
574                     return rv;
575                 }
576             }
577
578             zRC = deflate(&(ctx->stream), Z_NO_FLUSH);
579
580             if (zRC != Z_OK) {
581                 /*
582                  * Things screwed up. It is likely that we never return into
583                  * this filter, so clean libz's internal structures to avoid a
584                  * possible memory leak.
585                  */
586                 deflateEnd(&ctx->stream);
587                 /* Remove ourselves to ensure that we really NEVER come back */
588                 ap_remove_output_filter(f);
589                 return APR_EGENERAL;
590             }
591         }
592
593         apr_bucket_delete(e);
594     }
595
596     apr_brigade_cleanup(bb);
597     return APR_SUCCESS;
598 }
599
600 /* This is the deflate input filter (inflates).  */
601 static apr_status_t deflate_in_filter(ap_filter_t *f,
602                                       apr_bucket_brigade *bb,
603                                       ap_input_mode_t mode,
604                                       apr_read_type_e block,
605                                       apr_off_t readbytes)
606 {
607     apr_bucket *bkt;
608     request_rec *r = f->r;
609     deflate_ctx *ctx = f->ctx;
610     int zRC;
611     apr_status_t rv;
612     deflate_filter_config *c;
613
614     /* just get out of the way of things we don't want. */
615     if (mode != AP_MODE_READBYTES) {
616         return ap_get_brigade(f->next, bb, mode, block, readbytes);
617     }
618
619     c = ap_get_module_config(r->server->module_config, &deflate_module);
620
621     if (!ctx) {
622         int found = 0;
623         char *token, deflate_hdr[10];
624         const char *encoding;
625         apr_size_t len;
626
627         /* only work on main request/no subrequests */
628         if (!ap_is_initial_req(r)) {
629             ap_remove_input_filter(f);
630             return ap_get_brigade(f->next, bb, mode, block, readbytes);
631         }
632
633         /* Let's see what our current Content-Encoding is.
634          * If gzip is present, don't gzip again.  (We could, but let's not.)
635          */
636         encoding = apr_table_get(r->headers_in, "Content-Encoding");
637         if (encoding) {
638             const char *tmp = encoding;
639
640             token = ap_get_token(r->pool, &tmp, 0);
641             while (token && token[0]) {
642                 if (!strcasecmp(token, "gzip")) {
643                     found = 1;
644                     break;
645                 }
646                 /* Otherwise, skip token */
647                 tmp++;
648                 token = ap_get_token(r->pool, &tmp, 0);
649             }
650         }
651
652         if (found == 0) {
653             ap_remove_input_filter(f);
654             return ap_get_brigade(f->next, bb, mode, block, readbytes);
655         }
656
657         f->ctx = ctx = apr_pcalloc(f->r->pool, sizeof(*ctx));
658         ctx->bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
659         ctx->proc_bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
660         ctx->buffer = apr_palloc(r->pool, c->bufferSize);
661
662         rv = ap_get_brigade(f->next, ctx->bb, AP_MODE_READBYTES, block, 10);
663         if (rv != APR_SUCCESS) {
664             return rv;
665         }
666
667         len = 10;
668         rv = apr_brigade_flatten(ctx->bb, deflate_hdr, &len);
669         if (rv != APR_SUCCESS) {
670             return rv;
671         }
672
673         /* We didn't get the magic bytes. */
674         if (len != 10 ||
675             deflate_hdr[0] != deflate_magic[0] ||
676             deflate_hdr[1] != deflate_magic[1]) {
677             return APR_EGENERAL;
678         }
679
680         /* We can't handle flags for now. */
681         if (deflate_hdr[3] != 0) {
682             return APR_EGENERAL;
683         }
684
685         zRC = inflateInit2(&ctx->stream, c->windowSize);
686
687         if (zRC != Z_OK) {
688             f->ctx = NULL;
689             inflateEnd(&ctx->stream);
690             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
691                           "unable to init Zlib: "
692                           "inflateInit2 returned %d: URL %s",
693                           zRC, r->uri);
694             ap_remove_input_filter(f);
695             return ap_get_brigade(f->next, bb, mode, block, readbytes);
696         }
697
698         /* initialize deflate output buffer */
699         ctx->stream.next_out = ctx->buffer;
700         ctx->stream.avail_out = c->bufferSize;
701
702         apr_brigade_cleanup(ctx->bb);
703     }
704
705     if (APR_BRIGADE_EMPTY(ctx->proc_bb)) {
706         rv = ap_get_brigade(f->next, ctx->bb, mode, block, readbytes);
707
708         if (rv != APR_SUCCESS) {
709             /* What about APR_EAGAIN errors? */
710             inflateEnd(&ctx->stream);
711             return rv;
712         }
713
714         for (bkt = APR_BRIGADE_FIRST(ctx->bb);
715              bkt != APR_BRIGADE_SENTINEL(ctx->bb);
716              bkt = APR_BUCKET_NEXT(bkt))
717         {
718             const char *data;
719             apr_size_t len;
720
721             /* If we actually see the EOS, that means we screwed up! */
722             if (APR_BUCKET_IS_EOS(bkt)) {
723                 inflateEnd(&ctx->stream);
724                 return APR_EGENERAL;
725             }
726
727             if (APR_BUCKET_IS_FLUSH(bkt)) {
728                 apr_bucket *tmp_heap;
729                 zRC = inflate(&(ctx->stream), Z_SYNC_FLUSH);
730                 if (zRC != Z_OK) {
731                     inflateEnd(&ctx->stream);
732                     return APR_EGENERAL;
733                 }
734
735                 ctx->stream.next_out = ctx->buffer;
736                 len = c->bufferSize - ctx->stream.avail_out;
737
738                 ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
739                 tmp_heap = apr_bucket_heap_create((char *)ctx->buffer, len,
740                                                  NULL, f->c->bucket_alloc);
741                 APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, tmp_heap);
742                 ctx->stream.avail_out = c->bufferSize;
743
744                 /* Move everything to the returning brigade. */
745                 APR_BUCKET_REMOVE(bkt);
746                 APR_BRIGADE_CONCAT(bb, ctx->bb);
747                 break;
748             }
749
750             /* read */
751             apr_bucket_read(bkt, &data, &len, APR_BLOCK_READ);
752
753             /* pass through zlib inflate. */
754             ctx->stream.next_in = (unsigned char *)data;
755             ctx->stream.avail_in = len;
756
757             zRC = Z_OK;
758
759             while (ctx->stream.avail_in != 0) {
760                 if (ctx->stream.avail_out == 0) {
761                     apr_bucket *tmp_heap;
762                     ctx->stream.next_out = ctx->buffer;
763                     len = c->bufferSize - ctx->stream.avail_out;
764
765                     ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
766                     tmp_heap = apr_bucket_heap_create((char *)ctx->buffer, len,
767                                                       NULL, f->c->bucket_alloc);
768                     APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, tmp_heap);
769                     ctx->stream.avail_out = c->bufferSize;
770                 }
771
772                 zRC = inflate(&ctx->stream, Z_NO_FLUSH);
773
774                 if (zRC == Z_STREAM_END) {
775                     break;
776                 }
777
778                 if (zRC != Z_OK) {
779                     inflateEnd(&ctx->stream);
780                     return APR_EGENERAL;
781                 }
782             }
783             if (zRC == Z_STREAM_END) {
784                 apr_bucket *tmp_heap, *eos;
785
786                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
787                               "Zlib: Inflated %ld to %ld : URL %s",
788                               ctx->stream.total_in, ctx->stream.total_out,
789                               r->uri);
790
791                 len = c->bufferSize - ctx->stream.avail_out;
792
793                 ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
794                 tmp_heap = apr_bucket_heap_create((char *)ctx->buffer, len,
795                                                   NULL, f->c->bucket_alloc);
796                 APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, tmp_heap);
797                 ctx->stream.avail_out = c->bufferSize;
798
799                 /* Is the remaining 8 bytes already in the avail stream? */
800                 if (ctx->stream.avail_in >= 8) {
801                     unsigned long compCRC, compLen;
802                     compCRC = getLong(ctx->stream.next_in);
803                     if (ctx->crc != compCRC) {
804                         inflateEnd(&ctx->stream);
805                         return APR_EGENERAL;
806                     }
807                     ctx->stream.next_in += 4;
808                     compLen = getLong(ctx->stream.next_in);
809                     if (ctx->stream.total_out != compLen) {
810                         inflateEnd(&ctx->stream);
811                         return APR_EGENERAL;
812                     }
813                 }
814                 else {
815                     /* FIXME: We need to grab the 8 verification bytes
816                      * from the wire! */
817                     inflateEnd(&ctx->stream);
818                     return APR_EGENERAL;
819                 }
820
821                 inflateEnd(&ctx->stream);
822
823                 eos = apr_bucket_eos_create(f->c->bucket_alloc);
824                 APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, eos);
825                 break;
826             }
827
828         }
829         apr_brigade_cleanup(ctx->bb);
830     }
831
832     /* If we are about to return nothing for a 'blocking' read and we have
833      * some data in our zlib buffer, flush it out so we can return something.
834      */
835     if (block == APR_BLOCK_READ &&
836         APR_BRIGADE_EMPTY(ctx->proc_bb) &&
837         ctx->stream.avail_out < c->bufferSize) {
838         apr_bucket *tmp_heap;
839         apr_size_t len;
840         ctx->stream.next_out = ctx->buffer;
841         len = c->bufferSize - ctx->stream.avail_out;
842
843         ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
844         tmp_heap = apr_bucket_heap_create((char *)ctx->buffer, len,
845                                           NULL, f->c->bucket_alloc);
846         APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, tmp_heap);
847         ctx->stream.avail_out = c->bufferSize;
848     }
849
850     if (!APR_BRIGADE_EMPTY(ctx->proc_bb)) {
851         apr_bucket_brigade *newbb;
852
853         /* May return APR_INCOMPLETE which is fine by us. */
854         apr_brigade_partition(ctx->proc_bb, readbytes, &bkt);
855
856         newbb = apr_brigade_split(ctx->proc_bb, bkt);
857         APR_BRIGADE_CONCAT(bb, ctx->proc_bb);
858         APR_BRIGADE_CONCAT(ctx->proc_bb, newbb);
859     }
860
861     return APR_SUCCESS;
862 }
863
864
865 /* Filter to inflate for a content-transforming proxy.  */
866 static apr_status_t inflate_out_filter(ap_filter_t *f,
867                                       apr_bucket_brigade *bb)
868 {
869     int zlib_method;
870     int zlib_flags;
871     int deflate_init = 1;
872     apr_bucket *bkt;
873     request_rec *r = f->r;
874     deflate_ctx *ctx = f->ctx;
875     int zRC;
876     apr_status_t rv;
877     deflate_filter_config *c;
878
879     /* Do nothing if asked to filter nothing. */
880     if (APR_BRIGADE_EMPTY(bb)) {
881         return APR_SUCCESS;
882     }
883
884     c = ap_get_module_config(r->server->module_config, &deflate_module);
885
886     if (!ctx) {
887         int found = 0;
888         char *token;
889         const char *encoding;
890
891         /* only work on main request/no subrequests */
892         if (!ap_is_initial_req(r)) {
893             ap_remove_output_filter(f);
894             return ap_pass_brigade(f->next, bb);
895         }
896
897         /* Let's see what our current Content-Encoding is.
898          * If gzip is present, don't gzip again.  (We could, but let's not.)
899          */
900         encoding = apr_table_get(r->headers_out, "Content-Encoding");
901         if (encoding) {
902             const char *tmp = encoding;
903
904             token = ap_get_token(r->pool, &tmp, 0);
905             while (token && token[0]) {
906                 if (!strcasecmp(token, "gzip")) {
907                     found = 1;
908                     break;
909                 }
910                 /* Otherwise, skip token */
911                 tmp++;
912                 token = ap_get_token(r->pool, &tmp, 0);
913             }
914         }
915
916         if (found == 0) {
917             ap_remove_output_filter(f);
918             return ap_pass_brigade(f->next, bb);
919         }
920         apr_table_unset(r->headers_out, "Content-Encoding");
921
922         /* No need to inflate HEAD or 204/304 */
923         if (APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(bb))) {
924             ap_remove_output_filter(f);
925             return ap_pass_brigade(f->next, bb);
926         }
927
928
929         f->ctx = ctx = apr_pcalloc(f->r->pool, sizeof(*ctx));
930         ctx->proc_bb = apr_brigade_create(r->pool, f->c->bucket_alloc);
931         ctx->buffer = apr_palloc(r->pool, c->bufferSize);
932
933
934         zRC = inflateInit2(&ctx->stream, c->windowSize);
935
936         if (zRC != Z_OK) {
937             f->ctx = NULL;
938             inflateEnd(&ctx->stream);
939             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
940                           "unable to init Zlib: "
941                           "inflateInit2 returned %d: URL %s",
942                           zRC, r->uri);
943             ap_remove_output_filter(f);
944             return ap_pass_brigade(f->next, bb);
945         }
946
947         /* initialize deflate output buffer */
948         ctx->stream.next_out = ctx->buffer;
949         ctx->stream.avail_out = c->bufferSize;
950
951         deflate_init = 0;
952     }
953
954     for (bkt = APR_BRIGADE_FIRST(bb);
955          bkt != APR_BRIGADE_SENTINEL(bb);
956          bkt = APR_BUCKET_NEXT(bkt))
957     {
958         const char *data;
959         apr_size_t len;
960
961         /* If we actually see the EOS, that means we screwed up! */
962         /* no it doesn't - not in a HEAD or 204/304 */
963         if (APR_BUCKET_IS_EOS(bkt)) {
964             inflateEnd(&ctx->stream);
965             return ap_pass_brigade(f->next, bb);
966         }
967
968         if (APR_BUCKET_IS_FLUSH(bkt)) {
969             continue;
970         }
971
972         /* read */
973         apr_bucket_read(bkt, &data, &len, APR_BLOCK_READ);
974
975         /* first bucket contains zlib header */
976         if (!deflate_init++) {
977             if (len < 10) {
978                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
979                               "Insufficient data for inflate");
980                 return APR_EGENERAL;
981             }
982             else  {
983                 zlib_method = data[2];
984                 zlib_flags = data[3];
985                 if (zlib_method != Z_DEFLATED) {
986                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
987                                   "inflate: data not deflated!");
988                     ap_remove_output_filter(f);
989                     return ap_pass_brigade(f->next, bb);
990                 }
991                 if (data[0] != deflate_magic[0] ||
992                     data[1] != deflate_magic[1] ||
993                     (zlib_flags & RESERVED) != 0) {
994                         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
995                                       "inflate: bad header");
996                     return APR_EGENERAL ;
997                 }
998                 data += 10 ;
999                 len -= 10 ;
1000            }
1001            if (zlib_flags & EXTRA_FIELD) {
1002                unsigned int bytes = (unsigned int)(data[0]);
1003                bytes += ((unsigned int)(data[1])) << 8;
1004                bytes += 2;
1005                if (len < bytes) {
1006                    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1007                                  "inflate: extra field too big (not "
1008                                  "supported)");
1009                    return APR_EGENERAL;
1010                }
1011                data += bytes;
1012                len -= bytes;
1013            }
1014            if (zlib_flags & ORIG_NAME) {
1015                while (len-- && *data++);
1016            }
1017            if (zlib_flags & COMMENT) {
1018                while (len-- && *data++);
1019            }
1020            if (zlib_flags & HEAD_CRC) {
1021                 len -= 2;
1022                 data += 2;
1023            }
1024         }
1025
1026         /* pass through zlib inflate. */
1027         ctx->stream.next_in = (unsigned char *)data;
1028         ctx->stream.avail_in = len;
1029
1030         zRC = Z_OK;
1031
1032         while (ctx->stream.avail_in != 0) {
1033             if (ctx->stream.avail_out == 0) {
1034                 apr_bucket *tmp_heap;
1035                 ctx->stream.next_out = ctx->buffer;
1036                 len = c->bufferSize - ctx->stream.avail_out;
1037
1038                 ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
1039                 tmp_heap = apr_bucket_heap_create((char *)ctx->buffer, len,
1040                                                   NULL, f->c->bucket_alloc);
1041                 APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, tmp_heap);
1042                 ctx->stream.avail_out = c->bufferSize;
1043             }
1044
1045             zRC = inflate(&ctx->stream, Z_NO_FLUSH);
1046
1047             if (zRC == Z_STREAM_END) {
1048                 break;
1049             }
1050
1051             if (zRC != Z_OK) {
1052                     inflateEnd(&ctx->stream);
1053                     return APR_EGENERAL;
1054             }
1055         }
1056         if (zRC == Z_STREAM_END) {
1057             apr_bucket *tmp_heap, *eos;
1058
1059             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1060                           "Zlib: Inflated %ld to %ld : URL %s",
1061                           ctx->stream.total_in, ctx->stream.total_out,
1062                           r->uri);
1063
1064             len = c->bufferSize - ctx->stream.avail_out;
1065
1066             ctx->crc = crc32(ctx->crc, (const Bytef *)ctx->buffer, len);
1067             tmp_heap = apr_bucket_heap_create((char *)ctx->buffer, len,
1068                                               NULL, f->c->bucket_alloc);
1069             APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, tmp_heap);
1070             ctx->stream.avail_out = c->bufferSize;
1071
1072             /* Is the remaining 8 bytes already in the avail stream? */
1073             if (ctx->stream.avail_in >= 8) {
1074                 unsigned long compCRC, compLen;
1075                 compCRC = getLong(ctx->stream.next_in);
1076                 if (ctx->crc != compCRC) {
1077                     inflateEnd(&ctx->stream);
1078                     return APR_EGENERAL;
1079                 }
1080                 ctx->stream.next_in += 4;
1081                 compLen = getLong(ctx->stream.next_in);
1082                 if (ctx->stream.total_out != compLen) {
1083                     inflateEnd(&ctx->stream);
1084                     return APR_EGENERAL;
1085                 }
1086             }
1087             else {
1088                 /* FIXME: We need to grab the 8 verification bytes
1089                  * from the wire! */
1090                 inflateEnd(&ctx->stream);
1091                 return APR_EGENERAL;
1092             }
1093
1094             inflateEnd(&ctx->stream);
1095
1096             eos = apr_bucket_eos_create(f->c->bucket_alloc);
1097             APR_BRIGADE_INSERT_TAIL(ctx->proc_bb, eos);
1098             break;
1099         }
1100
1101     }
1102
1103     rv = ap_pass_brigade(f->next, ctx->proc_bb);
1104     apr_brigade_cleanup(ctx->proc_bb);
1105     return rv ;
1106 }
1107
1108 #define PROTO_FLAGS AP_FILTER_PROTO_CHANGE|AP_FILTER_PROTO_CHANGE_LENGTH
1109 static void register_hooks(apr_pool_t *p)
1110 {
1111     ap_register_output_filter(deflateFilterName, deflate_out_filter, NULL,
1112                               AP_FTYPE_CONTENT_SET);
1113     ap_register_output_filter("INFLATE", inflate_out_filter, NULL,
1114                               AP_FTYPE_RESOURCE-1);
1115     ap_register_input_filter(deflateFilterName, deflate_in_filter, NULL,
1116                               AP_FTYPE_CONTENT_SET);
1117 }
1118
1119 static const command_rec deflate_filter_cmds[] = {
1120     AP_INIT_TAKE12("DeflateFilterNote", deflate_set_note, NULL, RSRC_CONF,
1121                   "Set a note to report on compression ratio"),
1122     AP_INIT_TAKE1("DeflateWindowSize", deflate_set_window_size, NULL,
1123                   RSRC_CONF, "Set the Deflate window size (1-15)"),
1124     AP_INIT_TAKE1("DeflateBufferSize", deflate_set_buffer_size, NULL, RSRC_CONF,
1125                   "Set the Deflate Buffer Size"),
1126     AP_INIT_TAKE1("DeflateMemLevel", deflate_set_memlevel, NULL, RSRC_CONF,
1127                   "Set the Deflate Memory Level (1-9)"),
1128     AP_INIT_TAKE1("DeflateCompressionLevel", deflate_set_compressionlevel, NULL, RSRC_CONF,
1129                   "Set the Deflate Compression Level (1-9)"),
1130     {NULL}
1131 };
1132
1133 module AP_MODULE_DECLARE_DATA deflate_module = {
1134     STANDARD20_MODULE_STUFF,
1135     NULL,                         /* dir config creater */
1136     NULL,                         /* dir merger --- default is to override */
1137     create_deflate_server_config, /* server config */
1138     NULL,                         /* merge server config */
1139     deflate_filter_cmds,          /* command table */
1140     register_hooks                /* register hooks */
1141 };