Fix a compiler warning when building without zlib support
[privoxy.git] / parsers.c
1 const char parsers_rcs[] = "$Id: parsers.c,v 1.306 2016/01/16 12:33:36 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-2016 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 (content_filters_enabled(csp->action))
2376       {
2377          log_error(LOG_LEVEL_INFO,
2378             "Compressed content detected, content filtering disabled. "
2379             "Consider recompiling Privoxy with zlib support or "
2380             "enable the prevent-compression action.");
2381       }
2382    }
2383 #endif /* defined(FEATURE_ZLIB) */
2384
2385    return JB_ERR_OK;
2386
2387 }
2388
2389
2390 #ifdef FEATURE_ZLIB
2391 /*********************************************************************
2392  *
2393  * Function    :  server_adjust_content_encoding
2394  *
2395  * Description :  Remove the Content-Encoding header if the
2396  *                decompression was successful and the content
2397  *                has been modifed.
2398  *
2399  * Parameters  :
2400  *          1  :  csp = Current client state (buffers, headers, etc...)
2401  *          2  :  header = On input, pointer to header to modify.
2402  *                On output, pointer to the modified header, or NULL
2403  *                to remove the header.  This function frees the
2404  *                original string if necessary.
2405  *
2406  * Returns     :  JB_ERR_OK on success, or
2407  *                JB_ERR_MEMORY on out-of-memory error.
2408  *
2409  *********************************************************************/
2410 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2411 {
2412    if ((csp->flags & CSP_FLAG_MODIFIED)
2413     && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2414    {
2415       /*
2416        * We successfully decompressed the content,
2417        * and have to clean the header now, so the
2418        * client no longer expects compressed data.
2419        *
2420        * XXX: There is a difference between cleaning
2421        * and removing it completely.
2422        */
2423       log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2424       freez(*header);
2425    }
2426
2427    return JB_ERR_OK;
2428
2429 }
2430 #endif /* defined(FEATURE_ZLIB) */
2431
2432
2433 /*********************************************************************
2434  *
2435  * Function    :  server_adjust_content_length
2436  *
2437  * Description :  Adjust Content-Length header if we modified
2438  *                the body.
2439  *
2440  * Parameters  :
2441  *          1  :  csp = Current client state (buffers, headers, etc...)
2442  *          2  :  header = On input, pointer to header to modify.
2443  *                On output, pointer to the modified header, or NULL
2444  *                to remove the header.  This function frees the
2445  *                original string if necessary.
2446  *
2447  * Returns     :  JB_ERR_OK on success, or
2448  *                JB_ERR_MEMORY on out-of-memory error.
2449  *
2450  *********************************************************************/
2451 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2452 {
2453    /* Regenerate header if the content was modified. */
2454    if (csp->flags & CSP_FLAG_MODIFIED)
2455    {
2456       const size_t header_length = 50;
2457       freez(*header);
2458       *header = malloc(header_length);
2459       if (*header == NULL)
2460       {
2461          return JB_ERR_MEMORY;
2462       }
2463       create_content_length_header(csp->content_length, *header, header_length);
2464       log_error(LOG_LEVEL_HEADER,
2465          "Adjusted Content-Length to %llu", csp->content_length);
2466    }
2467
2468    return JB_ERR_OK;
2469 }
2470
2471
2472 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2473 /*********************************************************************
2474  *
2475  * Function    :  server_save_content_length
2476  *
2477  * Description :  Save the Content-Length sent by the server.
2478  *
2479  * Parameters  :
2480  *          1  :  csp = Current client state (buffers, headers, etc...)
2481  *          2  :  header = On input, pointer to header to modify.
2482  *                On output, pointer to the modified header, or NULL
2483  *                to remove the header.  This function frees the
2484  *                original string if necessary.
2485  *
2486  * Returns     :  JB_ERR_OK on success, or
2487  *                JB_ERR_MEMORY on out-of-memory error.
2488  *
2489  *********************************************************************/
2490 static jb_err server_save_content_length(struct client_state *csp, char **header)
2491 {
2492    unsigned long long content_length = 0;
2493    const char *header_value;
2494
2495    assert(*(*header+14) == ':');
2496
2497    header_value = *header + 15;
2498    if (JB_ERR_OK != get_content_length(header_value, &content_length))
2499    {
2500       log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2501       freez(*header);
2502    }
2503    else
2504    {
2505       csp->expected_content_length = content_length;
2506       csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2507       csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2508    }
2509
2510    return JB_ERR_OK;
2511 }
2512 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2513
2514
2515 /*********************************************************************
2516  *
2517  * Function    :  server_content_md5
2518  *
2519  * Description :  Crumble any Content-MD5 headers if the document was
2520  *                modified. FIXME: Should we re-compute instead?
2521  *
2522  * Parameters  :
2523  *          1  :  csp = Current client state (buffers, headers, etc...)
2524  *          2  :  header = On input, pointer to header to modify.
2525  *                On output, pointer to the modified header, or NULL
2526  *                to remove the header.  This function frees the
2527  *                original string if necessary.
2528  *
2529  * Returns     :  JB_ERR_OK on success, or
2530  *                JB_ERR_MEMORY on out-of-memory error.
2531  *
2532  *********************************************************************/
2533 static jb_err server_content_md5(struct client_state *csp, char **header)
2534 {
2535    if (csp->flags & CSP_FLAG_MODIFIED)
2536    {
2537       log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2538       freez(*header);
2539    }
2540
2541    return JB_ERR_OK;
2542 }
2543
2544
2545 /*********************************************************************
2546  *
2547  * Function    :  server_content_disposition
2548  *
2549  * Description :  If enabled, blocks or modifies the "Content-Disposition" header.
2550  *                Called from `sed'.
2551  *
2552  * Parameters  :
2553  *          1  :  csp = Current client state (buffers, headers, etc...)
2554  *          2  :  header = On input, pointer to header to modify.
2555  *                On output, pointer to the modified header, or NULL
2556  *                to remove the header.  This function frees the
2557  *                original string if necessary.
2558  *
2559  * Returns     :  JB_ERR_OK on success, or
2560  *                JB_ERR_MEMORY on out-of-memory error.
2561  *
2562  *********************************************************************/
2563 static jb_err server_content_disposition(struct client_state *csp, char **header)
2564 {
2565    const char *newval;
2566
2567    /*
2568     * Are we messing with the Content-Disposition header?
2569     */
2570    if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2571    {
2572       /* Me tinks not */
2573       return JB_ERR_OK;
2574    }
2575
2576    newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2577
2578    if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2579    {
2580       /*
2581        * Blocking content-disposition header
2582        */
2583       log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2584       freez(*header);
2585       return JB_ERR_OK;
2586    }
2587    else
2588    {
2589       /*
2590        * Replacing Content-Disposition header
2591        */
2592       freez(*header);
2593       *header = strdup("Content-Disposition: ");
2594       string_append(header, newval);
2595
2596       if (*header != NULL)
2597       {
2598          log_error(LOG_LEVEL_HEADER,
2599             "Content-Disposition header crunched and replaced with: %s", *header);
2600       }
2601    }
2602    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2603 }
2604
2605
2606 /*********************************************************************
2607  *
2608  * Function    :  server_last_modified
2609  *
2610  * Description :  Changes Last-Modified header to the actual date
2611  *                to help hide-if-modified-since.
2612  *                Called from `sed'.
2613  *
2614  * Parameters  :
2615  *          1  :  csp = Current client state (buffers, headers, etc...)
2616  *          2  :  header = On input, pointer to header to modify.
2617  *                On output, pointer to the modified header, or NULL
2618  *                to remove the header.  This function frees the
2619  *                original string if necessary.
2620  *
2621  * Returns     :  JB_ERR_OK on success, or
2622  *                JB_ERR_MEMORY on out-of-memory error.
2623  *
2624  *********************************************************************/
2625 static jb_err server_last_modified(struct client_state *csp, char **header)
2626 {
2627    const char *newval;
2628    time_t last_modified;
2629    char newheader[50];
2630
2631    /*
2632     * Are we messing with the Last-Modified header?
2633     */
2634    if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2635    {
2636       /*Nope*/
2637       return JB_ERR_OK;
2638    }
2639
2640    newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2641
2642    if (0 == strcmpic(newval, "block"))
2643    {
2644       /*
2645        * Blocking Last-Modified header. Useless but why not.
2646        */
2647       log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2648       freez(*header);
2649       return JB_ERR_OK;
2650    }
2651    else if (0 == strcmpic(newval, "reset-to-request-time"))
2652    {
2653       /*
2654        * Setting Last-Modified Header to now.
2655        */
2656       char buf[30];
2657       get_http_time(0, buf, sizeof(buf));
2658       freez(*header);
2659       *header = strdup("Last-Modified: ");
2660       string_append(header, buf);
2661
2662       if (*header == NULL)
2663       {
2664          log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2665       }
2666       else
2667       {
2668          log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2669       }
2670    }
2671    else if (0 == strcmpic(newval, "randomize"))
2672    {
2673       log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2674
2675       if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2676       {
2677          log_error(LOG_LEVEL_HEADER,
2678             "Couldn't parse time in %s (crunching!)", *header);
2679          freez(*header);
2680       }
2681       else
2682       {
2683          time_t now;
2684          struct tm *timeptr = NULL;
2685          long int rtime;
2686 #ifdef HAVE_GMTIME_R
2687          struct tm gmt;
2688 #endif
2689          now = time(NULL);
2690          rtime = (long int)difftime(now, last_modified);
2691          if (rtime)
2692          {
2693             long int days, hours, minutes, seconds;
2694             const int negative_delta = (rtime < 0);
2695
2696             if (negative_delta)
2697             {
2698                rtime *= -1;
2699                log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2700             }
2701             rtime = pick_from_range(rtime);
2702             if (negative_delta)
2703             {
2704                rtime *= -1;
2705             }
2706             last_modified += rtime;
2707 #ifdef HAVE_GMTIME_R
2708             timeptr = gmtime_r(&last_modified, &gmt);
2709 #elif defined(MUTEX_LOCKS_AVAILABLE)
2710             privoxy_mutex_lock(&gmtime_mutex);
2711             timeptr = gmtime(&last_modified);
2712             privoxy_mutex_unlock(&gmtime_mutex);
2713 #else
2714             timeptr = gmtime(&last_modified);
2715 #endif
2716             if ((NULL == timeptr) || !strftime(newheader,
2717                   sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2718             {
2719                log_error(LOG_LEVEL_ERROR,
2720                   "Randomizing '%s' failed. Crunching the header without replacement.",
2721                   *header);
2722                freez(*header);
2723                return JB_ERR_OK;
2724             }
2725
2726             freez(*header);
2727             *header = strdup("Last-Modified: ");
2728             string_append(header, newheader);
2729
2730             if (*header == NULL)
2731             {
2732                log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2733                return JB_ERR_MEMORY;
2734             }
2735
2736             days    = rtime / (3600 * 24);
2737             hours   = rtime / 3600 % 24;
2738             minutes = rtime / 60 % 60;
2739             seconds = rtime % 60;
2740
2741             log_error(LOG_LEVEL_HEADER,
2742                "Randomized:  %s (added %d da%s %d hou%s %d minut%s %d second%s",
2743                *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2744                minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2745          }
2746          else
2747          {
2748             log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2749          }
2750       }
2751    }
2752
2753    return JB_ERR_OK;
2754 }
2755
2756
2757 /*********************************************************************
2758  *
2759  * Function    :  client_accept_encoding
2760  *
2761  * Description :  Rewrite the client's Accept-Encoding header so that
2762  *                if doesn't allow compression, if the action applies.
2763  *                Note: For HTTP/1.0 the absence of the header is enough.
2764  *
2765  * Parameters  :
2766  *          1  :  csp = Current client state (buffers, headers, etc...)
2767  *          2  :  header = On input, pointer to header to modify.
2768  *                On output, pointer to the modified header, or NULL
2769  *                to remove the header.  This function frees the
2770  *                original string if necessary.
2771  *
2772  * Returns     :  JB_ERR_OK on success, or
2773  *                JB_ERR_MEMORY on out-of-memory error.
2774  *
2775  *********************************************************************/
2776 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2777 {
2778 #ifdef FEATURE_COMPRESSION
2779    if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2780       && strstr(*header, "deflate"))
2781    {
2782       csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2783    }
2784 #endif
2785    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2786    {
2787       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2788       freez(*header);
2789    }
2790
2791    return JB_ERR_OK;
2792 }
2793
2794
2795 /*********************************************************************
2796  *
2797  * Function    :  client_te
2798  *
2799  * Description :  Rewrite the client's TE header so that
2800  *                if doesn't allow compression, if the action applies.
2801  *
2802  * Parameters  :
2803  *          1  :  csp = Current client state (buffers, headers, etc...)
2804  *          2  :  header = On input, pointer to header to modify.
2805  *                On output, pointer to the modified header, or NULL
2806  *                to remove the header.  This function frees the
2807  *                original string if necessary.
2808  *
2809  * Returns     :  JB_ERR_OK on success, or
2810  *                JB_ERR_MEMORY on out-of-memory error.
2811  *
2812  *********************************************************************/
2813 static jb_err client_te(struct client_state *csp, char **header)
2814 {
2815    if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2816    {
2817       freez(*header);
2818       log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2819    }
2820
2821    return JB_ERR_OK;
2822 }
2823
2824
2825 /*********************************************************************
2826  *
2827  * Function    :  client_referrer
2828  *
2829  * Description :  Handle the "referer" config setting properly.
2830  *                Called from `sed'.
2831  *
2832  * Parameters  :
2833  *          1  :  csp = Current client state (buffers, headers, etc...)
2834  *          2  :  header = On input, pointer to header to modify.
2835  *                On output, pointer to the modified header, or NULL
2836  *                to remove the header.  This function frees the
2837  *                original string if necessary.
2838  *
2839  * Returns     :  JB_ERR_OK on success, or
2840  *                JB_ERR_MEMORY on out-of-memory error.
2841  *
2842  *********************************************************************/
2843 static jb_err client_referrer(struct client_state *csp, char **header)
2844 {
2845    const char *parameter;
2846    /* booleans for parameters we have to check multiple times */
2847    int parameter_conditional_block;
2848    int parameter_conditional_forge;
2849
2850 #ifdef FEATURE_FORCE_LOAD
2851    /*
2852     * Since the referrer can include the prefix even
2853     * if the request itself is non-forced, we must
2854     * clean it unconditionally.
2855     *
2856     * XXX: strclean is too broad
2857     */
2858    strclean(*header, FORCE_PREFIX);
2859 #endif /* def FEATURE_FORCE_LOAD */
2860
2861    if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2862    {
2863       /* Nothing left to do */
2864       return JB_ERR_OK;
2865    }
2866
2867    parameter = csp->action->string[ACTION_STRING_REFERER];
2868    assert(parameter != NULL);
2869    parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2870    parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2871
2872    if (!parameter_conditional_block && !parameter_conditional_forge)
2873    {
2874       /*
2875        * As conditional-block and conditional-forge are the only
2876        * parameters that rely on the original referrer, we can
2877        * remove it now for all the others.
2878        */
2879       freez(*header);
2880    }
2881
2882    if (0 == strcmpic(parameter, "block"))
2883    {
2884       log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2885       return JB_ERR_OK;
2886    }
2887    else if (parameter_conditional_block || parameter_conditional_forge)
2888    {
2889       return handle_conditional_hide_referrer_parameter(header,
2890          csp->http->hostport, parameter_conditional_block);
2891    }
2892    else if (0 == strcmpic(parameter, "forge"))
2893    {
2894       return create_forged_referrer(header, csp->http->hostport);
2895    }
2896    else
2897    {
2898       /* interpret parameter as user-supplied referer to fake */
2899       return create_fake_referrer(header, parameter);
2900    }
2901 }
2902
2903
2904 /*********************************************************************
2905  *
2906  * Function    :  client_accept_language
2907  *
2908  * Description :  Handle the "Accept-Language" config setting properly.
2909  *                Called from `sed'.
2910  *
2911  * Parameters  :
2912  *          1  :  csp = Current client state (buffers, headers, etc...)
2913  *          2  :  header = On input, pointer to header to modify.
2914  *                On output, pointer to the modified header, or NULL
2915  *                to remove the header.  This function frees the
2916  *                original string if necessary.
2917  *
2918  * Returns     :  JB_ERR_OK on success, or
2919  *                JB_ERR_MEMORY on out-of-memory error.
2920  *
2921  *********************************************************************/
2922 static jb_err client_accept_language(struct client_state *csp, char **header)
2923 {
2924    const char *newval;
2925
2926    /*
2927     * Are we messing with the Accept-Language?
2928     */
2929    if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2930    {
2931       /*I don't think so*/
2932       return JB_ERR_OK;
2933    }
2934
2935    newval = csp->action->string[ACTION_STRING_LANGUAGE];
2936
2937    if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2938    {
2939       /*
2940        * Blocking Accept-Language header
2941        */
2942       log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2943       freez(*header);
2944       return JB_ERR_OK;
2945    }
2946    else
2947    {
2948       /*
2949        * Replacing Accept-Language header
2950        */
2951       freez(*header);
2952       *header = strdup("Accept-Language: ");
2953       string_append(header, newval);
2954
2955       if (*header == NULL)
2956       {
2957          log_error(LOG_LEVEL_ERROR,
2958             "Insufficient memory. Accept-Language header crunched without replacement.");
2959       }
2960       else
2961       {
2962          log_error(LOG_LEVEL_HEADER,
2963             "Accept-Language header crunched and replaced with: %s", *header);
2964       }
2965    }
2966    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2967 }
2968
2969
2970 /*********************************************************************
2971  *
2972  * Function    :  crunch_client_header
2973  *
2974  * Description :  Crunch client header if it matches a string supplied by the
2975  *                user. Called from `sed'.
2976  *
2977  * Parameters  :
2978  *          1  :  csp = Current client state (buffers, headers, etc...)
2979  *          2  :  header = On input, pointer to header to modify.
2980  *                On output, pointer to the modified header, or NULL
2981  *                to remove the header.  This function frees the
2982  *                original string if necessary.
2983  *
2984  * Returns     :  JB_ERR_OK on success and always succeeds
2985  *
2986  *********************************************************************/
2987 static jb_err crunch_client_header(struct client_state *csp, char **header)
2988 {
2989    const char *crunch_pattern;
2990
2991    /* Do we feel like crunching? */
2992    if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2993    {
2994       crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2995
2996       /* Is the current header the lucky one? */
2997       if (strstr(*header, crunch_pattern))
2998       {
2999          log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3000          freez(*header);
3001       }
3002    }
3003    return JB_ERR_OK;
3004 }
3005
3006
3007 /*********************************************************************
3008  *
3009  * Function    :  client_uagent
3010  *
3011  * Description :  Handle the "user-agent" config setting properly
3012  *                and remember its original value to enable browser
3013  *                bug workarounds. Called from `sed'.
3014  *
3015  * Parameters  :
3016  *          1  :  csp = Current client state (buffers, headers, etc...)
3017  *          2  :  header = On input, pointer to header to modify.
3018  *                On output, pointer to the modified header, or NULL
3019  *                to remove the header.  This function frees the
3020  *                original string if necessary.
3021  *
3022  * Returns     :  JB_ERR_OK on success, or
3023  *                JB_ERR_MEMORY on out-of-memory error.
3024  *
3025  *********************************************************************/
3026 static jb_err client_uagent(struct client_state *csp, char **header)
3027 {
3028    const char *newval;
3029
3030    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3031    {
3032       return JB_ERR_OK;
3033    }
3034
3035    newval = csp->action->string[ACTION_STRING_USER_AGENT];
3036    if (newval == NULL)
3037    {
3038       return JB_ERR_OK;
3039    }
3040
3041    freez(*header);
3042    *header = strdup("User-Agent: ");
3043    string_append(header, newval);
3044
3045    log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3046
3047    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3048 }
3049
3050
3051 /*********************************************************************
3052  *
3053  * Function    :  client_ua
3054  *
3055  * Description :  Handle "ua-" headers properly.  Called from `sed'.
3056  *
3057  * Parameters  :
3058  *          1  :  csp = Current client state (buffers, headers, etc...)
3059  *          2  :  header = On input, pointer to header to modify.
3060  *                On output, pointer to the modified header, or NULL
3061  *                to remove the header.  This function frees the
3062  *                original string if necessary.
3063  *
3064  * Returns     :  JB_ERR_OK on success, or
3065  *                JB_ERR_MEMORY on out-of-memory error.
3066  *
3067  *********************************************************************/
3068 static jb_err client_ua(struct client_state *csp, char **header)
3069 {
3070    if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3071    {
3072       log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3073       freez(*header);
3074    }
3075
3076    return JB_ERR_OK;
3077 }
3078
3079
3080 /*********************************************************************
3081  *
3082  * Function    :  client_from
3083  *
3084  * Description :  Handle the "from" config setting properly.
3085  *                Called from `sed'.
3086  *
3087  * Parameters  :
3088  *          1  :  csp = Current client state (buffers, headers, etc...)
3089  *          2  :  header = On input, pointer to header to modify.
3090  *                On output, pointer to the modified header, or NULL
3091  *                to remove the header.  This function frees the
3092  *                original string if necessary.
3093  *
3094  * Returns     :  JB_ERR_OK on success, or
3095  *                JB_ERR_MEMORY on out-of-memory error.
3096  *
3097  *********************************************************************/
3098 static jb_err client_from(struct client_state *csp, char **header)
3099 {
3100    const char *newval;
3101
3102    if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3103    {
3104       return JB_ERR_OK;
3105    }
3106
3107    freez(*header);
3108
3109    newval = csp->action->string[ACTION_STRING_FROM];
3110
3111    /*
3112     * Are we blocking the e-mail address?
3113     */
3114    if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3115    {
3116       log_error(LOG_LEVEL_HEADER, "crunched From!");
3117       return JB_ERR_OK;
3118    }
3119
3120    log_error(LOG_LEVEL_HEADER, " modified");
3121
3122    *header = strdup("From: ");
3123    string_append(header, newval);
3124
3125    return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3126 }
3127
3128
3129 /*********************************************************************
3130  *
3131  * Function    :  client_send_cookie
3132  *
3133  * Description :  Crunches the "cookie" header if necessary.
3134  *                Called from `sed'.
3135  *
3136  *                XXX: Stupid name, doesn't send squat.
3137  *
3138  * Parameters  :
3139  *          1  :  csp = Current client state (buffers, headers, etc...)
3140  *          2  :  header = On input, pointer to header to modify.
3141  *                On output, pointer to the modified header, or NULL
3142  *                to remove the header.  This function frees the
3143  *                original string if necessary.
3144  *
3145  * Returns     :  JB_ERR_OK on success, or
3146  *                JB_ERR_MEMORY on out-of-memory error.
3147  *
3148  *********************************************************************/
3149 static jb_err client_send_cookie(struct client_state *csp, char **header)
3150 {
3151    if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3152    {
3153       log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3154       freez(*header);
3155    }
3156
3157    return JB_ERR_OK;
3158 }
3159
3160
3161 /*********************************************************************
3162  *
3163  * Function    :  client_x_forwarded
3164  *
3165  * Description :  Handle the "x-forwarded-for" config setting properly,
3166  *                also used in the add_client_headers list.  Called from `sed'.
3167  *
3168  * Parameters  :
3169  *          1  :  csp = Current client state (buffers, headers, etc...)
3170  *          2  :  header = On input, pointer to header to modify.
3171  *                On output, pointer to the modified header, or NULL
3172  *                to remove the header.  This function frees the
3173  *                original string if necessary.
3174  *
3175  * Returns     :  JB_ERR_OK on success, or
3176  *                JB_ERR_MEMORY on out-of-memory error.
3177  *
3178  *********************************************************************/
3179 jb_err client_x_forwarded(struct client_state *csp, char **header)
3180 {
3181    if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3182    {
3183       const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3184
3185       if (0 == strcmpic(parameter, "block"))
3186       {
3187          freez(*header);
3188          log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3189       }
3190       else if (0 == strcmpic(parameter, "add"))
3191       {
3192          string_append(header, ", ");
3193          string_append(header, csp->ip_addr_str);
3194
3195          if (*header == NULL)
3196          {
3197             return JB_ERR_MEMORY;
3198          }
3199          log_error(LOG_LEVEL_HEADER,
3200             "Appended client IP address to %s", *header);
3201          csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3202       }
3203       else
3204       {
3205          log_error(LOG_LEVEL_FATAL,
3206             "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3207       }
3208    }
3209
3210    return JB_ERR_OK;
3211 }
3212
3213
3214 /*********************************************************************
3215  *
3216  * Function    :  client_max_forwards
3217  *
3218  * Description :  If the HTTP method is OPTIONS or TRACE, subtract one
3219  *                from the value of the Max-Forwards header field.
3220  *
3221  * Parameters  :
3222  *          1  :  csp = Current client state (buffers, headers, etc...)
3223  *          2  :  header = On input, pointer to header to modify.
3224  *                On output, pointer to the modified header, or NULL
3225  *                to remove the header.  This function frees the
3226  *                original string if necessary.
3227  *
3228  * Returns     :  JB_ERR_OK on success, or
3229  *                JB_ERR_MEMORY on out-of-memory error.
3230  *
3231  *********************************************************************/
3232 static jb_err client_max_forwards(struct client_state *csp, char **header)
3233 {
3234    int max_forwards;
3235
3236    if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3237        (0 == strcmpic(csp->http->gpc, "options")))
3238    {
3239       assert(*(*header+12) == ':');
3240       if (1 == sscanf(*header+12, ": %d", &max_forwards))
3241       {
3242          if (max_forwards > 0)
3243          {
3244             snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3245             log_error(LOG_LEVEL_HEADER,
3246                "Max-Forwards value for %s request reduced to %d.",
3247                csp->http->gpc, max_forwards);
3248          }
3249          else if (max_forwards < 0)
3250          {
3251             log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3252             freez(*header);
3253          }
3254       }
3255       else
3256       {
3257          log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3258          freez(*header);
3259       }
3260    }
3261
3262    return JB_ERR_OK;
3263 }
3264
3265
3266 /*********************************************************************
3267  *
3268  * Function    :  client_host
3269  *
3270  * Description :  If the request URI did not contain host and
3271  *                port information, parse and evaluate the Host
3272  *                header field.
3273  *
3274  * Parameters  :
3275  *          1  :  csp = Current client state (buffers, headers, etc...)
3276  *          2  :  header = On input, pointer to header to modify.
3277  *                On output, pointer to the modified header, or NULL
3278  *                to remove the header.  This function frees the
3279  *                original string if necessary.
3280  *
3281  * Returns     :  JB_ERR_OK on success, or
3282  *                JB_ERR_MEMORY on out-of-memory error.
3283  *
3284  *********************************************************************/
3285 static jb_err client_host(struct client_state *csp, char **header)
3286 {
3287    char *p, *q;
3288
3289    if (strlen(*header) < 7)
3290    {
3291       log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3292       freez(*header);
3293       return JB_ERR_OK;
3294    }
3295
3296    if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3297        *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3298    {
3299
3300       p = strdup_or_die((*header)+6);
3301       chomp(p);
3302       q = strdup_or_die(p);
3303
3304       freez(csp->http->hostport);
3305       csp->http->hostport = p;
3306       freez(csp->http->host);
3307       csp->http->host = q;
3308       q = strchr(csp->http->host, ':');
3309       if (q != NULL)
3310       {
3311          /* Terminate hostname and evaluate port string */
3312          *q++ = '\0';
3313          csp->http->port = atoi(q);
3314       }
3315       else
3316       {
3317          csp->http->port = csp->http->ssl ? 443 : 80;
3318       }
3319
3320       log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3321                 csp->http->hostport, csp->http->host, csp->http->port);
3322    }
3323
3324    /* Signal client_host_adder() to return right away */
3325    csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3326
3327    return JB_ERR_OK;
3328 }
3329
3330
3331 /*********************************************************************
3332  *
3333  * Function    :  client_if_modified_since
3334  *
3335  * Description :  Remove or modify the If-Modified-Since header.
3336  *
3337  * Parameters  :
3338  *          1  :  csp = Current client state (buffers, headers, etc...)
3339  *          2  :  header = On input, pointer to header to modify.
3340  *                On output, pointer to the modified header, or NULL
3341  *                to remove the header.  This function frees the
3342  *                original string if necessary.
3343  *
3344  * Returns     :  JB_ERR_OK on success, or
3345  *                JB_ERR_MEMORY on out-of-memory error.
3346  *
3347  *********************************************************************/
3348 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3349 {
3350    char newheader[50];
3351 #ifdef HAVE_GMTIME_R
3352    struct tm gmt;
3353 #endif
3354    struct tm *timeptr = NULL;
3355    time_t tm = 0;
3356    const char *newval;
3357    char * endptr;
3358
3359    if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3360    {
3361       /*
3362        * The client got an error message because of a temporary problem,
3363        * the problem is gone and the client now tries to revalidate our
3364        * error message on the real server. The revalidation would always
3365        * end with the transmission of the whole document and there is
3366        * no need to expose the bogus If-Modified-Since header.
3367        */
3368       log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3369       freez(*header);
3370    }
3371    else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3372    {
3373       newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3374
3375       if ((0 == strcmpic(newval, "block")))
3376       {
3377          log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3378          freez(*header);
3379       }
3380       else /* add random value */
3381       {
3382          if (JB_ERR_OK != parse_time_header(*header, &tm))
3383          {
3384             log_error(LOG_LEVEL_HEADER,
3385                "Couldn't parse time in %s (crunching!)", *header);
3386             freez(*header);
3387          }
3388          else
3389          {
3390             long int hours, minutes, seconds;
3391             long int rtime = strtol(newval, &endptr, 0);
3392             const int negative_range = (rtime < 0);
3393
3394             if (rtime)
3395             {
3396                log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3397                   *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3398                if (negative_range)
3399                {
3400                   rtime *= -1;
3401                }
3402                rtime *= 60;
3403                rtime = pick_from_range(rtime);
3404             }
3405             else
3406             {
3407                log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3408                   *header);
3409             }
3410             tm += rtime * (negative_range ? -1 : 1);
3411 #ifdef HAVE_GMTIME_R
3412             timeptr = gmtime_r(&tm, &gmt);
3413 #elif defined(MUTEX_LOCKS_AVAILABLE)
3414             privoxy_mutex_lock(&gmtime_mutex);
3415             timeptr = gmtime(&tm);
3416             privoxy_mutex_unlock(&gmtime_mutex);
3417 #else
3418             timeptr = gmtime(&tm);
3419 #endif
3420             if ((NULL == timeptr) || !strftime(newheader,
3421                   sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3422             {
3423                log_error(LOG_LEVEL_ERROR,
3424                   "Randomizing '%s' failed. Crunching the header without replacement.",
3425                   *header);
3426                freez(*header);
3427                return JB_ERR_OK;
3428             }
3429
3430             freez(*header);
3431             *header = strdup("If-Modified-Since: ");
3432             string_append(header, newheader);
3433
3434             if (*header == NULL)
3435             {
3436                log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3437                return JB_ERR_MEMORY;
3438             }
3439
3440             hours   = rtime / 3600;
3441             minutes = rtime / 60 % 60;
3442             seconds = rtime % 60;
3443
3444             log_error(LOG_LEVEL_HEADER,
3445                "Randomized:  %s (%s %d hou%s %d minut%s %d second%s",
3446                *header, (negative_range) ? "subtracted" : "added", hours,
3447                (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3448                seconds, (seconds == 1) ? ")" : "s)");
3449          }
3450       }
3451    }
3452
3453    return JB_ERR_OK;
3454 }
3455
3456
3457 /*********************************************************************
3458  *
3459  * Function    :  client_if_none_match
3460  *
3461  * Description :  Remove the If-None-Match header.
3462  *
3463  * Parameters  :
3464  *          1  :  csp = Current client state (buffers, headers, etc...)
3465  *          2  :  header = On input, pointer to header to modify.
3466  *                On output, pointer to the modified header, or NULL
3467  *                to remove the header.  This function frees the
3468  *                original string if necessary.
3469  *
3470  * Returns     :  JB_ERR_OK on success, or
3471  *                JB_ERR_MEMORY on out-of-memory error.
3472  *
3473  *********************************************************************/
3474 static jb_err client_if_none_match(struct client_state *csp, char **header)
3475 {
3476    if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3477    {
3478       log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3479       freez(*header);
3480    }
3481
3482    return JB_ERR_OK;
3483 }
3484
3485
3486 /*********************************************************************
3487  *
3488  * Function    :  client_x_filter
3489  *
3490  * Description :  Disables filtering if the client set "X-Filter: No".
3491  *                Called from `sed'.
3492  *
3493  * Parameters  :
3494  *          1  :  csp = Current client state (buffers, headers, etc...)
3495  *          2  :  header = On input, pointer to header to modify.
3496  *                On output, pointer to the modified header, or NULL
3497  *                to remove the header.  This function frees the
3498  *                original string if necessary.
3499  *
3500  * Returns     :  JB_ERR_OK on success
3501  *
3502  *********************************************************************/
3503 jb_err client_x_filter(struct client_state *csp, char **header)
3504 {
3505    if (0 == strcmpic(*header, "X-Filter: No"))
3506    {
3507       if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3508       {
3509          log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3510       }
3511       else
3512       {
3513          if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3514          {
3515             log_error(LOG_LEVEL_HEADER,
3516                "force-text-mode overruled the client's request to fetch without filtering!");
3517          }
3518          else
3519          {
3520             csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3521             csp->flags |= CSP_FLAG_NO_FILTERING;
3522             log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3523          }
3524          log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3525          freez(*header);
3526       }
3527    }
3528    return JB_ERR_OK;
3529 }
3530
3531
3532 /*********************************************************************
3533  *
3534  * Function    :  client_range
3535  *
3536  * Description :  Removes Range, Request-Range and If-Range headers if
3537  *                content filtering is enabled and the range doesn't
3538  *                start at byte 0.
3539  *
3540  *                If the client's version of the document has been
3541  *                altered by Privoxy, the server could interpret the
3542  *                range differently than the client intended in which
3543  *                case the user could end up with corrupted content.
3544  *
3545  *                If the range starts at byte 0 this isn't an issue
3546  *                so the header can pass. Partial requests like this
3547  *                are used to render preview images for videos without
3548  *                downloading the whole video.
3549  *
3550  *                While HTTP doesn't require that range requests are
3551  *                honoured and the client could simply abort the download
3552  *                after receiving a sufficient amount of data, various
3553  *                clients don't handle complete responses to range
3554  *                requests gracefully and emit misleading error messages
3555  *                instead.
3556  *
3557  * Parameters  :
3558  *          1  :  csp = Current client state (buffers, headers, etc...)
3559  *          2  :  header = On input, pointer to header to modify.
3560  *                On output, pointer to the modified header, or NULL
3561  *                to remove the header.  This function frees the
3562  *                original string if necessary.
3563  *
3564  * Returns     :  JB_ERR_OK
3565  *
3566  *********************************************************************/
3567 static jb_err client_range(struct client_state *csp, char **header)
3568 {
3569    if (content_filters_enabled(csp->action)
3570       && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3571    {
3572       log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3573          " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3574       freez(*header);
3575    }
3576
3577    return JB_ERR_OK;
3578 }
3579
3580 /* the following functions add headers directly to the header list */
3581
3582 /*********************************************************************
3583  *
3584  * Function    :  client_host_adder
3585  *
3586  * Description :  Adds the Host: header field if it is missing.
3587  *                Called from `sed'.
3588  *
3589  * Parameters  :
3590  *          1  :  csp = Current client state (buffers, headers, etc...)
3591  *
3592  * Returns     :  JB_ERR_OK on success, or
3593  *                JB_ERR_MEMORY on out-of-memory error.
3594  *
3595  *********************************************************************/
3596 static jb_err client_host_adder(struct client_state *csp)
3597 {
3598    char *p;
3599    jb_err err;
3600
3601    if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3602    {
3603       /* Header already set by the client, nothing to do. */
3604       return JB_ERR_OK;
3605    }
3606
3607    if (!csp->http->hostport || !*(csp->http->hostport))
3608    {
3609       log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3610       return JB_ERR_PARSE;
3611    }
3612
3613    /*
3614     * remove 'user:pass@' from 'proto://user:pass@host'
3615     */
3616    if ((p = strchr( csp->http->hostport, '@')) != NULL)
3617    {
3618       p++;
3619    }
3620    else
3621    {
3622       p = csp->http->hostport;
3623    }
3624
3625    /* XXX: Just add it, we already made sure that it will be unique */
3626    log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3627    err = enlist_unique_header(csp->headers, "Host", p);
3628    return err;
3629
3630 }
3631
3632
3633 /*********************************************************************
3634  *
3635  * Function    :  client_xtra_adder
3636  *
3637  * Description :  Used in the add_client_headers list.  Called from `sed'.
3638  *
3639  * Parameters  :
3640  *          1  :  csp = Current client state (buffers, headers, etc...)
3641  *
3642  * Returns     :  JB_ERR_OK on success, or
3643  *                JB_ERR_MEMORY on out-of-memory error.
3644  *
3645  *********************************************************************/
3646 static jb_err client_xtra_adder(struct client_state *csp)
3647 {
3648    struct list_entry *lst;
3649    jb_err err;
3650
3651    for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3652         lst ; lst = lst->next)
3653    {
3654       log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3655       err = enlist(csp->headers, lst->str);
3656       if (err)
3657       {
3658          return err;
3659       }
3660
3661    }
3662
3663    return JB_ERR_OK;
3664 }
3665
3666
3667 /*********************************************************************
3668  *
3669  * Function    :  client_x_forwarded_for_adder
3670  *
3671  * Description :  Used in the add_client_headers list.  Called from `sed'.
3672  *
3673  * Parameters  :
3674  *          1  :  csp = Current client state (buffers, headers, etc...)
3675  *
3676  * Returns     :  JB_ERR_OK on success, or
3677  *                JB_ERR_MEMORY on out-of-memory error.
3678  *
3679  *********************************************************************/
3680 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3681 {
3682    char *header = NULL;
3683    jb_err err;
3684
3685    if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3686          && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3687       || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3688    {
3689       /*
3690        * If we aren't adding X-Forwarded-For headers,
3691        * or we already appended an existing X-Forwarded-For
3692        * header, there's nothing left to do here.
3693        */
3694       return JB_ERR_OK;
3695    }
3696
3697    header = strdup("X-Forwarded-For: ");
3698    string_append(&header, csp->ip_addr_str);
3699
3700    if (header == NULL)
3701    {
3702       return JB_ERR_MEMORY;
3703    }
3704
3705    log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3706    err = enlist(csp->headers, header);
3707    freez(header);
3708
3709    return err;
3710 }
3711
3712
3713 /*********************************************************************
3714  *
3715  * Function    :  server_connection_adder
3716  *
3717  * Description :  Adds an appropriate "Connection:" header to csp->headers
3718  *                unless the header was already present. Called from `sed'.
3719  *
3720  * Parameters  :
3721  *          1  :  csp = Current client state (buffers, headers, etc...)
3722  *
3723  * Returns     :  JB_ERR_OK on success, or
3724  *                JB_ERR_MEMORY on out-of-memory error.
3725  *
3726  *********************************************************************/
3727 static jb_err server_connection_adder(struct client_state *csp)
3728 {
3729    const unsigned int flags = csp->flags;
3730    const char *response_status_line = csp->headers->first->str;
3731    static const char connection_close[] = "Connection: close";
3732
3733    if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3734     && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3735    {
3736       return JB_ERR_OK;
3737    }
3738
3739    /*
3740     * XXX: if we downgraded the response, this check will fail.
3741     */
3742    if ((csp->config->feature_flags &
3743         RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3744     && (NULL != response_status_line)
3745     && !strncmpic(response_status_line, "HTTP/1.1", 8)
3746 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3747     && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3748 #endif
3749       )
3750    {
3751       log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3752          "without Connection header implies keep-alive.");
3753       csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3754       return JB_ERR_OK;
3755    }
3756
3757    log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3758
3759    return enlist(csp->headers, connection_close);
3760 }
3761
3762
3763 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3764 /*********************************************************************
3765  *
3766  * Function    :  server_proxy_connection_adder
3767  *
3768  * Description :  Adds a "Proxy-Connection: keep-alive" header to
3769  *                csp->headers when appropriate.
3770  *
3771  * Parameters  :
3772  *          1  :  csp = Current client state (buffers, headers, etc...)
3773  *
3774  * Returns     :  JB_ERR_OK on success, or
3775  *                JB_ERR_MEMORY on out-of-memory error.
3776  *
3777  *********************************************************************/
3778 static jb_err server_proxy_connection_adder(struct client_state *csp)
3779 {
3780    static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3781    jb_err err = JB_ERR_OK;
3782
3783    if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3784     && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3785     && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3786     && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3787        || (csp->flags & CSP_FLAG_CHUNKED)))
3788    {
3789       log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3790       err = enlist(csp->headers, proxy_connection_header);
3791    }
3792
3793    return err;
3794 }
3795 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3796
3797
3798 /*********************************************************************
3799  *
3800  * Function    :  client_connection_header_adder
3801  *
3802  * Description :  Adds a proper "Connection:" header to csp->headers
3803  *                unless the header was already present. Called from `sed'.
3804  *
3805  * Parameters  :
3806  *          1  :  csp = Current client state (buffers, headers, etc...)
3807  *
3808  * Returns     :  JB_ERR_OK on success, or
3809  *                JB_ERR_MEMORY on out-of-memory error.
3810  *
3811  *********************************************************************/
3812 static jb_err client_connection_header_adder(struct client_state *csp)
3813 {
3814    static const char connection_close[] = "Connection: close";
3815
3816    if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3817      && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3818    {
3819       return JB_ERR_OK;
3820    }
3821
3822 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3823    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3824       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3825       && (csp->http->ssl == 0)
3826       && !strcmpic(csp->http->ver, "HTTP/1.1"))
3827    {
3828       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3829       return JB_ERR_OK;
3830    }
3831 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3832
3833    log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3834
3835    return enlist(csp->headers, connection_close);
3836 }
3837
3838
3839 /*********************************************************************
3840  *
3841  * Function    :  server_http
3842  *
3843  * Description :  - Save the HTTP Status into csp->http->status
3844  *                - Set CT_TABOO to prevent filtering if the answer
3845  *                  is a partial range (HTTP status 206)
3846  *                - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3847  *                  action applies.
3848  *                - Normalize the HTTP-version.
3849  *
3850  * Parameters  :
3851  *          1  :  csp = Current client state (buffers, headers, etc...)
3852  *          2  :  header = On input, pointer to header to modify.
3853  *                On output, pointer to the modified header, or NULL
3854  *                to remove the header.  This function frees the
3855  *                original string if necessary.
3856  *
3857  * Returns     :  JB_ERR_OK on success, or
3858  *                JB_ERR_PARSE on fatal parse errors.
3859  *
3860  *********************************************************************/
3861 static jb_err server_http(struct client_state *csp, char **header)
3862 {
3863    char *reason_phrase = NULL;
3864    char *new_response_line;
3865    char *p;
3866    size_t length;
3867    unsigned int major_version;
3868    unsigned int minor_version;
3869
3870    /* Get the reason phrase which start after the second whitespace */
3871    p = strchr(*header, ' ');
3872    if (NULL != p)
3873    {
3874       p++;
3875       reason_phrase = strchr(p, ' ');
3876    }
3877
3878    if (reason_phrase != NULL)
3879    {
3880       reason_phrase++;
3881    }
3882    else
3883    {
3884       log_error(LOG_LEVEL_ERROR,
3885          "Response line lacks reason phrase: %s", *header);
3886       reason_phrase="";
3887    }
3888
3889    if (3 != sscanf(*header, "HTTP/%u.%u %d", &major_version,
3890          &minor_version, &(csp->http->status)))
3891    {
3892       log_error(LOG_LEVEL_ERROR,
3893          "Failed to parse the response line: %s", *header);
3894       return JB_ERR_PARSE;
3895    }
3896
3897    if (csp->http->status == 206)
3898    {
3899       csp->content_type = CT_TABOO;
3900    }
3901
3902    if (major_version != 1 || (minor_version != 0 && minor_version != 1))
3903    {
3904       /*
3905        * According to RFC 7230 2.6 intermediaries MUST send
3906        * their own HTTP-version in forwarded messages.
3907        */
3908       log_error(LOG_LEVEL_ERROR,
3909          "Unsupported HTTP version. Downgrading to 1.1.");
3910       major_version = 1;
3911       minor_version = 1;
3912    }
3913
3914    if (((csp->action->flags & ACTION_DOWNGRADE) != 0) && (minor_version == 1))
3915    {
3916       log_error(LOG_LEVEL_HEADER, "Downgrading answer to HTTP/1.0");
3917       minor_version = 0;
3918    }
3919
3920    /* Rebuild response line. */
3921    length = sizeof("HTTP/1.1 200 ") + strlen(reason_phrase) + 1;
3922    new_response_line = malloc_or_die(length);
3923
3924    snprintf(new_response_line, length, "HTTP/%u.%u %d %s",
3925       major_version, minor_version, csp->http->status, reason_phrase);
3926
3927    if (0 != strcmp(*header, new_response_line))
3928    {
3929       log_error(LOG_LEVEL_HEADER, "Response line '%s' changed to '%s'",
3930          *header, new_response_line);
3931    }
3932
3933    freez(*header);
3934    *header = new_response_line;
3935
3936    return JB_ERR_OK;
3937 }
3938
3939 /*********************************************************************
3940  *
3941  * Function    :  add_cooky_expiry_date
3942  *
3943  * Description :  Adds a cookie expiry date to a string.
3944  *
3945  * Parameters  :
3946  *          1  :  cookie = On input, pointer to cookie to modify.
3947  *                         On output, pointer to the modified header.
3948  *                         The original string is freed.
3949  *          2  :  lifetime = Seconds the cookie should be valid
3950  *
3951  * Returns     :  N/A
3952  *
3953  *********************************************************************/
3954 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
3955 {
3956    char tmp[50];
3957    struct tm *timeptr = NULL;
3958    time_t expiry_date = time(NULL) + lifetime;
3959 #ifdef HAVE_GMTIME_R
3960    struct tm gmt;
3961
3962    timeptr = gmtime_r(&expiry_date, &gmt);
3963 #elif defined(MUTEX_LOCKS_AVAILABLE)
3964    privoxy_mutex_lock(&gmtime_mutex);
3965    timeptr = gmtime(&expiry_date);
3966    privoxy_mutex_unlock(&gmtime_mutex);
3967 #else
3968    timeptr = gmtime(&expiry_date);
3969 #endif
3970
3971    if (NULL == timeptr)
3972    {
3973       log_error(LOG_LEVEL_FATAL,
3974          "Failed to get the time in add_cooky_expiry_date()");
3975    }
3976    strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
3977    if (JB_ERR_OK != string_append(cookie, tmp))
3978    {
3979       log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
3980    }
3981 }
3982
3983
3984 /*********************************************************************
3985  *
3986  * Function    :  server_set_cookie
3987  *
3988  * Description :  Handle the server "cookie" header properly.
3989  *                Crunch, accept or rewrite it to a session cookie.
3990  *                Called from `sed'.
3991  *
3992  * Parameters  :
3993  *          1  :  csp = Current client state (buffers, headers, etc...)
3994  *          2  :  header = On input, pointer to header to modify.
3995  *                On output, pointer to the modified header, or NULL
3996  *                to remove the header.  This function frees the
3997  *                original string if necessary.
3998  *
3999  * Returns     :  JB_ERR_OK on success, or
4000  *                JB_ERR_MEMORY on out-of-memory error.
4001  *
4002  *********************************************************************/
4003 static jb_err server_set_cookie(struct client_state *csp, char **header)
4004 {
4005    if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
4006    {
4007       log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
4008       freez(*header);
4009    }
4010    else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
4011          || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
4012    {
4013       time_t now;
4014       time_t cookie_time;
4015       long cookie_lifetime = 0;
4016       enum
4017       {
4018          NO_EXPIRY_DATE_SPECIFIED,
4019          EXPIRY_DATE_ACCEPTABLE,
4020          EXPIRY_DATE_UNACCEPTABLE
4021       } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
4022
4023       /* A variable to store the tag we're working on */
4024       char *cur_tag;
4025
4026       /* Skip "Set-Cookie:" (11 characters) in header */
4027       cur_tag = *header + 11;
4028
4029       /* skip whitespace between "Set-Cookie:" and value */
4030       while (*cur_tag && privoxy_isspace(*cur_tag))
4031       {
4032          cur_tag++;
4033       }
4034
4035       time(&now);
4036
4037       if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
4038       {
4039          const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
4040
4041          cookie_lifetime = strtol(param, NULL, 0);
4042          if (cookie_lifetime < 0)
4043          {
4044             log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
4045          }
4046          cookie_lifetime *= 60;
4047       }
4048
4049       /* Loop through each tag in the cookie */
4050       while (*cur_tag)
4051       {
4052          /* Find next tag */
4053          char *next_tag = strchr(cur_tag, ';');
4054          if (next_tag != NULL)
4055          {
4056             /* Skip the ';' character itself */
4057             next_tag++;
4058
4059             /* skip whitespace ";" and start of tag */
4060             while (*next_tag && privoxy_isspace(*next_tag))
4061             {
4062                next_tag++;
4063             }
4064          }
4065          else
4066          {
4067             /* "Next tag" is the end of the string */
4068             next_tag = cur_tag + strlen(cur_tag);
4069          }
4070
4071          /*
4072           * Check the expiration date to see
4073           * if the cookie is still valid, if yes,
4074           * rewrite it to a session cookie.
4075           */
4076          if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
4077          {
4078             char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
4079
4080             if ((expiration_date[0] == '"')
4081              && (expiration_date[1] != '\0'))
4082             {
4083                /*
4084                 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
4085                 * that the expiration date isn't supposed to be quoted,
4086                 * but some servers do it anyway.
4087                 */
4088                expiration_date++;
4089             }
4090
4091             /* Did we detect the date properly? */
4092             if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
4093             {
4094                /*
4095                 * Nope, treat it as if it was still valid.
4096                 *
4097                 * XXX: Should we remove the whole cookie instead?
4098                 */
4099                log_error(LOG_LEVEL_ERROR,
4100                   "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
4101                string_move(cur_tag, next_tag);
4102                expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4103             }
4104             else
4105             {
4106                /*
4107                 * Yes. Check if the cookie is still valid.
4108                 *
4109                 * If the cookie is already expired it's probably
4110                 * a delete cookie and even if it isn't, the browser
4111                 * will discard it anyway.
4112                 */
4113
4114                /*
4115                 * XXX: timegm() isn't available on some AmigaOS
4116                 * versions and our replacement doesn't work.
4117                 *
4118                 * Our options are to either:
4119                 *
4120                 * - disable session-cookies-only completely if timegm
4121                 *   is missing,
4122                 *
4123                 * - to simply remove all expired tags, like it has
4124                 *   been done until Privoxy 3.0.6 and to live with
4125                 *    the consequence that it can cause login/logout
4126                 *   problems on servers that don't validate their
4127                 *   input properly, or
4128                 *
4129                 * - to replace it with mktime in which
4130                 *   case there is a slight chance of valid cookies
4131                 *   passing as already expired.
4132                 *
4133                 *   This is the way it's currently done and it's not
4134                 *   as bad as it sounds. If the missing GMT offset is
4135                 *   enough to change the result of the expiration check
4136                 *   the cookie will be only valid for a few hours
4137                 *   anyway, which in many cases will be shorter
4138                 *   than a browser session.
4139                 */
4140                if (cookie_time < now)
4141                {
4142                   log_error(LOG_LEVEL_HEADER,
4143                      "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4144                   /* Just in case some clown sets more then one expiration date */
4145                   cur_tag = next_tag;
4146                   expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4147                }
4148                else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4149                {
4150                   log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4151                      "Its lifetime is below the limit.", *header);
4152                   /* Just in case some clown sets more then one expiration date */
4153                   cur_tag = next_tag;
4154                   expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4155                }
4156                else
4157                {
4158                   /*
4159                    * Still valid, delete expiration date by copying
4160                    * the rest of the string over it.
4161                    */
4162                   string_move(cur_tag, next_tag);
4163
4164                   /* That changed the header, need to issue a log message */
4165                   expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4166
4167                   /*
4168                    * Note that the next tag has now been moved to *cur_tag,
4169                    * so we do not need to update the cur_tag pointer.
4170                    */
4171                }
4172             }
4173
4174          }
4175          else
4176          {
4177             /* Move on to next cookie tag */
4178             cur_tag = next_tag;
4179          }
4180       }
4181
4182       if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4183       {
4184          assert(NULL != *header);
4185          if (cookie_lifetime != 0)
4186          {
4187             add_cookie_expiry_date(header, cookie_lifetime);
4188             log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4189          }
4190          else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4191          {
4192             log_error(LOG_LEVEL_HEADER,
4193                "Cookie rewritten to a temporary one: %s", *header);
4194          }
4195       }
4196    }
4197
4198    return JB_ERR_OK;
4199 }
4200
4201
4202 #ifdef FEATURE_FORCE_LOAD
4203 /*********************************************************************
4204  *
4205  * Function    :  strclean
4206  *
4207  * Description :  In-Situ-Eliminate all occurrences of substring in
4208  *                string
4209  *
4210  * Parameters  :
4211  *          1  :  string = string to clean
4212  *          2  :  substring = substring to eliminate
4213  *
4214  * Returns     :  Number of eliminations
4215  *
4216  *********************************************************************/
4217 int strclean(char *string, const char *substring)
4218 {
4219    int hits = 0;
4220    size_t len;
4221    char *pos, *p;
4222
4223    len = strlen(substring);
4224
4225    while((pos = strstr(string, substring)) != NULL)
4226    {
4227       p = pos + len;
4228       do
4229       {
4230          *(p - len) = *p;
4231       }
4232       while (*p++ != '\0');
4233
4234       hits++;
4235    }
4236
4237    return(hits);
4238 }
4239 #endif /* def FEATURE_FORCE_LOAD */
4240
4241
4242 /*********************************************************************
4243  *
4244  * Function    :  parse_header_time
4245  *
4246  * Description :  Parses time formats used in HTTP header strings
4247  *                to get the numerical respresentation.
4248  *
4249  * Parameters  :
4250  *          1  :  header_time = HTTP header time as string.
4251  *          2  :  result = storage for header_time in seconds
4252  *
4253  * Returns     :  JB_ERR_OK if the time format was recognized, or
4254  *                JB_ERR_PARSE otherwise.
4255  *
4256  *********************************************************************/
4257 static jb_err parse_header_time(const char *header_time, time_t *result)
4258 {
4259    struct tm gmt;
4260    /*
4261     * Checking for two-digit years first in an
4262     * attempt to work around GNU libc's strptime()
4263     * reporting negative year values when using %Y.
4264     */
4265    static const char time_formats[][22] = {
4266       /* Tue, 02-Jun-37 20:00:00 */
4267       "%a, %d-%b-%y %H:%M:%S",
4268       /* Tue, 02 Jun 2037 20:00:00 */
4269       "%a, %d %b %Y %H:%M:%S",
4270       /* Tue, 02-Jun-2037 20:00:00 */
4271       "%a, %d-%b-%Y %H:%M:%S",
4272       /* Tuesday, 02-Jun-2037 20:00:00 */
4273       "%A, %d-%b-%Y %H:%M:%S",
4274       /* Tuesday Jun 02 20:00:00 2037 */
4275       "%A %b %d %H:%M:%S %Y"
4276    };
4277    unsigned int i;
4278
4279    for (i = 0; i < SZ(time_formats); i++)
4280    {
4281       /*
4282        * Zero out gmt to prevent time zone offsets.
4283        * Documented to be required for GNU libc.
4284        */
4285       memset(&gmt, 0, sizeof(gmt));
4286
4287       if (NULL != strptime(header_time, time_formats[i], &gmt))
4288       {
4289          /* Sanity check for GNU libc. */
4290          if (gmt.tm_year < 0)
4291          {
4292             log_error(LOG_LEVEL_HEADER,
4293                "Failed to parse '%s' using '%s'. Moving on.",
4294                header_time, time_formats[i]);
4295             continue;
4296          }
4297          *result = timegm(&gmt);
4298
4299 #ifdef FEATURE_STRPTIME_SANITY_CHECKS
4300          /*
4301           * Verify that parsing the date recreated from the first
4302           * parse operation gets the previous result. If it doesn't,
4303           * either strptime() or strftime() are malfunctioning.
4304           *
4305           * We could string-compare the recreated date with the original
4306           * header date, but this leads to false positives as strptime()
4307           * may let %a accept all day formats while strftime() will only
4308           * create one.
4309           */
4310          {
4311             char recreated_date[100];
4312             struct tm *tm;
4313             time_t result2;
4314
4315             tm = gmtime(result);
4316             strftime(recreated_date, sizeof(recreated_date), time_formats[i], tm);
4317             memset(&gmt, 0, sizeof(gmt));
4318             if (NULL == strptime(recreated_date, time_formats[i], &gmt))
4319             {
4320                log_error(LOG_LEVEL_ERROR,
4321                   "Failed to parse '%s' generated with '%s' to recreate '%s'.",
4322                   recreated_date, time_formats[i], header_time);
4323                continue;
4324             }
4325             result2 = timegm(&gmt);
4326             if (*result != result2)
4327             {
4328                log_error(LOG_LEVEL_ERROR, "strftime() and strptime() disagree. "
4329                   "Format: '%s'. In: '%s', out: '%s'. %d != %d. Rejecting.",
4330                   time_formats[i], header_time, recreated_date, *result, result2);
4331                continue;
4332             }
4333          }
4334 #endif
4335
4336          return JB_ERR_OK;
4337       }
4338    }
4339
4340    return JB_ERR_PARSE;
4341
4342 }
4343
4344 /*********************************************************************
4345  *
4346  * Function    :  parse_time_header
4347  *
4348  * Description :  Parses the time in an HTTP time header to get
4349  *                the numerical respresentation.
4350  *
4351  * Parameters  :
4352  *          1  :  header = HTTP header with a time value
4353  *          2  :  result = storage for header_time in seconds
4354  *
4355  * Returns     :  JB_ERR_OK if the time format was recognized, or
4356  *                JB_ERR_PARSE otherwise.
4357  *
4358  *********************************************************************/
4359 static jb_err parse_time_header(const char *header, time_t *result)
4360 {
4361    const char *header_time;
4362
4363    header_time = strchr(header, ':');
4364
4365    /*
4366     * Currently this can't happen as all callers are called
4367     * through sed() which requires a header name followed by
4368     * a colon.
4369     */
4370    assert(header_time != NULL);
4371
4372    header_time++;
4373    if (*header_time == ' ')
4374    {
4375       header_time++;
4376    }
4377
4378    return parse_header_time(header_time, result);
4379
4380 }
4381
4382
4383 /*********************************************************************
4384  *
4385  * Function    :  get_destination_from_headers
4386  *
4387  * Description :  Parse the "Host:" header to get the request's destination.
4388  *                Only needed if the client's request was forcefully
4389  *                redirected into Privoxy.
4390  *
4391  *                Code mainly copied from client_host() which is currently
4392  *                run too late for this purpose.
4393  *
4394  * Parameters  :
4395  *          1  :  headers = List of headers (one of them hopefully being
4396  *                the "Host:" header)
4397  *          2  :  http = storage for the result (host, port and hostport).
4398  *
4399  * Returns     :  JB_ERR_MEMORY (or terminates) in case of memory problems,
4400  *                JB_ERR_PARSE if the host header couldn't be found,
4401  *                JB_ERR_OK otherwise.
4402  *
4403  *********************************************************************/
4404 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4405 {
4406    char *q;
4407    char *p;
4408    char *host;
4409
4410    assert(!http->ssl);
4411
4412    host = get_header_value(headers, "Host:");
4413
4414    if (NULL == host)
4415    {
4416       log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4417       return JB_ERR_PARSE;
4418    }
4419
4420    p = strdup_or_die(host);
4421    chomp(p);
4422    q = strdup_or_die(p);
4423
4424    freez(http->hostport);
4425    http->hostport = p;
4426    freez(http->host);
4427    http->host = q;
4428    q = strchr(http->host, ':');
4429    if (q != NULL)
4430    {
4431       /* Terminate hostname and evaluate port string */
4432       *q++ = '\0';
4433       http->port = atoi(q);
4434    }
4435    else
4436    {
4437       http->port = 80;
4438    }
4439
4440    /* Rebuild request URL */
4441    freez(http->url);
4442    http->url = strdup("http://");
4443    string_append(&http->url, http->hostport);
4444    string_append(&http->url, http->path);
4445    if (http->url == NULL)
4446    {
4447       return JB_ERR_MEMORY;
4448    }
4449
4450    log_error(LOG_LEVEL_HEADER,
4451       "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    return JB_ERR_OK;
4471
4472 }
4473
4474
4475 /*********************************************************************
4476  *
4477  * Function    :  create_forged_referrer
4478  *
4479  * Description :  Helper for client_referrer to forge a referer as
4480  *                'http://hostname[:port]/' to fool stupid
4481  *                checks for in-site links
4482  *
4483  * Parameters  :
4484  *          1  :  header   = Pointer to header pointer
4485  *          2  :  hostport = Host and optionally port as string
4486  *
4487  * Returns     :  JB_ERR_OK in case of success, or
4488  *                JB_ERR_MEMORY in case of memory problems.
4489  *
4490  *********************************************************************/
4491 static jb_err create_forged_referrer(char **header, const char *hostport)
4492 {
4493     assert(NULL == *header);
4494
4495     *header = strdup("Referer: http://");
4496     string_append(header, hostport);
4497     string_append(header, "/");
4498
4499     if (NULL == *header)
4500     {
4501        return JB_ERR_MEMORY;
4502     }
4503
4504     log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4505
4506     return JB_ERR_OK;
4507
4508 }
4509
4510
4511 /*********************************************************************
4512  *
4513  * Function    :  create_fake_referrer
4514  *
4515  * Description :  Helper for client_referrer to create a fake referrer
4516  *                based on a string supplied by the user.
4517  *
4518  * Parameters  :
4519  *          1  :  header   = Pointer to header pointer
4520  *          2  :  hosthost = Referrer to fake
4521  *
4522  * Returns     :  JB_ERR_OK in case of success, or
4523  *                JB_ERR_MEMORY in case of memory problems.
4524  *
4525  *********************************************************************/
4526 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4527 {
4528    assert(NULL == *header);
4529
4530    if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4531    {
4532       log_error(LOG_LEVEL_HEADER,
4533          "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4534    }
4535    *header = strdup("Referer: ");
4536    string_append(header, fake_referrer);
4537
4538    if (NULL == *header)
4539    {
4540       return JB_ERR_MEMORY;
4541    }
4542
4543    log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4544
4545    return JB_ERR_OK;
4546
4547 }
4548
4549
4550 /*********************************************************************
4551  *
4552  * Function    :  handle_conditional_hide_referrer_parameter
4553  *
4554  * Description :  Helper for client_referrer to crunch or forge
4555  *                the referrer header if the host has changed.
4556  *
4557  * Parameters  :
4558  *          1  :  header = Pointer to header pointer
4559  *          2  :  host   = The target host (may include the port)
4560  *          3  :  parameter_conditional_block = Boolean to signal
4561  *                if we're in conditional-block mode. If not set,
4562  *                we're in conditional-forge mode.
4563  *
4564  * Returns     :  JB_ERR_OK in case of success, or
4565  *                JB_ERR_MEMORY in case of memory problems.
4566  *
4567  *********************************************************************/
4568 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4569    const char *host, const int parameter_conditional_block)
4570 {
4571    char *referer = strdup_or_die(*header);
4572    const size_t hostlength = strlen(host);
4573    const char *referer_url = NULL;
4574
4575    /* referer begins with 'Referer: http[s]://' */
4576    if ((hostlength+17) < strlen(referer))
4577    {
4578       /*
4579        * Shorten referer to make sure the referer is blocked
4580        * if www.example.org/www.example.com-shall-see-the-referer/
4581        * links to www.example.com/
4582        */
4583       referer[hostlength+17] = '\0';
4584    }
4585    referer_url = strstr(referer, "http://");
4586    if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4587    {
4588       /* Host has changed, Referer is invalid or a https URL. */
4589       if (parameter_conditional_block)
4590       {
4591          log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4592          freez(*header);
4593       }
4594       else
4595       {
4596          freez(*header);
4597          freez(referer);
4598          return create_forged_referrer(header, host);
4599       }
4600    }
4601    freez(referer);
4602
4603    return JB_ERR_OK;
4604
4605 }
4606
4607
4608 /*********************************************************************
4609  *
4610  * Function    :  create_content_length_header
4611  *
4612  * Description :  Creates a Content-Length header.
4613  *
4614  * Parameters  :
4615  *          1  :  content_length = The content length to be used in the header.
4616  *          2  :  header = Allocated space to safe the header.
4617  *          3  :  buffer_length = The length of the allocated space.
4618  *
4619  * Returns     :  void
4620  *
4621  *********************************************************************/
4622 static void create_content_length_header(unsigned long long content_length,
4623                                          char *header, size_t buffer_length)
4624 {
4625    snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4626 }
4627
4628
4629 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4630 /*********************************************************************
4631  *
4632  * Function    :  get_expected_content_length
4633  *
4634  * Description :  Figures out the content length from a list of headers.
4635  *
4636  * Parameters  :
4637  *          1  :  headers = List of headers
4638  *
4639  * Returns     :  Number of bytes to expect
4640  *
4641  *********************************************************************/
4642 unsigned long long get_expected_content_length(struct list *headers)
4643 {
4644    const char *content_length_header;
4645    unsigned long long content_length = 0;
4646
4647    content_length_header = get_header_value(headers, "Content-Length:");
4648    if (content_length_header != NULL)
4649    {
4650       if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4651       {
4652          log_error(LOG_LEVEL_ERROR,
4653             "Failed to get the Content-Length in %s", content_length_header);
4654          /* XXX: The header will be removed later on */
4655          return 0;
4656       }
4657    }
4658
4659    return content_length;
4660 }
4661 #endif
4662
4663 /*
4664   Local Variables:
4665   tab-width: 3
4666   end:
4667 */