1 const char parsers_rcs[] = "$Id: parsers.c,v 1.188 2009/07/05 12:02:54 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
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'.
20 * Copyright : Written by and Copyright (C) 2001-2009 the
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
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.
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.
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.
45 *********************************************************************/
52 #include <sys/types.h>
62 * Convince GNU's libc to provide a strptime prototype.
71 #define GZIP_IDENTIFIER_1 0x1f
72 #define GZIP_IDENTIFIER_2 0x8b
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
81 #if !defined(_WIN32) && !defined(__OS2__)
87 #ifdef FEATURE_PTHREAD
89 /* jcc.h is for mutex semapores only */
90 #endif /* def FEATURE_PTHREAD */
95 #include "jbsockets.h"
101 #ifndef HAVE_STRPTIME
102 #include "strptime.h"
105 const char parsers_h_rcs[] = PARSERS_H_VERSION;
107 /* Fix a problem with Solaris. There should be no effect on other
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".
114 * Why did they write a character function that can't take a simple
115 * "char" argument? Doh!
117 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
118 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
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);
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);
156 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
157 static jb_err server_save_content_length(struct client_state *csp, char **header);
158 static jb_err server_keep_alive(struct client_state *csp, char **header);
159 static jb_err client_keep_alive(struct client_state *csp, char **header);
160 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
162 static jb_err client_host_adder (struct client_state *csp);
163 static jb_err client_xtra_adder (struct client_state *csp);
164 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
165 static jb_err client_connection_header_adder(struct client_state *csp);
166 static jb_err server_connection_adder(struct client_state *csp);
167 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
168 static jb_err server_proxy_connection_adder(struct client_state *csp);
169 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
171 static jb_err create_forged_referrer(char **header, const char *hostport);
172 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
173 static jb_err handle_conditional_hide_referrer_parameter(char **header,
174 const char *host, const int parameter_conditional_block);
175 static const char *get_appropiate_connection_header(const struct client_state *csp);
176 static void create_content_length_header(unsigned long long content_length,
177 char *header, size_t buffer_length);
180 * List of functions to run on a list of headers.
184 /** The header prefix to match */
187 /** The length of the prefix to match */
190 /** The function to apply to this line */
191 const parser_func_ptr parser;
194 static const struct parsers client_patterns[] = {
195 { "referer:", 8, client_referrer },
196 { "user-agent:", 11, client_uagent },
197 { "ua-", 3, client_ua },
198 { "from:", 5, client_from },
199 { "cookie:", 7, client_send_cookie },
200 { "x-forwarded-for:", 16, client_x_forwarded },
201 { "Accept-Encoding:", 16, client_accept_encoding },
202 { "TE:", 3, client_te },
203 { "Host:", 5, client_host },
204 { "if-modified-since:", 18, client_if_modified_since },
205 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
206 { "Keep-Alive:", 11, client_keep_alive },
208 { "Keep-Alive:", 11, crumble },
210 { "connection:", 11, client_connection },
211 { "proxy-connection:", 17, crumble },
212 { "max-forwards:", 13, client_max_forwards },
213 { "Accept-Language:", 16, client_accept_language },
214 { "if-none-match:", 14, client_if_none_match },
215 { "Range:", 6, client_range },
216 { "Request-Range:", 14, client_range },
217 { "If-Range:", 9, client_range },
218 { "X-Filter:", 9, client_x_filter },
219 { "*", 0, crunch_client_header },
220 { "*", 0, filter_header },
224 static const struct parsers server_patterns[] = {
225 { "HTTP/", 5, server_http },
226 { "set-cookie:", 11, server_set_cookie },
227 { "connection:", 11, server_connection },
228 { "Content-Type:", 13, server_content_type },
229 { "Content-MD5:", 12, server_content_md5 },
230 { "Content-Encoding:", 17, server_content_encoding },
231 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
232 { "Content-Length:", 15, server_save_content_length },
233 { "Keep-Alive:", 11, server_keep_alive },
235 { "Keep-Alive:", 11, crumble },
236 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
237 { "Transfer-Encoding:", 18, server_transfer_coding },
238 { "content-disposition:", 20, server_content_disposition },
239 { "Last-Modified:", 14, server_last_modified },
240 { "*", 0, crunch_server_header },
241 { "*", 0, filter_header },
245 static const add_header_func_ptr add_client_headers[] = {
247 client_x_forwarded_for_adder,
249 /* Temporarily disabled: client_accept_encoding_adder, */
250 client_connection_header_adder,
254 static const add_header_func_ptr add_server_headers[] = {
255 server_connection_adder,
256 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
257 server_proxy_connection_adder,
258 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
262 /*********************************************************************
264 * Function : flush_socket
266 * Description : Write any pending "buffered" content.
269 * 1 : fd = file descriptor of the socket to read
270 * 2 : iob = The I/O buffer to flush, usually csp->iob.
272 * Returns : On success, the number of bytes written are returned (zero
273 * indicates nothing was written). On error, -1 is returned,
274 * and errno is set appropriately. If count is zero and the
275 * file descriptor refers to a regular file, 0 will be
276 * returned without causing any other effect. For a special
277 * file, the results are not portable.
279 *********************************************************************/
280 long flush_socket(jb_socket fd, struct iob *iob)
282 long len = iob->eod - iob->cur;
289 if (write_socket(fd, iob->cur, (size_t)len))
293 iob->eod = iob->cur = iob->buf;
299 /*********************************************************************
301 * Function : add_to_iob
303 * Description : Add content to the buffered page, expanding the
304 * buffer if necessary.
307 * 1 : csp = Current client state (buffers, headers, etc...)
308 * 2 : buf = holds the content to be added to the page
309 * 3 : n = number of bytes to be added
311 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
312 * or buffer limit reached.
314 *********************************************************************/
315 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
317 struct iob *iob = csp->iob;
318 size_t used, offset, need, want;
321 if (n <= 0) return JB_ERR_OK;
323 used = (size_t)(iob->eod - iob->buf);
324 offset = (size_t)(iob->cur - iob->buf);
325 need = used + (size_t)n + 1;
328 * If the buffer can't hold the new data, extend it first.
329 * Use the next power of two if possible, else use the actual need.
331 if (need > csp->config->buffer_limit)
333 log_error(LOG_LEVEL_INFO,
334 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
335 need, csp->config->buffer_limit);
336 return JB_ERR_MEMORY;
339 if (need > iob->size)
341 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
343 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
347 else if (NULL != (p = (char *)realloc(iob->buf, need)))
353 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
354 return JB_ERR_MEMORY;
357 /* Update the iob pointers */
358 iob->cur = p + offset;
363 /* copy the new data into the iob buffer */
364 memcpy(iob->eod, buf, (size_t)n);
366 /* point to the end of the data */
369 /* null terminate == cheap insurance */
378 /*********************************************************************
380 * Function : decompress_iob
382 * Description : Decompress buffered page, expanding the
383 * buffer as necessary. csp->iob->cur
384 * should point to the the beginning of the
385 * compressed data block.
388 * 1 : csp = Current client state (buffers, headers, etc...)
390 * Returns : JB_ERR_OK on success,
391 * JB_ERR_MEMORY if out-of-memory limit reached, and
392 * JB_ERR_COMPRESS if error decompressing buffer.
394 *********************************************************************/
395 jb_err decompress_iob(struct client_state *csp)
397 char *buf; /* new, uncompressed buffer */
398 char *cur; /* Current iob position (to keep the original
399 * iob->cur unmodified if we return early) */
400 size_t bufsize; /* allocated size of the new buffer */
401 size_t old_size; /* Content size before decompression */
402 size_t skip_size; /* Number of bytes at the beginning of the iob
403 that we should NOT decompress. */
404 int status; /* return status of the inflate() call */
405 z_stream zstr; /* used by calls to zlib */
407 assert(csp->iob->cur - csp->iob->buf > 0);
408 assert(csp->iob->eod - csp->iob->cur > 0);
410 bufsize = csp->iob->size;
411 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
412 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
416 if (bufsize < (size_t)10)
419 * This is to protect the parsing of gzipped data,
420 * but it should(?) be valid for deflated data also.
422 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
423 return JB_ERR_COMPRESS;
426 if (csp->content_type & CT_GZIP)
429 * Our task is slightly complicated by the facts that data
430 * compressed by gzip does not include a zlib header, and
431 * that there is no easily accessible interface in zlib to
432 * handle a gzip header. We strip off the gzip header by
433 * hand, and later inform zlib not to expect a header.
437 * Strip off the gzip header. Please see RFC 1952 for more
438 * explanation of the appropriate fields.
440 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
441 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
442 || (*cur++ != Z_DEFLATED))
444 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
445 return JB_ERR_COMPRESS;
450 if (flags & GZIP_FLAG_RESERVED_BITS)
452 /* The gzip header has reserved bits set; bail out. */
453 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
454 return JB_ERR_COMPRESS;
458 * Skip mtime (4 bytes), extra flags (1 byte)
459 * and OS type (1 byte).
463 /* Skip extra fields if necessary. */
464 if (flags & GZIP_FLAG_EXTRA_FIELDS)
467 * Skip a given number of bytes, specified
468 * as a 16-bit little-endian value.
470 * XXX: this code is untested and should probably be removed.
474 skip_bytes += *cur++ << 8;
477 * The number of bytes to skip should be positive
478 * and we'd like to stay in the buffer.
480 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
482 log_error(LOG_LEVEL_ERROR,
483 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
485 return JB_ERR_COMPRESS;
487 log_error(LOG_LEVEL_INFO,
488 "Skipping %d bytes for gzip compression. Does this sound right?",
493 /* Skip the filename if necessary. */
494 if (flags & GZIP_FLAG_FILE_NAME)
496 /* A null-terminated string is supposed to follow. */
497 while (*cur++ && (cur < csp->iob->eod));
500 /* Skip the comment if necessary. */
501 if (flags & GZIP_FLAG_COMMENT)
503 /* A null-terminated string is supposed to follow. */
504 while (*cur++ && (cur < csp->iob->eod));
507 /* Skip the CRC if necessary. */
508 if (flags & GZIP_FLAG_CHECKSUM)
513 if (cur >= csp->iob->eod)
516 * If the current position pointer reached or passed
517 * the buffer end, we were obviously tricked to skip
520 log_error(LOG_LEVEL_ERROR,
521 "Malformed gzip header detected. Aborting decompression.");
522 return JB_ERR_COMPRESS;
526 else if (csp->content_type & CT_DEFLATE)
529 * XXX: The debug level should be lowered
530 * before the next stable release.
532 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
534 * In theory (that is, according to RFC 1950), deflate-compressed
535 * data should begin with a two-byte zlib header and have an
536 * adler32 checksum at the end. It seems that in practice only
537 * the raw compressed data is sent. Note that this means that
538 * we are not RFC 1950-compliant here, but the advantage is that
539 * this actually works. :)
541 * We add a dummy null byte to tell zlib where the data ends,
542 * and later inform it not to expect a header.
544 * Fortunately, add_to_iob() has thoughtfully null-terminated
545 * the buffer; we can just increment the end pointer to include
552 log_error(LOG_LEVEL_ERROR,
553 "Unable to determine compression format for decompression");
554 return JB_ERR_COMPRESS;
557 /* Set up the fields required by zlib. */
558 zstr.next_in = (Bytef *)cur;
559 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
560 zstr.zalloc = Z_NULL;
562 zstr.opaque = Z_NULL;
565 * Passing -MAX_WBITS to inflateInit2 tells the library
566 * that there is no zlib header.
568 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
570 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
571 return JB_ERR_COMPRESS;
575 * Next, we allocate new storage for the inflated data.
576 * We don't modify the existing iob yet, so in case there
577 * is error in decompression we can recover gracefully.
579 buf = zalloc(bufsize);
582 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
583 return JB_ERR_MEMORY;
586 assert(bufsize >= skip_size);
587 memcpy(buf, csp->iob->buf, skip_size);
588 zstr.avail_out = bufsize - skip_size;
589 zstr.next_out = (Bytef *)buf + skip_size;
591 /* Try to decompress the whole stream in one shot. */
592 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
594 /* We need to allocate more memory for the output buffer. */
596 char *tmpbuf; /* used for realloc'ing the buffer */
597 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
599 if (0 == zstr.avail_in)
602 * If zlib wants more data then there's a problem, because
603 * the complete compressed file should have been buffered.
605 log_error(LOG_LEVEL_ERROR,
606 "Unexpected end of compressed iob. Using what we got so far.");
611 * If we tried the limit and still didn't have enough
612 * memory, just give up.
614 if (bufsize == csp->config->buffer_limit)
616 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
617 return JB_ERR_MEMORY;
620 /* Try doubling the buffer size each time. */
623 /* Don't exceed the buffer limit. */
624 if (bufsize > csp->config->buffer_limit)
626 bufsize = csp->config->buffer_limit;
629 /* Try to allocate the new buffer. */
630 tmpbuf = realloc(buf, bufsize);
633 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
635 return JB_ERR_MEMORY;
639 char *oldnext_out = (char *)zstr.next_out;
642 * Update the fields for inflate() to use the new
643 * buffer, which may be in a location different from
646 zstr.avail_out += bufsize - oldbufsize;
647 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
650 * Compare with an uglier method of calculating these values
651 * that doesn't require the extra oldbufsize variable.
653 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
654 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
655 assert(zstr.avail_out > 0U);
661 if (Z_STREAM_ERROR == inflateEnd(&zstr))
663 log_error(LOG_LEVEL_ERROR,
664 "Inconsistent stream state after decompression: %s", zstr.msg);
666 * XXX: Intentionally no return.
668 * According to zlib.h, Z_STREAM_ERROR is returned
669 * "if the stream state was inconsistent".
671 * I assume in this case inflate()'s status
672 * would also be something different than Z_STREAM_END
673 * so this check should be redundant, but lets see.
677 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
680 * We failed to decompress the stream and it's
681 * not simply because of missing data.
683 log_error(LOG_LEVEL_ERROR,
684 "Unexpected error while decompressing to the buffer (iob): %s",
686 return JB_ERR_COMPRESS;
690 * Finally, we can actually update the iob, since the
691 * decompression was successful. First, free the old
694 freez(csp->iob->buf);
696 /* Now, update the iob to use the new buffer. */
698 csp->iob->cur = csp->iob->buf + skip_size;
699 csp->iob->eod = (char *)zstr.next_out;
700 csp->iob->size = bufsize;
703 * Make sure the new uncompressed iob obeys some minimal
704 * consistency conditions.
706 if ((csp->iob->buf < csp->iob->cur)
707 && (csp->iob->cur <= csp->iob->eod)
708 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
710 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
711 if (new_size > (size_t)0)
713 log_error(LOG_LEVEL_RE_FILTER,
714 "Decompression successful. Old size: %d, new size: %d.",
719 /* zlib thinks this is OK, so lets do the same. */
720 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
725 /* It seems that zlib did something weird. */
726 log_error(LOG_LEVEL_ERROR,
727 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
728 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
729 csp->iob->eod, csp->iob->buf + csp->iob->size);
730 return JB_ERR_COMPRESS;
736 #endif /* defined(FEATURE_ZLIB) */
739 /*********************************************************************
741 * Function : string_move
743 * Description : memmove wrapper to move the last part of a string
744 * towards the beginning, overwriting the part in
745 * the middle. strlcpy() can't be used here as the
749 * 1 : dst = Destination to overwrite
750 * 2 : src = Source to move.
754 *********************************************************************/
755 static void string_move(char *dst, char *src)
759 /* +1 to copy the terminating nul as well. */
760 memmove(dst, src, strlen(src)+1);
764 /*********************************************************************
766 * Function : normalize_lws
768 * Description : Reduces unquoted linear white space in headers
769 * to a single space in accordance with RFC 2616 2.2.
770 * This simplifies parsing and filtering later on.
772 * XXX: Remove log messages before
773 * the next stable release?
776 * 1 : header = A header with linear white space to reduce.
780 *********************************************************************/
781 static void normalize_lws(char *header)
787 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
791 while (ijb_isspace(*q))
795 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
801 log_error(LOG_LEVEL_HEADER,
802 "Converting tab to space in '%s'", header);
807 char *end_of_token = strstr(p+1, "\"");
809 if (NULL != end_of_token)
811 /* Don't mess with quoted text. */
816 log_error(LOG_LEVEL_HEADER,
817 "Ignoring single quote in '%s'", header);
823 p = strchr(header, ':');
824 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
827 * There's still space before the colon.
835 /*********************************************************************
837 * Function : get_header
839 * Description : This (odd) routine will parse the csp->iob
840 * to get the next complete header.
843 * 1 : iob = The I/O buffer to parse, usually csp->iob.
845 * Returns : Any one of the following:
847 * 1) a pointer to a dynamically allocated string that contains a header line
848 * 2) NULL indicating that the end of the header was reached
849 * 3) "" indicating that the end of the iob was reached before finding
850 * a complete header line.
852 *********************************************************************/
853 char *get_header(struct iob *iob)
857 header = get_header_line(iob);
859 if ((header == NULL) || (*header == '\0'))
862 * No complete header read yet, tell the client.
867 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
870 * Header spans multiple lines, append the next one.
872 char *continued_header;
874 continued_header = get_header_line(iob);
875 if ((continued_header == NULL) || (*continued_header == '\0'))
878 * No complete header read yet, return what we got.
879 * XXX: Should "unread" header instead.
881 log_error(LOG_LEVEL_INFO,
882 "Failed to read a multi-line header properly: '%s'",
887 if (JB_ERR_OK != string_join(&header, continued_header))
889 log_error(LOG_LEVEL_FATAL,
890 "Out of memory while appending multiple headers.");
894 /* XXX: remove before next stable release. */
895 log_error(LOG_LEVEL_HEADER,
896 "Merged multiple header lines to: '%s'",
901 normalize_lws(header);
908 /*********************************************************************
910 * Function : get_header_line
912 * Description : This (odd) routine will parse the csp->iob
913 * to get the next header line.
916 * 1 : iob = The I/O buffer to parse, usually csp->iob.
918 * Returns : Any one of the following:
920 * 1) a pointer to a dynamically allocated string that contains a header line
921 * 2) NULL indicating that the end of the header was reached
922 * 3) "" indicating that the end of the iob was reached before finding
923 * a complete header line.
925 *********************************************************************/
926 static char *get_header_line(struct iob *iob)
930 if ((iob->cur == NULL)
931 || ((p = strchr(iob->cur, '\n')) == NULL))
933 return(""); /* couldn't find a complete header */
938 ret = strdup(iob->cur);
941 /* FIXME No way to handle error properly */
942 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
948 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
950 /* is this a blank line (i.e. the end of the header) ? */
962 /*********************************************************************
964 * Function : get_header_value
966 * Description : Get the value of a given header from a chained list
967 * of header lines or return NULL if no such header is
968 * present in the list.
971 * 1 : header_list = pointer to list
972 * 2 : header_name = string with name of header to look for.
973 * Trailing colon required, capitalization
976 * Returns : NULL if not found, else value of header
978 *********************************************************************/
979 char *get_header_value(const struct list *header_list, const char *header_name)
981 struct list_entry *cur_entry;
987 length = strlen(header_name);
989 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
993 if (!strncmpic(cur_entry->str, header_name, length))
996 * Found: return pointer to start of value
998 ret = cur_entry->str + length;
999 while (*ret && ijb_isspace(*ret)) ret++;
1013 /*********************************************************************
1015 * Function : scan_headers
1017 * Description : Scans headers, applies tags and updates action bits.
1020 * 1 : csp = Current client state (buffers, headers, etc...)
1022 * Returns : JB_ERR_OK
1024 *********************************************************************/
1025 static jb_err scan_headers(struct client_state *csp)
1027 struct list_entry *h; /* Header */
1028 jb_err err = JB_ERR_OK;
1030 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1032 /* Header crunch()ed in previous run? -> ignore */
1033 if (h->str == NULL) continue;
1034 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1035 err = header_tagger(csp, h->str);
1042 /*********************************************************************
1046 * Description : add, delete or modify lines in the HTTP header streams.
1047 * On entry, it receives a linked list of headers space
1048 * that was allocated dynamically (both the list nodes
1049 * and the header contents).
1051 * As a side effect it frees the space used by the original
1055 * 1 : csp = Current client state (buffers, headers, etc...)
1056 * 2 : filter_server_headers = Boolean to switch between
1057 * server and header filtering.
1059 * Returns : JB_ERR_OK in case off success, or
1060 * JB_ERR_MEMORY on out-of-memory error.
1062 *********************************************************************/
1063 jb_err sed(struct client_state *csp, int filter_server_headers)
1065 /* XXX: use more descriptive names. */
1066 struct list_entry *p;
1067 const struct parsers *v;
1068 const add_header_func_ptr *f;
1069 jb_err err = JB_ERR_OK;
1071 if (filter_server_headers)
1073 v = server_patterns;
1074 f = add_server_headers;
1078 v = client_patterns;
1079 f = add_client_headers;
1084 while ((err == JB_ERR_OK) && (v->str != NULL))
1086 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1088 /* Header crunch()ed in previous run? -> ignore */
1089 if (p->str == NULL) continue;
1091 /* Does the current parser handle this header? */
1092 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1093 (v->len == CHECK_EVERY_HEADER_REMAINING))
1095 err = v->parser(csp, &(p->str));
1101 /* place additional headers on the csp->headers list */
1102 while ((err == JB_ERR_OK) && (*f))
1112 /*********************************************************************
1114 * Function : update_server_headers
1116 * Description : Updates server headers after the body has been modified.
1119 * 1 : csp = Current client state (buffers, headers, etc...)
1121 * Returns : JB_ERR_OK in case off success, or
1122 * JB_ERR_MEMORY on out-of-memory error.
1124 *********************************************************************/
1125 jb_err update_server_headers(struct client_state *csp)
1127 jb_err err = JB_ERR_OK;
1129 static const struct parsers server_patterns_light[] = {
1130 { "Content-Length:", 15, server_adjust_content_length },
1131 { "Transfer-Encoding:", 18, server_transfer_coding },
1133 { "Content-Encoding:", 17, server_content_encoding },
1134 #endif /* def FEATURE_ZLIB */
1138 if (strncmpic(csp->http->cmd, "HEAD", 4))
1140 const struct parsers *v;
1141 struct list_entry *p;
1143 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1145 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1147 /* Header crunch()ed in previous run? -> ignore */
1148 if (p->str == NULL) continue;
1150 /* Does the current parser handle this header? */
1151 if (strncmpic(p->str, v->str, v->len) == 0)
1153 err = v->parser(csp, (char **)&(p->str));
1159 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1160 if ((JB_ERR_OK == err)
1161 && (csp->flags & CSP_FLAG_MODIFIED)
1162 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1163 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1167 create_content_length_header(csp->content_length, header, sizeof(header));
1168 err = enlist(csp->headers, header);
1169 if (JB_ERR_OK == err)
1171 log_error(LOG_LEVEL_HEADER,
1172 "Content modified with no Content-Length header set. "
1173 "Created: %s.", header);
1176 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1182 /*********************************************************************
1184 * Function : header_tagger
1186 * Description : Executes all text substitutions from applying
1187 * tag actions and saves the result as tag.
1189 * XXX: Shares enough code with filter_header() and
1190 * pcrs_filter_response() to warrant some helper functions.
1193 * 1 : csp = Current client state (buffers, headers, etc...)
1194 * 2 : header = Header that is used as tagger input
1196 * Returns : JB_ERR_OK on success and always succeeds
1198 *********************************************************************/
1199 static jb_err header_tagger(struct client_state *csp, char *header)
1201 int wanted_filter_type;
1202 int multi_action_index;
1206 struct file_list *fl;
1207 struct re_filterfile_spec *b;
1208 struct list_entry *tag_name;
1210 int found_filters = 0;
1211 const size_t header_length = strlen(header);
1213 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1215 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1216 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1220 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1221 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1224 /* Check if there are any filters */
1225 for (i = 0; i < MAX_AF_FILES; i++)
1238 if (0 == found_filters)
1240 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1241 "tagging enabled, but no taggers available.");
1245 for (i = 0; i < MAX_AF_FILES; i++)
1248 if ((NULL == fl) || (NULL == fl->f))
1251 * Either there are no filter files
1252 * left, or this filter file just
1253 * contains no valid filters.
1255 * Continue to be sure we don't miss
1256 * valid filter files that are chained
1257 * after empty or invalid ones.
1262 /* For all filters, */
1263 for (b = fl->f; b; b = b->next)
1265 if (b->type != wanted_filter_type)
1267 /* skip the ones we don't care about, */
1270 /* leaving only taggers that could apply, of which we use the ones, */
1271 for (tag_name = csp->action->multi[multi_action_index]->first;
1272 NULL != tag_name; tag_name = tag_name->next)
1274 /* that do apply, and */
1275 if (strcmp(b->name, tag_name->str) == 0)
1277 char *modified_tag = NULL;
1279 size_t size = header_length;
1280 pcrs_job *joblist = b->joblist;
1282 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1284 if (NULL == joblist)
1286 log_error(LOG_LEVEL_RE_FILTER,
1287 "Tagger %s has empty joblist. Nothing to do.", b->name);
1291 /* execute their pcrs_joblist on the header. */
1292 for (job = joblist; NULL != job; job = job->next)
1294 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1298 /* Success, continue with the modified version. */
1307 /* Tagger doesn't match */
1310 /* Regex failure, log it but continue anyway. */
1311 assert(NULL != header);
1312 log_error(LOG_LEVEL_ERROR,
1313 "Problems with tagger \'%s\' and header \'%s\': %s",
1314 b->name, *header, pcrs_strerror(hits));
1316 freez(modified_tag);
1320 if (b->dynamic) pcrs_free_joblist(joblist);
1322 /* If this tagger matched */
1328 * There is to technical limitation which makes
1329 * it impossible to use empty tags, but I assume
1330 * no one would do it intentionally.
1333 log_error(LOG_LEVEL_INFO,
1334 "Tagger \'%s\' created an empty tag. Ignored.",
1339 if (!list_contains_item(csp->tags, tag))
1341 if (JB_ERR_OK != enlist(csp->tags, tag))
1343 log_error(LOG_LEVEL_ERROR,
1344 "Insufficient memory to add tag \'%s\', "
1345 "based on tagger \'%s\' and header \'%s\'",
1346 tag, b->name, *header);
1350 char *action_message;
1352 * update the action bits right away, to make
1353 * tagging based on tags set by earlier taggers
1354 * of the same kind possible.
1356 if (update_action_bits_for_tag(csp, tag))
1358 action_message = "Action bits updated accordingly.";
1362 action_message = "No action bits update necessary.";
1365 log_error(LOG_LEVEL_HEADER,
1366 "Tagger \'%s\' added tag \'%s\'. %s",
1367 b->name, tag, action_message);
1372 /* XXX: Is this log-worthy? */
1373 log_error(LOG_LEVEL_HEADER,
1374 "Tagger \'%s\' didn't add tag \'%s\'. "
1375 "Tag already present", b->name, tag);
1378 } /* if the tagger matched */
1379 } /* if the tagger applies */
1380 } /* for every tagger that could apply */
1381 } /* for all filters */
1382 } /* for all filter files */
1387 /* here begins the family of parser functions that reformat header lines */
1389 /*********************************************************************
1391 * Function : filter_header
1393 * Description : Executes all text substitutions from all applying
1394 * +(server|client)-header-filter actions on the header.
1395 * Most of the code was copied from pcrs_filter_response,
1396 * including the rather short variable names
1399 * 1 : csp = Current client state (buffers, headers, etc...)
1400 * 2 : header = On input, pointer to header to modify.
1401 * On output, pointer to the modified header, or NULL
1402 * to remove the header. This function frees the
1403 * original string if necessary.
1405 * Returns : JB_ERR_OK on success and always succeeds
1407 *********************************************************************/
1408 static jb_err filter_header(struct client_state *csp, char **header)
1412 size_t size = strlen(*header);
1414 char *newheader = NULL;
1417 struct file_list *fl;
1418 struct re_filterfile_spec *b;
1419 struct list_entry *filtername;
1421 int i, found_filters = 0;
1422 int wanted_filter_type;
1423 int multi_action_index;
1425 if (csp->flags & CSP_FLAG_NO_FILTERING)
1430 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1432 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1433 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1437 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1438 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1442 * Need to check the set of re_filterfiles...
1444 for (i = 0; i < MAX_AF_FILES; i++)
1457 if (0 == found_filters)
1459 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1460 "header filtering enabled, but no matching filters available.");
1464 for (i = 0; i < MAX_AF_FILES; i++)
1467 if ((NULL == fl) || (NULL == fl->f))
1470 * Either there are no filter files
1471 * left, or this filter file just
1472 * contains no valid filters.
1474 * Continue to be sure we don't miss
1475 * valid filter files that are chained
1476 * after empty or invalid ones.
1481 * For all applying +filter actions, look if a filter by that
1482 * name exists and if yes, execute its pcrs_joblist on the
1485 for (b = fl->f; b; b = b->next)
1487 if (b->type != wanted_filter_type)
1489 /* Skip other filter types */
1493 for (filtername = csp->action->multi[multi_action_index]->first;
1494 filtername ; filtername = filtername->next)
1496 if (strcmp(b->name, filtername->str) == 0)
1498 int current_hits = 0;
1499 pcrs_job *joblist = b->joblist;
1501 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1503 if (NULL == joblist)
1505 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1509 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1510 *header, size, b->name);
1512 /* Apply all jobs from the joblist */
1513 for (job = joblist; NULL != job; job = job->next)
1515 matches = pcrs_execute(job, *header, size, &newheader, &size);
1518 current_hits += matches;
1519 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1521 *header = newheader;
1523 else if ( 0 == matches )
1525 /* Filter doesn't change header */
1531 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1532 *header, b->name, pcrs_strerror(matches));
1533 if (newheader != NULL)
1535 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1541 if (b->dynamic) pcrs_free_joblist(joblist);
1543 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1544 hits += current_hits;
1551 * Additionally checking for hits is important because if
1552 * the continue hack is triggered, server headers can
1553 * arrive empty to separate multiple heads from each other.
1555 if ((0 == size) && hits)
1557 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1565 /*********************************************************************
1567 * Function : server_connection
1569 * Description : Makes sure a proper "Connection:" header is
1570 * set and signals connection_header_adder to
1574 * 1 : csp = Current client state (buffers, headers, etc...)
1575 * 2 : header = On input, pointer to header to modify.
1576 * On output, pointer to the modified header, or NULL
1577 * to remove the header. This function frees the
1578 * original string if necessary.
1580 * Returns : JB_ERR_OK on success, or
1581 * JB_ERR_MEMORY on out-of-memory error.
1583 *********************************************************************/
1584 static jb_err server_connection(struct client_state *csp, char **header)
1586 if (!strcmpic(*header, "Connection: keep-alive")
1587 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1588 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1592 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1593 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1595 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1598 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1600 log_error(LOG_LEVEL_HEADER,
1601 "Keeping the server header '%s' around.", *header);
1604 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1606 char *old_header = *header;
1608 *header = strdup("Connection: close");
1611 return JB_ERR_MEMORY;
1613 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1618 /* Signal server_connection_adder() to return early. */
1619 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1625 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1626 /*********************************************************************
1628 * Function : server_keep_alive
1630 * Description : Stores the server's keep alive timeout.
1633 * 1 : csp = Current client state (buffers, headers, etc...)
1634 * 2 : header = On input, pointer to header to modify.
1635 * On output, pointer to the modified header, or NULL
1636 * to remove the header. This function frees the
1637 * original string if necessary.
1639 * Returns : JB_ERR_OK.
1641 *********************************************************************/
1642 static jb_err server_keep_alive(struct client_state *csp, char **header)
1644 unsigned int keep_alive_timeout;
1645 const char *timeout_position = strstr(*header, "timeout=");
1647 if ((NULL == timeout_position)
1648 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1650 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1654 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1656 log_error(LOG_LEVEL_HEADER,
1657 "Reducing keep-alive timeout from %u to %u.",
1658 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1659 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1663 /* XXX: Is this log worthy? */
1664 log_error(LOG_LEVEL_HEADER,
1665 "Server keep-alive timeout is %u. Sticking with %u.",
1666 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1674 /*********************************************************************
1676 * Function : client_keep_alive
1678 * Description : Stores the client's keep alive timeout.
1681 * 1 : csp = Current client state (buffers, headers, etc...)
1682 * 2 : header = On input, pointer to header to modify.
1683 * On output, pointer to the modified header, or NULL
1684 * to remove the header. This function frees the
1685 * original string if necessary.
1687 * Returns : JB_ERR_OK.
1689 *********************************************************************/
1690 static jb_err client_keep_alive(struct client_state *csp, char **header)
1692 unsigned int keep_alive_timeout;
1693 const char *timeout_position = strstr(*header, ": ");
1695 if ((NULL == timeout_position)
1696 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1698 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1702 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1704 log_error(LOG_LEVEL_HEADER,
1705 "Reducing keep-alive timeout from %u to %u.",
1706 csp->config->keep_alive_timeout, keep_alive_timeout);
1707 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1711 /* XXX: Is this log worthy? */
1712 log_error(LOG_LEVEL_HEADER,
1713 "Client keep-alive timeout is %u. Sticking with %u.",
1714 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1720 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1724 /*********************************************************************
1726 * Function : client_connection
1728 * Description : Makes sure a proper "Connection:" header is
1729 * set and signals connection_header_adder
1733 * 1 : csp = Current client state (buffers, headers, etc...)
1734 * 2 : header = On input, pointer to header to modify.
1735 * On output, pointer to the modified header, or NULL
1736 * to remove the header. This function frees the
1737 * original string if necessary.
1739 * Returns : JB_ERR_OK on success, or
1740 * JB_ERR_MEMORY on out-of-memory error.
1742 *********************************************************************/
1743 static jb_err client_connection(struct client_state *csp, char **header)
1745 const char *wanted_header = get_appropiate_connection_header(csp);
1747 if (strcmpic(*header, wanted_header))
1749 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1750 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1752 log_error(LOG_LEVEL_HEADER,
1753 "Keeping the client header '%s' around. "
1754 "The connection will not be kept alive.",
1758 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1760 char *old_header = *header;
1762 *header = strdup(wanted_header);
1765 return JB_ERR_MEMORY;
1767 log_error(LOG_LEVEL_HEADER,
1768 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1772 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1775 log_error(LOG_LEVEL_HEADER,
1776 "Keeping the client header '%s' around. "
1777 "The server connection will be kept alive if possible.",
1779 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1781 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1783 /* Signal client_connection_adder() to return early. */
1784 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1790 /*********************************************************************
1792 * Function : crumble
1794 * Description : This is called if a header matches a pattern to "crunch"
1797 * 1 : csp = Current client state (buffers, headers, etc...)
1798 * 2 : header = On input, pointer to header to modify.
1799 * On output, pointer to the modified header, or NULL
1800 * to remove the header. This function frees the
1801 * original string if necessary.
1803 * Returns : JB_ERR_OK on success, or
1804 * JB_ERR_MEMORY on out-of-memory error.
1806 *********************************************************************/
1807 static jb_err crumble(struct client_state *csp, char **header)
1810 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1816 /*********************************************************************
1818 * Function : crunch_server_header
1820 * Description : Crunch server header if it matches a string supplied by the
1821 * user. Called from `sed'.
1824 * 1 : csp = Current client state (buffers, headers, etc...)
1825 * 2 : header = On input, pointer to header to modify.
1826 * On output, pointer to the modified header, or NULL
1827 * to remove the header. This function frees the
1828 * original string if necessary.
1830 * Returns : JB_ERR_OK on success and always succeeds
1832 *********************************************************************/
1833 static jb_err crunch_server_header(struct client_state *csp, char **header)
1835 const char *crunch_pattern;
1837 /* Do we feel like crunching? */
1838 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1840 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1842 /* Is the current header the lucky one? */
1843 if (strstr(*header, crunch_pattern))
1845 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1854 /*********************************************************************
1856 * Function : server_content_type
1858 * Description : Set the content-type for filterable types (text/.*,
1859 * .*xml.*, javascript and image/gif) unless filtering has been
1860 * forbidden (CT_TABOO) while parsing earlier headers.
1861 * NOTE: Since text/plain is commonly used by web servers
1862 * for files whose correct type is unknown, we don't
1863 * set CT_TEXT for it.
1866 * 1 : csp = Current client state (buffers, headers, etc...)
1867 * 2 : header = On input, pointer to header to modify.
1868 * On output, pointer to the modified header, or NULL
1869 * to remove the header. This function frees the
1870 * original string if necessary.
1872 * Returns : JB_ERR_OK on success, or
1873 * JB_ERR_MEMORY on out-of-memory error.
1875 *********************************************************************/
1876 static jb_err server_content_type(struct client_state *csp, char **header)
1878 /* Remove header if it isn't the first Content-Type header */
1879 if ((csp->content_type & CT_DECLARED))
1882 * Another, slightly slower, way to see if
1883 * we already parsed another Content-Type header.
1885 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1887 log_error(LOG_LEVEL_ERROR,
1888 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1896 * Signal that the Content-Type has been set.
1898 csp->content_type |= CT_DECLARED;
1900 if (!(csp->content_type & CT_TABOO))
1903 * XXX: The assumption that text/plain is a sign of
1904 * binary data seems to be somewhat unreasonable nowadays
1905 * and should be dropped after 3.0.8 is out.
1907 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
1908 || strstr(*header, "xml")
1909 || strstr(*header, "application/x-javascript"))
1911 csp->content_type |= CT_TEXT;
1913 else if (strstr(*header, "image/gif"))
1915 csp->content_type |= CT_GIF;
1920 * Are we messing with the content type?
1922 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1925 * Make sure the user doesn't accidently
1926 * change the content type of binary documents.
1928 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
1931 *header = strdup("Content-Type: ");
1932 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1936 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1937 return JB_ERR_MEMORY;
1939 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1943 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
1944 "It doesn't look like a content type that should be filtered. "
1945 "Enable force-text-mode if you know what you're doing.", *header);
1953 /*********************************************************************
1955 * Function : server_transfer_coding
1957 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1958 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1959 * - Remove header if body was chunked but has been
1960 * de-chunked for filtering.
1963 * 1 : csp = Current client state (buffers, headers, etc...)
1964 * 2 : header = On input, pointer to header to modify.
1965 * On output, pointer to the modified header, or NULL
1966 * to remove the header. This function frees the
1967 * original string if necessary.
1969 * Returns : JB_ERR_OK on success, or
1970 * JB_ERR_MEMORY on out-of-memory error.
1972 *********************************************************************/
1973 static jb_err server_transfer_coding(struct client_state *csp, char **header)
1976 * Turn off pcrs and gif filtering if body compressed
1978 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1982 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1984 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1985 csp->http->cmd, *header);
1986 #endif /* def FEATURE_ZLIB */
1987 csp->content_type = CT_TABOO;
1991 * Raise flag if body chunked
1993 if (strstr(*header, "chunked"))
1995 csp->flags |= CSP_FLAG_CHUNKED;
1998 * If the body was modified, it has been de-chunked first
1999 * and the header must be removed.
2001 * FIXME: If there is more than one transfer encoding,
2002 * only the "chunked" part should be removed here.
2004 if (csp->flags & CSP_FLAG_MODIFIED)
2006 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2015 /*********************************************************************
2017 * Function : server_content_encoding
2019 * Description : This function is run twice for each request,
2020 * unless FEATURE_ZLIB and filtering are disabled.
2022 * The first run is used to check if the content
2023 * is compressed, if FEATURE_ZLIB is disabled
2024 * filtering is then disabled as well, if FEATURE_ZLIB
2025 * is enabled the content is marked for decompression.
2027 * The second run is used to remove the Content-Encoding
2028 * header if the decompression was successful.
2031 * 1 : csp = Current client state (buffers, headers, etc...)
2032 * 2 : header = On input, pointer to header to modify.
2033 * On output, pointer to the modified header, or NULL
2034 * to remove the header. This function frees the
2035 * original string if necessary.
2037 * Returns : JB_ERR_OK on success, or
2038 * JB_ERR_MEMORY on out-of-memory error.
2040 *********************************************************************/
2041 static jb_err server_content_encoding(struct client_state *csp, char **header)
2044 if ((csp->flags & CSP_FLAG_MODIFIED)
2045 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2048 * We successfully decompressed the content,
2049 * and have to clean the header now, so the
2050 * client no longer expects compressed data..
2052 * XXX: There is a difference between cleaning
2053 * and removing it completely.
2055 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2058 else if (strstr(*header, "gzip"))
2060 /* Mark for gzip decompression */
2061 csp->content_type |= CT_GZIP;
2063 else if (strstr(*header, "deflate"))
2065 /* Mark for zlib decompression */
2066 csp->content_type |= CT_DEFLATE;
2068 else if (strstr(*header, "compress"))
2071 * We can't decompress this; therefore we can't filter
2074 csp->content_type |= CT_TABOO;
2076 #else /* !defined(FEATURE_ZLIB) */
2077 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2080 * Body is compressed, turn off pcrs and gif filtering.
2082 csp->content_type |= CT_TABOO;
2085 * Log a warning if the user expects the content to be filtered.
2087 if ((csp->rlist != NULL) &&
2088 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2090 log_error(LOG_LEVEL_INFO,
2091 "Compressed content detected, content filtering disabled. "
2092 "Consider recompiling Privoxy with zlib support or "
2093 "enable the prevent-compression action.");
2096 #endif /* defined(FEATURE_ZLIB) */
2103 /*********************************************************************
2105 * Function : server_adjust_content_length
2107 * Description : Adjust Content-Length header if we modified
2111 * 1 : csp = Current client state (buffers, headers, etc...)
2112 * 2 : header = On input, pointer to header to modify.
2113 * On output, pointer to the modified header, or NULL
2114 * to remove the header. This function frees the
2115 * original string if necessary.
2117 * Returns : JB_ERR_OK on success, or
2118 * JB_ERR_MEMORY on out-of-memory error.
2120 *********************************************************************/
2121 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2123 /* Regenerate header if the content was modified. */
2124 if (csp->flags & CSP_FLAG_MODIFIED)
2126 const size_t header_length = 50;
2128 *header = malloc(header_length);
2129 if (*header == NULL)
2131 return JB_ERR_MEMORY;
2133 create_content_length_header(csp->content_length, *header, header_length);
2134 log_error(LOG_LEVEL_HEADER,
2135 "Adjusted Content-Length to %llu", csp->content_length);
2142 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2143 /*********************************************************************
2145 * Function : server_save_content_length
2147 * Description : Save the Content-Length sent by the server.
2150 * 1 : csp = Current client state (buffers, headers, etc...)
2151 * 2 : header = On input, pointer to header to modify.
2152 * On output, pointer to the modified header, or NULL
2153 * to remove the header. This function frees the
2154 * original string if necessary.
2156 * Returns : JB_ERR_OK on success, or
2157 * JB_ERR_MEMORY on out-of-memory error.
2159 *********************************************************************/
2160 static jb_err server_save_content_length(struct client_state *csp, char **header)
2162 unsigned long long content_length = 0;
2164 assert(*(*header+14) == ':');
2166 if (1 != sscanf(*header+14, ": %llu", &content_length))
2168 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2173 csp->expected_content_length = content_length;
2174 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2175 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2180 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2183 /*********************************************************************
2185 * Function : server_content_md5
2187 * Description : Crumble any Content-MD5 headers if the document was
2188 * modified. FIXME: Should we re-compute instead?
2191 * 1 : csp = Current client state (buffers, headers, etc...)
2192 * 2 : header = On input, pointer to header to modify.
2193 * On output, pointer to the modified header, or NULL
2194 * to remove the header. This function frees the
2195 * original string if necessary.
2197 * Returns : JB_ERR_OK on success, or
2198 * JB_ERR_MEMORY on out-of-memory error.
2200 *********************************************************************/
2201 static jb_err server_content_md5(struct client_state *csp, char **header)
2203 if (csp->flags & CSP_FLAG_MODIFIED)
2205 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2213 /*********************************************************************
2215 * Function : server_content_disposition
2217 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2218 * Called from `sed'.
2221 * 1 : csp = Current client state (buffers, headers, etc...)
2222 * 2 : header = On input, pointer to header to modify.
2223 * On output, pointer to the modified header, or NULL
2224 * to remove the header. This function frees the
2225 * original string if necessary.
2227 * Returns : JB_ERR_OK on success, or
2228 * JB_ERR_MEMORY on out-of-memory error.
2230 *********************************************************************/
2231 static jb_err server_content_disposition(struct client_state *csp, char **header)
2236 * Are we messing with the Content-Disposition header?
2238 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2244 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2246 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2249 * Blocking content-disposition header
2251 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2258 * Replacing Content-Disposition header
2261 *header = strdup("Content-Disposition: ");
2262 string_append(header, newval);
2264 if (*header != NULL)
2266 log_error(LOG_LEVEL_HEADER,
2267 "Content-Disposition header crunched and replaced with: %s", *header);
2270 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2274 /*********************************************************************
2276 * Function : server_last_modified
2278 * Description : Changes Last-Modified header to the actual date
2279 * to help hide-if-modified-since.
2280 * Called from `sed'.
2283 * 1 : csp = Current client state (buffers, headers, etc...)
2284 * 2 : header = On input, pointer to header to modify.
2285 * On output, pointer to the modified header, or NULL
2286 * to remove the header. This function frees the
2287 * original string if necessary.
2289 * Returns : JB_ERR_OK on success, or
2290 * JB_ERR_MEMORY on out-of-memory error.
2292 *********************************************************************/
2293 static jb_err server_last_modified(struct client_state *csp, char **header)
2296 char buf[BUFFER_SIZE];
2299 #ifdef HAVE_GMTIME_R
2302 struct tm *timeptr = NULL;
2303 time_t now, last_modified;
2304 long int days, hours, minutes, seconds;
2307 * Are we messing with the Last-Modified header?
2309 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2315 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2317 if (0 == strcmpic(newval, "block") )
2320 * Blocking Last-Modified header. Useless but why not.
2322 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2326 else if (0 == strcmpic(newval, "reset-to-request-time"))
2329 * Setting Last-Modified Header to now.
2331 get_http_time(0, buf, sizeof(buf));
2333 *header = strdup("Last-Modified: ");
2334 string_append(header, buf);
2336 if (*header == NULL)
2338 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2342 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2345 else if (0 == strcmpic(newval, "randomize"))
2347 const char *header_time = *header + sizeof("Last-Modified:");
2349 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2351 #ifdef HAVE_GMTIME_R
2352 gmtime_r(&now, &gmt);
2353 #elif defined(MUTEX_LOCKS_AVAILABLE)
2354 privoxy_mutex_lock(&gmtime_mutex);
2356 privoxy_mutex_unlock(&gmtime_mutex);
2360 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2362 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2367 long int rtime = (long int)difftime(now, last_modified);
2370 const int negative_delta = (rtime < 0);
2375 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2377 rtime = pick_from_range(rtime);
2382 last_modified += rtime;
2383 #ifdef HAVE_GMTIME_R
2384 timeptr = gmtime_r(&last_modified, &gmt);
2385 #elif defined(MUTEX_LOCKS_AVAILABLE)
2386 privoxy_mutex_lock(&gmtime_mutex);
2387 timeptr = gmtime(&last_modified);
2388 privoxy_mutex_unlock(&gmtime_mutex);
2390 timeptr = gmtime(&last_modified);
2392 if ((NULL == timeptr) || !strftime(newheader,
2393 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2395 log_error(LOG_LEVEL_ERROR,
2396 "Randomizing '%s' failed. Crunching the header without replacement.",
2403 *header = strdup("Last-Modified: ");
2404 string_append(header, newheader);
2406 if (*header == NULL)
2408 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2409 return JB_ERR_MEMORY;
2412 days = rtime / (3600 * 24);
2413 hours = rtime / 3600 % 24;
2414 minutes = rtime / 60 % 60;
2415 seconds = rtime % 60;
2417 log_error(LOG_LEVEL_HEADER,
2418 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2419 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2420 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2424 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2433 /*********************************************************************
2435 * Function : client_accept_encoding
2437 * Description : Rewrite the client's Accept-Encoding header so that
2438 * if doesn't allow compression, if the action applies.
2439 * Note: For HTTP/1.0 the absence of the header is enough.
2442 * 1 : csp = Current client state (buffers, headers, etc...)
2443 * 2 : header = On input, pointer to header to modify.
2444 * On output, pointer to the modified header, or NULL
2445 * to remove the header. This function frees the
2446 * original string if necessary.
2448 * Returns : JB_ERR_OK on success, or
2449 * JB_ERR_MEMORY on out-of-memory error.
2451 *********************************************************************/
2452 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2454 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2456 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2460 /* Temporarily disable the correct behaviour to
2461 * work around a PHP bug.
2463 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2465 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2466 * if (*header == NULL)
2468 * return JB_ERR_MEMORY;
2479 /*********************************************************************
2481 * Function : client_te
2483 * Description : Rewrite the client's TE header so that
2484 * if doesn't allow compression, if the action applies.
2487 * 1 : csp = Current client state (buffers, headers, etc...)
2488 * 2 : header = On input, pointer to header to modify.
2489 * On output, pointer to the modified header, or NULL
2490 * to remove the header. This function frees the
2491 * original string if necessary.
2493 * Returns : JB_ERR_OK on success, or
2494 * JB_ERR_MEMORY on out-of-memory error.
2496 *********************************************************************/
2497 static jb_err client_te(struct client_state *csp, char **header)
2499 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2502 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2509 /*********************************************************************
2511 * Function : client_referrer
2513 * Description : Handle the "referer" config setting properly.
2514 * Called from `sed'.
2517 * 1 : csp = Current client state (buffers, headers, etc...)
2518 * 2 : header = On input, pointer to header to modify.
2519 * On output, pointer to the modified header, or NULL
2520 * to remove the header. This function frees the
2521 * original string if necessary.
2523 * Returns : JB_ERR_OK on success, or
2524 * JB_ERR_MEMORY on out-of-memory error.
2526 *********************************************************************/
2527 static jb_err client_referrer(struct client_state *csp, char **header)
2529 const char *parameter;
2530 /* booleans for parameters we have to check multiple times */
2531 int parameter_conditional_block;
2532 int parameter_conditional_forge;
2534 #ifdef FEATURE_FORCE_LOAD
2536 * Since the referrer can include the prefix even
2537 * if the request itself is non-forced, we must
2538 * clean it unconditionally.
2540 * XXX: strclean is too broad
2542 strclean(*header, FORCE_PREFIX);
2543 #endif /* def FEATURE_FORCE_LOAD */
2545 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2547 /* Nothing left to do */
2551 parameter = csp->action->string[ACTION_STRING_REFERER];
2552 assert(parameter != NULL);
2553 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2554 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2556 if (!parameter_conditional_block && !parameter_conditional_forge)
2559 * As conditional-block and conditional-forge are the only
2560 * parameters that rely on the original referrer, we can
2561 * remove it now for all the others.
2566 if (0 == strcmpic(parameter, "block"))
2568 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2571 else if (parameter_conditional_block || parameter_conditional_forge)
2573 return handle_conditional_hide_referrer_parameter(header,
2574 csp->http->hostport, parameter_conditional_block);
2576 else if (0 == strcmpic(parameter, "forge"))
2578 return create_forged_referrer(header, csp->http->hostport);
2582 /* interpret parameter as user-supplied referer to fake */
2583 return create_fake_referrer(header, parameter);
2588 /*********************************************************************
2590 * Function : client_accept_language
2592 * Description : Handle the "Accept-Language" config setting properly.
2593 * Called from `sed'.
2596 * 1 : csp = Current client state (buffers, headers, etc...)
2597 * 2 : header = On input, pointer to header to modify.
2598 * On output, pointer to the modified header, or NULL
2599 * to remove the header. This function frees the
2600 * original string if necessary.
2602 * Returns : JB_ERR_OK on success, or
2603 * JB_ERR_MEMORY on out-of-memory error.
2605 *********************************************************************/
2606 static jb_err client_accept_language(struct client_state *csp, char **header)
2611 * Are we messing with the Accept-Language?
2613 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2615 /*I don't think so*/
2619 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2621 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2624 * Blocking Accept-Language header
2626 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2633 * Replacing Accept-Language header
2636 *header = strdup("Accept-Language: ");
2637 string_append(header, newval);
2639 if (*header == NULL)
2641 log_error(LOG_LEVEL_ERROR,
2642 "Insufficient memory. Accept-Language header crunched without replacement.");
2646 log_error(LOG_LEVEL_HEADER,
2647 "Accept-Language header crunched and replaced with: %s", *header);
2650 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2654 /*********************************************************************
2656 * Function : crunch_client_header
2658 * Description : Crunch client header if it matches a string supplied by the
2659 * user. Called from `sed'.
2662 * 1 : csp = Current client state (buffers, headers, etc...)
2663 * 2 : header = On input, pointer to header to modify.
2664 * On output, pointer to the modified header, or NULL
2665 * to remove the header. This function frees the
2666 * original string if necessary.
2668 * Returns : JB_ERR_OK on success and always succeeds
2670 *********************************************************************/
2671 static jb_err crunch_client_header(struct client_state *csp, char **header)
2673 const char *crunch_pattern;
2675 /* Do we feel like crunching? */
2676 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2678 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2680 /* Is the current header the lucky one? */
2681 if (strstr(*header, crunch_pattern))
2683 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2691 /*********************************************************************
2693 * Function : client_uagent
2695 * Description : Handle the "user-agent" config setting properly
2696 * and remember its original value to enable browser
2697 * bug workarounds. Called from `sed'.
2700 * 1 : csp = Current client state (buffers, headers, etc...)
2701 * 2 : header = On input, pointer to header to modify.
2702 * On output, pointer to the modified header, or NULL
2703 * to remove the header. This function frees the
2704 * original string if necessary.
2706 * Returns : JB_ERR_OK on success, or
2707 * JB_ERR_MEMORY on out-of-memory error.
2709 *********************************************************************/
2710 static jb_err client_uagent(struct client_state *csp, char **header)
2714 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2719 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2726 *header = strdup("User-Agent: ");
2727 string_append(header, newval);
2729 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2731 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2735 /*********************************************************************
2737 * Function : client_ua
2739 * Description : Handle "ua-" headers properly. Called from `sed'.
2742 * 1 : csp = Current client state (buffers, headers, etc...)
2743 * 2 : header = On input, pointer to header to modify.
2744 * On output, pointer to the modified header, or NULL
2745 * to remove the header. This function frees the
2746 * original string if necessary.
2748 * Returns : JB_ERR_OK on success, or
2749 * JB_ERR_MEMORY on out-of-memory error.
2751 *********************************************************************/
2752 static jb_err client_ua(struct client_state *csp, char **header)
2754 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2756 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2764 /*********************************************************************
2766 * Function : client_from
2768 * Description : Handle the "from" config setting properly.
2769 * Called from `sed'.
2772 * 1 : csp = Current client state (buffers, headers, etc...)
2773 * 2 : header = On input, pointer to header to modify.
2774 * On output, pointer to the modified header, or NULL
2775 * to remove the header. This function frees the
2776 * original string if necessary.
2778 * Returns : JB_ERR_OK on success, or
2779 * JB_ERR_MEMORY on out-of-memory error.
2781 *********************************************************************/
2782 static jb_err client_from(struct client_state *csp, char **header)
2786 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2793 newval = csp->action->string[ACTION_STRING_FROM];
2796 * Are we blocking the e-mail address?
2798 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2800 log_error(LOG_LEVEL_HEADER, "crunched From!");
2804 log_error(LOG_LEVEL_HEADER, " modified");
2806 *header = strdup("From: ");
2807 string_append(header, newval);
2809 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2813 /*********************************************************************
2815 * Function : client_send_cookie
2817 * Description : Crunches the "cookie" header if necessary.
2818 * Called from `sed'.
2820 * XXX: Stupid name, doesn't send squat.
2823 * 1 : csp = Current client state (buffers, headers, etc...)
2824 * 2 : header = On input, pointer to header to modify.
2825 * On output, pointer to the modified header, or NULL
2826 * to remove the header. This function frees the
2827 * original string if necessary.
2829 * Returns : JB_ERR_OK on success, or
2830 * JB_ERR_MEMORY on out-of-memory error.
2832 *********************************************************************/
2833 static jb_err client_send_cookie(struct client_state *csp, char **header)
2835 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2837 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2845 /*********************************************************************
2847 * Function : client_x_forwarded
2849 * Description : Handle the "x-forwarded-for" config setting properly,
2850 * also used in the add_client_headers list. Called from `sed'.
2853 * 1 : csp = Current client state (buffers, headers, etc...)
2854 * 2 : header = On input, pointer to header to modify.
2855 * On output, pointer to the modified header, or NULL
2856 * to remove the header. This function frees the
2857 * original string if necessary.
2859 * Returns : JB_ERR_OK on success, or
2860 * JB_ERR_MEMORY on out-of-memory error.
2862 *********************************************************************/
2863 jb_err client_x_forwarded(struct client_state *csp, char **header)
2865 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
2867 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
2869 if (0 == strcmpic(parameter, "block"))
2872 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2874 else if (0 == strcmpic(parameter, "add"))
2876 string_append(header, ", ");
2877 string_append(header, csp->ip_addr_str);
2879 if (*header == NULL)
2881 return JB_ERR_MEMORY;
2883 log_error(LOG_LEVEL_HEADER,
2884 "Appended client IP address to %s", *header);
2885 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
2889 log_error(LOG_LEVEL_FATAL,
2890 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
2898 /*********************************************************************
2900 * Function : client_max_forwards
2902 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2903 * from the value of the Max-Forwards header field.
2906 * 1 : csp = Current client state (buffers, headers, etc...)
2907 * 2 : header = On input, pointer to header to modify.
2908 * On output, pointer to the modified header, or NULL
2909 * to remove the header. This function frees the
2910 * original string if necessary.
2912 * Returns : JB_ERR_OK on success, or
2913 * JB_ERR_MEMORY on out-of-memory error.
2915 *********************************************************************/
2916 static jb_err client_max_forwards(struct client_state *csp, char **header)
2920 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2921 (0 == strcmpic(csp->http->gpc, "options")))
2923 assert(*(*header+12) == ':');
2924 if (1 == sscanf(*header+12, ": %d", &max_forwards))
2926 if (max_forwards > 0)
2928 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
2929 log_error(LOG_LEVEL_HEADER,
2930 "Max-Forwards value for %s request reduced to %d.",
2931 csp->http->gpc, max_forwards);
2933 else if (max_forwards < 0)
2935 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2941 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2950 /*********************************************************************
2952 * Function : client_host
2954 * Description : If the request URI did not contain host and
2955 * port information, parse and evaluate the Host
2958 * Also, kill ill-formed HOST: headers as sent by
2959 * Apple's iTunes software when used with a proxy.
2962 * 1 : csp = Current client state (buffers, headers, etc...)
2963 * 2 : header = On input, pointer to header to modify.
2964 * On output, pointer to the modified header, or NULL
2965 * to remove the header. This function frees the
2966 * original string if necessary.
2968 * Returns : JB_ERR_OK on success, or
2969 * JB_ERR_MEMORY on out-of-memory error.
2971 *********************************************************************/
2972 static jb_err client_host(struct client_state *csp, char **header)
2977 * If the header field name is all upper-case, chances are that it's
2978 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2979 * not a problem -- they are regenerated later.
2981 if ((*header)[1] == 'O')
2983 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2988 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2989 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2992 if (NULL == (p = strdup((*header)+6)))
2994 return JB_ERR_MEMORY;
2997 if (NULL == (q = strdup(p)))
3000 return JB_ERR_MEMORY;
3003 freez(csp->http->hostport);
3004 csp->http->hostport = p;
3005 freez(csp->http->host);
3006 csp->http->host = q;
3007 q = strchr(csp->http->host, ':');
3010 /* Terminate hostname and evaluate port string */
3012 csp->http->port = atoi(q);
3016 csp->http->port = csp->http->ssl ? 443 : 80;
3019 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3020 csp->http->hostport, csp->http->host, csp->http->port);
3023 /* Signal client_host_adder() to return right away */
3024 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3030 /*********************************************************************
3032 * Function : client_if_modified_since
3034 * Description : Remove or modify the If-Modified-Since header.
3037 * 1 : csp = Current client state (buffers, headers, etc...)
3038 * 2 : header = On input, pointer to header to modify.
3039 * On output, pointer to the modified header, or NULL
3040 * to remove the header. This function frees the
3041 * original string if necessary.
3043 * Returns : JB_ERR_OK on success, or
3044 * JB_ERR_MEMORY on out-of-memory error.
3046 *********************************************************************/
3047 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3050 #ifdef HAVE_GMTIME_R
3053 struct tm *timeptr = NULL;
3056 long int hours, minutes, seconds;
3059 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3062 * The client got an error message because of a temporary problem,
3063 * the problem is gone and the client now tries to revalidate our
3064 * error message on the real server. The revalidation would always
3065 * end with the transmission of the whole document and there is
3066 * no need to expose the bogus If-Modified-Since header.
3068 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3071 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3073 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3075 if ((0 == strcmpic(newval, "block")))
3077 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3080 else /* add random value */
3082 const char *header_time = *header + sizeof("If-Modified-Since:");
3084 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3086 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3091 long int rtime = strtol(newval, &endptr, 0);
3092 const int negative_range = (rtime < 0);
3096 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3097 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3103 rtime = pick_from_range(rtime);
3107 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3110 tm += rtime * (negative_range ? -1 : 1);
3111 #ifdef HAVE_GMTIME_R
3112 timeptr = gmtime_r(&tm, &gmt);
3113 #elif defined(MUTEX_LOCKS_AVAILABLE)
3114 privoxy_mutex_lock(&gmtime_mutex);
3115 timeptr = gmtime(&tm);
3116 privoxy_mutex_unlock(&gmtime_mutex);
3118 timeptr = gmtime(&tm);
3120 if ((NULL == timeptr) || !strftime(newheader,
3121 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3123 log_error(LOG_LEVEL_ERROR,
3124 "Randomizing '%s' failed. Crunching the header without replacement.",
3131 *header = strdup("If-Modified-Since: ");
3132 string_append(header, newheader);
3134 if (*header == NULL)
3136 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3137 return JB_ERR_MEMORY;
3140 hours = rtime / 3600;
3141 minutes = rtime / 60 % 60;
3142 seconds = rtime % 60;
3144 log_error(LOG_LEVEL_HEADER,
3145 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3146 *header, (negative_range) ? "subtracted" : "added", hours,
3147 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3148 seconds, (seconds == 1) ? ")" : "s)");
3157 /*********************************************************************
3159 * Function : client_if_none_match
3161 * Description : Remove the If-None-Match header.
3164 * 1 : csp = Current client state (buffers, headers, etc...)
3165 * 2 : header = On input, pointer to header to modify.
3166 * On output, pointer to the modified header, or NULL
3167 * to remove the header. This function frees the
3168 * original string if necessary.
3170 * Returns : JB_ERR_OK on success, or
3171 * JB_ERR_MEMORY on out-of-memory error.
3173 *********************************************************************/
3174 static jb_err client_if_none_match(struct client_state *csp, char **header)
3176 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3178 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3186 /*********************************************************************
3188 * Function : client_x_filter
3190 * Description : Disables filtering if the client set "X-Filter: No".
3191 * Called from `sed'.
3194 * 1 : csp = Current client state (buffers, headers, etc...)
3195 * 2 : header = On input, pointer to header to modify.
3196 * On output, pointer to the modified header, or NULL
3197 * to remove the header. This function frees the
3198 * original string if necessary.
3200 * Returns : JB_ERR_OK on success
3202 *********************************************************************/
3203 jb_err client_x_filter(struct client_state *csp, char **header)
3205 if ( 0 == strcmpic(*header, "X-Filter: No"))
3207 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3209 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3213 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3215 log_error(LOG_LEVEL_HEADER,
3216 "force-text-mode overruled the client's request to fetch without filtering!");
3220 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3221 csp->flags |= CSP_FLAG_NO_FILTERING;
3222 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3224 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3232 /*********************************************************************
3234 * Function : client_range
3236 * Description : Removes Range, Request-Range and If-Range headers if
3237 * content filtering is enabled. If the client's version
3238 * of the document has been altered by Privoxy, the server
3239 * could interpret the range differently than the client
3240 * intended in which case the user could end up with
3241 * corrupted content.
3244 * 1 : csp = Current client state (buffers, headers, etc...)
3245 * 2 : header = On input, pointer to header to modify.
3246 * On output, pointer to the modified header, or NULL
3247 * to remove the header. This function frees the
3248 * original string if necessary.
3250 * Returns : JB_ERR_OK
3252 *********************************************************************/
3253 static jb_err client_range(struct client_state *csp, char **header)
3255 if (content_filters_enabled(csp->action))
3257 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3258 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3265 /* the following functions add headers directly to the header list */
3267 /*********************************************************************
3269 * Function : client_host_adder
3271 * Description : Adds the Host: header field if it is missing.
3272 * Called from `sed'.
3275 * 1 : csp = Current client state (buffers, headers, etc...)
3277 * Returns : JB_ERR_OK on success, or
3278 * JB_ERR_MEMORY on out-of-memory error.
3280 *********************************************************************/
3281 static jb_err client_host_adder(struct client_state *csp)
3286 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3288 /* Header already set by the client, nothing to do. */
3292 if ( !csp->http->hostport || !*(csp->http->hostport))
3294 /* XXX: When does this happen and why is it OK? */
3295 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3300 * remove 'user:pass@' from 'proto://user:pass@host'
3302 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3308 p = csp->http->hostport;
3311 /* XXX: Just add it, we already made sure that it will be unique */
3312 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3313 err = enlist_unique_header(csp->headers, "Host", p);
3320 /*********************************************************************
3322 * Function : client_accept_encoding_adder
3324 * Description : Add an Accept-Encoding header to the client's request
3325 * that disables compression if the action applies, and
3326 * the header is not already there. Called from `sed'.
3327 * Note: For HTTP/1.0, the absence of the header is enough.
3330 * 1 : csp = Current client state (buffers, headers, etc...)
3332 * Returns : JB_ERR_OK on success, or
3333 * JB_ERR_MEMORY on out-of-memory error.
3335 *********************************************************************/
3336 static jb_err client_accept_encoding_adder(struct client_state *csp)
3338 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3339 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3341 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3349 /*********************************************************************
3351 * Function : client_xtra_adder
3353 * Description : Used in the add_client_headers list. Called from `sed'.
3356 * 1 : csp = Current client state (buffers, headers, etc...)
3358 * Returns : JB_ERR_OK on success, or
3359 * JB_ERR_MEMORY on out-of-memory error.
3361 *********************************************************************/
3362 static jb_err client_xtra_adder(struct client_state *csp)
3364 struct list_entry *lst;
3367 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3368 lst ; lst = lst->next)
3370 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3371 err = enlist(csp->headers, lst->str);
3383 /*********************************************************************
3385 * Function : client_x_forwarded_for_adder
3387 * Description : Used in the add_client_headers list. Called from `sed'.
3390 * 1 : csp = Current client state (buffers, headers, etc...)
3392 * Returns : JB_ERR_OK on success, or
3393 * JB_ERR_MEMORY on out-of-memory error.
3395 *********************************************************************/
3396 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3398 char *header = NULL;
3401 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3402 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3403 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3406 * If we aren't adding X-Forwarded-For headers,
3407 * or we already appended an existing X-Forwarded-For
3408 * header, there's nothing left to do here.
3413 header = strdup("X-Forwarded-For: ");
3414 string_append(&header, csp->ip_addr_str);
3418 return JB_ERR_MEMORY;
3421 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3422 err = enlist(csp->headers, header);
3429 /*********************************************************************
3431 * Function : server_connection_adder
3433 * Description : Adds an appropiate "Connection:" header to csp->headers
3434 * unless the header was already present. Called from `sed'.
3437 * 1 : csp = Current client state (buffers, headers, etc...)
3439 * Returns : JB_ERR_OK on success, or
3440 * JB_ERR_MEMORY on out-of-memory error.
3442 *********************************************************************/
3443 static jb_err server_connection_adder(struct client_state *csp)
3445 const unsigned int flags = csp->flags;
3446 const char *response_status_line = csp->headers->first->str;
3447 const char *wanted_header = get_appropiate_connection_header(csp);
3449 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3450 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3456 * XXX: if we downgraded the response, this check will fail.
3458 if ((csp->config->feature_flags &
3459 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3460 && (NULL != response_status_line)
3461 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3462 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3463 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3465 && (csp->http->status == 200)
3469 * XXX: not doing this for status codes other than 200 works
3470 * around problems with broken servers that will keep the
3471 * connection open, but terminate the connection when the
3472 * next request arrives. Once we are able to figure out which
3473 * requests are safe to send again, this will probably no
3474 * longer be necessary.
3476 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3477 "without Connection header implies keep-alive.");
3478 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3481 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3483 return enlist(csp->headers, wanted_header);
3487 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3488 /*********************************************************************
3490 * Function : server_proxy_connection_adder
3492 * Description : Adds a "Proxy-Connection: keep-alive" header to
3493 * csp->headers if the client asked for keep-alive.
3494 * XXX: We should reuse existant ones.
3497 * 1 : csp = Current client state (buffers, headers, etc...)
3499 * Returns : JB_ERR_OK on success, or
3500 * JB_ERR_MEMORY on out-of-memory error.
3502 *********************************************************************/
3503 static jb_err server_proxy_connection_adder(struct client_state *csp)
3505 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3506 jb_err err = JB_ERR_OK;
3508 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3509 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
3511 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3512 err = enlist(csp->headers, proxy_connection_header);
3517 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3520 /*********************************************************************
3522 * Function : client_connection_header_adder
3524 * Description : Adds a proper "Connection:" header to csp->headers
3525 * unless the header was already present. Called from `sed'.
3528 * 1 : csp = Current client state (buffers, headers, etc...)
3530 * Returns : JB_ERR_OK on success, or
3531 * JB_ERR_MEMORY on out-of-memory error.
3533 *********************************************************************/
3534 static jb_err client_connection_header_adder(struct client_state *csp)
3536 const char *wanted_header = get_appropiate_connection_header(csp);
3538 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3539 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3544 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3545 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3546 && (csp->http->ssl == 0)
3547 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3549 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3551 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3553 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3555 return enlist(csp->headers, wanted_header);
3559 /*********************************************************************
3561 * Function : server_http
3563 * Description : - Save the HTTP Status into csp->http->status
3564 * - Set CT_TABOO to prevent filtering if the answer
3565 * is a partial range (HTTP status 206)
3566 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3570 * 1 : csp = Current client state (buffers, headers, etc...)
3571 * 2 : header = On input, pointer to header to modify.
3572 * On output, pointer to the modified header, or NULL
3573 * to remove the header. This function frees the
3574 * original string if necessary.
3576 * Returns : JB_ERR_OK on success, or
3577 * JB_ERR_MEMORY on out-of-memory error.
3579 *********************************************************************/
3580 static jb_err server_http(struct client_state *csp, char **header)
3582 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3583 if (csp->http->status == 206)
3585 csp->content_type = CT_TABOO;
3588 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3590 /* XXX: Should we do a real validity check here? */
3591 if (strlen(*header) > 8)
3594 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3599 * XXX: Should we block the request or
3600 * enlist a valid status code line here?
3602 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3603 "Downgrading to HTTP/1.0 impossible.");
3611 /*********************************************************************
3613 * Function : server_set_cookie
3615 * Description : Handle the server "cookie" header properly.
3616 * Log cookie to the jar file. Then "crunch",
3617 * accept or rewrite it to a session cookie.
3618 * Called from `sed'.
3620 * TODO: Allow the user to specify a new expiration
3621 * time to cause the cookie to expire even before the
3622 * browser is closed.
3625 * 1 : csp = Current client state (buffers, headers, etc...)
3626 * 2 : header = On input, pointer to header to modify.
3627 * On output, pointer to the modified header, or NULL
3628 * to remove the header. This function frees the
3629 * original string if necessary.
3631 * Returns : JB_ERR_OK on success, or
3632 * JB_ERR_MEMORY on out-of-memory error.
3634 *********************************************************************/
3635 static jb_err server_set_cookie(struct client_state *csp, char **header)
3642 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3644 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3647 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3649 /* Flag whether or not to log a message */
3652 /* A variable to store the tag we're working on */
3655 /* Skip "Set-Cookie:" (11 characters) in header */
3656 cur_tag = *header + 11;
3658 /* skip whitespace between "Set-Cookie:" and value */
3659 while (*cur_tag && ijb_isspace(*cur_tag))
3664 /* Loop through each tag in the cookie */
3668 char *next_tag = strchr(cur_tag, ';');
3669 if (next_tag != NULL)
3671 /* Skip the ';' character itself */
3674 /* skip whitespace ";" and start of tag */
3675 while (*next_tag && ijb_isspace(*next_tag))
3682 /* "Next tag" is the end of the string */
3683 next_tag = cur_tag + strlen(cur_tag);
3687 * Check the expiration date to see
3688 * if the cookie is still valid, if yes,
3689 * rewrite it to a session cookie.
3691 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3693 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3695 /* Did we detect the date properly? */
3696 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3699 * Nope, treat it as if it was still valid.
3701 * XXX: Should we remove the whole cookie instead?
3703 log_error(LOG_LEVEL_ERROR,
3704 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3705 string_move(cur_tag, next_tag);
3711 * Yes. Check if the cookie is still valid.
3713 * If the cookie is already expired it's probably
3714 * a delete cookie and even if it isn't, the browser
3715 * will discard it anyway.
3719 * XXX: timegm() isn't available on some AmigaOS
3720 * versions and our replacement doesn't work.
3722 * Our options are to either:
3724 * - disable session-cookies-only completely if timegm
3727 * - to simply remove all expired tags, like it has
3728 * been done until Privoxy 3.0.6 and to live with
3729 * the consequence that it can cause login/logout
3730 * problems on servers that don't validate their
3731 * input properly, or
3733 * - to replace it with mktime in which
3734 * case there is a slight chance of valid cookies
3735 * passing as already expired.
3737 * This is the way it's currently done and it's not
3738 * as bad as it sounds. If the missing GMT offset is
3739 * enough to change the result of the expiration check
3740 * the cookie will be only valid for a few hours
3741 * anyway, which in many cases will be shorter
3742 * than a browser session.
3744 if (cookie_time - now < 0)
3746 log_error(LOG_LEVEL_HEADER,
3747 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3748 /* Just in case some clown sets more then one expiration date */
3754 * Still valid, delete expiration date by copying
3755 * the rest of the string over it.
3757 string_move(cur_tag, next_tag);
3759 /* That changed the header, need to issue a log message */
3763 * Note that the next tag has now been moved to *cur_tag,
3764 * so we do not need to update the cur_tag pointer.
3772 /* Move on to next cookie tag */
3779 assert(NULL != *header);
3780 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3789 #ifdef FEATURE_FORCE_LOAD
3790 /*********************************************************************
3792 * Function : strclean
3794 * Description : In-Situ-Eliminate all occurances of substring in
3798 * 1 : string = string to clean
3799 * 2 : substring = substring to eliminate
3801 * Returns : Number of eliminations
3803 *********************************************************************/
3804 int strclean(char *string, const char *substring)
3810 len = strlen(substring);
3812 while((pos = strstr(string, substring)) != NULL)
3819 while (*p++ != '\0');
3826 #endif /* def FEATURE_FORCE_LOAD */
3829 /*********************************************************************
3831 * Function : parse_header_time
3833 * Description : Parses time formats used in HTTP header strings
3834 * to get the numerical respresentation.
3837 * 1 : header_time = HTTP header time as string.
3838 * 2 : result = storage for header_time in seconds
3840 * Returns : JB_ERR_OK if the time format was recognized, or
3841 * JB_ERR_PARSE otherwise.
3843 *********************************************************************/
3844 static jb_err parse_header_time(const char *header_time, time_t *result)
3849 * Zero out gmt to prevent time zone offsets.
3851 * While this is only necessary on some platforms
3852 * (mingw32 for example), I don't know how to
3853 * detect these automatically and doing it everywhere
3856 memset(&gmt, 0, sizeof(gmt));
3858 /* Tue, 02 Jun 2037 20:00:00 */
3859 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3860 /* Tue, 02-Jun-2037 20:00:00 */
3861 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3862 /* Tue, 02-Jun-37 20:00:00 */
3863 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3864 /* Tuesday, 02-Jun-2037 20:00:00 */
3865 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3866 /* Tuesday Jun 02 20:00:00 2037 */
3867 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3869 return JB_ERR_PARSE;
3872 *result = timegm(&gmt);
3879 /*********************************************************************
3881 * Function : get_destination_from_headers
3883 * Description : Parse the "Host:" header to get the request's destination.
3884 * Only needed if the client's request was forcefully
3885 * redirected into Privoxy.
3887 * Code mainly copied from client_host() which is currently
3888 * run too late for this purpose.
3891 * 1 : headers = List of headers (one of them hopefully being
3892 * the "Host:" header)
3893 * 2 : http = storage for the result (host, port and hostport).
3895 * Returns : JB_ERR_MEMORY in case of memory problems,
3896 * JB_ERR_PARSE if the host header couldn't be found,
3897 * JB_ERR_OK otherwise.
3899 *********************************************************************/
3900 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3906 host = get_header_value(headers, "Host:");
3910 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3911 return JB_ERR_PARSE;
3914 if (NULL == (p = strdup((host))))
3916 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3917 return JB_ERR_MEMORY;
3920 if (NULL == (q = strdup(p)))
3923 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3924 return JB_ERR_MEMORY;
3927 freez(http->hostport);
3931 q = strchr(http->host, ':');
3934 /* Terminate hostname and evaluate port string */
3936 http->port = atoi(q);
3940 http->port = http->ssl ? 443 : 80;
3943 /* Rebuild request URL */
3945 http->url = strdup(http->ssl ? "https://" : "http://");
3946 string_append(&http->url, http->hostport);
3947 string_append(&http->url, http->path);
3948 if (http->url == NULL)
3950 return JB_ERR_MEMORY;
3953 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
3961 /*********************************************************************
3963 * Function : create_forged_referrer
3965 * Description : Helper for client_referrer to forge a referer as
3966 * 'http://[hostname:port/' to fool stupid
3967 * checks for in-site links
3970 * 1 : header = Pointer to header pointer
3971 * 2 : hostport = Host and optionally port as string
3973 * Returns : JB_ERR_OK in case of success, or
3974 * JB_ERR_MEMORY in case of memory problems.
3976 *********************************************************************/
3977 static jb_err create_forged_referrer(char **header, const char *hostport)
3979 assert(NULL == *header);
3981 *header = strdup("Referer: http://");
3982 string_append(header, hostport);
3983 string_append(header, "/");
3985 if (NULL == *header)
3987 return JB_ERR_MEMORY;
3990 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
3997 /*********************************************************************
3999 * Function : create_fake_referrer
4001 * Description : Helper for client_referrer to create a fake referrer
4002 * based on a string supplied by the user.
4005 * 1 : header = Pointer to header pointer
4006 * 2 : hosthost = Referrer to fake
4008 * Returns : JB_ERR_OK in case of success, or
4009 * JB_ERR_MEMORY in case of memory problems.
4011 *********************************************************************/
4012 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4014 assert(NULL == *header);
4016 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4018 log_error(LOG_LEVEL_HEADER,
4019 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4021 *header = strdup("Referer: ");
4022 string_append(header, fake_referrer);
4024 if (NULL == *header)
4026 return JB_ERR_MEMORY;
4029 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4036 /*********************************************************************
4038 * Function : handle_conditional_hide_referrer_parameter
4040 * Description : Helper for client_referrer to crunch or forge
4041 * the referrer header if the host has changed.
4044 * 1 : header = Pointer to header pointer
4045 * 2 : host = The target host (may include the port)
4046 * 3 : parameter_conditional_block = Boolean to signal
4047 * if we're in conditional-block mode. If not set,
4048 * we're in conditional-forge mode.
4050 * Returns : JB_ERR_OK in case of success, or
4051 * JB_ERR_MEMORY in case of memory problems.
4053 *********************************************************************/
4054 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4055 const char *host, const int parameter_conditional_block)
4057 char *referer = strdup(*header);
4058 const size_t hostlenght = strlen(host);
4059 const char *referer_url = NULL;
4061 if (NULL == referer)
4064 return JB_ERR_MEMORY;
4067 /* referer begins with 'Referer: http[s]://' */
4068 if ((hostlenght+17) < strlen(referer))
4071 * Shorten referer to make sure the referer is blocked
4072 * if www.example.org/www.example.com-shall-see-the-referer/
4073 * links to www.example.com/
4075 referer[hostlenght+17] = '\0';
4077 referer_url = strstr(referer, "http://");
4078 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4080 /* Host has changed, Referer is invalid or a https URL. */
4081 if (parameter_conditional_block)
4083 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4090 return create_forged_referrer(header, host);
4100 /*********************************************************************
4102 * Function : get_appropiate_connection_header
4104 * Description : Returns an appropiate Connection header
4105 * depending on whether or not we try to keep
4106 * the connection to the server alive.
4109 * 1 : csp = Current client state (buffers, headers, etc...)
4111 * Returns : Pointer to statically allocated header buffer.
4113 *********************************************************************/
4114 static const char *get_appropiate_connection_header(const struct client_state *csp)
4116 static const char connection_keep_alive[] = "Connection: keep-alive";
4117 static const char connection_close[] = "Connection: close";
4119 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4120 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4121 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4123 && (csp->http->ssl == 0))
4125 return connection_keep_alive;
4127 return connection_close;
4131 /*********************************************************************
4133 * Function : create_content_length_header
4135 * Description : Creates a Content-Length header.
4138 * 1 : content_length = The content length to be used in the header.
4139 * 2 : header = Allocated space to safe the header.
4140 * 3 : buffer_length = The length of the allocated space.
4144 *********************************************************************/
4145 static void create_content_length_header(unsigned long long content_length,
4146 char *header, size_t buffer_length)
4148 snprintf(header, buffer_length, "Content-Length: %llu", content_length);