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