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