b5644ef0cfcae0eb7ad60d69e3dd9f5cadd360b5
[privoxy.git] / parsers.c
1 const char parsers_rcs[] = "$Id: parsers.c,v 1.281 2013/12/24 13:34:22 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       char *modified_tag = NULL;
1312       char *tag = header;
1313       size_t size = header_length;
1314       pcrs_job *joblist;
1315
1316       b = get_filter(csp, tag_name->str, wanted_filter_type);
1317       if (b == NULL)
1318       {
1319          continue;
1320       }
1321
1322       joblist = b->joblist;
1323
1324       if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1325
1326       if (NULL == joblist)
1327       {
1328          log_error(LOG_LEVEL_RE_FILTER,
1329             "Tagger %s has empty joblist. Nothing to do.", b->name);
1330          continue;
1331       }
1332
1333       /* execute their pcrs_joblist on the header. */
1334       for (job = joblist; NULL != job; job = job->next)
1335       {
1336          const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1337
1338          if (0 < hits)
1339          {
1340             /* Success, continue with the modified version. */
1341             if (tag != header)
1342             {
1343                freez(tag);
1344             }
1345             tag = modified_tag;
1346          }
1347          else
1348          {
1349             /* Tagger doesn't match */
1350             if (0 > hits)
1351             {
1352                /* Regex failure, log it but continue anyway. */
1353                assert(NULL != header);
1354                log_error(LOG_LEVEL_ERROR,
1355                   "Problems with tagger \'%s\' and header \'%s\': %s",
1356                   b->name, *header, pcrs_strerror(hits));
1357             }
1358             freez(modified_tag);
1359          }
1360       }
1361
1362       if (b->dynamic) pcrs_free_joblist(joblist);
1363
1364       /* If this tagger matched */
1365       if (tag != header)
1366       {
1367          if (0 == size)
1368          {
1369             /*
1370              * There is no technical limitation which makes
1371              * it impossible to use empty tags, but I assume
1372              * no one would do it intentionally.
1373              */
1374             freez(tag);
1375             log_error(LOG_LEVEL_INFO,
1376                "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1377             continue;
1378          }
1379
1380          if (!list_contains_item(csp->tags, tag))
1381          {
1382             if (JB_ERR_OK != enlist(csp->tags, tag))
1383             {
1384                log_error(LOG_LEVEL_ERROR,
1385                   "Insufficient memory to add tag \'%s\', "
1386                   "based on tagger \'%s\' and header \'%s\'",
1387                   tag, b->name, *header);
1388             }
1389             else
1390             {
1391                char *action_message;
1392                /*
1393                 * update the action bits right away, to make
1394                 * tagging based on tags set by earlier taggers
1395                 * of the same kind possible.
1396                 */
1397                if (update_action_bits_for_tag(csp, tag))
1398                {
1399                   action_message = "Action bits updated accordingly.";
1400                }
1401                else
1402                {
1403                   action_message = "No action bits update necessary.";
1404                }
1405
1406                log_error(LOG_LEVEL_HEADER,
1407                   "Tagger \'%s\' added tag \'%s\'. %s",
1408                   b->name, tag, action_message);
1409             }
1410          }
1411          else
1412          {
1413             /* XXX: Is this log-worthy? */
1414             log_error(LOG_LEVEL_HEADER,
1415                "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1416                b->name, tag);
1417          }
1418          freez(tag);
1419       }
1420    }
1421
1422    return JB_ERR_OK;
1423 }
1424
1425 /* here begins the family of parser functions that reformat header lines */
1426
1427 /*********************************************************************
1428  *
1429  * Function    :  filter_header
1430  *
1431  * Description :  Executes all text substitutions from all applying
1432  *                +(server|client)-header-filter actions on the header.
1433  *                Most of the code was copied from pcrs_filter_response,
1434  *                including the rather short variable names
1435  *
1436  * Parameters  :
1437  *          1  :  csp = Current client state (buffers, headers, etc...)
1438  *          2  :  header = On input, pointer to header to modify.
1439  *                On output, pointer to the modified header, or NULL
1440  *                to remove the header.  This function frees the
1441  *                original string if necessary.
1442  *
1443  * Returns     :  JB_ERR_OK on success and always succeeds
1444  *
1445  *********************************************************************/
1446 static jb_err filter_header(struct client_state *csp, char **header)
1447 {
1448    int hits=0;
1449    int matches;
1450    size_t size = strlen(*header);
1451
1452    char *newheader = NULL;
1453    pcrs_job *job;
1454
1455    struct re_filterfile_spec *b;
1456    struct list_entry *filtername;
1457
1458    int wanted_filter_type;
1459    int multi_action_index;
1460
1461    if (csp->flags & CSP_FLAG_NO_FILTERING)
1462    {
1463       return JB_ERR_OK;
1464    }
1465
1466    if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1467    {
1468       wanted_filter_type = FT_SERVER_HEADER_FILTER;
1469       multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1470    }
1471    else
1472    {
1473       wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1474       multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1475    }
1476
1477    if (list_is_empty(csp->action->multi[multi_action_index])
1478       || filters_available(csp) == FALSE)
1479    {
1480       /* Return early if no filters apply or if none are available. */
1481       return JB_ERR_OK;
1482    }
1483
1484    /* Execute all applying header filters */
1485    for (filtername = csp->action->multi[multi_action_index]->first;
1486         filtername != NULL; filtername = filtername->next)
1487    {
1488       int current_hits = 0;
1489       pcrs_job *joblist;
1490
1491       b = get_filter(csp, filtername->str, wanted_filter_type);
1492       if (b == NULL)
1493       {
1494          continue;
1495       }
1496
1497       joblist = b->joblist;
1498
1499       if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1500
1501       if (NULL == joblist)
1502       {
1503          log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1504          continue;
1505       }
1506
1507       log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1508          *header, size, b->name);
1509
1510       /* Apply all jobs from the joblist */
1511       for (job = joblist; NULL != job; job = job->next)
1512       {
1513          matches = pcrs_execute(job, *header, size, &newheader, &size);
1514          if (0 < matches)
1515          {
1516             current_hits += matches;
1517             log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1518             freez(*header);
1519             *header = newheader;
1520          }
1521          else if (0 == matches)
1522          {
1523             /* Filter doesn't change header */
1524             freez(newheader);
1525          }
1526          else
1527          {
1528             /* RegEx failure */
1529             log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1530                *header, b->name, pcrs_strerror(matches));
1531             if (newheader != NULL)
1532             {
1533                log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1534                freez(newheader);
1535             }
1536          }
1537       }
1538
1539       if (b->dynamic) pcrs_free_joblist(joblist);
1540
1541       log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1542       hits += current_hits;
1543    }
1544
1545    /*
1546     * Additionally checking for hits is important because if
1547     * the continue hack is triggered, server headers can
1548     * arrive empty to separate multiple heads from each other.
1549     */
1550    if ((0 == size) && hits)
1551    {
1552       log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1553       freez(*header);
1554    }
1555
1556    return JB_ERR_OK;
1557 }
1558
1559
1560 /*********************************************************************
1561  *
1562  * Function    :  server_connection
1563  *
1564  * Description :  Makes sure a proper "Connection:" header is
1565  *                set and signals connection_header_adder to
1566  *                do nothing.
1567  *
1568  * Parameters  :
1569  *          1  :  csp = Current client state (buffers, headers, etc...)
1570  *          2  :  header = On input, pointer to header to modify.
1571  *                On output, pointer to the modified header, or NULL
1572  *                to remove the header.  This function frees the
1573  *                original string if necessary.
1574  *
1575  * Returns     :  JB_ERR_OK on success.
1576  *
1577  *********************************************************************/
1578 static jb_err server_connection(struct client_state *csp, char **header)
1579 {
1580    if (!strcmpic(*header, "Connection: keep-alive")
1581 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1582     && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1583 #endif
1584      )
1585    {
1586 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1587       if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1588       {
1589          csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1590       }
1591
1592       if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1593       {
1594          log_error(LOG_LEVEL_HEADER,
1595             "Keeping the server header '%s' around.", *header);
1596       }
1597       else
1598 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1599       {
1600          char *old_header = *header;
1601
1602          *header = strdup_or_die("Connection: close");
1603          log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1604          freez(old_header);
1605       }
1606    }
1607
1608    /* Signal server_connection_adder() to return early. */
1609    csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1610
1611    return JB_ERR_OK;
1612 }
1613
1614
1615 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1616 /*********************************************************************
1617  *
1618  * Function    :  server_keep_alive
1619  *
1620  * Description :  Stores the server's keep alive timeout.
1621  *
1622  * Parameters  :
1623  *          1  :  csp = Current client state (buffers, headers, etc...)
1624  *          2  :  header = On input, pointer to header to modify.
1625  *                On output, pointer to the modified header, or NULL
1626  *                to remove the header.  This function frees the
1627  *                original string if necessary.
1628  *
1629  * Returns     :  JB_ERR_OK.
1630  *
1631  *********************************************************************/
1632 static jb_err server_keep_alive(struct client_state *csp, char **header)
1633 {
1634    unsigned int keep_alive_timeout;
1635    const char *timeout_position = strstr(*header, "timeout=");
1636
1637    if ((NULL == timeout_position)
1638     || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1639    {
1640       log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1641    }
1642    else
1643    {
1644       if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1645       {
1646          log_error(LOG_LEVEL_HEADER,
1647             "Reducing keep-alive timeout from %u to %u.",
1648             csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1649          csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1650       }
1651       else
1652       {
1653          /* XXX: Is this log worthy? */
1654          log_error(LOG_LEVEL_HEADER,
1655             "Server keep-alive timeout is %u. Sticking with %u.",
1656             keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1657       }
1658       csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1659    }
1660
1661    return JB_ERR_OK;
1662 }
1663
1664
1665 /*********************************************************************
1666  *
1667  * Function    :  server_proxy_connection
1668  *
1669  * Description :  Figures out whether or not we should add a
1670  *                Proxy-Connection header.
1671  *
1672  * Parameters  :
1673  *          1  :  csp = Current client state (buffers, headers, etc...)
1674  *          2  :  header = On input, pointer to header to modify.
1675  *                On output, pointer to the modified header, or NULL
1676  *                to remove the header.  This function frees the
1677  *                original string if necessary.
1678  *
1679  * Returns     :  JB_ERR_OK.
1680  *
1681  *********************************************************************/
1682 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1683 {
1684    csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1685    return JB_ERR_OK;
1686 }
1687
1688
1689 /*********************************************************************
1690  *
1691  * Function    :  proxy_authentication
1692  *
1693  * Description :  Removes headers that are relevant for proxy
1694  *                authentication unless forwarding them has
1695  *                been explicitly requested.
1696  *
1697  * Parameters  :
1698  *          1  :  csp = Current client state (buffers, headers, etc...)
1699  *          2  :  header = On input, pointer to header to modify.
1700  *                On output, pointer to the modified header, or NULL
1701  *                to remove the header.  This function frees the
1702  *                original string if necessary.
1703  *
1704  * Returns     :  JB_ERR_OK.
1705  *
1706  *********************************************************************/
1707 static jb_err proxy_authentication(struct client_state *csp, char **header)
1708 {
1709    if ((csp->config->feature_flags &
1710       RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1711       log_error(LOG_LEVEL_HEADER,
1712          "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1713       freez(*header);
1714    }
1715    return JB_ERR_OK;
1716 }
1717
1718
1719 /*********************************************************************
1720  *
1721  * Function    :  client_keep_alive
1722  *
1723  * Description :  Stores the client's keep alive timeout.
1724  *
1725  * Parameters  :
1726  *          1  :  csp = Current client state (buffers, headers, etc...)
1727  *          2  :  header = On input, pointer to header to modify.
1728  *                On output, pointer to the modified header, or NULL
1729  *                to remove the header.  This function frees the
1730  *                original string if necessary.
1731  *
1732  * Returns     :  JB_ERR_OK.
1733  *
1734  *********************************************************************/
1735 static jb_err client_keep_alive(struct client_state *csp, char **header)
1736 {
1737    unsigned int keep_alive_timeout;
1738    const char *timeout_position = strstr(*header, ": ");
1739
1740    if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1741    {
1742       log_error(LOG_LEVEL_HEADER,
1743          "keep-alive support is disabled. Crunching: %s.", *header);
1744       freez(*header);
1745       return JB_ERR_OK;
1746    }
1747
1748    if ((NULL == timeout_position)
1749     || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1750    {
1751       log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1752    }
1753    else
1754    {
1755       if (keep_alive_timeout < csp->config->keep_alive_timeout)
1756       {
1757          log_error(LOG_LEVEL_HEADER,
1758             "Reducing keep-alive timeout from %u to %u.",
1759             csp->config->keep_alive_timeout, keep_alive_timeout);
1760          csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1761       }
1762       else
1763       {
1764          /* XXX: Is this log worthy? */
1765          log_error(LOG_LEVEL_HEADER,
1766             "Client keep-alive timeout is %u. Sticking with %u.",
1767             keep_alive_timeout, csp->config->keep_alive_timeout);
1768       }
1769    }
1770
1771    return JB_ERR_OK;
1772 }
1773
1774
1775 /*********************************************************************
1776  *
1777  * Function    :  get_content_length
1778  *
1779  * Description :  Gets the content length specified in a
1780  *                Content-Length header.
1781  *
1782  * Parameters  :
1783  *          1  :  header_value = The Content-Length header value.
1784  *          2  :  length = Storage to return the value.
1785  *
1786  * Returns     :  JB_ERR_OK on success, or
1787  *                JB_ERR_PARSE if no value is recognized.
1788  *
1789  *********************************************************************/
1790 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1791 {
1792 #ifdef _WIN32
1793    assert(sizeof(unsigned long long) > 4);
1794    if (1 != sscanf(header_value, "%I64u", length))
1795 #else
1796    if (1 != sscanf(header_value, "%llu", length))
1797 #endif
1798    {
1799       return JB_ERR_PARSE;
1800    }
1801
1802    return JB_ERR_OK;
1803 }
1804
1805
1806 /*********************************************************************
1807  *
1808  * Function    :  client_save_content_length
1809  *
1810  * Description :  Save the Content-Length sent by the client.
1811  *
1812  * Parameters  :
1813  *          1  :  csp = Current client state (buffers, headers, etc...)
1814  *          2  :  header = On input, pointer to header to modify.
1815  *                On output, pointer to the modified header, or NULL
1816  *                to remove the header.  This function frees the
1817  *                original string if necessary.
1818  *
1819  * Returns     :  JB_ERR_OK on success, or
1820  *                JB_ERR_MEMORY on out-of-memory error.
1821  *
1822  *********************************************************************/
1823 static jb_err client_save_content_length(struct client_state *csp, char **header)
1824 {
1825    unsigned long long content_length = 0;
1826    const char *header_value;
1827
1828    assert(*(*header+14) == ':');
1829
1830    header_value = *header + 15;
1831    if (JB_ERR_OK != get_content_length(header_value, &content_length))
1832    {
1833       log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1834       freez(*header);
1835    }
1836    else
1837    {
1838       csp->expected_client_content_length = content_length;
1839    }
1840
1841    return JB_ERR_OK;
1842 }
1843 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1844
1845
1846
1847 /*********************************************************************
1848  *
1849  * Function    :  client_connection
1850  *
1851  * Description :  Makes sure a proper "Connection:" header is
1852  *                set and signals connection_header_adder
1853  *                to do nothing.
1854  *
1855  * Parameters  :
1856  *          1  :  csp = Current client state (buffers, headers, etc...)
1857  *          2  :  header = On input, pointer to header to modify.
1858  *                On output, pointer to the modified header, or NULL
1859  *                to remove the header.  This function frees the
1860  *                original string if necessary.
1861  *
1862  * Returns     :  JB_ERR_OK on success.
1863  *
1864  *********************************************************************/
1865 static jb_err client_connection(struct client_state *csp, char **header)
1866 {
1867    static const char connection_close[] = "Connection: close";
1868
1869    if (!strcmpic(*header, connection_close))
1870    {
1871 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1872       if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1873         && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1874       {
1875           if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1876           {
1877              log_error(LOG_LEVEL_HEADER,
1878                 "Removing \'%s\' to imply keep-alive.", *header);
1879              freez(*header);
1880              /*
1881               * While we imply keep-alive to the server,
1882               * we have to remember that the client didn't.
1883               */
1884              csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1885           }
1886           else
1887           {
1888              char *old_header = *header;
1889
1890              *header = strdup_or_die("Connection: keep-alive");
1891              log_error(LOG_LEVEL_HEADER,
1892                 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1893              freez(old_header);
1894           }
1895       }
1896       else
1897       {
1898          log_error(LOG_LEVEL_HEADER,
1899             "Keeping the client header '%s' around. "
1900             "The connection will not be kept alive.",
1901             *header);
1902          csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1903       }
1904    }
1905    else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1906         && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1907    {
1908       log_error(LOG_LEVEL_HEADER,
1909          "Keeping the client header '%s' around. "
1910          "The server connection will be kept alive if possible.",
1911          *header);
1912       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1913 #endif  /* def FEATURE_CONNECTION_KEEP_ALIVE */
1914    }
1915    else
1916    {
1917       char *old_header = *header;
1918
1919       *header = strdup_or_die(connection_close);
1920       log_error(LOG_LEVEL_HEADER,
1921          "Replaced: \'%s\' with \'%s\'", old_header, *header);
1922       freez(old_header);
1923    }
1924
1925    /* Signal client_connection_header_adder() to return early. */
1926    csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1927
1928    return JB_ERR_OK;
1929 }
1930
1931
1932 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1933 /*********************************************************************
1934  *
1935  * Function    :  client_proxy_connection
1936  *
1937  * Description :  Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
1938  *                appropriate and removes the Proxy-Connection
1939  *                header.
1940  *
1941  * Parameters  :
1942  *          1  :  csp = Current client state (buffers, headers, etc...)
1943  *          2  :  header = On input, pointer to header to modify.
1944  *                On output, pointer to the modified header, or NULL
1945  *                to remove the header.  This function frees the
1946  *                original string if necessary.
1947  *
1948  * Returns     :  JB_ERR_OK
1949  *
1950  *********************************************************************/
1951 static jb_err client_proxy_connection(struct client_state *csp, char **header)
1952 {
1953    if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1954       && (csp->http->ssl == 0)
1955       && (NULL == strstr(*header, "close")))
1956    {
1957       log_error(LOG_LEVEL_HEADER,
1958          "The client connection can be kept alive due to: %s", *header);
1959       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1960    }
1961    crumble(csp, header);
1962
1963    return JB_ERR_OK;
1964 }
1965 #endif  /* def FEATURE_CONNECTION_KEEP_ALIVE */
1966
1967
1968 /*********************************************************************
1969  *
1970  * Function    :  client_transfer_encoding
1971  *
1972  * Description :  Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
1973  *                the request body is "chunked"
1974  *
1975  *                XXX: Currently not called through sed() as we
1976  *                     need the flag earlier on. Should be fixed.
1977  *
1978  * Parameters  :
1979  *          1  :  csp = Current client state (buffers, headers, etc...)
1980  *          2  :  header = On input, pointer to header to modify.
1981  *                On output, pointer to the modified header, or NULL
1982  *                to remove the header.  This function frees the
1983  *                original string if necessary.
1984  *
1985  * Returns     :  JB_ERR_OK on success, or
1986  *
1987  *********************************************************************/
1988 jb_err client_transfer_encoding(struct client_state *csp, char **header)
1989 {
1990    if (strstr(*header, "chunked"))
1991    {
1992       csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
1993       log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
1994    }
1995
1996    return JB_ERR_OK;
1997 }
1998
1999
2000 /*********************************************************************
2001  *
2002  * Function    :  crumble
2003  *
2004  * Description :  This is called if a header matches a pattern to "crunch"
2005  *
2006  * Parameters  :
2007  *          1  :  csp = Current client state (buffers, headers, etc...)
2008  *          2  :  header = On input, pointer to header to modify.
2009  *                On output, pointer to the modified header, or NULL
2010  *                to remove the header.  This function frees the
2011  *                original string if necessary.
2012  *
2013  * Returns     :  JB_ERR_OK on success, or
2014  *                JB_ERR_MEMORY on out-of-memory error.
2015  *
2016  *********************************************************************/
2017 static jb_err crumble(struct client_state *csp, char **header)
2018 {
2019    (void)csp;
2020    log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2021    freez(*header);
2022    return JB_ERR_OK;
2023 }
2024
2025
2026 /*********************************************************************
2027  *
2028  * Function    :  crunch_server_header
2029  *
2030  * Description :  Crunch server header if it matches a string supplied by the
2031  *                user. Called from `sed'.
2032  *
2033  * Parameters  :
2034  *          1  :  csp = Current client state (buffers, headers, etc...)
2035  *          2  :  header = On input, pointer to header to modify.
2036  *                On output, pointer to the modified header, or NULL
2037  *                to remove the header.  This function frees the
2038  *                original string if necessary.
2039  *
2040  * Returns     :  JB_ERR_OK on success and always succeeds
2041  *
2042  *********************************************************************/
2043 static jb_err crunch_server_header(struct client_state *csp, char **header)
2044 {
2045    const char *crunch_pattern;
2046
2047    /* Do we feel like crunching? */
2048    if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2049    {
2050       crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2051
2052       /* Is the current header the lucky one? */
2053       if (strstr(*header, crunch_pattern))
2054       {
2055          log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2056          freez(*header);
2057       }
2058    }
2059
2060    return JB_ERR_OK;
2061 }
2062
2063
2064 /*********************************************************************
2065  *
2066  * Function    :  server_content_type
2067  *
2068  * Description :  Set the content-type for filterable types (text/.*,
2069  *                .*xml.*, .*script.* and image/gif) unless filtering has been
2070  *                forbidden (CT_TABOO) while parsing earlier headers.
2071  *                NOTE: Since text/plain is commonly used by web servers
2072  *                      for files whose correct type is unknown, we don't
2073  *                      set CT_TEXT for it.
2074  *
2075  * Parameters  :
2076  *          1  :  csp = Current client state (buffers, headers, etc...)
2077  *          2  :  header = On input, pointer to header to modify.
2078  *                On output, pointer to the modified header, or NULL
2079  *                to remove the header.  This function frees the
2080  *                original string if necessary.
2081  *
2082  * Returns     :  JB_ERR_OK on success, or
2083  *                JB_ERR_MEMORY on out-of-memory error.
2084  *
2085  *********************************************************************/
2086 static jb_err server_content_type(struct client_state *csp, char **header)
2087 {
2088    /* Remove header if it isn't the first Content-Type header */
2089    if ((csp->content_type & CT_DECLARED))
2090    {
2091       if (content_filters_enabled(csp->action))
2092       {
2093          /*
2094           * Making sure the client interprets the content the same way
2095           * Privoxy did is only relevant if Privoxy modified it.
2096           *
2097           * Checking for this is "hard" as it's not yet known when
2098           * this function is called, thus go shopping and and just
2099           * check if Privoxy could filter it.
2100           *
2101           * The main thing is that we don't mess with the headers
2102           * unless the user signalled that it's acceptable.
2103           */
2104          log_error(LOG_LEVEL_HEADER,
2105             "Multiple Content-Type headers detected. "
2106             "Removing and ignoring: %s",
2107             *header);
2108          freez(*header);
2109       }
2110       return JB_ERR_OK;
2111    }
2112
2113    /*
2114     * Signal that the Content-Type has been set.
2115     */
2116    csp->content_type |= CT_DECLARED;
2117
2118    if (!(csp->content_type & CT_TABOO))
2119    {
2120       /*
2121        * XXX: The assumption that text/plain is a sign of
2122        * binary data seems to be somewhat unreasonable nowadays
2123        * and should be dropped after 3.0.8 is out.
2124        */
2125       if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2126         || strstr(*header, "xml")
2127         || strstr(*header, "script"))
2128       {
2129          csp->content_type |= CT_TEXT;
2130       }
2131       else if (strstr(*header, "image/gif"))
2132       {
2133          csp->content_type |= CT_GIF;
2134       }
2135    }
2136
2137    /*
2138     * Are we messing with the content type?
2139     */
2140    if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2141    {
2142       /*
2143        * Make sure the user doesn't accidentally
2144        * change the content type of binary documents.
2145        */
2146       if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2147       {
2148          freez(*header);
2149          *header = strdup_or_die("Content-Type: ");
2150          string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2151
2152          if (header == NULL)
2153          {
2154             log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2155             return JB_ERR_MEMORY;
2156          }
2157          log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2158       }
2159       else
2160       {
2161          log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2162             "It doesn't look like a content type that should be filtered. "
2163             "Enable force-text-mode if you know what you're doing.", *header);
2164       }
2165    }
2166
2167    return JB_ERR_OK;
2168 }
2169
2170
2171 /*********************************************************************
2172  *
2173  * Function    :  server_transfer_coding
2174  *
2175  * Description :  - Prohibit filtering (CT_TABOO) if transfer coding compresses
2176  *                - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2177  *                - Remove header if body was chunked but has been
2178  *                  de-chunked for filtering.
2179  *
2180  * Parameters  :
2181  *          1  :  csp = Current client state (buffers, headers, etc...)
2182  *          2  :  header = On input, pointer to header to modify.
2183  *                On output, pointer to the modified header, or NULL
2184  *                to remove the header.  This function frees the
2185  *                original string if necessary.
2186  *
2187  * Returns     :  JB_ERR_OK on success, or
2188  *                JB_ERR_MEMORY on out-of-memory error.
2189  *
2190  *********************************************************************/
2191 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2192 {
2193    /*
2194     * Turn off pcrs and gif filtering if body compressed
2195     */
2196    if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2197    {
2198 #ifdef FEATURE_ZLIB
2199       /*
2200        * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2201        */
2202       log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2203          csp->http->cmd, *header);
2204 #endif /* def FEATURE_ZLIB */
2205       csp->content_type = CT_TABOO;
2206    }
2207
2208    /*
2209     * Raise flag if body chunked
2210     */
2211    if (strstr(*header, "chunked"))
2212    {
2213       csp->flags |= CSP_FLAG_CHUNKED;
2214
2215       /*
2216        * If the body was modified, it has been de-chunked first
2217        * and the header must be removed.
2218        *
2219        * FIXME: If there is more than one transfer encoding,
2220        * only the "chunked" part should be removed here.
2221        */
2222       if (csp->flags & CSP_FLAG_MODIFIED)
2223       {
2224          log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2225          freez(*header);
2226       }
2227    }
2228
2229    return JB_ERR_OK;
2230 }
2231
2232
2233 /*********************************************************************
2234  *
2235  * Function    :  server_content_encoding
2236  *
2237  * Description :  Used to check if the content is compressed, and if
2238  *                FEATURE_ZLIB is disabled, filtering is disabled as
2239  *                well.
2240  *
2241  *                If FEATURE_ZLIB is enabled and the compression type
2242  *                supported, the content is marked for decompression.
2243  *
2244  *                XXX: Doesn't properly deal with multiple or with
2245  *                     unsupported but unknown encodings.
2246  *                     Is case-sensitive but shouldn't be.
2247  *
2248  * Parameters  :
2249  *          1  :  csp = Current client state (buffers, headers, etc...)
2250  *          2  :  header = On input, pointer to header to modify.
2251  *                On output, pointer to the modified header, or NULL
2252  *                to remove the header.  This function frees the
2253  *                original string if necessary.
2254  *
2255  * Returns     :  JB_ERR_OK on success, or
2256  *                JB_ERR_MEMORY on out-of-memory error.
2257  *
2258  *********************************************************************/
2259 static jb_err server_content_encoding(struct client_state *csp, char **header)
2260 {
2261 #ifdef FEATURE_ZLIB
2262    if (strstr(*header, "sdch"))
2263    {
2264       /*
2265        * Shared Dictionary Compression over HTTP isn't supported,
2266        * filtering it anyway is pretty much guaranteed to mess up
2267        * the encoding.
2268        */
2269       csp->content_type |= CT_TABOO;
2270
2271       /*
2272        * Log a warning if the user expects the content to be filtered.
2273        */
2274       if ((csp->rlist != NULL) &&
2275          (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2276       {
2277          log_error(LOG_LEVEL_INFO,
2278             "SDCH-compressed content detected, content filtering disabled. "
2279             "Consider suppressing SDCH offers made by the client.");
2280       }
2281    }
2282    else if (strstr(*header, "gzip"))
2283    {
2284       /* Mark for gzip decompression */
2285       csp->content_type |= CT_GZIP;
2286    }
2287    else if (strstr(*header, "deflate"))
2288    {
2289       /* Mark for zlib decompression */
2290       csp->content_type |= CT_DEFLATE;
2291    }
2292    else if (strstr(*header, "compress"))
2293    {
2294       /*
2295        * We can't decompress this; therefore we can't filter
2296        * it either.
2297        */
2298       csp->content_type |= CT_TABOO;
2299    }
2300 #else /* !defined(FEATURE_ZLIB) */
2301    /*
2302     * XXX: Using a black list here isn't the right approach.
2303     *
2304     *      In case of SDCH, building with zlib support isn't
2305     *      going to help.
2306     */
2307    if (strstr(*header, "gzip") ||
2308        strstr(*header, "compress") ||
2309        strstr(*header, "deflate") ||
2310        strstr(*header, "sdch"))
2311    {
2312       /*
2313        * Body is compressed, turn off pcrs and gif filtering.
2314        */
2315       csp->content_type |= CT_TABOO;
2316
2317       /*
2318        * Log a warning if the user expects the content to be filtered.
2319        */
2320       if ((csp->rlist != NULL) &&
2321          (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2322       {
2323          log_error(LOG_LEVEL_INFO,
2324             "Compressed content detected, content filtering disabled. "
2325             "Consider recompiling Privoxy with zlib support or "
2326             "enable the prevent-compression action.");
2327       }
2328    }
2329 #endif /* defined(FEATURE_ZLIB) */
2330
2331    return JB_ERR_OK;
2332
2333 }
2334
2335
2336 #ifdef FEATURE_ZLIB
2337 /*********************************************************************
2338  *
2339  * Function    :  server_adjust_content_encoding
2340  *
2341  * Description :  Remove the Content-Encoding header if the
2342  *                decompression was successful and the content
2343  *                has been modifed.
2344  *
2345  * Parameters  :
2346  *          1  :  csp = Current client state (buffers, headers, etc...)
2347  *          2  :  header = On input, pointer to header to modify.
2348  *                On output, pointer to the modified header, or NULL
2349  *                to remove the header.  This function frees the
2350  *                original string if necessary.
2351  *
2352  * Returns     :  JB_ERR_OK on success, or
2353  *                JB_ERR_MEMORY on out-of-memory error.
2354  *
2355  *********************************************************************/
2356 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2357 {
2358    if ((csp->flags & CSP_FLAG_MODIFIED)
2359     && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2360    {
2361       /*
2362        * We successfully decompressed the content,
2363        * and have to clean the header now, so the
2364        * client no longer expects compressed data.
2365        *
2366        * XXX: There is a difference between cleaning
2367        * and removing it completely.
2368        */
2369       log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2370       freez(*header);
2371    }
2372
2373    return JB_ERR_OK;
2374
2375 }
2376 #endif /* defined(FEATURE_ZLIB) */
2377
2378
2379 /*********************************************************************
2380  *
2381  * Function    :  server_adjust_content_length
2382  *
2383  * Description :  Adjust Content-Length header if we modified
2384  *                the body.
2385  *
2386  * Parameters  :
2387  *          1  :  csp = Current client state (buffers, headers, etc...)
2388  *          2  :  header = On input, pointer to header to modify.
2389  *                On output, pointer to the modified header, or NULL
2390  *                to remove the header.  This function frees the
2391  *                original string if necessary.
2392  *
2393  * Returns     :  JB_ERR_OK on success, or
2394  *                JB_ERR_MEMORY on out-of-memory error.
2395  *
2396  *********************************************************************/
2397 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2398 {
2399    /* Regenerate header if the content was modified. */
2400    if (csp->flags & CSP_FLAG_MODIFIED)
2401    {
2402       const size_t header_length = 50;
2403       freez(*header);
2404       *header = malloc(header_length);
2405       if (*header == NULL)
2406       {
2407          return JB_ERR_MEMORY;
2408       }
2409       create_content_length_header(csp->content_length, *header, header_length);
2410       log_error(LOG_LEVEL_HEADER,
2411          "Adjusted Content-Length to %llu", csp->content_length);
2412    }
2413
2414    return JB_ERR_OK;
2415 }
2416
2417
2418 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2419 /*********************************************************************
2420  *
2421  * Function    :  server_save_content_length
2422  *
2423  * Description :  Save the Content-Length sent by the server.
2424  *
2425  * Parameters  :
2426  *          1  :  csp = Current client state (buffers, headers, etc...)
2427  *          2  :  header = On input, pointer to header to modify.
2428  *                On output, pointer to the modified header, or NULL
2429  *                to remove the header.  This function frees the
2430  *                original string if necessary.
2431  *
2432  * Returns     :  JB_ERR_OK on success, or
2433  *                JB_ERR_MEMORY on out-of-memory error.
2434  *
2435  *********************************************************************/
2436 static jb_err server_save_content_length(struct client_state *csp, char **header)
2437 {
2438    unsigned long long content_length = 0;
2439    const char *header_value;
2440
2441    assert(*(*header+14) == ':');
2442
2443    header_value = *header + 15;
2444    if (JB_ERR_OK != get_content_length(header_value, &content_length))
2445    {
2446       log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2447       freez(*header);
2448    }
2449    else
2450    {
2451       csp->expected_content_length = content_length;
2452       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2453       csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2454    }
2455
2456    return JB_ERR_OK;
2457 }
2458 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2459
2460
2461 /*********************************************************************
2462  *
2463  * Function    :  server_content_md5
2464  *
2465  * Description :  Crumble any Content-MD5 headers if the document was
2466  *                modified. FIXME: Should we re-compute instead?
2467  *
2468  * Parameters  :
2469  *          1  :  csp = Current client state (buffers, headers, etc...)
2470  *          2  :  header = On input, pointer to header to modify.
2471  *                On output, pointer to the modified header, or NULL
2472  *                to remove the header.  This function frees the
2473  *                original string if necessary.
2474  *
2475  * Returns     :  JB_ERR_OK on success, or
2476  *                JB_ERR_MEMORY on out-of-memory error.
2477  *
2478  *********************************************************************/
2479 static jb_err server_content_md5(struct client_state *csp, char **header)
2480 {
2481    if (csp->flags & CSP_FLAG_MODIFIED)
2482    {
2483       log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2484       freez(*header);
2485    }
2486
2487    return JB_ERR_OK;
2488 }
2489
2490
2491 /*********************************************************************
2492  *
2493  * Function    :  server_content_disposition
2494  *
2495  * Description :  If enabled, blocks or modifies the "Content-Disposition" header.
2496  *                Called from `sed'.
2497  *
2498  * Parameters  :
2499  *          1  :  csp = Current client state (buffers, headers, etc...)
2500  *          2  :  header = On input, pointer to header to modify.
2501  *                On output, pointer to the modified header, or NULL
2502  *                to remove the header.  This function frees the
2503  *                original string if necessary.
2504  *
2505  * Returns     :  JB_ERR_OK on success, or
2506  *                JB_ERR_MEMORY on out-of-memory error.
2507  *
2508  *********************************************************************/
2509 static jb_err server_content_disposition(struct client_state *csp, char **header)
2510 {
2511    const char *newval;
2512
2513    /*
2514     * Are we messing with the Content-Disposition header?
2515     */
2516    if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2517    {
2518       /* Me tinks not */
2519       return JB_ERR_OK;
2520    }
2521
2522    newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2523
2524    if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2525    {
2526       /*
2527        * Blocking content-disposition header
2528        */
2529       log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2530       freez(*header);
2531       return JB_ERR_OK;
2532    }
2533    else
2534    {
2535       /*
2536        * Replacing Content-Disposition header
2537        */
2538       freez(*header);
2539       *header = strdup("Content-Disposition: ");
2540       string_append(header, newval);
2541
2542       if (*header != NULL)
2543       {
2544          log_error(LOG_LEVEL_HEADER,
2545             "Content-Disposition header crunched and replaced with: %s", *header);
2546       }
2547    }
2548    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2549 }
2550
2551
2552 /*********************************************************************
2553  *
2554  * Function    :  server_last_modified
2555  *
2556  * Description :  Changes Last-Modified header to the actual date
2557  *                to help hide-if-modified-since.
2558  *                Called from `sed'.
2559  *
2560  * Parameters  :
2561  *          1  :  csp = Current client state (buffers, headers, etc...)
2562  *          2  :  header = On input, pointer to header to modify.
2563  *                On output, pointer to the modified header, or NULL
2564  *                to remove the header.  This function frees the
2565  *                original string if necessary.
2566  *
2567  * Returns     :  JB_ERR_OK on success, or
2568  *                JB_ERR_MEMORY on out-of-memory error.
2569  *
2570  *********************************************************************/
2571 static jb_err server_last_modified(struct client_state *csp, char **header)
2572 {
2573    const char *newval;
2574    time_t last_modified;
2575    char newheader[50];
2576
2577    /*
2578     * Are we messing with the Last-Modified header?
2579     */
2580    if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2581    {
2582       /*Nope*/
2583       return JB_ERR_OK;
2584    }
2585
2586    newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2587
2588    if (0 == strcmpic(newval, "block"))
2589    {
2590       /*
2591        * Blocking Last-Modified header. Useless but why not.
2592        */
2593       log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2594       freez(*header);
2595       return JB_ERR_OK;
2596    }
2597    else if (0 == strcmpic(newval, "reset-to-request-time"))
2598    {
2599       /*
2600        * Setting Last-Modified Header to now.
2601        */
2602       char buf[30];
2603       get_http_time(0, buf, sizeof(buf));
2604       freez(*header);
2605       *header = strdup("Last-Modified: ");
2606       string_append(header, buf);
2607
2608       if (*header == NULL)
2609       {
2610          log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2611       }
2612       else
2613       {
2614          log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2615       }
2616    }
2617    else if (0 == strcmpic(newval, "randomize"))
2618    {
2619       const char *header_time = *header + sizeof("Last-Modified:");
2620
2621       log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2622
2623       if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2624       {
2625          log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2626          freez(*header);
2627       }
2628       else
2629       {
2630          time_t now;
2631          struct tm *timeptr = NULL;
2632          long int rtime;
2633 #ifdef HAVE_GMTIME_R
2634          struct tm gmt;
2635 #endif
2636          now = time(NULL);
2637          rtime = (long int)difftime(now, last_modified);
2638          if (rtime)
2639          {
2640             long int days, hours, minutes, seconds;
2641             const int negative_delta = (rtime < 0);
2642
2643             if (negative_delta)
2644             {
2645                rtime *= -1;
2646                log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2647             }
2648             rtime = pick_from_range(rtime);
2649             if (negative_delta)
2650             {
2651                rtime *= -1;
2652             }
2653             last_modified += rtime;
2654 #ifdef HAVE_GMTIME_R
2655             timeptr = gmtime_r(&last_modified, &gmt);
2656 #elif defined(MUTEX_LOCKS_AVAILABLE)
2657             privoxy_mutex_lock(&gmtime_mutex);
2658             timeptr = gmtime(&last_modified);
2659             privoxy_mutex_unlock(&gmtime_mutex);
2660 #else
2661             timeptr = gmtime(&last_modified);
2662 #endif
2663             if ((NULL == timeptr) || !strftime(newheader,
2664                   sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2665             {
2666                log_error(LOG_LEVEL_ERROR,
2667                   "Randomizing '%s' failed. Crunching the header without replacement.",
2668                   *header);
2669                freez(*header);
2670                return JB_ERR_OK;
2671             }
2672
2673             freez(*header);
2674             *header = strdup("Last-Modified: ");
2675             string_append(header, newheader);
2676
2677             if (*header == NULL)
2678             {
2679                log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2680                return JB_ERR_MEMORY;
2681             }
2682
2683             days    = rtime / (3600 * 24);
2684             hours   = rtime / 3600 % 24;
2685             minutes = rtime / 60 % 60;
2686             seconds = rtime % 60;
2687
2688             log_error(LOG_LEVEL_HEADER,
2689                "Randomized:  %s (added %d da%s %d hou%s %d minut%s %d second%s",
2690                *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2691                minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2692          }
2693          else
2694          {
2695             log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2696          }
2697       }
2698    }
2699
2700    return JB_ERR_OK;
2701 }
2702
2703
2704 /*********************************************************************
2705  *
2706  * Function    :  client_accept_encoding
2707  *
2708  * Description :  Rewrite the client's Accept-Encoding header so that
2709  *                if doesn't allow compression, if the action applies.
2710  *                Note: For HTTP/1.0 the absence of the header is enough.
2711  *
2712  * Parameters  :
2713  *          1  :  csp = Current client state (buffers, headers, etc...)
2714  *          2  :  header = On input, pointer to header to modify.
2715  *                On output, pointer to the modified header, or NULL
2716  *                to remove the header.  This function frees the
2717  *                original string if necessary.
2718  *
2719  * Returns     :  JB_ERR_OK on success, or
2720  *                JB_ERR_MEMORY on out-of-memory error.
2721  *
2722  *********************************************************************/
2723 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2724 {
2725 #ifdef FEATURE_COMPRESSION
2726    if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2727       && strstr(*header, "deflate"))
2728    {
2729       csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2730    }
2731 #endif
2732    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2733    {
2734       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2735       freez(*header);
2736    }
2737
2738    return JB_ERR_OK;
2739 }
2740
2741
2742 /*********************************************************************
2743  *
2744  * Function    :  client_te
2745  *
2746  * Description :  Rewrite the client's TE header so that
2747  *                if doesn't allow compression, if the action applies.
2748  *
2749  * Parameters  :
2750  *          1  :  csp = Current client state (buffers, headers, etc...)
2751  *          2  :  header = On input, pointer to header to modify.
2752  *                On output, pointer to the modified header, or NULL
2753  *                to remove the header.  This function frees the
2754  *                original string if necessary.
2755  *
2756  * Returns     :  JB_ERR_OK on success, or
2757  *                JB_ERR_MEMORY on out-of-memory error.
2758  *
2759  *********************************************************************/
2760 static jb_err client_te(struct client_state *csp, char **header)
2761 {
2762    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2763    {
2764       freez(*header);
2765       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2766    }
2767
2768    return JB_ERR_OK;
2769 }
2770
2771
2772 /*********************************************************************
2773  *
2774  * Function    :  client_referrer
2775  *
2776  * Description :  Handle the "referer" config setting properly.
2777  *                Called from `sed'.
2778  *
2779  * Parameters  :
2780  *          1  :  csp = Current client state (buffers, headers, etc...)
2781  *          2  :  header = On input, pointer to header to modify.
2782  *                On output, pointer to the modified header, or NULL
2783  *                to remove the header.  This function frees the
2784  *                original string if necessary.
2785  *
2786  * Returns     :  JB_ERR_OK on success, or
2787  *                JB_ERR_MEMORY on out-of-memory error.
2788  *
2789  *********************************************************************/
2790 static jb_err client_referrer(struct client_state *csp, char **header)
2791 {
2792    const char *parameter;
2793    /* booleans for parameters we have to check multiple times */
2794    int parameter_conditional_block;
2795    int parameter_conditional_forge;
2796
2797 #ifdef FEATURE_FORCE_LOAD
2798    /*
2799     * Since the referrer can include the prefix even
2800     * if the request itself is non-forced, we must
2801     * clean it unconditionally.
2802     *
2803     * XXX: strclean is too broad
2804     */
2805    strclean(*header, FORCE_PREFIX);
2806 #endif /* def FEATURE_FORCE_LOAD */
2807
2808    if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2809    {
2810       /* Nothing left to do */
2811       return JB_ERR_OK;
2812    }
2813
2814    parameter = csp->action->string[ACTION_STRING_REFERER];
2815    assert(parameter != NULL);
2816    parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2817    parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2818
2819    if (!parameter_conditional_block && !parameter_conditional_forge)
2820    {
2821       /*
2822        * As conditional-block and conditional-forge are the only
2823        * parameters that rely on the original referrer, we can
2824        * remove it now for all the others.
2825        */
2826       freez(*header);
2827    }
2828
2829    if (0 == strcmpic(parameter, "block"))
2830    {
2831       log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2832       return JB_ERR_OK;
2833    }
2834    else if (parameter_conditional_block || parameter_conditional_forge)
2835    {
2836       return handle_conditional_hide_referrer_parameter(header,
2837          csp->http->hostport, parameter_conditional_block);
2838    }
2839    else if (0 == strcmpic(parameter, "forge"))
2840    {
2841       return create_forged_referrer(header, csp->http->hostport);
2842    }
2843    else
2844    {
2845       /* interpret parameter as user-supplied referer to fake */
2846       return create_fake_referrer(header, parameter);
2847    }
2848 }
2849
2850
2851 /*********************************************************************
2852  *
2853  * Function    :  client_accept_language
2854  *
2855  * Description :  Handle the "Accept-Language" config setting properly.
2856  *                Called from `sed'.
2857  *
2858  * Parameters  :
2859  *          1  :  csp = Current client state (buffers, headers, etc...)
2860  *          2  :  header = On input, pointer to header to modify.
2861  *                On output, pointer to the modified header, or NULL
2862  *                to remove the header.  This function frees the
2863  *                original string if necessary.
2864  *
2865  * Returns     :  JB_ERR_OK on success, or
2866  *                JB_ERR_MEMORY on out-of-memory error.
2867  *
2868  *********************************************************************/
2869 static jb_err client_accept_language(struct client_state *csp, char **header)
2870 {
2871    const char *newval;
2872
2873    /*
2874     * Are we messing with the Accept-Language?
2875     */
2876    if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2877    {
2878       /*I don't think so*/
2879       return JB_ERR_OK;
2880    }
2881
2882    newval = csp->action->string[ACTION_STRING_LANGUAGE];
2883
2884    if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2885    {
2886       /*
2887        * Blocking Accept-Language header
2888        */
2889       log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2890       freez(*header);
2891       return JB_ERR_OK;
2892    }
2893    else
2894    {
2895       /*
2896        * Replacing Accept-Language header
2897        */
2898       freez(*header);
2899       *header = strdup("Accept-Language: ");
2900       string_append(header, newval);
2901
2902       if (*header == NULL)
2903       {
2904          log_error(LOG_LEVEL_ERROR,
2905             "Insufficient memory. Accept-Language header crunched without replacement.");
2906       }
2907       else
2908       {
2909          log_error(LOG_LEVEL_HEADER,
2910             "Accept-Language header crunched and replaced with: %s", *header);
2911       }
2912    }
2913    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2914 }
2915
2916
2917 /*********************************************************************
2918  *
2919  * Function    :  crunch_client_header
2920  *
2921  * Description :  Crunch client header if it matches a string supplied by the
2922  *                user. Called from `sed'.
2923  *
2924  * Parameters  :
2925  *          1  :  csp = Current client state (buffers, headers, etc...)
2926  *          2  :  header = On input, pointer to header to modify.
2927  *                On output, pointer to the modified header, or NULL
2928  *                to remove the header.  This function frees the
2929  *                original string if necessary.
2930  *
2931  * Returns     :  JB_ERR_OK on success and always succeeds
2932  *
2933  *********************************************************************/
2934 static jb_err crunch_client_header(struct client_state *csp, char **header)
2935 {
2936    const char *crunch_pattern;
2937
2938    /* Do we feel like crunching? */
2939    if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2940    {
2941       crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2942
2943       /* Is the current header the lucky one? */
2944       if (strstr(*header, crunch_pattern))
2945       {
2946          log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2947          freez(*header);
2948       }
2949    }
2950    return JB_ERR_OK;
2951 }
2952
2953
2954 /*********************************************************************
2955  *
2956  * Function    :  client_uagent
2957  *
2958  * Description :  Handle the "user-agent" config setting properly
2959  *                and remember its original value to enable browser
2960  *                bug workarounds. Called from `sed'.
2961  *
2962  * Parameters  :
2963  *          1  :  csp = Current client state (buffers, headers, etc...)
2964  *          2  :  header = On input, pointer to header to modify.
2965  *                On output, pointer to the modified header, or NULL
2966  *                to remove the header.  This function frees the
2967  *                original string if necessary.
2968  *
2969  * Returns     :  JB_ERR_OK on success, or
2970  *                JB_ERR_MEMORY on out-of-memory error.
2971  *
2972  *********************************************************************/
2973 static jb_err client_uagent(struct client_state *csp, char **header)
2974 {
2975    const char *newval;
2976
2977    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2978    {
2979       return JB_ERR_OK;
2980    }
2981
2982    newval = csp->action->string[ACTION_STRING_USER_AGENT];
2983    if (newval == NULL)
2984    {
2985       return JB_ERR_OK;
2986    }
2987
2988    freez(*header);
2989    *header = strdup("User-Agent: ");
2990    string_append(header, newval);
2991
2992    log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2993
2994    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2995 }
2996
2997
2998 /*********************************************************************
2999  *
3000  * Function    :  client_ua
3001  *
3002  * Description :  Handle "ua-" headers properly.  Called from `sed'.
3003  *
3004  * Parameters  :
3005  *          1  :  csp = Current client state (buffers, headers, etc...)
3006  *          2  :  header = On input, pointer to header to modify.
3007  *                On output, pointer to the modified header, or NULL
3008  *                to remove the header.  This function frees the
3009  *                original string if necessary.
3010  *
3011  * Returns     :  JB_ERR_OK on success, or
3012  *                JB_ERR_MEMORY on out-of-memory error.
3013  *
3014  *********************************************************************/
3015 static jb_err client_ua(struct client_state *csp, char **header)
3016 {
3017    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3018    {
3019       log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3020       freez(*header);
3021    }
3022
3023    return JB_ERR_OK;
3024 }
3025
3026
3027 /*********************************************************************
3028  *
3029  * Function    :  client_from
3030  *
3031  * Description :  Handle the "from" config setting properly.
3032  *                Called from `sed'.
3033  *
3034  * Parameters  :
3035  *          1  :  csp = Current client state (buffers, headers, etc...)
3036  *          2  :  header = On input, pointer to header to modify.
3037  *                On output, pointer to the modified header, or NULL
3038  *                to remove the header.  This function frees the
3039  *                original string if necessary.
3040  *
3041  * Returns     :  JB_ERR_OK on success, or
3042  *                JB_ERR_MEMORY on out-of-memory error.
3043  *
3044  *********************************************************************/
3045 static jb_err client_from(struct client_state *csp, char **header)
3046 {
3047    const char *newval;
3048
3049    if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3050    {
3051       return JB_ERR_OK;
3052    }
3053
3054    freez(*header);
3055
3056    newval = csp->action->string[ACTION_STRING_FROM];
3057
3058    /*
3059     * Are we blocking the e-mail address?
3060     */
3061    if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3062    {
3063       log_error(LOG_LEVEL_HEADER, "crunched From!");
3064       return JB_ERR_OK;
3065    }
3066
3067    log_error(LOG_LEVEL_HEADER, " modified");
3068
3069    *header = strdup("From: ");
3070    string_append(header, newval);
3071
3072    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3073 }
3074
3075
3076 /*********************************************************************
3077  *
3078  * Function    :  client_send_cookie
3079  *
3080  * Description :  Crunches the "cookie" header if necessary.
3081  *                Called from `sed'.
3082  *
3083  *                XXX: Stupid name, doesn't send squat.
3084  *
3085  * Parameters  :
3086  *          1  :  csp = Current client state (buffers, headers, etc...)
3087  *          2  :  header = On input, pointer to header to modify.
3088  *                On output, pointer to the modified header, or NULL
3089  *                to remove the header.  This function frees the
3090  *                original string if necessary.
3091  *
3092  * Returns     :  JB_ERR_OK on success, or
3093  *                JB_ERR_MEMORY on out-of-memory error.
3094  *
3095  *********************************************************************/
3096 static jb_err client_send_cookie(struct client_state *csp, char **header)
3097 {
3098    if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3099    {
3100       log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3101       freez(*header);
3102    }
3103
3104    return JB_ERR_OK;
3105 }
3106
3107
3108 /*********************************************************************
3109  *
3110  * Function    :  client_x_forwarded
3111  *
3112  * Description :  Handle the "x-forwarded-for" config setting properly,
3113  *                also used in the add_client_headers list.  Called from `sed'.
3114  *
3115  * Parameters  :
3116  *          1  :  csp = Current client state (buffers, headers, etc...)
3117  *          2  :  header = On input, pointer to header to modify.
3118  *                On output, pointer to the modified header, or NULL
3119  *                to remove the header.  This function frees the
3120  *                original string if necessary.
3121  *
3122  * Returns     :  JB_ERR_OK on success, or
3123  *                JB_ERR_MEMORY on out-of-memory error.
3124  *
3125  *********************************************************************/
3126 jb_err client_x_forwarded(struct client_state *csp, char **header)
3127 {
3128    if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3129    {
3130       const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3131
3132       if (0 == strcmpic(parameter, "block"))
3133       {
3134          freez(*header);
3135          log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3136       }
3137       else if (0 == strcmpic(parameter, "add"))
3138       {
3139          string_append(header, ", ");
3140          string_append(header, csp->ip_addr_str);
3141
3142          if (*header == NULL)
3143          {
3144             return JB_ERR_MEMORY;
3145          }
3146          log_error(LOG_LEVEL_HEADER,
3147             "Appended client IP address to %s", *header);
3148          csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3149       }
3150       else
3151       {
3152          log_error(LOG_LEVEL_FATAL,
3153             "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3154       }
3155    }
3156
3157    return JB_ERR_OK;
3158 }
3159
3160
3161 /*********************************************************************
3162  *
3163  * Function    :  client_max_forwards
3164  *
3165  * Description :  If the HTTP method is OPTIONS or TRACE, subtract one
3166  *                from the value of the Max-Forwards header field.
3167  *
3168  * Parameters  :
3169  *          1  :  csp = Current client state (buffers, headers, etc...)
3170  *          2  :  header = On input, pointer to header to modify.
3171  *                On output, pointer to the modified header, or NULL
3172  *                to remove the header.  This function frees the
3173  *                original string if necessary.
3174  *
3175  * Returns     :  JB_ERR_OK on success, or
3176  *                JB_ERR_MEMORY on out-of-memory error.
3177  *
3178  *********************************************************************/
3179 static jb_err client_max_forwards(struct client_state *csp, char **header)
3180 {
3181    int max_forwards;
3182
3183    if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3184        (0 == strcmpic(csp->http->gpc, "options")))
3185    {
3186       assert(*(*header+12) == ':');
3187       if (1 == sscanf(*header+12, ": %d", &max_forwards))
3188       {
3189          if (max_forwards > 0)
3190          {
3191             snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3192             log_error(LOG_LEVEL_HEADER,
3193                "Max-Forwards value for %s request reduced to %d.",
3194                csp->http->gpc, max_forwards);
3195          }
3196          else if (max_forwards < 0)
3197          {
3198             log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3199             freez(*header);
3200          }
3201       }
3202       else
3203       {
3204          log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3205          freez(*header);
3206       }
3207    }
3208
3209    return JB_ERR_OK;
3210 }
3211
3212
3213 /*********************************************************************
3214  *
3215  * Function    :  client_host
3216  *
3217  * Description :  If the request URI did not contain host and
3218  *                port information, parse and evaluate the Host
3219  *                header field.
3220  *
3221  * Parameters  :
3222  *          1  :  csp = Current client state (buffers, headers, etc...)
3223  *          2  :  header = On input, pointer to header to modify.
3224  *                On output, pointer to the modified header, or NULL
3225  *                to remove the header.  This function frees the
3226  *                original string if necessary.
3227  *
3228  * Returns     :  JB_ERR_OK on success, or
3229  *                JB_ERR_MEMORY on out-of-memory error.
3230  *
3231  *********************************************************************/
3232 static jb_err client_host(struct client_state *csp, char **header)
3233 {
3234    char *p, *q;
3235
3236    if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3237        *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3238    {
3239
3240       p = strdup_or_die((*header)+6);
3241       chomp(p);
3242       q = strdup_or_die(p);
3243
3244       freez(csp->http->hostport);
3245       csp->http->hostport = p;
3246       freez(csp->http->host);
3247       csp->http->host = q;
3248       q = strchr(csp->http->host, ':');
3249       if (q != NULL)
3250       {
3251          /* Terminate hostname and evaluate port string */
3252          *q++ = '\0';
3253          csp->http->port = atoi(q);
3254       }
3255       else
3256       {
3257          csp->http->port = csp->http->ssl ? 443 : 80;
3258       }
3259
3260       log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3261                 csp->http->hostport, csp->http->host, csp->http->port);
3262    }
3263
3264    /* Signal client_host_adder() to return right away */
3265    csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3266
3267    return JB_ERR_OK;
3268 }
3269
3270
3271 /*********************************************************************
3272  *
3273  * Function    :  client_if_modified_since
3274  *
3275  * Description :  Remove or modify the If-Modified-Since header.
3276  *
3277  * Parameters  :
3278  *          1  :  csp = Current client state (buffers, headers, etc...)
3279  *          2  :  header = On input, pointer to header to modify.
3280  *                On output, pointer to the modified header, or NULL
3281  *                to remove the header.  This function frees the
3282  *                original string if necessary.
3283  *
3284  * Returns     :  JB_ERR_OK on success, or
3285  *                JB_ERR_MEMORY on out-of-memory error.
3286  *
3287  *********************************************************************/
3288 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3289 {
3290    char newheader[50];
3291 #ifdef HAVE_GMTIME_R
3292    struct tm gmt;
3293 #endif
3294    struct tm *timeptr = NULL;
3295    time_t tm = 0;
3296    const char *newval;
3297    char * endptr;
3298
3299    if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3300    {
3301       /*
3302        * The client got an error message because of a temporary problem,
3303        * the problem is gone and the client now tries to revalidate our
3304        * error message on the real server. The revalidation would always
3305        * end with the transmission of the whole document and there is
3306        * no need to expose the bogus If-Modified-Since header.
3307        */
3308       log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3309       freez(*header);
3310    }
3311    else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3312    {
3313       newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3314
3315       if ((0 == strcmpic(newval, "block")))
3316       {
3317          log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3318          freez(*header);
3319       }
3320       else /* add random value */
3321       {
3322          const char *header_time = *header + sizeof("If-Modified-Since:");
3323
3324          if (JB_ERR_OK != parse_header_time(header_time, &tm))
3325          {
3326             log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3327             freez(*header);
3328          }
3329          else
3330          {
3331             long int hours, minutes, seconds;
3332             long int rtime = strtol(newval, &endptr, 0);
3333             const int negative_range = (rtime < 0);
3334
3335             if (rtime)
3336             {
3337                log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3338                   *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3339                if (negative_range)
3340                {
3341                   rtime *= -1;
3342                }
3343                rtime *= 60;
3344                rtime = pick_from_range(rtime);
3345             }
3346             else
3347             {
3348                log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3349                   *header);
3350             }
3351             tm += rtime * (negative_range ? -1 : 1);
3352 #ifdef HAVE_GMTIME_R
3353             timeptr = gmtime_r(&tm, &gmt);
3354 #elif defined(MUTEX_LOCKS_AVAILABLE)
3355             privoxy_mutex_lock(&gmtime_mutex);
3356             timeptr = gmtime(&tm);
3357             privoxy_mutex_unlock(&gmtime_mutex);
3358 #else
3359             timeptr = gmtime(&tm);
3360 #endif
3361             if ((NULL == timeptr) || !strftime(newheader,
3362                   sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3363             {
3364                log_error(LOG_LEVEL_ERROR,
3365                   "Randomizing '%s' failed. Crunching the header without replacement.",
3366                   *header);
3367                freez(*header);
3368                return JB_ERR_OK;
3369             }
3370
3371             freez(*header);
3372             *header = strdup("If-Modified-Since: ");
3373             string_append(header, newheader);
3374
3375             if (*header == NULL)
3376             {
3377                log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3378                return JB_ERR_MEMORY;
3379             }
3380
3381             hours   = rtime / 3600;
3382             minutes = rtime / 60 % 60;
3383             seconds = rtime % 60;
3384
3385             log_error(LOG_LEVEL_HEADER,
3386                "Randomized:  %s (%s %d hou%s %d minut%s %d second%s",
3387                *header, (negative_range) ? "subtracted" : "added", hours,
3388                (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3389                seconds, (seconds == 1) ? ")" : "s)");
3390          }
3391       }
3392    }
3393
3394    return JB_ERR_OK;
3395 }
3396
3397
3398 /*********************************************************************
3399  *
3400  * Function    :  client_if_none_match
3401  *
3402  * Description :  Remove the If-None-Match header.
3403  *
3404  * Parameters  :
3405  *          1  :  csp = Current client state (buffers, headers, etc...)
3406  *          2  :  header = On input, pointer to header to modify.
3407  *                On output, pointer to the modified header, or NULL
3408  *                to remove the header.  This function frees the
3409  *                original string if necessary.
3410  *
3411  * Returns     :  JB_ERR_OK on success, or
3412  *                JB_ERR_MEMORY on out-of-memory error.
3413  *
3414  *********************************************************************/
3415 static jb_err client_if_none_match(struct client_state *csp, char **header)
3416 {
3417    if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3418    {
3419       log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3420       freez(*header);
3421    }
3422
3423    return JB_ERR_OK;
3424 }
3425
3426
3427 /*********************************************************************
3428  *
3429  * Function    :  client_x_filter
3430  *
3431  * Description :  Disables filtering if the client set "X-Filter: No".
3432  *                Called from `sed'.
3433  *
3434  * Parameters  :
3435  *          1  :  csp = Current client state (buffers, headers, etc...)
3436  *          2  :  header = On input, pointer to header to modify.
3437  *                On output, pointer to the modified header, or NULL
3438  *                to remove the header.  This function frees the
3439  *                original string if necessary.
3440  *
3441  * Returns     :  JB_ERR_OK on success
3442  *
3443  *********************************************************************/
3444 jb_err client_x_filter(struct client_state *csp, char **header)
3445 {
3446    if (0 == strcmpic(*header, "X-Filter: No"))
3447    {
3448       if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3449       {
3450          log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3451       }
3452       else
3453       {
3454          if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3455          {
3456             log_error(LOG_LEVEL_HEADER,
3457                "force-text-mode overruled the client's request to fetch without filtering!");
3458          }
3459          else
3460          {
3461             csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3462             csp->flags |= CSP_FLAG_NO_FILTERING;
3463             log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3464          }
3465          log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3466          freez(*header);
3467       }
3468    }
3469    return JB_ERR_OK;
3470 }
3471
3472
3473 /*********************************************************************
3474  *
3475  * Function    :  client_range
3476  *
3477  * Description :  Removes Range, Request-Range and If-Range headers if
3478  *                content filtering is enabled and the range doesn't
3479  *                start at byte 0.
3480  *
3481  *                If the client's version of the document has been
3482  *                altered by Privoxy, the server could interpret the
3483  *                range differently than the client intended in which
3484  *                case the user could end up with corrupted content.
3485  *
3486  *                If the range starts at byte 0 this isn't an issue
3487  *                so the header can pass. Partial requests like this
3488  *                are used to render preview images for videos without
3489  *                downloading the whole video.
3490  *
3491  *                While HTTP doesn't require that range requests are
3492  *                honoured and the client could simply abort the download
3493  *                after receiving a sufficient amount of data, various
3494  *                clients don't handle complete responses to range
3495  *                requests gracefully and emit misleading error messages
3496  *                instead.
3497  *
3498  * Parameters  :
3499  *          1  :  csp = Current client state (buffers, headers, etc...)
3500  *          2  :  header = On input, pointer to header to modify.
3501  *                On output, pointer to the modified header, or NULL
3502  *                to remove the header.  This function frees the
3503  *                original string if necessary.
3504  *
3505  * Returns     :  JB_ERR_OK
3506  *
3507  *********************************************************************/
3508 static jb_err client_range(struct client_state *csp, char **header)
3509 {
3510    if (content_filters_enabled(csp->action)
3511       && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3512    {
3513       log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3514          " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3515       freez(*header);
3516    }
3517
3518    return JB_ERR_OK;
3519 }
3520
3521 /* the following functions add headers directly to the header list */
3522
3523 /*********************************************************************
3524  *
3525  * Function    :  client_host_adder
3526  *
3527  * Description :  Adds the Host: header field if it is missing.
3528  *                Called from `sed'.
3529  *
3530  * Parameters  :
3531  *          1  :  csp = Current client state (buffers, headers, etc...)
3532  *
3533  * Returns     :  JB_ERR_OK on success, or
3534  *                JB_ERR_MEMORY on out-of-memory error.
3535  *
3536  *********************************************************************/
3537 static jb_err client_host_adder(struct client_state *csp)
3538 {
3539    char *p;
3540    jb_err err;
3541
3542    if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3543    {
3544       /* Header already set by the client, nothing to do. */
3545       return JB_ERR_OK;
3546    }
3547
3548    if (!csp->http->hostport || !*(csp->http->hostport))
3549    {
3550       /* XXX: When does this happen and why is it OK? */
3551       log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3552       return JB_ERR_OK;
3553    }
3554
3555    /*
3556     * remove 'user:pass@' from 'proto://user:pass@host'
3557     */
3558    if ((p = strchr( csp->http->hostport, '@')) != NULL)
3559    {
3560       p++;
3561    }
3562    else
3563    {
3564       p = csp->http->hostport;
3565    }
3566
3567    /* XXX: Just add it, we already made sure that it will be unique */
3568    log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3569    err = enlist_unique_header(csp->headers, "Host", p);
3570    return err;
3571
3572 }
3573
3574
3575 /*********************************************************************
3576  *
3577  * Function    :  client_xtra_adder
3578  *
3579  * Description :  Used in the add_client_headers list.  Called from `sed'.
3580  *
3581  * Parameters  :
3582  *          1  :  csp = Current client state (buffers, headers, etc...)
3583  *
3584  * Returns     :  JB_ERR_OK on success, or
3585  *                JB_ERR_MEMORY on out-of-memory error.
3586  *
3587  *********************************************************************/
3588 static jb_err client_xtra_adder(struct client_state *csp)
3589 {
3590    struct list_entry *lst;
3591    jb_err err;
3592
3593    for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3594         lst ; lst = lst->next)
3595    {
3596       log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3597       err = enlist(csp->headers, lst->str);
3598       if (err)
3599       {
3600          return err;
3601       }
3602
3603    }
3604
3605    return JB_ERR_OK;
3606 }
3607
3608
3609 /*********************************************************************
3610  *
3611  * Function    :  client_x_forwarded_for_adder
3612  *
3613  * Description :  Used in the add_client_headers list.  Called from `sed'.
3614  *
3615  * Parameters  :
3616  *          1  :  csp = Current client state (buffers, headers, etc...)
3617  *
3618  * Returns     :  JB_ERR_OK on success, or
3619  *                JB_ERR_MEMORY on out-of-memory error.
3620  *
3621  *********************************************************************/
3622 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3623 {
3624    char *header = NULL;
3625    jb_err err;
3626
3627    if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3628          && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3629       || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3630    {
3631       /*
3632        * If we aren't adding X-Forwarded-For headers,
3633        * or we already appended an existing X-Forwarded-For
3634        * header, there's nothing left to do here.
3635        */
3636       return JB_ERR_OK;
3637    }
3638
3639    header = strdup("X-Forwarded-For: ");
3640    string_append(&header, csp->ip_addr_str);
3641
3642    if (header == NULL)
3643    {
3644       return JB_ERR_MEMORY;
3645    }
3646
3647    log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3648    err = enlist(csp->headers, header);
3649    freez(header);
3650
3651    return err;
3652 }
3653
3654
3655 /*********************************************************************
3656  *
3657  * Function    :  server_connection_adder
3658  *
3659  * Description :  Adds an appropriate "Connection:" header to csp->headers
3660  *                unless the header was already present. Called from `sed'.
3661  *
3662  * Parameters  :
3663  *          1  :  csp = Current client state (buffers, headers, etc...)
3664  *
3665  * Returns     :  JB_ERR_OK on success, or
3666  *                JB_ERR_MEMORY on out-of-memory error.
3667  *
3668  *********************************************************************/
3669 static jb_err server_connection_adder(struct client_state *csp)
3670 {
3671    const unsigned int flags = csp->flags;
3672    const char *response_status_line = csp->headers->first->str;
3673    static const char connection_close[] = "Connection: close";
3674
3675    if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3676     && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3677    {
3678       return JB_ERR_OK;
3679    }
3680
3681    /*
3682     * XXX: if we downgraded the response, this check will fail.
3683     */
3684    if ((csp->config->feature_flags &
3685         RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3686     && (NULL != response_status_line)
3687     && !strncmpic(response_status_line, "HTTP/1.1", 8)
3688 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3689     && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3690 #endif
3691       )
3692    {
3693       log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3694          "without Connection header implies keep-alive.");
3695       csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3696       return JB_ERR_OK;
3697    }
3698
3699    log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3700
3701    return enlist(csp->headers, connection_close);
3702 }
3703
3704
3705 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3706 /*********************************************************************
3707  *
3708  * Function    :  server_proxy_connection_adder
3709  *
3710  * Description :  Adds a "Proxy-Connection: keep-alive" header to
3711  *                csp->headers when appropriate.
3712  *
3713  * Parameters  :
3714  *          1  :  csp = Current client state (buffers, headers, etc...)
3715  *
3716  * Returns     :  JB_ERR_OK on success, or
3717  *                JB_ERR_MEMORY on out-of-memory error.
3718  *
3719  *********************************************************************/
3720 static jb_err server_proxy_connection_adder(struct client_state *csp)
3721 {
3722    static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3723    jb_err err = JB_ERR_OK;
3724
3725    if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3726     && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3727     && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3728     && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3729        || (csp->flags & CSP_FLAG_CHUNKED)))
3730    {
3731       log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3732       err = enlist(csp->headers, proxy_connection_header);
3733    }
3734
3735    return err;
3736 }
3737 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3738
3739
3740 /*********************************************************************
3741  *
3742  * Function    :  client_connection_header_adder
3743  *
3744  * Description :  Adds a proper "Connection:" header to csp->headers
3745  *                unless the header was already present. Called from `sed'.
3746  *
3747  * Parameters  :
3748  *          1  :  csp = Current client state (buffers, headers, etc...)
3749  *
3750  * Returns     :  JB_ERR_OK on success, or
3751  *                JB_ERR_MEMORY on out-of-memory error.
3752  *
3753  *********************************************************************/
3754 static jb_err client_connection_header_adder(struct client_state *csp)
3755 {
3756    static const char connection_close[] = "Connection: close";
3757
3758    if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3759      && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3760    {
3761       return JB_ERR_OK;
3762    }
3763
3764 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3765    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3766       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3767       && (csp->http->ssl == 0)
3768       && !strcmpic(csp->http->ver, "HTTP/1.1"))
3769    {
3770       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3771       return JB_ERR_OK;
3772    }
3773 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3774
3775    log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3776
3777    return enlist(csp->headers, connection_close);
3778 }
3779
3780
3781 /*********************************************************************
3782  *
3783  * Function    :  server_http
3784  *
3785  * Description :  - Save the HTTP Status into csp->http->status
3786  *                - Set CT_TABOO to prevent filtering if the answer
3787  *                  is a partial range (HTTP status 206)
3788  *                - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3789  *                  action applies.
3790  *
3791  * Parameters  :
3792  *          1  :  csp = Current client state (buffers, headers, etc...)
3793  *          2  :  header = On input, pointer to header to modify.
3794  *                On output, pointer to the modified header, or NULL
3795  *                to remove the header.  This function frees the
3796  *                original string if necessary.
3797  *
3798  * Returns     :  JB_ERR_OK on success, or
3799  *                JB_ERR_MEMORY on out-of-memory error.
3800  *
3801  *********************************************************************/
3802 static jb_err server_http(struct client_state *csp, char **header)
3803 {
3804    sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3805    if (csp->http->status == 206)
3806    {
3807       csp->content_type = CT_TABOO;
3808    }
3809
3810    if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3811    {
3812       /* XXX: Should we do a real validity check here? */
3813       if (strlen(*header) > 8)
3814       {
3815          (*header)[7] = '0';
3816          log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3817       }
3818       else
3819       {
3820          /*
3821           * XXX: Should we block the request or
3822           * enlist a valid status code line here?
3823           */
3824          log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3825             "Downgrading to HTTP/1.0 impossible.");
3826       }
3827    }
3828
3829    return JB_ERR_OK;
3830 }
3831
3832 /*********************************************************************
3833  *
3834  * Function    :  add_cooky_expiry_date
3835  *
3836  * Description :  Adds a cookie expiry date to a string.
3837  *
3838  * Parameters  :
3839  *          1  :  cookie = On input, pointer to cookie to modify.
3840  *                         On output, pointer to the modified header.
3841  *                         The original string is freed.
3842  *          2  :  lifetime = Seconds the cookie should be valid
3843  *
3844  * Returns     :  N/A
3845  *
3846  *********************************************************************/
3847 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
3848 {
3849    char tmp[50];
3850    struct tm *timeptr = NULL;
3851    time_t expiry_date = time(NULL) + lifetime;
3852 #ifdef HAVE_GMTIME_R
3853    struct tm gmt;
3854
3855    timeptr = gmtime_r(&expiry_date, &gmt);
3856 #elif defined(MUTEX_LOCKS_AVAILABLE)
3857    privoxy_mutex_lock(&gmtime_mutex);
3858    timeptr = gmtime(&expiry_date);
3859    privoxy_mutex_unlock(&gmtime_mutex);
3860 #else
3861    timeptr = gmtime(&expiry_date);
3862 #endif
3863
3864    if (NULL == timeptr)
3865    {
3866       log_error(LOG_LEVEL_FATAL,
3867          "Failed to get the time in add_cooky_expiry_date()");
3868    }
3869    strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
3870    if (JB_ERR_OK != string_append(cookie, tmp))
3871    {
3872       log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
3873    }
3874 }
3875
3876
3877 /*********************************************************************
3878  *
3879  * Function    :  server_set_cookie
3880  *
3881  * Description :  Handle the server "cookie" header properly.
3882  *                Crunch, accept or rewrite it to a session cookie.
3883  *                Called from `sed'.
3884  *
3885  * Parameters  :
3886  *          1  :  csp = Current client state (buffers, headers, etc...)
3887  *          2  :  header = On input, pointer to header to modify.
3888  *                On output, pointer to the modified header, or NULL
3889  *                to remove the header.  This function frees the
3890  *                original string if necessary.
3891  *
3892  * Returns     :  JB_ERR_OK on success, or
3893  *                JB_ERR_MEMORY on out-of-memory error.
3894  *
3895  *********************************************************************/
3896 static jb_err server_set_cookie(struct client_state *csp, char **header)
3897 {
3898    if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
3899    {
3900       log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3901       freez(*header);
3902    }
3903    else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
3904          || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
3905    {
3906       time_t now;
3907       time_t cookie_time;
3908       long cookie_lifetime = 0;
3909       enum
3910       {
3911          NO_EXPIRY_DATE_SPECIFIED,
3912          EXPIRY_DATE_ACCEPTABLE,
3913          EXPIRY_DATE_UNACCEPTABLE
3914       } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
3915
3916       /* A variable to store the tag we're working on */
3917       char *cur_tag;
3918
3919       /* Skip "Set-Cookie:" (11 characters) in header */
3920       cur_tag = *header + 11;
3921
3922       /* skip whitespace between "Set-Cookie:" and value */
3923       while (*cur_tag && privoxy_isspace(*cur_tag))
3924       {
3925          cur_tag++;
3926       }
3927
3928       time(&now);
3929
3930       if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
3931       {
3932          const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
3933
3934          cookie_lifetime = strtol(param, NULL, 0);
3935          if (cookie_lifetime < 0)
3936          {
3937             log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
3938          }
3939          cookie_lifetime *= 60;
3940       }
3941
3942       /* Loop through each tag in the cookie */
3943       while (*cur_tag)
3944       {
3945          /* Find next tag */
3946          char *next_tag = strchr(cur_tag, ';');
3947          if (next_tag != NULL)
3948          {
3949             /* Skip the ';' character itself */
3950             next_tag++;
3951
3952             /* skip whitespace ";" and start of tag */
3953             while (*next_tag && privoxy_isspace(*next_tag))
3954             {
3955                next_tag++;
3956             }
3957          }
3958          else
3959          {
3960             /* "Next tag" is the end of the string */
3961             next_tag = cur_tag + strlen(cur_tag);
3962          }
3963
3964          /*
3965           * Check the expiration date to see
3966           * if the cookie is still valid, if yes,
3967           * rewrite it to a session cookie.
3968           */
3969          if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3970          {
3971             char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3972
3973             if ((expiration_date[0] == '"')
3974              && (expiration_date[1] != '\0'))
3975             {
3976                /*
3977                 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
3978                 * that the expiration date isn't supposed to be quoted,
3979                 * but some servers do it anyway.
3980                 */
3981                expiration_date++;
3982             }
3983
3984             /* Did we detect the date properly? */
3985             if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3986             {
3987                /*
3988                 * Nope, treat it as if it was still valid.
3989                 *
3990                 * XXX: Should we remove the whole cookie instead?
3991                 */
3992                log_error(LOG_LEVEL_ERROR,
3993                   "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3994                string_move(cur_tag, next_tag);
3995                expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
3996             }
3997             else
3998             {
3999                /*
4000                 * Yes. Check if the cookie is still valid.
4001                 *
4002                 * If the cookie is already expired it's probably
4003                 * a delete cookie and even if it isn't, the browser
4004                 * will discard it anyway.
4005                 */
4006
4007                /*
4008                 * XXX: timegm() isn't available on some AmigaOS
4009                 * versions and our replacement doesn't work.
4010                 *
4011                 * Our options are to either:
4012                 *
4013                 * - disable session-cookies-only completely if timegm
4014                 *   is missing,
4015                 *
4016                 * - to simply remove all expired tags, like it has
4017                 *   been done until Privoxy 3.0.6 and to live with
4018                 *    the consequence that it can cause login/logout
4019                 *   problems on servers that don't validate their
4020                 *   input properly, or
4021                 *
4022                 * - to replace it with mktime in which
4023                 *   case there is a slight chance of valid cookies
4024                 *   passing as already expired.
4025                 *
4026                 *   This is the way it's currently done and it's not
4027                 *   as bad as it sounds. If the missing GMT offset is
4028                 *   enough to change the result of the expiration check
4029                 *   the cookie will be only valid for a few hours
4030                 *   anyway, which in many cases will be shorter
4031                 *   than a browser session.
4032                 */
4033                if (cookie_time < now)
4034                {
4035                   log_error(LOG_LEVEL_HEADER,
4036                      "Cookie \'%s\' is already expired and can pass unmodified.", *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 if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4042                {
4043                   log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4044                      "Its lifetime is below the limit.", *header);
4045                   /* Just in case some clown sets more then one expiration date */
4046                   cur_tag = next_tag;
4047                   expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4048                }
4049                else
4050                {
4051                   /*
4052                    * Still valid, delete expiration date by copying
4053                    * the rest of the string over it.
4054                    */
4055                   string_move(cur_tag, next_tag);
4056
4057                   /* That changed the header, need to issue a log message */
4058                   expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4059
4060                   /*
4061                    * Note that the next tag has now been moved to *cur_tag,
4062                    * so we do not need to update the cur_tag pointer.
4063                    */
4064                }
4065             }
4066
4067          }
4068          else
4069          {
4070             /* Move on to next cookie tag */
4071             cur_tag = next_tag;
4072          }
4073       }
4074
4075       if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4076       {
4077          assert(NULL != *header);
4078          if (cookie_lifetime != 0)
4079          {
4080             add_cookie_expiry_date(header, cookie_lifetime);
4081             log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4082          }
4083          else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4084          {
4085             log_error(LOG_LEVEL_HEADER,
4086                "Cookie rewritten to a temporary one: %s", *header);
4087          }
4088       }
4089    }
4090
4091    return JB_ERR_OK;
4092 }
4093
4094
4095 #ifdef FEATURE_FORCE_LOAD
4096 /*********************************************************************
4097  *
4098  * Function    :  strclean
4099  *
4100  * Description :  In-Situ-Eliminate all occurrences of substring in
4101  *                string
4102  *
4103  * Parameters  :
4104  *          1  :  string = string to clean
4105  *          2  :  substring = substring to eliminate
4106  *
4107  * Returns     :  Number of eliminations
4108  *
4109  *********************************************************************/
4110 int strclean(char *string, const char *substring)
4111 {
4112    int hits = 0;
4113    size_t len;
4114    char *pos, *p;
4115
4116    len = strlen(substring);
4117
4118    while((pos = strstr(string, substring)) != NULL)
4119    {
4120       p = pos + len;
4121       do
4122       {
4123          *(p - len) = *p;
4124       }
4125       while (*p++ != '\0');
4126
4127       hits++;
4128    }
4129
4130    return(hits);
4131 }
4132 #endif /* def FEATURE_FORCE_LOAD */
4133
4134
4135 /*********************************************************************
4136  *
4137  * Function    :  parse_header_time
4138  *
4139  * Description :  Parses time formats used in HTTP header strings
4140  *                to get the numerical respresentation.
4141  *
4142  * Parameters  :
4143  *          1  :  header_time = HTTP header time as string.
4144  *          2  :  result = storage for header_time in seconds
4145  *
4146  * Returns     :  JB_ERR_OK if the time format was recognized, or
4147  *                JB_ERR_PARSE otherwise.
4148  *
4149  *********************************************************************/
4150 static jb_err parse_header_time(const char *header_time, time_t *result)
4151 {
4152    struct tm gmt;
4153    /*
4154     * Checking for two-digit years first in an
4155     * attempt to work around GNU libc's strptime()
4156     * reporting negative year values when using %Y.
4157     */
4158    static const char time_formats[][22] = {
4159       /* Tue, 02-Jun-37 20:00:00 */
4160       "%a, %d-%b-%y %H:%M:%S",
4161       /* Tue, 02 Jun 2037 20:00:00 */
4162       "%a, %d %b %Y %H:%M:%S",
4163       /* Tue, 02-Jun-2037 20:00:00 */
4164       "%a, %d-%b-%Y %H:%M:%S",
4165       /* Tuesday, 02-Jun-2037 20:00:00 */
4166       "%A, %d-%b-%Y %H:%M:%S",
4167       /* Tuesday Jun 02 20:00:00 2037 */
4168       "%A %b %d %H:%M:%S %Y"
4169    };
4170    unsigned int i;
4171
4172    for (i = 0; i < SZ(time_formats); i++)
4173    {
4174       /*
4175        * Zero out gmt to prevent time zone offsets.
4176        * Documented to be required for GNU libc.
4177        */
4178       memset(&gmt, 0, sizeof(gmt));
4179
4180       if (NULL != strptime(header_time, time_formats[i], &gmt))
4181       {
4182          /* Sanity check for GNU libc. */
4183          if (gmt.tm_year < 0)
4184          {
4185             log_error(LOG_LEVEL_HEADER,
4186                "Failed to parse '%s' using '%s'. Moving on.",
4187                header_time, time_formats[i]);
4188             continue;
4189          }
4190          *result = timegm(&gmt);
4191
4192 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4193          /*
4194           * Verify that parsing the date recreated from the first
4195           * parse operation gets the previous result. If it doesn't,
4196           * either strptime() or strftime() are malfunctioning.
4197           *
4198           * We could string-compare the recreated date with the original
4199           * header date, but this leads to false positives as strptime()
4200           * may let %a accept all day formats while strftime() will only
4201           * create one.
4202           */
4203          {
4204             char recreated_date[100];
4205             struct tm *tm;
4206             time_t result2;
4207
4208             tm = gmtime(result);
4209             strftime(recreated_date, sizeof(recreated_date), time_formats[i], tm);
4210             memset(&gmt, 0, sizeof(gmt));
4211             if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4212             {
4213                log_error(LOG_LEVEL_ERROR,
4214                   "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4215                   recreated_date, time_formats[i], header_time);
4216                continue;
4217             }
4218             result2 = timegm(&gmt);
4219             if (*result != result2)
4220             {
4221                log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4222                   "Format: '%s'. In: '%s', out: '%s'. %d != %d. Rejecting.",
4223                   time_formats[i], header_time, recreated_date, *result, result2);
4224                continue;
4225             }
4226          }
4227 #endif
4228
4229          return JB_ERR_OK;
4230       }
4231    }
4232
4233    return JB_ERR_PARSE;
4234
4235 }
4236
4237
4238 /*********************************************************************
4239  *
4240  * Function    :  get_destination_from_headers
4241  *
4242  * Description :  Parse the "Host:" header to get the request's destination.
4243  *                Only needed if the client's request was forcefully
4244  *                redirected into Privoxy.
4245  *
4246  *                Code mainly copied from client_host() which is currently
4247  *                run too late for this purpose.
4248  *
4249  * Parameters  :
4250  *          1  :  headers = List of headers (one of them hopefully being
4251  *                the "Host:" header)
4252  *          2  :  http = storage for the result (host, port and hostport).
4253  *
4254  * Returns     :  JB_ERR_MEMORY (or terminates) in case of memory problems,
4255  *                JB_ERR_PARSE if the host header couldn't be found,
4256  *                JB_ERR_OK otherwise.
4257  *
4258  *********************************************************************/
4259 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4260 {
4261    char *q;
4262    char *p;
4263    char *host;
4264
4265    host = get_header_value(headers, "Host:");
4266
4267    if (NULL == host)
4268    {
4269       log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4270       return JB_ERR_PARSE;
4271    }
4272
4273    p = strdup_or_die(host);
4274    chomp(p);
4275    q = strdup_or_die(p);
4276
4277    freez(http->hostport);
4278    http->hostport = p;
4279    freez(http->host);
4280    http->host = q;
4281    q = strchr(http->host, ':');
4282    if (q != NULL)
4283    {
4284       /* Terminate hostname and evaluate port string */
4285       *q++ = '\0';
4286       http->port = atoi(q);
4287    }
4288    else
4289    {
4290       http->port = http->ssl ? 443 : 80;
4291    }
4292
4293    /* Rebuild request URL */
4294    freez(http->url);
4295    http->url = strdup(http->ssl ? "https://" : "http://");
4296    string_append(&http->url, http->hostport);
4297    string_append(&http->url, http->path);
4298    if (http->url == NULL)
4299    {
4300       return JB_ERR_MEMORY;
4301    }
4302
4303    log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4304       http->url);
4305
4306    return JB_ERR_OK;
4307
4308 }
4309
4310
4311 /*********************************************************************
4312  *
4313  * Function    :  create_forged_referrer
4314  *
4315  * Description :  Helper for client_referrer to forge a referer as
4316  *                'http://hostname[:port]/' to fool stupid
4317  *                checks for in-site links
4318  *
4319  * Parameters  :
4320  *          1  :  header   = Pointer to header pointer
4321  *          2  :  hostport = Host and optionally port as string
4322  *
4323  * Returns     :  JB_ERR_OK in case of success, or
4324  *                JB_ERR_MEMORY in case of memory problems.
4325  *
4326  *********************************************************************/
4327 static jb_err create_forged_referrer(char **header, const char *hostport)
4328 {
4329     assert(NULL == *header);
4330
4331     *header = strdup("Referer: http://");
4332     string_append(header, hostport);
4333     string_append(header, "/");
4334
4335     if (NULL == *header)
4336     {
4337        return JB_ERR_MEMORY;
4338     }
4339
4340     log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4341
4342     return JB_ERR_OK;
4343
4344 }
4345
4346
4347 /*********************************************************************
4348  *
4349  * Function    :  create_fake_referrer
4350  *
4351  * Description :  Helper for client_referrer to create a fake referrer
4352  *                based on a string supplied by the user.
4353  *
4354  * Parameters  :
4355  *          1  :  header   = Pointer to header pointer
4356  *          2  :  hosthost = Referrer to fake
4357  *
4358  * Returns     :  JB_ERR_OK in case of success, or
4359  *                JB_ERR_MEMORY in case of memory problems.
4360  *
4361  *********************************************************************/
4362 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4363 {
4364    assert(NULL == *header);
4365
4366    if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4367    {
4368       log_error(LOG_LEVEL_HEADER,
4369          "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4370    }
4371    *header = strdup("Referer: ");
4372    string_append(header, fake_referrer);
4373
4374    if (NULL == *header)
4375    {
4376       return JB_ERR_MEMORY;
4377    }
4378
4379    log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4380
4381    return JB_ERR_OK;
4382
4383 }
4384
4385
4386 /*********************************************************************
4387  *
4388  * Function    :  handle_conditional_hide_referrer_parameter
4389  *
4390  * Description :  Helper for client_referrer to crunch or forge
4391  *                the referrer header if the host has changed.
4392  *
4393  * Parameters  :
4394  *          1  :  header = Pointer to header pointer
4395  *          2  :  host   = The target host (may include the port)
4396  *          3  :  parameter_conditional_block = Boolean to signal
4397  *                if we're in conditional-block mode. If not set,
4398  *                we're in conditional-forge mode.
4399  *
4400  * Returns     :  JB_ERR_OK in case of success, or
4401  *                JB_ERR_MEMORY in case of memory problems.
4402  *
4403  *********************************************************************/
4404 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4405    const char *host, const int parameter_conditional_block)
4406 {
4407    char *referer = strdup_or_die(*header);
4408    const size_t hostlength = strlen(host);
4409    const char *referer_url = NULL;
4410
4411    /* referer begins with 'Referer: http[s]://' */
4412    if ((hostlength+17) < strlen(referer))
4413    {
4414       /*
4415        * Shorten referer to make sure the referer is blocked
4416        * if www.example.org/www.example.com-shall-see-the-referer/
4417        * links to www.example.com/
4418        */
4419       referer[hostlength+17] = '\0';
4420    }
4421    referer_url = strstr(referer, "http://");
4422    if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4423    {
4424       /* Host has changed, Referer is invalid or a https URL. */
4425       if (parameter_conditional_block)
4426       {
4427          log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4428          freez(*header);
4429       }
4430       else
4431       {
4432          freez(*header);
4433          freez(referer);
4434          return create_forged_referrer(header, host);
4435       }
4436    }
4437    freez(referer);
4438
4439    return JB_ERR_OK;
4440
4441 }
4442
4443
4444 /*********************************************************************
4445  *
4446  * Function    :  create_content_length_header
4447  *
4448  * Description :  Creates a Content-Length header.
4449  *
4450  * Parameters  :
4451  *          1  :  content_length = The content length to be used in the header.
4452  *          2  :  header = Allocated space to safe the header.
4453  *          3  :  buffer_length = The length of the allocated space.
4454  *
4455  * Returns     :  void
4456  *
4457  *********************************************************************/
4458 static void create_content_length_header(unsigned long long content_length,
4459                                          char *header, size_t buffer_length)
4460 {
4461    snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4462 }
4463
4464
4465 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4466 /*********************************************************************
4467  *
4468  * Function    :  get_expected_content_length
4469  *
4470  * Description :  Figures out the content length from a list of headers.
4471  *
4472  * Parameters  :
4473  *          1  :  headers = List of headers
4474  *
4475  * Returns     :  Number of bytes to expect
4476  *
4477  *********************************************************************/
4478 unsigned long long get_expected_content_length(struct list *headers)
4479 {
4480    const char *content_length_header;
4481    unsigned long long content_length = 0;
4482
4483    content_length_header = get_header_value(headers, "Content-Length:");
4484    if (content_length_header != NULL)
4485    {
4486       if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4487       {
4488          log_error(LOG_LEVEL_ERROR,
4489             "Failed to get the Content-Length in %s", content_length_header);
4490          /* XXX: The header will be removed later on */
4491          return 0;
4492       }
4493    }
4494
4495    return content_length;
4496 }
4497 #endif
4498
4499 /*
4500   Local Variables:
4501   tab-width: 3
4502   end:
4503 */