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