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