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