1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include "http_core.h"
20 #include "apr_strings.h"
22 #include <brotli/encode.h>
24 module AP_MODULE_DECLARE_DATA brotli_module;
27 ETAG_MODE_ADDSUFFIX = 0,
28 ETAG_MODE_NOCHANGE = 1,
32 typedef struct brotli_server_config_t {
36 etag_mode_e etag_mode;
37 const char *note_ratio_name;
38 const char *note_input_name;
39 const char *note_output_name;
40 } brotli_server_config_t;
42 static void *create_server_config(apr_pool_t *p, server_rec *s)
44 brotli_server_config_t *conf = apr_pcalloc(p, sizeof(*conf));
46 /* These default values allow mod_brotli to behave similarly to
47 * mod_deflate in terms of compression speed and memory usage.
49 * The idea is that since Brotli (generally) gives better compression
50 * ratio than Deflate, simply enabling mod_brotli on the server
51 * will reduce the amount of transferred data while keeping everything
52 * else unchanged. See https://quixdb.github.io/squash-benchmark/
56 /* Zero is a special value for BROTLI_PARAM_LGBLOCK that allows
57 * Brotli to automatically select the optimal input block size based
58 * on other encoder parameters. See enc/quality.h: ComputeLgBlock().
61 conf->etag_mode = ETAG_MODE_ADDSUFFIX;
66 static const char *set_filter_note(cmd_parms *cmd, void *dummy,
67 const char *arg1, const char *arg2)
69 brotli_server_config_t *conf =
70 ap_get_module_config(cmd->server->module_config, &brotli_module);
73 conf->note_ratio_name = arg1;
77 if (ap_cstr_casecmp(arg1, "Ratio") == 0) {
78 conf->note_ratio_name = arg2;
80 else if (ap_cstr_casecmp(arg1, "Input") == 0) {
81 conf->note_input_name = arg2;
83 else if (ap_cstr_casecmp(arg1, "Output") == 0) {
84 conf->note_output_name = arg2;
87 return apr_psprintf(cmd->pool, "Unknown BrotliFilterNote type '%s'",
94 static const char *set_compression_quality(cmd_parms *cmd, void *dummy,
97 brotli_server_config_t *conf =
98 ap_get_module_config(cmd->server->module_config, &brotli_module);
101 if (val < 0 || val > 11) {
102 return "BrotliCompressionQuality must be between 0 and 11";
109 static const char *set_compression_lgwin(cmd_parms *cmd, void *dummy,
112 brotli_server_config_t *conf =
113 ap_get_module_config(cmd->server->module_config, &brotli_module);
116 if (val < 10 || val > 24) {
117 return "BrotliCompressionWindow must be between 10 and 24";
124 static const char *set_compression_lgblock(cmd_parms *cmd, void *dummy,
127 brotli_server_config_t *conf =
128 ap_get_module_config(cmd->server->module_config, &brotli_module);
131 if (val < 16 || val > 24) {
132 return "BrotliCompressionMaxInputBlock must be between 16 and 24";
139 static const char *set_etag_mode(cmd_parms *cmd, void *dummy,
142 brotli_server_config_t *conf =
143 ap_get_module_config(cmd->server->module_config, &brotli_module);
145 if (ap_cstr_casecmp(arg, "AddSuffix") == 0) {
146 conf->etag_mode = ETAG_MODE_ADDSUFFIX;
148 else if (ap_cstr_casecmp(arg, "NoChange") == 0) {
149 conf->etag_mode = ETAG_MODE_NOCHANGE;
151 else if (ap_cstr_casecmp(arg, "Remove") == 0) {
152 conf->etag_mode = ETAG_MODE_REMOVE;
155 return "BrotliAlterETag accepts only 'AddSuffix', 'NoChange' and 'Remove'";
161 typedef struct brotli_ctx_t {
162 BrotliEncoderState *state;
163 apr_bucket_brigade *bb;
168 static void *alloc_func(void *opaque, size_t size)
170 return apr_bucket_alloc(size, opaque);
173 static void free_func(void *opaque, void *block)
176 apr_bucket_free(block);
180 static apr_status_t cleanup_ctx(void *data)
182 brotli_ctx_t *ctx = data;
184 BrotliEncoderDestroyInstance(ctx->state);
189 static brotli_ctx_t *create_ctx(int quality,
192 apr_bucket_alloc_t *alloc,
195 brotli_ctx_t *ctx = apr_pcalloc(pool, sizeof(*ctx));
197 ctx->state = BrotliEncoderCreateInstance(alloc_func, free_func, alloc);
198 BrotliEncoderSetParameter(ctx->state, BROTLI_PARAM_QUALITY, quality);
199 BrotliEncoderSetParameter(ctx->state, BROTLI_PARAM_LGWIN, lgwin);
200 BrotliEncoderSetParameter(ctx->state, BROTLI_PARAM_LGBLOCK, lgblock);
201 apr_pool_cleanup_register(pool, ctx, cleanup_ctx, apr_pool_cleanup_null);
203 ctx->bb = apr_brigade_create(pool, alloc);
210 static apr_status_t process_chunk(brotli_ctx_t *ctx,
215 const apr_byte_t *next_in = data;
216 apr_size_t avail_in = len;
218 while (avail_in > 0) {
219 apr_byte_t *next_out = NULL;
220 apr_size_t avail_out = 0;
222 if (!BrotliEncoderCompressStream(ctx->state,
223 BROTLI_OPERATION_PROCESS,
225 &avail_out, &next_out, NULL)) {
226 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, f->r, APLOGNO(03459)
227 "Error while compressing data");
231 if (BrotliEncoderHasMoreOutput(ctx->state)) {
232 apr_size_t output_len = 0;
233 const apr_byte_t *output;
237 /* Drain the accumulated output. Avoid copying the data by
238 * wrapping a pointer to the internal output buffer and passing
239 * it down to the next filter. The pointer is only valid until
240 * the next call to BrotliEncoderCompressStream(), but we're okay
241 * with that, since the brigade is cleaned up right after the
242 * ap_pass_brigade() call.
244 output = BrotliEncoderTakeOutput(ctx->state, &output_len);
245 ctx->total_out += output_len;
247 b = apr_bucket_transient_create((const char *)output, output_len,
248 ctx->bb->bucket_alloc);
249 APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
251 rv = ap_pass_brigade(f->next, ctx->bb);
252 apr_brigade_cleanup(ctx->bb);
253 if (rv != APR_SUCCESS) {
259 ctx->total_in += len;
263 static apr_status_t flush(brotli_ctx_t *ctx,
264 BrotliEncoderOperation op,
268 const apr_byte_t *next_in = NULL;
269 apr_size_t avail_in = 0;
270 apr_byte_t *next_out = NULL;
271 apr_size_t avail_out = 0;
272 apr_size_t output_len;
273 const apr_byte_t *output;
276 if (!BrotliEncoderCompressStream(ctx->state, op,
278 &avail_out, &next_out, NULL)) {
279 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, f->r, APLOGNO(03460)
280 "Error while compressing data");
284 if (!BrotliEncoderHasMoreOutput(ctx->state)) {
288 /* A flush can require several calls to BrotliEncoderCompressStream(),
289 * so place the data on the heap (otherwise, the pointer will become
290 * invalid after the next call to BrotliEncoderCompressStream()).
293 output = BrotliEncoderTakeOutput(ctx->state, &output_len);
294 ctx->total_out += output_len;
296 b = apr_bucket_heap_create((const char *)output, output_len, NULL,
297 ctx->bb->bucket_alloc);
298 APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
304 static const char *get_content_encoding(request_rec *r)
306 const char *encoding;
308 encoding = apr_table_get(r->headers_out, "Content-Encoding");
312 err_enc = apr_table_get(r->err_headers_out, "Content-Encoding");
314 encoding = apr_pstrcat(r->pool, encoding, ",", err_enc, NULL);
318 encoding = apr_table_get(r->err_headers_out, "Content-Encoding");
321 if (r->content_encoding) {
322 encoding = encoding ? apr_pstrcat(r->pool, encoding, ",",
323 r->content_encoding, NULL)
324 : r->content_encoding;
330 static apr_status_t compress_filter(ap_filter_t *f, apr_bucket_brigade *bb)
332 request_rec *r = f->r;
333 brotli_ctx_t *ctx = f->ctx;
335 brotli_server_config_t *conf;
337 if (APR_BRIGADE_EMPTY(bb)) {
341 conf = ap_get_module_config(r->server->module_config, &brotli_module);
344 const char *encoding;
347 const char *q = NULL;
349 /* Only work on main request, not subrequests, that are not
350 * a 204 response with no content, and are not tagged with the
351 * no-brotli env variable, and are not a partial response to
354 * Note that responding to 304 is handled separately to set
355 * the required headers (such as ETag) per RFC7232, 4.1.
357 if (r->main || r->status == HTTP_NO_CONTENT
358 || apr_table_get(r->subprocess_env, "no-brotli")
359 || apr_table_get(r->headers_out, "Content-Range")) {
360 ap_remove_output_filter(f);
361 return ap_pass_brigade(f->next, bb);
364 /* Let's see what our current Content-Encoding is. */
365 encoding = get_content_encoding(r);
368 const char *tmp = encoding;
370 token = ap_get_token(r->pool, &tmp, 0);
371 while (token && *token) {
372 if (strcmp(token, "identity") != 0 &&
373 strcmp(token, "7bit") != 0 &&
374 strcmp(token, "8bit") != 0 &&
375 strcmp(token, "binary") != 0) {
376 /* The data is already encoded, do nothing. */
377 ap_remove_output_filter(f);
378 return ap_pass_brigade(f->next, bb);
384 token = (*tmp) ? ap_get_token(r->pool, &tmp, 0) : NULL;
388 /* Even if we don't accept this request based on it not having
389 * the Accept-Encoding, we need to note that we were looking
390 * for this header and downstream proxies should be aware of
393 apr_table_mergen(r->headers_out, "Vary", "Accept-Encoding");
395 accepts = apr_table_get(r->headers_in, "Accept-Encoding");
397 ap_remove_output_filter(f);
398 return ap_pass_brigade(f->next, bb);
401 /* Do we have Accept-Encoding: br? */
402 token = ap_get_token(r->pool, &accepts, 0);
403 while (token && token[0] && ap_cstr_casecmp(token, "br") != 0) {
404 while (*accepts == ';') {
406 ap_get_token(r->pool, &accepts, 1);
409 if (*accepts == ',') {
412 token = (*accepts) ? ap_get_token(r->pool, &accepts, 0) : NULL;
415 /* Find the qvalue, if provided */
417 while (*accepts == ';') {
420 q = ap_get_token(r->pool, &accepts, 1);
421 ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
422 "token: '%s' - q: '%s'", token, q);
425 /* No acceptable token found or q=0 */
426 if (!token || token[0] == '\0' ||
427 (q && strlen(q) >= 3 && strncmp("q=0.000", q, strlen(q)) == 0)) {
428 ap_remove_output_filter(f);
429 return ap_pass_brigade(f->next, bb);
432 /* If the entire Content-Encoding is "identity", we can replace it. */
433 if (!encoding || ap_cstr_casecmp(encoding, "identity") == 0) {
434 apr_table_setn(r->headers_out, "Content-Encoding", "br");
436 apr_table_mergen(r->headers_out, "Content-Encoding", "br");
439 if (r->content_encoding) {
440 r->content_encoding = apr_table_get(r->headers_out,
444 apr_table_unset(r->headers_out, "Content-Length");
445 apr_table_unset(r->headers_out, "Content-MD5");
447 /* https://bz.apache.org/bugzilla/show_bug.cgi?id=39727
448 * https://bz.apache.org/bugzilla/show_bug.cgi?id=45023
450 * ETag must be unique among the possible representations, so a
451 * change to content-encoding requires a corresponding change to the
452 * ETag. We make this behavior configurable, and mimic mod_deflate's
453 * DeflateAlterETag with BrotliAlterETag to keep the transition from
454 * mod_deflate seamless.
456 if (conf->etag_mode == ETAG_MODE_REMOVE) {
457 apr_table_unset(r->headers_out, "ETag");
459 else if (conf->etag_mode == ETAG_MODE_ADDSUFFIX) {
460 const char *etag = apr_table_get(r->headers_out, "ETag");
463 apr_size_t len = strlen(etag);
465 if (len > 2 && etag[len - 1] == '"') {
466 etag = apr_pstrmemdup(r->pool, etag, len - 1);
467 etag = apr_pstrcat(r->pool, etag, "-br\"", NULL);
468 apr_table_setn(r->headers_out, "ETag", etag);
473 /* For 304 responses, we only need to send out the headers. */
474 if (r->status == HTTP_NOT_MODIFIED) {
475 ap_remove_output_filter(f);
476 return ap_pass_brigade(f->next, bb);
479 ctx = create_ctx(conf->quality, conf->lgwin, conf->lgblock,
480 f->c->bucket_alloc, r->pool);
484 while (!APR_BRIGADE_EMPTY(bb)) {
485 apr_bucket *e = APR_BRIGADE_FIRST(bb);
487 /* Optimization: If we are a HEAD request and bytes_sent is not zero
488 * it means that we have passed the content-length filter once and
489 * have more data to send. This means that the content-length filter
490 * could not determine our content-length for the response to the
491 * HEAD request anyway (the associated GET request would deliver the
492 * body in chunked encoding) and we can stop compressing.
494 if (r->header_only && r->bytes_sent) {
495 ap_remove_output_filter(f);
496 return ap_pass_brigade(f->next, bb);
499 if (APR_BUCKET_IS_EOS(e)) {
500 rv = flush(ctx, BROTLI_OPERATION_FINISH, f);
501 if (rv != APR_SUCCESS) {
505 /* Leave notes for logging. */
506 if (conf->note_input_name) {
507 apr_table_setn(r->notes, conf->note_input_name,
508 apr_off_t_toa(r->pool, ctx->total_in));
510 if (conf->note_output_name) {
511 apr_table_setn(r->notes, conf->note_output_name,
512 apr_off_t_toa(r->pool, ctx->total_out));
514 if (conf->note_ratio_name) {
515 if (ctx->total_in > 0) {
516 int ratio = (int) (ctx->total_out * 100 / ctx->total_in);
518 apr_table_setn(r->notes, conf->note_ratio_name,
519 apr_itoa(r->pool, ratio));
522 apr_table_setn(r->notes, conf->note_ratio_name, "-");
526 APR_BUCKET_REMOVE(e);
527 APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
529 rv = ap_pass_brigade(f->next, ctx->bb);
530 apr_brigade_cleanup(ctx->bb);
531 apr_pool_cleanup_run(r->pool, ctx, cleanup_ctx);
534 else if (APR_BUCKET_IS_FLUSH(e)) {
535 rv = flush(ctx, BROTLI_OPERATION_FLUSH, f);
536 if (rv != APR_SUCCESS) {
540 APR_BUCKET_REMOVE(e);
541 APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
543 rv = ap_pass_brigade(f->next, ctx->bb);
544 apr_brigade_cleanup(ctx->bb);
545 if (rv != APR_SUCCESS) {
549 else if (APR_BUCKET_IS_METADATA(e)) {
550 APR_BUCKET_REMOVE(e);
551 APR_BRIGADE_INSERT_TAIL(ctx->bb, e);
557 rv = apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
558 if (rv != APR_SUCCESS) {
561 rv = process_chunk(ctx, data, len, f);
562 if (rv != APR_SUCCESS) {
565 apr_bucket_delete(e);
571 static void register_hooks(apr_pool_t *p)
573 ap_register_output_filter("BROTLI_COMPRESS", compress_filter, NULL,
574 AP_FTYPE_CONTENT_SET);
577 static const command_rec cmds[] = {
578 AP_INIT_TAKE12("BrotliFilterNote", set_filter_note,
580 "Set a note to report on compression ratio"),
581 AP_INIT_TAKE1("BrotliCompressionQuality", set_compression_quality,
583 "Compression quality between 0 and 11 (higher quality means "
584 "slower compression)"),
585 AP_INIT_TAKE1("BrotliCompressionWindow", set_compression_lgwin,
587 "Sliding window size between 10 and 24 (larger windows can "
588 "improve compression, but require more memory)"),
589 AP_INIT_TAKE1("BrotliCompressionMaxInputBlock", set_compression_lgblock,
591 "Maximum input block size between 16 and 24 (larger block "
592 "sizes require more memory)"),
593 AP_INIT_TAKE1("BrotliAlterETag", set_etag_mode,
595 "Set how mod_brotli should modify ETag response headers: "
596 "'AddSuffix' (default), 'NoChange', 'Remove'"),
600 AP_DECLARE_MODULE(brotli) = {
601 STANDARD20_MODULE_STUFF,
602 NULL, /* create per-directory config structure */
603 NULL, /* merge per-directory config structures */
604 create_server_config, /* create per-server config structure */
605 NULL, /* merge per-server config structures */
606 cmds, /* command apr_table_t */
607 register_hooks /* register hooks */