Add #182: Before enforcing the client-header-order, check that the client headers...
[privoxy.git] / parsers.c
1 /*********************************************************************
2  *
3  * File        :  $Source: /cvsroot/ijbswa/current/parsers.c,v $
4  *
5  * Purpose     :  Declares functions to parse/crunch headers and pages.
6  *
7  * Copyright   :  Written by and Copyright (C) 2001-2021 the
8  *                Privoxy team. https://www.privoxy.org/
9  *
10  *                Based on the Internet Junkbuster originally written
11  *                by and Copyright (C) 1997 Anonymous Coders and
12  *                Junkbusters Corporation.  http://www.junkbusters.com
13  *
14  *                This program is free software; you can redistribute it
15  *                and/or modify it under the terms of the GNU General
16  *                Public License as published by the Free Software
17  *                Foundation; either version 2 of the License, or (at
18  *                your option) any later version.
19  *
20  *                This program is distributed in the hope that it will
21  *                be useful, but WITHOUT ANY WARRANTY; without even the
22  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
23  *                PARTICULAR PURPOSE.  See the GNU General Public
24  *                License for more details.
25  *
26  *                The GNU General Public License should be included with
27  *                this file.  If not, you can view it at
28  *                http://www.gnu.org/copyleft/gpl.html
29  *                or write to the Free Software Foundation, Inc., 59
30  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
31  *
32  *********************************************************************/
33
34
35 #include "config.h"
36
37 #ifndef _WIN32
38 #include <stdio.h>
39 #include <sys/types.h>
40 #endif
41
42 #include <stdlib.h>
43 #include <ctype.h>
44 #include <assert.h>
45 #include <string.h>
46
47 #ifdef __GLIBC__
48 /*
49  * Convince GNU's libc to provide a strptime prototype.
50  */
51 #define __USE_XOPEN
52 #endif /*__GLIBC__ */
53 #include <time.h>
54
55 #ifdef FEATURE_ZLIB
56 #include <zlib.h>
57
58 #define GZIP_IDENTIFIER_1       0x1f
59 #define GZIP_IDENTIFIER_2       0x8b
60
61 #define GZIP_FLAG_CHECKSUM      0x02
62 #define GZIP_FLAG_EXTRA_FIELDS  0x04
63 #define GZIP_FLAG_FILE_NAME     0x08
64 #define GZIP_FLAG_COMMENT       0x10
65 #define GZIP_FLAG_RESERVED_BITS 0xe0
66 #endif
67 #ifdef FEATURE_BROTLI
68 #include <brotli/decode.h>
69 #endif
70
71 #if !defined(_WIN32)
72 #include <unistd.h>
73 #endif
74
75 #include "project.h"
76
77 #ifdef FEATURE_PTHREAD
78 #include "jcc.h"
79 /* jcc.h is for mutex semapores only */
80 #endif /* def FEATURE_PTHREAD */
81 #include "list.h"
82 #include "parsers.h"
83 #include "ssplit.h"
84 #include "errlog.h"
85 #include "jbsockets.h"
86 #include "miscutil.h"
87 #include "list.h"
88 #include "actions.h"
89 #include "filters.h"
90 #ifdef FEATURE_HTTPS_INSPECTION
91 #include "ssl.h"
92 #endif
93
94 #ifndef HAVE_STRPTIME
95 #include "strptime.h"
96 #endif
97
98 static char *get_header_line(struct iob *iob);
99 static jb_err scan_headers(struct client_state *csp);
100 static jb_err header_tagger(struct client_state *csp, char *header);
101 static jb_err parse_header_time(const char *header_time, time_t *result);
102 static jb_err parse_time_header(const char *header, time_t *result);
103
104 static jb_err crumble                   (struct client_state *csp, char **header);
105 static jb_err filter_header             (struct client_state *csp, char **header);
106 static jb_err client_connection         (struct client_state *csp, char **header);
107 static jb_err client_referrer           (struct client_state *csp, char **header);
108 static jb_err client_uagent             (struct client_state *csp, char **header);
109 static jb_err client_ua                 (struct client_state *csp, char **header);
110 static jb_err client_from               (struct client_state *csp, char **header);
111 static jb_err client_send_cookie        (struct client_state *csp, char **header);
112 static jb_err client_x_forwarded        (struct client_state *csp, char **header);
113 static jb_err client_accept_encoding    (struct client_state *csp, char **header);
114 static jb_err client_te                 (struct client_state *csp, char **header);
115 static jb_err client_max_forwards       (struct client_state *csp, char **header);
116 static jb_err client_host               (struct client_state *csp, char **header);
117 static jb_err client_if_modified_since  (struct client_state *csp, char **header);
118 static jb_err client_accept_language    (struct client_state *csp, char **header);
119 static jb_err client_if_none_match      (struct client_state *csp, char **header);
120 static jb_err crunch_client_header      (struct client_state *csp, char **header);
121 static jb_err client_x_filter           (struct client_state *csp, char **header);
122 static jb_err client_range              (struct client_state *csp, char **header);
123 static jb_err client_expect             (struct client_state *csp, char **header);
124 static jb_err server_set_cookie         (struct client_state *csp, char **header);
125 static jb_err server_connection         (struct client_state *csp, char **header);
126 static jb_err server_content_type       (struct client_state *csp, char **header);
127 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
128 static jb_err server_content_md5        (struct client_state *csp, char **header);
129 static jb_err server_content_encoding   (struct client_state *csp, char **header);
130 static jb_err server_transfer_coding    (struct client_state *csp, char **header);
131 static jb_err server_http               (struct client_state *csp, char **header);
132 static jb_err crunch_server_header      (struct client_state *csp, char **header);
133 static jb_err server_last_modified      (struct client_state *csp, char **header);
134 static jb_err server_content_disposition(struct client_state *csp, char **header);
135 #ifdef FEATURE_ZLIB
136 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
137 #endif
138
139 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
140 static jb_err server_save_content_length(struct client_state *csp, char **header);
141 static jb_err server_keep_alive(struct client_state *csp, char **header);
142 static jb_err server_proxy_connection(struct client_state *csp, char **header);
143 static jb_err client_keep_alive(struct client_state *csp, char **header);
144 static jb_err client_proxy_connection(struct client_state *csp, char **header);
145 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
146
147 static jb_err client_save_content_length(struct client_state *csp, char **header);
148 static jb_err client_host_adder       (struct client_state *csp);
149 static jb_err client_xtra_adder       (struct client_state *csp);
150 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
151 static jb_err client_connection_header_adder(struct client_state *csp);
152 static jb_err server_connection_adder(struct client_state *csp);
153 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
154 static jb_err server_proxy_connection_adder(struct client_state *csp);
155 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
156 static jb_err proxy_authentication(struct client_state *csp, char **header);
157
158 static jb_err create_forged_referrer(char **header, const char *hostport);
159 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
160 static jb_err handle_conditional_hide_referrer_parameter(char **header,
161    const char *host, const int parameter_conditional_block);
162 static void create_content_length_header(unsigned long long content_length,
163                                          char *header, size_t buffer_length);
164
165 /*
166  * List of functions to run on a list of headers.
167  */
168 struct parsers
169 {
170    /** The header prefix to match */
171    const char *str;
172
173    /** The length of the prefix to match */
174    const size_t len;
175
176    /** The function to apply to this line */
177    const parser_func_ptr parser;
178 };
179
180 static const struct parsers client_patterns[] = {
181    { "referer:",                  8,   client_referrer },
182    { "user-agent:",              11,   client_uagent },
183    { "ua-",                       3,   client_ua },
184    { "from:",                     5,   client_from },
185    { "cookie:",                   7,   client_send_cookie },
186    { "x-forwarded-for:",         16,   client_x_forwarded },
187    { "Accept-Encoding:",         16,   client_accept_encoding },
188    { "TE:",                       3,   client_te },
189    { "Host:",                     5,   client_host },
190    { "if-modified-since:",       18,   client_if_modified_since },
191    { "Content-Length:",          15,   client_save_content_length },
192 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
193    { "Keep-Alive:",              11,   client_keep_alive },
194    { "Proxy-Connection:",        17,   client_proxy_connection },
195 #else
196    { "Keep-Alive:",              11,   crumble },
197    { "Proxy-Connection:",        17,   crumble },
198 #endif
199    { "connection:",              11,   client_connection },
200    { "max-forwards:",            13,   client_max_forwards },
201    { "Accept-Language:",         16,   client_accept_language },
202    { "if-none-match:",           14,   client_if_none_match },
203    { "Range:",                    6,   client_range },
204    { "Request-Range:",           14,   client_range },
205    { "If-Range:",                 9,   client_range },
206    { "X-Filter:",                 9,   client_x_filter },
207    { "Proxy-Authorization:",     20,   proxy_authentication },
208 #if 0
209    { "Transfer-Encoding:",       18,   client_transfer_encoding },
210 #endif
211    { "Expect:",                   7,   client_expect },
212    { "*",                         0,   crunch_client_header },
213    { "*",                         0,   filter_header },
214    { NULL,                        0,   NULL }
215 };
216
217 static const struct parsers server_patterns[] = {
218    { "HTTP/",                     5, server_http },
219    { "set-cookie:",              11, server_set_cookie },
220    { "connection:",              11, server_connection },
221    { "Content-Type:",            13, server_content_type },
222    { "Content-MD5:",             12, server_content_md5 },
223    { "Content-Encoding:",        17, server_content_encoding },
224 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
225    { "Content-Length:",          15, server_save_content_length },
226    { "Keep-Alive:",              11, server_keep_alive },
227    { "Proxy-Connection:",        17, server_proxy_connection },
228 #else
229    { "Keep-Alive:",              11, crumble },
230 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
231    { "Transfer-Encoding:",       18, server_transfer_coding },
232    { "content-disposition:",     20, server_content_disposition },
233    { "Last-Modified:",           14, server_last_modified },
234    { "Proxy-Authenticate:",      19, proxy_authentication },
235    { "*",                         0, crunch_server_header },
236    { "*",                         0, filter_header },
237    { NULL,                        0, NULL }
238 };
239
240 static const add_header_func_ptr add_client_headers[] = {
241    client_host_adder,
242    client_x_forwarded_for_adder,
243    client_xtra_adder,
244    client_connection_header_adder,
245    NULL
246 };
247
248 static const add_header_func_ptr add_server_headers[] = {
249    server_connection_adder,
250 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
251    server_proxy_connection_adder,
252 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
253    NULL
254 };
255
256 /*********************************************************************
257  *
258  * Function    :  flush_iob
259  *
260  * Description :  Write any pending "buffered" content.
261  *
262  * Parameters  :
263  *          1  :  fd = file descriptor of the socket to read
264  *          2  :  iob = The I/O buffer to flush, usually csp->iob.
265  *          3  :  delay = Number of milliseconds to delay the writes
266  *
267  * Returns     :  On success, the number of bytes written are returned (zero
268  *                indicates nothing was written).  On error, -1 is returned,
269  *                and errno is set appropriately.  If count is zero and the
270  *                file descriptor refers to a regular file, 0 will be
271  *                returned without causing any other effect.  For a special
272  *                file, the results are not portable.
273  *
274  *********************************************************************/
275 long flush_iob(jb_socket fd, struct iob *iob, unsigned int delay)
276 {
277    long len = iob->eod - iob->cur;
278
279    if (len <= 0)
280    {
281       return(0);
282    }
283
284    if (write_socket_delayed(fd, iob->cur, (size_t)len, delay))
285    {
286       return(-1);
287    }
288    iob->eod = iob->cur = iob->buf;
289    return(len);
290
291 }
292
293
294 /*********************************************************************
295  *
296  * Function    :  can_add_to_iob
297  *
298  * Description :  Checks if the given number of bytes can be added to the given iob
299  *                without exceeding the given buffer limit.
300  *
301  * Parameters  :
302  *          1  :  iob = Destination buffer.
303  *          2  :  buffer_limit = Limit to which the destination may grow
304  *          3  :  n = number of bytes to be added
305  *
306  * Returns     :  TRUE if the given iob can handle given number of bytes
307  *                FALSE buffer limit will be exceeded
308  *
309  *********************************************************************/
310 int can_add_to_iob(const struct iob *iob, const size_t buffer_limit, size_t n)
311 {
312    return ((size_t)(iob->eod - iob->buf) + n + 1) > buffer_limit ? FALSE : TRUE;
313 }
314
315 /*********************************************************************
316  *
317  * Function    :  add_to_iob
318  *
319  * Description :  Add content to the buffer, expanding the
320  *                buffer if necessary.
321  *
322  * Parameters  :
323  *          1  :  iob = Destination buffer.
324  *          2  :  buffer_limit = Limit to which the destination may grow
325  *          3  :  src = holds the content to be added
326  *          4  :  n = number of bytes to be added
327  *
328  * Returns     :  JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
329  *                or buffer limit reached.
330  *
331  *********************************************************************/
332 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, const char *src, long n)
333 {
334    size_t used, offset, need;
335    char *p;
336
337    if (n <= 0) return JB_ERR_OK;
338
339    used   = (size_t)(iob->eod - iob->buf);
340    offset = (size_t)(iob->cur - iob->buf);
341    need   = used + (size_t)n + 1;
342
343    /*
344     * If the buffer can't hold the new data, extend it first.
345     * Use the next power of two if possible, else use the actual need.
346     */
347    if (need > buffer_limit)
348    {
349       log_error(LOG_LEVEL_INFO,
350          "Buffer limit reached while extending the buffer (iob). Needed: %lu. Limit: %lu",
351          need, buffer_limit);
352       return JB_ERR_MEMORY;
353    }
354
355    if (need > iob->size)
356    {
357       size_t want = iob->size ? iob->size : 512;
358
359       while (want <= need)
360       {
361          want *= 2;
362       }
363
364       if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
365       {
366          iob->size = want;
367       }
368       else if (NULL != (p = (char *)realloc(iob->buf, need)))
369       {
370          iob->size = need;
371       }
372       else
373       {
374          log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
375          return JB_ERR_MEMORY;
376       }
377
378       /* Update the iob pointers */
379       iob->cur = p + offset;
380       iob->eod = p + used;
381       iob->buf = p;
382    }
383
384    /* copy the new data into the iob buffer */
385    memcpy(iob->eod, src, (size_t)n);
386
387    /* point to the end of the data */
388    iob->eod += n;
389
390    /* null terminate == cheap insurance */
391    *iob->eod = '\0';
392
393    return JB_ERR_OK;
394
395 }
396
397
398 /*********************************************************************
399  *
400  * Function    :  clear_iob
401  *
402  * Description :  Frees the memory allocated for an I/O buffer and
403  *                resets the structure.
404  *
405  * Parameters  :
406  *          1  :  iob = I/O buffer to clear.
407  *
408  * Returns     :  N/A
409  *
410  *********************************************************************/
411 void clear_iob(struct iob *iob)
412 {
413    free(iob->buf);
414    memset(iob, '\0', sizeof(*iob));
415 }
416
417
418 #ifdef FEATURE_ZLIB
419 #ifdef FEATURE_BROTLI
420 /*********************************************************************
421  *
422  * Function    :  decompress_iob_with_brotli
423  *
424  * Description :  Decompress buffered page using Brotli.
425  *
426  * Parameters  :
427  *          1  :  csp = Current client state (buffers, headers, etc...)
428  *
429  * Returns     :  JB_ERR_OK on success,
430  *                JB_ERR_MEMORY if out-of-memory limit reached, and
431  *                JB_ERR_COMPRESS if error decompressing buffer.
432  *
433  *********************************************************************/
434 static jb_err decompress_iob_with_brotli(struct client_state *csp)
435 {
436    BrotliDecoderResult result;
437    char *decoded_buffer;
438    size_t decoded_size;
439    size_t decoded_buffer_size;
440    size_t encoded_size;
441    enum { MAX_COMPRESSION_FACTOR = 15 };
442
443    encoded_size = (size_t)(csp->iob->eod - csp->iob->cur);
444    /*
445     * The BrotliDecoderDecompress() api is a bit unfortunate
446     * and requires the caller to reserve enough memory for
447     * the decompressed content. Hopefully reserving
448     * MAX_COMPRESSION_FACTOR times the original size is
449     * sufficient. If not, BrotliDecoderDecompress() will fail.
450     */
451    decoded_buffer_size = encoded_size * MAX_COMPRESSION_FACTOR;
452
453    if (decoded_buffer_size > csp->config->buffer_limit)
454    {
455       log_error(LOG_LEVEL_ERROR,
456          "Buffer limit reached before decompressing iob with Brotli");
457       return JB_ERR_MEMORY;
458    }
459
460    decoded_buffer = malloc(decoded_buffer_size);
461    if (decoded_buffer == NULL)
462    {
463       log_error(LOG_LEVEL_ERROR,
464          "Failed to allocate %lu bytes for Brotli decompression",
465          decoded_buffer_size);
466       return JB_ERR_MEMORY;
467    }
468
469    decoded_size = decoded_buffer_size;
470    result = BrotliDecoderDecompress(encoded_size,
471       (const uint8_t *)csp->iob->cur, &decoded_size,
472       (uint8_t *)decoded_buffer);
473    if (result == BROTLI_DECODER_RESULT_SUCCESS)
474    {
475       /*
476        * Update the iob, since the decompression was successful.
477        */
478       freez(csp->iob->buf);
479       csp->iob->buf  = decoded_buffer;
480       csp->iob->cur  = csp->iob->buf;
481       csp->iob->eod  = csp->iob->cur + decoded_size;
482       csp->iob->size = decoded_buffer_size;
483
484       log_error(LOG_LEVEL_RE_FILTER,
485          "Decompression successful. Old size: %lu, new size: %lu.",
486          encoded_size, decoded_size);
487
488       return JB_ERR_OK;
489    }
490    else
491    {
492       log_error(LOG_LEVEL_ERROR, "Failed to decompress buffer with Brotli");
493       freez(decoded_buffer);
494
495       return JB_ERR_COMPRESS;
496    }
497 }
498 #endif
499
500 /*********************************************************************
501  *
502  * Function    :  decompress_iob
503  *
504  * Description :  Decompress buffered page, expanding the
505  *                buffer as necessary.  csp->iob->cur
506  *                should point to the the beginning of the
507  *                compressed data block.
508  *
509  * Parameters  :
510  *          1  :  csp = Current client state (buffers, headers, etc...)
511  *
512  * Returns     :  JB_ERR_OK on success,
513  *                JB_ERR_MEMORY if out-of-memory limit reached, and
514  *                JB_ERR_COMPRESS if error decompressing buffer.
515  *
516  *********************************************************************/
517 jb_err decompress_iob(struct client_state *csp)
518 {
519    char  *buf;       /* new, uncompressed buffer */
520    char  *cur;       /* Current iob position (to keep the original
521                       * iob->cur unmodified if we return early) */
522    size_t bufsize;   /* allocated size of the new buffer */
523    size_t old_size;  /* Content size before decompression */
524    size_t skip_size; /* Number of bytes at the beginning of the iob
525                         that we should NOT decompress. */
526    int status;       /* return status of the inflate() call */
527    z_stream zstr;    /* used by calls to zlib */
528
529 #ifdef FUZZ
530    assert(csp->iob->cur - csp->iob->buf >= 0);
531    assert(csp->iob->eod - csp->iob->cur >= 0);
532 #else
533    assert(csp->iob->cur - csp->iob->buf > 0);
534    assert(csp->iob->eod - csp->iob->cur > 0);
535 #endif
536
537    bufsize = csp->iob->size;
538    skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
539    old_size = (size_t)(csp->iob->eod - csp->iob->cur);
540
541    cur = csp->iob->cur;
542
543    if (bufsize < (size_t)10)
544    {
545       /*
546        * This is to protect the parsing of gzipped data,
547        * but it should(?) be valid for deflated data also.
548        */
549       log_error(LOG_LEVEL_ERROR,
550          "Insufficient data to start decompression. Bytes in buffer: %ld",
551          csp->iob->eod - csp->iob->cur);
552       return JB_ERR_COMPRESS;
553    }
554
555 #ifdef FEATURE_BROTLI
556    if (csp->content_type & CT_BROTLI)
557    {
558       return decompress_iob_with_brotli(csp);
559    }
560 #endif
561
562    if (csp->content_type & CT_GZIP)
563    {
564       /*
565        * Our task is slightly complicated by the facts that data
566        * compressed by gzip does not include a zlib header, and
567        * that there is no easily accessible interface in zlib to
568        * handle a gzip header. We strip off the gzip header by
569        * hand, and later inform zlib not to expect a header.
570        */
571
572       /*
573        * Strip off the gzip header. Please see RFC 1952 for more
574        * explanation of the appropriate fields.
575        */
576       if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
577        || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
578        || (*cur++ != Z_DEFLATED))
579       {
580          log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
581          return JB_ERR_COMPRESS;
582       }
583       else
584       {
585          int flags = *cur++;
586          if (flags & GZIP_FLAG_RESERVED_BITS)
587          {
588             /* The gzip header has reserved bits set; bail out. */
589             log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
590             return JB_ERR_COMPRESS;
591          }
592
593          /*
594           * Skip mtime (4 bytes), extra flags (1 byte)
595           * and OS type (1 byte).
596           */
597          cur += 6;
598
599          /* Skip extra fields if necessary. */
600          if (flags & GZIP_FLAG_EXTRA_FIELDS)
601          {
602             /*
603              * Skip a given number of bytes, specified
604              * as a 16-bit little-endian value.
605              *
606              * XXX: this code is untested and should probably be removed.
607              */
608             int skip_bytes;
609             skip_bytes = *cur++;
610             skip_bytes += *cur++ << 8;
611
612             /*
613              * The number of bytes to skip should be positive
614              * and we'd like to stay in the buffer.
615              */
616             if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
617             {
618                log_error(LOG_LEVEL_ERROR,
619                   "Unreasonable amount of bytes to skip (%d). Stopping decompression",
620                   skip_bytes);
621                return JB_ERR_COMPRESS;
622             }
623             log_error(LOG_LEVEL_INFO,
624                "Skipping %d bytes for gzip compression. Does this sound right?",
625                skip_bytes);
626             cur += skip_bytes;
627          }
628
629          /* Skip the filename if necessary. */
630          if (flags & GZIP_FLAG_FILE_NAME)
631          {
632             /* A null-terminated string is supposed to follow. */
633             while (*cur++ && (cur < csp->iob->eod));
634          }
635
636          /* Skip the comment if necessary. */
637          if (flags & GZIP_FLAG_COMMENT)
638          {
639             /* A null-terminated string is supposed to follow. */
640             while (*cur++ && (cur < csp->iob->eod));
641          }
642
643          /* Skip the CRC if necessary. */
644          if (flags & GZIP_FLAG_CHECKSUM)
645          {
646             cur += 2;
647          }
648
649          if (cur >= csp->iob->eod)
650          {
651             /*
652              * If the current position pointer reached or passed
653              * the buffer end, we were obviously tricked to skip
654              * too much.
655              */
656             log_error(LOG_LEVEL_ERROR,
657                "Malformed gzip header detected. Aborting decompression.");
658             return JB_ERR_COMPRESS;
659          }
660       }
661    }
662    else if (csp->content_type & CT_DEFLATE)
663    {
664       /*
665        * In theory (that is, according to RFC 1950), deflate-compressed
666        * data should begin with a two-byte zlib header and have an
667        * adler32 checksum at the end. It seems that in practice only
668        * the raw compressed data is sent. Note that this means that
669        * we are not RFC 1950-compliant here, but the advantage is that
670        * this actually works. :)
671        *
672        * We add a dummy null byte to tell zlib where the data ends,
673        * and later inform it not to expect a header.
674        *
675        * Fortunately, add_to_iob() has thoughtfully null-terminated
676        * the buffer; we can just increment the end pointer to include
677        * the dummy byte.
678        */
679       csp->iob->eod++;
680    }
681    else
682    {
683       log_error(LOG_LEVEL_ERROR,
684          "Unable to determine compression format for decompression");
685       return JB_ERR_COMPRESS;
686    }
687
688    /* Set up the fields required by zlib. */
689    zstr.next_in  = (Bytef *)cur;
690    zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
691    zstr.zalloc   = Z_NULL;
692    zstr.zfree    = Z_NULL;
693    zstr.opaque   = Z_NULL;
694
695    /*
696     * Passing -MAX_WBITS to inflateInit2 tells the library
697     * that there is no zlib header.
698     */
699    if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
700    {
701       log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
702       return JB_ERR_COMPRESS;
703    }
704
705    /*
706     * Next, we allocate new storage for the inflated data.
707     * We don't modify the existing iob yet, so in case there
708     * is error in decompression we can recover gracefully.
709     */
710    buf = zalloc(bufsize);
711    if (NULL == buf)
712    {
713       log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
714       return JB_ERR_MEMORY;
715    }
716
717    assert(bufsize >= skip_size);
718    memcpy(buf, csp->iob->buf, skip_size);
719    zstr.avail_out = (uInt)(bufsize - skip_size);
720    zstr.next_out  = (Bytef *)buf + skip_size;
721
722    /* Try to decompress the whole stream in one shot. */
723    while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
724    {
725       /* We need to allocate more memory for the output buffer. */
726
727       char *tmpbuf;                /* used for realloc'ing the buffer */
728       size_t oldbufsize = bufsize; /* keep track of the old bufsize */
729
730       if (0 == zstr.avail_in)
731       {
732          /*
733           * If zlib wants more data then there's a problem, because
734           * the complete compressed file should have been buffered.
735           */
736          log_error(LOG_LEVEL_ERROR,
737             "Unexpected end of compressed iob. Using what we got so far.");
738          break;
739       }
740
741       /*
742        * If we reached the buffer limit and still didn't have enough
743        * memory, just give up. Due to the ceiling enforced by the next
744        * if block we could actually check for equality here, but as it
745        * can be easily mistaken for a bug we don't.
746        */
747       if (bufsize >= csp->config->buffer_limit)
748       {
749          log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
750          freez(buf);
751          inflateEnd(&zstr);
752          return JB_ERR_MEMORY;
753       }
754
755       /* Try doubling the buffer size each time. */
756       bufsize *= 2;
757
758       /* Don't exceed the buffer limit. */
759       if (bufsize > csp->config->buffer_limit)
760       {
761          bufsize = csp->config->buffer_limit;
762       }
763
764       /* Try to allocate the new buffer. */
765       tmpbuf = realloc(buf, bufsize);
766       if (NULL == tmpbuf)
767       {
768          log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
769          freez(buf);
770          inflateEnd(&zstr);
771          return JB_ERR_MEMORY;
772       }
773       else
774       {
775          char *oldnext_out = (char *)zstr.next_out;
776
777          /*
778           * Update the fields for inflate() to use the new
779           * buffer, which may be in a location different from
780           * the old one.
781           */
782          zstr.avail_out += (uInt)(bufsize - oldbufsize);
783          zstr.next_out   = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
784
785          /*
786           * Compare with an uglier method of calculating these values
787           * that doesn't require the extra oldbufsize variable.
788           */
789          assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
790          assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
791
792          buf = tmpbuf;
793       }
794    }
795
796    if (Z_STREAM_ERROR == inflateEnd(&zstr))
797    {
798       log_error(LOG_LEVEL_ERROR,
799          "Inconsistent stream state after decompression: %s", zstr.msg);
800       /*
801        * XXX: Intentionally no return.
802        *
803        * According to zlib.h, Z_STREAM_ERROR is returned
804        * "if the stream state was inconsistent".
805        *
806        * I assume in this case inflate()'s status
807        * would also be something different than Z_STREAM_END
808        * so this check should be redundant, but lets see.
809        */
810    }
811
812    if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
813    {
814       /*
815        * We failed to decompress the stream and it's
816        * not simply because of missing data.
817        */
818       log_error(LOG_LEVEL_ERROR,
819          "Unexpected error while decompressing to the buffer (iob): %s",
820          zstr.msg);
821       return JB_ERR_COMPRESS;
822    }
823
824    /*
825     * Finally, we can actually update the iob, since the
826     * decompression was successful. First, free the old
827     * buffer.
828     */
829    freez(csp->iob->buf);
830
831    /* Now, update the iob to use the new buffer. */
832    csp->iob->buf  = buf;
833    csp->iob->cur  = csp->iob->buf + skip_size;
834    csp->iob->eod  = (char *)zstr.next_out;
835    csp->iob->size = bufsize;
836
837    /*
838     * Make sure the new uncompressed iob obeys some minimal
839     * consistency conditions.
840     */
841    if ((csp->iob->buf <= csp->iob->cur)
842     && (csp->iob->cur <= csp->iob->eod)
843     && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
844    {
845       const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
846       if (new_size > (size_t)0)
847       {
848          log_error(LOG_LEVEL_RE_FILTER,
849             "Decompression successful. Old size: %lu, new size: %lu.",
850             old_size, new_size);
851       }
852       else
853       {
854          /* zlib thinks this is OK, so let's do the same. */
855          log_error(LOG_LEVEL_RE_FILTER,
856             "Decompression didn't result in any content.");
857       }
858    }
859    else
860    {
861       /* It seems that zlib did something weird. */
862       log_error(LOG_LEVEL_ERROR, "Inconsistent buffer after decompression");
863       return JB_ERR_COMPRESS;
864    }
865
866    return JB_ERR_OK;
867
868 }
869 #endif /* defined(FEATURE_ZLIB) */
870
871
872 /*********************************************************************
873  *
874  * Function    :  normalize_lws
875  *
876  * Description :  Reduces unquoted linear whitespace in headers to
877  *                a single space in accordance with RFC 7230 3.2.4.
878  *                This simplifies parsing and filtering later on.
879  *
880  * Parameters  :
881  *          1  :  header = A header with linear whitespace to reduce.
882  *
883  * Returns     :  N/A
884  *
885  *********************************************************************/
886 static void normalize_lws(char *header)
887 {
888    char *p = header;
889
890    while (*p != '\0')
891    {
892       if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
893       {
894          char *q = p+1;
895
896          while (privoxy_isspace(*q))
897          {
898             q++;
899          }
900          log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
901          string_move(p+1, q);
902       }
903
904       if (*p == '\t')
905       {
906          log_error(LOG_LEVEL_HEADER,
907             "Converting tab to space in '%s'", header);
908          *p = ' ';
909       }
910       else if (*p == '"')
911       {
912          char *end_of_token = strstr(p+1, "\"");
913
914          if (NULL != end_of_token)
915          {
916             /* Don't mess with quoted text. */
917             p = end_of_token;
918          }
919          else
920          {
921             log_error(LOG_LEVEL_HEADER,
922                "Ignoring single quote in '%s'", header);
923          }
924       }
925       p++;
926    }
927
928    p = strchr(header, ':');
929    if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
930    {
931       /*
932        * There's still space before the colon.
933        * We don't want it.
934        */
935       string_move(p-1, p);
936    }
937 }
938
939
940 /*********************************************************************
941  *
942  * Function    :  get_header
943  *
944  * Description :  This (odd) routine will parse the csp->iob
945  *                to get the next complete header.
946  *
947  * Parameters  :
948  *          1  :  iob = The I/O buffer to parse, usually csp->iob.
949  *
950  * Returns     :  Any one of the following:
951  *
952  * 1) a pointer to a dynamically allocated string that contains a header line
953  * 2) NULL  indicating that the end of the header was reached
954  * 3) ""    indicating that the end of the iob was reached before finding
955  *          a complete header line.
956  *
957  *********************************************************************/
958 char *get_header(struct iob *iob)
959 {
960    char *header;
961
962    header = get_header_line(iob);
963
964    if ((header == NULL) || (*header == '\0'))
965    {
966       /*
967        * No complete header read yet, tell the client.
968        */
969       return header;
970    }
971
972    while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
973    {
974       /*
975        * Header spans multiple lines, append the next one.
976        */
977       char *continued_header;
978
979       continued_header = get_header_line(iob);
980       if ((continued_header == NULL) || (*continued_header == '\0'))
981       {
982          /*
983           * No complete header read yet, return what we got.
984           * XXX: Should "unread" header instead.
985           */
986          log_error(LOG_LEVEL_INFO,
987             "Failed to read a multi-line header properly: '%s'",
988             header);
989          break;
990       }
991
992       if (JB_ERR_OK != string_join(&header, continued_header))
993       {
994          log_error(LOG_LEVEL_FATAL,
995             "Out of memory while appending multiple headers.");
996       }
997       else
998       {
999          /* XXX: remove before next stable release. */
1000          log_error(LOG_LEVEL_HEADER,
1001             "Merged multiple header lines to: '%s'",
1002             header);
1003       }
1004    }
1005
1006    normalize_lws(header);
1007
1008    return header;
1009
1010 }
1011
1012
1013 /*********************************************************************
1014  *
1015  * Function    :  get_header_line
1016  *
1017  * Description :  This (odd) routine will parse the csp->iob
1018  *                to get the next header line.
1019  *
1020  * Parameters  :
1021  *          1  :  iob = The I/O buffer to parse, usually csp->iob.
1022  *
1023  * Returns     :  Any one of the following:
1024  *
1025  * 1) a pointer to a dynamically allocated string that contains a header line
1026  * 2) NULL  indicating that the end of the header was reached
1027  * 3) ""    indicating that the end of the iob was reached before finding
1028  *          a complete header line.
1029  *
1030  *********************************************************************/
1031 static char *get_header_line(struct iob *iob)
1032 {
1033    char *p, *q, *ret;
1034
1035    if ((iob->cur == NULL)
1036       || ((p = strchr(iob->cur, '\n')) == NULL))
1037    {
1038       return(""); /* couldn't find a complete header */
1039    }
1040
1041    *p = '\0';
1042
1043    ret = strdup(iob->cur);
1044    if (ret == NULL)
1045    {
1046       /* FIXME No way to handle error properly */
1047       log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1048    }
1049    assert(ret != NULL);
1050
1051    iob->cur = p+1;
1052
1053    if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1054
1055    /* is this a blank line (i.e. the end of the header) ? */
1056    if (*ret == '\0')
1057    {
1058       freez(ret);
1059       return NULL;
1060    }
1061
1062    return ret;
1063
1064 }
1065
1066
1067 /*********************************************************************
1068  *
1069  * Function    :  get_header_value
1070  *
1071  * Description :  Get the value of a given header from a chained list
1072  *                of header lines or return NULL if no such header is
1073  *                present in the list.
1074  *
1075  * Parameters  :
1076  *          1  :  header_list = pointer to list
1077  *          2  :  header_name = string with name of header to look for.
1078  *                              Trailing colon required, capitalization
1079  *                              doesn't matter.
1080  *
1081  * Returns     :  NULL if not found, else value of header
1082  *
1083  *********************************************************************/
1084 char *get_header_value(const struct list *header_list, const char *header_name)
1085 {
1086    struct list_entry *cur_entry;
1087    char *ret = NULL;
1088    size_t length = 0;
1089
1090    assert(header_list);
1091    assert(header_name);
1092    length = strlen(header_name);
1093
1094    for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1095    {
1096       if (cur_entry->str)
1097       {
1098          if (!strncmpic(cur_entry->str, header_name, length))
1099          {
1100             /*
1101              * Found: return pointer to start of value
1102              */
1103             ret = cur_entry->str + length;
1104             while (*ret && privoxy_isspace(*ret)) ret++;
1105             return ret;
1106          }
1107       }
1108    }
1109
1110    /*
1111     * Not found
1112     */
1113    return NULL;
1114
1115 }
1116
1117
1118 /*********************************************************************
1119  *
1120  * Function    :  scan_headers
1121  *
1122  * Description :  Scans headers, applies tags and updates action bits.
1123  *
1124  * Parameters  :
1125  *          1  :  csp = Current client state (buffers, headers, etc...)
1126  *
1127  * Returns     :  JB_ERR_OK
1128  *
1129  *********************************************************************/
1130 static jb_err scan_headers(struct client_state *csp)
1131 {
1132    struct list_entry *h; /* Header */
1133    jb_err err = JB_ERR_OK;
1134
1135    for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1136    {
1137       /* Header crunch()ed in previous run? -> ignore */
1138       if (h->str == NULL) continue;
1139       log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1140       err = header_tagger(csp, h->str);
1141    }
1142
1143    return err;
1144 }
1145
1146
1147 /*********************************************************************
1148  *
1149  * Function    :  enforce_header_order
1150  *
1151  * Description :  Enforces a given header order.
1152  *
1153  * Parameters  :
1154  *          1  :  headers         = List of headers to order.
1155  *          2  :  ordered_headers = List of ordered header names.
1156  *
1157  * Returns     :  N/A
1158  *
1159  *********************************************************************/
1160 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1161 {
1162    struct list_entry *sorted_header;
1163    struct list new_headers[1];
1164    struct list_entry *header;
1165
1166    init_list(new_headers);
1167
1168    /* The request line is always the first "header" */
1169
1170    assert(NULL != headers->first->str);
1171    enlist(new_headers, headers->first->str);
1172    freez(headers->first->str)
1173
1174    /* Enlist the specified headers in the given order */
1175
1176    for (sorted_header = ordered_headers->first; sorted_header != NULL;
1177         sorted_header = sorted_header->next)
1178    {
1179       const size_t sorted_header_length = strlen(sorted_header->str);
1180       for (header = headers->first; header != NULL; header = header->next)
1181       {
1182          /* Header enlisted in previous run? -> ignore */
1183          if (header->str == NULL) continue;
1184
1185          if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1186             && (header->str[sorted_header_length] == ':'))
1187          {
1188             log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1189             if (JB_ERR_OK != enlist(new_headers, header->str))
1190             {
1191                log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1192             }
1193             freez(header->str);
1194          }
1195       }
1196    }
1197
1198    /* Enlist the rest of the headers behind the ordered ones */
1199    for (header = headers->first; header != NULL; header = header->next)
1200    {
1201       /* Header enlisted in previous run? -> ignore */
1202       if (header->str == NULL) continue;
1203
1204       log_error(LOG_LEVEL_HEADER,
1205          "Enlisting left-over header %s", header->str);
1206       if (JB_ERR_OK != enlist(new_headers, header->str))
1207       {
1208          log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1209       }
1210       freez(header->str);
1211    }
1212
1213    list_remove_all(headers);
1214    list_duplicate(headers, new_headers);
1215    list_remove_all(new_headers);
1216
1217    return;
1218 }
1219
1220
1221 /*********************************************************************
1222  *
1223  * Function    :  sed
1224  *
1225  * Description :  add, delete or modify lines in the HTTP header streams.
1226  *                On entry, it receives a linked list of headers space
1227  *                that was allocated dynamically (both the list nodes
1228  *                and the header contents).
1229  *
1230  *                As a side effect it frees the space used by the original
1231  *                header lines.
1232  *
1233  * Parameters  :
1234  *          1  :  csp = Current client state (buffers, headers, etc...)
1235  *          2  :  filter_server_headers = Boolean to switch between
1236  *                                        server and header filtering.
1237  *
1238  * Returns     :  JB_ERR_OK in case off success, or
1239  *                JB_ERR_MEMORY on some out-of-memory errors, or
1240  *                JB_ERR_PARSE in case of fatal parse errors.
1241  *
1242  *********************************************************************/
1243 jb_err sed(struct client_state *csp, int filter_server_headers)
1244 {
1245    /* XXX: use more descriptive names. */
1246    struct list_entry *p;
1247    const struct parsers *v;
1248    const add_header_func_ptr *f;
1249    jb_err err = JB_ERR_OK;
1250
1251    scan_headers(csp);
1252
1253    if (filter_server_headers)
1254    {
1255       v = server_patterns;
1256       f = add_server_headers;
1257       check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1258    }
1259    else
1260    {
1261       v = client_patterns;
1262       f = add_client_headers;
1263       check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1264    }
1265
1266    while (v->str != NULL)
1267    {
1268       for (p = csp->headers->first; p != NULL; p = p->next)
1269       {
1270          /* Header crunch()ed in previous run? -> ignore */
1271          if (p->str == NULL) continue;
1272
1273          /* Does the current parser handle this header? */
1274          if ((strncmpic(p->str, v->str, v->len) == 0) ||
1275              (v->len == CHECK_EVERY_HEADER_REMAINING))
1276          {
1277             err = v->parser(csp, &(p->str));
1278             if (err != JB_ERR_OK)
1279             {
1280                return err;
1281             }
1282          }
1283       }
1284       v++;
1285    }
1286
1287    /* place additional headers on the csp->headers list */
1288    while ((err == JB_ERR_OK) && (*f))
1289    {
1290       err = (*f)(csp);
1291       f++;
1292    }
1293
1294    if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1295    {
1296       enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1297    }
1298
1299    return err;
1300 }
1301
1302
1303 #ifdef FEATURE_HTTPS_INSPECTION
1304 /*********************************************************************
1305  *
1306  * Function    :  sed_https
1307  *
1308  * Description :  add, delete or modify lines in the HTTPS client
1309  *                header streams. Wrapper around sed().
1310  *
1311  * Parameters  :
1312  *          1  :  csp = Current client state (buffers, headers, etc...)
1313  *
1314  * Returns     :  JB_ERR_OK in case off success, or
1315  *                JB_ERR_MEMORY on some out-of-memory errors, or
1316  *                JB_ERR_PARSE in case of fatal parse errors.
1317  *
1318  *********************************************************************/
1319 jb_err sed_https(struct client_state *csp)
1320 {
1321    jb_err err;
1322    struct list headers;
1323
1324    /*
1325     * Temporarily replace csp->headers with csp->https_headers
1326     * to trick sed() into filtering the https headers.
1327     */
1328    headers.first = csp->headers->first;
1329    headers.last  = csp->headers->last;
1330    csp->headers->first = csp->https_headers->first;
1331    csp->headers->last  = csp->https_headers->last;
1332
1333    /*
1334     * Start with fresh tags. Already existing tags may
1335     * be set again. This is necessary to overrule
1336     * URL-based patterns.
1337     */
1338    destroy_list(csp->tags);
1339
1340    /*
1341     * We want client header filters and taggers
1342     * so temporarily remove the flag.
1343     */
1344    csp->flags &= ~CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1345    err = sed(csp, FILTER_CLIENT_HEADERS);
1346    csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1347
1348    /*
1349     * Update the https headers list which may have
1350     * been modified due to header additions or header
1351     * reordering.
1352     */
1353    csp->https_headers->first = csp->headers->first;
1354    csp->https_headers->last = csp->headers->last;
1355
1356    csp->headers->first = headers.first;
1357    csp->headers->last  = headers.last;
1358
1359    return err;
1360 }
1361 #endif /* def FEATURE_HTTPS_INSPECTION */
1362
1363
1364 /*********************************************************************
1365  *
1366  * Function    :  update_server_headers
1367  *
1368  * Description :  Updates server headers after the body has been modified.
1369  *
1370  * Parameters  :
1371  *          1  :  csp = Current client state (buffers, headers, etc...)
1372  *
1373  * Returns     :  JB_ERR_OK in case off success, or
1374  *                JB_ERR_MEMORY on out-of-memory error.
1375  *
1376  *********************************************************************/
1377 jb_err update_server_headers(struct client_state *csp)
1378 {
1379    jb_err err = JB_ERR_OK;
1380
1381    static const struct parsers server_patterns_light[] = {
1382       { "Content-Length:",    15, server_adjust_content_length },
1383       { "Transfer-Encoding:", 18, server_transfer_coding },
1384 #ifdef FEATURE_ZLIB
1385       { "Content-Encoding:",  17, server_adjust_content_encoding },
1386 #endif /* def FEATURE_ZLIB */
1387       { NULL,                  0, NULL }
1388    };
1389
1390    if (strncmpic(csp->http->cmd, "HEAD", 4))
1391    {
1392       const struct parsers *v;
1393       struct list_entry *p;
1394
1395       for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1396       {
1397          for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1398          {
1399             /* Header crunch()ed in previous run? -> ignore */
1400             if (p->str == NULL) continue;
1401
1402             /* Does the current parser handle this header? */
1403             if (strncmpic(p->str, v->str, v->len) == 0)
1404             {
1405                err = v->parser(csp, (char **)&(p->str));
1406             }
1407          }
1408       }
1409    }
1410
1411 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1412    if ((JB_ERR_OK == err)
1413     && (csp->flags & CSP_FLAG_MODIFIED)
1414     && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1415     && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1416    {
1417       char header[50];
1418
1419       create_content_length_header(csp->content_length, header, sizeof(header));
1420       err = enlist(csp->headers, header);
1421       if (JB_ERR_OK == err)
1422       {
1423          log_error(LOG_LEVEL_HEADER,
1424             "Content modified with no Content-Length header set. "
1425             "Created: %s.", header);
1426          csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1427       }
1428    }
1429 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1430
1431 #ifdef FEATURE_COMPRESSION
1432    if ((JB_ERR_OK == err)
1433       && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1434    {
1435       err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1436       if (JB_ERR_OK == err)
1437       {
1438          log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1439       }
1440    }
1441 #endif
1442
1443    return err;
1444 }
1445
1446
1447 /*********************************************************************
1448  *
1449  * Function    :  header_tagger
1450  *
1451  * Description :  Executes all text substitutions from applying
1452  *                tag actions and saves the result as tag.
1453  *
1454  *                XXX: Shares enough code with filter_header() and
1455  *                pcrs_filter_response() to warrant some helper functions.
1456  *
1457  * Parameters  :
1458  *          1  :  csp = Current client state (buffers, headers, etc...)
1459  *          2  :  header = Header that is used as tagger input
1460  *
1461  * Returns     :  JB_ERR_OK on success and always succeeds
1462  *
1463  *********************************************************************/
1464 static jb_err header_tagger(struct client_state *csp, char *header)
1465 {
1466    enum filter_type wanted_filter_type;
1467    int multi_action_index;
1468    pcrs_job *job;
1469
1470    struct re_filterfile_spec *b;
1471    struct list_entry *tag_name;
1472
1473    const size_t header_length = strlen(header);
1474
1475    if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1476    {
1477       wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1478       multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1479    }
1480    else
1481    {
1482       wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1483       multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1484    }
1485
1486    if (list_is_empty(csp->action->multi[multi_action_index])
1487       || filters_available(csp) == FALSE)
1488    {
1489       /* Return early if no taggers apply or if none are available. */
1490       return JB_ERR_OK;
1491    }
1492
1493    /* Execute all applying taggers */
1494    for (tag_name = csp->action->multi[multi_action_index]->first;
1495         NULL != tag_name; tag_name = tag_name->next)
1496    {
1497       char *modified_tag = NULL;
1498       char *tag = header;
1499       size_t size = header_length;
1500       pcrs_job *joblist;
1501
1502       b = get_filter(csp, tag_name->str, wanted_filter_type);
1503       if (b == NULL)
1504       {
1505          continue;
1506       }
1507
1508       joblist = b->joblist;
1509
1510       if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1511
1512       if (NULL == joblist)
1513       {
1514          log_error(LOG_LEVEL_TAGGING,
1515             "Tagger %s has empty joblist. Nothing to do.", b->name);
1516          continue;
1517       }
1518
1519       /* execute their pcrs_joblist on the header. */
1520       for (job = joblist; NULL != job; job = job->next)
1521       {
1522          const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1523
1524          if (0 < hits)
1525          {
1526             /* Success, continue with the modified version. */
1527             if (tag != header)
1528             {
1529                freez(tag);
1530             }
1531             tag = modified_tag;
1532          }
1533          else
1534          {
1535             /* Tagger doesn't match */
1536             if (0 > hits)
1537             {
1538                /* Regex failure, log it but continue anyway. */
1539                assert(NULL != header);
1540                log_error(LOG_LEVEL_ERROR,
1541                   "Problems with tagger \'%s\' and header \'%s\': %s",
1542                   b->name, header, pcrs_strerror(hits));
1543             }
1544             freez(modified_tag);
1545          }
1546       }
1547
1548       if (b->dynamic) pcrs_free_joblist(joblist);
1549
1550       /* If this tagger matched */
1551       if (tag != header)
1552       {
1553          if (0 == size)
1554          {
1555             /*
1556              * There is no technical limitation which makes
1557              * it impossible to use empty tags, but I assume
1558              * no one would do it intentionally.
1559              */
1560             freez(tag);
1561             log_error(LOG_LEVEL_TAGGING,
1562                "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1563             continue;
1564          }
1565
1566          if (list_contains_item(csp->action->multi[ACTION_MULTI_SUPPRESS_TAG], tag))
1567          {
1568             log_error(LOG_LEVEL_TAGGING,
1569                "Tagger \'%s\' didn't add tag \'%s\': suppressed",
1570                b->name, tag);
1571             freez(tag);
1572             continue;
1573          }
1574
1575          if (!list_contains_item(csp->tags, tag))
1576          {
1577             if (JB_ERR_OK != enlist(csp->tags, tag))
1578             {
1579                log_error(LOG_LEVEL_ERROR,
1580                   "Insufficient memory to add tag \'%s\', "
1581                   "based on tagger \'%s\' and header \'%s\'",
1582                   tag, b->name, header);
1583             }
1584             else
1585             {
1586                char *action_message;
1587                /*
1588                 * update the action bits right away, to make
1589                 * tagging based on tags set by earlier taggers
1590                 * of the same kind possible.
1591                 */
1592                if (update_action_bits_for_tag(csp, tag))
1593                {
1594                   action_message = "Action bits updated accordingly.";
1595                }
1596                else
1597                {
1598                   action_message = "No action bits update necessary.";
1599                }
1600
1601                log_error(LOG_LEVEL_TAGGING,
1602                   "Tagger \'%s\' added tag \'%s\'. %s",
1603                   b->name, tag, action_message);
1604             }
1605          }
1606          else
1607          {
1608             /* XXX: Is this log-worthy? */
1609             log_error(LOG_LEVEL_TAGGING,
1610                "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1611                b->name, tag);
1612          }
1613          freez(tag);
1614       }
1615    }
1616
1617    return JB_ERR_OK;
1618 }
1619
1620 /* here begins the family of parser functions that reformat header lines */
1621
1622 /*********************************************************************
1623  *
1624  * Function    :  filter_header
1625  *
1626  * Description :  Executes all text substitutions from all applying
1627  *                +(server|client)-header-filter actions on the header.
1628  *                Most of the code was copied from pcrs_filter_response,
1629  *                including the rather short variable names
1630  *
1631  * Parameters  :
1632  *          1  :  csp = Current client state (buffers, headers, etc...)
1633  *          2  :  header = On input, pointer to header to modify.
1634  *                On output, pointer to the modified header, or NULL
1635  *                to remove the header.  This function frees the
1636  *                original string if necessary.
1637  *
1638  * Returns     :  JB_ERR_OK on success and always succeeds
1639  *
1640  *********************************************************************/
1641 static jb_err filter_header(struct client_state *csp, char **header)
1642 {
1643    int hits=0;
1644    int matches;
1645    size_t size = strlen(*header);
1646
1647    char *newheader = NULL;
1648    pcrs_job *job;
1649
1650    struct re_filterfile_spec *b;
1651    struct list_entry *filtername;
1652
1653    enum filter_type wanted_filter_type;
1654    int multi_action_index;
1655
1656    if (csp->flags & CSP_FLAG_NO_FILTERING)
1657    {
1658       return JB_ERR_OK;
1659    }
1660
1661    if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1662    {
1663       wanted_filter_type = FT_SERVER_HEADER_FILTER;
1664       multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1665    }
1666    else
1667    {
1668       wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1669       multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1670    }
1671
1672    if (list_is_empty(csp->action->multi[multi_action_index])
1673       || filters_available(csp) == FALSE)
1674    {
1675       /* Return early if no filters apply or if none are available. */
1676       return JB_ERR_OK;
1677    }
1678
1679    /* Execute all applying header filters */
1680    for (filtername = csp->action->multi[multi_action_index]->first;
1681         filtername != NULL; filtername = filtername->next)
1682    {
1683       int current_hits = 0;
1684       pcrs_job *joblist;
1685
1686       b = get_filter(csp, filtername->str, wanted_filter_type);
1687       if (b == NULL)
1688       {
1689          continue;
1690       }
1691
1692       joblist = b->joblist;
1693
1694       if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1695
1696       if (NULL == joblist)
1697       {
1698          log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1699          continue;
1700       }
1701
1702       log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %lu) with \'%s\' ...",
1703          *header, size, b->name);
1704
1705       /* Apply all jobs from the joblist */
1706       for (job = joblist; NULL != job; job = job->next)
1707       {
1708          matches = pcrs_execute(job, *header, size, &newheader, &size);
1709          if (0 < matches)
1710          {
1711             current_hits += matches;
1712             log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1713             freez(*header);
1714             *header = newheader;
1715          }
1716          else if (0 == matches)
1717          {
1718             /* Filter doesn't change header */
1719             freez(newheader);
1720          }
1721          else
1722          {
1723             /* RegEx failure */
1724             log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1725                *header, b->name, pcrs_strerror(matches));
1726             if (newheader != NULL)
1727             {
1728                log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1729                freez(newheader);
1730             }
1731          }
1732       }
1733
1734       if (b->dynamic) pcrs_free_joblist(joblist);
1735
1736       log_error(LOG_LEVEL_RE_FILTER,
1737          "... produced %d hits (new size %lu).", current_hits, size);
1738       hits += current_hits;
1739    }
1740
1741    /*
1742     * Additionally checking for hits is important because if
1743     * the continue hack is triggered, server headers can
1744     * arrive empty to separate multiple heads from each other.
1745     */
1746    if ((0 == size) && hits)
1747    {
1748       log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1749       freez(*header);
1750    }
1751
1752    return JB_ERR_OK;
1753 }
1754
1755
1756 /*********************************************************************
1757  *
1758  * Function    :  server_connection
1759  *
1760  * Description :  Makes sure a proper "Connection:" header is
1761  *                set and signals connection_header_adder to
1762  *                do nothing.
1763  *
1764  * Parameters  :
1765  *          1  :  csp = Current client state (buffers, headers, etc...)
1766  *          2  :  header = On input, pointer to header to modify.
1767  *                On output, pointer to the modified header, or NULL
1768  *                to remove the header.  This function frees the
1769  *                original string if necessary.
1770  *
1771  * Returns     :  JB_ERR_OK on success.
1772  *
1773  *********************************************************************/
1774 static jb_err server_connection(struct client_state *csp, char **header)
1775 {
1776    if (!strcmpic(*header, "Connection: keep-alive")
1777 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1778     && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1779 #endif
1780      )
1781    {
1782 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1783       if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1784       {
1785          csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1786       }
1787
1788       if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1789       {
1790          log_error(LOG_LEVEL_HEADER,
1791             "Keeping the server header '%s' around.", *header);
1792       }
1793       else
1794 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1795       {
1796          char *old_header = *header;
1797
1798          *header = strdup_or_die("Connection: close");
1799          log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1800          freez(old_header);
1801       }
1802    }
1803
1804    /* Signal server_connection_adder() to return early. */
1805    csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1806
1807    return JB_ERR_OK;
1808 }
1809
1810
1811 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1812 /*********************************************************************
1813  *
1814  * Function    :  server_keep_alive
1815  *
1816  * Description :  Stores the server's keep alive timeout.
1817  *
1818  * Parameters  :
1819  *          1  :  csp = Current client state (buffers, headers, etc...)
1820  *          2  :  header = On input, pointer to header to modify.
1821  *                On output, pointer to the modified header, or NULL
1822  *                to remove the header.  This function frees the
1823  *                original string if necessary.
1824  *
1825  * Returns     :  JB_ERR_OK.
1826  *
1827  *********************************************************************/
1828 static jb_err server_keep_alive(struct client_state *csp, char **header)
1829 {
1830    unsigned int keep_alive_timeout;
1831    const char *timeout_position = strstr(*header, "timeout=");
1832
1833    if ((NULL == timeout_position)
1834     || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1835    {
1836       log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1837    }
1838    else
1839    {
1840       if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1841       {
1842          log_error(LOG_LEVEL_HEADER,
1843             "Reducing keep-alive timeout from %u to %u.",
1844             csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1845          csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1846       }
1847       else
1848       {
1849          /* XXX: Is this log worthy? */
1850          log_error(LOG_LEVEL_HEADER,
1851             "Server keep-alive timeout is %u. Sticking with %u.",
1852             keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1853       }
1854       csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1855    }
1856
1857    freez(*header);
1858
1859    return JB_ERR_OK;
1860 }
1861
1862
1863 /*********************************************************************
1864  *
1865  * Function    :  server_proxy_connection
1866  *
1867  * Description :  Figures out whether or not we should add a
1868  *                Proxy-Connection header.
1869  *
1870  * Parameters  :
1871  *          1  :  csp = Current client state (buffers, headers, etc...)
1872  *          2  :  header = On input, pointer to header to modify.
1873  *                On output, pointer to the modified header, or NULL
1874  *                to remove the header.  This function frees the
1875  *                original string if necessary.
1876  *
1877  * Returns     :  JB_ERR_OK.
1878  *
1879  *********************************************************************/
1880 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1881 {
1882    csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1883    return JB_ERR_OK;
1884 }
1885 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1886
1887
1888 /*********************************************************************
1889  *
1890  * Function    :  proxy_authentication
1891  *
1892  * Description :  Removes headers that are relevant for proxy
1893  *                authentication unless forwarding them has
1894  *                been explicitly requested.
1895  *
1896  * Parameters  :
1897  *          1  :  csp = Current client state (buffers, headers, etc...)
1898  *          2  :  header = On input, pointer to header to modify.
1899  *                On output, pointer to the modified header, or NULL
1900  *                to remove the header.  This function frees the
1901  *                original string if necessary.
1902  *
1903  * Returns     :  JB_ERR_OK.
1904  *
1905  *********************************************************************/
1906 static jb_err proxy_authentication(struct client_state *csp, char **header)
1907 {
1908    if ((csp->config->feature_flags &
1909       RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1910       log_error(LOG_LEVEL_HEADER,
1911          "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1912       freez(*header);
1913    }
1914    return JB_ERR_OK;
1915 }
1916
1917
1918 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1919 /*********************************************************************
1920  *
1921  * Function    :  client_keep_alive
1922  *
1923  * Description :  Stores the client's keep alive timeout.
1924  *
1925  * Parameters  :
1926  *          1  :  csp = Current client state (buffers, headers, etc...)
1927  *          2  :  header = On input, pointer to header to modify.
1928  *                On output, pointer to the modified header, or NULL
1929  *                to remove the header.  This function frees the
1930  *                original string if necessary.
1931  *
1932  * Returns     :  JB_ERR_OK.
1933  *
1934  *********************************************************************/
1935 static jb_err client_keep_alive(struct client_state *csp, char **header)
1936 {
1937    unsigned int keep_alive_timeout;
1938    char *timeout_position;
1939
1940    if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1941    {
1942       log_error(LOG_LEVEL_HEADER,
1943          "keep-alive support is disabled. Crunching: %s.", *header);
1944       freez(*header);
1945       return JB_ERR_OK;
1946    }
1947
1948    /* Check for parameter-less format "Keep-Alive: 100" */
1949    timeout_position = strstr(*header, ": ");
1950    if ((NULL == timeout_position)
1951     || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1952    {
1953       /* Assume parameter format "Keep-Alive: timeout=100" */
1954       timeout_position = strstr(*header, "timeout=");
1955       if ((NULL == timeout_position)
1956          || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1957       {
1958          log_error(LOG_LEVEL_HEADER,
1959             "Couldn't parse: '%s'. Using default timeout %u",
1960             *header, csp->config->keep_alive_timeout);
1961          freez(*header);
1962
1963          return JB_ERR_OK;
1964       }
1965    }
1966
1967    if (keep_alive_timeout < csp->config->keep_alive_timeout)
1968    {
1969       log_error(LOG_LEVEL_HEADER,
1970          "Reducing keep-alive timeout from %u to %u.",
1971          csp->config->keep_alive_timeout, keep_alive_timeout);
1972       csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1973    }
1974    else
1975    {
1976       /* XXX: Is this log worthy? */
1977       log_error(LOG_LEVEL_HEADER,
1978          "Client keep-alive timeout is %u. Sticking with %u.",
1979          keep_alive_timeout, csp->config->keep_alive_timeout);
1980       freez(*header);
1981    }
1982
1983    return JB_ERR_OK;
1984 }
1985 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1986
1987
1988 /*********************************************************************
1989  *
1990  * Function    :  get_content_length
1991  *
1992  * Description :  Gets the content length specified in a
1993  *                Content-Length header.
1994  *
1995  * Parameters  :
1996  *          1  :  header_value = The Content-Length header value.
1997  *          2  :  length = Storage to return the value.
1998  *
1999  * Returns     :  JB_ERR_OK on success, or
2000  *                JB_ERR_PARSE if no value is recognized.
2001  *
2002  *********************************************************************/
2003 static jb_err get_content_length(const char *header_value, unsigned long long *length)
2004 {
2005 #ifdef _WIN32
2006 #if SIZEOF_LONG_LONG < 8
2007 #error sizeof(unsigned long long) too small
2008 #endif
2009    if (1 != sscanf(header_value, "%I64u", length))
2010 #else
2011    if (1 != sscanf(header_value, "%llu", length))
2012 #endif
2013    {
2014       return JB_ERR_PARSE;
2015    }
2016
2017    return JB_ERR_OK;
2018 }
2019
2020
2021 /*********************************************************************
2022  *
2023  * Function    :  client_save_content_length
2024  *
2025  * Description :  Save the Content-Length sent by the client.
2026  *
2027  * Parameters  :
2028  *          1  :  csp = Current client state (buffers, headers, etc...)
2029  *          2  :  header = pointer to the Content-Length header
2030  *
2031  * Returns     :  JB_ERR_OK on success, or
2032  *                JB_ERR_MEMORY on out-of-memory error.
2033  *
2034  *********************************************************************/
2035 static jb_err client_save_content_length(struct client_state *csp, char **header)
2036 {
2037    unsigned long long content_length = 0;
2038    const char *header_value;
2039
2040    assert(*(*header+14) == ':');
2041
2042    header_value = *header + 15;
2043    if (JB_ERR_OK != get_content_length(header_value, &content_length))
2044    {
2045       log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2046       freez(*header);
2047    }
2048    else
2049    {
2050       csp->expected_client_content_length = content_length;
2051    }
2052
2053    return JB_ERR_OK;
2054 }
2055
2056
2057 /*********************************************************************
2058  *
2059  * Function    :  client_connection
2060  *
2061  * Description :  Makes sure a proper "Connection:" header is
2062  *                set and signals connection_header_adder
2063  *                to do nothing.
2064  *
2065  * Parameters  :
2066  *          1  :  csp = Current client state (buffers, headers, etc...)
2067  *          2  :  header = On input, pointer to header to modify.
2068  *                On output, pointer to the modified header, or NULL
2069  *                to remove the header.  This function frees the
2070  *                original string if necessary.
2071  *
2072  * Returns     :  JB_ERR_OK on success.
2073  *
2074  *********************************************************************/
2075 static jb_err client_connection(struct client_state *csp, char **header)
2076 {
2077    static const char connection_close[] = "Connection: close";
2078
2079    if (!strcmpic(*header, connection_close))
2080    {
2081 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2082       if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2083          && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2084 #ifdef FEATURE_HTTPS_INSPECTION
2085          && !client_use_ssl(csp)
2086 #endif
2087           )
2088       {
2089           if (!strcmpic(csp->http->version, "HTTP/1.1"))
2090           {
2091              log_error(LOG_LEVEL_HEADER,
2092                 "Removing \'%s\' to imply keep-alive.", *header);
2093              freez(*header);
2094              /*
2095               * While we imply keep-alive to the server,
2096               * we have to remember that the client didn't.
2097               */
2098              csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2099           }
2100           else
2101           {
2102              char *old_header = *header;
2103
2104              *header = strdup_or_die("Connection: keep-alive");
2105              log_error(LOG_LEVEL_HEADER,
2106                 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2107              freez(old_header);
2108           }
2109       }
2110       else
2111       {
2112          log_error(LOG_LEVEL_HEADER,
2113             "Keeping the client header '%s' around. "
2114             "The connection will not be kept alive.",
2115             *header);
2116          csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2117       }
2118    }
2119    else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2120         && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2121    {
2122       log_error(LOG_LEVEL_HEADER,
2123          "Keeping the client header '%s' around. "
2124          "The server connection will be kept alive if possible.",
2125          *header);
2126       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2127 #endif  /* def FEATURE_CONNECTION_KEEP_ALIVE */
2128    }
2129    else
2130    {
2131       char *old_header = *header;
2132
2133       *header = strdup_or_die(connection_close);
2134       log_error(LOG_LEVEL_HEADER,
2135          "Replaced: \'%s\' with \'%s\'", old_header, *header);
2136       freez(old_header);
2137    }
2138
2139    /* Signal client_connection_header_adder() to return early. */
2140    csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2141
2142    return JB_ERR_OK;
2143 }
2144
2145
2146 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2147 /*********************************************************************
2148  *
2149  * Function    :  client_proxy_connection
2150  *
2151  * Description :  Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
2152  *                appropriate and removes the Proxy-Connection
2153  *                header.
2154  *
2155  * Parameters  :
2156  *          1  :  csp = Current client state (buffers, headers, etc...)
2157  *          2  :  header = On input, pointer to header to modify.
2158  *                On output, pointer to the modified header, or NULL
2159  *                to remove the header.  This function frees the
2160  *                original string if necessary.
2161  *
2162  * Returns     :  JB_ERR_OK
2163  *
2164  *********************************************************************/
2165 static jb_err client_proxy_connection(struct client_state *csp, char **header)
2166 {
2167    if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2168       && (csp->http->ssl == 0)
2169       && (NULL == strstr(*header, "close")))
2170    {
2171       log_error(LOG_LEVEL_HEADER,
2172          "The client connection can be kept alive due to: %s", *header);
2173       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2174    }
2175    crumble(csp, header);
2176
2177    return JB_ERR_OK;
2178 }
2179 #endif  /* def FEATURE_CONNECTION_KEEP_ALIVE */
2180
2181
2182 /*********************************************************************
2183  *
2184  * Function    :  client_transfer_encoding
2185  *
2186  * Description :  Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2187  *                the request body is "chunked"
2188  *
2189  *                XXX: Currently not called through sed() as we
2190  *                     need the flag earlier on. Should be fixed.
2191  *
2192  * Parameters  :
2193  *          1  :  csp = Current client state (buffers, headers, etc...)
2194  *          2  :  header = On input, pointer to header to modify.
2195  *                On output, pointer to the modified header, or NULL
2196  *                to remove the header.  This function frees the
2197  *                original string if necessary.
2198  *
2199  * Returns     :  JB_ERR_OK on success, or
2200  *
2201  *********************************************************************/
2202 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2203 {
2204    if (strstr(*header, "chunked"))
2205    {
2206       csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2207       log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2208    }
2209
2210    return JB_ERR_OK;
2211 }
2212
2213
2214 /*********************************************************************
2215  *
2216  * Function    :  client_expect
2217  *
2218  * Description :  Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2219  *                if the Expect header value is unsupported.
2220  *
2221  *                Rejecting unsupported expectations is a RFC 7231 5.1.1
2222  *                MAY and a RFC 2616 (obsolete) MUST.
2223  *
2224  * Parameters  :
2225  *          1  :  csp = Current client state (buffers, headers, etc...)
2226  *          2  :  header = On input, pointer to header to modify.
2227  *                On output, pointer to the modified header, or NULL
2228  *                to remove the header.  This function frees the
2229  *                original string if necessary.
2230  *
2231  * Returns     :  JB_ERR_OK on success, or
2232  *
2233  *********************************************************************/
2234 jb_err client_expect(struct client_state *csp, char **header)
2235 {
2236    if (0 != strcmpic(*header, "Expect: 100-continue"))
2237    {
2238       csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2239       log_error(LOG_LEVEL_HEADER,
2240          "Unsupported client expectaction: %s", *header);
2241    }
2242
2243    return JB_ERR_OK;
2244
2245 }
2246
2247
2248 /*********************************************************************
2249  *
2250  * Function    :  crumble
2251  *
2252  * Description :  This is called if a header matches a pattern to "crunch"
2253  *
2254  * Parameters  :
2255  *          1  :  csp = Current client state (buffers, headers, etc...)
2256  *          2  :  header = On input, pointer to header to modify.
2257  *                On output, pointer to the modified header, or NULL
2258  *                to remove the header.  This function frees the
2259  *                original string if necessary.
2260  *
2261  * Returns     :  JB_ERR_OK on success, or
2262  *                JB_ERR_MEMORY on out-of-memory error.
2263  *
2264  *********************************************************************/
2265 static jb_err crumble(struct client_state *csp, char **header)
2266 {
2267    (void)csp;
2268    log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2269    freez(*header);
2270    return JB_ERR_OK;
2271 }
2272
2273
2274 /*********************************************************************
2275  *
2276  * Function    :  crunch_server_header
2277  *
2278  * Description :  Crunch server header if it matches a string supplied by the
2279  *                user. Called from `sed'.
2280  *
2281  * Parameters  :
2282  *          1  :  csp = Current client state (buffers, headers, etc...)
2283  *          2  :  header = On input, pointer to header to modify.
2284  *                On output, pointer to the modified header, or NULL
2285  *                to remove the header.  This function frees the
2286  *                original string if necessary.
2287  *
2288  * Returns     :  JB_ERR_OK on success and always succeeds
2289  *
2290  *********************************************************************/
2291 static jb_err crunch_server_header(struct client_state *csp, char **header)
2292 {
2293    const char *crunch_pattern;
2294
2295    /* Do we feel like crunching? */
2296    if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2297    {
2298       crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2299
2300       /* Is the current header the lucky one? */
2301       if (strstr(*header, crunch_pattern))
2302       {
2303          log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2304          freez(*header);
2305       }
2306    }
2307
2308    return JB_ERR_OK;
2309 }
2310
2311
2312 /*********************************************************************
2313  *
2314  * Function    :  server_content_type
2315  *
2316  * Description :  Set the content-type for filterable types (text/.*,
2317  *                .*xml.*, .*script.* and image/gif) unless filtering has been
2318  *                forbidden (CT_TABOO) while parsing earlier headers.
2319  *                NOTE: Since text/plain is commonly used by web servers
2320  *                      for files whose correct type is unknown, we don't
2321  *                      set CT_TEXT for it.
2322  *
2323  * Parameters  :
2324  *          1  :  csp = Current client state (buffers, headers, etc...)
2325  *          2  :  header = On input, pointer to header to modify.
2326  *                On output, pointer to the modified header, or NULL
2327  *                to remove the header.  This function frees the
2328  *                original string if necessary.
2329  *
2330  * Returns     :  JB_ERR_OK on success, or
2331  *                JB_ERR_MEMORY on out-of-memory error.
2332  *
2333  *********************************************************************/
2334 static jb_err server_content_type(struct client_state *csp, char **header)
2335 {
2336    /* Remove header if it isn't the first Content-Type header */
2337    if ((csp->content_type & CT_DECLARED))
2338    {
2339       if (content_filters_enabled(csp->action))
2340       {
2341          /*
2342           * Making sure the client interprets the content the same way
2343           * Privoxy did is only relevant if Privoxy modified it.
2344           *
2345           * Checking for this is "hard" as it's not yet known when
2346           * this function is called, thus go shopping and and just
2347           * check if Privoxy could filter it.
2348           *
2349           * The main thing is that we don't mess with the headers
2350           * unless the user signalled that it's acceptable.
2351           */
2352          log_error(LOG_LEVEL_HEADER,
2353             "Multiple Content-Type headers detected. "
2354             "Removing and ignoring: %s",
2355             *header);
2356          freez(*header);
2357       }
2358       return JB_ERR_OK;
2359    }
2360
2361    /*
2362     * Signal that the Content-Type has been set.
2363     */
2364    csp->content_type |= CT_DECLARED;
2365
2366    if (!(csp->content_type & CT_TABOO))
2367    {
2368       /*
2369        * XXX: The assumption that text/plain is a sign of
2370        * binary data seems to be somewhat unreasonable nowadays
2371        * and should be dropped after 3.0.8 is out.
2372        */
2373       if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2374         || strstr(*header, "xml")
2375         || strstr(*header, "script"))
2376       {
2377          csp->content_type |= CT_TEXT;
2378       }
2379       else if (strstr(*header, "image/gif"))
2380       {
2381          csp->content_type |= CT_GIF;
2382       }
2383    }
2384
2385    /*
2386     * Are we messing with the content type?
2387     */
2388    if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2389    {
2390       /*
2391        * Make sure the user doesn't accidentally
2392        * change the content type of binary documents.
2393        */
2394       if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2395       {
2396          jb_err err;
2397          freez(*header);
2398          *header = strdup_or_die("Content-Type: ");
2399
2400          err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2401          if (JB_ERR_OK != err)
2402          {
2403             log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2404             return JB_ERR_MEMORY;
2405          }
2406          log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2407       }
2408       else
2409       {
2410          log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2411             "It doesn't look like a content type that should be filtered. "
2412             "Enable force-text-mode if you know what you're doing.", *header);
2413       }
2414    }
2415
2416    return JB_ERR_OK;
2417 }
2418
2419
2420 /*********************************************************************
2421  *
2422  * Function    :  server_transfer_coding
2423  *
2424  * Description :  - Prohibit filtering (CT_TABOO) if transfer coding compresses
2425  *                - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2426  *                - Remove header if body was chunked but has been
2427  *                  de-chunked for filtering.
2428  *
2429  * Parameters  :
2430  *          1  :  csp = Current client state (buffers, headers, etc...)
2431  *          2  :  header = On input, pointer to header to modify.
2432  *                On output, pointer to the modified header, or NULL
2433  *                to remove the header.  This function frees the
2434  *                original string if necessary.
2435  *
2436  * Returns     :  JB_ERR_OK on success, or
2437  *                JB_ERR_MEMORY on out-of-memory error.
2438  *
2439  *********************************************************************/
2440 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2441 {
2442    /*
2443     * Turn off pcrs and gif filtering if body compressed
2444     */
2445    if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2446    {
2447 #ifdef FEATURE_ZLIB
2448       /*
2449        * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2450        */
2451       log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2452          csp->http->cmd, *header);
2453 #endif /* def FEATURE_ZLIB */
2454       csp->content_type = CT_TABOO;
2455    }
2456
2457    /*
2458     * Raise flag if body chunked
2459     */
2460    if (strstr(*header, "chunked"))
2461    {
2462       csp->flags |= CSP_FLAG_CHUNKED;
2463
2464       /*
2465        * If the body was modified, it has been de-chunked first
2466        * and the header must be removed.
2467        *
2468        * FIXME: If there is more than one transfer encoding,
2469        * only the "chunked" part should be removed here.
2470        */
2471       if (csp->flags & CSP_FLAG_MODIFIED)
2472       {
2473          log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2474          freez(*header);
2475       }
2476    }
2477
2478    return JB_ERR_OK;
2479 }
2480
2481
2482 /*********************************************************************
2483  *
2484  * Function    :  server_content_encoding
2485  *
2486  * Description :  Used to check if the content is compressed, and if
2487  *                FEATURE_ZLIB is disabled, filtering is disabled as
2488  *                well.
2489  *
2490  *                If FEATURE_ZLIB is enabled and the compression type
2491  *                supported, the content is marked for decompression.
2492  *
2493  *                XXX: Doesn't properly deal with multiple or with
2494  *                     unsupported but unknown encodings.
2495  *                     Is case-sensitive but shouldn't be.
2496  *
2497  * Parameters  :
2498  *          1  :  csp = Current client state (buffers, headers, etc...)
2499  *          2  :  header = On input, pointer to header to modify.
2500  *                On output, pointer to the modified header, or NULL
2501  *                to remove the header.  This function frees the
2502  *                original string if necessary.
2503  *
2504  * Returns     :  JB_ERR_OK on success, or
2505  *                JB_ERR_MEMORY on out-of-memory error.
2506  *
2507  *********************************************************************/
2508 static jb_err server_content_encoding(struct client_state *csp, char **header)
2509 {
2510 #ifdef FEATURE_ZLIB
2511    if (strstr(*header, "sdch"))
2512    {
2513       /*
2514        * Shared Dictionary Compression over HTTP isn't supported,
2515        * filtering it anyway is pretty much guaranteed to mess up
2516        * the encoding.
2517        */
2518       csp->content_type |= CT_TABOO;
2519
2520       /*
2521        * Log a warning if the user expects the content to be filtered.
2522        */
2523       if (content_filters_enabled(csp->action))
2524       {
2525          log_error(LOG_LEVEL_INFO,
2526             "SDCH-compressed content detected, content filtering disabled. "
2527             "Consider suppressing SDCH offers made by the client.");
2528       }
2529    }
2530    else if (strstr(*header, "gzip"))
2531    {
2532       /* Mark for gzip decompression */
2533       csp->content_type |= CT_GZIP;
2534    }
2535    else if (strstr(*header, "deflate"))
2536    {
2537       /* Mark for zlib decompression */
2538       csp->content_type |= CT_DEFLATE;
2539    }
2540    else if (strstr(*header, "br"))
2541    {
2542 #ifdef FEATURE_BROTLI
2543       /* Mark for Brotli decompression */
2544       csp->content_type |= CT_BROTLI;
2545 #else
2546       csp->content_type |= CT_TABOO;
2547 #endif
2548    }
2549    else if (strstr(*header, "compress"))
2550    {
2551       /*
2552        * We can't decompress this; therefore we can't filter
2553        * it either.
2554        */
2555       csp->content_type |= CT_TABOO;
2556    }
2557 #else /* !defined(FEATURE_ZLIB) */
2558    /*
2559     * XXX: Using a black list here isn't the right approach.
2560     *
2561     *      In case of SDCH, building with zlib support isn't
2562     *      going to help.
2563     */
2564    if (strstr(*header, "gzip") ||
2565        strstr(*header, "compress") ||
2566        strstr(*header, "deflate") ||
2567        strstr(*header, "sdch"))
2568    {
2569       /*
2570        * Body is compressed, turn off pcrs and gif filtering.
2571        */
2572       csp->content_type |= CT_TABOO;
2573
2574       /*
2575        * Log a warning if the user expects the content to be filtered.
2576        */
2577       if (content_filters_enabled(csp->action))
2578       {
2579          log_error(LOG_LEVEL_INFO,
2580             "Compressed content detected, content filtering disabled. "
2581             "Consider recompiling Privoxy with zlib support or "
2582             "enable the prevent-compression action.");
2583       }
2584    }
2585 #endif /* defined(FEATURE_ZLIB) */
2586
2587    return JB_ERR_OK;
2588
2589 }
2590
2591
2592 #ifdef FEATURE_ZLIB
2593 /*********************************************************************
2594  *
2595  * Function    :  server_adjust_content_encoding
2596  *
2597  * Description :  Remove the Content-Encoding header if the
2598  *                decompression was successful and the content
2599  *                has been modified.
2600  *
2601  * Parameters  :
2602  *          1  :  csp = Current client state (buffers, headers, etc...)
2603  *          2  :  header = On input, pointer to header to modify.
2604  *                On output, pointer to the modified header, or NULL
2605  *                to remove the header.  This function frees the
2606  *                original string if necessary.
2607  *
2608  * Returns     :  JB_ERR_OK on success, or
2609  *                JB_ERR_MEMORY on out-of-memory error.
2610  *
2611  *********************************************************************/
2612 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2613 {
2614    if ((csp->flags & CSP_FLAG_MODIFIED)
2615       && ((csp->content_type & (CT_GZIP | CT_DEFLATE))
2616 #ifdef FEATURE_BROTLI
2617          || (csp->content_type & CT_BROTLI)
2618 #endif
2619          )
2620       )
2621    {
2622       /*
2623        * We successfully decompressed the content,
2624        * and have to clean the header now, so the
2625        * client no longer expects compressed data.
2626        *
2627        * XXX: There is a difference between cleaning
2628        * and removing it completely.
2629        */
2630       log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2631       freez(*header);
2632    }
2633
2634    return JB_ERR_OK;
2635
2636 }
2637 #endif /* defined(FEATURE_ZLIB) */
2638
2639
2640 /*********************************************************************
2641  *
2642  * Function    :  header_adjust_content_length
2643  *
2644  * Description :  Replace given header with new Content-Length header.
2645  *
2646  * Parameters  :
2647  *          1  :  header = On input, pointer to header to modify.
2648  *                On output, pointer to the modified header, or NULL
2649  *                to remove the header.  This function frees the
2650  *                original string if necessary.
2651  *          2  :  content_length = content length value to set
2652  *
2653  * Returns     :  JB_ERR_OK on success, or
2654  *                JB_ERR_MEMORY on out-of-memory error.
2655  *
2656  *********************************************************************/
2657 jb_err header_adjust_content_length(char **header, size_t content_length)
2658 {
2659    const size_t header_length = 50;
2660    freez(*header);
2661    *header = malloc(header_length);
2662    if (*header == NULL)
2663    {
2664       return JB_ERR_MEMORY;
2665    }
2666    create_content_length_header(content_length, *header, header_length);
2667    return JB_ERR_OK;
2668 }
2669
2670
2671 /*********************************************************************
2672  *
2673  * Function    :  server_adjust_content_length
2674  *
2675  * Description :  Adjust Content-Length header if we modified
2676  *                the body.
2677  *
2678  * Parameters  :
2679  *          1  :  csp = Current client state (buffers, headers, etc...)
2680  *          2  :  header = On input, pointer to header to modify.
2681  *                On output, pointer to the modified header, or NULL
2682  *                to remove the header.  This function frees the
2683  *                original string if necessary.
2684  *
2685  * Returns     :  JB_ERR_OK on success, or
2686  *                JB_ERR_MEMORY on out-of-memory error.
2687  *
2688  *********************************************************************/
2689 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2690 {
2691    /* Regenerate header if the content was modified. */
2692    if (csp->flags & CSP_FLAG_MODIFIED)
2693    {
2694       if (JB_ERR_OK != header_adjust_content_length(header, csp->content_length))
2695       {
2696          return JB_ERR_MEMORY;
2697       }
2698       log_error(LOG_LEVEL_HEADER,
2699          "Adjusted Content-Length to %llu", csp->content_length);
2700    }
2701
2702    return JB_ERR_OK;
2703 }
2704
2705
2706 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2707 /*********************************************************************
2708  *
2709  * Function    :  server_save_content_length
2710  *
2711  * Description :  Save the Content-Length sent by the server.
2712  *
2713  * Parameters  :
2714  *          1  :  csp = Current client state (buffers, headers, etc...)
2715  *          2  :  header = On input, pointer to header to modify.
2716  *                On output, pointer to the modified header, or NULL
2717  *                to remove the header.  This function frees the
2718  *                original string if necessary.
2719  *
2720  * Returns     :  JB_ERR_OK on success, or
2721  *                JB_ERR_MEMORY on out-of-memory error.
2722  *
2723  *********************************************************************/
2724 static jb_err server_save_content_length(struct client_state *csp, char **header)
2725 {
2726    unsigned long long content_length = 0;
2727    const char *header_value;
2728
2729    assert(*(*header+14) == ':');
2730
2731    header_value = *header + 15;
2732    if (JB_ERR_OK != get_content_length(header_value, &content_length))
2733    {
2734       log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2735       freez(*header);
2736    }
2737    else
2738    {
2739       csp->expected_content_length = content_length;
2740       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2741       csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2742    }
2743
2744    return JB_ERR_OK;
2745 }
2746 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2747
2748
2749 /*********************************************************************
2750  *
2751  * Function    :  server_content_md5
2752  *
2753  * Description :  Crumble any Content-MD5 headers if the document was
2754  *                modified. FIXME: Should we re-compute instead?
2755  *
2756  * Parameters  :
2757  *          1  :  csp = Current client state (buffers, headers, etc...)
2758  *          2  :  header = On input, pointer to header to modify.
2759  *                On output, pointer to the modified header, or NULL
2760  *                to remove the header.  This function frees the
2761  *                original string if necessary.
2762  *
2763  * Returns     :  JB_ERR_OK on success, or
2764  *                JB_ERR_MEMORY on out-of-memory error.
2765  *
2766  *********************************************************************/
2767 static jb_err server_content_md5(struct client_state *csp, char **header)
2768 {
2769    if (csp->flags & CSP_FLAG_MODIFIED)
2770    {
2771       log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2772       freez(*header);
2773    }
2774
2775    return JB_ERR_OK;
2776 }
2777
2778
2779 /*********************************************************************
2780  *
2781  * Function    :  server_content_disposition
2782  *
2783  * Description :  If enabled, blocks or modifies the "Content-Disposition" header.
2784  *                Called from `sed'.
2785  *
2786  * Parameters  :
2787  *          1  :  csp = Current client state (buffers, headers, etc...)
2788  *          2  :  header = On input, pointer to header to modify.
2789  *                On output, pointer to the modified header, or NULL
2790  *                to remove the header.  This function frees the
2791  *                original string if necessary.
2792  *
2793  * Returns     :  JB_ERR_OK on success, or
2794  *                JB_ERR_MEMORY on out-of-memory error.
2795  *
2796  *********************************************************************/
2797 static jb_err server_content_disposition(struct client_state *csp, char **header)
2798 {
2799    const char *newval;
2800
2801    /*
2802     * Are we messing with the Content-Disposition header?
2803     */
2804    if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2805    {
2806       /* Me tinks not */
2807       return JB_ERR_OK;
2808    }
2809
2810    newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2811
2812    if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2813    {
2814       /*
2815        * Blocking content-disposition header
2816        */
2817       log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2818       freez(*header);
2819       return JB_ERR_OK;
2820    }
2821    else
2822    {
2823       /*
2824        * Replacing Content-Disposition header
2825        */
2826       freez(*header);
2827       *header = strdup("Content-Disposition: ");
2828       string_append(header, newval);
2829
2830       if (*header != NULL)
2831       {
2832          log_error(LOG_LEVEL_HEADER,
2833             "Content-Disposition header crunched and replaced with: %s", *header);
2834       }
2835    }
2836    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2837 }
2838
2839
2840 /*********************************************************************
2841  *
2842  * Function    :  server_last_modified
2843  *
2844  * Description :  Changes Last-Modified header to the actual date
2845  *                to help hide-if-modified-since.
2846  *                Called from `sed'.
2847  *
2848  * Parameters  :
2849  *          1  :  csp = Current client state (buffers, headers, etc...)
2850  *          2  :  header = On input, pointer to header to modify.
2851  *                On output, pointer to the modified header, or NULL
2852  *                to remove the header.  This function frees the
2853  *                original string if necessary.
2854  *
2855  * Returns     :  JB_ERR_OK on success, or
2856  *                JB_ERR_MEMORY on out-of-memory error.
2857  *
2858  *********************************************************************/
2859 static jb_err server_last_modified(struct client_state *csp, char **header)
2860 {
2861    const char *newval;
2862    time_t last_modified;
2863    char newheader[50];
2864
2865    /*
2866     * Are we messing with the Last-Modified header?
2867     */
2868    if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2869    {
2870       /*Nope*/
2871       return JB_ERR_OK;
2872    }
2873
2874    newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2875
2876    if (0 == strcmpic(newval, "block"))
2877    {
2878       /*
2879        * Blocking Last-Modified header. Useless but why not.
2880        */
2881       log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2882       freez(*header);
2883       return JB_ERR_OK;
2884    }
2885    else if (0 == strcmpic(newval, "reset-to-request-time"))
2886    {
2887       /*
2888        * Setting Last-Modified Header to now.
2889        */
2890       char buf[30];
2891       get_http_time(0, buf, sizeof(buf));
2892       freez(*header);
2893       *header = strdup("Last-Modified: ");
2894       string_append(header, buf);
2895
2896       if (*header == NULL)
2897       {
2898          log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2899       }
2900       else
2901       {
2902          log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2903       }
2904    }
2905    else if (0 == strcmpic(newval, "randomize"))
2906    {
2907       log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2908
2909       if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2910       {
2911          log_error(LOG_LEVEL_HEADER,
2912             "Couldn't parse time in %s (crunching!)", *header);
2913          freez(*header);
2914       }
2915       else
2916       {
2917          time_t now;
2918          struct tm *timeptr = NULL;
2919          long int rtime;
2920          struct tm gmt;
2921
2922          now = time(NULL);
2923          rtime = (long int)difftime(now, last_modified);
2924          if (rtime)
2925          {
2926             long int days, hours, minutes, seconds;
2927             const int negative_delta = (rtime < 0);
2928
2929             if (negative_delta)
2930             {
2931                rtime *= -1;
2932                log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2933             }
2934             rtime = pick_from_range(rtime);
2935             if (negative_delta)
2936             {
2937                rtime *= -1;
2938             }
2939             last_modified += rtime;
2940             timeptr = privoxy_gmtime_r(&last_modified, &gmt);
2941             if ((NULL == timeptr) || !strftime(newheader,
2942                   sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2943             {
2944                log_error(LOG_LEVEL_ERROR,
2945                   "Randomizing '%s' failed. Crunching the header without replacement.",
2946                   *header);
2947                freez(*header);
2948                return JB_ERR_OK;
2949             }
2950             freez(*header);
2951             *header = strdup("Last-Modified: ");
2952             string_append(header, newheader);
2953
2954             if (*header == NULL)
2955             {
2956                log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2957                return JB_ERR_MEMORY;
2958             }
2959
2960             days    = rtime / (3600 * 24);
2961             hours   = rtime / 3600 % 24;
2962             minutes = rtime / 60 % 60;
2963             seconds = rtime % 60;
2964
2965             log_error(LOG_LEVEL_HEADER,
2966                "Randomized:  %s (added %ld da%s %ld hou%s %ld minut%s %ld second%s",
2967                *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2968                minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2969          }
2970          else
2971          {
2972             log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2973          }
2974       }
2975    }
2976
2977    return JB_ERR_OK;
2978 }
2979
2980
2981 /*********************************************************************
2982  *
2983  * Function    :  client_accept_encoding
2984  *
2985  * Description :  Rewrite the client's Accept-Encoding header so that
2986  *                if doesn't allow compression, if the action applies.
2987  *                Note: For HTTP/1.0 the absence of the header is enough.
2988  *
2989  * Parameters  :
2990  *          1  :  csp = Current client state (buffers, headers, etc...)
2991  *          2  :  header = On input, pointer to header to modify.
2992  *                On output, pointer to the modified header, or NULL
2993  *                to remove the header.  This function frees the
2994  *                original string if necessary.
2995  *
2996  * Returns     :  JB_ERR_OK on success, or
2997  *                JB_ERR_MEMORY on out-of-memory error.
2998  *
2999  *********************************************************************/
3000 static jb_err client_accept_encoding(struct client_state *csp, char **header)
3001 {
3002 #ifdef FEATURE_COMPRESSION
3003    if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
3004       && strstr(*header, "deflate"))
3005    {
3006       csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
3007    }
3008 #endif
3009    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3010    {
3011       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
3012       freez(*header);
3013    }
3014
3015    return JB_ERR_OK;
3016 }
3017
3018
3019 /*********************************************************************
3020  *
3021  * Function    :  client_te
3022  *
3023  * Description :  Rewrite the client's TE header so that
3024  *                if doesn't allow compression, if the action applies.
3025  *
3026  * Parameters  :
3027  *          1  :  csp = Current client state (buffers, headers, etc...)
3028  *          2  :  header = On input, pointer to header to modify.
3029  *                On output, pointer to the modified header, or NULL
3030  *                to remove the header.  This function frees the
3031  *                original string if necessary.
3032  *
3033  * Returns     :  JB_ERR_OK on success, or
3034  *                JB_ERR_MEMORY on out-of-memory error.
3035  *
3036  *********************************************************************/
3037 static jb_err client_te(struct client_state *csp, char **header)
3038 {
3039    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3040    {
3041       freez(*header);
3042       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3043    }
3044
3045    return JB_ERR_OK;
3046 }
3047
3048
3049 /*********************************************************************
3050  *
3051  * Function    :  client_referrer
3052  *
3053  * Description :  Handle the "referer" config setting properly.
3054  *                Called from `sed'.
3055  *
3056  * Parameters  :
3057  *          1  :  csp = Current client state (buffers, headers, etc...)
3058  *          2  :  header = On input, pointer to header to modify.
3059  *                On output, pointer to the modified header, or NULL
3060  *                to remove the header.  This function frees the
3061  *                original string if necessary.
3062  *
3063  * Returns     :  JB_ERR_OK on success, or
3064  *                JB_ERR_MEMORY on out-of-memory error.
3065  *
3066  *********************************************************************/
3067 static jb_err client_referrer(struct client_state *csp, char **header)
3068 {
3069    const char *parameter;
3070    /* booleans for parameters we have to check multiple times */
3071    int parameter_conditional_block;
3072    int parameter_conditional_forge;
3073
3074 #ifdef FEATURE_FORCE_LOAD
3075    /*
3076     * Since the referrer can include the prefix even
3077     * if the request itself is non-forced, we must
3078     * clean it unconditionally.
3079     *
3080     * XXX: strclean is too broad
3081     */
3082    strclean(*header, FORCE_PREFIX);
3083 #endif /* def FEATURE_FORCE_LOAD */
3084
3085    if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3086    {
3087       /* Nothing left to do */
3088       return JB_ERR_OK;
3089    }
3090
3091    parameter = csp->action->string[ACTION_STRING_REFERER];
3092    assert(parameter != NULL);
3093    parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3094    parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3095
3096    if (!parameter_conditional_block && !parameter_conditional_forge)
3097    {
3098       /*
3099        * As conditional-block and conditional-forge are the only
3100        * parameters that rely on the original referrer, we can
3101        * remove it now for all the others.
3102        */
3103       freez(*header);
3104    }
3105
3106    if (0 == strcmpic(parameter, "block"))
3107    {
3108       log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3109       return JB_ERR_OK;
3110    }
3111    else if (parameter_conditional_block || parameter_conditional_forge)
3112    {
3113       return handle_conditional_hide_referrer_parameter(header,
3114          csp->http->hostport, parameter_conditional_block);
3115    }
3116    else if (0 == strcmpic(parameter, "forge"))
3117    {
3118       return create_forged_referrer(header, csp->http->hostport);
3119    }
3120    else
3121    {
3122       /* interpret parameter as user-supplied referer to fake */
3123       return create_fake_referrer(header, parameter);
3124    }
3125 }
3126
3127
3128 /*********************************************************************
3129  *
3130  * Function    :  client_accept_language
3131  *
3132  * Description :  Handle the "Accept-Language" config setting properly.
3133  *                Called from `sed'.
3134  *
3135  * Parameters  :
3136  *          1  :  csp = Current client state (buffers, headers, etc...)
3137  *          2  :  header = On input, pointer to header to modify.
3138  *                On output, pointer to the modified header, or NULL
3139  *                to remove the header.  This function frees the
3140  *                original string if necessary.
3141  *
3142  * Returns     :  JB_ERR_OK on success, or
3143  *                JB_ERR_MEMORY on out-of-memory error.
3144  *
3145  *********************************************************************/
3146 static jb_err client_accept_language(struct client_state *csp, char **header)
3147 {
3148    const char *newval;
3149
3150    /*
3151     * Are we messing with the Accept-Language?
3152     */
3153    if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3154    {
3155       /*I don't think so*/
3156       return JB_ERR_OK;
3157    }
3158
3159    newval = csp->action->string[ACTION_STRING_LANGUAGE];
3160
3161    if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3162    {
3163       /*
3164        * Blocking Accept-Language header
3165        */
3166       log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3167       freez(*header);
3168       return JB_ERR_OK;
3169    }
3170    else
3171    {
3172       /*
3173        * Replacing Accept-Language header
3174        */
3175       freez(*header);
3176       *header = strdup("Accept-Language: ");
3177       string_append(header, newval);
3178
3179       if (*header == NULL)
3180       {
3181          log_error(LOG_LEVEL_ERROR,
3182             "Insufficient memory. Accept-Language header crunched without replacement.");
3183       }
3184       else
3185       {
3186          log_error(LOG_LEVEL_HEADER,
3187             "Accept-Language header crunched and replaced with: %s", *header);
3188       }
3189    }
3190    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3191 }
3192
3193
3194 /*********************************************************************
3195  *
3196  * Function    :  crunch_client_header
3197  *
3198  * Description :  Crunch client header if it matches a string supplied by the
3199  *                user. Called from `sed'.
3200  *
3201  * Parameters  :
3202  *          1  :  csp = Current client state (buffers, headers, etc...)
3203  *          2  :  header = On input, pointer to header to modify.
3204  *                On output, pointer to the modified header, or NULL
3205  *                to remove the header.  This function frees the
3206  *                original string if necessary.
3207  *
3208  * Returns     :  JB_ERR_OK on success and always succeeds
3209  *
3210  *********************************************************************/
3211 static jb_err crunch_client_header(struct client_state *csp, char **header)
3212 {
3213    const char *crunch_pattern;
3214
3215    /* Do we feel like crunching? */
3216    if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3217    {
3218       crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3219
3220       /* Is the current header the lucky one? */
3221       if (strstr(*header, crunch_pattern))
3222       {
3223          log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3224          freez(*header);
3225       }
3226    }
3227    return JB_ERR_OK;
3228 }
3229
3230
3231 /*********************************************************************
3232  *
3233  * Function    :  client_uagent
3234  *
3235  * Description :  Handle the "user-agent" config setting properly
3236  *                and remember its original value to enable browser
3237  *                bug workarounds. Called from `sed'.
3238  *
3239  * Parameters  :
3240  *          1  :  csp = Current client state (buffers, headers, etc...)
3241  *          2  :  header = On input, pointer to header to modify.
3242  *                On output, pointer to the modified header, or NULL
3243  *                to remove the header.  This function frees the
3244  *                original string if necessary.
3245  *
3246  * Returns     :  JB_ERR_OK on success, or
3247  *                JB_ERR_MEMORY on out-of-memory error.
3248  *
3249  *********************************************************************/
3250 static jb_err client_uagent(struct client_state *csp, char **header)
3251 {
3252    const char *newval;
3253
3254    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3255    {
3256       return JB_ERR_OK;
3257    }
3258
3259    newval = csp->action->string[ACTION_STRING_USER_AGENT];
3260    if (newval == NULL)
3261    {
3262       return JB_ERR_OK;
3263    }
3264
3265    freez(*header);
3266    *header = strdup("User-Agent: ");
3267    string_append(header, newval);
3268
3269    log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3270
3271    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3272 }
3273
3274
3275 /*********************************************************************
3276  *
3277  * Function    :  client_ua
3278  *
3279  * Description :  Handle "ua-" headers properly.  Called from `sed'.
3280  *
3281  * Parameters  :
3282  *          1  :  csp = Current client state (buffers, headers, etc...)
3283  *          2  :  header = On input, pointer to header to modify.
3284  *                On output, pointer to the modified header, or NULL
3285  *                to remove the header.  This function frees the
3286  *                original string if necessary.
3287  *
3288  * Returns     :  JB_ERR_OK on success, or
3289  *                JB_ERR_MEMORY on out-of-memory error.
3290  *
3291  *********************************************************************/
3292 static jb_err client_ua(struct client_state *csp, char **header)
3293 {
3294    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3295    {
3296       log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3297       freez(*header);
3298    }
3299
3300    return JB_ERR_OK;
3301 }
3302
3303
3304 /*********************************************************************
3305  *
3306  * Function    :  client_from
3307  *
3308  * Description :  Handle the "from" config setting properly.
3309  *                Called from `sed'.
3310  *
3311  * Parameters  :
3312  *          1  :  csp = Current client state (buffers, headers, etc...)
3313  *          2  :  header = On input, pointer to header to modify.
3314  *                On output, pointer to the modified header, or NULL
3315  *                to remove the header.  This function frees the
3316  *                original string if necessary.
3317  *
3318  * Returns     :  JB_ERR_OK on success, or
3319  *                JB_ERR_MEMORY on out-of-memory error.
3320  *
3321  *********************************************************************/
3322 static jb_err client_from(struct client_state *csp, char **header)
3323 {
3324    const char *newval;
3325
3326    if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3327    {
3328       return JB_ERR_OK;
3329    }
3330
3331    freez(*header);
3332
3333    newval = csp->action->string[ACTION_STRING_FROM];
3334
3335    /*
3336     * Are we blocking the e-mail address?
3337     */
3338    if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3339    {
3340       log_error(LOG_LEVEL_HEADER, "crunched From!");
3341       return JB_ERR_OK;
3342    }
3343
3344    log_error(LOG_LEVEL_HEADER, " modified");
3345
3346    *header = strdup("From: ");
3347    string_append(header, newval);
3348
3349    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3350 }
3351
3352
3353 /*********************************************************************
3354  *
3355  * Function    :  client_send_cookie
3356  *
3357  * Description :  Crunches the "cookie" header if necessary.
3358  *                Called from `sed'.
3359  *
3360  *                XXX: Stupid name, doesn't send squat.
3361  *
3362  * Parameters  :
3363  *          1  :  csp = Current client state (buffers, headers, etc...)
3364  *          2  :  header = On input, pointer to header to modify.
3365  *                On output, pointer to the modified header, or NULL
3366  *                to remove the header.  This function frees the
3367  *                original string if necessary.
3368  *
3369  * Returns     :  JB_ERR_OK on success, or
3370  *                JB_ERR_MEMORY on out-of-memory error.
3371  *
3372  *********************************************************************/
3373 static jb_err client_send_cookie(struct client_state *csp, char **header)
3374 {
3375    if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3376    {
3377       log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3378       freez(*header);
3379    }
3380
3381    return JB_ERR_OK;
3382 }
3383
3384
3385 /*********************************************************************
3386  *
3387  * Function    :  client_x_forwarded
3388  *
3389  * Description :  Handle the "x-forwarded-for" config setting properly,
3390  *                also used in the add_client_headers list.  Called from `sed'.
3391  *
3392  * Parameters  :
3393  *          1  :  csp = Current client state (buffers, headers, etc...)
3394  *          2  :  header = On input, pointer to header to modify.
3395  *                On output, pointer to the modified header, or NULL
3396  *                to remove the header.  This function frees the
3397  *                original string if necessary.
3398  *
3399  * Returns     :  JB_ERR_OK on success, or
3400  *                JB_ERR_MEMORY on out-of-memory error.
3401  *
3402  *********************************************************************/
3403 jb_err client_x_forwarded(struct client_state *csp, char **header)
3404 {
3405    if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3406    {
3407       const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3408
3409       if (0 == strcmpic(parameter, "block"))
3410       {
3411          freez(*header);
3412          log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3413       }
3414       else if (0 == strcmpic(parameter, "add"))
3415       {
3416          string_append(header, ", ");
3417          string_append(header, csp->ip_addr_str);
3418
3419          if (*header == NULL)
3420          {
3421             return JB_ERR_MEMORY;
3422          }
3423          log_error(LOG_LEVEL_HEADER,
3424             "Appended client IP address to %s", *header);
3425          csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3426       }
3427       else
3428       {
3429          log_error(LOG_LEVEL_FATAL,
3430             "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3431       }
3432    }
3433
3434    return JB_ERR_OK;
3435 }
3436
3437
3438 /*********************************************************************
3439  *
3440  * Function    :  client_max_forwards
3441  *
3442  * Description :  If the HTTP method is OPTIONS or TRACE, subtract one
3443  *                from the value of the Max-Forwards header field.
3444  *
3445  * Parameters  :
3446  *          1  :  csp = Current client state (buffers, headers, etc...)
3447  *          2  :  header = On input, pointer to header to modify.
3448  *                On output, pointer to the modified header, or NULL
3449  *                to remove the header.  This function frees the
3450  *                original string if necessary.
3451  *
3452  * Returns     :  JB_ERR_OK on success, or
3453  *                JB_ERR_MEMORY on out-of-memory error.
3454  *
3455  *********************************************************************/
3456 static jb_err client_max_forwards(struct client_state *csp, char **header)
3457 {
3458    int max_forwards;
3459
3460    if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3461        (0 == strcmpic(csp->http->gpc, "options")))
3462    {
3463       assert(*(*header+12) == ':');
3464       if (1 == sscanf(*header+12, ": %d", &max_forwards))
3465       {
3466          if (max_forwards > 0)
3467          {
3468             snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3469             log_error(LOG_LEVEL_HEADER,
3470                "Max-Forwards value for %s request reduced to %d.",
3471                csp->http->gpc, max_forwards);
3472          }
3473          else if (max_forwards < 0)
3474          {
3475             log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3476             freez(*header);
3477          }
3478       }
3479       else
3480       {
3481          log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3482          freez(*header);
3483       }
3484    }
3485
3486    return JB_ERR_OK;
3487 }
3488
3489
3490 /*********************************************************************
3491  *
3492  * Function    :  client_host
3493  *
3494  * Description :  If the request URI did not contain host and
3495  *                port information, parse and evaluate the Host
3496  *                header field.
3497  *
3498  * Parameters  :
3499  *          1  :  csp = Current client state (buffers, headers, etc...)
3500  *          2  :  header = On input, pointer to header to modify.
3501  *                On output, pointer to the modified header, or NULL
3502  *                to remove the header.  This function frees the
3503  *                original string if necessary.
3504  *
3505  * Returns     :  JB_ERR_OK on success, or
3506  *                JB_ERR_MEMORY on out-of-memory error.
3507  *
3508  *********************************************************************/
3509 static jb_err client_host(struct client_state *csp, char **header)
3510 {
3511    char *p, *q;
3512
3513    if (strlen(*header) < 7)
3514    {
3515       log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3516       freez(*header);
3517       return JB_ERR_OK;
3518    }
3519
3520    if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3521        *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3522    {
3523
3524       p = strdup_or_die((*header)+6);
3525       chomp(p);
3526       q = strdup_or_die(p);
3527
3528       freez(csp->http->hostport);
3529       csp->http->hostport = p;
3530       freez(csp->http->host);
3531       csp->http->host = q;
3532       q = strchr(csp->http->host, ':');
3533       if (q != NULL)
3534       {
3535          /* Terminate hostname and evaluate port string */
3536          *q++ = '\0';
3537          csp->http->port = atoi(q);
3538       }
3539       else
3540       {
3541          csp->http->port = csp->http->ssl ? 443 : 80;
3542       }
3543
3544       log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3545                 csp->http->hostport, csp->http->host, csp->http->port);
3546    }
3547
3548    /* Signal client_host_adder() to return right away */
3549    csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3550
3551    return JB_ERR_OK;
3552 }
3553
3554
3555 /*********************************************************************
3556  *
3557  * Function    :  client_if_modified_since
3558  *
3559  * Description :  Remove or modify the If-Modified-Since header.
3560  *
3561  * Parameters  :
3562  *          1  :  csp = Current client state (buffers, headers, etc...)
3563  *          2  :  header = On input, pointer to header to modify.
3564  *                On output, pointer to the modified header, or NULL
3565  *                to remove the header.  This function frees the
3566  *                original string if necessary.
3567  *
3568  * Returns     :  JB_ERR_OK on success, or
3569  *                JB_ERR_MEMORY on out-of-memory error.
3570  *
3571  *********************************************************************/
3572 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3573 {
3574    char newheader[50];
3575    struct tm gmt;
3576    struct tm *timeptr = NULL;
3577    time_t tm = 0;
3578    const char *newval;
3579    char * endptr;
3580
3581    if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3582    {
3583       /*
3584        * The client got an error message because of a temporary problem,
3585        * the problem is gone and the client now tries to revalidate our
3586        * error message on the real server. The revalidation would always
3587        * end with the transmission of the whole document and there is
3588        * no need to expose the bogus If-Modified-Since header.
3589        */
3590       log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3591       freez(*header);
3592    }
3593    else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3594    {
3595       newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3596
3597       if ((0 == strcmpic(newval, "block")))
3598       {
3599          log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3600          freez(*header);
3601       }
3602       else /* add random value */
3603       {
3604          if (JB_ERR_OK != parse_time_header(*header, &tm))
3605          {
3606             log_error(LOG_LEVEL_HEADER,
3607                "Couldn't parse time in %s (crunching!)", *header);
3608             freez(*header);
3609          }
3610          else
3611          {
3612             long int hours, minutes, seconds;
3613             long int rtime = strtol(newval, &endptr, 0);
3614             const int negative_range = (rtime < 0);
3615
3616             if (rtime)
3617             {
3618                log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %ld minut%s)",
3619                   *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3620                if (negative_range)
3621                {
3622                   rtime *= -1;
3623                }
3624                rtime *= 60;
3625                rtime = pick_from_range(rtime);
3626             }
3627             else
3628             {
3629                log_error(LOG_LEVEL_ERROR,
3630                   "Random range is 0. Assuming time transformation test.");
3631             }
3632             tm += rtime * (negative_range ? -1 : 1);
3633             timeptr = privoxy_gmtime_r(&tm, &gmt);
3634             if ((NULL == timeptr) || !strftime(newheader,
3635                   sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3636             {
3637                log_error(LOG_LEVEL_ERROR,
3638                   "Randomizing '%s' failed. Crunching the header without replacement.",
3639                   *header);
3640                freez(*header);
3641                return JB_ERR_OK;
3642             }
3643             freez(*header);
3644             *header = strdup("If-Modified-Since: ");
3645             string_append(header, newheader);
3646
3647             if (*header == NULL)
3648             {
3649                log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3650                return JB_ERR_MEMORY;
3651             }
3652
3653             hours   = rtime / 3600;
3654             minutes = rtime / 60 % 60;
3655             seconds = rtime % 60;
3656
3657             log_error(LOG_LEVEL_HEADER,
3658                "Randomized:  %s (%s %ld hou%s %ld minut%s %ld second%s",
3659                *header, (negative_range) ? "subtracted" : "added", hours,
3660                (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3661                seconds, (seconds == 1) ? ")" : "s)");
3662          }
3663       }
3664    }
3665
3666    return JB_ERR_OK;
3667 }
3668
3669
3670 /*********************************************************************
3671  *
3672  * Function    :  client_if_none_match
3673  *
3674  * Description :  Remove the If-None-Match header.
3675  *
3676  * Parameters  :
3677  *          1  :  csp = Current client state (buffers, headers, etc...)
3678  *          2  :  header = On input, pointer to header to modify.
3679  *                On output, pointer to the modified header, or NULL
3680  *                to remove the header.  This function frees the
3681  *                original string if necessary.
3682  *
3683  * Returns     :  JB_ERR_OK on success, or
3684  *                JB_ERR_MEMORY on out-of-memory error.
3685  *
3686  *********************************************************************/
3687 static jb_err client_if_none_match(struct client_state *csp, char **header)
3688 {
3689    if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3690    {
3691       log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3692       freez(*header);
3693    }
3694
3695    return JB_ERR_OK;
3696 }
3697
3698
3699 /*********************************************************************
3700  *
3701  * Function    :  client_x_filter
3702  *
3703  * Description :  Disables filtering if the client set "X-Filter: No".
3704  *                Called from `sed'.
3705  *
3706  * Parameters  :
3707  *          1  :  csp = Current client state (buffers, headers, etc...)
3708  *          2  :  header = On input, pointer to header to modify.
3709  *                On output, pointer to the modified header, or NULL
3710  *                to remove the header.  This function frees the
3711  *                original string if necessary.
3712  *
3713  * Returns     :  JB_ERR_OK on success
3714  *
3715  *********************************************************************/
3716 jb_err client_x_filter(struct client_state *csp, char **header)
3717 {
3718    if (0 == strcmpic(*header, "X-Filter: No"))
3719    {
3720       if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3721       {
3722          log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3723       }
3724       else
3725       {
3726          if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3727          {
3728             log_error(LOG_LEVEL_HEADER,
3729                "force-text-mode overruled the client's request to fetch without filtering!");
3730          }
3731          else
3732          {
3733             csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3734             csp->flags |= CSP_FLAG_NO_FILTERING;
3735             log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3736          }
3737          log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3738          freez(*header);
3739       }
3740    }
3741    return JB_ERR_OK;
3742 }
3743
3744
3745 /*********************************************************************
3746  *
3747  * Function    :  client_range
3748  *
3749  * Description :  Removes Range, Request-Range and If-Range headers if
3750  *                content filtering is enabled and the range doesn't
3751  *                start at byte 0.
3752  *
3753  *                If the client's version of the document has been
3754  *                altered by Privoxy, the server could interpret the
3755  *                range differently than the client intended in which
3756  *                case the user could end up with corrupted content.
3757  *
3758  *                If the range starts at byte 0 this isn't an issue
3759  *                so the header can pass. Partial requests like this
3760  *                are used to render preview images for videos without
3761  *                downloading the whole video.
3762  *
3763  *                While HTTP doesn't require that range requests are
3764  *                honoured and the client could simply abort the download
3765  *                after receiving a sufficient amount of data, various
3766  *                clients don't handle complete responses to range
3767  *                requests gracefully and emit misleading error messages
3768  *                instead.
3769  *
3770  * Parameters  :
3771  *          1  :  csp = Current client state (buffers, headers, etc...)
3772  *          2  :  header = On input, pointer to header to modify.
3773  *                On output, pointer to the modified header, or NULL
3774  *                to remove the header.  This function frees the
3775  *                original string if necessary.
3776  *
3777  * Returns     :  JB_ERR_OK
3778  *
3779  *********************************************************************/
3780 static jb_err client_range(struct client_state *csp, char **header)
3781 {
3782    if (content_filters_enabled(csp->action)
3783       && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3784    {
3785       log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3786          " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3787       freez(*header);
3788    }
3789
3790    return JB_ERR_OK;
3791 }
3792
3793 /* the following functions add headers directly to the header list */
3794
3795 /*********************************************************************
3796  *
3797  * Function    :  client_host_adder
3798  *
3799  * Description :  Adds the Host: header field if it is missing.
3800  *                Called from `sed'.
3801  *
3802  * Parameters  :
3803  *          1  :  csp = Current client state (buffers, headers, etc...)
3804  *
3805  * Returns     :  JB_ERR_OK on success, or
3806  *                JB_ERR_MEMORY on out-of-memory error.
3807  *
3808  *********************************************************************/
3809 static jb_err client_host_adder(struct client_state *csp)
3810 {
3811    char *p;
3812    jb_err err;
3813
3814    if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3815    {
3816       /* Header already set by the client, nothing to do. */
3817       return JB_ERR_OK;
3818    }
3819
3820    if (!csp->http->hostport || !*(csp->http->hostport))
3821    {
3822       log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3823       return JB_ERR_PARSE;
3824    }
3825
3826    /*
3827     * remove 'user:pass@' from 'proto://user:pass@host'
3828     */
3829    if ((p = strchr( csp->http->hostport, '@')) != NULL)
3830    {
3831       p++;
3832    }
3833    else
3834    {
3835       p = csp->http->hostport;
3836    }
3837
3838    /* XXX: Just add it, we already made sure that it will be unique */
3839    log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3840    err = enlist_unique_header(csp->headers, "Host", p);
3841    return err;
3842
3843 }
3844
3845
3846 /*********************************************************************
3847  *
3848  * Function    :  client_xtra_adder
3849  *
3850  * Description :  Used in the add_client_headers list.  Called from `sed'.
3851  *
3852  * Parameters  :
3853  *          1  :  csp = Current client state (buffers, headers, etc...)
3854  *
3855  * Returns     :  JB_ERR_OK on success, or
3856  *                JB_ERR_MEMORY on out-of-memory error.
3857  *
3858  *********************************************************************/
3859 static jb_err client_xtra_adder(struct client_state *csp)
3860 {
3861    struct list_entry *lst;
3862    jb_err err;
3863
3864    for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3865         lst ; lst = lst->next)
3866    {
3867       log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3868       err = enlist(csp->headers, lst->str);
3869       if (err)
3870       {
3871          return err;
3872       }
3873
3874    }
3875
3876    return JB_ERR_OK;
3877 }
3878
3879
3880 /*********************************************************************
3881  *
3882  * Function    :  client_x_forwarded_for_adder
3883  *
3884  * Description :  Used in the add_client_headers list.  Called from `sed'.
3885  *
3886  * Parameters  :
3887  *          1  :  csp = Current client state (buffers, headers, etc...)
3888  *
3889  * Returns     :  JB_ERR_OK on success, or
3890  *                JB_ERR_MEMORY on out-of-memory error.
3891  *
3892  *********************************************************************/
3893 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3894 {
3895    char *header = NULL;
3896    jb_err err;
3897
3898    if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3899          && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3900       || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3901    {
3902       /*
3903        * If we aren't adding X-Forwarded-For headers,
3904        * or we already appended an existing X-Forwarded-For
3905        * header, there's nothing left to do here.
3906        */
3907       return JB_ERR_OK;
3908    }
3909
3910    header = strdup("X-Forwarded-For: ");
3911    string_append(&header, csp->ip_addr_str);
3912
3913    if (header == NULL)
3914    {
3915       return JB_ERR_MEMORY;
3916    }
3917
3918    log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3919    err = enlist(csp->headers, header);
3920    freez(header);
3921
3922    return err;
3923 }
3924
3925
3926 /*********************************************************************
3927  *
3928  * Function    :  server_connection_adder
3929  *
3930  * Description :  Adds an appropriate "Connection:" header to csp->headers
3931  *                unless the header was already present. Called from `sed'.
3932  *
3933  * Parameters  :
3934  *          1  :  csp = Current client state (buffers, headers, etc...)
3935  *
3936  * Returns     :  JB_ERR_OK on success, or
3937  *                JB_ERR_MEMORY on out-of-memory error.
3938  *
3939  *********************************************************************/
3940 static jb_err server_connection_adder(struct client_state *csp)
3941 {
3942    const unsigned int flags = csp->flags;
3943    const char *response_status_line = csp->headers->first->str;
3944    static const char connection_close[] = "Connection: close";
3945
3946    if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3947     && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3948    {
3949       return JB_ERR_OK;
3950    }
3951
3952    /*
3953     * XXX: if we downgraded the response, this check will fail.
3954     */
3955    if ((csp->config->feature_flags &
3956         RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3957     && (NULL != response_status_line)
3958     && !strncmpic(response_status_line, "HTTP/1.1", 8)
3959 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3960     && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3961 #endif
3962       )
3963    {
3964       log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3965          "without Connection header implies keep-alive.");
3966       csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3967       return JB_ERR_OK;
3968    }
3969
3970    log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3971
3972    return enlist(csp->headers, connection_close);
3973 }
3974
3975
3976 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3977 /*********************************************************************
3978  *
3979  * Function    :  server_proxy_connection_adder
3980  *
3981  * Description :  Adds a "Proxy-Connection: keep-alive" header to
3982  *                csp->headers when appropriate.
3983  *
3984  * Parameters  :
3985  *          1  :  csp = Current client state (buffers, headers, etc...)
3986  *
3987  * Returns     :  JB_ERR_OK on success, or
3988  *                JB_ERR_MEMORY on out-of-memory error.
3989  *
3990  *********************************************************************/
3991 static jb_err server_proxy_connection_adder(struct client_state *csp)
3992 {
3993    static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3994    jb_err err = JB_ERR_OK;
3995
3996    if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3997     && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3998     && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3999     && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4000        || (csp->flags & CSP_FLAG_CHUNKED))
4001 #ifdef FEATURE_HTTPS_INSPECTION
4002     && !client_use_ssl(csp)
4003     && !csp->http->ssl
4004 #endif
4005        )
4006    {
4007       log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
4008       err = enlist(csp->headers, proxy_connection_header);
4009    }
4010
4011    return err;
4012 }
4013 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4014
4015
4016 /*********************************************************************
4017  *
4018  * Function    :  client_connection_header_adder
4019  *
4020  * Description :  Adds a proper "Connection:" header to csp->headers
4021  *                unless the header was already present or it's a
4022  *                CONNECT request. Called from `sed'.
4023  *
4024  * Parameters  :
4025  *          1  :  csp = Current client state (buffers, headers, etc...)
4026  *
4027  * Returns     :  JB_ERR_OK on success, or
4028  *                JB_ERR_MEMORY on out-of-memory error.
4029  *
4030  *********************************************************************/
4031 static jb_err client_connection_header_adder(struct client_state *csp)
4032 {
4033    static const char connection_close[] = "Connection: close";
4034
4035    if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
4036      && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
4037    {
4038       return JB_ERR_OK;
4039    }
4040
4041    /*
4042     * In case of CONNECT requests "Connection: close" is implied,
4043     * but actually setting the header has been reported to cause
4044     * problems with some forwarding proxies that close the
4045     * connection prematurely.
4046     */
4047    if (csp->http->ssl != 0)
4048    {
4049       return JB_ERR_OK;
4050    }
4051
4052 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4053    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4054       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4055       && !strcmpic(csp->http->version, "HTTP/1.1"))
4056    {
4057       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4058       return JB_ERR_OK;
4059    }
4060 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
4061
4062    log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
4063
4064    return enlist(csp->headers, connection_close);
4065 }
4066
4067
4068 /*********************************************************************
4069  *
4070  * Function    :  server_http
4071  *
4072  * Description :  - Save the HTTP Status into csp->http->status
4073  *                - Set CT_TABOO to prevent filtering if the answer
4074  *                  is a partial range (HTTP status 206)
4075  *                - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
4076  *                  action applies.
4077  *                - Normalize the HTTP-version.
4078  *
4079  * Parameters  :
4080  *          1  :  csp = Current client state (buffers, headers, etc...)
4081  *          2  :  header = On input, pointer to header to modify.
4082  *                On output, pointer to the modified header, or NULL
4083  *                to remove the header.  This function frees the
4084  *                original string if necessary.
4085  *
4086  * Returns     :  JB_ERR_OK on success, or
4087  *                JB_ERR_PARSE on fatal parse errors.
4088  *
4089  *********************************************************************/
4090 static jb_err server_http(struct client_state *csp, char **header)
4091 {
4092    char *reason_phrase = NULL;
4093    char *new_response_line;
4094    char *p;
4095    size_t length;
4096    unsigned int major_version;
4097    unsigned int minor_version;
4098
4099    /* Get the reason phrase which start after the second whitespace */
4100    p = strchr(*header, ' ');
4101    if (NULL != p)
4102    {
4103       p++;
4104       reason_phrase = strchr(p, ' ');
4105    }
4106
4107    if (reason_phrase != NULL)
4108    {
4109       reason_phrase++;
4110    }
4111    else
4112    {
4113       log_error(LOG_LEVEL_ERROR,
4114          "Response line lacks reason phrase: %s", *header);
4115       reason_phrase="";
4116    }
4117
4118    if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
4119          &minor_version, &(csp->http->status)))
4120    {
4121       log_error(LOG_LEVEL_ERROR,
4122          "Failed to parse the response line: %s", *header);
4123       return JB_ERR_PARSE;
4124    }
4125
4126    if (csp->http->status == 101 ||
4127        csp->http->status == 206)
4128    {
4129       csp->content_type = CT_TABOO;
4130    }
4131
4132    if (major_version != 1 || (minor_version != 0 && minor_version != 1))
4133    {
4134       /*
4135        * According to RFC 7230 2.6 intermediaries MUST send
4136        * their own HTTP-version in forwarded messages.
4137        */
4138       log_error(LOG_LEVEL_ERROR,
4139          "Unsupported HTTP version. Downgrading to 1.1.");
4140       major_version = 1;
4141       minor_version = 1;
4142    }
4143
4144    if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
4145    {
4146       log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
4147       minor_version = 0;
4148    }
4149
4150    /* Rebuild response line. */
4151    length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
4152    new_response_line = malloc_or_die(length);
4153
4154    snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
4155       major_version, minor_version, csp->http->status, reason_phrase);
4156
4157    if (0 != strcmp(*header, new_response_line))
4158    {
4159       log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
4160          *header, new_response_line);
4161    }
4162
4163    freez(*header);
4164    *header = new_response_line;
4165
4166    return JB_ERR_OK;
4167 }
4168
4169 /*********************************************************************
4170  *
4171  * Function    :  add_cooky_expiry_date
4172  *
4173  * Description :  Adds a cookie expiry date to a string.
4174  *
4175  * Parameters  :
4176  *          1  :  cookie = On input, pointer to cookie to modify.
4177  *                         On output, pointer to the modified header.
4178  *                         The original string is freed.
4179  *          2  :  lifetime = Seconds the cookie should be valid
4180  *
4181  * Returns     :  N/A
4182  *
4183  *********************************************************************/
4184 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
4185 {
4186    char tmp[50];
4187    struct tm *timeptr = NULL;
4188    time_t expiry_date = time(NULL) + lifetime;
4189    struct tm gmt;
4190
4191    timeptr = privoxy_gmtime_r(&expiry_date, &gmt);
4192    if (NULL == timeptr)
4193    {
4194       log_error(LOG_LEVEL_FATAL,
4195          "Failed to get the time in add_cooky_expiry_date()");
4196    }
4197    strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
4198    if (JB_ERR_OK != string_append(cookie, tmp))
4199    {
4200       log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
4201    }
4202 }
4203
4204
4205 /*********************************************************************
4206  *
4207  * Function    :  server_set_cookie
4208  *
4209  * Description :  Handle the server "cookie" header properly.
4210  *                Crunch, accept or rewrite it to a session cookie.
4211  *                Called from `sed'.
4212  *
4213  * Parameters  :
4214  *          1  :  csp = Current client state (buffers, headers, etc...)
4215  *          2  :  header = On input, pointer to header to modify.
4216  *                On output, pointer to the modified header, or NULL
4217  *                to remove the header.  This function frees the
4218  *                original string if necessary.
4219  *
4220  * Returns     :  JB_ERR_OK on success, or
4221  *                JB_ERR_MEMORY on out-of-memory error.
4222  *
4223  *********************************************************************/
4224 static jb_err server_set_cookie(struct client_state *csp, char **header)
4225 {
4226    if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4227    {
4228       log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4229       freez(*header);
4230    }
4231    else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4232          || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4233    {
4234       time_t now;
4235       time_t cookie_time;
4236       long cookie_lifetime = 0;
4237       enum
4238       {
4239          NO_EXPIRY_DATE_SPECIFIED,
4240          EXPIRY_DATE_ACCEPTABLE,
4241          EXPIRY_DATE_UNACCEPTABLE
4242       } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4243
4244       /* A variable to store the tag we're working on */
4245       char *cur_tag;
4246
4247       /* Skip "Set-Cookie:" (11 characters) in header */
4248       cur_tag = *header + 11;
4249
4250       /* skip whitespace between "Set-Cookie:" and value */
4251       while (*cur_tag && privoxy_isspace(*cur_tag))
4252       {
4253          cur_tag++;
4254       }
4255
4256       time(&now);
4257
4258       if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4259       {
4260          const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4261
4262          cookie_lifetime = strtol(param, NULL, 0);
4263          if (cookie_lifetime < 0)
4264          {
4265             log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4266          }
4267          cookie_lifetime *= 60;
4268       }
4269
4270       /* Loop through each tag in the cookie */
4271       while (*cur_tag)
4272       {
4273          /* Find next tag */
4274          char *next_tag = strchr(cur_tag, ';');
4275          if (next_tag != NULL)
4276          {
4277             /* Skip the ';' character itself */
4278             next_tag++;
4279
4280             /* skip whitespace ";" and start of tag */
4281             while (*next_tag && privoxy_isspace(*next_tag))
4282             {
4283                next_tag++;
4284             }
4285          }
4286          else
4287          {
4288             /* "Next tag" is the end of the string */
4289             next_tag = cur_tag + strlen(cur_tag);
4290          }
4291
4292          /*
4293           * Check the expiration date to see
4294           * if the cookie is still valid, if yes,
4295           * rewrite it to a session cookie.
4296           */
4297          if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4298          {
4299             char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4300
4301             if ((expiration_date[0] == '"')
4302              && (expiration_date[1] != '\0'))
4303             {
4304                /*
4305                 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4306                 * that the expiration date isn't supposed to be quoted,
4307                 * but some servers do it anyway.
4308                 */
4309                expiration_date++;
4310             }
4311
4312             /* Did we detect the date properly? */
4313             if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4314             {
4315                /*
4316                 * Nope, treat it as if it was still valid.
4317                 *
4318                 * XXX: Should we remove the whole cookie instead?
4319                 */
4320                log_error(LOG_LEVEL_ERROR,
4321                   "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4322                string_move(cur_tag, next_tag);
4323                expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4324             }
4325             else
4326             {
4327                /*
4328                 * Yes. Check if the cookie is still valid.
4329                 *
4330                 * If the cookie is already expired it's probably
4331                 * a delete cookie and even if it isn't, the browser
4332                 * will discard it anyway.
4333                 */
4334
4335                /*
4336                 * XXX: timegm() isn't available on some AmigaOS
4337                 * versions and our replacement doesn't work.
4338                 *
4339                 * Our options are to either:
4340                 *
4341                 * - disable session-cookies-only completely if timegm
4342                 *   is missing,
4343                 *
4344                 * - to simply remove all expired tags, like it has
4345                 *   been done until Privoxy 3.0.6 and to live with
4346                 *    the consequence that it can cause login/logout
4347                 *   problems on servers that don't validate their
4348                 *   input properly, or
4349                 *
4350                 * - to replace it with mktime in which
4351                 *   case there is a slight chance of valid cookies
4352                 *   passing as already expired.
4353                 *
4354                 *   This is the way it's currently done and it's not
4355                 *   as bad as it sounds. If the missing GMT offset is
4356                 *   enough to change the result of the expiration check
4357                 *   the cookie will be only valid for a few hours
4358                 *   anyway, which in many cases will be shorter
4359                 *   than a browser session.
4360                 */
4361                if (cookie_time < now)
4362                {
4363                   log_error(LOG_LEVEL_HEADER,
4364                      "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4365                   /* Just in case some clown sets more then one expiration date */
4366                   cur_tag = next_tag;
4367                   expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4368                }
4369                else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4370                {
4371                   log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4372                      "Its lifetime is below the limit.", *header);
4373                   /* Just in case some clown sets more then one expiration date */
4374                   cur_tag = next_tag;
4375                   expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4376                }
4377                else
4378                {
4379                   /*
4380                    * Still valid, delete expiration date by copying
4381                    * the rest of the string over it.
4382                    */
4383                   string_move(cur_tag, next_tag);
4384
4385                   /* That changed the header, need to issue a log message */
4386                   expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4387
4388                   /*
4389                    * Note that the next tag has now been moved to *cur_tag,
4390                    * so we do not need to update the cur_tag pointer.
4391                    */
4392                }
4393             }
4394
4395          }
4396          else
4397          {
4398             /* Move on to next cookie tag */
4399             cur_tag = next_tag;
4400          }
4401       }
4402
4403       if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4404       {
4405          assert(NULL != *header);
4406          if (cookie_lifetime != 0)
4407          {
4408             add_cookie_expiry_date(header, cookie_lifetime);
4409             log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4410          }
4411          else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4412          {
4413             log_error(LOG_LEVEL_HEADER,
4414                "Cookie rewritten to a temporary one: %s", *header);
4415          }
4416       }
4417    }
4418
4419    return JB_ERR_OK;
4420 }
4421
4422
4423 #ifdef FEATURE_FORCE_LOAD
4424 /*********************************************************************
4425  *
4426  * Function    :  strclean
4427  *
4428  * Description :  In-Situ-Eliminate all occurrences of substring in
4429  *                string
4430  *
4431  * Parameters  :
4432  *          1  :  string = string to clean
4433  *          2  :  substring = substring to eliminate
4434  *
4435  * Returns     :  Number of eliminations
4436  *
4437  *********************************************************************/
4438 int strclean(char *string, const char *substring)
4439 {
4440    int hits = 0;
4441    size_t len;
4442    char *pos, *p;
4443
4444    len = strlen(substring);
4445
4446    while((pos = strstr(string, substring)) != NULL)
4447    {
4448       p = pos + len;
4449       do
4450       {
4451          *(p - len) = *p;
4452       }
4453       while (*p++ != '\0');
4454
4455       hits++;
4456    }
4457
4458    return(hits);
4459 }
4460 #endif /* def FEATURE_FORCE_LOAD */
4461
4462
4463 /*********************************************************************
4464  *
4465  * Function    :  parse_header_time
4466  *
4467  * Description :  Parses time formats used in HTTP header strings
4468  *                to get the numerical respresentation.
4469  *
4470  * Parameters  :
4471  *          1  :  header_time = HTTP header time as string.
4472  *          2  :  result = storage for header_time in seconds
4473  *
4474  * Returns     :  JB_ERR_OK if the time format was recognized, or
4475  *                JB_ERR_PARSE otherwise.
4476  *
4477  *********************************************************************/
4478 static jb_err parse_header_time(const char *header_time, time_t *result)
4479 {
4480    struct tm gmt;
4481    /*
4482     * Checking for two-digit years first in an
4483     * attempt to work around GNU libc's strptime()
4484     * reporting negative year values when using %Y.
4485     */
4486    static const char time_formats[][22] = {
4487       /* Tue, 02-Jun-37 20:00:00 */
4488       "%a, %d-%b-%y %H:%M:%S",
4489       /* Tue, 02 Jun 2037 20:00:00 */
4490       "%a, %d %b %Y %H:%M:%S",
4491       /* Tue, 02-Jun-2037 20:00:00 */
4492       "%a, %d-%b-%Y %H:%M:%S",
4493       /* Tuesday, 02-Jun-2037 20:00:00 */
4494       "%A, %d-%b-%Y %H:%M:%S",
4495       /* Tuesday Jun 02 20:00:00 2037 */
4496       "%A %b %d %H:%M:%S %Y"
4497    };
4498    unsigned int i;
4499
4500    for (i = 0; i < SZ(time_formats); i++)
4501    {
4502       /*
4503        * Zero out gmt to prevent time zone offsets.
4504        * Documented to be required for GNU libc.
4505        */
4506       memset(&gmt, 0, sizeof(gmt));
4507
4508       if (NULL != strptime(header_time, time_formats[i], &gmt))
4509       {
4510          /* Sanity check for GNU libc. */
4511          if (gmt.tm_year < 0)
4512          {
4513             log_error(LOG_LEVEL_HEADER,
4514                "Failed to parse '%s' using '%s'. Moving on.",
4515                header_time, time_formats[i]);
4516             continue;
4517          }
4518          *result = timegm(&gmt);
4519
4520 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4521          /*
4522           * Verify that parsing the date recreated from the first
4523           * parse operation gets the previous result. If it doesn't,
4524           * either strptime() or strftime() are malfunctioning.
4525           *
4526           * We could string-compare the recreated date with the original
4527           * header date, but this leads to false positives as strptime()
4528           * may let %a accept all day formats while strftime() will only
4529           * create one.
4530           */
4531          {
4532             char recreated_date[100];
4533             struct tm *tm;
4534             struct tm storage;
4535             time_t result2;
4536
4537             tm = privoxy_gmtime_r(result, &storage);
4538             if (!strftime(recreated_date, sizeof(recreated_date),
4539                time_formats[i], tm))
4540             {
4541                log_error(LOG_LEVEL_ERROR, "Failed to recreate date '%s' with '%s'.",
4542                   header_time, time_formats[i]);
4543                continue;
4544             }
4545             memset(&gmt, 0, sizeof(gmt));
4546             if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4547             {
4548                log_error(LOG_LEVEL_ERROR,
4549                   "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4550                   recreated_date, time_formats[i], header_time);
4551                continue;
4552             }
4553             result2 = timegm(&gmt);
4554             if (*result != result2)
4555             {
4556                log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4557                   "Format: '%s'. In: '%s', out: '%s'. %ld != %ld. Rejecting.",
4558                   time_formats[i], header_time, recreated_date, *result, result2);
4559                continue;
4560             }
4561          }
4562 #endif
4563
4564          return JB_ERR_OK;
4565       }
4566    }
4567
4568    return JB_ERR_PARSE;
4569
4570 }
4571
4572 /*********************************************************************
4573  *
4574  * Function    :  parse_time_header
4575  *
4576  * Description :  Parses the time in an HTTP time header to get
4577  *                the numerical respresentation.
4578  *
4579  * Parameters  :
4580  *          1  :  header = HTTP header with a time value
4581  *          2  :  result = storage for header_time in seconds
4582  *
4583  * Returns     :  JB_ERR_OK if the time format was recognized, or
4584  *                JB_ERR_PARSE otherwise.
4585  *
4586  *********************************************************************/
4587 static jb_err parse_time_header(const char *header, time_t *result)
4588 {
4589    const char *header_time;
4590
4591    header_time = strchr(header, ':');
4592
4593    /*
4594     * Currently this can't happen as all callers are called
4595     * through sed() which requires a header name followed by
4596     * a colon.
4597     */
4598    assert(header_time != NULL);
4599
4600    header_time++;
4601    if (*header_time == ' ')
4602    {
4603       header_time++;
4604    }
4605
4606    return parse_header_time(header_time, result);
4607
4608 }
4609
4610
4611 /*********************************************************************
4612  *
4613  * Function    :  get_destination_from_headers
4614  *
4615  * Description :  Parse the "Host:" header to get the request's destination.
4616  *                Only needed if the client's request was forcefully
4617  *                redirected into Privoxy.
4618  *
4619  *                Code mainly copied from client_host() which is currently
4620  *                run too late for this purpose.
4621  *
4622  * Parameters  :
4623  *          1  :  headers = List of headers (one of them hopefully being
4624  *                the "Host:" header)
4625  *          2  :  http = storage for the result (host, port and hostport).
4626  *
4627  * Returns     :  JB_ERR_MEMORY (or terminates) in case of memory problems,
4628  *                JB_ERR_PARSE if the host header couldn't be found,
4629  *                JB_ERR_OK otherwise.
4630  *
4631  *********************************************************************/
4632 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4633 {
4634    char *q;
4635    char *p;
4636    char *host;
4637
4638    host = get_header_value(headers, "Host:");
4639
4640    if (NULL == host)
4641    {
4642       log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4643       return JB_ERR_PARSE;
4644    }
4645
4646    p = string_tolower(host);
4647    if (p == NULL)
4648    {
4649       return JB_ERR_MEMORY;
4650    }
4651    chomp(p);
4652    q = strdup_or_die(p);
4653
4654    freez(http->hostport);
4655    http->hostport = p;
4656    freez(http->host);
4657    http->host = q;
4658    q = strchr(http->host, ':');
4659    if (q != NULL)
4660    {
4661       /* Terminate hostname and evaluate port string */
4662       *q++ = '\0';
4663       http->port = atoi(q);
4664    }
4665    else
4666    {
4667       http->port = 80;
4668    }
4669
4670    /* Rebuild request URL */
4671    freez(http->url);
4672    http->url = strdup("http://");
4673    string_append(&http->url, http->hostport);
4674    string_append(&http->url, http->path);
4675    if (http->url == NULL)
4676    {
4677       return JB_ERR_MEMORY;
4678    }
4679
4680    log_error(LOG_LEVEL_HEADER,
4681       "Destination extracted from \"Host\" header. New request URL: %s",
4682       http->url);
4683
4684    /*
4685     * Regenerate request line in "proxy format"
4686     * to make rewrites more convenient.
4687     */
4688    assert(http->cmd != NULL);
4689    freez(http->cmd);
4690    http->cmd = strdup_or_die(http->gpc);
4691    string_append(&http->cmd, " ");
4692    string_append(&http->cmd, http->url);
4693    string_append(&http->cmd, " ");
4694    string_append(&http->cmd, http->version);
4695    if (http->cmd == NULL)
4696    {
4697       return JB_ERR_MEMORY;
4698    }
4699
4700    return JB_ERR_OK;
4701
4702 }
4703
4704
4705 #ifdef FEATURE_HTTPS_INSPECTION
4706 /*********************************************************************
4707  *
4708  * Function    :  get_destination_from_https_headers
4709  *
4710  * Description :  Parse the previously encrypted "Host:" header to
4711  *                get the request's destination.
4712  *
4713  * Parameters  :
4714  *          1  :  headers = List of headers (one of them hopefully being
4715  *                the "Host:" header)
4716  *          2  :  http = storage for the result (host, port and hostport).
4717  *
4718  * Returns     :  JB_ERR_MEMORY (or terminates) in case of memory problems,
4719  *                JB_ERR_PARSE if the host header couldn't be found,
4720  *                JB_ERR_OK otherwise.
4721  *
4722  *********************************************************************/
4723 jb_err get_destination_from_https_headers(const struct list *headers, struct http_request *http)
4724 {
4725    char *q;
4726    char *p;
4727    char *host;
4728
4729    host = get_header_value(headers, "Host:");
4730
4731    if (NULL == host)
4732    {
4733       log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4734       return JB_ERR_PARSE;
4735    }
4736
4737    p = string_tolower(host);
4738    if (p == NULL)
4739    {
4740       return JB_ERR_MEMORY;
4741    }
4742    chomp(p);
4743    q = strdup_or_die(p);
4744
4745    freez(http->hostport);
4746    http->hostport = p;
4747    freez(http->host);
4748    http->host = q;
4749    q = strchr(http->host, ':');
4750    if (q != NULL)
4751    {
4752       /* Terminate hostname and evaluate port string */
4753       *q++ = '\0';
4754       http->port = atoi(q);
4755    }
4756    else
4757    {
4758       http->port = 443;
4759    }
4760
4761    /* Rebuild request URL */
4762    freez(http->url);
4763    http->url = strdup_or_die(http->path);
4764
4765    log_error(LOG_LEVEL_HEADER,
4766       "Destination extracted from \"Host\" header. New request URL: %s",
4767       http->url);
4768
4769    /*
4770     * Regenerate request line in "proxy format"
4771     * to make rewrites more convenient.
4772     */
4773    assert(http->cmd != NULL);
4774    freez(http->cmd);
4775    http->cmd = strdup_or_die(http->gpc);
4776    string_append(&http->cmd, " ");
4777    string_append(&http->cmd, http->url);
4778    string_append(&http->cmd, " ");
4779    string_append(&http->cmd, http->version);
4780    if (http->cmd == NULL)
4781    {
4782       return JB_ERR_MEMORY;
4783    }
4784
4785    return JB_ERR_OK;
4786
4787 }
4788 #endif /* def FEATURE_HTTPS_INSPECTION */
4789
4790
4791 /*********************************************************************
4792  *
4793  * Function    :  create_forged_referrer
4794  *
4795  * Description :  Helper for client_referrer to forge a referer as
4796  *                'http://hostname[:port]/' to fool stupid
4797  *                checks for in-site links
4798  *
4799  * Parameters  :
4800  *          1  :  header   = Pointer to header pointer
4801  *          2  :  hostport = Host and optionally port as string
4802  *
4803  * Returns     :  JB_ERR_OK in case of success, or
4804  *                JB_ERR_MEMORY in case of memory problems.
4805  *
4806  *********************************************************************/
4807 static jb_err create_forged_referrer(char **header, const char *hostport)
4808 {
4809     assert(NULL == *header);
4810
4811     *header = strdup("Referer: http://");
4812     string_append(header, hostport);
4813     string_append(header, "/");
4814
4815     if (NULL == *header)
4816     {
4817        return JB_ERR_MEMORY;
4818     }
4819
4820     log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4821
4822     return JB_ERR_OK;
4823
4824 }
4825
4826
4827 /*********************************************************************
4828  *
4829  * Function    :  create_fake_referrer
4830  *
4831  * Description :  Helper for client_referrer to create a fake referrer
4832  *                based on a string supplied by the user.
4833  *
4834  * Parameters  :
4835  *          1  :  header   = Pointer to header pointer
4836  *          2  :  hosthost = Referrer to fake
4837  *
4838  * Returns     :  JB_ERR_OK in case of success, or
4839  *                JB_ERR_MEMORY in case of memory problems.
4840  *
4841  *********************************************************************/
4842 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4843 {
4844    assert(NULL == *header);
4845
4846    if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4847    {
4848       log_error(LOG_LEVEL_HEADER,
4849          "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4850    }
4851    *header = strdup("Referer: ");
4852    string_append(header, fake_referrer);
4853
4854    if (NULL == *header)
4855    {
4856       return JB_ERR_MEMORY;
4857    }
4858
4859    log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4860
4861    return JB_ERR_OK;
4862
4863 }
4864
4865
4866 /*********************************************************************
4867  *
4868  * Function    :  handle_conditional_hide_referrer_parameter
4869  *
4870  * Description :  Helper for client_referrer to crunch or forge
4871  *                the referrer header if the host has changed.
4872  *
4873  * Parameters  :
4874  *          1  :  header = Pointer to header pointer
4875  *          2  :  host   = The target host (may include the port)
4876  *          3  :  parameter_conditional_block = Boolean to signal
4877  *                if we're in conditional-block mode. If not set,
4878  *                we're in conditional-forge mode.
4879  *
4880  * Returns     :  JB_ERR_OK in case of success, or
4881  *                JB_ERR_MEMORY in case of memory problems.
4882  *
4883  *********************************************************************/
4884 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4885    const char *host, const int parameter_conditional_block)
4886 {
4887    char *referer = strdup_or_die(*header);
4888    const size_t hostlength = strlen(host);
4889    const char *referer_url = NULL;
4890
4891    /* referer begins with 'Referer: http[s]://' */
4892    if ((hostlength+17) < strlen(referer))
4893    {
4894       /*
4895        * Shorten referer to make sure the referer is blocked
4896        * if www.example.org/www.example.com-shall-see-the-referer/
4897        * links to www.example.com/
4898        */
4899       referer[hostlength+17] = '\0';
4900    }
4901    referer_url = strstr(referer, "http://");
4902    if (NULL == referer_url)
4903    {
4904       referer_url = strstr(referer, "https://");
4905    }
4906    if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4907    {
4908       /* Host has changed, Referer is invalid or a https URL. */
4909       if (parameter_conditional_block)
4910       {
4911          log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4912          freez(*header);
4913       }
4914       else
4915       {
4916          freez(*header);
4917          freez(referer);
4918          return create_forged_referrer(header, host);
4919       }
4920    }
4921    freez(referer);
4922
4923    return JB_ERR_OK;
4924
4925 }
4926
4927
4928 /*********************************************************************
4929  *
4930  * Function    :  create_content_length_header
4931  *
4932  * Description :  Creates a Content-Length header.
4933  *
4934  * Parameters  :
4935  *          1  :  content_length = The content length to be used in the header.
4936  *          2  :  header = Allocated space to safe the header.
4937  *          3  :  buffer_length = The length of the allocated space.
4938  *
4939  * Returns     :  void
4940  *
4941  *********************************************************************/
4942 static void create_content_length_header(unsigned long long content_length,
4943                                          char *header, size_t buffer_length)
4944 {
4945 #ifdef _WIN32
4946 #if SIZEOF_LONG_LONG < 8
4947 #error sizeof(unsigned long long) too small
4948 #endif
4949    snprintf(header, buffer_length, "Content-Length: %I64u", content_length);
4950 #else
4951    snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4952 #endif
4953 }
4954
4955
4956 /*********************************************************************
4957  *
4958  * Function    :  get_expected_content_length
4959  *
4960  * Description :  Figures out the content length from a list of headers.
4961  *
4962  * Parameters  :
4963  *          1  :  headers = List of headers
4964  *
4965  * Returns     :  Number of bytes to expect
4966  *
4967  *********************************************************************/
4968 unsigned long long get_expected_content_length(struct list *headers)
4969 {
4970    const char *content_length_header;
4971    unsigned long long content_length = 0;
4972
4973    content_length_header = get_header_value(headers, "Content-Length:");
4974    if (content_length_header != NULL)
4975    {
4976       if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4977       {
4978          log_error(LOG_LEVEL_ERROR,
4979             "Failed to get the Content-Length in %s", content_length_header);
4980          /* XXX: The header will be removed later on */
4981          return 0;
4982       }
4983    }
4984
4985    return content_length;
4986 }
4987
4988
4989 /*
4990   Local Variables:
4991   tab-width: 3
4992   end:
4993 */