1 const char parsers_rcs[] = "$Id: parsers.c,v 1.176 2009/06/08 16:47:07 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 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
161 static jb_err client_host_adder (struct client_state *csp);
162 static jb_err client_xtra_adder (struct client_state *csp);
163 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
164 static jb_err client_connection_header_adder(struct client_state *csp);
165 static jb_err server_connection_adder(struct client_state *csp);
166 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
167 static jb_err server_proxy_connection_adder(struct client_state *csp);
168 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
170 static jb_err create_forged_referrer(char **header, const char *hostport);
171 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
172 static jb_err handle_conditional_hide_referrer_parameter(char **header,
173 const char *host, const int parameter_conditional_block);
174 static const char *get_appropiate_connection_header(const struct client_state *csp);
175 static void create_content_length_header(unsigned long long content_length,
176 char *header, size_t buffer_length);
179 * List of functions to run on a list of headers.
183 /** The header prefix to match */
186 /** The length of the prefix to match */
189 /** The function to apply to this line */
190 const parser_func_ptr parser;
193 static const struct parsers client_patterns[] = {
194 { "referer:", 8, client_referrer },
195 { "user-agent:", 11, client_uagent },
196 { "ua-", 3, client_ua },
197 { "from:", 5, client_from },
198 { "cookie:", 7, client_send_cookie },
199 { "x-forwarded-for:", 16, client_x_forwarded },
200 { "Accept-Encoding:", 16, client_accept_encoding },
201 { "TE:", 3, client_te },
202 { "Host:", 5, client_host },
203 { "if-modified-since:", 18, client_if_modified_since },
204 #ifndef FEATURE_CONNECTION_KEEP_ALIVE
205 { "Keep-Alive:", 11, crumble },
207 { "connection:", 11, client_connection },
208 { "proxy-connection:", 17, crumble },
209 { "max-forwards:", 13, client_max_forwards },
210 { "Accept-Language:", 16, client_accept_language },
211 { "if-none-match:", 14, client_if_none_match },
212 { "Range:", 6, client_range },
213 { "Request-Range:", 14, client_range },
214 { "If-Range:", 9, client_range },
215 { "X-Filter:", 9, client_x_filter },
216 { "*", 0, crunch_client_header },
217 { "*", 0, filter_header },
221 static const struct parsers server_patterns[] = {
222 { "HTTP/", 5, server_http },
223 { "set-cookie:", 11, server_set_cookie },
224 { "connection:", 11, server_connection },
225 { "Content-Type:", 13, server_content_type },
226 { "Content-MD5:", 12, server_content_md5 },
227 { "Content-Encoding:", 17, server_content_encoding },
228 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
229 { "Content-Length:", 15, server_save_content_length },
230 { "Keep-Alive:", 11, server_keep_alive },
232 { "Keep-Alive:", 11, crumble },
233 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
234 { "Transfer-Encoding:", 18, server_transfer_coding },
235 { "content-disposition:", 20, server_content_disposition },
236 { "Last-Modified:", 14, server_last_modified },
237 { "*", 0, crunch_server_header },
238 { "*", 0, filter_header },
242 static const add_header_func_ptr add_client_headers[] = {
244 client_x_forwarded_for_adder,
246 /* Temporarily disabled: client_accept_encoding_adder, */
247 client_connection_header_adder,
251 static const add_header_func_ptr add_server_headers[] = {
252 server_connection_adder,
253 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
254 server_proxy_connection_adder,
255 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
259 /*********************************************************************
261 * Function : flush_socket
263 * Description : Write any pending "buffered" content.
266 * 1 : fd = file descriptor of the socket to read
267 * 2 : iob = The I/O buffer to flush, usually csp->iob.
269 * Returns : On success, the number of bytes written are returned (zero
270 * indicates nothing was written). On error, -1 is returned,
271 * and errno is set appropriately. If count is zero and the
272 * file descriptor refers to a regular file, 0 will be
273 * returned without causing any other effect. For a special
274 * file, the results are not portable.
276 *********************************************************************/
277 long flush_socket(jb_socket fd, struct iob *iob)
279 long len = iob->eod - iob->cur;
286 if (write_socket(fd, iob->cur, (size_t)len))
290 iob->eod = iob->cur = iob->buf;
296 /*********************************************************************
298 * Function : add_to_iob
300 * Description : Add content to the buffered page, expanding the
301 * buffer if necessary.
304 * 1 : csp = Current client state (buffers, headers, etc...)
305 * 2 : buf = holds the content to be added to the page
306 * 3 : n = number of bytes to be added
308 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
309 * or buffer limit reached.
311 *********************************************************************/
312 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
314 struct iob *iob = csp->iob;
315 size_t used, offset, need, want;
318 if (n <= 0) return JB_ERR_OK;
320 used = (size_t)(iob->eod - iob->buf);
321 offset = (size_t)(iob->cur - iob->buf);
322 need = used + (size_t)n + 1;
325 * If the buffer can't hold the new data, extend it first.
326 * Use the next power of two if possible, else use the actual need.
328 if (need > csp->config->buffer_limit)
330 log_error(LOG_LEVEL_INFO,
331 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
332 need, csp->config->buffer_limit);
333 return JB_ERR_MEMORY;
336 if (need > iob->size)
338 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
340 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
344 else if (NULL != (p = (char *)realloc(iob->buf, need)))
350 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
351 return JB_ERR_MEMORY;
354 /* Update the iob pointers */
355 iob->cur = p + offset;
360 /* copy the new data into the iob buffer */
361 memcpy(iob->eod, buf, (size_t)n);
363 /* point to the end of the data */
366 /* null terminate == cheap insurance */
375 /*********************************************************************
377 * Function : decompress_iob
379 * Description : Decompress buffered page, expanding the
380 * buffer as necessary. csp->iob->cur
381 * should point to the the beginning of the
382 * compressed data block.
385 * 1 : csp = Current client state (buffers, headers, etc...)
387 * Returns : JB_ERR_OK on success,
388 * JB_ERR_MEMORY if out-of-memory limit reached, and
389 * JB_ERR_COMPRESS if error decompressing buffer.
391 *********************************************************************/
392 jb_err decompress_iob(struct client_state *csp)
394 char *buf; /* new, uncompressed buffer */
395 char *cur; /* Current iob position (to keep the original
396 * iob->cur unmodified if we return early) */
397 size_t bufsize; /* allocated size of the new buffer */
398 size_t old_size; /* Content size before decompression */
399 size_t skip_size; /* Number of bytes at the beginning of the iob
400 that we should NOT decompress. */
401 int status; /* return status of the inflate() call */
402 z_stream zstr; /* used by calls to zlib */
404 assert(csp->iob->cur - csp->iob->buf > 0);
405 assert(csp->iob->eod - csp->iob->cur > 0);
407 bufsize = csp->iob->size;
408 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
409 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
413 if (bufsize < (size_t)10)
416 * This is to protect the parsing of gzipped data,
417 * but it should(?) be valid for deflated data also.
419 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
420 return JB_ERR_COMPRESS;
423 if (csp->content_type & CT_GZIP)
426 * Our task is slightly complicated by the facts that data
427 * compressed by gzip does not include a zlib header, and
428 * that there is no easily accessible interface in zlib to
429 * handle a gzip header. We strip off the gzip header by
430 * hand, and later inform zlib not to expect a header.
434 * Strip off the gzip header. Please see RFC 1952 for more
435 * explanation of the appropriate fields.
437 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
438 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
439 || (*cur++ != Z_DEFLATED))
441 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
442 return JB_ERR_COMPRESS;
447 if (flags & GZIP_FLAG_RESERVED_BITS)
449 /* The gzip header has reserved bits set; bail out. */
450 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
451 return JB_ERR_COMPRESS;
455 * Skip mtime (4 bytes), extra flags (1 byte)
456 * and OS type (1 byte).
460 /* Skip extra fields if necessary. */
461 if (flags & GZIP_FLAG_EXTRA_FIELDS)
464 * Skip a given number of bytes, specified
465 * as a 16-bit little-endian value.
467 * XXX: this code is untested and should probably be removed.
471 skip_bytes += *cur++ << 8;
474 * The number of bytes to skip should be positive
475 * and we'd like to stay in the buffer.
477 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
479 log_error(LOG_LEVEL_ERROR,
480 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
482 return JB_ERR_COMPRESS;
484 log_error(LOG_LEVEL_INFO,
485 "Skipping %d bytes for gzip compression. Does this sound right?",
490 /* Skip the filename if necessary. */
491 if (flags & GZIP_FLAG_FILE_NAME)
493 /* A null-terminated string is supposed to follow. */
494 while (*cur++ && (cur < csp->iob->eod));
497 /* Skip the comment if necessary. */
498 if (flags & GZIP_FLAG_COMMENT)
500 /* A null-terminated string is supposed to follow. */
501 while (*cur++ && (cur < csp->iob->eod));
504 /* Skip the CRC if necessary. */
505 if (flags & GZIP_FLAG_CHECKSUM)
510 if (cur >= csp->iob->eod)
513 * If the current position pointer reached or passed
514 * the buffer end, we were obviously tricked to skip
517 log_error(LOG_LEVEL_ERROR,
518 "Malformed gzip header detected. Aborting decompression.");
519 return JB_ERR_COMPRESS;
523 else if (csp->content_type & CT_DEFLATE)
526 * XXX: The debug level should be lowered
527 * before the next stable release.
529 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
531 * In theory (that is, according to RFC 1950), deflate-compressed
532 * data should begin with a two-byte zlib header and have an
533 * adler32 checksum at the end. It seems that in practice only
534 * the raw compressed data is sent. Note that this means that
535 * we are not RFC 1950-compliant here, but the advantage is that
536 * this actually works. :)
538 * We add a dummy null byte to tell zlib where the data ends,
539 * and later inform it not to expect a header.
541 * Fortunately, add_to_iob() has thoughtfully null-terminated
542 * the buffer; we can just increment the end pointer to include
549 log_error(LOG_LEVEL_ERROR,
550 "Unable to determine compression format for decompression");
551 return JB_ERR_COMPRESS;
554 /* Set up the fields required by zlib. */
555 zstr.next_in = (Bytef *)cur;
556 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
557 zstr.zalloc = Z_NULL;
559 zstr.opaque = Z_NULL;
562 * Passing -MAX_WBITS to inflateInit2 tells the library
563 * that there is no zlib header.
565 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
567 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
568 return JB_ERR_COMPRESS;
572 * Next, we allocate new storage for the inflated data.
573 * We don't modify the existing iob yet, so in case there
574 * is error in decompression we can recover gracefully.
576 buf = zalloc(bufsize);
579 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
580 return JB_ERR_MEMORY;
583 assert(bufsize >= skip_size);
584 memcpy(buf, csp->iob->buf, skip_size);
585 zstr.avail_out = bufsize - skip_size;
586 zstr.next_out = (Bytef *)buf + skip_size;
588 /* Try to decompress the whole stream in one shot. */
589 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
591 /* We need to allocate more memory for the output buffer. */
593 char *tmpbuf; /* used for realloc'ing the buffer */
594 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
596 if (0 == zstr.avail_in)
599 * If zlib wants more data then there's a problem, because
600 * the complete compressed file should have been buffered.
602 log_error(LOG_LEVEL_ERROR,
603 "Unexpected end of compressed iob. Using what we got so far.");
608 * If we tried the limit and still didn't have enough
609 * memory, just give up.
611 if (bufsize == csp->config->buffer_limit)
613 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
614 return JB_ERR_MEMORY;
617 /* Try doubling the buffer size each time. */
620 /* Don't exceed the buffer limit. */
621 if (bufsize > csp->config->buffer_limit)
623 bufsize = csp->config->buffer_limit;
626 /* Try to allocate the new buffer. */
627 tmpbuf = realloc(buf, bufsize);
630 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
632 return JB_ERR_MEMORY;
636 char *oldnext_out = (char *)zstr.next_out;
639 * Update the fields for inflate() to use the new
640 * buffer, which may be in a location different from
643 zstr.avail_out += bufsize - oldbufsize;
644 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
647 * Compare with an uglier method of calculating these values
648 * that doesn't require the extra oldbufsize variable.
650 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
651 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
652 assert(zstr.avail_out > 0U);
658 if (Z_STREAM_ERROR == inflateEnd(&zstr))
660 log_error(LOG_LEVEL_ERROR,
661 "Inconsistent stream state after decompression: %s", zstr.msg);
663 * XXX: Intentionally no return.
665 * According to zlib.h, Z_STREAM_ERROR is returned
666 * "if the stream state was inconsistent".
668 * I assume in this case inflate()'s status
669 * would also be something different than Z_STREAM_END
670 * so this check should be redundant, but lets see.
674 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
677 * We failed to decompress the stream and it's
678 * not simply because of missing data.
680 log_error(LOG_LEVEL_ERROR,
681 "Unexpected error while decompressing to the buffer (iob): %s",
683 return JB_ERR_COMPRESS;
687 * Finally, we can actually update the iob, since the
688 * decompression was successful. First, free the old
691 freez(csp->iob->buf);
693 /* Now, update the iob to use the new buffer. */
695 csp->iob->cur = csp->iob->buf + skip_size;
696 csp->iob->eod = (char *)zstr.next_out;
697 csp->iob->size = bufsize;
700 * Make sure the new uncompressed iob obeys some minimal
701 * consistency conditions.
703 if ((csp->iob->buf < csp->iob->cur)
704 && (csp->iob->cur <= csp->iob->eod)
705 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
707 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
708 if (new_size > (size_t)0)
710 log_error(LOG_LEVEL_RE_FILTER,
711 "Decompression successful. Old size: %d, new size: %d.",
716 /* zlib thinks this is OK, so lets do the same. */
717 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
722 /* It seems that zlib did something weird. */
723 log_error(LOG_LEVEL_ERROR,
724 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
725 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
726 csp->iob->eod, csp->iob->buf + csp->iob->size);
727 return JB_ERR_COMPRESS;
733 #endif /* defined(FEATURE_ZLIB) */
736 /*********************************************************************
738 * Function : string_move
740 * Description : memmove wrapper to move the last part of a string
741 * towards the beginning, overwriting the part in
742 * the middle. strlcpy() can't be used here as the
746 * 1 : dst = Destination to overwrite
747 * 2 : src = Source to move.
751 *********************************************************************/
752 static void string_move(char *dst, char *src)
756 /* +1 to copy the terminating nul as well. */
757 memmove(dst, src, strlen(src)+1);
761 /*********************************************************************
763 * Function : normalize_lws
765 * Description : Reduces unquoted linear white space in headers
766 * to a single space in accordance with RFC 2616 2.2.
767 * This simplifies parsing and filtering later on.
769 * XXX: Remove log messages before
770 * the next stable release?
773 * 1 : header = A header with linear white space to reduce.
777 *********************************************************************/
778 static void normalize_lws(char *header)
784 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
788 while (ijb_isspace(*q))
792 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
798 log_error(LOG_LEVEL_HEADER,
799 "Converting tab to space in '%s'", header);
804 char *end_of_token = strstr(p+1, "\"");
806 if (NULL != end_of_token)
808 /* Don't mess with quoted text. */
813 log_error(LOG_LEVEL_HEADER,
814 "Ignoring single quote in '%s'", header);
820 p = strchr(header, ':');
821 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
824 * There's still space before the colon.
832 /*********************************************************************
834 * Function : get_header
836 * Description : This (odd) routine will parse the csp->iob
837 * to get the next complete header.
840 * 1 : iob = The I/O buffer to parse, usually csp->iob.
842 * Returns : Any one of the following:
844 * 1) a pointer to a dynamically allocated string that contains a header line
845 * 2) NULL indicating that the end of the header was reached
846 * 3) "" indicating that the end of the iob was reached before finding
847 * a complete header line.
849 *********************************************************************/
850 char *get_header(struct iob *iob)
854 header = get_header_line(iob);
856 if ((header == NULL) || (*header == '\0'))
859 * No complete header read yet, tell the client.
864 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
867 * Header spans multiple lines, append the next one.
869 char *continued_header;
871 continued_header = get_header_line(iob);
872 if ((continued_header == NULL) || (*continued_header == '\0'))
875 * No complete header read yet, return what we got.
876 * XXX: Should "unread" header instead.
878 log_error(LOG_LEVEL_INFO,
879 "Failed to read a multi-line header properly: '%s'",
884 if (JB_ERR_OK != string_join(&header, continued_header))
886 log_error(LOG_LEVEL_FATAL,
887 "Out of memory while appending multiple headers.");
891 /* XXX: remove before next stable release. */
892 log_error(LOG_LEVEL_HEADER,
893 "Merged multiple header lines to: '%s'",
898 normalize_lws(header);
905 /*********************************************************************
907 * Function : get_header_line
909 * Description : This (odd) routine will parse the csp->iob
910 * to get the next header line.
913 * 1 : iob = The I/O buffer to parse, usually csp->iob.
915 * Returns : Any one of the following:
917 * 1) a pointer to a dynamically allocated string that contains a header line
918 * 2) NULL indicating that the end of the header was reached
919 * 3) "" indicating that the end of the iob was reached before finding
920 * a complete header line.
922 *********************************************************************/
923 static char *get_header_line(struct iob *iob)
927 if ((iob->cur == NULL)
928 || ((p = strchr(iob->cur, '\n')) == NULL))
930 return(""); /* couldn't find a complete header */
935 ret = strdup(iob->cur);
938 /* FIXME No way to handle error properly */
939 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
945 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
947 /* is this a blank line (i.e. the end of the header) ? */
959 /*********************************************************************
961 * Function : get_header_value
963 * Description : Get the value of a given header from a chained list
964 * of header lines or return NULL if no such header is
965 * present in the list.
968 * 1 : header_list = pointer to list
969 * 2 : header_name = string with name of header to look for.
970 * Trailing colon required, capitalization
973 * Returns : NULL if not found, else value of header
975 *********************************************************************/
976 char *get_header_value(const struct list *header_list, const char *header_name)
978 struct list_entry *cur_entry;
984 length = strlen(header_name);
986 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
990 if (!strncmpic(cur_entry->str, header_name, length))
993 * Found: return pointer to start of value
995 ret = cur_entry->str + length;
996 while (*ret && ijb_isspace(*ret)) ret++;
1010 /*********************************************************************
1012 * Function : scan_headers
1014 * Description : Scans headers, applies tags and updates action bits.
1017 * 1 : csp = Current client state (buffers, headers, etc...)
1019 * Returns : JB_ERR_OK
1021 *********************************************************************/
1022 static jb_err scan_headers(struct client_state *csp)
1024 struct list_entry *h; /* Header */
1025 jb_err err = JB_ERR_OK;
1027 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1029 /* Header crunch()ed in previous run? -> ignore */
1030 if (h->str == NULL) continue;
1031 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1032 err = header_tagger(csp, h->str);
1039 /*********************************************************************
1043 * Description : add, delete or modify lines in the HTTP header streams.
1044 * On entry, it receives a linked list of headers space
1045 * that was allocated dynamically (both the list nodes
1046 * and the header contents).
1048 * As a side effect it frees the space used by the original
1052 * 1 : csp = Current client state (buffers, headers, etc...)
1053 * 2 : filter_server_headers = Boolean to switch between
1054 * server and header filtering.
1056 * Returns : JB_ERR_OK in case off success, or
1057 * JB_ERR_MEMORY on out-of-memory error.
1059 *********************************************************************/
1060 jb_err sed(struct client_state *csp, int filter_server_headers)
1062 /* XXX: use more descriptive names. */
1063 struct list_entry *p;
1064 const struct parsers *v;
1065 const add_header_func_ptr *f;
1066 jb_err err = JB_ERR_OK;
1068 if (filter_server_headers)
1070 v = server_patterns;
1071 f = add_server_headers;
1075 v = client_patterns;
1076 f = add_client_headers;
1081 while ((err == JB_ERR_OK) && (v->str != NULL))
1083 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1085 /* Header crunch()ed in previous run? -> ignore */
1086 if (p->str == NULL) continue;
1088 /* Does the current parser handle this header? */
1089 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1090 (v->len == CHECK_EVERY_HEADER_REMAINING))
1092 err = v->parser(csp, &(p->str));
1098 /* place additional headers on the csp->headers list */
1099 while ((err == JB_ERR_OK) && (*f))
1109 /*********************************************************************
1111 * Function : update_server_headers
1113 * Description : Updates server headers after the body has been modified.
1116 * 1 : csp = Current client state (buffers, headers, etc...)
1118 * Returns : JB_ERR_OK in case off success, or
1119 * JB_ERR_MEMORY on out-of-memory error.
1121 *********************************************************************/
1122 jb_err update_server_headers(struct client_state *csp)
1124 jb_err err = JB_ERR_OK;
1126 static const struct parsers server_patterns_light[] = {
1127 { "Content-Length:", 15, server_adjust_content_length },
1128 { "Transfer-Encoding:", 18, server_transfer_coding },
1130 { "Content-Encoding:", 17, server_content_encoding },
1131 #endif /* def FEATURE_ZLIB */
1135 if (strncmpic(csp->http->cmd, "HEAD", 4))
1137 const struct parsers *v;
1138 struct list_entry *p;
1140 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1142 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1144 /* Header crunch()ed in previous run? -> ignore */
1145 if (p->str == NULL) continue;
1147 /* Does the current parser handle this header? */
1148 if (strncmpic(p->str, v->str, v->len) == 0)
1150 err = v->parser(csp, (char **)&(p->str));
1156 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1157 if ((JB_ERR_OK == err)
1158 && (csp->flags & CSP_FLAG_MODIFIED)
1159 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1160 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1164 create_content_length_header(csp->content_length, header, sizeof(header));
1165 err = enlist(csp->headers, header);
1166 if (JB_ERR_OK == err)
1168 log_error(LOG_LEVEL_HEADER,
1169 "Content modified with no Content-Length header set. "
1170 "Created: %s.", header);
1173 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1179 /*********************************************************************
1181 * Function : header_tagger
1183 * Description : Executes all text substitutions from applying
1184 * tag actions and saves the result as tag.
1186 * XXX: Shares enough code with filter_header() and
1187 * pcrs_filter_response() to warrant some helper functions.
1190 * 1 : csp = Current client state (buffers, headers, etc...)
1191 * 2 : header = Header that is used as tagger input
1193 * Returns : JB_ERR_OK on success and always succeeds
1195 *********************************************************************/
1196 static jb_err header_tagger(struct client_state *csp, char *header)
1198 int wanted_filter_type;
1199 int multi_action_index;
1203 struct file_list *fl;
1204 struct re_filterfile_spec *b;
1205 struct list_entry *tag_name;
1207 int found_filters = 0;
1208 const size_t header_length = strlen(header);
1210 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1212 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1213 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1217 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1218 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1221 /* Check if there are any filters */
1222 for (i = 0; i < MAX_AF_FILES; i++)
1235 if (0 == found_filters)
1237 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1238 "tagging enabled, but no taggers available.");
1242 for (i = 0; i < MAX_AF_FILES; i++)
1245 if ((NULL == fl) || (NULL == fl->f))
1248 * Either there are no filter files
1249 * left, or this filter file just
1250 * contains no valid filters.
1252 * Continue to be sure we don't miss
1253 * valid filter files that are chained
1254 * after empty or invalid ones.
1259 /* For all filters, */
1260 for (b = fl->f; b; b = b->next)
1262 if (b->type != wanted_filter_type)
1264 /* skip the ones we don't care about, */
1267 /* leaving only taggers that could apply, of which we use the ones, */
1268 for (tag_name = csp->action->multi[multi_action_index]->first;
1269 NULL != tag_name; tag_name = tag_name->next)
1271 /* that do apply, and */
1272 if (strcmp(b->name, tag_name->str) == 0)
1274 char *modified_tag = NULL;
1276 size_t size = header_length;
1277 pcrs_job *joblist = b->joblist;
1279 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1281 if (NULL == joblist)
1283 log_error(LOG_LEVEL_RE_FILTER,
1284 "Tagger %s has empty joblist. Nothing to do.", b->name);
1288 /* execute their pcrs_joblist on the header. */
1289 for (job = joblist; NULL != job; job = job->next)
1291 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1295 /* Success, continue with the modified version. */
1304 /* Tagger doesn't match */
1307 /* Regex failure, log it but continue anyway. */
1308 assert(NULL != header);
1309 log_error(LOG_LEVEL_ERROR,
1310 "Problems with tagger \'%s\' and header \'%s\': %s",
1311 b->name, *header, pcrs_strerror(hits));
1313 freez(modified_tag);
1317 if (b->dynamic) pcrs_free_joblist(joblist);
1319 /* If this tagger matched */
1325 * There is to technical limitation which makes
1326 * it impossible to use empty tags, but I assume
1327 * no one would do it intentionally.
1330 log_error(LOG_LEVEL_INFO,
1331 "Tagger \'%s\' created an empty tag. Ignored.",
1336 if (!list_contains_item(csp->tags, tag))
1338 if (JB_ERR_OK != enlist(csp->tags, tag))
1340 log_error(LOG_LEVEL_ERROR,
1341 "Insufficient memory to add tag \'%s\', "
1342 "based on tagger \'%s\' and header \'%s\'",
1343 tag, b->name, *header);
1347 char *action_message;
1349 * update the action bits right away, to make
1350 * tagging based on tags set by earlier taggers
1351 * of the same kind possible.
1353 if (update_action_bits_for_tag(csp, tag))
1355 action_message = "Action bits updated accordingly.";
1359 action_message = "No action bits update necessary.";
1362 log_error(LOG_LEVEL_HEADER,
1363 "Tagger \'%s\' added tag \'%s\'. %s",
1364 b->name, tag, action_message);
1369 /* XXX: Is this log-worthy? */
1370 log_error(LOG_LEVEL_HEADER,
1371 "Tagger \'%s\' didn't add tag \'%s\'. "
1372 "Tag already present", b->name, tag);
1375 } /* if the tagger matched */
1376 } /* if the tagger applies */
1377 } /* for every tagger that could apply */
1378 } /* for all filters */
1379 } /* for all filter files */
1384 /* here begins the family of parser functions that reformat header lines */
1386 /*********************************************************************
1388 * Function : filter_header
1390 * Description : Executes all text substitutions from all applying
1391 * +(server|client)-header-filter actions on the header.
1392 * Most of the code was copied from pcrs_filter_response,
1393 * including the rather short variable names
1396 * 1 : csp = Current client state (buffers, headers, etc...)
1397 * 2 : header = On input, pointer to header to modify.
1398 * On output, pointer to the modified header, or NULL
1399 * to remove the header. This function frees the
1400 * original string if necessary.
1402 * Returns : JB_ERR_OK on success and always succeeds
1404 *********************************************************************/
1405 static jb_err filter_header(struct client_state *csp, char **header)
1409 size_t size = strlen(*header);
1411 char *newheader = NULL;
1414 struct file_list *fl;
1415 struct re_filterfile_spec *b;
1416 struct list_entry *filtername;
1418 int i, found_filters = 0;
1419 int wanted_filter_type;
1420 int multi_action_index;
1422 if (csp->flags & CSP_FLAG_NO_FILTERING)
1427 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1429 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1430 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1434 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1435 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1439 * Need to check the set of re_filterfiles...
1441 for (i = 0; i < MAX_AF_FILES; i++)
1454 if (0 == found_filters)
1456 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1457 "header filtering enabled, but no matching filters available.");
1461 for (i = 0; i < MAX_AF_FILES; i++)
1464 if ((NULL == fl) || (NULL == fl->f))
1467 * Either there are no filter files
1468 * left, or this filter file just
1469 * contains no valid filters.
1471 * Continue to be sure we don't miss
1472 * valid filter files that are chained
1473 * after empty or invalid ones.
1478 * For all applying +filter actions, look if a filter by that
1479 * name exists and if yes, execute its pcrs_joblist on the
1482 for (b = fl->f; b; b = b->next)
1484 if (b->type != wanted_filter_type)
1486 /* Skip other filter types */
1490 for (filtername = csp->action->multi[multi_action_index]->first;
1491 filtername ; filtername = filtername->next)
1493 if (strcmp(b->name, filtername->str) == 0)
1495 int current_hits = 0;
1496 pcrs_job *joblist = b->joblist;
1498 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1500 if (NULL == joblist)
1502 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1506 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1507 *header, size, b->name);
1509 /* Apply all jobs from the joblist */
1510 for (job = joblist; NULL != job; job = job->next)
1512 matches = pcrs_execute(job, *header, size, &newheader, &size);
1515 current_hits += matches;
1516 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1518 *header = newheader;
1520 else if ( 0 == matches )
1522 /* Filter doesn't change header */
1528 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1529 *header, b->name, pcrs_strerror(matches));
1530 if (newheader != NULL)
1532 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1538 if (b->dynamic) pcrs_free_joblist(joblist);
1540 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1541 hits += current_hits;
1548 * Additionally checking for hits is important because if
1549 * the continue hack is triggered, server headers can
1550 * arrive empty to separate multiple heads from each other.
1552 if ((0 == size) && hits)
1554 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1562 /*********************************************************************
1564 * Function : server_connection
1566 * Description : Makes sure a proper "Connection:" header is
1567 * set and signals connection_header_adder to
1571 * 1 : csp = Current client state (buffers, headers, etc...)
1572 * 2 : header = On input, pointer to header to modify.
1573 * On output, pointer to the modified header, or NULL
1574 * to remove the header. This function frees the
1575 * original string if necessary.
1577 * Returns : JB_ERR_OK on success, or
1578 * JB_ERR_MEMORY on out-of-memory error.
1580 *********************************************************************/
1581 static jb_err server_connection(struct client_state *csp, char **header)
1583 if (!strcmpic(*header, "Connection: keep-alive"))
1585 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1586 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1588 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1591 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1593 log_error(LOG_LEVEL_HEADER,
1594 "Keeping the server header '%s' around.", *header);
1597 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1599 char *old_header = *header;
1601 *header = strdup("Connection: close");
1604 return JB_ERR_MEMORY;
1606 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1611 /* Signal server_connection_adder() to return early. */
1612 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1618 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1619 /*********************************************************************
1621 * Function : server_keep_alive
1623 * Description : Stores the servers keep alive timeout.
1626 * 1 : csp = Current client state (buffers, headers, etc...)
1627 * 2 : header = On input, pointer to header to modify.
1628 * On output, pointer to the modified header, or NULL
1629 * to remove the header. This function frees the
1630 * original string if necessary.
1632 * Returns : JB_ERR_OK.
1634 *********************************************************************/
1635 static jb_err server_keep_alive(struct client_state *csp, char **header)
1637 unsigned int keep_alive_timeout;
1638 const char *timeout_position = strstr(*header, "timeout=");
1640 if ((NULL == timeout_position)
1641 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1643 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1647 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1649 log_error(LOG_LEVEL_HEADER,
1650 "Reducing keep-alive timeout from %u to %u.",
1651 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1652 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1656 /* XXX: Is this log worthy? */
1657 log_error(LOG_LEVEL_HEADER,
1658 "Server keep-alive timeout is %u. Sticking with %u.",
1659 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1665 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1669 /*********************************************************************
1671 * Function : client_connection
1673 * Description : Makes sure a proper "Connection:" header is
1674 * set and signals connection_header_adder
1678 * 1 : csp = Current client state (buffers, headers, etc...)
1679 * 2 : header = On input, pointer to header to modify.
1680 * On output, pointer to the modified header, or NULL
1681 * to remove the header. This function frees the
1682 * original string if necessary.
1684 * Returns : JB_ERR_OK on success, or
1685 * JB_ERR_MEMORY on out-of-memory error.
1687 *********************************************************************/
1688 static jb_err client_connection(struct client_state *csp, char **header)
1690 const char *wanted_header = get_appropiate_connection_header(csp);
1692 if (strcmpic(*header, wanted_header))
1694 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1695 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1697 log_error(LOG_LEVEL_HEADER,
1698 "Keeping the client header '%s' around. "
1699 "The connection will not be kept alive.",
1703 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1705 char *old_header = *header;
1707 *header = strdup(wanted_header);
1710 return JB_ERR_MEMORY;
1712 log_error(LOG_LEVEL_HEADER,
1713 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1717 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1720 log_error(LOG_LEVEL_HEADER,
1721 "Keeping the client header '%s' around. "
1722 "The server connection will be kept alive if possible.",
1724 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1726 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1728 /* Signal client_connection_adder() to return early. */
1729 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1735 /*********************************************************************
1737 * Function : crumble
1739 * Description : This is called if a header matches a pattern to "crunch"
1742 * 1 : csp = Current client state (buffers, headers, etc...)
1743 * 2 : header = On input, pointer to header to modify.
1744 * On output, pointer to the modified header, or NULL
1745 * to remove the header. This function frees the
1746 * original string if necessary.
1748 * Returns : JB_ERR_OK on success, or
1749 * JB_ERR_MEMORY on out-of-memory error.
1751 *********************************************************************/
1752 static jb_err crumble(struct client_state *csp, char **header)
1755 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1761 /*********************************************************************
1763 * Function : crunch_server_header
1765 * Description : Crunch server header if it matches a string supplied by the
1766 * user. Called from `sed'.
1769 * 1 : csp = Current client state (buffers, headers, etc...)
1770 * 2 : header = On input, pointer to header to modify.
1771 * On output, pointer to the modified header, or NULL
1772 * to remove the header. This function frees the
1773 * original string if necessary.
1775 * Returns : JB_ERR_OK on success and always succeeds
1777 *********************************************************************/
1778 static jb_err crunch_server_header(struct client_state *csp, char **header)
1780 const char *crunch_pattern;
1782 /* Do we feel like crunching? */
1783 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1785 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1787 /* Is the current header the lucky one? */
1788 if (strstr(*header, crunch_pattern))
1790 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1799 /*********************************************************************
1801 * Function : server_content_type
1803 * Description : Set the content-type for filterable types (text/.*,
1804 * .*xml.*, javascript and image/gif) unless filtering has been
1805 * forbidden (CT_TABOO) while parsing earlier headers.
1806 * NOTE: Since text/plain is commonly used by web servers
1807 * for files whose correct type is unknown, we don't
1808 * set CT_TEXT for it.
1811 * 1 : csp = Current client state (buffers, headers, etc...)
1812 * 2 : header = On input, pointer to header to modify.
1813 * On output, pointer to the modified header, or NULL
1814 * to remove the header. This function frees the
1815 * original string if necessary.
1817 * Returns : JB_ERR_OK on success, or
1818 * JB_ERR_MEMORY on out-of-memory error.
1820 *********************************************************************/
1821 static jb_err server_content_type(struct client_state *csp, char **header)
1823 /* Remove header if it isn't the first Content-Type header */
1824 if ((csp->content_type & CT_DECLARED))
1827 * Another, slightly slower, way to see if
1828 * we already parsed another Content-Type header.
1830 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1832 log_error(LOG_LEVEL_ERROR,
1833 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1841 * Signal that the Content-Type has been set.
1843 csp->content_type |= CT_DECLARED;
1845 if (!(csp->content_type & CT_TABOO))
1848 * XXX: The assumption that text/plain is a sign of
1849 * binary data seems to be somewhat unreasonable nowadays
1850 * and should be dropped after 3.0.8 is out.
1852 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
1853 || strstr(*header, "xml")
1854 || strstr(*header, "application/x-javascript"))
1856 csp->content_type |= CT_TEXT;
1858 else if (strstr(*header, "image/gif"))
1860 csp->content_type |= CT_GIF;
1865 * Are we messing with the content type?
1867 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1870 * Make sure the user doesn't accidently
1871 * change the content type of binary documents.
1873 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
1876 *header = strdup("Content-Type: ");
1877 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1881 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1882 return JB_ERR_MEMORY;
1884 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1888 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
1889 "It doesn't look like a content type that should be filtered. "
1890 "Enable force-text-mode if you know what you're doing.", *header);
1898 /*********************************************************************
1900 * Function : server_transfer_coding
1902 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1903 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1904 * - Remove header if body was chunked but has been
1905 * de-chunked for filtering.
1908 * 1 : csp = Current client state (buffers, headers, etc...)
1909 * 2 : header = On input, pointer to header to modify.
1910 * On output, pointer to the modified header, or NULL
1911 * to remove the header. This function frees the
1912 * original string if necessary.
1914 * Returns : JB_ERR_OK on success, or
1915 * JB_ERR_MEMORY on out-of-memory error.
1917 *********************************************************************/
1918 static jb_err server_transfer_coding(struct client_state *csp, char **header)
1921 * Turn off pcrs and gif filtering if body compressed
1923 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1927 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1929 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1930 csp->http->cmd, *header);
1931 #endif /* def FEATURE_ZLIB */
1932 csp->content_type = CT_TABOO;
1936 * Raise flag if body chunked
1938 if (strstr(*header, "chunked"))
1940 csp->flags |= CSP_FLAG_CHUNKED;
1943 * If the body was modified, it has been de-chunked first
1944 * and the header must be removed.
1946 * FIXME: If there is more than one transfer encoding,
1947 * only the "chunked" part should be removed here.
1949 if (csp->flags & CSP_FLAG_MODIFIED)
1951 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1960 /*********************************************************************
1962 * Function : server_content_encoding
1964 * Description : This function is run twice for each request,
1965 * unless FEATURE_ZLIB and filtering are disabled.
1967 * The first run is used to check if the content
1968 * is compressed, if FEATURE_ZLIB is disabled
1969 * filtering is then disabled as well, if FEATURE_ZLIB
1970 * is enabled the content is marked for decompression.
1972 * The second run is used to remove the Content-Encoding
1973 * header if the decompression was successful.
1976 * 1 : csp = Current client state (buffers, headers, etc...)
1977 * 2 : header = On input, pointer to header to modify.
1978 * On output, pointer to the modified header, or NULL
1979 * to remove the header. This function frees the
1980 * original string if necessary.
1982 * Returns : JB_ERR_OK on success, or
1983 * JB_ERR_MEMORY on out-of-memory error.
1985 *********************************************************************/
1986 static jb_err server_content_encoding(struct client_state *csp, char **header)
1989 if ((csp->flags & CSP_FLAG_MODIFIED)
1990 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1993 * We successfully decompressed the content,
1994 * and have to clean the header now, so the
1995 * client no longer expects compressed data..
1997 * XXX: There is a difference between cleaning
1998 * and removing it completely.
2000 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2003 else if (strstr(*header, "gzip"))
2005 /* Mark for gzip decompression */
2006 csp->content_type |= CT_GZIP;
2008 else if (strstr(*header, "deflate"))
2010 /* Mark for zlib decompression */
2011 csp->content_type |= CT_DEFLATE;
2013 else if (strstr(*header, "compress"))
2016 * We can't decompress this; therefore we can't filter
2019 csp->content_type |= CT_TABOO;
2021 #else /* !defined(FEATURE_ZLIB) */
2022 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2025 * Body is compressed, turn off pcrs and gif filtering.
2027 csp->content_type |= CT_TABOO;
2030 * Log a warning if the user expects the content to be filtered.
2032 if ((csp->rlist != NULL) &&
2033 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2035 log_error(LOG_LEVEL_INFO,
2036 "Compressed content detected, content filtering disabled. "
2037 "Consider recompiling Privoxy with zlib support or "
2038 "enable the prevent-compression action.");
2041 #endif /* defined(FEATURE_ZLIB) */
2048 /*********************************************************************
2050 * Function : server_adjust_content_length
2052 * Description : Adjust Content-Length header if we modified
2056 * 1 : csp = Current client state (buffers, headers, etc...)
2057 * 2 : header = On input, pointer to header to modify.
2058 * On output, pointer to the modified header, or NULL
2059 * to remove the header. This function frees the
2060 * original string if necessary.
2062 * Returns : JB_ERR_OK on success, or
2063 * JB_ERR_MEMORY on out-of-memory error.
2065 *********************************************************************/
2066 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2068 /* Regenerate header if the content was modified. */
2069 if (csp->flags & CSP_FLAG_MODIFIED)
2071 const size_t header_length = 50;
2073 *header = malloc(header_length);
2074 if (*header == NULL)
2076 return JB_ERR_MEMORY;
2078 create_content_length_header(csp->content_length, *header, header_length);
2079 log_error(LOG_LEVEL_HEADER,
2080 "Adjusted Content-Length to %llu", csp->content_length);
2087 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2088 /*********************************************************************
2090 * Function : server_save_content_length
2092 * Description : Save the Content-Length sent by the server.
2095 * 1 : csp = Current client state (buffers, headers, etc...)
2096 * 2 : header = On input, pointer to header to modify.
2097 * On output, pointer to the modified header, or NULL
2098 * to remove the header. This function frees the
2099 * original string if necessary.
2101 * Returns : JB_ERR_OK on success, or
2102 * JB_ERR_MEMORY on out-of-memory error.
2104 *********************************************************************/
2105 static jb_err server_save_content_length(struct client_state *csp, char **header)
2107 unsigned long long content_length = 0;
2109 assert(*(*header+14) == ':');
2111 if (1 != sscanf(*header+14, ": %llu", &content_length))
2113 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2118 csp->expected_content_length = content_length;
2119 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2120 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2125 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2128 /*********************************************************************
2130 * Function : server_content_md5
2132 * Description : Crumble any Content-MD5 headers if the document was
2133 * modified. FIXME: Should we re-compute instead?
2136 * 1 : csp = Current client state (buffers, headers, etc...)
2137 * 2 : header = On input, pointer to header to modify.
2138 * On output, pointer to the modified header, or NULL
2139 * to remove the header. This function frees the
2140 * original string if necessary.
2142 * Returns : JB_ERR_OK on success, or
2143 * JB_ERR_MEMORY on out-of-memory error.
2145 *********************************************************************/
2146 static jb_err server_content_md5(struct client_state *csp, char **header)
2148 if (csp->flags & CSP_FLAG_MODIFIED)
2150 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2158 /*********************************************************************
2160 * Function : server_content_disposition
2162 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2163 * Called from `sed'.
2166 * 1 : csp = Current client state (buffers, headers, etc...)
2167 * 2 : header = On input, pointer to header to modify.
2168 * On output, pointer to the modified header, or NULL
2169 * to remove the header. This function frees the
2170 * original string if necessary.
2172 * Returns : JB_ERR_OK on success, or
2173 * JB_ERR_MEMORY on out-of-memory error.
2175 *********************************************************************/
2176 static jb_err server_content_disposition(struct client_state *csp, char **header)
2181 * Are we messing with the Content-Disposition header?
2183 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2189 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2191 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2194 * Blocking content-disposition header
2196 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2203 * Replacing Content-Disposition header
2206 *header = strdup("Content-Disposition: ");
2207 string_append(header, newval);
2209 if (*header != NULL)
2211 log_error(LOG_LEVEL_HEADER,
2212 "Content-Disposition header crunched and replaced with: %s", *header);
2215 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2219 /*********************************************************************
2221 * Function : server_last_modified
2223 * Description : Changes Last-Modified header to the actual date
2224 * to help hide-if-modified-since.
2225 * Called from `sed'.
2228 * 1 : csp = Current client state (buffers, headers, etc...)
2229 * 2 : header = On input, pointer to header to modify.
2230 * On output, pointer to the modified header, or NULL
2231 * to remove the header. This function frees the
2232 * original string if necessary.
2234 * Returns : JB_ERR_OK on success, or
2235 * JB_ERR_MEMORY on out-of-memory error.
2237 *********************************************************************/
2238 static jb_err server_last_modified(struct client_state *csp, char **header)
2241 char buf[BUFFER_SIZE];
2244 #ifdef HAVE_GMTIME_R
2247 struct tm *timeptr = NULL;
2248 time_t now, last_modified;
2249 long int days, hours, minutes, seconds;
2252 * Are we messing with the Last-Modified header?
2254 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2260 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2262 if (0 == strcmpic(newval, "block") )
2265 * Blocking Last-Modified header. Useless but why not.
2267 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2271 else if (0 == strcmpic(newval, "reset-to-request-time"))
2274 * Setting Last-Modified Header to now.
2276 get_http_time(0, buf, sizeof(buf));
2278 *header = strdup("Last-Modified: ");
2279 string_append(header, buf);
2281 if (*header == NULL)
2283 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2287 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2290 else if (0 == strcmpic(newval, "randomize"))
2292 const char *header_time = *header + sizeof("Last-Modified:");
2294 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2296 #ifdef HAVE_GMTIME_R
2297 gmtime_r(&now, &gmt);
2298 #elif defined(MUTEX_LOCKS_AVAILABLE)
2299 privoxy_mutex_lock(&gmtime_mutex);
2301 privoxy_mutex_unlock(&gmtime_mutex);
2305 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2307 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2312 long int rtime = (long int)difftime(now, last_modified);
2315 const int negative_delta = (rtime < 0);
2320 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2322 rtime = pick_from_range(rtime);
2327 last_modified += rtime;
2328 #ifdef HAVE_GMTIME_R
2329 timeptr = gmtime_r(&last_modified, &gmt);
2330 #elif defined(MUTEX_LOCKS_AVAILABLE)
2331 privoxy_mutex_lock(&gmtime_mutex);
2332 timeptr = gmtime(&last_modified);
2333 privoxy_mutex_unlock(&gmtime_mutex);
2335 timeptr = gmtime(&last_modified);
2337 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2339 *header = strdup("Last-Modified: ");
2340 string_append(header, newheader);
2342 if (*header == NULL)
2344 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2345 return JB_ERR_MEMORY;
2348 days = rtime / (3600 * 24);
2349 hours = rtime / 3600 % 24;
2350 minutes = rtime / 60 % 60;
2351 seconds = rtime % 60;
2353 log_error(LOG_LEVEL_HEADER,
2354 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2355 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2356 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2360 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2369 /*********************************************************************
2371 * Function : client_accept_encoding
2373 * Description : Rewrite the client's Accept-Encoding header so that
2374 * if doesn't allow compression, if the action applies.
2375 * Note: For HTTP/1.0 the absence of the header is enough.
2378 * 1 : csp = Current client state (buffers, headers, etc...)
2379 * 2 : header = On input, pointer to header to modify.
2380 * On output, pointer to the modified header, or NULL
2381 * to remove the header. This function frees the
2382 * original string if necessary.
2384 * Returns : JB_ERR_OK on success, or
2385 * JB_ERR_MEMORY on out-of-memory error.
2387 *********************************************************************/
2388 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2390 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2392 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2396 /* Temporarily disable the correct behaviour to
2397 * work around a PHP bug.
2399 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2401 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2402 * if (*header == NULL)
2404 * return JB_ERR_MEMORY;
2415 /*********************************************************************
2417 * Function : client_te
2419 * Description : Rewrite the client's TE header so that
2420 * if doesn't allow compression, if the action applies.
2423 * 1 : csp = Current client state (buffers, headers, etc...)
2424 * 2 : header = On input, pointer to header to modify.
2425 * On output, pointer to the modified header, or NULL
2426 * to remove the header. This function frees the
2427 * original string if necessary.
2429 * Returns : JB_ERR_OK on success, or
2430 * JB_ERR_MEMORY on out-of-memory error.
2432 *********************************************************************/
2433 static jb_err client_te(struct client_state *csp, char **header)
2435 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2438 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2445 /*********************************************************************
2447 * Function : client_referrer
2449 * Description : Handle the "referer" config setting properly.
2450 * Called from `sed'.
2453 * 1 : csp = Current client state (buffers, headers, etc...)
2454 * 2 : header = On input, pointer to header to modify.
2455 * On output, pointer to the modified header, or NULL
2456 * to remove the header. This function frees the
2457 * original string if necessary.
2459 * Returns : JB_ERR_OK on success, or
2460 * JB_ERR_MEMORY on out-of-memory error.
2462 *********************************************************************/
2463 static jb_err client_referrer(struct client_state *csp, char **header)
2465 const char *parameter;
2466 /* booleans for parameters we have to check multiple times */
2467 int parameter_conditional_block;
2468 int parameter_conditional_forge;
2470 #ifdef FEATURE_FORCE_LOAD
2472 * Since the referrer can include the prefix even
2473 * if the request itself is non-forced, we must
2474 * clean it unconditionally.
2476 * XXX: strclean is too broad
2478 strclean(*header, FORCE_PREFIX);
2479 #endif /* def FEATURE_FORCE_LOAD */
2481 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2483 /* Nothing left to do */
2487 parameter = csp->action->string[ACTION_STRING_REFERER];
2488 assert(parameter != NULL);
2489 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2490 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2492 if (!parameter_conditional_block && !parameter_conditional_forge)
2495 * As conditional-block and conditional-forge are the only
2496 * parameters that rely on the original referrer, we can
2497 * remove it now for all the others.
2502 if (0 == strcmpic(parameter, "block"))
2504 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2507 else if (parameter_conditional_block || parameter_conditional_forge)
2509 return handle_conditional_hide_referrer_parameter(header,
2510 csp->http->hostport, parameter_conditional_block);
2512 else if (0 == strcmpic(parameter, "forge"))
2514 return create_forged_referrer(header, csp->http->hostport);
2518 /* interpret parameter as user-supplied referer to fake */
2519 return create_fake_referrer(header, parameter);
2524 /*********************************************************************
2526 * Function : client_accept_language
2528 * Description : Handle the "Accept-Language" config setting properly.
2529 * Called from `sed'.
2532 * 1 : csp = Current client state (buffers, headers, etc...)
2533 * 2 : header = On input, pointer to header to modify.
2534 * On output, pointer to the modified header, or NULL
2535 * to remove the header. This function frees the
2536 * original string if necessary.
2538 * Returns : JB_ERR_OK on success, or
2539 * JB_ERR_MEMORY on out-of-memory error.
2541 *********************************************************************/
2542 static jb_err client_accept_language(struct client_state *csp, char **header)
2547 * Are we messing with the Accept-Language?
2549 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2551 /*I don't think so*/
2555 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2557 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2560 * Blocking Accept-Language header
2562 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2569 * Replacing Accept-Language header
2572 *header = strdup("Accept-Language: ");
2573 string_append(header, newval);
2575 if (*header == NULL)
2577 log_error(LOG_LEVEL_ERROR,
2578 "Insufficient memory. Accept-Language header crunched without replacement.");
2582 log_error(LOG_LEVEL_HEADER,
2583 "Accept-Language header crunched and replaced with: %s", *header);
2586 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2590 /*********************************************************************
2592 * Function : crunch_client_header
2594 * Description : Crunch client header if it matches a string supplied by the
2595 * user. Called from `sed'.
2598 * 1 : csp = Current client state (buffers, headers, etc...)
2599 * 2 : header = On input, pointer to header to modify.
2600 * On output, pointer to the modified header, or NULL
2601 * to remove the header. This function frees the
2602 * original string if necessary.
2604 * Returns : JB_ERR_OK on success and always succeeds
2606 *********************************************************************/
2607 static jb_err crunch_client_header(struct client_state *csp, char **header)
2609 const char *crunch_pattern;
2611 /* Do we feel like crunching? */
2612 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2614 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2616 /* Is the current header the lucky one? */
2617 if (strstr(*header, crunch_pattern))
2619 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2627 /*********************************************************************
2629 * Function : client_uagent
2631 * Description : Handle the "user-agent" config setting properly
2632 * and remember its original value to enable browser
2633 * bug workarounds. Called from `sed'.
2636 * 1 : csp = Current client state (buffers, headers, etc...)
2637 * 2 : header = On input, pointer to header to modify.
2638 * On output, pointer to the modified header, or NULL
2639 * to remove the header. This function frees the
2640 * original string if necessary.
2642 * Returns : JB_ERR_OK on success, or
2643 * JB_ERR_MEMORY on out-of-memory error.
2645 *********************************************************************/
2646 static jb_err client_uagent(struct client_state *csp, char **header)
2650 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2655 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2662 *header = strdup("User-Agent: ");
2663 string_append(header, newval);
2665 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2667 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2671 /*********************************************************************
2673 * Function : client_ua
2675 * Description : Handle "ua-" headers properly. Called from `sed'.
2678 * 1 : csp = Current client state (buffers, headers, etc...)
2679 * 2 : header = On input, pointer to header to modify.
2680 * On output, pointer to the modified header, or NULL
2681 * to remove the header. This function frees the
2682 * original string if necessary.
2684 * Returns : JB_ERR_OK on success, or
2685 * JB_ERR_MEMORY on out-of-memory error.
2687 *********************************************************************/
2688 static jb_err client_ua(struct client_state *csp, char **header)
2690 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2692 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2700 /*********************************************************************
2702 * Function : client_from
2704 * Description : Handle the "from" config setting properly.
2705 * Called from `sed'.
2708 * 1 : csp = Current client state (buffers, headers, etc...)
2709 * 2 : header = On input, pointer to header to modify.
2710 * On output, pointer to the modified header, or NULL
2711 * to remove the header. This function frees the
2712 * original string if necessary.
2714 * Returns : JB_ERR_OK on success, or
2715 * JB_ERR_MEMORY on out-of-memory error.
2717 *********************************************************************/
2718 static jb_err client_from(struct client_state *csp, char **header)
2722 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2729 newval = csp->action->string[ACTION_STRING_FROM];
2732 * Are we blocking the e-mail address?
2734 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2736 log_error(LOG_LEVEL_HEADER, "crunched From!");
2740 log_error(LOG_LEVEL_HEADER, " modified");
2742 *header = strdup("From: ");
2743 string_append(header, newval);
2745 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2749 /*********************************************************************
2751 * Function : client_send_cookie
2753 * Description : Crunches the "cookie" header if necessary.
2754 * Called from `sed'.
2756 * XXX: Stupid name, doesn't send squat.
2759 * 1 : csp = Current client state (buffers, headers, etc...)
2760 * 2 : header = On input, pointer to header to modify.
2761 * On output, pointer to the modified header, or NULL
2762 * to remove the header. This function frees the
2763 * original string if necessary.
2765 * Returns : JB_ERR_OK on success, or
2766 * JB_ERR_MEMORY on out-of-memory error.
2768 *********************************************************************/
2769 static jb_err client_send_cookie(struct client_state *csp, char **header)
2771 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2773 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2781 /*********************************************************************
2783 * Function : client_x_forwarded
2785 * Description : Handle the "x-forwarded-for" config setting properly,
2786 * also used in the add_client_headers list. Called from `sed'.
2789 * 1 : csp = Current client state (buffers, headers, etc...)
2790 * 2 : header = On input, pointer to header to modify.
2791 * On output, pointer to the modified header, or NULL
2792 * to remove the header. This function frees the
2793 * original string if necessary.
2795 * Returns : JB_ERR_OK on success, or
2796 * JB_ERR_MEMORY on out-of-memory error.
2798 *********************************************************************/
2799 jb_err client_x_forwarded(struct client_state *csp, char **header)
2801 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
2803 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
2805 if (0 == strcmpic(parameter, "block"))
2808 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2810 else if (0 == strcmpic(parameter, "add"))
2812 string_append(header, ", ");
2813 string_append(header, csp->ip_addr_str);
2815 if (*header == NULL)
2817 return JB_ERR_MEMORY;
2819 log_error(LOG_LEVEL_HEADER,
2820 "Appended client IP address to %s", *header);
2821 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
2825 log_error(LOG_LEVEL_FATAL,
2826 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
2834 /*********************************************************************
2836 * Function : client_max_forwards
2838 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2839 * from the value of the Max-Forwards header field.
2842 * 1 : csp = Current client state (buffers, headers, etc...)
2843 * 2 : header = On input, pointer to header to modify.
2844 * On output, pointer to the modified header, or NULL
2845 * to remove the header. This function frees the
2846 * original string if necessary.
2848 * Returns : JB_ERR_OK on success, or
2849 * JB_ERR_MEMORY on out-of-memory error.
2851 *********************************************************************/
2852 static jb_err client_max_forwards(struct client_state *csp, char **header)
2856 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2857 (0 == strcmpic(csp->http->gpc, "options")))
2859 assert(*(*header+12) == ':');
2860 if (1 == sscanf(*header+12, ": %d", &max_forwards))
2862 if (max_forwards > 0)
2864 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
2865 log_error(LOG_LEVEL_HEADER,
2866 "Max-Forwards value for %s request reduced to %d.",
2867 csp->http->gpc, max_forwards);
2869 else if (max_forwards < 0)
2871 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2877 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2886 /*********************************************************************
2888 * Function : client_host
2890 * Description : If the request URI did not contain host and
2891 * port information, parse and evaluate the Host
2894 * Also, kill ill-formed HOST: headers as sent by
2895 * Apple's iTunes software when used with a proxy.
2898 * 1 : csp = Current client state (buffers, headers, etc...)
2899 * 2 : header = On input, pointer to header to modify.
2900 * On output, pointer to the modified header, or NULL
2901 * to remove the header. This function frees the
2902 * original string if necessary.
2904 * Returns : JB_ERR_OK on success, or
2905 * JB_ERR_MEMORY on out-of-memory error.
2907 *********************************************************************/
2908 static jb_err client_host(struct client_state *csp, char **header)
2913 * If the header field name is all upper-case, chances are that it's
2914 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2915 * not a problem -- they are regenerated later.
2917 if ((*header)[1] == 'O')
2919 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2924 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2925 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2928 if (NULL == (p = strdup((*header)+6)))
2930 return JB_ERR_MEMORY;
2933 if (NULL == (q = strdup(p)))
2936 return JB_ERR_MEMORY;
2939 freez(csp->http->hostport);
2940 csp->http->hostport = p;
2941 freez(csp->http->host);
2942 csp->http->host = q;
2943 q = strchr(csp->http->host, ':');
2946 /* Terminate hostname and evaluate port string */
2948 csp->http->port = atoi(q);
2952 csp->http->port = csp->http->ssl ? 443 : 80;
2955 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2956 csp->http->hostport, csp->http->host, csp->http->port);
2959 /* Signal client_host_adder() to return right away */
2960 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
2966 /*********************************************************************
2968 * Function : client_if_modified_since
2970 * Description : Remove or modify the If-Modified-Since header.
2973 * 1 : csp = Current client state (buffers, headers, etc...)
2974 * 2 : header = On input, pointer to header to modify.
2975 * On output, pointer to the modified header, or NULL
2976 * to remove the header. This function frees the
2977 * original string if necessary.
2979 * Returns : JB_ERR_OK on success, or
2980 * JB_ERR_MEMORY on out-of-memory error.
2982 *********************************************************************/
2983 static jb_err client_if_modified_since(struct client_state *csp, char **header)
2986 #ifdef HAVE_GMTIME_R
2989 struct tm *timeptr = NULL;
2992 long int hours, minutes, seconds;
2995 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2998 * The client got an error message because of a temporary problem,
2999 * the problem is gone and the client now tries to revalidate our
3000 * error message on the real server. The revalidation would always
3001 * end with the transmission of the whole document and there is
3002 * no need to expose the bogus If-Modified-Since header.
3004 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3007 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3009 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3011 if ((0 == strcmpic(newval, "block")))
3013 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3016 else /* add random value */
3018 const char *header_time = *header + sizeof("If-Modified-Since:");
3020 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3022 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3027 long int rtime = strtol(newval, &endptr, 0);
3028 const int negative_range = (rtime < 0);
3032 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3033 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3039 rtime = pick_from_range(rtime);
3043 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3046 tm += rtime * (negative_range ? -1 : 1);
3047 #ifdef HAVE_GMTIME_R
3048 timeptr = gmtime_r(&tm, &gmt);
3049 #elif defined(MUTEX_LOCKS_AVAILABLE)
3050 privoxy_mutex_lock(&gmtime_mutex);
3051 timeptr = gmtime(&tm);
3052 privoxy_mutex_unlock(&gmtime_mutex);
3054 timeptr = gmtime(&tm);
3056 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3059 *header = strdup("If-Modified-Since: ");
3060 string_append(header, newheader);
3062 if (*header == NULL)
3064 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3065 return JB_ERR_MEMORY;
3068 hours = rtime / 3600;
3069 minutes = rtime / 60 % 60;
3070 seconds = rtime % 60;
3072 log_error(LOG_LEVEL_HEADER,
3073 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3074 *header, (negative_range) ? "subtracted" : "added", hours,
3075 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3076 seconds, (seconds == 1) ? ")" : "s)");
3085 /*********************************************************************
3087 * Function : client_if_none_match
3089 * Description : Remove the If-None-Match header.
3092 * 1 : csp = Current client state (buffers, headers, etc...)
3093 * 2 : header = On input, pointer to header to modify.
3094 * On output, pointer to the modified header, or NULL
3095 * to remove the header. This function frees the
3096 * original string if necessary.
3098 * Returns : JB_ERR_OK on success, or
3099 * JB_ERR_MEMORY on out-of-memory error.
3101 *********************************************************************/
3102 static jb_err client_if_none_match(struct client_state *csp, char **header)
3104 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3106 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3114 /*********************************************************************
3116 * Function : client_x_filter
3118 * Description : Disables filtering if the client set "X-Filter: No".
3119 * Called from `sed'.
3122 * 1 : csp = Current client state (buffers, headers, etc...)
3123 * 2 : header = On input, pointer to header to modify.
3124 * On output, pointer to the modified header, or NULL
3125 * to remove the header. This function frees the
3126 * original string if necessary.
3128 * Returns : JB_ERR_OK on success
3130 *********************************************************************/
3131 jb_err client_x_filter(struct client_state *csp, char **header)
3133 if ( 0 == strcmpic(*header, "X-Filter: No"))
3135 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3137 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3141 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3143 log_error(LOG_LEVEL_HEADER,
3144 "force-text-mode overruled the client's request to fetch without filtering!");
3148 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3149 csp->flags |= CSP_FLAG_NO_FILTERING;
3150 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3152 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3160 /*********************************************************************
3162 * Function : client_range
3164 * Description : Removes Range, Request-Range and If-Range headers if
3165 * content filtering is enabled. If the client's version
3166 * of the document has been altered by Privoxy, the server
3167 * could interpret the range differently than the client
3168 * intended in which case the user could end up with
3169 * corrupted content.
3172 * 1 : csp = Current client state (buffers, headers, etc...)
3173 * 2 : header = On input, pointer to header to modify.
3174 * On output, pointer to the modified header, or NULL
3175 * to remove the header. This function frees the
3176 * original string if necessary.
3178 * Returns : JB_ERR_OK
3180 *********************************************************************/
3181 static jb_err client_range(struct client_state *csp, char **header)
3183 if (content_filters_enabled(csp->action))
3185 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3186 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3193 /* the following functions add headers directly to the header list */
3195 /*********************************************************************
3197 * Function : client_host_adder
3199 * Description : Adds the Host: header field if it is missing.
3200 * Called from `sed'.
3203 * 1 : csp = Current client state (buffers, headers, etc...)
3205 * Returns : JB_ERR_OK on success, or
3206 * JB_ERR_MEMORY on out-of-memory error.
3208 *********************************************************************/
3209 static jb_err client_host_adder(struct client_state *csp)
3214 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3216 /* Header already set by the client, nothing to do. */
3220 if ( !csp->http->hostport || !*(csp->http->hostport))
3222 /* XXX: When does this happen and why is it OK? */
3223 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3228 * remove 'user:pass@' from 'proto://user:pass@host'
3230 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3236 p = csp->http->hostport;
3239 /* XXX: Just add it, we already made sure that it will be unique */
3240 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3241 err = enlist_unique_header(csp->headers, "Host", p);
3248 /*********************************************************************
3250 * Function : client_accept_encoding_adder
3252 * Description : Add an Accept-Encoding header to the client's request
3253 * that disables compression if the action applies, and
3254 * the header is not already there. Called from `sed'.
3255 * Note: For HTTP/1.0, the absence of the header is enough.
3258 * 1 : csp = Current client state (buffers, headers, etc...)
3260 * Returns : JB_ERR_OK on success, or
3261 * JB_ERR_MEMORY on out-of-memory error.
3263 *********************************************************************/
3264 static jb_err client_accept_encoding_adder(struct client_state *csp)
3266 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3267 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3269 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3277 /*********************************************************************
3279 * Function : client_xtra_adder
3281 * Description : Used in the add_client_headers list. Called from `sed'.
3284 * 1 : csp = Current client state (buffers, headers, etc...)
3286 * Returns : JB_ERR_OK on success, or
3287 * JB_ERR_MEMORY on out-of-memory error.
3289 *********************************************************************/
3290 static jb_err client_xtra_adder(struct client_state *csp)
3292 struct list_entry *lst;
3295 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3296 lst ; lst = lst->next)
3298 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3299 err = enlist(csp->headers, lst->str);
3311 /*********************************************************************
3313 * Function : client_x_forwarded_for_adder
3315 * Description : Used in the add_client_headers list. Called from `sed'.
3318 * 1 : csp = Current client state (buffers, headers, etc...)
3320 * Returns : JB_ERR_OK on success, or
3321 * JB_ERR_MEMORY on out-of-memory error.
3323 *********************************************************************/
3324 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3326 char *header = NULL;
3329 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3330 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3331 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3334 * If we aren't adding X-Forwarded-For headers,
3335 * or we already appended an existing X-Forwarded-For
3336 * header, there's nothing left to do here.
3341 header = strdup("X-Forwarded-For: ");
3342 string_append(&header, csp->ip_addr_str);
3346 return JB_ERR_MEMORY;
3349 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3350 err = enlist(csp->headers, header);
3357 /*********************************************************************
3359 * Function : server_connection_adder
3361 * Description : Adds an appropiate "Connection:" header to csp->headers
3362 * unless the header was already present. Called from `sed'.
3365 * 1 : csp = Current client state (buffers, headers, etc...)
3367 * Returns : JB_ERR_OK on success, or
3368 * JB_ERR_MEMORY on out-of-memory error.
3370 *********************************************************************/
3371 static jb_err server_connection_adder(struct client_state *csp)
3373 const unsigned int flags = csp->flags;
3374 const char *response_status_line = csp->headers->first->str;
3375 const char *wanted_header = get_appropiate_connection_header(csp);
3377 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3378 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3384 * XXX: if we downgraded the response, this check will fail.
3386 if ((csp->config->feature_flags &
3387 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3388 && (NULL != response_status_line)
3389 && !strncmpic(response_status_line, "HTTP/1.1", 8))
3391 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3392 "without Connection header implies keep-alive.");
3393 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3396 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3398 return enlist(csp->headers, wanted_header);
3402 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3403 /*********************************************************************
3405 * Function : server_proxy_connection_adder
3407 * Description : Adds a "Proxy-Connection: keep-alive" header to
3408 * csp->headers if the client asked for keep-alive.
3409 * XXX: We should reuse existant ones.
3412 * 1 : csp = Current client state (buffers, headers, etc...)
3414 * Returns : JB_ERR_OK on success, or
3415 * JB_ERR_MEMORY on out-of-memory error.
3417 *********************************************************************/
3418 static jb_err server_proxy_connection_adder(struct client_state *csp)
3420 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3421 jb_err err = JB_ERR_OK;
3423 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3425 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3426 err = enlist(csp->headers, proxy_connection_header);
3431 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3434 /*********************************************************************
3436 * Function : client_connection_header_adder
3438 * Description : Adds a proper "Connection:" header to csp->headers
3439 * unless the header was already present. Called from `sed'.
3442 * 1 : csp = Current client state (buffers, headers, etc...)
3444 * Returns : JB_ERR_OK on success, or
3445 * JB_ERR_MEMORY on out-of-memory error.
3447 *********************************************************************/
3448 static jb_err client_connection_header_adder(struct client_state *csp)
3450 const char *wanted_header = get_appropiate_connection_header(csp);
3452 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3453 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3458 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3459 && (csp->http->ssl == 0))
3461 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3464 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3466 return enlist(csp->headers, wanted_header);
3470 /*********************************************************************
3472 * Function : server_http
3474 * Description : - Save the HTTP Status into csp->http->status
3475 * - Set CT_TABOO to prevent filtering if the answer
3476 * is a partial range (HTTP status 206)
3477 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3481 * 1 : csp = Current client state (buffers, headers, etc...)
3482 * 2 : header = On input, pointer to header to modify.
3483 * On output, pointer to the modified header, or NULL
3484 * to remove the header. This function frees the
3485 * original string if necessary.
3487 * Returns : JB_ERR_OK on success, or
3488 * JB_ERR_MEMORY on out-of-memory error.
3490 *********************************************************************/
3491 static jb_err server_http(struct client_state *csp, char **header)
3493 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3494 if (csp->http->status == 206)
3496 csp->content_type = CT_TABOO;
3499 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3501 /* XXX: Should we do a real validity check here? */
3502 if (strlen(*header) > 8)
3505 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3510 * XXX: Should we block the request or
3511 * enlist a valid status code line here?
3513 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3514 "Downgrading to HTTP/1.0 impossible.");
3522 /*********************************************************************
3524 * Function : server_set_cookie
3526 * Description : Handle the server "cookie" header properly.
3527 * Log cookie to the jar file. Then "crunch",
3528 * accept or rewrite it to a session cookie.
3529 * Called from `sed'.
3531 * TODO: Allow the user to specify a new expiration
3532 * time to cause the cookie to expire even before the
3533 * browser is closed.
3536 * 1 : csp = Current client state (buffers, headers, etc...)
3537 * 2 : header = On input, pointer to header to modify.
3538 * On output, pointer to the modified header, or NULL
3539 * to remove the header. This function frees the
3540 * original string if necessary.
3542 * Returns : JB_ERR_OK on success, or
3543 * JB_ERR_MEMORY on out-of-memory error.
3545 *********************************************************************/
3546 static jb_err server_set_cookie(struct client_state *csp, char **header)
3553 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3555 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3558 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3560 /* Flag whether or not to log a message */
3563 /* A variable to store the tag we're working on */
3566 /* Skip "Set-Cookie:" (11 characters) in header */
3567 cur_tag = *header + 11;
3569 /* skip whitespace between "Set-Cookie:" and value */
3570 while (*cur_tag && ijb_isspace(*cur_tag))
3575 /* Loop through each tag in the cookie */
3579 char *next_tag = strchr(cur_tag, ';');
3580 if (next_tag != NULL)
3582 /* Skip the ';' character itself */
3585 /* skip whitespace ";" and start of tag */
3586 while (*next_tag && ijb_isspace(*next_tag))
3593 /* "Next tag" is the end of the string */
3594 next_tag = cur_tag + strlen(cur_tag);
3598 * Check the expiration date to see
3599 * if the cookie is still valid, if yes,
3600 * rewrite it to a session cookie.
3602 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3604 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3606 /* Did we detect the date properly? */
3607 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3610 * Nope, treat it as if it was still valid.
3612 * XXX: Should we remove the whole cookie instead?
3614 log_error(LOG_LEVEL_ERROR,
3615 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3616 string_move(cur_tag, next_tag);
3622 * Yes. Check if the cookie is still valid.
3624 * If the cookie is already expired it's probably
3625 * a delete cookie and even if it isn't, the browser
3626 * will discard it anyway.
3630 * XXX: timegm() isn't available on some AmigaOS
3631 * versions and our replacement doesn't work.
3633 * Our options are to either:
3635 * - disable session-cookies-only completely if timegm
3638 * - to simply remove all expired tags, like it has
3639 * been done until Privoxy 3.0.6 and to live with
3640 * the consequence that it can cause login/logout
3641 * problems on servers that don't validate their
3642 * input properly, or
3644 * - to replace it with mktime in which
3645 * case there is a slight chance of valid cookies
3646 * passing as already expired.
3648 * This is the way it's currently done and it's not
3649 * as bad as it sounds. If the missing GMT offset is
3650 * enough to change the result of the expiration check
3651 * the cookie will be only valid for a few hours
3652 * anyway, which in many cases will be shorter
3653 * than a browser session.
3655 if (cookie_time - now < 0)
3657 log_error(LOG_LEVEL_HEADER,
3658 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3659 /* Just in case some clown sets more then one expiration date */
3665 * Still valid, delete expiration date by copying
3666 * the rest of the string over it.
3668 string_move(cur_tag, next_tag);
3670 /* That changed the header, need to issue a log message */
3674 * Note that the next tag has now been moved to *cur_tag,
3675 * so we do not need to update the cur_tag pointer.
3683 /* Move on to next cookie tag */
3690 assert(NULL != *header);
3691 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3700 #ifdef FEATURE_FORCE_LOAD
3701 /*********************************************************************
3703 * Function : strclean
3705 * Description : In-Situ-Eliminate all occurances of substring in
3709 * 1 : string = string to clean
3710 * 2 : substring = substring to eliminate
3712 * Returns : Number of eliminations
3714 *********************************************************************/
3715 int strclean(char *string, const char *substring)
3721 len = strlen(substring);
3723 while((pos = strstr(string, substring)) != NULL)
3730 while (*p++ != '\0');
3737 #endif /* def FEATURE_FORCE_LOAD */
3740 /*********************************************************************
3742 * Function : parse_header_time
3744 * Description : Parses time formats used in HTTP header strings
3745 * to get the numerical respresentation.
3748 * 1 : header_time = HTTP header time as string.
3749 * 2 : result = storage for header_time in seconds
3751 * Returns : JB_ERR_OK if the time format was recognized, or
3752 * JB_ERR_PARSE otherwise.
3754 *********************************************************************/
3755 static jb_err parse_header_time(const char *header_time, time_t *result)
3760 * Zero out gmt to prevent time zone offsets.
3762 * While this is only necessary on some platforms
3763 * (mingw32 for example), I don't know how to
3764 * detect these automatically and doing it everywhere
3767 memset(&gmt, 0, sizeof(gmt));
3769 /* Tue, 02 Jun 2037 20:00:00 */
3770 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3771 /* Tue, 02-Jun-2037 20:00:00 */
3772 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3773 /* Tue, 02-Jun-37 20:00:00 */
3774 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3775 /* Tuesday, 02-Jun-2037 20:00:00 */
3776 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3777 /* Tuesday Jun 02 20:00:00 2037 */
3778 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3780 return JB_ERR_PARSE;
3783 *result = timegm(&gmt);
3790 /*********************************************************************
3792 * Function : get_destination_from_headers
3794 * Description : Parse the "Host:" header to get the request's destination.
3795 * Only needed if the client's request was forcefully
3796 * redirected into Privoxy.
3798 * Code mainly copied from client_host() which is currently
3799 * run too late for this purpose.
3802 * 1 : headers = List of headers (one of them hopefully being
3803 * the "Host:" header)
3804 * 2 : http = storage for the result (host, port and hostport).
3806 * Returns : JB_ERR_MEMORY in case of memory problems,
3807 * JB_ERR_PARSE if the host header couldn't be found,
3808 * JB_ERR_OK otherwise.
3810 *********************************************************************/
3811 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3817 host = get_header_value(headers, "Host:");
3821 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3822 return JB_ERR_PARSE;
3825 if (NULL == (p = strdup((host))))
3827 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3828 return JB_ERR_MEMORY;
3831 if (NULL == (q = strdup(p)))
3834 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3835 return JB_ERR_MEMORY;
3838 freez(http->hostport);
3842 q = strchr(http->host, ':');
3845 /* Terminate hostname and evaluate port string */
3847 http->port = atoi(q);
3851 http->port = http->ssl ? 443 : 80;
3854 /* Rebuild request URL */
3856 http->url = strdup(http->ssl ? "https://" : "http://");
3857 string_append(&http->url, http->hostport);
3858 string_append(&http->url, http->path);
3859 if (http->url == NULL)
3861 return JB_ERR_MEMORY;
3864 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
3872 /*********************************************************************
3874 * Function : create_forged_referrer
3876 * Description : Helper for client_referrer to forge a referer as
3877 * 'http://[hostname:port/' to fool stupid
3878 * checks for in-site links
3881 * 1 : header = Pointer to header pointer
3882 * 2 : hostport = Host and optionally port as string
3884 * Returns : JB_ERR_OK in case of success, or
3885 * JB_ERR_MEMORY in case of memory problems.
3887 *********************************************************************/
3888 static jb_err create_forged_referrer(char **header, const char *hostport)
3890 assert(NULL == *header);
3892 *header = strdup("Referer: http://");
3893 string_append(header, hostport);
3894 string_append(header, "/");
3896 if (NULL == *header)
3898 return JB_ERR_MEMORY;
3901 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
3908 /*********************************************************************
3910 * Function : create_fake_referrer
3912 * Description : Helper for client_referrer to create a fake referrer
3913 * based on a string supplied by the user.
3916 * 1 : header = Pointer to header pointer
3917 * 2 : hosthost = Referrer to fake
3919 * Returns : JB_ERR_OK in case of success, or
3920 * JB_ERR_MEMORY in case of memory problems.
3922 *********************************************************************/
3923 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
3925 assert(NULL == *header);
3927 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
3929 log_error(LOG_LEVEL_HEADER,
3930 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
3932 *header = strdup("Referer: ");
3933 string_append(header, fake_referrer);
3935 if (NULL == *header)
3937 return JB_ERR_MEMORY;
3940 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
3947 /*********************************************************************
3949 * Function : handle_conditional_hide_referrer_parameter
3951 * Description : Helper for client_referrer to crunch or forge
3952 * the referrer header if the host has changed.
3955 * 1 : header = Pointer to header pointer
3956 * 2 : host = The target host (may include the port)
3957 * 3 : parameter_conditional_block = Boolean to signal
3958 * if we're in conditional-block mode. If not set,
3959 * we're in conditional-forge mode.
3961 * Returns : JB_ERR_OK in case of success, or
3962 * JB_ERR_MEMORY in case of memory problems.
3964 *********************************************************************/
3965 static jb_err handle_conditional_hide_referrer_parameter(char **header,
3966 const char *host, const int parameter_conditional_block)
3968 char *referer = strdup(*header);
3969 const size_t hostlenght = strlen(host);
3970 const char *referer_url = NULL;
3972 if (NULL == referer)
3975 return JB_ERR_MEMORY;
3978 /* referer begins with 'Referer: http[s]://' */
3979 if ((hostlenght+17) < strlen(referer))
3982 * Shorten referer to make sure the referer is blocked
3983 * if www.example.org/www.example.com-shall-see-the-referer/
3984 * links to www.example.com/
3986 referer[hostlenght+17] = '\0';
3988 referer_url = strstr(referer, "http://");
3989 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
3991 /* Host has changed, Referer is invalid or a https URL. */
3992 if (parameter_conditional_block)
3994 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4001 return create_forged_referrer(header, host);
4011 /*********************************************************************
4013 * Function : get_appropiate_connection_header
4015 * Description : Returns an appropiate Connection header
4016 * depending on whether or not we try to keep
4017 * the connection to the server alive.
4020 * 1 : csp = Current client state (buffers, headers, etc...)
4022 * Returns : Pointer to statically allocated header buffer.
4024 *********************************************************************/
4025 static const char *get_appropiate_connection_header(const struct client_state *csp)
4027 static const char connection_keep_alive[] = "Connection: keep-alive";
4028 static const char connection_close[] = "Connection: close";
4030 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4031 && (csp->http->ssl == 0))
4033 return connection_keep_alive;
4035 return connection_close;
4039 /*********************************************************************
4041 * Function : create_content_length_header
4043 * Description : Creates a Content-Length header.
4046 * 1 : content_length = The content length to be used in the header.
4047 * 2 : header = Allocated space to safe the header.
4048 * 3 : buffer_length = The length of the allocated space.
4052 *********************************************************************/
4053 static void create_content_length_header(unsigned long long content_length,
4054 char *header, size_t buffer_length)
4056 snprintf(header, buffer_length, "Content-Length: %llu", content_length);