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