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