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