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