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