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