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