xref: /lighttpd1.4/src/mod_deflate.c (revision 54c07b54)
1 /* mod_deflate
2  *
3  *
4  * bug fix on Robert Jakabosky from alphatrade.com's lighttp 1.4.10 mod_deflate patch
5  *
6  * Bug fix and new features:
7  * 1) fix loop bug when content-length is bigger than work-block-size*k
8  *
9  * -------
10  *
11  * lighttpd-1.4.26.mod_deflate.patch from
12  *   https://redmine.lighttpd.net/projects/1/wiki/Docs_ModDeflate
13  *
14  * -------
15  *
16  * Patch further modified in this incarnation.
17  *
18  * Note: this patch only handles completed responses
19  *         (r->resp_body_finished)
20  *       this patch does not currently handle streaming dynamic responses,
21  *       and therefore also does not worry about Transfer-Encoding: chunked
22  *       (or having separate con->output_queue for chunked-encoded output)
23  *       (or using separate buffers per connection instead of p->tmp_buf)
24  *       (or handling interactions with block buffering and write timeouts)
25  *
26  * Bug fix:
27  * - fixed major bug with compressing chunks with offset > 0
28  *     x-ref:
29  *       "Response breaking in mod_deflate"
30  *       https://redmine.lighttpd.net/issues/986
31  * - fix broken (in some cases) chunk accounting in deflate_compress_response()
32  * - fix broken bzip2
33  *     x-ref:
34  *       "mod_deflate's bzip2 broken by default"
35  *       https://redmine.lighttpd.net/issues/2035
36  * - fix mismatch with current chunk interfaces
37  *     x-ref:
38  *       "Weird things in chunk.c (functions only handling specific cases, unexpected behaviour)"
39  *       https://redmine.lighttpd.net/issues/1510
40  *
41  * Behavior changes from prior patch:
42  * - deflate.mimetypes must now be configured to enable compression
43  *     deflate.mimetypes = ( )          # compress nothing (disabled; default)
44  *     deflate.mimetypes = ( "" )       # compress all mimetypes
45  *     deflate.mimetypes = ( "text/" )  # compress text/... mimetypes
46  *     x-ref:
47  *       "mod_deflate enabled by default"
48  *       https://redmine.lighttpd.net/issues/1394
49  * - deflate.enabled directive removed (see new behavior of deflate.mimetypes)
50  * - deflate.debug removed (was developer debug trace, not end-user debug)
51  * - deflate.bzip2 replaced with deflate.allowed-encodings (like mod_compress)
52  *     x-ref:
53  *       "mod_deflate should allow limiting of compression algorithm from the configuration file"
54  *       https://redmine.lighttpd.net/issues/996
55  *       "mod_compress disabling methods"
56  *       https://redmine.lighttpd.net/issues/1773
57  * - deflate.nocompress-url removed since disabling compression for a URL
58  *   can now easily be done by setting to a blank list either directive
59  *   deflate.accept_encodings = () or deflate.mimetypes = () in a conditional
60  *   block, e.g. $HTTP["url"] =~ "....." { deflate.mimetypes = ( ) }
61  * - deflate.sync-flush removed; controlled by r->conf.stream_response_body
62  *     (though streaming compression not currently implemented in mod_deflate)
63  * - inactive directives in this patch
64  *       (since r->resp_body_finished required)
65  *     deflate.work-block-size
66  *     deflate.output-buffer-size
67  * - remove weak file size check; SIGBUS is trapped, file that shrink will error
68  *     x-ref:
69  *       "mod_deflate: filesize check is too weak"
70  *       https://redmine.lighttpd.net/issues/1512
71  * - change default deflate.min-compress-size from 0 to now be 256
72  *   http://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits
73  *   Apache 2.4 mod_deflate minimum is 68 bytes
74  *   Akamai recommends minimum 860 bytes
75  *   Google recommends minimum be somewhere in range between 150 and 1024 bytes
76  * - deflate.max-compress-size new directive (in kb like compress.max_filesize)
77  * - deflate.mem-level removed (too many knobs for little benefit)
78  * - deflate.window-size removed (too many knobs for little benefit)
79  *
80  * Future:
81  * - config directives may be changed, renamed, or removed
82  *   e.g. A set of reasonable defaults might be chosen
83  *        instead of making them configurable.
84  *     deflate.min-compress-size
85  * - might add deflate.mimetypes-exclude = ( ... ) for list of mimetypes
86  *   to avoid compressing, even if a broader deflate.mimetypes matched,
87  *   e.g. to compress all "text/" except "text/special".
88  *
89  * Implementation notes:
90  * - http_chunk_append_mem() used instead of http_chunk_append_buffer()
91  *   so that p->tmp_buf can be large and re-used.  This results in an extra copy
92  *   of compressed data before data is sent to network, though if the compressed
93  *   size is larger than 64k, it ends up being sent to a temporary file on
94  *   disk without suffering an extra copy in memory, and without extra chunk
95  *   create and destroy.  If this is ever changed to give away buffers, then use
96  *   a unique hctx->output buffer per hctx; do not reuse p->tmp_buf across
97  *   multiple requests being handled in parallel.
98  */
99 #include "first.h"
100 
101 #include <sys/types.h>
102 #include <sys/stat.h>
103 #include "sys-mmap.h"
104 #ifdef HAVE_MMAP
105 #include "sys-setjmp.h"
106 #endif
107 #include "sys-time.h"
108 
109 #include <fcntl.h>
110 #include <stdlib.h>
111 #include <string.h>
112 #include <errno.h>
113 #include <unistd.h>     /* getpid() read() unlink() write() */
114 
115 #include "base.h"
116 #include "ck.h"
117 #include "fdevent.h"
118 #include "log.h"
119 #include "buffer.h"
120 #include "http_chunk.h"
121 #include "http_etag.h"
122 #include "http_header.h"
123 #include "response.h"
124 #include "stat_cache.h"
125 
126 #include "plugin.h"
127 
128 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
129 # define USE_ZLIB
130 # include <zlib.h>
131 #endif
132 #ifndef Z_DEFAULT_COMPRESSION
133 #define Z_DEFAULT_COMPRESSION -1
134 #endif
135 #ifndef MAX_WBITS
136 #define MAX_WBITS 15
137 #endif
138 
139 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
140 # define USE_BZ2LIB
141 /* we don't need stdio interface */
142 # define BZ_NO_STDIO
143 # include <bzlib.h>
144 #endif
145 
146 #if defined HAVE_BROTLI_ENCODE_H && defined HAVE_BROTLI
147 # define USE_BROTLI
148 # include <brotli/encode.h>
149 #endif
150 
151 #if defined HAVE_ZSTD_H && defined HAVE_ZSTD
152 # define USE_ZSTD
153 # include <zstd.h>
154 #endif
155 
156 #ifndef HAVE_LIBZ
157 #undef HAVE_LIBDEFLATE
158 #endif
159 
160 /* request: accept-encoding */
161 #define HTTP_ACCEPT_ENCODING_IDENTITY BV(0)
162 #define HTTP_ACCEPT_ENCODING_GZIP     BV(1)
163 #define HTTP_ACCEPT_ENCODING_DEFLATE  BV(2)
164 #define HTTP_ACCEPT_ENCODING_COMPRESS BV(3)
165 #define HTTP_ACCEPT_ENCODING_BZIP2    BV(4)
166 #define HTTP_ACCEPT_ENCODING_X_GZIP   BV(5)
167 #define HTTP_ACCEPT_ENCODING_X_BZIP2  BV(6)
168 #define HTTP_ACCEPT_ENCODING_BR       BV(7)
169 #define HTTP_ACCEPT_ENCODING_ZSTD     BV(8)
170 
171 typedef struct {
172 	struct {
173 		int clevel;       /*(compression level)*/
174 		int windowBits;
175 		int memLevel;
176 		int strategy;
177 	} gzip;
178 	struct {
179 		uint32_t quality; /*(compression level)*/
180 		uint32_t window;
181 		uint32_t mode;
182 	} brotli;
183 	struct {
184 		int clevel;       /*(compression level)*/
185 		int strategy;
186 		int windowLog;
187 	} zstd;
188 	struct {
189 		int clevel;       /*(compression level)*/
190 	} bzip2;
191 } encparms;
192 
193 typedef struct {
194 	const array	*mimetypes;
195 	const buffer    *cache_dir;
196 	unsigned int	max_compress_size;
197 	unsigned short	min_compress_size;
198 	unsigned short	output_buffer_size;
199 	unsigned short	work_block_size;
200 	unsigned short	sync_flush;
201 	short		compression_level;
202 	uint16_t *	allowed_encodings;
203 	double		max_loadavg;
204 	const encparms *params;
205 } plugin_config;
206 
207 typedef struct {
208     PLUGIN_DATA;
209     plugin_config defaults;
210     plugin_config conf;
211 
212     buffer tmp_buf;
213 } plugin_data;
214 
215 typedef struct {
216 	union {
217 	      #ifdef USE_ZLIB
218 		z_stream z;
219 	      #endif
220 	      #ifdef USE_BZ2LIB
221 		bz_stream bz;
222 	      #endif
223 	      #ifdef USE_BROTLI
224 		BrotliEncoderState *br;
225 	      #endif
226 	      #ifdef USE_ZSTD
227 		ZSTD_CStream *cctx;
228 	      #endif
229 		int dummy;
230 	} u;
231 	off_t bytes_in;
232 	off_t bytes_out;
233 	buffer *output;
234 	plugin_data *plugin_data;
235 	request_st *r;
236 	int compression_type;
237 	int cache_fd;
238 	char *cache_fn;
239 	chunkqueue in_queue;
240 } handler_ctx;
241 
242 static handler_ctx *handler_ctx_init() {
243 	handler_ctx *hctx;
244 
245 	hctx = calloc(1, sizeof(*hctx));
246 	chunkqueue_init(&hctx->in_queue);
247 	hctx->cache_fd = -1;
248 
249 	return hctx;
250 }
251 
252 static void handler_ctx_free(handler_ctx *hctx) {
253 	if (hctx->cache_fn) {
254 		unlink(hctx->cache_fn);
255 		free(hctx->cache_fn);
256 	}
257 	if (-1 != hctx->cache_fd)
258 		close(hctx->cache_fd);
259       #if 0
260 	if (hctx->output != &p->tmp_buf) {
261 		buffer_free(hctx->output);
262 	}
263       #endif
264 	chunkqueue_reset(&hctx->in_queue);
265 	free(hctx);
266 }
267 
268 INIT_FUNC(mod_deflate_init) {
269     plugin_data * const p = calloc(1, sizeof(plugin_data));
270   #ifdef USE_ZSTD
271     buffer_string_prepare_copy(&p->tmp_buf, ZSTD_CStreamOutSize());
272   #else
273     buffer_string_prepare_copy(&p->tmp_buf, 65536);
274   #endif
275     return p;
276 }
277 
278 FREE_FUNC(mod_deflate_free) {
279     plugin_data *p = p_d;
280     free(p->tmp_buf.ptr);
281     if (NULL == p->cvlist) return;
282     /* (init i to 0 if global context; to 1 to skip empty global context) */
283     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
284         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
285         for (; -1 != cpv->k_id; ++cpv) {
286             if (cpv->vtype != T_CONFIG_LOCAL || NULL == cpv->v.v) continue;
287             switch (cpv->k_id) {
288               case 1: /* deflate.allowed-encodings */
289               case 14:/* deflate.params */
290                 free(cpv->v.v);
291                 break;
292               default:
293                 break;
294             }
295         }
296     }
297 }
298 
299 #if defined(_WIN32) && !defined(__CYGWIN__)
300 #define mkdir(x,y) mkdir(x)
301 #endif
302 
303 static int mkdir_for_file (char *fn) {
304     for (char *p = fn; (p = strchr(p + 1, '/')) != NULL; ) {
305         if (p[1] == '\0') return 0; /* ignore trailing slash */
306         *p = '\0';
307         int rc = mkdir(fn, 0700);
308         *p = '/';
309         if (0 != rc && errno != EEXIST) return -1;
310     }
311     return 0;
312 }
313 
314 static int mkdir_recursive (char *dir) {
315     return 0 == mkdir_for_file(dir) && (0 == mkdir(dir,0700) || errno == EEXIST)
316       ? 0
317       : -1;
318 }
319 
320 static buffer * mod_deflate_cache_file_name(request_st * const r, const buffer *cache_dir, const buffer * const etag) {
321     /* XXX: future: for shorter paths into the cache, we could checksum path,
322      *      and then shard it to avoid a huge single directory.
323      *      Alternatively, could use &r->uri.path, minus any
324      *      (matching) &r->pathinfo suffix, with result url-encoded
325      *      Alternative, we could shard etag which is already our "checksum" */
326     buffer * const tb = r->tmp_buf;
327     buffer_copy_path_len2(tb, BUF_PTR_LEN(cache_dir),
328                               BUF_PTR_LEN(&r->physical.path));
329     buffer_append_str2(tb, CONST_STR_LEN("-"), /*(strip surrounding '"')*/
330                            etag->ptr+1, buffer_clen(etag)-2);
331     return tb;
332 }
333 
334 static void mod_deflate_cache_file_open (handler_ctx * const hctx, const buffer * const fn) {
335     /* race exists whereby up to # workers might attempt to compress same
336      * file at same time if requested at same time, but this is unlikely
337      * and resolves itself by atomic rename into place when done */
338     const uint32_t fnlen = buffer_clen(fn);
339     hctx->cache_fn = malloc(fnlen+1+LI_ITOSTRING_LENGTH+1);
340     force_assert(hctx->cache_fn);
341     memcpy(hctx->cache_fn, fn->ptr, fnlen);
342     hctx->cache_fn[fnlen] = '.';
343     const size_t ilen =
344       li_itostrn(hctx->cache_fn+fnlen+1, LI_ITOSTRING_LENGTH, getpid());
345     hctx->cache_fn[fnlen+1+ilen] = '\0';
346     hctx->cache_fd = fdevent_open_cloexec(hctx->cache_fn, 1, O_RDWR|O_CREAT, 0600);
347     if (-1 == hctx->cache_fd) {
348         free(hctx->cache_fn);
349         hctx->cache_fn = NULL;
350     }
351 }
352 
353 static int mod_deflate_cache_file_finish (request_st * const r, handler_ctx * const hctx, const buffer * const fn) {
354     if (0 != fdevent_rename(hctx->cache_fn, fn->ptr))
355         return -1;
356     free(hctx->cache_fn);
357     hctx->cache_fn = NULL;
358     chunkqueue_reset(&r->write_queue);
359     int rc = http_chunk_append_file_fd(r, fn, hctx->cache_fd, hctx->bytes_out);
360     hctx->cache_fd = -1;
361     return rc;
362 }
363 
364 static void mod_deflate_merge_config_cpv(plugin_config * const pconf, const config_plugin_value_t * const cpv) {
365     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
366       case 0: /* deflate.mimetypes */
367         pconf->mimetypes = cpv->v.a;
368         break;
369       case 1: /* deflate.allowed-encodings */
370         if (cpv->vtype == T_CONFIG_LOCAL)
371             pconf->allowed_encodings = cpv->v.v;
372         break;
373       case 2: /* deflate.max-compress-size */
374         pconf->max_compress_size = cpv->v.u;
375         break;
376       case 3: /* deflate.min-compress-size */
377         pconf->min_compress_size = cpv->v.shrt;
378         break;
379       case 4: /* deflate.compression-level */
380         pconf->compression_level = (short)cpv->v.shrt;
381         break;
382       case 5: /* deflate.output-buffer-size */
383         pconf->output_buffer_size = cpv->v.shrt;
384         break;
385       case 6: /* deflate.work-block-size */
386         pconf->work_block_size = cpv->v.shrt;
387         break;
388       case 7: /* deflate.max-loadavg */
389         pconf->max_loadavg = cpv->v.d;
390         break;
391       case 8: /* deflate.cache-dir */
392         pconf->cache_dir = cpv->v.b;
393         break;
394     #if 0 /*(cpv->k_id remapped in mod_deflate_set_defaults())*/
395       case 9: /* compress.filetype */
396         pconf->mimetypes = cpv->v.a;
397         break;
398       case 10:/* compress.allowed-encodings */
399         if (cpv->vtype == T_CONFIG_LOCAL)
400             pconf->allowed_encodings = cpv->v.v;
401         break;
402       case 11:/* compress.cache-dir */
403         pconf->cache_dir = cpv->v.b;
404         break;
405       case 12:/* compress.max-filesize */
406         pconf->max_compress_size = cpv->v.u;
407         break;
408       case 13:/* compress.max-loadavg */
409         pconf->max_loadavg = cpv->v.d;
410         break;
411     #endif
412       case 14:/* deflate.params */
413         if (cpv->vtype == T_CONFIG_LOCAL)
414             pconf->params = cpv->v.v;
415         break;
416       default:/* should not happen */
417         return;
418     }
419 }
420 
421 static void mod_deflate_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) {
422     do {
423         mod_deflate_merge_config_cpv(pconf, cpv);
424     } while ((++cpv)->k_id != -1);
425 }
426 
427 static void mod_deflate_patch_config(request_st * const r, plugin_data * const p) {
428     memcpy(&p->conf, &p->defaults, sizeof(plugin_config));
429     for (int i = 1, used = p->nconfig; i < used; ++i) {
430         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
431             mod_deflate_merge_config(&p->conf, p->cvlist + p->cvlist[i].v.u2[0]);
432     }
433 }
434 
435 static encparms * mod_deflate_parse_params(const array * const a, log_error_st * const errh) {
436     encparms * params = calloc(1, sizeof(encparms));
437     force_assert(params);
438 
439     /* set defaults */
440   #ifdef USE_ZLIB
441     params->gzip.clevel = 0; /*(unset)*/
442     params->gzip.windowBits = MAX_WBITS;
443     params->gzip.memLevel = 8;
444     params->gzip.strategy = Z_DEFAULT_STRATEGY;
445   #endif
446   #ifdef USE_BROTLI
447     /* BROTLI_DEFAULT_QUALITY is 11 and can be *very* time-consuming */
448     params->brotli.quality = 5;
449     params->brotli.window = BROTLI_DEFAULT_WINDOW;
450     params->brotli.mode = BROTLI_MODE_GENERIC;
451   #endif
452   #ifdef USE_ZSTD
453     params->zstd.clevel = ZSTD_CLEVEL_DEFAULT;
454     params->zstd.strategy = 0; /*(use default strategy)*/
455     params->zstd.windowLog = 0;/*(use default windowLog)*/
456   #endif
457   #ifdef USE_BZ2LIB
458     params->bzip2.clevel = 0; /*(unset)*/
459   #endif
460 
461     for (uint32_t i = 0; i < a->used; ++i) {
462         const data_unset * const du = a->data[i];
463       #if defined(USE_ZLIB) || defined(USE_BZ2LIB) || defined(USE_BROTLI) \
464        || defined(USE_ZSTD)
465         int32_t v = config_plugin_value_to_int32(du, -1);
466       #endif
467       #ifdef USE_BROTLI
468         if (buffer_eq_icase_slen(&du->key,
469                                  CONST_STR_LEN("BROTLI_PARAM_QUALITY"))) {
470             /*(future: could check for string and then look for and translate
471              * BROTLI_DEFAULT_QUALITY BROTLI_MIN_QUALITY BROTLI_MAX_QUALITY)*/
472             if (BROTLI_MIN_QUALITY <= v && v <= BROTLI_MAX_QUALITY)
473                 params->brotli.quality = (uint32_t)v; /* 0 .. 11 */
474             else
475                 log_error(errh, __FILE__, __LINE__,
476                           "invalid value for BROTLI_PARAM_QUALITY");
477             continue;
478         }
479         if (buffer_eq_icase_slen(&du->key,
480                                  CONST_STR_LEN("BROTLI_PARAM_LGWIN"))) {
481             /*(future: could check for string and then look for and translate
482              * BROTLI_DEFAULT_WINDOW
483              * BROTLI_MIN_WINDOW_BITS BROTLI_MAX_WINDOW_BITS)*/
484             if (BROTLI_MIN_WINDOW_BITS <= v && v <= BROTLI_MAX_WINDOW_BITS)
485                 params->brotli.window = (uint32_t)v; /* 10 .. 24 */
486             else
487                 log_error(errh, __FILE__, __LINE__,
488                           "invalid value for BROTLI_PARAM_LGWIN");
489             continue;
490         }
491         if (buffer_eq_icase_slen(&du->key,
492                                  CONST_STR_LEN("BROTLI_PARAM_MODE"))) {
493             /*(future: could check for string and then look for and translate
494              * BROTLI_MODE_GENERIC BROTLI_MODE_TEXT BROTLI_MODE_FONT)*/
495             if (0 <= v && v <= 2)
496                 params->brotli.mode = (uint32_t)v; /* 0 .. 2 */
497             else
498                 log_error(errh, __FILE__, __LINE__,
499                           "invalid value for BROTLI_PARAM_MODE");
500             continue;
501         }
502       #endif
503       #ifdef USE_ZSTD
504         if (buffer_eq_icase_slen(&du->key,
505                                  CONST_STR_LEN("ZSTD_c_compressionLevel"))) {
506             params->zstd.clevel = v;
507             /*(not warning if number parse error.  future: to detect, could
508              * use absurd default to config_plugin_value_to_int32 to detect)*/
509             continue;
510         }
511        #if ZSTD_VERSION_NUMBER >= 10000+400+0 /* v1.4.0 */
512         /*(XXX: (selected) experimental API params in zstd v1.4.0)*/
513         if (buffer_eq_icase_slen(&du->key,
514                                  CONST_STR_LEN("ZSTD_c_strategy"))) {
515             /*(future: could check for string and then look for and translate
516              * enum ZSTD_strategy ZSTD_STRATEGY_MIN ZSTD_STRATEGY_MAX)*/
517             #ifndef ZSTD_STRATEGY_MIN
518             #define ZSTD_STRATEGY_MIN 1
519             #endif
520             #ifndef ZSTD_STRATEGY_MAX
521             #define ZSTD_STRATEGY_MAX 9
522             #endif
523             if (ZSTD_STRATEGY_MIN <= v && v <= ZSTD_STRATEGY_MAX)
524                 params->zstd.strategy = v; /* 1 .. 9 */
525             else
526                 log_error(errh, __FILE__, __LINE__,
527                           "invalid value for ZSTD_c_strategy");
528             continue;
529         }
530         if (buffer_eq_icase_slen(&du->key,
531                                  CONST_STR_LEN("ZSTD_c_windowLog"))) {
532             /*(future: could check for string and then look for and translate
533              * ZSTD_WINDOWLOG_MIN ZSTD_WINDOWLOG_MAX)*/
534             #ifndef ZSTD_WINDOWLOG_MIN
535             #define ZSTD_WINDOWLOG_MIN 10
536             #endif
537             #ifndef ZSTD_WINDOWLOG_MAX_32
538             #define ZSTD_WINDOWLOG_MAX_32 30
539             #endif
540             #ifndef ZSTD_WINDOWLOG_MAX_64
541             #define ZSTD_WINDOWLOG_MAX_64 31
542             #endif
543             #ifndef ZSTD_WINDOWLOG_MAX
544             #define ZSTD_WINDOWLOG_MAX \
545              (sizeof(size_t)==4 ? ZSTD_WINDOWLOG_MAX_32 : ZSTD_WINDOWLOG_MAX_64)
546             #endif
547             if (ZSTD_WINDOWLOG_MIN <= v && v <= ZSTD_WINDOWLOG_MAX)
548                 params->zstd.windowLog = v;/* 10 .. 31 *//*(30 max for 32-bit)*/
549             else
550                 log_error(errh, __FILE__, __LINE__,
551                           "invalid value for ZSTD_c_windowLog");
552             continue;
553         }
554        #endif
555       #endif
556       #ifdef USE_ZLIB
557         if (buffer_eq_icase_slen(&du->key,
558                                  CONST_STR_LEN("gzip.level"))) {
559             if (1 <= v && v <= 9)
560                 params->gzip.clevel = v; /* 1 .. 9 */
561             else
562                 log_error(errh, __FILE__, __LINE__,
563                           "invalid value for gzip.level");
564             continue;
565         }
566         if (buffer_eq_icase_slen(&du->key,
567                                  CONST_STR_LEN("gzip.windowBits"))) {
568             if (9 <= v && v <= 15)
569                 params->gzip.windowBits = v; /* 9 .. 15 */
570             else
571                 log_error(errh, __FILE__, __LINE__,
572                           "invalid value for gzip.windowBits");
573             continue;
574         }
575         if (buffer_eq_icase_slen(&du->key,
576                                  CONST_STR_LEN("gzip.memLevel"))) {
577             if (1 <= v && v <= 9)
578                 params->gzip.memLevel = v; /* 1 .. 9 */
579             else
580                 log_error(errh, __FILE__, __LINE__,
581                           "invalid value for gzip.memLevel");
582             continue;
583         }
584         if (buffer_eq_icase_slen(&du->key,
585                                  CONST_STR_LEN("gzip.strategy"))) {
586             /*(future: could check for string and then look for and translate
587              * Z_DEFAULT_STRATEGY Z_FILTERED Z_HUFFMAN_ONLY Z_RLE Z_FIXED)*/
588             if (0 <= v && v <= 4)
589                 params->gzip.strategy = v; /* 0 .. 4 */
590             else
591                 log_error(errh, __FILE__, __LINE__,
592                           "invalid value for gzip.strategy");
593             continue;
594         }
595       #endif
596       #ifdef USE_BZ2LIB
597         if (buffer_eq_icase_slen(&du->key,
598                                  CONST_STR_LEN("bzip2.blockSize100k"))) {
599             if (1 <= v && v <= 9) /*(bzip2 blockSize100k param)*/
600                 params->bzip2.clevel = v; /* 1 .. 9 */
601             else
602                 log_error(errh, __FILE__, __LINE__,
603                           "invalid value for bzip2.blockSize100k");
604             continue;
605         }
606       #endif
607         log_error(errh, __FILE__, __LINE__,
608                   "unrecognized param: %s", du->key.ptr);
609     }
610 
611     return params;
612 }
613 
614 static uint16_t * mod_deflate_encodings_to_flags(const array *encodings) {
615     if (encodings->used) {
616         uint16_t * const x = calloc(encodings->used+1, sizeof(short));
617         force_assert(x);
618         int i = 0;
619         for (uint32_t j = 0; j < encodings->used; ++j) {
620           #if defined(USE_ZLIB) || defined(USE_BZ2LIB) || defined(USE_BROTLI) \
621            || defined(USE_ZSTD)
622             data_string *ds = (data_string *)encodings->data[j];
623           #endif
624           #ifdef USE_ZLIB /* "gzip", "x-gzip" */
625             if (NULL != strstr(ds->value.ptr, "gzip"))
626                 x[i++] = HTTP_ACCEPT_ENCODING_GZIP
627                        | HTTP_ACCEPT_ENCODING_X_GZIP;
628             if (NULL != strstr(ds->value.ptr, "deflate"))
629                 x[i++] = HTTP_ACCEPT_ENCODING_DEFLATE;
630             /*
631             if (NULL != strstr(ds->value.ptr, "compress"))
632                 x[i++] = HTTP_ACCEPT_ENCODING_COMPRESS;
633             */
634           #endif
635           #ifdef USE_BZ2LIB /* "bzip2", "x-bzip2" */
636             if (NULL != strstr(ds->value.ptr, "bzip2"))
637                 x[i++] = HTTP_ACCEPT_ENCODING_BZIP2
638                        | HTTP_ACCEPT_ENCODING_X_BZIP2;
639           #endif
640           #ifdef USE_BROTLI /* "br" (also accepts "brotli") */
641             if (NULL != strstr(ds->value.ptr, "br"))
642                 x[i++] = HTTP_ACCEPT_ENCODING_BR;
643           #endif
644           #ifdef USE_ZSTD
645             if (NULL != strstr(ds->value.ptr, "zstd"))
646                 x[i++] = HTTP_ACCEPT_ENCODING_ZSTD;
647           #endif
648         }
649         x[i] = 0; /* end of list */
650         return x;
651     }
652     else {
653         /* default encodings */
654         uint16_t * const x = calloc(4+1, sizeof(short));
655         force_assert(x);
656         int i = 0;
657       #ifdef USE_ZSTD
658         x[i++] = HTTP_ACCEPT_ENCODING_ZSTD;
659       #endif
660       #ifdef USE_BROTLI
661         x[i++] = HTTP_ACCEPT_ENCODING_BR;
662       #endif
663       #ifdef USE_BZ2LIB
664         x[i++] = HTTP_ACCEPT_ENCODING_BZIP2
665                | HTTP_ACCEPT_ENCODING_X_BZIP2;
666       #endif
667       #ifdef USE_ZLIB
668         x[i++] = HTTP_ACCEPT_ENCODING_GZIP
669                | HTTP_ACCEPT_ENCODING_X_GZIP
670                | HTTP_ACCEPT_ENCODING_DEFLATE;
671       #endif
672         x[i] = 0; /* end of list */
673         return x;
674     }
675 }
676 
677 SETDEFAULTS_FUNC(mod_deflate_set_defaults) {
678     static const config_plugin_keys_t cpk[] = {
679       { CONST_STR_LEN("deflate.mimetypes"),
680         T_CONFIG_ARRAY_VLIST,
681         T_CONFIG_SCOPE_CONNECTION }
682      ,{ CONST_STR_LEN("deflate.allowed-encodings"),
683         T_CONFIG_ARRAY_VLIST,
684         T_CONFIG_SCOPE_CONNECTION }
685      ,{ CONST_STR_LEN("deflate.max-compress-size"),
686         T_CONFIG_INT,
687         T_CONFIG_SCOPE_CONNECTION }
688      ,{ CONST_STR_LEN("deflate.min-compress-size"),
689         T_CONFIG_SHORT,
690         T_CONFIG_SCOPE_CONNECTION }
691      ,{ CONST_STR_LEN("deflate.compression-level"),
692         T_CONFIG_SHORT,
693         T_CONFIG_SCOPE_CONNECTION }
694      ,{ CONST_STR_LEN("deflate.output-buffer-size"),
695         T_CONFIG_SHORT,
696         T_CONFIG_SCOPE_CONNECTION }
697      ,{ CONST_STR_LEN("deflate.work-block-size"),
698         T_CONFIG_SHORT,
699         T_CONFIG_SCOPE_CONNECTION }
700      ,{ CONST_STR_LEN("deflate.max-loadavg"),
701         T_CONFIG_STRING,
702         T_CONFIG_SCOPE_CONNECTION }
703      ,{ CONST_STR_LEN("deflate.cache-dir"),
704         T_CONFIG_STRING,
705         T_CONFIG_SCOPE_CONNECTION }
706      ,{ CONST_STR_LEN("compress.filetype"),
707         T_CONFIG_ARRAY_VLIST,
708         T_CONFIG_SCOPE_CONNECTION }
709      ,{ CONST_STR_LEN("compress.allowed-encodings"),
710         T_CONFIG_ARRAY_VLIST,
711         T_CONFIG_SCOPE_CONNECTION }
712      ,{ CONST_STR_LEN("compress.cache-dir"),
713         T_CONFIG_STRING,
714         T_CONFIG_SCOPE_CONNECTION }
715      ,{ CONST_STR_LEN("compress.max-filesize"),
716         T_CONFIG_INT,
717         T_CONFIG_SCOPE_CONNECTION }
718      ,{ CONST_STR_LEN("compress.max-loadavg"),
719         T_CONFIG_STRING,
720         T_CONFIG_SCOPE_CONNECTION }
721      ,{ CONST_STR_LEN("deflate.params"),
722         T_CONFIG_ARRAY_KVANY,
723         T_CONFIG_SCOPE_CONNECTION }
724      ,{ NULL, 0,
725         T_CONFIG_UNSET,
726         T_CONFIG_SCOPE_UNSET }
727     };
728 
729     plugin_data * const p = p_d;
730     if (!config_plugin_values_init(srv, p, cpk, "mod_deflate"))
731         return HANDLER_ERROR;
732 
733     /* process and validate config directives
734      * (init i to 0 if global context; to 1 to skip empty global context) */
735     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
736         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
737         for (; -1 != cpv->k_id; ++cpv) {
738             switch (cpv->k_id) {
739               case 9: /* compress.filetype */
740                 log_error(srv->errh, __FILE__, __LINE__,
741                   "DEPRECATED: %s replaced with deflate.mimetypes",
742                   cpk[cpv->k_id].k);
743                 cpv->k_id = 0; /* deflate.mimetypes */
744                 __attribute_fallthrough__
745               case 0: /* deflate.mimetypes */
746                 /* mod_deflate matches mimetype as prefix of Content-Type
747                  * so ignore '*' at end of mimetype for end-user flexibility
748                  * in specifying trailing wildcard to grouping of mimetypes */
749                 for (uint32_t m = 0; m < cpv->v.a->used; ++m) {
750                     buffer *mimetype=&((data_string *)cpv->v.a->data[m])->value;
751                     size_t len = buffer_clen(mimetype);
752                     if (len > 2 && mimetype->ptr[len-1] == '*')
753                         buffer_truncate(mimetype, len-1);
754                 }
755                 if (0 == cpv->v.a->used) cpv->v.a = NULL;
756                 break;
757               case 10:/* compress.allowed-encodings */
758                 log_error(srv->errh, __FILE__, __LINE__,
759                   "DEPRECATED: %s replaced with deflate.allowed-encodings",
760                   cpk[cpv->k_id].k);
761                 cpv->k_id = 1; /* deflate.allowed-encodings */
762                 __attribute_fallthrough__
763               case 1: /* deflate.allowed-encodings */
764                 cpv->v.v = mod_deflate_encodings_to_flags(cpv->v.a);
765                 cpv->vtype = T_CONFIG_LOCAL;
766                 break;
767               case 12:/* compress.max-filesize */
768                 log_error(srv->errh, __FILE__, __LINE__,
769                   "DEPRECATED: %s replaced with deflate.max-compress-size",
770                   cpk[cpv->k_id].k);
771                 cpv->k_id = 2; /* deflate.max-compress-size */
772                 __attribute_fallthrough__
773               case 2: /* deflate.max-compress-size */
774               case 3: /* deflate.min-compress-size */
775                 break;
776               case 4: /* deflate.compression-level */
777                 if ((cpv->v.shrt < 1 || cpv->v.shrt > 9)
778                     && *(short *)&cpv->v.shrt != -1) {
779                     log_error(srv->errh, __FILE__, __LINE__,
780                       "compression-level must be between 1 and 9: %hu",
781                       cpv->v.shrt);
782                     return HANDLER_ERROR;
783                 }
784                 break;
785               case 5: /* deflate.output-buffer-size */
786               case 6: /* deflate.work-block-size */
787                 break;
788               case 13:/* compress.max-loadavg */
789                 log_error(srv->errh, __FILE__, __LINE__,
790                   "DEPRECATED: %s replaced with deflate.max-loadavg",
791                   cpk[cpv->k_id].k);
792                 cpv->k_id = 7; /* deflate.max-loadavg */
793                 __attribute_fallthrough__
794               case 7: /* deflate.max-loadavg */
795                 cpv->v.d = (!buffer_is_blank(cpv->v.b))
796                   ? strtod(cpv->v.b->ptr, NULL)
797                   : 0.0;
798                 break;
799               case 11:/* compress.cache-dir */
800                 log_error(srv->errh, __FILE__, __LINE__,
801                   "DEPRECATED: %s replaced with deflate.cache-dir",
802                   cpk[cpv->k_id].k);
803                 cpv->k_id = 8; /* deflate.cache-dir */
804                 __attribute_fallthrough__
805               case 8: /* deflate.cache-dir */
806                 if (!buffer_is_blank(cpv->v.b)) {
807                     buffer *b;
808                     *(const buffer **)&b = cpv->v.b;
809                     const uint32_t len = buffer_clen(b);
810                     if (len > 0 && '/' == b->ptr[len-1])
811                         buffer_truncate(b, len-1); /*remove end slash*/
812                     struct stat st;
813                     if (0 != stat(b->ptr,&st) && 0 != mkdir_recursive(b->ptr)) {
814                         log_perror(srv->errh, __FILE__, __LINE__,
815                           "can't stat %s %s", cpk[cpv->k_id].k, b->ptr);
816                         return HANDLER_ERROR;
817                     }
818                 }
819                 else
820                     cpv->v.b = NULL;
821                 break;
822              #if 0    /*(handled further above)*/
823               case 9: /* compress.filetype */
824               case 10:/* compress.allowed-encodings */
825               case 11:/* compress.cache-dir */
826               case 12:/* compress.max-filesize */
827               case 13:/* compress.max-loadavg */
828                 break;
829              #endif
830               case 14:/* deflate.params */
831                 cpv->v.v = mod_deflate_parse_params(cpv->v.a, srv->errh);
832                 cpv->vtype = T_CONFIG_LOCAL;
833                 break;
834               default:/* should not happen */
835                 break;
836             }
837         }
838     }
839 
840     p->defaults.max_compress_size = 128*1024; /*(128 MB measured as num KB)*/
841     p->defaults.min_compress_size = 256;
842     p->defaults.compression_level = -1;
843     p->defaults.output_buffer_size = 0;
844     p->defaults.work_block_size = 2048;
845     p->defaults.max_loadavg = 0.0;
846     p->defaults.sync_flush = 0;
847 
848     /* initialize p->defaults from global config context */
849     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
850         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
851         if (-1 != cpv->k_id)
852             mod_deflate_merge_config(&p->defaults, cpv);
853     }
854 
855     return HANDLER_GO_ON;
856 }
857 
858 
859 #if defined(USE_ZLIB) || defined(USE_BZ2LIB) || defined(USE_BROTLI) \
860  || defined(USE_ZSTD)
861 static int mod_deflate_cache_file_append (handler_ctx * const hctx, const char *out, size_t len) {
862     ssize_t wr;
863     do {
864         wr = write(hctx->cache_fd, out, len);
865     } while (wr > 0 ? ((out += wr), (len -= (size_t)wr)) : errno == EINTR);
866     return (0 == len) ? 0 : -1;
867 }
868 
869 static int stream_http_chunk_append_mem(handler_ctx * const hctx, const char * const out, size_t len) {
870     if (0 == len) return 0;
871     return (-1 == hctx->cache_fd)
872       ? http_chunk_append_mem(hctx->r, out, len)
873       : mod_deflate_cache_file_append(hctx, out, len);
874 }
875 #endif
876 
877 
878 #ifdef USE_ZLIB
879 
880 static int stream_deflate_init(handler_ctx *hctx) {
881 	z_stream * const z = &hctx->u.z;
882 	z->zalloc = Z_NULL;
883 	z->zfree = Z_NULL;
884 	z->opaque = Z_NULL;
885 	z->total_in = 0;
886 	z->total_out = 0;
887 	z->next_out = (unsigned char *)hctx->output->ptr;
888 	z->avail_out = hctx->output->size;
889 
890 	const plugin_data * const p = hctx->plugin_data;
891 	const encparms * const params = p->conf.params;
892 	const int clevel = (NULL != params)
893 	  ? params->gzip.clevel
894 	  : p->conf.compression_level;
895 	const int wbits = (NULL != params)
896 	  ? params->gzip.windowBits
897 	  : MAX_WBITS;
898 
899 	if (Z_OK != deflateInit2(z,
900 				 clevel > 0 ? clevel : Z_DEFAULT_COMPRESSION,
901 				 Z_DEFLATED,
902 				 (hctx->compression_type == HTTP_ACCEPT_ENCODING_GZIP)
903 				  ? (wbits | 16) /*(0x10 flags gzip header, trailer)*/
904 				  : -wbits,      /*(negate to suppress zlib header)*/
905 				 params ? params->gzip.memLevel : 8,/*default memLevel*/
906 				 params ? params->gzip.strategy : Z_DEFAULT_STRATEGY)) {
907 		return -1;
908 	}
909 
910 	return 0;
911 }
912 
913 static int stream_deflate_compress(handler_ctx * const hctx, const unsigned char * const start, off_t st_size) {
914 	z_stream * const z = &(hctx->u.z);
915 	size_t len;
916 
917 	/*(unknown whether or not linked zlib was built with ZLIB_CONST defined)*/
918 	*((const unsigned char **)&z->next_in) = start;
919 	z->avail_in = st_size;
920 	hctx->bytes_in += st_size;
921 
922 	/* compress data */
923 	do {
924 		if (Z_OK != deflate(z, Z_NO_FLUSH)) return -1;
925 
926 		if (z->avail_out == 0 || z->avail_in > 0) {
927 			len = hctx->output->size - z->avail_out;
928 			hctx->bytes_out += len;
929 			if (0 != stream_http_chunk_append_mem(hctx, hctx->output->ptr, len))
930 				return -1;
931 			z->next_out = (unsigned char *)hctx->output->ptr;
932 			z->avail_out = hctx->output->size;
933 		}
934 	} while (z->avail_in > 0);
935 
936 	return 0;
937 }
938 
939 static int stream_deflate_flush(handler_ctx * const hctx, int end) {
940 	z_stream * const z = &(hctx->u.z);
941 	const plugin_data *p = hctx->plugin_data;
942 	size_t len;
943 	int rc = 0;
944 	int done;
945 
946 	/* compress data */
947 	do {
948 		done = 1;
949 		if (end) {
950 			rc = deflate(z, Z_FINISH);
951 			if (rc == Z_OK) {
952 				done = 0;
953 			} else if (rc != Z_STREAM_END) {
954 				return -1;
955 			}
956 		} else {
957 			if (p->conf.sync_flush) {
958 				rc = deflate(z, Z_SYNC_FLUSH);
959 				if (rc != Z_OK) return -1;
960 			} else if (z->avail_in > 0) {
961 				rc = deflate(z, Z_NO_FLUSH);
962 				if (rc != Z_OK) return -1;
963 			}
964 		}
965 
966 		len = hctx->output->size - z->avail_out;
967 		if (z->avail_out == 0 || (len > 0 && (end || p->conf.sync_flush))) {
968 			hctx->bytes_out += len;
969 			if (0 != stream_http_chunk_append_mem(hctx, hctx->output->ptr, len))
970 				return -1;
971 			z->next_out = (unsigned char *)hctx->output->ptr;
972 			z->avail_out = hctx->output->size;
973 		}
974 	} while (z->avail_in != 0 || !done);
975 
976 	return 0;
977 }
978 
979 static int stream_deflate_end(handler_ctx *hctx) {
980 	z_stream * const z = &(hctx->u.z);
981 	int rc = deflateEnd(z);
982 	if (Z_OK == rc || Z_DATA_ERROR == rc) return 0;
983 
984 	if (z->msg != NULL) {
985 		log_error(hctx->r->conf.errh, __FILE__, __LINE__,
986 		  "deflateEnd error ret=%d, msg=%s", rc, z->msg);
987 	} else {
988 		log_error(hctx->r->conf.errh, __FILE__, __LINE__,
989 		  "deflateEnd error ret=%d", rc);
990 	}
991 	return -1;
992 }
993 
994 #endif
995 
996 
997 #ifdef USE_BZ2LIB
998 
999 static int stream_bzip2_init(handler_ctx *hctx) {
1000 	bz_stream * const bz = &hctx->u.bz;
1001 	bz->bzalloc = NULL;
1002 	bz->bzfree = NULL;
1003 	bz->opaque = NULL;
1004 	bz->total_in_lo32 = 0;
1005 	bz->total_in_hi32 = 0;
1006 	bz->total_out_lo32 = 0;
1007 	bz->total_out_hi32 = 0;
1008 	bz->next_out = hctx->output->ptr;
1009 	bz->avail_out = hctx->output->size;
1010 
1011 	const plugin_data * const p = hctx->plugin_data;
1012 	const encparms * const params = p->conf.params;
1013 	const int clevel = (NULL != params)
1014 	  ? params->bzip2.clevel
1015 	  : p->conf.compression_level;
1016 
1017 	if (BZ_OK != BZ2_bzCompressInit(bz,
1018 					clevel > 0
1019 					 ? p->conf.compression_level
1020 					 : 9, /* blocksize = 900k */
1021 					0,    /* verbosity */
1022 					0)) { /* workFactor: default */
1023 		return -1;
1024 	}
1025 
1026 	return 0;
1027 }
1028 
1029 static int stream_bzip2_compress(handler_ctx * const hctx, const unsigned char * const start, off_t st_size) {
1030 	bz_stream * const bz = &(hctx->u.bz);
1031 	size_t len;
1032 
1033 	bz->next_in = (char *)start;
1034 	bz->avail_in = st_size;
1035 	hctx->bytes_in += st_size;
1036 
1037 	/* compress data */
1038 	do {
1039 		if (BZ_RUN_OK != BZ2_bzCompress(bz, BZ_RUN)) return -1;
1040 
1041 		if (bz->avail_out == 0 || bz->avail_in > 0) {
1042 			len = hctx->output->size - bz->avail_out;
1043 			hctx->bytes_out += len;
1044 			if (0 != stream_http_chunk_append_mem(hctx, hctx->output->ptr, len))
1045 				return -1;
1046 			bz->next_out = hctx->output->ptr;
1047 			bz->avail_out = hctx->output->size;
1048 		}
1049 	} while (bz->avail_in > 0);
1050 
1051 	return 0;
1052 }
1053 
1054 static int stream_bzip2_flush(handler_ctx * const hctx, int end) {
1055 	bz_stream * const bz = &(hctx->u.bz);
1056 	const plugin_data *p = hctx->plugin_data;
1057 	size_t len;
1058 	int rc;
1059 	int done;
1060 
1061 	/* compress data */
1062 	do {
1063 		done = 1;
1064 		if (end) {
1065 			rc = BZ2_bzCompress(bz, BZ_FINISH);
1066 			if (rc == BZ_FINISH_OK) {
1067 				done = 0;
1068 			} else if (rc != BZ_STREAM_END) {
1069 				return -1;
1070 			}
1071 		} else if (bz->avail_in > 0) {
1072 			/* p->conf.sync_flush not implemented here,
1073 			 * which would loop on BZ_FLUSH while BZ_FLUSH_OK
1074 			 * until BZ_RUN_OK returned */
1075 			rc = BZ2_bzCompress(bz, BZ_RUN);
1076 			if (rc != BZ_RUN_OK) {
1077 				return -1;
1078 			}
1079 		}
1080 
1081 		len = hctx->output->size - bz->avail_out;
1082 		if (bz->avail_out == 0 || (len > 0 && (end || p->conf.sync_flush))) {
1083 			hctx->bytes_out += len;
1084 			if (0 != stream_http_chunk_append_mem(hctx, hctx->output->ptr, len))
1085 				return -1;
1086 			bz->next_out = hctx->output->ptr;
1087 			bz->avail_out = hctx->output->size;
1088 		}
1089 	} while (bz->avail_in != 0 || !done);
1090 
1091 	return 0;
1092 }
1093 
1094 static int stream_bzip2_end(handler_ctx *hctx) {
1095 	bz_stream * const bz = &(hctx->u.bz);
1096 	int rc = BZ2_bzCompressEnd(bz);
1097 	if (BZ_OK == rc || BZ_DATA_ERROR == rc) return 0;
1098 
1099 	log_error(hctx->r->conf.errh, __FILE__, __LINE__,
1100 	  "BZ2_bzCompressEnd error ret=%d", rc);
1101 	return -1;
1102 }
1103 
1104 #endif
1105 
1106 
1107 #ifdef USE_BROTLI
1108 
1109 static int stream_br_init(handler_ctx *hctx) {
1110     BrotliEncoderState * const br = hctx->u.br =
1111       BrotliEncoderCreateInstance(NULL, NULL, NULL);
1112     if (NULL == br) return -1;
1113 
1114     /*(note: we ignore any errors while tuning parameters here)*/
1115     const plugin_data * const p = hctx->plugin_data;
1116     const encparms * const params = p->conf.params;
1117     const uint32_t quality = (NULL != params)
1118       ? params->brotli.quality
1119       : (p->conf.compression_level >= 0) /* 0 .. 11 are valid values */
1120         ? (uint32_t)p->conf.compression_level
1121         : 5;
1122         /* BROTLI_DEFAULT_QUALITY is 11 and can be *very* time-consuming */
1123     if (quality != BROTLI_DEFAULT_QUALITY)
1124         BrotliEncoderSetParameter(br, BROTLI_PARAM_QUALITY, quality);
1125 
1126     if (params && params->brotli.window != BROTLI_DEFAULT_WINDOW)
1127         BrotliEncoderSetParameter(br, BROTLI_PARAM_LGWIN,params->brotli.window);
1128 
1129     const buffer *vb;
1130     if (params && params->brotli.mode != BROTLI_MODE_GENERIC)
1131         BrotliEncoderSetParameter(br, BROTLI_PARAM_MODE, params->brotli.mode);
1132     else if ((vb = http_header_response_get(hctx->r, HTTP_HEADER_CONTENT_TYPE,
1133                                             CONST_STR_LEN("Content-Type")))) {
1134         /* BROTLI_MODE_GENERIC vs BROTLI_MODE_TEXT or BROTLI_MODE_FONT */
1135         const uint32_t len = buffer_clen(vb);
1136         if (0 == strncmp(vb->ptr, "text/", sizeof("text/")-1)
1137             || (0 == strncmp(vb->ptr, "application/", sizeof("application/")-1)
1138                 && (0 == strncmp(vb->ptr+12,"javascript",sizeof("javascript")-1)
1139                  || 0 == strncmp(vb->ptr+12,"json",      sizeof("json")-1)
1140                  || 0 == strncmp(vb->ptr+12,"xml",       sizeof("xml")-1)))
1141             || (len > 4
1142                 && (0 == strncmp(vb->ptr+len-5, "+json", sizeof("+json")-1)
1143                  || 0 == strncmp(vb->ptr+len-4, "+xml",  sizeof("+xml")-1))))
1144             BrotliEncoderSetParameter(br, BROTLI_PARAM_MODE, BROTLI_MODE_TEXT);
1145         else if (0 == strncmp(vb->ptr, "font/", sizeof("font/")-1))
1146             BrotliEncoderSetParameter(br, BROTLI_PARAM_MODE, BROTLI_MODE_FONT);
1147     }
1148 
1149     return 0;
1150 }
1151 
1152 static int stream_br_compress(handler_ctx * const hctx, const unsigned char * const start, off_t st_size) {
1153     const uint8_t *in = (uint8_t *)start;
1154     BrotliEncoderState * const br = hctx->u.br;
1155     hctx->bytes_in += st_size;
1156     while (st_size || BrotliEncoderHasMoreOutput(br)) {
1157         size_t insz = ((off_t)((~(uint32_t)0) >> 1) > st_size)
1158           ? (size_t)st_size
1159           : ((~(uint32_t)0) >> 1);
1160         size_t outsz = 0;
1161         BrotliEncoderCompressStream(br, BROTLI_OPERATION_PROCESS,
1162                                     &insz, &in, &outsz, NULL, NULL);
1163         const uint8_t *out = BrotliEncoderTakeOutput(br, &outsz);
1164         st_size -= (st_size - (off_t)insz);
1165         if (outsz) {
1166             hctx->bytes_out += (off_t)outsz;
1167             if (0 != stream_http_chunk_append_mem(hctx, (char *)out, outsz))
1168                 return -1;
1169         }
1170     }
1171     return 0;
1172 }
1173 
1174 static int stream_br_flush(handler_ctx * const hctx, int end) {
1175     const int brmode = end ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_FLUSH;
1176     BrotliEncoderState * const br = hctx->u.br;
1177     do {
1178         size_t insz = 0;
1179         size_t outsz = 0;
1180         BrotliEncoderCompressStream(br, brmode,
1181                                     &insz, NULL, &outsz, NULL, NULL);
1182         const uint8_t *out = BrotliEncoderTakeOutput(br, &outsz);
1183         if (outsz) {
1184             hctx->bytes_out += (off_t)outsz;
1185             if (0 != stream_http_chunk_append_mem(hctx, (char *)out, outsz))
1186                 return -1;
1187         }
1188     } while (BrotliEncoderHasMoreOutput(br));
1189     return 0;
1190 }
1191 
1192 static int stream_br_end(handler_ctx *hctx) {
1193     BrotliEncoderState * const br = hctx->u.br;
1194     BrotliEncoderDestroyInstance(br);
1195     return 0;
1196 }
1197 
1198 #endif
1199 
1200 
1201 #ifdef USE_ZSTD
1202 
1203 static int stream_zstd_init(handler_ctx *hctx) {
1204     ZSTD_CStream * const cctx = hctx->u.cctx = ZSTD_createCStream();
1205     if (NULL == cctx) return -1;
1206     hctx->output->used = 0;
1207 
1208     /*(note: we ignore any errors while tuning parameters here)*/
1209     const plugin_data * const p = hctx->plugin_data;
1210     const encparms * const params = p->conf.params;
1211     if (params) {
1212         if (params->zstd.clevel && params->zstd.clevel != ZSTD_CLEVEL_DEFAULT) {
1213             const int level = params->zstd.clevel;
1214           #if ZSTD_VERSION_NUMBER >= 10000+400+0 /* v1.4.0 */
1215             ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, level);
1216           #else
1217             ZSTD_initCStream(cctx, level);
1218           #endif
1219         }
1220       #if ZSTD_VERSION_NUMBER >= 10000+400+0 /* v1.4.0 */
1221         if (params->zstd.strategy)
1222             ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy,
1223                                    params->zstd.strategy);
1224         if (params->zstd.windowLog)
1225             ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog,
1226                                    params->zstd.windowLog);
1227       #endif
1228     }
1229     else if (p->conf.compression_level >= 0) { /* -1 here is "unset" */
1230         int level = p->conf.compression_level;
1231       #if ZSTD_VERSION_NUMBER >= 10000+400+0 /* v1.4.0 */
1232         ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, level);
1233       #else
1234         ZSTD_initCStream(cctx, level);
1235       #endif
1236     }
1237     return 0;
1238 }
1239 
1240 static int stream_zstd_compress(handler_ctx * const hctx, const unsigned char * const start, off_t st_size) {
1241     ZSTD_CStream * const cctx = hctx->u.cctx;
1242     ZSTD_inBuffer zib = { start, (size_t)st_size, 0 };
1243     ZSTD_outBuffer zob = { hctx->output->ptr,
1244                            hctx->output->size,
1245                            hctx->output->used };
1246     hctx->output->used = 0;
1247     hctx->bytes_in += st_size;
1248     while (zib.pos < zib.size) {
1249       #if ZSTD_VERSION_NUMBER >= 10000+400+0 /* v1.4.0 */
1250         const size_t rv = ZSTD_compressStream2(cctx,&zob,&zib,ZSTD_e_continue);
1251       #else
1252         const size_t rv = ZSTD_compressStream(cctx, &zob, &zib);
1253       #endif
1254         if (ZSTD_isError(rv)) return -1;
1255         if (zib.pos == zib.size) break; /* defer flush */
1256         hctx->bytes_out += (off_t)zob.pos;
1257         if (0 != stream_http_chunk_append_mem(hctx, zob.dst, zob.pos))
1258             return -1;
1259         zob.pos = 0;
1260     }
1261     hctx->output->used = (uint32_t)zob.pos;
1262     return 0;
1263 }
1264 
1265 static int stream_zstd_flush(handler_ctx * const hctx, int end) {
1266     ZSTD_CStream * const cctx = hctx->u.cctx;
1267   #if ZSTD_VERSION_NUMBER >= 10000+400+0 /* v1.4.0 */
1268     const ZSTD_EndDirective endOp = end ? ZSTD_e_end : ZSTD_e_flush;
1269     ZSTD_inBuffer zib = { NULL, 0, 0 };
1270   #endif
1271     ZSTD_outBuffer zob = { hctx->output->ptr,
1272                            hctx->output->size,
1273                            hctx->output->used };
1274     size_t rv;
1275     do {
1276       #if ZSTD_VERSION_NUMBER >= 10000+400+0 /* v1.4.0 */
1277         rv = ZSTD_compressStream2(cctx, &zob, &zib, endOp);
1278       #else
1279         rv = end
1280            ? ZSTD_endStream(cctx, &zob)
1281            : ZSTD_flushStream(cctx, &zob);
1282       #endif
1283         if (ZSTD_isError(rv)) return -1;
1284         hctx->bytes_out += (off_t)zob.pos;
1285         if (0 != stream_http_chunk_append_mem(hctx, zob.dst, zob.pos))
1286             return -1;
1287         zob.pos = 0;
1288     } while (0 != rv);
1289     return 0;
1290 }
1291 
1292 static int stream_zstd_end(handler_ctx *hctx) {
1293     ZSTD_CStream * const cctx = hctx->u.cctx;
1294     ZSTD_freeCStream(cctx);
1295     return 0;
1296 }
1297 
1298 #endif
1299 
1300 
1301 static int mod_deflate_stream_init(handler_ctx *hctx) {
1302 	switch(hctx->compression_type) {
1303 #ifdef USE_ZLIB
1304 	case HTTP_ACCEPT_ENCODING_GZIP:
1305 	case HTTP_ACCEPT_ENCODING_DEFLATE:
1306 		return stream_deflate_init(hctx);
1307 #endif
1308 #ifdef USE_BZ2LIB
1309 	case HTTP_ACCEPT_ENCODING_BZIP2:
1310 		return stream_bzip2_init(hctx);
1311 #endif
1312 #ifdef USE_BROTLI
1313 	case HTTP_ACCEPT_ENCODING_BR:
1314 		return stream_br_init(hctx);
1315 #endif
1316 #ifdef USE_ZSTD
1317 	case HTTP_ACCEPT_ENCODING_ZSTD:
1318 		return stream_zstd_init(hctx);
1319 #endif
1320 	default:
1321 		return -1;
1322 	}
1323 }
1324 
1325 static int mod_deflate_compress(handler_ctx * const hctx, const unsigned char * const start, off_t st_size) {
1326 	if (0 == st_size) return 0;
1327 	switch(hctx->compression_type) {
1328 #ifdef USE_ZLIB
1329 	case HTTP_ACCEPT_ENCODING_GZIP:
1330 	case HTTP_ACCEPT_ENCODING_DEFLATE:
1331 		return stream_deflate_compress(hctx, start, st_size);
1332 #endif
1333 #ifdef USE_BZ2LIB
1334 	case HTTP_ACCEPT_ENCODING_BZIP2:
1335 		return stream_bzip2_compress(hctx, start, st_size);
1336 #endif
1337 #ifdef USE_BROTLI
1338 	case HTTP_ACCEPT_ENCODING_BR:
1339 		return stream_br_compress(hctx, start, st_size);
1340 #endif
1341 #ifdef USE_ZSTD
1342 	case HTTP_ACCEPT_ENCODING_ZSTD:
1343 		return stream_zstd_compress(hctx, start, st_size);
1344 #endif
1345 	default:
1346 		UNUSED(start);
1347 		return -1;
1348 	}
1349 }
1350 
1351 static int mod_deflate_stream_flush(handler_ctx * const hctx, int end) {
1352 	if (0 == hctx->bytes_in) return 0;
1353 	switch(hctx->compression_type) {
1354 #ifdef USE_ZLIB
1355 	case HTTP_ACCEPT_ENCODING_GZIP:
1356 	case HTTP_ACCEPT_ENCODING_DEFLATE:
1357 		return stream_deflate_flush(hctx, end);
1358 #endif
1359 #ifdef USE_BZ2LIB
1360 	case HTTP_ACCEPT_ENCODING_BZIP2:
1361 		return stream_bzip2_flush(hctx, end);
1362 #endif
1363 #ifdef USE_BROTLI
1364 	case HTTP_ACCEPT_ENCODING_BR:
1365 		return stream_br_flush(hctx, end);
1366 #endif
1367 #ifdef USE_ZSTD
1368 	case HTTP_ACCEPT_ENCODING_ZSTD:
1369 		return stream_zstd_flush(hctx, end);
1370 #endif
1371 	default:
1372 		UNUSED(end);
1373 		return -1;
1374 	}
1375 }
1376 
1377 static void mod_deflate_note_ratio(request_st * const r, const off_t bytes_out, const off_t bytes_in) {
1378     /* store compression ratio in environment
1379      * for possible logging by mod_accesslog
1380      * (late in response handling, so not seen by most other modules) */
1381     /*(should be called only at end of successful response compression)*/
1382     if (0 == bytes_in) return;
1383     buffer_append_int(
1384       http_header_env_set_ptr(r, CONST_STR_LEN("ratio")),
1385       bytes_out * 100 / bytes_in);
1386 }
1387 
1388 static int mod_deflate_stream_end(handler_ctx *hctx) {
1389 	switch(hctx->compression_type) {
1390 #ifdef USE_ZLIB
1391 	case HTTP_ACCEPT_ENCODING_GZIP:
1392 	case HTTP_ACCEPT_ENCODING_DEFLATE:
1393 		return stream_deflate_end(hctx);
1394 #endif
1395 #ifdef USE_BZ2LIB
1396 	case HTTP_ACCEPT_ENCODING_BZIP2:
1397 		return stream_bzip2_end(hctx);
1398 #endif
1399 #ifdef USE_BROTLI
1400 	case HTTP_ACCEPT_ENCODING_BR:
1401 		return stream_br_end(hctx);
1402 #endif
1403 #ifdef USE_ZSTD
1404 	case HTTP_ACCEPT_ENCODING_ZSTD:
1405 		return stream_zstd_end(hctx);
1406 #endif
1407 	default:
1408 		return -1;
1409 	}
1410 }
1411 
1412 static int deflate_compress_cleanup(request_st * const r, handler_ctx * const hctx) {
1413 	int rc = mod_deflate_stream_end(hctx);
1414 
1415       #if 1 /* unnecessary if deflate.min-compress-size is set to a reasonable value */
1416 	if (0 == rc && hctx->bytes_in < hctx->bytes_out)
1417 		log_error(r->conf.errh, __FILE__, __LINE__,
1418 		  "uri %s in=%lld smaller than out=%lld", r->target.ptr,
1419 		  (long long)hctx->bytes_in, (long long)hctx->bytes_out);
1420       #endif
1421 
1422 	handler_ctx_free(hctx);
1423 	return rc;
1424 }
1425 
1426 
1427 #ifdef HAVE_LIBDEFLATE
1428 #include <libdeflate.h>
1429 
1430 __attribute_cold__
1431 __attribute_noinline__
1432 static int mod_deflate_using_libdeflate_err (handler_ctx * const hctx, buffer * const fn, const int fd)
1433 {
1434     if (-1 == fd) {
1435     }
1436     else if (fd == hctx->cache_fd) {
1437         if (0 != ftruncate(fd, 0))
1438             log_perror(hctx->r->conf.errh, __FILE__, __LINE__, "ftruncate");
1439         if (0 != lseek(fd, 0, SEEK_SET))
1440             log_perror(hctx->r->conf.errh, __FILE__, __LINE__, "lseek");
1441     }
1442     else {
1443         if (0 != unlink(fn->ptr))
1444             log_perror(hctx->r->conf.errh, __FILE__, __LINE__, "unlink");
1445         close(fd);
1446     }
1447     buffer_clear(fn); /*(&p->tmp_buf)*/
1448     return 0;
1449 }
1450 
1451 
1452 static int mod_deflate_using_libdeflate_sm (handler_ctx * const hctx, const plugin_data * const p)
1453 {
1454     const encparms * const params = p->conf.params;
1455     const int clevel = (NULL != params)
1456       ? params->gzip.clevel
1457       : p->conf.compression_level;
1458     struct libdeflate_compressor * const compressor =
1459       libdeflate_alloc_compressor(clevel > 0 ? clevel : 6);
1460       /* Z_DEFAULT_COMPRESSION -1 not supported */
1461     if (NULL == compressor)
1462         return 0;
1463 
1464     char * const in = hctx->r->write_queue.first->mem->ptr;
1465     const size_t in_nbytes = (size_t)hctx->bytes_in;
1466     buffer * const addrb = hctx->output; /*(&p->tmp_buf)*/
1467     size_t sz = buffer_string_space(addrb)+1;
1468     sz = (hctx->compression_type == HTTP_ACCEPT_ENCODING_GZIP)
1469       ? libdeflate_gzip_compress(compressor, in, in_nbytes, addrb->ptr, sz)
1470       : libdeflate_deflate_compress(compressor, in, in_nbytes, addrb->ptr, sz);
1471     libdeflate_free_compressor(compressor);
1472 
1473     if (0 == sz) {
1474         buffer_clear(addrb);
1475         return 0;
1476     }
1477 
1478     chunkqueue_reset(&hctx->r->write_queue);
1479     hctx->bytes_out = (off_t)sz;
1480     if (0 != stream_http_chunk_append_mem(hctx, addrb->ptr, sz))
1481         return mod_deflate_using_libdeflate_err(hctx, addrb, hctx->cache_fd);
1482 
1483     buffer * const vb =
1484       http_header_response_set_ptr(hctx->r, HTTP_HEADER_CONTENT_LENGTH,
1485                                    CONST_STR_LEN("Content-Length"));
1486     buffer_append_int(vb, hctx->bytes_out);
1487     return 1;
1488 }
1489 
1490 
1491 #ifdef HAVE_MMAP
1492 #if defined(_LP64) || defined(__LP64__) || defined(_WIN64)
1493 
1494 struct mod_deflate_setjmp_params {
1495     struct libdeflate_compressor *compressor;
1496     void *out;
1497     size_t outsz;
1498 };
1499 
1500 static off_t mod_deflate_using_libdeflate_setjmp_cb (void *dst, const void *src, off_t len)
1501 {
1502     const struct mod_deflate_setjmp_params * const params = dst;
1503     const handler_ctx * const hctx = src;
1504     const chunk * const c = hctx->r->write_queue.first;
1505     const char *in = chunk_file_view_dptr(c->file.view, c->offset);
1506     return (off_t)((hctx->compression_type == HTTP_ACCEPT_ENCODING_GZIP)
1507       ? libdeflate_gzip_compress(params->compressor, in, (size_t)len,
1508                                  params->out, params->outsz)
1509       : libdeflate_deflate_compress(params->compressor, in, (size_t)len,
1510                                     params->out, params->outsz));
1511 }
1512 
1513 
1514 static int mod_deflate_using_libdeflate (handler_ctx * const hctx, const plugin_data * const p)
1515 {
1516     buffer * const fn = hctx->output; /*(&p->tmp_buf)*/
1517     int fd = hctx->cache_fd;
1518     if (-1 == fd) {
1519         chunkqueue * const cq = &hctx->r->write_queue;
1520         if (cq->tempdirs && cq->tempdir_idx < cq->tempdirs->used) {
1521             data_string *ds =(data_string *)cq->tempdirs->data[cq->tempdir_idx];
1522             buffer_copy_string_len(fn, BUF_PTR_LEN(&ds->value));
1523         }
1524         else
1525             buffer_copy_string_len(fn, CONST_STR_LEN("/var/tmp"));
1526         buffer_append_path_len(fn, CONST_STR_LEN("lighttpd-XXXXXX"));
1527         fd = fdevent_mkostemp(fn->ptr, 0);
1528         if (-1 == fd) return 0;
1529     }
1530 
1531     const size_t sz =
1532       libdeflate_deflate_compress_bound(NULL, (size_t)hctx->bytes_in);
1533     /*(XXX: consider trying posix_fallocate() first,
1534      * with fallback to ftrunctate() if EOPNOTSUPP)*/
1535     if (0 != ftruncate(fd, (off_t)sz)) {
1536         log_perror(hctx->r->conf.errh, __FILE__, __LINE__, "ftruncate");
1537         return mod_deflate_using_libdeflate_err(hctx, fn, fd);
1538     }
1539 
1540     /*void *addr = mmap(NULL, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);*/
1541     void * const addr = mmap(NULL, sz, PROT_WRITE, MAP_PRIVATE, fd, 0);
1542     if (MAP_FAILED == addr) {
1543         log_perror(hctx->r->conf.errh, __FILE__, __LINE__, "mmap");
1544         return mod_deflate_using_libdeflate_err(hctx, fn, fd);
1545     }
1546 
1547     const encparms * const params = p->conf.params;
1548     const int clevel = (NULL != params)
1549       ? params->gzip.clevel
1550       : p->conf.compression_level;
1551     struct libdeflate_compressor * const compressor =
1552       libdeflate_alloc_compressor(clevel > 0 ? clevel : 6);
1553       /* Z_DEFAULT_COMPRESSION -1 not supported */
1554     if (NULL != compressor) {
1555         struct mod_deflate_setjmp_params outparams = { compressor, addr, sz };
1556         hctx->bytes_out =
1557           sys_setjmp_eval3(mod_deflate_using_libdeflate_setjmp_cb,
1558                            &outparams, hctx, hctx->bytes_in);
1559         libdeflate_free_compressor(compressor);
1560     }
1561 
1562     /*(XXX: we theoretically could assign mmap to FILE_CHUNK in output
1563      * r->write_queue, for potential use by TLS modules, or if not using
1564      * sendfile in network_write.c, but we do not (easily) know if either
1565      * are configured or in use for this request.  Might consider heuristic:
1566      * (*srv->srvconf.network_backend->ptr == 'w') (writev or write), or
1567      * to check con->is_ssl_sock.)  These files would be safe to pass to
1568      * TLS modules to read from mmap without catching SIGBUS since these files
1569      * are created by lighttpd, either in deflate cache or as temporary file */
1570     if (0 != munmap(addr, sz))
1571         log_perror(hctx->r->conf.errh, __FILE__, __LINE__, "munmap");
1572 
1573     if (0 == hctx->bytes_out) {
1574         const chunk * const c = hctx->r->write_queue.first;
1575         log_error(hctx->r->conf.errh, __FILE__, __LINE__,
1576           "SIGBUS in mmap: %s %d", c->mem->ptr, c->file.fd);
1577     }
1578     else if (0 != ftruncate(fd, hctx->bytes_out))
1579         hctx->bytes_out = 0;
1580 
1581     if (0 == hctx->bytes_out)
1582         return mod_deflate_using_libdeflate_err(hctx, fn, fd);
1583 
1584     if (fd != hctx->cache_fd) {
1585         chunkqueue * const cq = &hctx->r->write_queue;
1586         chunkqueue_reset(cq);
1587         http_chunk_append_file_fd_range(hctx->r, fn, fd, 0, hctx->bytes_out);
1588         cq->last->file.is_temp = 1;
1589     }
1590 
1591     buffer * const vb =
1592       http_header_response_set_ptr(hctx->r, HTTP_HEADER_CONTENT_LENGTH,
1593                                    CONST_STR_LEN("Content-Length"));
1594     buffer_append_int(vb, hctx->bytes_out);
1595     return 1;
1596 }
1597 
1598 #endif /* defined(_LP64) || defined(__LP64__) || defined(_WIN64) */
1599 #endif /* HAVE_MMAP */
1600 
1601 #endif /* HAVE_LIBDEFLATE */
1602 
1603 
1604 static off_t mod_deflate_file_chunk_no_mmap(request_st * const r, handler_ctx * const hctx, const chunk * const c, off_t n)
1605 {
1606     const off_t insz = n;
1607     const size_t psz = (n < 2*1024*1024) ? (size_t)n : 2*1024*1024;
1608     char * const p = malloc(psz);
1609     if (NULL == p) {
1610         log_perror(r->conf.errh, __FILE__, __LINE__, "malloc");
1611         return -1;
1612     }
1613 
1614     ssize_t rd = 0;
1615     for (n = 0; n < insz; n += rd) {
1616         rd = chunk_file_pread(c->file.fd, p, (size_t)psz, c->offset+n);
1617         if (__builtin_expect( (rd > 0), 1)) {
1618             if (0 == mod_deflate_compress(hctx, (unsigned char *)p, rd))
1619                 continue;
1620             /*(else error trace printed upon return)*/
1621         }
1622         else if (-1 == rd)
1623             log_perror(r->conf.errh, __FILE__, __LINE__,
1624               "reading %s failed", c->mem->ptr);
1625         else /*(0 == rd)*/
1626             log_error(r->conf.errh, __FILE__, __LINE__,
1627               "file truncated %s", c->mem->ptr);
1628         n = -1;
1629         break;
1630     }
1631 
1632     free(p);
1633     return n;
1634 }
1635 
1636 
1637 #ifdef ENABLE_MMAP
1638 
1639 static off_t mod_deflate_file_chunk_setjmp_cb (void *dst, const void *src, off_t len)
1640 {
1641     return mod_deflate_compress(dst, (const unsigned char *)src, len);
1642 }
1643 
1644 
1645 static off_t mod_deflate_file_chunk_mmap(request_st * const r, handler_ctx * const hctx, chunk * const c, off_t n)
1646 {
1647     /* n is length of entire file since server blocks while compressing
1648      * (mod_deflate is not recommended for large files;
1649      *  mod_deflate default upper limit is 128MB; deflate.max-compress-size) */
1650 
1651     const chunk_file_view * const restrict cfv = (!c->file.is_temp)
1652       ? chunkqueue_chunk_file_view(c, n, r->conf.errh)
1653       : NULL;
1654     if (NULL == cfv)
1655         return mod_deflate_file_chunk_no_mmap(r, hctx, c, n);
1656 
1657     const char * const p = chunk_file_view_dptr(cfv, c->offset);
1658     off_t len = chunk_file_view_dlen(cfv, c->offset);
1659     if (len > n) len = n;
1660     off_t rc = sys_setjmp_eval3(mod_deflate_file_chunk_setjmp_cb, hctx, p, len);
1661     if (__builtin_expect( (rc < 0), 0)) {
1662         if (errno == EFAULT)
1663             log_error(r->conf.errh, __FILE__, __LINE__,
1664               "SIGBUS in mmap: %s %d", c->mem->ptr, c->file.fd);
1665         else
1666             log_error(r->conf.errh, __FILE__, __LINE__, "compress failed.");
1667         len = -1; /*return -1;*/
1668     }
1669     return len;
1670 }
1671 
1672 #endif
1673 
1674 
1675 static off_t mod_deflate_file_chunk(request_st * const r, handler_ctx * const hctx, chunk * const c, off_t n) {
1676     if (-1 == c->file.fd) {  /* open the file if not already open */
1677         if (-1 == (c->file.fd = fdevent_open_cloexec(c->mem->ptr, r->conf.follow_symlink, O_RDONLY, 0))) {
1678             log_perror(r->conf.errh, __FILE__, __LINE__, "open failed %s", c->mem->ptr);
1679             return -1;
1680         }
1681     }
1682   #ifdef ENABLE_MMAP
1683     return mod_deflate_file_chunk_mmap(r, hctx, c, n);
1684   #else
1685     return mod_deflate_file_chunk_no_mmap(r, hctx, c, n);
1686   #endif
1687 }
1688 
1689 
1690 static handler_t deflate_compress_response(request_st * const r, handler_ctx * const hctx) {
1691 	off_t len, max;
1692 	int close_stream;
1693 
1694 	/* move all chunk from write_queue into our in_queue, then adjust
1695 	 * counters since r->write_queue is reused for compressed output */
1696 	chunkqueue * const cq = &r->write_queue;
1697 	len = chunkqueue_length(cq);
1698 	chunkqueue_remove_finished_chunks(cq);
1699 	chunkqueue_append_chunkqueue(&hctx->in_queue, cq);
1700 	cq->bytes_in  -= len;
1701 	cq->bytes_out -= len;
1702 
1703 	max = chunkqueue_length(&hctx->in_queue);
1704       #if 0
1705 	/* calculate max bytes to compress for this call */
1706 	if (p->conf.sync_flush && max > (len = p->conf.work_block_size << 10)) {
1707 		max = len;
1708 	}
1709       #endif
1710 
1711 	/* Compress chunks from in_queue into chunks for write_queue */
1712 	while (max) {
1713 		chunk *c = hctx->in_queue.first;
1714 
1715 		switch(c->type) {
1716 		case MEM_CHUNK:
1717 			len = buffer_clen(c->mem) - c->offset;
1718 			if (len > max) len = max;
1719 			if (mod_deflate_compress(hctx, (unsigned char *)c->mem->ptr+c->offset, len) < 0) {
1720 				log_error(r->conf.errh, __FILE__, __LINE__, "compress failed.");
1721 				return HANDLER_ERROR;
1722 			}
1723 			break;
1724 		case FILE_CHUNK:
1725 			len = c->file.length - c->offset;
1726 			if (len > max) len = max;
1727 			if ((len = mod_deflate_file_chunk(r, hctx, c, len)) < 0) {
1728 				log_error(r->conf.errh, __FILE__, __LINE__,
1729 				  "compress file chunk failed %s", c->mem->ptr);
1730 				return HANDLER_ERROR;
1731 			}
1732 			break;
1733 		default:
1734 			log_error(r->conf.errh, __FILE__, __LINE__, "%d type not known", c->type);
1735 			return HANDLER_ERROR;
1736 		}
1737 
1738 		max -= len;
1739 		chunkqueue_mark_written(&hctx->in_queue, len);
1740 	}
1741 
1742 	/*(currently should always be true)*/
1743 	/*(current implementation requires response be complete)*/
1744 	close_stream = (r->resp_body_finished
1745                         && chunkqueue_is_empty(&hctx->in_queue));
1746 	if (mod_deflate_stream_flush(hctx, close_stream) < 0) {
1747 		log_error(r->conf.errh, __FILE__, __LINE__, "flush error");
1748 		return HANDLER_ERROR;
1749 	}
1750 
1751 	return close_stream ? HANDLER_FINISHED : HANDLER_GO_ON;
1752 }
1753 
1754 
1755 static int mod_deflate_choose_encoding (const char *value, plugin_data *p, const char **label) {
1756 	/* get client side support encodings */
1757 	int accept_encoding = 0;
1758       #if !defined(USE_ZLIB) && !defined(USE_BZ2LIB) && !defined(USE_BROTLI) \
1759        && !defined(USE_ZSTD)
1760 	UNUSED(value);
1761 	UNUSED(label);
1762       #else
1763         for (; *value; ++value) {
1764             const char *v;
1765             while (*value == ' ' || *value == ',') ++value;
1766             v = value;
1767             while (*value!=' ' && *value!=',' && *value!=';' && *value!='\0')
1768                 ++value;
1769             switch (value - v) {
1770               case 2:
1771                #ifdef USE_BROTLI
1772                 if (0 == memcmp(v, "br", 2))
1773                     accept_encoding |= HTTP_ACCEPT_ENCODING_BR;
1774                #endif
1775                 break;
1776               case 4:
1777                #ifdef USE_ZLIB
1778                 if (0 == memcmp(v, "gzip", 4))
1779                     accept_encoding |= HTTP_ACCEPT_ENCODING_GZIP;
1780                #endif
1781                #ifdef USE_ZSTD
1782                 #ifdef USE_ZLIB
1783                 else
1784                 #endif
1785                 if (0 == memcmp(v, "zstd", 4))
1786                     accept_encoding |= HTTP_ACCEPT_ENCODING_ZSTD;
1787                #endif
1788                 break;
1789               case 5:
1790                #ifdef USE_BZ2LIB
1791                 if (0 == memcmp(v, "bzip2", 5))
1792                     accept_encoding |= HTTP_ACCEPT_ENCODING_BZIP2;
1793                #endif
1794                 break;
1795               case 6:
1796                #ifdef USE_ZLIB
1797                 if (0 == memcmp(v, "x-gzip", 6))
1798                     accept_encoding |= HTTP_ACCEPT_ENCODING_X_GZIP;
1799                #endif
1800                 break;
1801               case 7:
1802                #ifdef USE_ZLIB
1803                 if (0 == memcmp(v, "deflate", 7))
1804                     accept_encoding |= HTTP_ACCEPT_ENCODING_DEFLATE;
1805                #endif
1806                #ifdef USE_BZ2LIB
1807                 if (0 == memcmp(v, "x-bzip2", 7))
1808                     accept_encoding |= HTTP_ACCEPT_ENCODING_X_BZIP2;
1809                #endif
1810                 break;
1811              #if 0
1812               case 8:
1813                 if (0 == memcmp(v, "identity", 8))
1814                     accept_encoding |= HTTP_ACCEPT_ENCODING_IDENTITY;
1815                 else if (0 == memcmp(v, "compress", 8))
1816                     accept_encoding |= HTTP_ACCEPT_ENCODING_COMPRESS;
1817                 break;
1818              #endif
1819               default:
1820                 break;
1821             }
1822             if (*value == ';') {
1823                 while (*value != ',' && *value != '\0') ++value;
1824             }
1825             if (*value == '\0') break;
1826         }
1827       #endif
1828 
1829 	/* select best matching encoding */
1830 	const uint16_t *x = p->conf.allowed_encodings;
1831 	if (NULL == x) return 0;
1832 	while (*x && !(*x & accept_encoding)) ++x;
1833 	accept_encoding &= *x;
1834 #ifdef USE_ZSTD
1835 	if (accept_encoding & HTTP_ACCEPT_ENCODING_ZSTD) {
1836 		*label = "zstd";
1837 		return HTTP_ACCEPT_ENCODING_ZSTD;
1838 	} else
1839 #endif
1840 #ifdef USE_BROTLI
1841 	if (accept_encoding & HTTP_ACCEPT_ENCODING_BR) {
1842 		*label = "br";
1843 		return HTTP_ACCEPT_ENCODING_BR;
1844 	} else
1845 #endif
1846 #ifdef USE_BZ2LIB
1847 	if (accept_encoding & HTTP_ACCEPT_ENCODING_BZIP2) {
1848 		*label = "bzip2";
1849 		return HTTP_ACCEPT_ENCODING_BZIP2;
1850 	} else if (accept_encoding & HTTP_ACCEPT_ENCODING_X_BZIP2) {
1851 		*label = "x-bzip2";
1852 		return HTTP_ACCEPT_ENCODING_BZIP2;
1853 	} else
1854 #endif
1855 #ifdef USE_ZLIB
1856 	if (accept_encoding & HTTP_ACCEPT_ENCODING_GZIP) {
1857 		*label = "gzip";
1858 		return HTTP_ACCEPT_ENCODING_GZIP;
1859 	} else if (accept_encoding & HTTP_ACCEPT_ENCODING_X_GZIP) {
1860 		*label = "x-gzip";
1861 		return HTTP_ACCEPT_ENCODING_GZIP;
1862 	} else if (accept_encoding & HTTP_ACCEPT_ENCODING_DEFLATE) {
1863 		*label = "deflate";
1864 		return HTTP_ACCEPT_ENCODING_DEFLATE;
1865 	} else
1866 #endif
1867 	if (0 == accept_encoding) {
1868 		return 0;
1869 	} else {
1870 		return 0;
1871 	}
1872 }
1873 
1874 REQUEST_FUNC(mod_deflate_handle_response_start) {
1875 	plugin_data *p = p_d;
1876 	const buffer *vbro;
1877 	buffer *vb;
1878 	handler_ctx *hctx;
1879 	const char *label;
1880 	off_t len;
1881 	uint32_t etaglen;
1882 	int compression_type;
1883 	handler_t rc;
1884 	int had_vary = 0;
1885 
1886 	/*(current implementation requires response be complete)*/
1887 	if (!r->resp_body_finished) return HANDLER_GO_ON;
1888 	if (r->http_method == HTTP_METHOD_HEAD) return HANDLER_GO_ON;
1889 	if (light_btst(r->resp_htags, HTTP_HEADER_TRANSFER_ENCODING))
1890 		return HANDLER_GO_ON;
1891 	if (light_btst(r->resp_htags, HTTP_HEADER_CONTENT_ENCODING))
1892 		return HANDLER_GO_ON;
1893 
1894 	/* disable compression for some http status types. */
1895 	switch(r->http_status) {
1896 	case 100:
1897 	case 101:
1898 	case 204:
1899 	case 205:
1900 	case 304:
1901 		/* disable compression as we have no response entity */
1902 		return HANDLER_GO_ON;
1903 	default:
1904 		break;
1905 	}
1906 
1907 	mod_deflate_patch_config(r, p);
1908 
1909 	/* check if deflate configured for any mimetypes */
1910 	if (NULL == p->conf.mimetypes) return HANDLER_GO_ON;
1911 
1912 	/* check if size of response is below min-compress-size or exceeds max*/
1913 	/* (r->resp_body_finished checked at top of routine) */
1914 	len = chunkqueue_length(&r->write_queue);
1915 	if (len <= (off_t)p->conf.min_compress_size) return HANDLER_GO_ON;
1916 	if (p->conf.max_compress_size /*(max_compress_size in KB)*/
1917 	    && len > ((off_t)p->conf.max_compress_size << 10)) {
1918 		return HANDLER_GO_ON;
1919 	}
1920 
1921 	/* Check Accept-Encoding for supported encoding. */
1922 	vbro = http_header_request_get(r, HTTP_HEADER_ACCEPT_ENCODING, CONST_STR_LEN("Accept-Encoding"));
1923 	if (NULL == vbro) return HANDLER_GO_ON;
1924 
1925 	/* find matching encodings */
1926 	compression_type = mod_deflate_choose_encoding(vbro->ptr, p, &label);
1927 	if (!compression_type) return HANDLER_GO_ON;
1928 
1929 	/* Check mimetype in response header "Content-Type" */
1930 	if (NULL != (vbro = http_header_response_get(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type")))) {
1931 		if (NULL == array_match_value_prefix(p->conf.mimetypes, vbro)) return HANDLER_GO_ON;
1932 	} else {
1933 		/* If no Content-Type set, compress only if first p->conf.mimetypes value is "" */
1934 		data_string *mimetype = (data_string *)p->conf.mimetypes->data[0];
1935 		if (!buffer_is_blank(&mimetype->value)) return HANDLER_GO_ON;
1936 	}
1937 
1938 	/* Vary: Accept-Encoding (response might change according to request Accept-Encoding) */
1939 	if (NULL != (vb = http_header_response_get(r, HTTP_HEADER_VARY, CONST_STR_LEN("Vary")))) {
1940 		had_vary = 1;
1941 		if (!http_header_str_contains_token(BUF_PTR_LEN(vb),
1942 		                                    CONST_STR_LEN("Accept-Encoding")))
1943 			buffer_append_string_len(vb, CONST_STR_LEN(",Accept-Encoding"));
1944 	} else {
1945 		http_header_response_append(r, HTTP_HEADER_VARY,
1946 					    CONST_STR_LEN("Vary"),
1947 					    CONST_STR_LEN("Accept-Encoding"));
1948 	}
1949 
1950 	/* check ETag as is done in http_response_handle_cachable()
1951 	 * (slightly imperfect (close enough?) match of ETag "000000" to "000000-gzip") */
1952 	vb = http_header_response_get(r, HTTP_HEADER_ETAG, CONST_STR_LEN("ETag"));
1953 	etaglen = vb ? buffer_clen(vb) : 0;
1954 	if (etaglen && light_btst(r->rqst_htags, HTTP_HEADER_IF_NONE_MATCH)) {
1955 		const buffer *if_none_match = http_header_request_get(r, HTTP_HEADER_IF_NONE_MATCH, CONST_STR_LEN("If-None-Match"));
1956 		if (   r->http_status < 300 /*(want 2xx only)*/
1957 		    && NULL != if_none_match
1958 		    && 0 == strncmp(if_none_match->ptr, vb->ptr, etaglen-1)
1959 		    && if_none_match->ptr[etaglen-1] == '-'
1960 		    && 0 == strncmp(if_none_match->ptr+etaglen, label, strlen(label))) {
1961 
1962 			if (http_method_get_or_head(r->http_method)) {
1963 				/* modify ETag response header in-place to remove '"' and append '-label"' */
1964 				vb->ptr[etaglen-1] = '-'; /*(overwrite end '"')*/
1965 				buffer_append_string(vb, label);
1966 				buffer_append_string_len(vb, CONST_STR_LEN("\""));
1967 				r->http_status = 304;
1968 			} else {
1969 				r->http_status = 412;
1970 			}
1971 
1972 			/* response_start hook occurs after error docs have been handled.
1973 			 * For now, send back empty response body.
1974 			 * In the future, might extract the error doc code so that it
1975 			 * might be run again if response_start hooks return with
1976 			 * changed http_status and r->handler_module = NULL */
1977 			/* clear content length even if 304 since compressed length unknown */
1978 			http_response_body_clear(r, 0);
1979 
1980 			r->resp_body_finished = 1;
1981 			r->handler_module = NULL;
1982 			return HANDLER_GO_ON;
1983 		}
1984 	}
1985 
1986 	if (0.0 < p->conf.max_loadavg && p->conf.max_loadavg < r->con->srv->loadavg[0]) {
1987 		return HANDLER_GO_ON;
1988 	}
1989 
1990 	/* update ETag, if ETag response header is set */
1991 	if (etaglen) {
1992 		/* modify ETag response header in-place to remove '"' and append '-label"' */
1993 		vb->ptr[etaglen-1] = '-'; /*(overwrite end '"')*/
1994 		buffer_append_string(vb, label);
1995 		buffer_append_string_len(vb, CONST_STR_LEN("\""));
1996 	}
1997 
1998 	/* set Content-Encoding to show selected compression type */
1999 	http_header_response_set(r, HTTP_HEADER_CONTENT_ENCODING, CONST_STR_LEN("Content-Encoding"), label, strlen(label));
2000 
2001 	/* clear Content-Length and r->write_queue if HTTP HEAD request
2002 	 * (alternatively, could return original Content-Length with HEAD
2003 	 *  request if ETag not modified and Content-Encoding not added)
2004 	 * (see top of this func where short-circuit is done on HTTP HEAD) */
2005 	if (HTTP_METHOD_HEAD == r->http_method) {
2006 		/* ensure that uncompressed Content-Length is not sent in HEAD response */
2007 		http_response_body_clear(r, 0);
2008 		return HANDLER_GO_ON;
2009 	}
2010 
2011 	/* restrict items eligible for cache of compressed responses
2012 	 * (This module does not aim to be a full caching proxy)
2013 	 * response must be complete (not streaming response)
2014 	 * must not have prior Vary response header (before Accept-Encoding added)
2015 	 * must have ETag
2016 	 * must be file
2017 	 * must be single FILE_CHUNK in chunkqueue
2018 	 * must not be chunkqueue temporary file
2019 	 * must be whole file, not partial content
2020 	 * must not be HTTP status 206 Partial Content
2021 	 * Note: small files (< 32k (see http_chunk.c)) will have been read into
2022 	 *       memory (if streaming HTTP/1.1 chunked response) and will end up
2023 	 *       getting stream-compressed rather than cached on disk as compressed
2024 	 *       file
2025 	 */
2026 	buffer *tb = NULL;
2027 	if (p->conf.cache_dir
2028 	    && !had_vary
2029 	    && etaglen > 2
2030 	    && r->resp_body_finished
2031 	    && r->write_queue.first == r->write_queue.last
2032 	    && r->write_queue.first->type == FILE_CHUNK
2033 	    && r->write_queue.first->offset == 0
2034 	    && !r->write_queue.first->file.is_temp
2035 	    && r->http_status != 206) {
2036 		tb = mod_deflate_cache_file_name(r, p->conf.cache_dir, vb);
2037 		/*(checked earlier and skipped if Transfer-Encoding had been set)*/
2038 		stat_cache_entry *sce = stat_cache_get_entry_open(tb, 1);
2039 		if (NULL != sce) {
2040 			chunkqueue_reset(&r->write_queue);
2041 			if (sce->fd < 0 || 0 != http_chunk_append_file_ref(r, sce))
2042 				return HANDLER_ERROR;
2043 			if (light_btst(r->resp_htags, HTTP_HEADER_CONTENT_LENGTH))
2044 				http_header_response_unset(r, HTTP_HEADER_CONTENT_LENGTH,
2045 				                           CONST_STR_LEN("Content-Length"));
2046 			mod_deflate_note_ratio(r, sce->st.st_size, len);
2047 			return HANDLER_GO_ON;
2048 		}
2049 		/* sanity check that response was whole file;
2050 		 * (racy since using stat_cache, but cache file only if match) */
2051 		sce = stat_cache_get_entry(r->write_queue.first->mem);
2052 		if (NULL == sce || sce->st.st_size != len)
2053 			tb = NULL;
2054 		else if (0 != mkdir_for_file(tb->ptr))
2055 			tb = NULL;
2056 	}
2057 
2058 	/* enable compression */
2059 	p->conf.sync_flush =
2060 	  ((r->conf.stream_response_body
2061 	    & (FDEVENT_STREAM_RESPONSE | FDEVENT_STREAM_RESPONSE_BUFMIN))
2062 	   && 0 == p->conf.output_buffer_size);
2063 	hctx = handler_ctx_init();
2064 	hctx->plugin_data = p;
2065 	hctx->compression_type = compression_type;
2066 	hctx->r = r;
2067 	/* setup output buffer */
2068 	buffer_clear(&p->tmp_buf);
2069 	hctx->output = &p->tmp_buf;
2070 	/* open cache file if caching compressed file */
2071 	if (tb) mod_deflate_cache_file_open(hctx, tb);
2072 
2073   #ifdef HAVE_LIBDEFLATE
2074 	chunk * const c = r->write_queue.first; /*(invalid after compression)*/
2075   #ifdef HAVE_MMAP
2076   #if defined(_LP64) || defined(__LP64__) || defined(_WIN64)
2077 	/* optimization to compress single file in one-shot to writeable mmap */
2078 	/*(future: might extend to other compression types)*/
2079 	/*(chunkqueue_chunk_file_view() current min size for mmap is 128k)*/
2080 	if (len > 131072 /* XXX: TBD what should min size be for optimization?*/
2081 	    && (hctx->compression_type == HTTP_ACCEPT_ENCODING_GZIP
2082 	        || hctx->compression_type == HTTP_ACCEPT_ENCODING_DEFLATE)
2083 	    && c == r->write_queue.last
2084 	    && c->type == FILE_CHUNK
2085 	    && chunkqueue_chunk_file_view(c, len, r->conf.errh)
2086 	    && chunk_file_view_dlen(c->file.view, c->offset) >= len) { /*(cfv)*/
2087 		rc = HANDLER_GO_ON;
2088 		hctx->bytes_in = len;
2089 		if (mod_deflate_using_libdeflate(hctx, p)) {
2090 			if (NULL == tb || 0 == mod_deflate_cache_file_finish(r, hctx, tb))
2091 				mod_deflate_note_ratio(r, hctx->bytes_out, hctx->bytes_in);
2092 			else
2093 				rc = HANDLER_ERROR;
2094 			handler_ctx_free(hctx);
2095 			return rc;
2096 		}
2097 		hctx->bytes_in = hctx->bytes_out = 0;
2098 	}
2099 	else
2100   #endif
2101   #endif
2102 	if (len <= 65536 /*(p->tmp_buf is at least 64k)*/
2103 	    && (hctx->compression_type == HTTP_ACCEPT_ENCODING_GZIP
2104 	        || hctx->compression_type == HTTP_ACCEPT_ENCODING_DEFLATE)
2105 	    && c == r->write_queue.last
2106 	    && c->type == MEM_CHUNK) {
2107 		/*(skip if FILE_CHUNK; not worth mmap/munmap overhead on small file)*/
2108 		rc = HANDLER_GO_ON;
2109 		hctx->bytes_in = len;
2110 		if (mod_deflate_using_libdeflate_sm(hctx, p)) {
2111 			if (NULL == tb || 0 == mod_deflate_cache_file_finish(r, hctx, tb))
2112 				mod_deflate_note_ratio(r, hctx->bytes_out, hctx->bytes_in);
2113 			else
2114 				rc = HANDLER_ERROR;
2115 			handler_ctx_free(hctx);
2116 			return rc;
2117 		}
2118 		hctx->bytes_in = hctx->bytes_out = 0;
2119 	}
2120   #endif /* HAVE_LIBDEFLATE */
2121 
2122 	if (0 != mod_deflate_stream_init(hctx)) {
2123 		/*(should not happen unless ENOMEM)*/
2124 		handler_ctx_free(hctx);
2125 		log_error(r->conf.errh, __FILE__, __LINE__,
2126 		  "Failed to initialize compression %s", label);
2127 		/* restore prior Etag and unset Content-Encoding */
2128 		if (etaglen) {
2129 			vb->ptr[etaglen-1] = '"'; /*(overwrite '-')*/
2130 			buffer_truncate(vb, etaglen);
2131 		}
2132 		http_header_response_unset(r, HTTP_HEADER_CONTENT_ENCODING, CONST_STR_LEN("Content-Encoding"));
2133 		return HANDLER_GO_ON;
2134 	}
2135 
2136   #ifdef USE_BROTLI
2137 	if (r->resp_body_finished
2138 	    && (hctx->compression_type & HTTP_ACCEPT_ENCODING_BR)
2139 	    && (len >> 1) < (off_t)((~(uint32_t)0u) >> 1))
2140 		BrotliEncoderSetParameter(hctx->u.br, BROTLI_PARAM_SIZE_HINT, (uint32_t)len);
2141   #endif
2142 
2143 	if (light_btst(r->resp_htags, HTTP_HEADER_CONTENT_LENGTH)) {
2144 		http_header_response_unset(r, HTTP_HEADER_CONTENT_LENGTH, CONST_STR_LEN("Content-Length"));
2145 	}
2146 	r->plugin_ctx[p->id] = hctx;
2147 
2148 	rc = deflate_compress_response(r, hctx);
2149 	if (HANDLER_GO_ON == rc) return HANDLER_GO_ON;
2150 	if (HANDLER_FINISHED == rc) {
2151 	  #ifdef __COVERITY__
2152 		/* coverity misses if hctx->cache_fd is not -1, then tb is not NULL */
2153 		force_assert(-1 == hctx->cache_fd || NULL != tb);
2154 	  #endif
2155 		if (-1 == hctx->cache_fd
2156 		    || 0 == mod_deflate_cache_file_finish(r, hctx, tb)) {
2157 			mod_deflate_note_ratio(r, hctx->bytes_out, hctx->bytes_in);
2158 			rc = HANDLER_GO_ON;
2159 		}
2160 		else
2161 			rc = HANDLER_ERROR;
2162 	}
2163 	r->plugin_ctx[p->id] = NULL;
2164 	if (deflate_compress_cleanup(r, hctx) < 0) return HANDLER_ERROR;
2165 	return rc;
2166 }
2167 
2168 static handler_t mod_deflate_cleanup(request_st * const r, void *p_d) {
2169 	plugin_data *p = p_d;
2170 	handler_ctx *hctx = r->plugin_ctx[p->id];
2171 
2172 	if (NULL != hctx) {
2173 		r->plugin_ctx[p->id] = NULL;
2174 		deflate_compress_cleanup(r, hctx);
2175 	}
2176 
2177 	return HANDLER_GO_ON;
2178 }
2179 
2180 int mod_deflate_plugin_init(plugin *p);
2181 int mod_deflate_plugin_init(plugin *p) {
2182 	p->version     = LIGHTTPD_VERSION_ID;
2183 	p->name        = "deflate";
2184 
2185 	p->init		= mod_deflate_init;
2186 	p->cleanup	= mod_deflate_free;
2187 	p->set_defaults	= mod_deflate_set_defaults;
2188 	p->handle_request_reset = mod_deflate_cleanup;
2189 	p->handle_response_start	= mod_deflate_handle_response_start;
2190 
2191 	return 0;
2192 }
2193