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