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