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