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