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