1 const char parsers_rcs[] = "$Id: parsers.c,v 1.174 2009/06/05 16:54:27 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);
177 * List of functions to run on a list of headers.
181 /** The header prefix to match */
184 /** The length of the prefix to match */
187 /** The function to apply to this line */
188 const parser_func_ptr parser;
191 static const struct parsers client_patterns[] = {
192 { "referer:", 8, client_referrer },
193 { "user-agent:", 11, client_uagent },
194 { "ua-", 3, client_ua },
195 { "from:", 5, client_from },
196 { "cookie:", 7, client_send_cookie },
197 { "x-forwarded-for:", 16, client_x_forwarded },
198 { "Accept-Encoding:", 16, client_accept_encoding },
199 { "TE:", 3, client_te },
200 { "Host:", 5, client_host },
201 { "if-modified-since:", 18, client_if_modified_since },
202 #ifndef FEATURE_CONNECTION_KEEP_ALIVE
203 { "Keep-Alive:", 11, crumble },
205 { "connection:", 11, client_connection },
206 { "proxy-connection:", 17, crumble },
207 { "max-forwards:", 13, client_max_forwards },
208 { "Accept-Language:", 16, client_accept_language },
209 { "if-none-match:", 14, client_if_none_match },
210 { "Range:", 6, client_range },
211 { "Request-Range:", 14, client_range },
212 { "If-Range:", 9, client_range },
213 { "X-Filter:", 9, client_x_filter },
214 { "*", 0, crunch_client_header },
215 { "*", 0, filter_header },
219 static const struct parsers server_patterns[] = {
220 { "HTTP/", 5, server_http },
221 { "set-cookie:", 11, server_set_cookie },
222 { "connection:", 11, server_connection },
223 { "Content-Type:", 13, server_content_type },
224 { "Content-MD5:", 12, server_content_md5 },
225 { "Content-Encoding:", 17, server_content_encoding },
226 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
227 { "Content-Length:", 15, server_save_content_length },
228 { "Keep-Alive:", 11, server_keep_alive },
230 { "Keep-Alive:", 11, crumble },
231 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
232 { "Transfer-Encoding:", 18, server_transfer_coding },
233 { "content-disposition:", 20, server_content_disposition },
234 { "Last-Modified:", 14, server_last_modified },
235 { "*", 0, crunch_server_header },
236 { "*", 0, filter_header },
240 static const add_header_func_ptr add_client_headers[] = {
242 client_x_forwarded_for_adder,
244 /* Temporarily disabled: client_accept_encoding_adder, */
245 client_connection_header_adder,
249 static const add_header_func_ptr add_server_headers[] = {
250 server_connection_adder,
251 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
252 server_proxy_connection_adder,
253 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
257 /*********************************************************************
259 * Function : flush_socket
261 * Description : Write any pending "buffered" content.
264 * 1 : fd = file descriptor of the socket to read
265 * 2 : iob = The I/O buffer to flush, usually csp->iob.
267 * Returns : On success, the number of bytes written are returned (zero
268 * indicates nothing was written). On error, -1 is returned,
269 * and errno is set appropriately. If count is zero and the
270 * file descriptor refers to a regular file, 0 will be
271 * returned without causing any other effect. For a special
272 * file, the results are not portable.
274 *********************************************************************/
275 long flush_socket(jb_socket fd, struct iob *iob)
277 long len = iob->eod - iob->cur;
284 if (write_socket(fd, iob->cur, (size_t)len))
288 iob->eod = iob->cur = iob->buf;
294 /*********************************************************************
296 * Function : add_to_iob
298 * Description : Add content to the buffered page, expanding the
299 * buffer if necessary.
302 * 1 : csp = Current client state (buffers, headers, etc...)
303 * 2 : buf = holds the content to be added to the page
304 * 3 : n = number of bytes to be added
306 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
307 * or buffer limit reached.
309 *********************************************************************/
310 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
312 struct iob *iob = csp->iob;
313 size_t used, offset, need, want;
316 if (n <= 0) return JB_ERR_OK;
318 used = (size_t)(iob->eod - iob->buf);
319 offset = (size_t)(iob->cur - iob->buf);
320 need = used + (size_t)n + 1;
323 * If the buffer can't hold the new data, extend it first.
324 * Use the next power of two if possible, else use the actual need.
326 if (need > csp->config->buffer_limit)
328 log_error(LOG_LEVEL_INFO,
329 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
330 need, csp->config->buffer_limit);
331 return JB_ERR_MEMORY;
334 if (need > iob->size)
336 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
338 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
342 else if (NULL != (p = (char *)realloc(iob->buf, need)))
348 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
349 return JB_ERR_MEMORY;
352 /* Update the iob pointers */
353 iob->cur = p + offset;
358 /* copy the new data into the iob buffer */
359 memcpy(iob->eod, buf, (size_t)n);
361 /* point to the end of the data */
364 /* null terminate == cheap insurance */
373 /*********************************************************************
375 * Function : decompress_iob
377 * Description : Decompress buffered page, expanding the
378 * buffer as necessary. csp->iob->cur
379 * should point to the the beginning of the
380 * compressed data block.
383 * 1 : csp = Current client state (buffers, headers, etc...)
385 * Returns : JB_ERR_OK on success,
386 * JB_ERR_MEMORY if out-of-memory limit reached, and
387 * JB_ERR_COMPRESS if error decompressing buffer.
389 *********************************************************************/
390 jb_err decompress_iob(struct client_state *csp)
392 char *buf; /* new, uncompressed buffer */
393 char *cur; /* Current iob position (to keep the original
394 * iob->cur unmodified if we return early) */
395 size_t bufsize; /* allocated size of the new buffer */
396 size_t old_size; /* Content size before decompression */
397 size_t skip_size; /* Number of bytes at the beginning of the iob
398 that we should NOT decompress. */
399 int status; /* return status of the inflate() call */
400 z_stream zstr; /* used by calls to zlib */
402 assert(csp->iob->cur - csp->iob->buf > 0);
403 assert(csp->iob->eod - csp->iob->cur > 0);
405 bufsize = csp->iob->size;
406 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
407 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
411 if (bufsize < (size_t)10)
414 * This is to protect the parsing of gzipped data,
415 * but it should(?) be valid for deflated data also.
417 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
418 return JB_ERR_COMPRESS;
421 if (csp->content_type & CT_GZIP)
424 * Our task is slightly complicated by the facts that data
425 * compressed by gzip does not include a zlib header, and
426 * that there is no easily accessible interface in zlib to
427 * handle a gzip header. We strip off the gzip header by
428 * hand, and later inform zlib not to expect a header.
432 * Strip off the gzip header. Please see RFC 1952 for more
433 * explanation of the appropriate fields.
435 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
436 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
437 || (*cur++ != Z_DEFLATED))
439 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
440 return JB_ERR_COMPRESS;
445 if (flags & GZIP_FLAG_RESERVED_BITS)
447 /* The gzip header has reserved bits set; bail out. */
448 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
449 return JB_ERR_COMPRESS;
453 * Skip mtime (4 bytes), extra flags (1 byte)
454 * and OS type (1 byte).
458 /* Skip extra fields if necessary. */
459 if (flags & GZIP_FLAG_EXTRA_FIELDS)
462 * Skip a given number of bytes, specified
463 * as a 16-bit little-endian value.
465 * XXX: this code is untested and should probably be removed.
469 skip_bytes += *cur++ << 8;
472 * The number of bytes to skip should be positive
473 * and we'd like to stay in the buffer.
475 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
477 log_error(LOG_LEVEL_ERROR,
478 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
480 return JB_ERR_COMPRESS;
482 log_error(LOG_LEVEL_INFO,
483 "Skipping %d bytes for gzip compression. Does this sound right?",
488 /* Skip the filename if necessary. */
489 if (flags & GZIP_FLAG_FILE_NAME)
491 /* A null-terminated string is supposed to follow. */
492 while (*cur++ && (cur < csp->iob->eod));
495 /* Skip the comment if necessary. */
496 if (flags & GZIP_FLAG_COMMENT)
498 /* A null-terminated string is supposed to follow. */
499 while (*cur++ && (cur < csp->iob->eod));
502 /* Skip the CRC if necessary. */
503 if (flags & GZIP_FLAG_CHECKSUM)
508 if (cur >= csp->iob->eod)
511 * If the current position pointer reached or passed
512 * the buffer end, we were obviously tricked to skip
515 log_error(LOG_LEVEL_ERROR,
516 "Malformed gzip header detected. Aborting decompression.");
517 return JB_ERR_COMPRESS;
521 else if (csp->content_type & CT_DEFLATE)
524 * XXX: The debug level should be lowered
525 * before the next stable release.
527 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
529 * In theory (that is, according to RFC 1950), deflate-compressed
530 * data should begin with a two-byte zlib header and have an
531 * adler32 checksum at the end. It seems that in practice only
532 * the raw compressed data is sent. Note that this means that
533 * we are not RFC 1950-compliant here, but the advantage is that
534 * this actually works. :)
536 * We add a dummy null byte to tell zlib where the data ends,
537 * and later inform it not to expect a header.
539 * Fortunately, add_to_iob() has thoughtfully null-terminated
540 * the buffer; we can just increment the end pointer to include
547 log_error(LOG_LEVEL_ERROR,
548 "Unable to determine compression format for decompression");
549 return JB_ERR_COMPRESS;
552 /* Set up the fields required by zlib. */
553 zstr.next_in = (Bytef *)cur;
554 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
555 zstr.zalloc = Z_NULL;
557 zstr.opaque = Z_NULL;
560 * Passing -MAX_WBITS to inflateInit2 tells the library
561 * that there is no zlib header.
563 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
565 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
566 return JB_ERR_COMPRESS;
570 * Next, we allocate new storage for the inflated data.
571 * We don't modify the existing iob yet, so in case there
572 * is error in decompression we can recover gracefully.
574 buf = zalloc(bufsize);
577 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
578 return JB_ERR_MEMORY;
581 assert(bufsize >= skip_size);
582 memcpy(buf, csp->iob->buf, skip_size);
583 zstr.avail_out = bufsize - skip_size;
584 zstr.next_out = (Bytef *)buf + skip_size;
586 /* Try to decompress the whole stream in one shot. */
587 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
589 /* We need to allocate more memory for the output buffer. */
591 char *tmpbuf; /* used for realloc'ing the buffer */
592 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
594 if (0 == zstr.avail_in)
597 * If zlib wants more data then there's a problem, because
598 * the complete compressed file should have been buffered.
600 log_error(LOG_LEVEL_ERROR,
601 "Unexpected end of compressed iob. Using what we got so far.");
606 * If we tried the limit and still didn't have enough
607 * memory, just give up.
609 if (bufsize == csp->config->buffer_limit)
611 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
612 return JB_ERR_MEMORY;
615 /* Try doubling the buffer size each time. */
618 /* Don't exceed the buffer limit. */
619 if (bufsize > csp->config->buffer_limit)
621 bufsize = csp->config->buffer_limit;
624 /* Try to allocate the new buffer. */
625 tmpbuf = realloc(buf, bufsize);
628 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
630 return JB_ERR_MEMORY;
634 char *oldnext_out = (char *)zstr.next_out;
637 * Update the fields for inflate() to use the new
638 * buffer, which may be in a location different from
641 zstr.avail_out += bufsize - oldbufsize;
642 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
645 * Compare with an uglier method of calculating these values
646 * that doesn't require the extra oldbufsize variable.
648 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
649 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
650 assert(zstr.avail_out > 0U);
656 if (Z_STREAM_ERROR == inflateEnd(&zstr))
658 log_error(LOG_LEVEL_ERROR,
659 "Inconsistent stream state after decompression: %s", zstr.msg);
661 * XXX: Intentionally no return.
663 * According to zlib.h, Z_STREAM_ERROR is returned
664 * "if the stream state was inconsistent".
666 * I assume in this case inflate()'s status
667 * would also be something different than Z_STREAM_END
668 * so this check should be redundant, but lets see.
672 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
675 * We failed to decompress the stream and it's
676 * not simply because of missing data.
678 log_error(LOG_LEVEL_ERROR,
679 "Unexpected error while decompressing to the buffer (iob): %s",
681 return JB_ERR_COMPRESS;
685 * Finally, we can actually update the iob, since the
686 * decompression was successful. First, free the old
689 freez(csp->iob->buf);
691 /* Now, update the iob to use the new buffer. */
693 csp->iob->cur = csp->iob->buf + skip_size;
694 csp->iob->eod = (char *)zstr.next_out;
695 csp->iob->size = bufsize;
698 * Make sure the new uncompressed iob obeys some minimal
699 * consistency conditions.
701 if ((csp->iob->buf < csp->iob->cur)
702 && (csp->iob->cur <= csp->iob->eod)
703 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
705 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
706 if (new_size > (size_t)0)
708 log_error(LOG_LEVEL_RE_FILTER,
709 "Decompression successful. Old size: %d, new size: %d.",
714 /* zlib thinks this is OK, so lets do the same. */
715 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
720 /* It seems that zlib did something weird. */
721 log_error(LOG_LEVEL_ERROR,
722 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
723 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
724 csp->iob->eod, csp->iob->buf + csp->iob->size);
725 return JB_ERR_COMPRESS;
731 #endif /* defined(FEATURE_ZLIB) */
734 /*********************************************************************
736 * Function : string_move
738 * Description : memmove wrapper to move the last part of a string
739 * towards the beginning, overwriting the part in
740 * the middle. strlcpy() can't be used here as the
744 * 1 : dst = Destination to overwrite
745 * 2 : src = Source to move.
749 *********************************************************************/
750 static void string_move(char *dst, char *src)
754 /* +1 to copy the terminating nul as well. */
755 memmove(dst, src, strlen(src)+1);
759 /*********************************************************************
761 * Function : normalize_lws
763 * Description : Reduces unquoted linear white space in headers
764 * to a single space in accordance with RFC 2616 2.2.
765 * This simplifies parsing and filtering later on.
767 * XXX: Remove log messages before
768 * the next stable release?
771 * 1 : header = A header with linear white space to reduce.
775 *********************************************************************/
776 static void normalize_lws(char *header)
782 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
786 while (ijb_isspace(*q))
790 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
796 log_error(LOG_LEVEL_HEADER,
797 "Converting tab to space in '%s'", header);
802 char *end_of_token = strstr(p+1, "\"");
804 if (NULL != end_of_token)
806 /* Don't mess with quoted text. */
811 log_error(LOG_LEVEL_HEADER,
812 "Ignoring single quote in '%s'", header);
818 p = strchr(header, ':');
819 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
822 * There's still space before the colon.
830 /*********************************************************************
832 * Function : get_header
834 * Description : This (odd) routine will parse the csp->iob
835 * to get the next complete header.
838 * 1 : iob = The I/O buffer to parse, usually csp->iob.
840 * Returns : Any one of the following:
842 * 1) a pointer to a dynamically allocated string that contains a header line
843 * 2) NULL indicating that the end of the header was reached
844 * 3) "" indicating that the end of the iob was reached before finding
845 * a complete header line.
847 *********************************************************************/
848 char *get_header(struct iob *iob)
852 header = get_header_line(iob);
854 if ((header == NULL) || (*header == '\0'))
857 * No complete header read yet, tell the client.
862 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
865 * Header spans multiple lines, append the next one.
867 char *continued_header;
869 continued_header = get_header_line(iob);
870 if ((continued_header == NULL) || (*continued_header == '\0'))
873 * No complete header read yet, return what we got.
874 * XXX: Should "unread" header instead.
876 log_error(LOG_LEVEL_INFO,
877 "Failed to read a multi-line header properly: '%s'",
882 if (JB_ERR_OK != string_join(&header, continued_header))
884 log_error(LOG_LEVEL_FATAL,
885 "Out of memory while appending multiple headers.");
889 /* XXX: remove before next stable release. */
890 log_error(LOG_LEVEL_HEADER,
891 "Merged multiple header lines to: '%s'",
896 normalize_lws(header);
903 /*********************************************************************
905 * Function : get_header_line
907 * Description : This (odd) routine will parse the csp->iob
908 * to get the next header line.
911 * 1 : iob = The I/O buffer to parse, usually csp->iob.
913 * Returns : Any one of the following:
915 * 1) a pointer to a dynamically allocated string that contains a header line
916 * 2) NULL indicating that the end of the header was reached
917 * 3) "" indicating that the end of the iob was reached before finding
918 * a complete header line.
920 *********************************************************************/
921 static char *get_header_line(struct iob *iob)
925 if ((iob->cur == NULL)
926 || ((p = strchr(iob->cur, '\n')) == NULL))
928 return(""); /* couldn't find a complete header */
933 ret = strdup(iob->cur);
936 /* FIXME No way to handle error properly */
937 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
943 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
945 /* is this a blank line (i.e. the end of the header) ? */
957 /*********************************************************************
959 * Function : get_header_value
961 * Description : Get the value of a given header from a chained list
962 * of header lines or return NULL if no such header is
963 * present in the list.
966 * 1 : header_list = pointer to list
967 * 2 : header_name = string with name of header to look for.
968 * Trailing colon required, capitalization
971 * Returns : NULL if not found, else value of header
973 *********************************************************************/
974 char *get_header_value(const struct list *header_list, const char *header_name)
976 struct list_entry *cur_entry;
982 length = strlen(header_name);
984 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
988 if (!strncmpic(cur_entry->str, header_name, length))
991 * Found: return pointer to start of value
993 ret = cur_entry->str + length;
994 while (*ret && ijb_isspace(*ret)) ret++;
1008 /*********************************************************************
1010 * Function : scan_headers
1012 * Description : Scans headers, applies tags and updates action bits.
1015 * 1 : csp = Current client state (buffers, headers, etc...)
1017 * Returns : JB_ERR_OK
1019 *********************************************************************/
1020 static jb_err scan_headers(struct client_state *csp)
1022 struct list_entry *h; /* Header */
1023 jb_err err = JB_ERR_OK;
1025 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1027 /* Header crunch()ed in previous run? -> ignore */
1028 if (h->str == NULL) continue;
1029 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1030 err = header_tagger(csp, h->str);
1037 /*********************************************************************
1041 * Description : add, delete or modify lines in the HTTP header streams.
1042 * On entry, it receives a linked list of headers space
1043 * that was allocated dynamically (both the list nodes
1044 * and the header contents).
1046 * As a side effect it frees the space used by the original
1050 * 1 : csp = Current client state (buffers, headers, etc...)
1051 * 2 : filter_server_headers = Boolean to switch between
1052 * server and header filtering.
1054 * Returns : JB_ERR_OK in case off success, or
1055 * JB_ERR_MEMORY on out-of-memory error.
1057 *********************************************************************/
1058 jb_err sed(struct client_state *csp, int filter_server_headers)
1060 /* XXX: use more descriptive names. */
1061 struct list_entry *p;
1062 const struct parsers *v;
1063 const add_header_func_ptr *f;
1064 jb_err err = JB_ERR_OK;
1066 if (filter_server_headers)
1068 v = server_patterns;
1069 f = add_server_headers;
1073 v = client_patterns;
1074 f = add_client_headers;
1079 while ((err == JB_ERR_OK) && (v->str != NULL))
1081 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1083 /* Header crunch()ed in previous run? -> ignore */
1084 if (p->str == NULL) continue;
1086 /* Does the current parser handle this header? */
1087 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1088 (v->len == CHECK_EVERY_HEADER_REMAINING))
1090 err = v->parser(csp, &(p->str));
1096 /* place additional headers on the csp->headers list */
1097 while ((err == JB_ERR_OK) && (*f))
1107 /*********************************************************************
1109 * Function : update_server_headers
1111 * Description : Updates server headers after the body has been modified.
1114 * 1 : csp = Current client state (buffers, headers, etc...)
1116 * Returns : JB_ERR_OK in case off success, or
1117 * JB_ERR_MEMORY on out-of-memory error.
1119 *********************************************************************/
1120 jb_err update_server_headers(struct client_state *csp)
1122 jb_err err = JB_ERR_OK;
1124 static const struct parsers server_patterns_light[] = {
1125 { "Content-Length:", 15, server_adjust_content_length },
1126 { "Transfer-Encoding:", 18, server_transfer_coding },
1128 { "Content-Encoding:", 17, server_content_encoding },
1129 #endif /* def FEATURE_ZLIB */
1133 if (strncmpic(csp->http->cmd, "HEAD", 4))
1135 const struct parsers *v;
1136 struct list_entry *p;
1138 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1140 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1142 /* Header crunch()ed in previous run? -> ignore */
1143 if (p->str == NULL) continue;
1145 /* Does the current parser handle this header? */
1146 if (strncmpic(p->str, v->str, v->len) == 0)
1148 err = v->parser(csp, (char **)&(p->str));
1158 /*********************************************************************
1160 * Function : header_tagger
1162 * Description : Executes all text substitutions from applying
1163 * tag actions and saves the result as tag.
1165 * XXX: Shares enough code with filter_header() and
1166 * pcrs_filter_response() to warrant some helper functions.
1169 * 1 : csp = Current client state (buffers, headers, etc...)
1170 * 2 : header = Header that is used as tagger input
1172 * Returns : JB_ERR_OK on success and always succeeds
1174 *********************************************************************/
1175 static jb_err header_tagger(struct client_state *csp, char *header)
1177 int wanted_filter_type;
1178 int multi_action_index;
1182 struct file_list *fl;
1183 struct re_filterfile_spec *b;
1184 struct list_entry *tag_name;
1186 int found_filters = 0;
1187 const size_t header_length = strlen(header);
1189 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1191 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1192 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1196 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1197 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1200 /* Check if there are any filters */
1201 for (i = 0; i < MAX_AF_FILES; i++)
1214 if (0 == found_filters)
1216 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1217 "tagging enabled, but no taggers available.");
1221 for (i = 0; i < MAX_AF_FILES; i++)
1224 if ((NULL == fl) || (NULL == fl->f))
1227 * Either there are no filter files
1228 * left, or this filter file just
1229 * contains no valid filters.
1231 * Continue to be sure we don't miss
1232 * valid filter files that are chained
1233 * after empty or invalid ones.
1238 /* For all filters, */
1239 for (b = fl->f; b; b = b->next)
1241 if (b->type != wanted_filter_type)
1243 /* skip the ones we don't care about, */
1246 /* leaving only taggers that could apply, of which we use the ones, */
1247 for (tag_name = csp->action->multi[multi_action_index]->first;
1248 NULL != tag_name; tag_name = tag_name->next)
1250 /* that do apply, and */
1251 if (strcmp(b->name, tag_name->str) == 0)
1253 char *modified_tag = NULL;
1255 size_t size = header_length;
1256 pcrs_job *joblist = b->joblist;
1258 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1260 if (NULL == joblist)
1262 log_error(LOG_LEVEL_RE_FILTER,
1263 "Tagger %s has empty joblist. Nothing to do.", b->name);
1267 /* execute their pcrs_joblist on the header. */
1268 for (job = joblist; NULL != job; job = job->next)
1270 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1274 /* Success, continue with the modified version. */
1283 /* Tagger doesn't match */
1286 /* Regex failure, log it but continue anyway. */
1287 assert(NULL != header);
1288 log_error(LOG_LEVEL_ERROR,
1289 "Problems with tagger \'%s\' and header \'%s\': %s",
1290 b->name, *header, pcrs_strerror(hits));
1292 freez(modified_tag);
1296 if (b->dynamic) pcrs_free_joblist(joblist);
1298 /* If this tagger matched */
1304 * There is to technical limitation which makes
1305 * it impossible to use empty tags, but I assume
1306 * no one would do it intentionally.
1309 log_error(LOG_LEVEL_INFO,
1310 "Tagger \'%s\' created an empty tag. Ignored.",
1315 if (!list_contains_item(csp->tags, tag))
1317 if (JB_ERR_OK != enlist(csp->tags, tag))
1319 log_error(LOG_LEVEL_ERROR,
1320 "Insufficient memory to add tag \'%s\', "
1321 "based on tagger \'%s\' and header \'%s\'",
1322 tag, b->name, *header);
1326 char *action_message;
1328 * update the action bits right away, to make
1329 * tagging based on tags set by earlier taggers
1330 * of the same kind possible.
1332 if (update_action_bits_for_tag(csp, tag))
1334 action_message = "Action bits updated accordingly.";
1338 action_message = "No action bits update necessary.";
1341 log_error(LOG_LEVEL_HEADER,
1342 "Tagger \'%s\' added tag \'%s\'. %s",
1343 b->name, tag, action_message);
1348 /* XXX: Is this log-worthy? */
1349 log_error(LOG_LEVEL_HEADER,
1350 "Tagger \'%s\' didn't add tag \'%s\'. "
1351 "Tag already present", b->name, tag);
1354 } /* if the tagger matched */
1355 } /* if the tagger applies */
1356 } /* for every tagger that could apply */
1357 } /* for all filters */
1358 } /* for all filter files */
1363 /* here begins the family of parser functions that reformat header lines */
1365 /*********************************************************************
1367 * Function : filter_header
1369 * Description : Executes all text substitutions from all applying
1370 * +(server|client)-header-filter actions on the header.
1371 * Most of the code was copied from pcrs_filter_response,
1372 * including the rather short variable names
1375 * 1 : csp = Current client state (buffers, headers, etc...)
1376 * 2 : header = On input, pointer to header to modify.
1377 * On output, pointer to the modified header, or NULL
1378 * to remove the header. This function frees the
1379 * original string if necessary.
1381 * Returns : JB_ERR_OK on success and always succeeds
1383 *********************************************************************/
1384 static jb_err filter_header(struct client_state *csp, char **header)
1388 size_t size = strlen(*header);
1390 char *newheader = NULL;
1393 struct file_list *fl;
1394 struct re_filterfile_spec *b;
1395 struct list_entry *filtername;
1397 int i, found_filters = 0;
1398 int wanted_filter_type;
1399 int multi_action_index;
1401 if (csp->flags & CSP_FLAG_NO_FILTERING)
1406 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1408 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1409 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1413 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1414 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1418 * Need to check the set of re_filterfiles...
1420 for (i = 0; i < MAX_AF_FILES; i++)
1433 if (0 == found_filters)
1435 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1436 "header filtering enabled, but no matching filters available.");
1440 for (i = 0; i < MAX_AF_FILES; i++)
1443 if ((NULL == fl) || (NULL == fl->f))
1446 * Either there are no filter files
1447 * left, or this filter file just
1448 * contains no valid filters.
1450 * Continue to be sure we don't miss
1451 * valid filter files that are chained
1452 * after empty or invalid ones.
1457 * For all applying +filter actions, look if a filter by that
1458 * name exists and if yes, execute its pcrs_joblist on the
1461 for (b = fl->f; b; b = b->next)
1463 if (b->type != wanted_filter_type)
1465 /* Skip other filter types */
1469 for (filtername = csp->action->multi[multi_action_index]->first;
1470 filtername ; filtername = filtername->next)
1472 if (strcmp(b->name, filtername->str) == 0)
1474 int current_hits = 0;
1475 pcrs_job *joblist = b->joblist;
1477 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1479 if (NULL == joblist)
1481 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1485 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1486 *header, size, b->name);
1488 /* Apply all jobs from the joblist */
1489 for (job = joblist; NULL != job; job = job->next)
1491 matches = pcrs_execute(job, *header, size, &newheader, &size);
1494 current_hits += matches;
1495 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1497 *header = newheader;
1499 else if ( 0 == matches )
1501 /* Filter doesn't change header */
1507 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1508 *header, b->name, pcrs_strerror(matches));
1509 if (newheader != NULL)
1511 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1517 if (b->dynamic) pcrs_free_joblist(joblist);
1519 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1520 hits += current_hits;
1527 * Additionally checking for hits is important because if
1528 * the continue hack is triggered, server headers can
1529 * arrive empty to separate multiple heads from each other.
1531 if ((0 == size) && hits)
1533 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1541 /*********************************************************************
1543 * Function : server_connection
1545 * Description : Makes sure a proper "Connection:" header is
1546 * set and signals connection_header_adder to
1550 * 1 : csp = Current client state (buffers, headers, etc...)
1551 * 2 : header = On input, pointer to header to modify.
1552 * On output, pointer to the modified header, or NULL
1553 * to remove the header. This function frees the
1554 * original string if necessary.
1556 * Returns : JB_ERR_OK on success, or
1557 * JB_ERR_MEMORY on out-of-memory error.
1559 *********************************************************************/
1560 static jb_err server_connection(struct client_state *csp, char **header)
1562 if (!strcmpic(*header, "Connection: keep-alive"))
1564 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1565 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1567 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1570 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1572 log_error(LOG_LEVEL_HEADER,
1573 "Keeping the server header '%s' around.", *header);
1576 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1578 char *old_header = *header;
1580 *header = strdup("Connection: close");
1583 return JB_ERR_MEMORY;
1585 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1590 /* Signal server_connection_adder() to return early. */
1591 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1597 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1598 /*********************************************************************
1600 * Function : server_keep_alive
1602 * Description : Stores the servers keep alive timeout.
1605 * 1 : csp = Current client state (buffers, headers, etc...)
1606 * 2 : header = On input, pointer to header to modify.
1607 * On output, pointer to the modified header, or NULL
1608 * to remove the header. This function frees the
1609 * original string if necessary.
1611 * Returns : JB_ERR_OK.
1613 *********************************************************************/
1614 static jb_err server_keep_alive(struct client_state *csp, char **header)
1616 unsigned int keep_alive_timeout;
1617 const char *timeout_position = strstr(*header, "timeout=");
1619 if ((NULL == timeout_position)
1620 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1622 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1626 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1628 log_error(LOG_LEVEL_HEADER,
1629 "Reducing keep-alive timeout from %u to %u.",
1630 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1631 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1635 /* XXX: Is this log worthy? */
1636 log_error(LOG_LEVEL_HEADER,
1637 "Server keep-alive timeout is %u. Sticking with %u.",
1638 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1644 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1648 /*********************************************************************
1650 * Function : client_connection
1652 * Description : Makes sure a proper "Connection:" header is
1653 * set and signals connection_header_adder
1657 * 1 : csp = Current client state (buffers, headers, etc...)
1658 * 2 : header = On input, pointer to header to modify.
1659 * On output, pointer to the modified header, or NULL
1660 * to remove the header. This function frees the
1661 * original string if necessary.
1663 * Returns : JB_ERR_OK on success, or
1664 * JB_ERR_MEMORY on out-of-memory error.
1666 *********************************************************************/
1667 static jb_err client_connection(struct client_state *csp, char **header)
1669 const char *wanted_header = get_appropiate_connection_header(csp);
1671 if (strcmpic(*header, wanted_header))
1673 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1674 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1676 log_error(LOG_LEVEL_HEADER,
1677 "Keeping the client header '%s' around. "
1678 "The connection will not be kept alive.",
1682 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1684 char *old_header = *header;
1686 *header = strdup(wanted_header);
1689 return JB_ERR_MEMORY;
1691 log_error(LOG_LEVEL_HEADER,
1692 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1696 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1699 log_error(LOG_LEVEL_HEADER,
1700 "Keeping the client header '%s' around. "
1701 "The server connection will be kept alive if possible.",
1703 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1705 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1707 /* Signal client_connection_adder() to return early. */
1708 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1714 /*********************************************************************
1716 * Function : crumble
1718 * Description : This is called if a header matches a pattern to "crunch"
1721 * 1 : csp = Current client state (buffers, headers, etc...)
1722 * 2 : header = On input, pointer to header to modify.
1723 * On output, pointer to the modified header, or NULL
1724 * to remove the header. This function frees the
1725 * original string if necessary.
1727 * Returns : JB_ERR_OK on success, or
1728 * JB_ERR_MEMORY on out-of-memory error.
1730 *********************************************************************/
1731 static jb_err crumble(struct client_state *csp, char **header)
1734 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1740 /*********************************************************************
1742 * Function : crunch_server_header
1744 * Description : Crunch server header if it matches a string supplied by the
1745 * user. Called from `sed'.
1748 * 1 : csp = Current client state (buffers, headers, etc...)
1749 * 2 : header = On input, pointer to header to modify.
1750 * On output, pointer to the modified header, or NULL
1751 * to remove the header. This function frees the
1752 * original string if necessary.
1754 * Returns : JB_ERR_OK on success and always succeeds
1756 *********************************************************************/
1757 static jb_err crunch_server_header(struct client_state *csp, char **header)
1759 const char *crunch_pattern;
1761 /* Do we feel like crunching? */
1762 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1764 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1766 /* Is the current header the lucky one? */
1767 if (strstr(*header, crunch_pattern))
1769 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1778 /*********************************************************************
1780 * Function : server_content_type
1782 * Description : Set the content-type for filterable types (text/.*,
1783 * .*xml.*, javascript and image/gif) unless filtering has been
1784 * forbidden (CT_TABOO) while parsing earlier headers.
1785 * NOTE: Since text/plain is commonly used by web servers
1786 * for files whose correct type is unknown, we don't
1787 * set CT_TEXT for it.
1790 * 1 : csp = Current client state (buffers, headers, etc...)
1791 * 2 : header = On input, pointer to header to modify.
1792 * On output, pointer to the modified header, or NULL
1793 * to remove the header. This function frees the
1794 * original string if necessary.
1796 * Returns : JB_ERR_OK on success, or
1797 * JB_ERR_MEMORY on out-of-memory error.
1799 *********************************************************************/
1800 static jb_err server_content_type(struct client_state *csp, char **header)
1802 /* Remove header if it isn't the first Content-Type header */
1803 if ((csp->content_type & CT_DECLARED))
1806 * Another, slightly slower, way to see if
1807 * we already parsed another Content-Type header.
1809 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1811 log_error(LOG_LEVEL_ERROR,
1812 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1820 * Signal that the Content-Type has been set.
1822 csp->content_type |= CT_DECLARED;
1824 if (!(csp->content_type & CT_TABOO))
1827 * XXX: The assumption that text/plain is a sign of
1828 * binary data seems to be somewhat unreasonable nowadays
1829 * and should be dropped after 3.0.8 is out.
1831 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
1832 || strstr(*header, "xml")
1833 || strstr(*header, "application/x-javascript"))
1835 csp->content_type |= CT_TEXT;
1837 else if (strstr(*header, "image/gif"))
1839 csp->content_type |= CT_GIF;
1844 * Are we messing with the content type?
1846 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1849 * Make sure the user doesn't accidently
1850 * change the content type of binary documents.
1852 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
1855 *header = strdup("Content-Type: ");
1856 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1860 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1861 return JB_ERR_MEMORY;
1863 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1867 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
1868 "It doesn't look like a content type that should be filtered. "
1869 "Enable force-text-mode if you know what you're doing.", *header);
1877 /*********************************************************************
1879 * Function : server_transfer_coding
1881 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1882 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1883 * - Remove header if body was chunked but has been
1884 * de-chunked for filtering.
1887 * 1 : csp = Current client state (buffers, headers, etc...)
1888 * 2 : header = On input, pointer to header to modify.
1889 * On output, pointer to the modified header, or NULL
1890 * to remove the header. This function frees the
1891 * original string if necessary.
1893 * Returns : JB_ERR_OK on success, or
1894 * JB_ERR_MEMORY on out-of-memory error.
1896 *********************************************************************/
1897 static jb_err server_transfer_coding(struct client_state *csp, char **header)
1900 * Turn off pcrs and gif filtering if body compressed
1902 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1906 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1908 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1909 csp->http->cmd, *header);
1910 #endif /* def FEATURE_ZLIB */
1911 csp->content_type = CT_TABOO;
1915 * Raise flag if body chunked
1917 if (strstr(*header, "chunked"))
1919 csp->flags |= CSP_FLAG_CHUNKED;
1922 * If the body was modified, it has been de-chunked first
1923 * and the header must be removed.
1925 * FIXME: If there is more than one transfer encoding,
1926 * only the "chunked" part should be removed here.
1928 if (csp->flags & CSP_FLAG_MODIFIED)
1930 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1939 /*********************************************************************
1941 * Function : server_content_encoding
1943 * Description : This function is run twice for each request,
1944 * unless FEATURE_ZLIB and filtering are disabled.
1946 * The first run is used to check if the content
1947 * is compressed, if FEATURE_ZLIB is disabled
1948 * filtering is then disabled as well, if FEATURE_ZLIB
1949 * is enabled the content is marked for decompression.
1951 * The second run is used to remove the Content-Encoding
1952 * header if the decompression was successful.
1955 * 1 : csp = Current client state (buffers, headers, etc...)
1956 * 2 : header = On input, pointer to header to modify.
1957 * On output, pointer to the modified header, or NULL
1958 * to remove the header. This function frees the
1959 * original string if necessary.
1961 * Returns : JB_ERR_OK on success, or
1962 * JB_ERR_MEMORY on out-of-memory error.
1964 *********************************************************************/
1965 static jb_err server_content_encoding(struct client_state *csp, char **header)
1968 if ((csp->flags & CSP_FLAG_MODIFIED)
1969 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1972 * We successfully decompressed the content,
1973 * and have to clean the header now, so the
1974 * client no longer expects compressed data..
1976 * XXX: There is a difference between cleaning
1977 * and removing it completely.
1979 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1982 else if (strstr(*header, "gzip"))
1984 /* Mark for gzip decompression */
1985 csp->content_type |= CT_GZIP;
1987 else if (strstr(*header, "deflate"))
1989 /* Mark for zlib decompression */
1990 csp->content_type |= CT_DEFLATE;
1992 else if (strstr(*header, "compress"))
1995 * We can't decompress this; therefore we can't filter
1998 csp->content_type |= CT_TABOO;
2000 #else /* !defined(FEATURE_ZLIB) */
2001 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2004 * Body is compressed, turn off pcrs and gif filtering.
2006 csp->content_type |= CT_TABOO;
2009 * Log a warning if the user expects the content to be filtered.
2011 if ((csp->rlist != NULL) &&
2012 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2014 log_error(LOG_LEVEL_INFO,
2015 "Compressed content detected, content filtering disabled. "
2016 "Consider recompiling Privoxy with zlib support or "
2017 "enable the prevent-compression action.");
2020 #endif /* defined(FEATURE_ZLIB) */
2027 /*********************************************************************
2029 * Function : server_adjust_content_length
2031 * Description : Adjust Content-Length header if we modified
2035 * 1 : csp = Current client state (buffers, headers, etc...)
2036 * 2 : header = On input, pointer to header to modify.
2037 * On output, pointer to the modified header, or NULL
2038 * to remove the header. This function frees the
2039 * original string if necessary.
2041 * Returns : JB_ERR_OK on success, or
2042 * JB_ERR_MEMORY on out-of-memory error.
2044 *********************************************************************/
2045 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2047 const size_t max_header_length = 80;
2049 /* Regenerate header if the content was modified. */
2050 if (csp->flags & CSP_FLAG_MODIFIED)
2053 *header = (char *) zalloc(max_header_length);
2054 if (*header == NULL)
2056 return JB_ERR_MEMORY;
2059 snprintf(*header, max_header_length, "Content-Length: %d",
2060 (int)csp->content_length);
2061 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2062 (int)csp->content_length);
2069 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2070 /*********************************************************************
2072 * Function : server_save_content_length
2074 * Description : Save the Content-Length sent by the server.
2077 * 1 : csp = Current client state (buffers, headers, etc...)
2078 * 2 : header = On input, pointer to header to modify.
2079 * On output, pointer to the modified header, or NULL
2080 * to remove the header. This function frees the
2081 * original string if necessary.
2083 * Returns : JB_ERR_OK on success, or
2084 * JB_ERR_MEMORY on out-of-memory error.
2086 *********************************************************************/
2087 static jb_err server_save_content_length(struct client_state *csp, char **header)
2089 unsigned long long content_length = 0;
2091 assert(*(*header+14) == ':');
2093 if (1 != sscanf(*header+14, ": %llu", &content_length))
2095 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2100 csp->expected_content_length = content_length;
2101 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2106 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2109 /*********************************************************************
2111 * Function : server_content_md5
2113 * Description : Crumble any Content-MD5 headers if the document was
2114 * modified. FIXME: Should we re-compute instead?
2117 * 1 : csp = Current client state (buffers, headers, etc...)
2118 * 2 : header = On input, pointer to header to modify.
2119 * On output, pointer to the modified header, or NULL
2120 * to remove the header. This function frees the
2121 * original string if necessary.
2123 * Returns : JB_ERR_OK on success, or
2124 * JB_ERR_MEMORY on out-of-memory error.
2126 *********************************************************************/
2127 static jb_err server_content_md5(struct client_state *csp, char **header)
2129 if (csp->flags & CSP_FLAG_MODIFIED)
2131 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2139 /*********************************************************************
2141 * Function : server_content_disposition
2143 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2144 * Called from `sed'.
2147 * 1 : csp = Current client state (buffers, headers, etc...)
2148 * 2 : header = On input, pointer to header to modify.
2149 * On output, pointer to the modified header, or NULL
2150 * to remove the header. This function frees the
2151 * original string if necessary.
2153 * Returns : JB_ERR_OK on success, or
2154 * JB_ERR_MEMORY on out-of-memory error.
2156 *********************************************************************/
2157 static jb_err server_content_disposition(struct client_state *csp, char **header)
2162 * Are we messing with the Content-Disposition header?
2164 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2170 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2172 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2175 * Blocking content-disposition header
2177 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2184 * Replacing Content-Disposition header
2187 *header = strdup("Content-Disposition: ");
2188 string_append(header, newval);
2190 if (*header != NULL)
2192 log_error(LOG_LEVEL_HEADER,
2193 "Content-Disposition header crunched and replaced with: %s", *header);
2196 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2200 /*********************************************************************
2202 * Function : server_last_modified
2204 * Description : Changes Last-Modified header to the actual date
2205 * to help hide-if-modified-since.
2206 * Called from `sed'.
2209 * 1 : csp = Current client state (buffers, headers, etc...)
2210 * 2 : header = On input, pointer to header to modify.
2211 * On output, pointer to the modified header, or NULL
2212 * to remove the header. This function frees the
2213 * original string if necessary.
2215 * Returns : JB_ERR_OK on success, or
2216 * JB_ERR_MEMORY on out-of-memory error.
2218 *********************************************************************/
2219 static jb_err server_last_modified(struct client_state *csp, char **header)
2222 char buf[BUFFER_SIZE];
2225 #ifdef HAVE_GMTIME_R
2228 struct tm *timeptr = NULL;
2229 time_t now, last_modified;
2230 long int days, hours, minutes, seconds;
2233 * Are we messing with the Last-Modified header?
2235 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2241 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2243 if (0 == strcmpic(newval, "block") )
2246 * Blocking Last-Modified header. Useless but why not.
2248 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2252 else if (0 == strcmpic(newval, "reset-to-request-time"))
2255 * Setting Last-Modified Header to now.
2257 get_http_time(0, buf, sizeof(buf));
2259 *header = strdup("Last-Modified: ");
2260 string_append(header, buf);
2262 if (*header == NULL)
2264 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2268 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2271 else if (0 == strcmpic(newval, "randomize"))
2273 const char *header_time = *header + sizeof("Last-Modified:");
2275 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2277 #ifdef HAVE_GMTIME_R
2278 gmtime_r(&now, &gmt);
2279 #elif defined(MUTEX_LOCKS_AVAILABLE)
2280 privoxy_mutex_lock(&gmtime_mutex);
2282 privoxy_mutex_unlock(&gmtime_mutex);
2286 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2288 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2293 long int rtime = (long int)difftime(now, last_modified);
2296 const int negative_delta = (rtime < 0);
2301 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2303 rtime = pick_from_range(rtime);
2308 last_modified += rtime;
2309 #ifdef HAVE_GMTIME_R
2310 timeptr = gmtime_r(&last_modified, &gmt);
2311 #elif defined(MUTEX_LOCKS_AVAILABLE)
2312 privoxy_mutex_lock(&gmtime_mutex);
2313 timeptr = gmtime(&last_modified);
2314 privoxy_mutex_unlock(&gmtime_mutex);
2316 timeptr = gmtime(&last_modified);
2318 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2320 *header = strdup("Last-Modified: ");
2321 string_append(header, newheader);
2323 if (*header == NULL)
2325 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2326 return JB_ERR_MEMORY;
2329 days = rtime / (3600 * 24);
2330 hours = rtime / 3600 % 24;
2331 minutes = rtime / 60 % 60;
2332 seconds = rtime % 60;
2334 log_error(LOG_LEVEL_HEADER,
2335 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2336 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2337 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2341 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2350 /*********************************************************************
2352 * Function : client_accept_encoding
2354 * Description : Rewrite the client's Accept-Encoding header so that
2355 * if doesn't allow compression, if the action applies.
2356 * Note: For HTTP/1.0 the absence of the header is enough.
2359 * 1 : csp = Current client state (buffers, headers, etc...)
2360 * 2 : header = On input, pointer to header to modify.
2361 * On output, pointer to the modified header, or NULL
2362 * to remove the header. This function frees the
2363 * original string if necessary.
2365 * Returns : JB_ERR_OK on success, or
2366 * JB_ERR_MEMORY on out-of-memory error.
2368 *********************************************************************/
2369 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2371 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2373 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2377 /* Temporarily disable the correct behaviour to
2378 * work around a PHP bug.
2380 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2382 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2383 * if (*header == NULL)
2385 * return JB_ERR_MEMORY;
2396 /*********************************************************************
2398 * Function : client_te
2400 * Description : Rewrite the client's TE header so that
2401 * if doesn't allow compression, if the action applies.
2404 * 1 : csp = Current client state (buffers, headers, etc...)
2405 * 2 : header = On input, pointer to header to modify.
2406 * On output, pointer to the modified header, or NULL
2407 * to remove the header. This function frees the
2408 * original string if necessary.
2410 * Returns : JB_ERR_OK on success, or
2411 * JB_ERR_MEMORY on out-of-memory error.
2413 *********************************************************************/
2414 static jb_err client_te(struct client_state *csp, char **header)
2416 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2419 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2426 /*********************************************************************
2428 * Function : client_referrer
2430 * Description : Handle the "referer" config setting properly.
2431 * Called from `sed'.
2434 * 1 : csp = Current client state (buffers, headers, etc...)
2435 * 2 : header = On input, pointer to header to modify.
2436 * On output, pointer to the modified header, or NULL
2437 * to remove the header. This function frees the
2438 * original string if necessary.
2440 * Returns : JB_ERR_OK on success, or
2441 * JB_ERR_MEMORY on out-of-memory error.
2443 *********************************************************************/
2444 static jb_err client_referrer(struct client_state *csp, char **header)
2446 const char *parameter;
2447 /* booleans for parameters we have to check multiple times */
2448 int parameter_conditional_block;
2449 int parameter_conditional_forge;
2451 #ifdef FEATURE_FORCE_LOAD
2453 * Since the referrer can include the prefix even
2454 * if the request itself is non-forced, we must
2455 * clean it unconditionally.
2457 * XXX: strclean is too broad
2459 strclean(*header, FORCE_PREFIX);
2460 #endif /* def FEATURE_FORCE_LOAD */
2462 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2464 /* Nothing left to do */
2468 parameter = csp->action->string[ACTION_STRING_REFERER];
2469 assert(parameter != NULL);
2470 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2471 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2473 if (!parameter_conditional_block && !parameter_conditional_forge)
2476 * As conditional-block and conditional-forge are the only
2477 * parameters that rely on the original referrer, we can
2478 * remove it now for all the others.
2483 if (0 == strcmpic(parameter, "block"))
2485 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2488 else if (parameter_conditional_block || parameter_conditional_forge)
2490 return handle_conditional_hide_referrer_parameter(header,
2491 csp->http->hostport, parameter_conditional_block);
2493 else if (0 == strcmpic(parameter, "forge"))
2495 return create_forged_referrer(header, csp->http->hostport);
2499 /* interpret parameter as user-supplied referer to fake */
2500 return create_fake_referrer(header, parameter);
2505 /*********************************************************************
2507 * Function : client_accept_language
2509 * Description : Handle the "Accept-Language" config setting properly.
2510 * Called from `sed'.
2513 * 1 : csp = Current client state (buffers, headers, etc...)
2514 * 2 : header = On input, pointer to header to modify.
2515 * On output, pointer to the modified header, or NULL
2516 * to remove the header. This function frees the
2517 * original string if necessary.
2519 * Returns : JB_ERR_OK on success, or
2520 * JB_ERR_MEMORY on out-of-memory error.
2522 *********************************************************************/
2523 static jb_err client_accept_language(struct client_state *csp, char **header)
2528 * Are we messing with the Accept-Language?
2530 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2532 /*I don't think so*/
2536 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2538 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2541 * Blocking Accept-Language header
2543 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2550 * Replacing Accept-Language header
2553 *header = strdup("Accept-Language: ");
2554 string_append(header, newval);
2556 if (*header == NULL)
2558 log_error(LOG_LEVEL_ERROR,
2559 "Insufficient memory. Accept-Language header crunched without replacement.");
2563 log_error(LOG_LEVEL_HEADER,
2564 "Accept-Language header crunched and replaced with: %s", *header);
2567 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2571 /*********************************************************************
2573 * Function : crunch_client_header
2575 * Description : Crunch client header if it matches a string supplied by the
2576 * user. Called from `sed'.
2579 * 1 : csp = Current client state (buffers, headers, etc...)
2580 * 2 : header = On input, pointer to header to modify.
2581 * On output, pointer to the modified header, or NULL
2582 * to remove the header. This function frees the
2583 * original string if necessary.
2585 * Returns : JB_ERR_OK on success and always succeeds
2587 *********************************************************************/
2588 static jb_err crunch_client_header(struct client_state *csp, char **header)
2590 const char *crunch_pattern;
2592 /* Do we feel like crunching? */
2593 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2595 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2597 /* Is the current header the lucky one? */
2598 if (strstr(*header, crunch_pattern))
2600 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2608 /*********************************************************************
2610 * Function : client_uagent
2612 * Description : Handle the "user-agent" config setting properly
2613 * and remember its original value to enable browser
2614 * bug workarounds. Called from `sed'.
2617 * 1 : csp = Current client state (buffers, headers, etc...)
2618 * 2 : header = On input, pointer to header to modify.
2619 * On output, pointer to the modified header, or NULL
2620 * to remove the header. This function frees the
2621 * original string if necessary.
2623 * Returns : JB_ERR_OK on success, or
2624 * JB_ERR_MEMORY on out-of-memory error.
2626 *********************************************************************/
2627 static jb_err client_uagent(struct client_state *csp, char **header)
2631 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2636 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2643 *header = strdup("User-Agent: ");
2644 string_append(header, newval);
2646 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2648 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2652 /*********************************************************************
2654 * Function : client_ua
2656 * Description : Handle "ua-" headers properly. Called from `sed'.
2659 * 1 : csp = Current client state (buffers, headers, etc...)
2660 * 2 : header = On input, pointer to header to modify.
2661 * On output, pointer to the modified header, or NULL
2662 * to remove the header. This function frees the
2663 * original string if necessary.
2665 * Returns : JB_ERR_OK on success, or
2666 * JB_ERR_MEMORY on out-of-memory error.
2668 *********************************************************************/
2669 static jb_err client_ua(struct client_state *csp, char **header)
2671 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2673 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2681 /*********************************************************************
2683 * Function : client_from
2685 * Description : Handle the "from" config setting properly.
2686 * Called from `sed'.
2689 * 1 : csp = Current client state (buffers, headers, etc...)
2690 * 2 : header = On input, pointer to header to modify.
2691 * On output, pointer to the modified header, or NULL
2692 * to remove the header. This function frees the
2693 * original string if necessary.
2695 * Returns : JB_ERR_OK on success, or
2696 * JB_ERR_MEMORY on out-of-memory error.
2698 *********************************************************************/
2699 static jb_err client_from(struct client_state *csp, char **header)
2703 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2710 newval = csp->action->string[ACTION_STRING_FROM];
2713 * Are we blocking the e-mail address?
2715 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2717 log_error(LOG_LEVEL_HEADER, "crunched From!");
2721 log_error(LOG_LEVEL_HEADER, " modified");
2723 *header = strdup("From: ");
2724 string_append(header, newval);
2726 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2730 /*********************************************************************
2732 * Function : client_send_cookie
2734 * Description : Crunches the "cookie" header if necessary.
2735 * Called from `sed'.
2737 * XXX: Stupid name, doesn't send squat.
2740 * 1 : csp = Current client state (buffers, headers, etc...)
2741 * 2 : header = On input, pointer to header to modify.
2742 * On output, pointer to the modified header, or NULL
2743 * to remove the header. This function frees the
2744 * original string if necessary.
2746 * Returns : JB_ERR_OK on success, or
2747 * JB_ERR_MEMORY on out-of-memory error.
2749 *********************************************************************/
2750 static jb_err client_send_cookie(struct client_state *csp, char **header)
2752 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2754 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2762 /*********************************************************************
2764 * Function : client_x_forwarded
2766 * Description : Handle the "x-forwarded-for" config setting properly,
2767 * also used in the add_client_headers list. Called from `sed'.
2770 * 1 : csp = Current client state (buffers, headers, etc...)
2771 * 2 : header = On input, pointer to header to modify.
2772 * On output, pointer to the modified header, or NULL
2773 * to remove the header. This function frees the
2774 * original string if necessary.
2776 * Returns : JB_ERR_OK on success, or
2777 * JB_ERR_MEMORY on out-of-memory error.
2779 *********************************************************************/
2780 jb_err client_x_forwarded(struct client_state *csp, char **header)
2782 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
2784 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
2786 if (0 == strcmpic(parameter, "block"))
2789 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2791 else if (0 == strcmpic(parameter, "add"))
2793 string_append(header, ", ");
2794 string_append(header, csp->ip_addr_str);
2796 if (*header == NULL)
2798 return JB_ERR_MEMORY;
2800 log_error(LOG_LEVEL_HEADER,
2801 "Appended client IP address to %s", *header);
2802 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
2806 log_error(LOG_LEVEL_FATAL,
2807 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
2815 /*********************************************************************
2817 * Function : client_max_forwards
2819 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2820 * from the value of the Max-Forwards header field.
2823 * 1 : csp = Current client state (buffers, headers, etc...)
2824 * 2 : header = On input, pointer to header to modify.
2825 * On output, pointer to the modified header, or NULL
2826 * to remove the header. This function frees the
2827 * original string if necessary.
2829 * Returns : JB_ERR_OK on success, or
2830 * JB_ERR_MEMORY on out-of-memory error.
2832 *********************************************************************/
2833 static jb_err client_max_forwards(struct client_state *csp, char **header)
2837 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2838 (0 == strcmpic(csp->http->gpc, "options")))
2840 assert(*(*header+12) == ':');
2841 if (1 == sscanf(*header+12, ": %d", &max_forwards))
2843 if (max_forwards > 0)
2845 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
2846 log_error(LOG_LEVEL_HEADER,
2847 "Max-Forwards value for %s request reduced to %d.",
2848 csp->http->gpc, max_forwards);
2850 else if (max_forwards < 0)
2852 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2858 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2867 /*********************************************************************
2869 * Function : client_host
2871 * Description : If the request URI did not contain host and
2872 * port information, parse and evaluate the Host
2875 * Also, kill ill-formed HOST: headers as sent by
2876 * Apple's iTunes software when used with a proxy.
2879 * 1 : csp = Current client state (buffers, headers, etc...)
2880 * 2 : header = On input, pointer to header to modify.
2881 * On output, pointer to the modified header, or NULL
2882 * to remove the header. This function frees the
2883 * original string if necessary.
2885 * Returns : JB_ERR_OK on success, or
2886 * JB_ERR_MEMORY on out-of-memory error.
2888 *********************************************************************/
2889 static jb_err client_host(struct client_state *csp, char **header)
2894 * If the header field name is all upper-case, chances are that it's
2895 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2896 * not a problem -- they are regenerated later.
2898 if ((*header)[1] == 'O')
2900 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2905 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2906 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2909 if (NULL == (p = strdup((*header)+6)))
2911 return JB_ERR_MEMORY;
2914 if (NULL == (q = strdup(p)))
2917 return JB_ERR_MEMORY;
2920 freez(csp->http->hostport);
2921 csp->http->hostport = p;
2922 freez(csp->http->host);
2923 csp->http->host = q;
2924 q = strchr(csp->http->host, ':');
2927 /* Terminate hostname and evaluate port string */
2929 csp->http->port = atoi(q);
2933 csp->http->port = csp->http->ssl ? 443 : 80;
2936 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2937 csp->http->hostport, csp->http->host, csp->http->port);
2940 /* Signal client_host_adder() to return right away */
2941 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
2947 /*********************************************************************
2949 * Function : client_if_modified_since
2951 * Description : Remove or modify the If-Modified-Since header.
2954 * 1 : csp = Current client state (buffers, headers, etc...)
2955 * 2 : header = On input, pointer to header to modify.
2956 * On output, pointer to the modified header, or NULL
2957 * to remove the header. This function frees the
2958 * original string if necessary.
2960 * Returns : JB_ERR_OK on success, or
2961 * JB_ERR_MEMORY on out-of-memory error.
2963 *********************************************************************/
2964 static jb_err client_if_modified_since(struct client_state *csp, char **header)
2967 #ifdef HAVE_GMTIME_R
2970 struct tm *timeptr = NULL;
2973 long int hours, minutes, seconds;
2976 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2979 * The client got an error message because of a temporary problem,
2980 * the problem is gone and the client now tries to revalidate our
2981 * error message on the real server. The revalidation would always
2982 * end with the transmission of the whole document and there is
2983 * no need to expose the bogus If-Modified-Since header.
2985 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2988 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2990 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2992 if ((0 == strcmpic(newval, "block")))
2994 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2997 else /* add random value */
2999 const char *header_time = *header + sizeof("If-Modified-Since:");
3001 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3003 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3008 long int rtime = strtol(newval, &endptr, 0);
3009 const int negative_range = (rtime < 0);
3013 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3014 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3020 rtime = pick_from_range(rtime);
3024 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3027 tm += rtime * (negative_range ? -1 : 1);
3028 #ifdef HAVE_GMTIME_R
3029 timeptr = gmtime_r(&tm, &gmt);
3030 #elif defined(MUTEX_LOCKS_AVAILABLE)
3031 privoxy_mutex_lock(&gmtime_mutex);
3032 timeptr = gmtime(&tm);
3033 privoxy_mutex_unlock(&gmtime_mutex);
3035 timeptr = gmtime(&tm);
3037 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3040 *header = strdup("If-Modified-Since: ");
3041 string_append(header, newheader);
3043 if (*header == NULL)
3045 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3046 return JB_ERR_MEMORY;
3049 hours = rtime / 3600;
3050 minutes = rtime / 60 % 60;
3051 seconds = rtime % 60;
3053 log_error(LOG_LEVEL_HEADER,
3054 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3055 *header, (negative_range) ? "subtracted" : "added", hours,
3056 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3057 seconds, (seconds == 1) ? ")" : "s)");
3066 /*********************************************************************
3068 * Function : client_if_none_match
3070 * Description : Remove the If-None-Match header.
3073 * 1 : csp = Current client state (buffers, headers, etc...)
3074 * 2 : header = On input, pointer to header to modify.
3075 * On output, pointer to the modified header, or NULL
3076 * to remove the header. This function frees the
3077 * original string if necessary.
3079 * Returns : JB_ERR_OK on success, or
3080 * JB_ERR_MEMORY on out-of-memory error.
3082 *********************************************************************/
3083 static jb_err client_if_none_match(struct client_state *csp, char **header)
3085 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3087 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3095 /*********************************************************************
3097 * Function : client_x_filter
3099 * Description : Disables filtering if the client set "X-Filter: No".
3100 * Called from `sed'.
3103 * 1 : csp = Current client state (buffers, headers, etc...)
3104 * 2 : header = On input, pointer to header to modify.
3105 * On output, pointer to the modified header, or NULL
3106 * to remove the header. This function frees the
3107 * original string if necessary.
3109 * Returns : JB_ERR_OK on success
3111 *********************************************************************/
3112 jb_err client_x_filter(struct client_state *csp, char **header)
3114 if ( 0 == strcmpic(*header, "X-Filter: No"))
3116 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3118 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3122 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3124 log_error(LOG_LEVEL_HEADER,
3125 "force-text-mode overruled the client's request to fetch without filtering!");
3129 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3130 csp->flags |= CSP_FLAG_NO_FILTERING;
3131 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3133 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3141 /*********************************************************************
3143 * Function : client_range
3145 * Description : Removes Range, Request-Range and If-Range headers if
3146 * content filtering is enabled. If the client's version
3147 * of the document has been altered by Privoxy, the server
3148 * could interpret the range differently than the client
3149 * intended in which case the user could end up with
3150 * corrupted content.
3153 * 1 : csp = Current client state (buffers, headers, etc...)
3154 * 2 : header = On input, pointer to header to modify.
3155 * On output, pointer to the modified header, or NULL
3156 * to remove the header. This function frees the
3157 * original string if necessary.
3159 * Returns : JB_ERR_OK
3161 *********************************************************************/
3162 static jb_err client_range(struct client_state *csp, char **header)
3164 if (content_filters_enabled(csp->action))
3166 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3167 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3174 /* the following functions add headers directly to the header list */
3176 /*********************************************************************
3178 * Function : client_host_adder
3180 * Description : Adds the Host: header field if it is missing.
3181 * Called from `sed'.
3184 * 1 : csp = Current client state (buffers, headers, etc...)
3186 * Returns : JB_ERR_OK on success, or
3187 * JB_ERR_MEMORY on out-of-memory error.
3189 *********************************************************************/
3190 static jb_err client_host_adder(struct client_state *csp)
3195 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3197 /* Header already set by the client, nothing to do. */
3201 if ( !csp->http->hostport || !*(csp->http->hostport))
3203 /* XXX: When does this happen and why is it OK? */
3204 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3209 * remove 'user:pass@' from 'proto://user:pass@host'
3211 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3217 p = csp->http->hostport;
3220 /* XXX: Just add it, we already made sure that it will be unique */
3221 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3222 err = enlist_unique_header(csp->headers, "Host", p);
3229 /*********************************************************************
3231 * Function : client_accept_encoding_adder
3233 * Description : Add an Accept-Encoding header to the client's request
3234 * that disables compression if the action applies, and
3235 * the header is not already there. Called from `sed'.
3236 * Note: For HTTP/1.0, the absence of the header is enough.
3239 * 1 : csp = Current client state (buffers, headers, etc...)
3241 * Returns : JB_ERR_OK on success, or
3242 * JB_ERR_MEMORY on out-of-memory error.
3244 *********************************************************************/
3245 static jb_err client_accept_encoding_adder(struct client_state *csp)
3247 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3248 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3250 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3258 /*********************************************************************
3260 * Function : client_xtra_adder
3262 * Description : Used in the add_client_headers list. Called from `sed'.
3265 * 1 : csp = Current client state (buffers, headers, etc...)
3267 * Returns : JB_ERR_OK on success, or
3268 * JB_ERR_MEMORY on out-of-memory error.
3270 *********************************************************************/
3271 static jb_err client_xtra_adder(struct client_state *csp)
3273 struct list_entry *lst;
3276 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3277 lst ; lst = lst->next)
3279 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3280 err = enlist(csp->headers, lst->str);
3292 /*********************************************************************
3294 * Function : client_x_forwarded_for_adder
3296 * Description : Used in the add_client_headers list. Called from `sed'.
3299 * 1 : csp = Current client state (buffers, headers, etc...)
3301 * Returns : JB_ERR_OK on success, or
3302 * JB_ERR_MEMORY on out-of-memory error.
3304 *********************************************************************/
3305 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3307 char *header = NULL;
3310 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3311 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3312 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3315 * If we aren't adding X-Forwarded-For headers,
3316 * or we already appended an existing X-Forwarded-For
3317 * header, there's nothing left to do here.
3322 header = strdup("X-Forwarded-For: ");
3323 string_append(&header, csp->ip_addr_str);
3327 return JB_ERR_MEMORY;
3330 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3331 err = enlist(csp->headers, header);
3338 /*********************************************************************
3340 * Function : server_connection_adder
3342 * Description : Adds an appropiate "Connection:" header to csp->headers
3343 * unless the header was already present. Called from `sed'.
3346 * 1 : csp = Current client state (buffers, headers, etc...)
3348 * Returns : JB_ERR_OK on success, or
3349 * JB_ERR_MEMORY on out-of-memory error.
3351 *********************************************************************/
3352 static jb_err server_connection_adder(struct client_state *csp)
3354 const unsigned int flags = csp->flags;
3355 const char *response_status_line = csp->headers->first->str;
3356 const char *wanted_header = get_appropiate_connection_header(csp);
3358 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3359 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3365 * XXX: if we downgraded the response, this check will fail.
3367 if ((csp->config->feature_flags &
3368 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3369 && (NULL != response_status_line)
3370 && !strncmpic(response_status_line, "HTTP/1.1", 8))
3372 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3373 "without Connection header implies keep-alive.");
3374 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3377 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3379 return enlist(csp->headers, wanted_header);
3383 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3384 /*********************************************************************
3386 * Function : server_proxy_connection_adder
3388 * Description : Adds a "Proxy-Connection: keep-alive" header to
3389 * csp->headers if the client asked for keep-alive.
3390 * XXX: We should reuse existant ones.
3393 * 1 : csp = Current client state (buffers, headers, etc...)
3395 * Returns : JB_ERR_OK on success, or
3396 * JB_ERR_MEMORY on out-of-memory error.
3398 *********************************************************************/
3399 static jb_err server_proxy_connection_adder(struct client_state *csp)
3401 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3402 jb_err err = JB_ERR_OK;
3404 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3406 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3407 err = enlist(csp->headers, proxy_connection_header);
3412 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3415 /*********************************************************************
3417 * Function : client_connection_header_adder
3419 * Description : Adds a proper "Connection:" header to csp->headers
3420 * unless the header was already present. Called from `sed'.
3423 * 1 : csp = Current client state (buffers, headers, etc...)
3425 * Returns : JB_ERR_OK on success, or
3426 * JB_ERR_MEMORY on out-of-memory error.
3428 *********************************************************************/
3429 static jb_err client_connection_header_adder(struct client_state *csp)
3431 const char *wanted_header = get_appropiate_connection_header(csp);
3433 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3434 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3439 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3440 && (csp->http->ssl == 0))
3442 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3445 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3447 return enlist(csp->headers, wanted_header);
3451 /*********************************************************************
3453 * Function : server_http
3455 * Description : - Save the HTTP Status into csp->http->status
3456 * - Set CT_TABOO to prevent filtering if the answer
3457 * is a partial range (HTTP status 206)
3458 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3462 * 1 : csp = Current client state (buffers, headers, etc...)
3463 * 2 : header = On input, pointer to header to modify.
3464 * On output, pointer to the modified header, or NULL
3465 * to remove the header. This function frees the
3466 * original string if necessary.
3468 * Returns : JB_ERR_OK on success, or
3469 * JB_ERR_MEMORY on out-of-memory error.
3471 *********************************************************************/
3472 static jb_err server_http(struct client_state *csp, char **header)
3474 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3475 if (csp->http->status == 206)
3477 csp->content_type = CT_TABOO;
3480 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3482 /* XXX: Should we do a real validity check here? */
3483 if (strlen(*header) > 8)
3486 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3491 * XXX: Should we block the request or
3492 * enlist a valid status code line here?
3494 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3495 "Downgrading to HTTP/1.0 impossible.");
3503 /*********************************************************************
3505 * Function : server_set_cookie
3507 * Description : Handle the server "cookie" header properly.
3508 * Log cookie to the jar file. Then "crunch",
3509 * accept or rewrite it to a session cookie.
3510 * Called from `sed'.
3512 * TODO: Allow the user to specify a new expiration
3513 * time to cause the cookie to expire even before the
3514 * browser is closed.
3517 * 1 : csp = Current client state (buffers, headers, etc...)
3518 * 2 : header = On input, pointer to header to modify.
3519 * On output, pointer to the modified header, or NULL
3520 * to remove the header. This function frees the
3521 * original string if necessary.
3523 * Returns : JB_ERR_OK on success, or
3524 * JB_ERR_MEMORY on out-of-memory error.
3526 *********************************************************************/
3527 static jb_err server_set_cookie(struct client_state *csp, char **header)
3534 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3536 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3539 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3541 /* Flag whether or not to log a message */
3544 /* A variable to store the tag we're working on */
3547 /* Skip "Set-Cookie:" (11 characters) in header */
3548 cur_tag = *header + 11;
3550 /* skip whitespace between "Set-Cookie:" and value */
3551 while (*cur_tag && ijb_isspace(*cur_tag))
3556 /* Loop through each tag in the cookie */
3560 char *next_tag = strchr(cur_tag, ';');
3561 if (next_tag != NULL)
3563 /* Skip the ';' character itself */
3566 /* skip whitespace ";" and start of tag */
3567 while (*next_tag && ijb_isspace(*next_tag))
3574 /* "Next tag" is the end of the string */
3575 next_tag = cur_tag + strlen(cur_tag);
3579 * Check the expiration date to see
3580 * if the cookie is still valid, if yes,
3581 * rewrite it to a session cookie.
3583 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3585 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3587 /* Did we detect the date properly? */
3588 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3591 * Nope, treat it as if it was still valid.
3593 * XXX: Should we remove the whole cookie instead?
3595 log_error(LOG_LEVEL_ERROR,
3596 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3597 string_move(cur_tag, next_tag);
3603 * Yes. Check if the cookie is still valid.
3605 * If the cookie is already expired it's probably
3606 * a delete cookie and even if it isn't, the browser
3607 * will discard it anyway.
3611 * XXX: timegm() isn't available on some AmigaOS
3612 * versions and our replacement doesn't work.
3614 * Our options are to either:
3616 * - disable session-cookies-only completely if timegm
3619 * - to simply remove all expired tags, like it has
3620 * been done until Privoxy 3.0.6 and to live with
3621 * the consequence that it can cause login/logout
3622 * problems on servers that don't validate their
3623 * input properly, or
3625 * - to replace it with mktime in which
3626 * case there is a slight chance of valid cookies
3627 * passing as already expired.
3629 * This is the way it's currently done and it's not
3630 * as bad as it sounds. If the missing GMT offset is
3631 * enough to change the result of the expiration check
3632 * the cookie will be only valid for a few hours
3633 * anyway, which in many cases will be shorter
3634 * than a browser session.
3636 if (cookie_time - now < 0)
3638 log_error(LOG_LEVEL_HEADER,
3639 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3640 /* Just in case some clown sets more then one expiration date */
3646 * Still valid, delete expiration date by copying
3647 * the rest of the string over it.
3649 string_move(cur_tag, next_tag);
3651 /* That changed the header, need to issue a log message */
3655 * Note that the next tag has now been moved to *cur_tag,
3656 * so we do not need to update the cur_tag pointer.
3664 /* Move on to next cookie tag */
3671 assert(NULL != *header);
3672 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3681 #ifdef FEATURE_FORCE_LOAD
3682 /*********************************************************************
3684 * Function : strclean
3686 * Description : In-Situ-Eliminate all occurances of substring in
3690 * 1 : string = string to clean
3691 * 2 : substring = substring to eliminate
3693 * Returns : Number of eliminations
3695 *********************************************************************/
3696 int strclean(char *string, const char *substring)
3702 len = strlen(substring);
3704 while((pos = strstr(string, substring)) != NULL)
3711 while (*p++ != '\0');
3718 #endif /* def FEATURE_FORCE_LOAD */
3721 /*********************************************************************
3723 * Function : parse_header_time
3725 * Description : Parses time formats used in HTTP header strings
3726 * to get the numerical respresentation.
3729 * 1 : header_time = HTTP header time as string.
3730 * 2 : result = storage for header_time in seconds
3732 * Returns : JB_ERR_OK if the time format was recognized, or
3733 * JB_ERR_PARSE otherwise.
3735 *********************************************************************/
3736 static jb_err parse_header_time(const char *header_time, time_t *result)
3741 * Zero out gmt to prevent time zone offsets.
3743 * While this is only necessary on some platforms
3744 * (mingw32 for example), I don't know how to
3745 * detect these automatically and doing it everywhere
3748 memset(&gmt, 0, sizeof(gmt));
3750 /* Tue, 02 Jun 2037 20:00:00 */
3751 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3752 /* Tue, 02-Jun-2037 20:00:00 */
3753 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3754 /* Tue, 02-Jun-37 20:00:00 */
3755 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3756 /* Tuesday, 02-Jun-2037 20:00:00 */
3757 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3758 /* Tuesday Jun 02 20:00:00 2037 */
3759 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3761 return JB_ERR_PARSE;
3764 *result = timegm(&gmt);
3771 /*********************************************************************
3773 * Function : get_destination_from_headers
3775 * Description : Parse the "Host:" header to get the request's destination.
3776 * Only needed if the client's request was forcefully
3777 * redirected into Privoxy.
3779 * Code mainly copied from client_host() which is currently
3780 * run too late for this purpose.
3783 * 1 : headers = List of headers (one of them hopefully being
3784 * the "Host:" header)
3785 * 2 : http = storage for the result (host, port and hostport).
3787 * Returns : JB_ERR_MEMORY in case of memory problems,
3788 * JB_ERR_PARSE if the host header couldn't be found,
3789 * JB_ERR_OK otherwise.
3791 *********************************************************************/
3792 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3798 host = get_header_value(headers, "Host:");
3802 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3803 return JB_ERR_PARSE;
3806 if (NULL == (p = strdup((host))))
3808 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3809 return JB_ERR_MEMORY;
3812 if (NULL == (q = strdup(p)))
3815 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3816 return JB_ERR_MEMORY;
3819 freez(http->hostport);
3823 q = strchr(http->host, ':');
3826 /* Terminate hostname and evaluate port string */
3828 http->port = atoi(q);
3832 http->port = http->ssl ? 443 : 80;
3835 /* Rebuild request URL */
3837 http->url = strdup(http->ssl ? "https://" : "http://");
3838 string_append(&http->url, http->hostport);
3839 string_append(&http->url, http->path);
3840 if (http->url == NULL)
3842 return JB_ERR_MEMORY;
3845 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
3853 /*********************************************************************
3855 * Function : create_forged_referrer
3857 * Description : Helper for client_referrer to forge a referer as
3858 * 'http://[hostname:port/' to fool stupid
3859 * checks for in-site links
3862 * 1 : header = Pointer to header pointer
3863 * 2 : hostport = Host and optionally port as string
3865 * Returns : JB_ERR_OK in case of success, or
3866 * JB_ERR_MEMORY in case of memory problems.
3868 *********************************************************************/
3869 static jb_err create_forged_referrer(char **header, const char *hostport)
3871 assert(NULL == *header);
3873 *header = strdup("Referer: http://");
3874 string_append(header, hostport);
3875 string_append(header, "/");
3877 if (NULL == *header)
3879 return JB_ERR_MEMORY;
3882 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
3889 /*********************************************************************
3891 * Function : create_fake_referrer
3893 * Description : Helper for client_referrer to create a fake referrer
3894 * based on a string supplied by the user.
3897 * 1 : header = Pointer to header pointer
3898 * 2 : hosthost = Referrer to fake
3900 * Returns : JB_ERR_OK in case of success, or
3901 * JB_ERR_MEMORY in case of memory problems.
3903 *********************************************************************/
3904 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
3906 assert(NULL == *header);
3908 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
3910 log_error(LOG_LEVEL_HEADER,
3911 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
3913 *header = strdup("Referer: ");
3914 string_append(header, fake_referrer);
3916 if (NULL == *header)
3918 return JB_ERR_MEMORY;
3921 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
3928 /*********************************************************************
3930 * Function : handle_conditional_hide_referrer_parameter
3932 * Description : Helper for client_referrer to crunch or forge
3933 * the referrer header if the host has changed.
3936 * 1 : header = Pointer to header pointer
3937 * 2 : host = The target host (may include the port)
3938 * 3 : parameter_conditional_block = Boolean to signal
3939 * if we're in conditional-block mode. If not set,
3940 * we're in conditional-forge mode.
3942 * Returns : JB_ERR_OK in case of success, or
3943 * JB_ERR_MEMORY in case of memory problems.
3945 *********************************************************************/
3946 static jb_err handle_conditional_hide_referrer_parameter(char **header,
3947 const char *host, const int parameter_conditional_block)
3949 char *referer = strdup(*header);
3950 const size_t hostlenght = strlen(host);
3951 const char *referer_url = NULL;
3953 if (NULL == referer)
3956 return JB_ERR_MEMORY;
3959 /* referer begins with 'Referer: http[s]://' */
3960 if ((hostlenght+17) < strlen(referer))
3963 * Shorten referer to make sure the referer is blocked
3964 * if www.example.org/www.example.com-shall-see-the-referer/
3965 * links to www.example.com/
3967 referer[hostlenght+17] = '\0';
3969 referer_url = strstr(referer, "http://");
3970 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
3972 /* Host has changed, Referer is invalid or a https URL. */
3973 if (parameter_conditional_block)
3975 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
3982 return create_forged_referrer(header, host);
3992 /*********************************************************************
3994 * Function : get_appropiate_connection_header
3996 * Description : Returns an appropiate Connection header
3997 * depending on whether or not we try to keep
3998 * the connection to the server alive.
4001 * 1 : csp = Current client state (buffers, headers, etc...)
4003 * Returns : Pointer to statically allocated header buffer.
4005 *********************************************************************/
4006 static const char *get_appropiate_connection_header(const struct client_state *csp)
4008 static const char connection_keep_alive[] = "Connection: keep-alive";
4009 static const char connection_close[] = "Connection: close";
4011 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4012 && (csp->http->ssl == 0))
4014 return connection_keep_alive;
4016 return connection_close;