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