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