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