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