1 const char parsers_rcs[] = "$Id: parsers.c,v 1.236 2011/10/23 11:23:55 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 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
159 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
160 static jb_err server_save_content_length(struct client_state *csp, char **header);
161 static jb_err server_keep_alive(struct client_state *csp, char **header);
162 static jb_err server_proxy_connection(struct client_state *csp, char **header);
163 static jb_err client_keep_alive(struct client_state *csp, char **header);
164 static jb_err client_save_content_length(struct client_state *csp, char **header);
165 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
167 static jb_err client_host_adder (struct client_state *csp);
168 static jb_err client_xtra_adder (struct client_state *csp);
169 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
170 static jb_err client_connection_header_adder(struct client_state *csp);
171 static jb_err server_connection_adder(struct client_state *csp);
172 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
173 static jb_err server_proxy_connection_adder(struct client_state *csp);
174 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
176 static jb_err create_forged_referrer(char **header, const char *hostport);
177 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
178 static jb_err handle_conditional_hide_referrer_parameter(char **header,
179 const char *host, const int parameter_conditional_block);
180 static void create_content_length_header(unsigned long long content_length,
181 char *header, size_t buffer_length);
184 * List of functions to run on a list of headers.
188 /** The header prefix to match */
191 /** The length of the prefix to match */
194 /** The function to apply to this line */
195 const parser_func_ptr parser;
198 static const struct parsers client_patterns[] = {
199 { "referer:", 8, client_referrer },
200 { "user-agent:", 11, client_uagent },
201 { "ua-", 3, client_ua },
202 { "from:", 5, client_from },
203 { "cookie:", 7, client_send_cookie },
204 { "x-forwarded-for:", 16, client_x_forwarded },
205 { "Accept-Encoding:", 16, client_accept_encoding },
206 { "TE:", 3, client_te },
207 { "Host:", 5, client_host },
208 { "if-modified-since:", 18, client_if_modified_since },
209 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
210 { "Keep-Alive:", 11, client_keep_alive },
211 { "Content-Length:", 15, client_save_content_length },
213 { "Keep-Alive:", 11, crumble },
215 { "connection:", 11, client_connection },
216 { "proxy-connection:", 17, crumble },
217 { "max-forwards:", 13, client_max_forwards },
218 { "Accept-Language:", 16, client_accept_language },
219 { "if-none-match:", 14, client_if_none_match },
220 { "Range:", 6, client_range },
221 { "Request-Range:", 14, client_range },
222 { "If-Range:", 9, client_range },
223 { "X-Filter:", 9, client_x_filter },
224 { "*", 0, crunch_client_header },
225 { "*", 0, filter_header },
229 static const struct parsers server_patterns[] = {
230 { "HTTP/", 5, server_http },
231 { "set-cookie:", 11, server_set_cookie },
232 { "connection:", 11, server_connection },
233 { "Content-Type:", 13, server_content_type },
234 { "Content-MD5:", 12, server_content_md5 },
235 { "Content-Encoding:", 17, server_content_encoding },
236 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
237 { "Content-Length:", 15, server_save_content_length },
238 { "Keep-Alive:", 11, server_keep_alive },
239 { "Proxy-Connection:", 17, server_proxy_connection },
241 { "Keep-Alive:", 11, crumble },
242 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
243 { "Transfer-Encoding:", 18, server_transfer_coding },
244 { "content-disposition:", 20, server_content_disposition },
245 { "Last-Modified:", 14, server_last_modified },
246 { "*", 0, crunch_server_header },
247 { "*", 0, filter_header },
251 static const add_header_func_ptr add_client_headers[] = {
253 client_x_forwarded_for_adder,
255 client_connection_header_adder,
259 static const add_header_func_ptr add_server_headers[] = {
260 server_connection_adder,
261 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
262 server_proxy_connection_adder,
263 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
267 /*********************************************************************
269 * Function : flush_socket
271 * Description : Write any pending "buffered" content.
274 * 1 : fd = file descriptor of the socket to read
275 * 2 : iob = The I/O buffer to flush, usually csp->iob.
277 * Returns : On success, the number of bytes written are returned (zero
278 * indicates nothing was written). On error, -1 is returned,
279 * and errno is set appropriately. If count is zero and the
280 * file descriptor refers to a regular file, 0 will be
281 * returned without causing any other effect. For a special
282 * file, the results are not portable.
284 *********************************************************************/
285 long flush_socket(jb_socket fd, struct iob *iob)
287 long len = iob->eod - iob->cur;
294 if (write_socket(fd, iob->cur, (size_t)len))
298 iob->eod = iob->cur = iob->buf;
304 /*********************************************************************
306 * Function : add_to_iob
308 * Description : Add content to the buffered page, expanding the
309 * buffer if necessary.
312 * 1 : csp = Current client state (buffers, headers, etc...)
313 * 2 : buf = holds the content to be added to the page
314 * 3 : n = number of bytes to be added
316 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
317 * or buffer limit reached.
319 *********************************************************************/
320 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
322 struct iob *iob = csp->iob;
323 size_t used, offset, need;
326 if (n <= 0) return JB_ERR_OK;
328 used = (size_t)(iob->eod - iob->buf);
329 offset = (size_t)(iob->cur - iob->buf);
330 need = used + (size_t)n + 1;
333 * If the buffer can't hold the new data, extend it first.
334 * Use the next power of two if possible, else use the actual need.
336 if (need > csp->config->buffer_limit)
338 log_error(LOG_LEVEL_INFO,
339 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
340 need, csp->config->buffer_limit);
341 return JB_ERR_MEMORY;
344 if (need > iob->size)
346 size_t want = csp->iob->size ? csp->iob->size : 512;
353 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
357 else if (NULL != (p = (char *)realloc(iob->buf, need)))
363 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
364 return JB_ERR_MEMORY;
367 /* Update the iob pointers */
368 iob->cur = p + offset;
373 /* copy the new data into the iob buffer */
374 memcpy(iob->eod, buf, (size_t)n);
376 /* point to the end of the data */
379 /* null terminate == cheap insurance */
388 /*********************************************************************
390 * Function : decompress_iob
392 * Description : Decompress buffered page, expanding the
393 * buffer as necessary. csp->iob->cur
394 * should point to the the beginning of the
395 * compressed data block.
398 * 1 : csp = Current client state (buffers, headers, etc...)
400 * Returns : JB_ERR_OK on success,
401 * JB_ERR_MEMORY if out-of-memory limit reached, and
402 * JB_ERR_COMPRESS if error decompressing buffer.
404 *********************************************************************/
405 jb_err decompress_iob(struct client_state *csp)
407 char *buf; /* new, uncompressed buffer */
408 char *cur; /* Current iob position (to keep the original
409 * iob->cur unmodified if we return early) */
410 size_t bufsize; /* allocated size of the new buffer */
411 size_t old_size; /* Content size before decompression */
412 size_t skip_size; /* Number of bytes at the beginning of the iob
413 that we should NOT decompress. */
414 int status; /* return status of the inflate() call */
415 z_stream zstr; /* used by calls to zlib */
417 assert(csp->iob->cur - csp->iob->buf > 0);
418 assert(csp->iob->eod - csp->iob->cur > 0);
420 bufsize = csp->iob->size;
421 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
422 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
426 if (bufsize < (size_t)10)
429 * This is to protect the parsing of gzipped data,
430 * but it should(?) be valid for deflated data also.
432 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
433 return JB_ERR_COMPRESS;
436 if (csp->content_type & CT_GZIP)
439 * Our task is slightly complicated by the facts that data
440 * compressed by gzip does not include a zlib header, and
441 * that there is no easily accessible interface in zlib to
442 * handle a gzip header. We strip off the gzip header by
443 * hand, and later inform zlib not to expect a header.
447 * Strip off the gzip header. Please see RFC 1952 for more
448 * explanation of the appropriate fields.
450 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
451 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
452 || (*cur++ != Z_DEFLATED))
454 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
455 return JB_ERR_COMPRESS;
460 if (flags & GZIP_FLAG_RESERVED_BITS)
462 /* The gzip header has reserved bits set; bail out. */
463 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
464 return JB_ERR_COMPRESS;
468 * Skip mtime (4 bytes), extra flags (1 byte)
469 * and OS type (1 byte).
473 /* Skip extra fields if necessary. */
474 if (flags & GZIP_FLAG_EXTRA_FIELDS)
477 * Skip a given number of bytes, specified
478 * as a 16-bit little-endian value.
480 * XXX: this code is untested and should probably be removed.
484 skip_bytes += *cur++ << 8;
487 * The number of bytes to skip should be positive
488 * and we'd like to stay in the buffer.
490 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
492 log_error(LOG_LEVEL_ERROR,
493 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
495 return JB_ERR_COMPRESS;
497 log_error(LOG_LEVEL_INFO,
498 "Skipping %d bytes for gzip compression. Does this sound right?",
503 /* Skip the filename if necessary. */
504 if (flags & GZIP_FLAG_FILE_NAME)
506 /* A null-terminated string is supposed to follow. */
507 while (*cur++ && (cur < csp->iob->eod));
510 /* Skip the comment if necessary. */
511 if (flags & GZIP_FLAG_COMMENT)
513 /* A null-terminated string is supposed to follow. */
514 while (*cur++ && (cur < csp->iob->eod));
517 /* Skip the CRC if necessary. */
518 if (flags & GZIP_FLAG_CHECKSUM)
523 if (cur >= csp->iob->eod)
526 * If the current position pointer reached or passed
527 * the buffer end, we were obviously tricked to skip
530 log_error(LOG_LEVEL_ERROR,
531 "Malformed gzip header detected. Aborting decompression.");
532 return JB_ERR_COMPRESS;
536 else if (csp->content_type & CT_DEFLATE)
539 * XXX: The debug level should be lowered
540 * before the next stable release.
542 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
544 * In theory (that is, according to RFC 1950), deflate-compressed
545 * data should begin with a two-byte zlib header and have an
546 * adler32 checksum at the end. It seems that in practice only
547 * the raw compressed data is sent. Note that this means that
548 * we are not RFC 1950-compliant here, but the advantage is that
549 * this actually works. :)
551 * We add a dummy null byte to tell zlib where the data ends,
552 * and later inform it not to expect a header.
554 * Fortunately, add_to_iob() has thoughtfully null-terminated
555 * the buffer; we can just increment the end pointer to include
562 log_error(LOG_LEVEL_ERROR,
563 "Unable to determine compression format for decompression");
564 return JB_ERR_COMPRESS;
567 /* Set up the fields required by zlib. */
568 zstr.next_in = (Bytef *)cur;
569 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
570 zstr.zalloc = Z_NULL;
572 zstr.opaque = Z_NULL;
575 * Passing -MAX_WBITS to inflateInit2 tells the library
576 * that there is no zlib header.
578 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
580 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
581 return JB_ERR_COMPRESS;
585 * Next, we allocate new storage for the inflated data.
586 * We don't modify the existing iob yet, so in case there
587 * is error in decompression we can recover gracefully.
589 buf = zalloc(bufsize);
592 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
593 return JB_ERR_MEMORY;
596 assert(bufsize >= skip_size);
597 memcpy(buf, csp->iob->buf, skip_size);
598 zstr.avail_out = (uInt)(bufsize - skip_size);
599 zstr.next_out = (Bytef *)buf + skip_size;
601 /* Try to decompress the whole stream in one shot. */
602 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
604 /* We need to allocate more memory for the output buffer. */
606 char *tmpbuf; /* used for realloc'ing the buffer */
607 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
609 if (0 == zstr.avail_in)
612 * If zlib wants more data then there's a problem, because
613 * the complete compressed file should have been buffered.
615 log_error(LOG_LEVEL_ERROR,
616 "Unexpected end of compressed iob. Using what we got so far.");
621 * If we reached the buffer limit and still didn't have enough
622 * memory, just give up. Due to the ceiling enforced by the next
623 * if block we could actually check for equality here, but as it
624 * can be easily mistaken for a bug we don't.
626 if (bufsize >= csp->config->buffer_limit)
628 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
629 return JB_ERR_MEMORY;
632 /* Try doubling the buffer size each time. */
635 /* Don't exceed the buffer limit. */
636 if (bufsize > csp->config->buffer_limit)
638 bufsize = csp->config->buffer_limit;
641 /* Try to allocate the new buffer. */
642 tmpbuf = realloc(buf, bufsize);
645 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
647 return JB_ERR_MEMORY;
651 char *oldnext_out = (char *)zstr.next_out;
654 * Update the fields for inflate() to use the new
655 * buffer, which may be in a location different from
658 zstr.avail_out += (uInt)(bufsize - oldbufsize);
659 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
662 * Compare with an uglier method of calculating these values
663 * that doesn't require the extra oldbufsize variable.
665 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
666 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
672 if (Z_STREAM_ERROR == inflateEnd(&zstr))
674 log_error(LOG_LEVEL_ERROR,
675 "Inconsistent stream state after decompression: %s", zstr.msg);
677 * XXX: Intentionally no return.
679 * According to zlib.h, Z_STREAM_ERROR is returned
680 * "if the stream state was inconsistent".
682 * I assume in this case inflate()'s status
683 * would also be something different than Z_STREAM_END
684 * so this check should be redundant, but lets see.
688 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
691 * We failed to decompress the stream and it's
692 * not simply because of missing data.
694 log_error(LOG_LEVEL_ERROR,
695 "Unexpected error while decompressing to the buffer (iob): %s",
697 return JB_ERR_COMPRESS;
701 * Finally, we can actually update the iob, since the
702 * decompression was successful. First, free the old
705 freez(csp->iob->buf);
707 /* Now, update the iob to use the new buffer. */
709 csp->iob->cur = csp->iob->buf + skip_size;
710 csp->iob->eod = (char *)zstr.next_out;
711 csp->iob->size = bufsize;
714 * Make sure the new uncompressed iob obeys some minimal
715 * consistency conditions.
717 if ((csp->iob->buf < csp->iob->cur)
718 && (csp->iob->cur <= csp->iob->eod)
719 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
721 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
722 if (new_size > (size_t)0)
724 log_error(LOG_LEVEL_RE_FILTER,
725 "Decompression successful. Old size: %d, new size: %d.",
730 /* zlib thinks this is OK, so lets do the same. */
731 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
736 /* It seems that zlib did something weird. */
737 log_error(LOG_LEVEL_ERROR,
738 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
739 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
740 csp->iob->eod, csp->iob->buf + csp->iob->size);
741 return JB_ERR_COMPRESS;
747 #endif /* defined(FEATURE_ZLIB) */
750 /*********************************************************************
752 * Function : string_move
754 * Description : memmove wrapper to move the last part of a string
755 * towards the beginning, overwriting the part in
756 * the middle. strlcpy() can't be used here as the
760 * 1 : dst = Destination to overwrite
761 * 2 : src = Source to move.
765 *********************************************************************/
766 static void string_move(char *dst, char *src)
770 /* +1 to copy the terminating nul as well. */
771 memmove(dst, src, strlen(src)+1);
775 /*********************************************************************
777 * Function : normalize_lws
779 * Description : Reduces unquoted linear white space in headers
780 * to a single space in accordance with RFC 2616 2.2.
781 * This simplifies parsing and filtering later on.
783 * XXX: Remove log messages before
784 * the next stable release?
787 * 1 : header = A header with linear white space to reduce.
791 *********************************************************************/
792 static void normalize_lws(char *header)
798 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
802 while (ijb_isspace(*q))
806 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
812 log_error(LOG_LEVEL_HEADER,
813 "Converting tab to space in '%s'", header);
818 char *end_of_token = strstr(p+1, "\"");
820 if (NULL != end_of_token)
822 /* Don't mess with quoted text. */
827 log_error(LOG_LEVEL_HEADER,
828 "Ignoring single quote in '%s'", header);
834 p = strchr(header, ':');
835 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
838 * There's still space before the colon.
846 /*********************************************************************
848 * Function : get_header
850 * Description : This (odd) routine will parse the csp->iob
851 * to get the next complete header.
854 * 1 : iob = The I/O buffer to parse, usually csp->iob.
856 * Returns : Any one of the following:
858 * 1) a pointer to a dynamically allocated string that contains a header line
859 * 2) NULL indicating that the end of the header was reached
860 * 3) "" indicating that the end of the iob was reached before finding
861 * a complete header line.
863 *********************************************************************/
864 char *get_header(struct iob *iob)
868 header = get_header_line(iob);
870 if ((header == NULL) || (*header == '\0'))
873 * No complete header read yet, tell the client.
878 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
881 * Header spans multiple lines, append the next one.
883 char *continued_header;
885 continued_header = get_header_line(iob);
886 if ((continued_header == NULL) || (*continued_header == '\0'))
889 * No complete header read yet, return what we got.
890 * XXX: Should "unread" header instead.
892 log_error(LOG_LEVEL_INFO,
893 "Failed to read a multi-line header properly: '%s'",
898 if (JB_ERR_OK != string_join(&header, continued_header))
900 log_error(LOG_LEVEL_FATAL,
901 "Out of memory while appending multiple headers.");
905 /* XXX: remove before next stable release. */
906 log_error(LOG_LEVEL_HEADER,
907 "Merged multiple header lines to: '%s'",
912 normalize_lws(header);
919 /*********************************************************************
921 * Function : get_header_line
923 * Description : This (odd) routine will parse the csp->iob
924 * to get the next header line.
927 * 1 : iob = The I/O buffer to parse, usually csp->iob.
929 * Returns : Any one of the following:
931 * 1) a pointer to a dynamically allocated string that contains a header line
932 * 2) NULL indicating that the end of the header was reached
933 * 3) "" indicating that the end of the iob was reached before finding
934 * a complete header line.
936 *********************************************************************/
937 static char *get_header_line(struct iob *iob)
941 if ((iob->cur == NULL)
942 || ((p = strchr(iob->cur, '\n')) == NULL))
944 return(""); /* couldn't find a complete header */
949 ret = strdup(iob->cur);
952 /* FIXME No way to handle error properly */
953 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
959 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
961 /* is this a blank line (i.e. the end of the header) ? */
973 /*********************************************************************
975 * Function : get_header_value
977 * Description : Get the value of a given header from a chained list
978 * of header lines or return NULL if no such header is
979 * present in the list.
982 * 1 : header_list = pointer to list
983 * 2 : header_name = string with name of header to look for.
984 * Trailing colon required, capitalization
987 * Returns : NULL if not found, else value of header
989 *********************************************************************/
990 char *get_header_value(const struct list *header_list, const char *header_name)
992 struct list_entry *cur_entry;
998 length = strlen(header_name);
1000 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1004 if (!strncmpic(cur_entry->str, header_name, length))
1007 * Found: return pointer to start of value
1009 ret = cur_entry->str + length;
1010 while (*ret && ijb_isspace(*ret)) ret++;
1024 /*********************************************************************
1026 * Function : scan_headers
1028 * Description : Scans headers, applies tags and updates action bits.
1031 * 1 : csp = Current client state (buffers, headers, etc...)
1033 * Returns : JB_ERR_OK
1035 *********************************************************************/
1036 static jb_err scan_headers(struct client_state *csp)
1038 struct list_entry *h; /* Header */
1039 jb_err err = JB_ERR_OK;
1041 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1043 /* Header crunch()ed in previous run? -> ignore */
1044 if (h->str == NULL) continue;
1045 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1046 err = header_tagger(csp, h->str);
1053 /*********************************************************************
1057 * Description : add, delete or modify lines in the HTTP header streams.
1058 * On entry, it receives a linked list of headers space
1059 * that was allocated dynamically (both the list nodes
1060 * and the header contents).
1062 * As a side effect it frees the space used by the original
1066 * 1 : csp = Current client state (buffers, headers, etc...)
1067 * 2 : filter_server_headers = Boolean to switch between
1068 * server and header filtering.
1070 * Returns : JB_ERR_OK in case off success, or
1071 * JB_ERR_MEMORY on out-of-memory error.
1073 *********************************************************************/
1074 jb_err sed(struct client_state *csp, int filter_server_headers)
1076 /* XXX: use more descriptive names. */
1077 struct list_entry *p;
1078 const struct parsers *v;
1079 const add_header_func_ptr *f;
1080 jb_err err = JB_ERR_OK;
1082 if (filter_server_headers)
1084 v = server_patterns;
1085 f = add_server_headers;
1089 v = client_patterns;
1090 f = add_client_headers;
1095 while ((err == JB_ERR_OK) && (v->str != NULL))
1097 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1099 /* Header crunch()ed in previous run? -> ignore */
1100 if (p->str == NULL) continue;
1102 /* Does the current parser handle this header? */
1103 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1104 (v->len == CHECK_EVERY_HEADER_REMAINING))
1106 err = v->parser(csp, &(p->str));
1112 /* place additional headers on the csp->headers list */
1113 while ((err == JB_ERR_OK) && (*f))
1123 /*********************************************************************
1125 * Function : update_server_headers
1127 * Description : Updates server headers after the body has been modified.
1130 * 1 : csp = Current client state (buffers, headers, etc...)
1132 * Returns : JB_ERR_OK in case off success, or
1133 * JB_ERR_MEMORY on out-of-memory error.
1135 *********************************************************************/
1136 jb_err update_server_headers(struct client_state *csp)
1138 jb_err err = JB_ERR_OK;
1140 static const struct parsers server_patterns_light[] = {
1141 { "Content-Length:", 15, server_adjust_content_length },
1142 { "Transfer-Encoding:", 18, server_transfer_coding },
1144 { "Content-Encoding:", 17, server_adjust_content_encoding },
1145 #endif /* def FEATURE_ZLIB */
1149 if (strncmpic(csp->http->cmd, "HEAD", 4))
1151 const struct parsers *v;
1152 struct list_entry *p;
1154 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1156 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1158 /* Header crunch()ed in previous run? -> ignore */
1159 if (p->str == NULL) continue;
1161 /* Does the current parser handle this header? */
1162 if (strncmpic(p->str, v->str, v->len) == 0)
1164 err = v->parser(csp, (char **)&(p->str));
1170 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1171 if ((JB_ERR_OK == err)
1172 && (csp->flags & CSP_FLAG_MODIFIED)
1173 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1174 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1178 create_content_length_header(csp->content_length, header, sizeof(header));
1179 err = enlist(csp->headers, header);
1180 if (JB_ERR_OK == err)
1182 log_error(LOG_LEVEL_HEADER,
1183 "Content modified with no Content-Length header set. "
1184 "Created: %s.", header);
1187 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1189 #ifdef FEATURE_COMPRESSION
1190 if ((JB_ERR_OK == err)
1191 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1193 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1194 if (JB_ERR_OK == err)
1196 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1205 /*********************************************************************
1207 * Function : header_tagger
1209 * Description : Executes all text substitutions from applying
1210 * tag actions and saves the result as tag.
1212 * XXX: Shares enough code with filter_header() and
1213 * pcrs_filter_response() to warrant some helper functions.
1216 * 1 : csp = Current client state (buffers, headers, etc...)
1217 * 2 : header = Header that is used as tagger input
1219 * Returns : JB_ERR_OK on success and always succeeds
1221 *********************************************************************/
1222 static jb_err header_tagger(struct client_state *csp, char *header)
1224 int wanted_filter_type;
1225 int multi_action_index;
1229 struct file_list *fl;
1230 struct re_filterfile_spec *b;
1231 struct list_entry *tag_name;
1233 const size_t header_length = strlen(header);
1235 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1237 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1238 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1242 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1243 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1246 if (filters_available(csp) == FALSE)
1248 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1249 "tagging enabled, but no taggers available.");
1253 for (i = 0; i < MAX_AF_FILES; i++)
1256 if ((NULL == fl) || (NULL == fl->f))
1259 * Either there are no filter files
1260 * left, or this filter file just
1261 * contains no valid filters.
1263 * Continue to be sure we don't miss
1264 * valid filter files that are chained
1265 * after empty or invalid ones.
1270 /* For all filters, */
1271 for (b = fl->f; b; b = b->next)
1273 if (b->type != wanted_filter_type)
1275 /* skip the ones we don't care about, */
1278 /* leaving only taggers that could apply, of which we use the ones, */
1279 for (tag_name = csp->action->multi[multi_action_index]->first;
1280 NULL != tag_name; tag_name = tag_name->next)
1282 /* that do apply, and */
1283 if (strcmp(b->name, tag_name->str) == 0)
1285 char *modified_tag = NULL;
1287 size_t size = header_length;
1288 pcrs_job *joblist = b->joblist;
1290 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1292 if (NULL == joblist)
1294 log_error(LOG_LEVEL_RE_FILTER,
1295 "Tagger %s has empty joblist. Nothing to do.", b->name);
1299 /* execute their pcrs_joblist on the header. */
1300 for (job = joblist; NULL != job; job = job->next)
1302 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1306 /* Success, continue with the modified version. */
1315 /* Tagger doesn't match */
1318 /* Regex failure, log it but continue anyway. */
1319 assert(NULL != header);
1320 log_error(LOG_LEVEL_ERROR,
1321 "Problems with tagger \'%s\' and header \'%s\': %s",
1322 b->name, *header, pcrs_strerror(hits));
1324 freez(modified_tag);
1328 if (b->dynamic) pcrs_free_joblist(joblist);
1330 /* If this tagger matched */
1336 * There is to technical limitation which makes
1337 * it impossible to use empty tags, but I assume
1338 * no one would do it intentionally.
1341 log_error(LOG_LEVEL_INFO,
1342 "Tagger \'%s\' created an empty tag. Ignored.",
1347 if (!list_contains_item(csp->tags, tag))
1349 if (JB_ERR_OK != enlist(csp->tags, tag))
1351 log_error(LOG_LEVEL_ERROR,
1352 "Insufficient memory to add tag \'%s\', "
1353 "based on tagger \'%s\' and header \'%s\'",
1354 tag, b->name, *header);
1358 char *action_message;
1360 * update the action bits right away, to make
1361 * tagging based on tags set by earlier taggers
1362 * of the same kind possible.
1364 if (update_action_bits_for_tag(csp, tag))
1366 action_message = "Action bits updated accordingly.";
1370 action_message = "No action bits update necessary.";
1373 log_error(LOG_LEVEL_HEADER,
1374 "Tagger \'%s\' added tag \'%s\'. %s",
1375 b->name, tag, action_message);
1380 /* XXX: Is this log-worthy? */
1381 log_error(LOG_LEVEL_HEADER,
1382 "Tagger \'%s\' didn't add tag \'%s\'. "
1383 "Tag already present", b->name, tag);
1386 } /* if the tagger matched */
1387 } /* if the tagger applies */
1388 } /* for every tagger that could apply */
1389 } /* for all filters */
1390 } /* for all filter files */
1395 /* here begins the family of parser functions that reformat header lines */
1397 /*********************************************************************
1399 * Function : filter_header
1401 * Description : Executes all text substitutions from all applying
1402 * +(server|client)-header-filter actions on the header.
1403 * Most of the code was copied from pcrs_filter_response,
1404 * including the rather short variable names
1407 * 1 : csp = Current client state (buffers, headers, etc...)
1408 * 2 : header = On input, pointer to header to modify.
1409 * On output, pointer to the modified header, or NULL
1410 * to remove the header. This function frees the
1411 * original string if necessary.
1413 * Returns : JB_ERR_OK on success and always succeeds
1415 *********************************************************************/
1416 static jb_err filter_header(struct client_state *csp, char **header)
1420 size_t size = strlen(*header);
1422 char *newheader = NULL;
1425 struct file_list *fl;
1426 struct re_filterfile_spec *b;
1427 struct list_entry *filtername;
1430 int wanted_filter_type;
1431 int multi_action_index;
1433 if (csp->flags & CSP_FLAG_NO_FILTERING)
1438 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1440 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1441 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1445 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1446 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1449 if (filters_available(csp) == FALSE)
1451 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1452 "header filtering enabled, but no matching filters available.");
1456 for (i = 0; i < MAX_AF_FILES; i++)
1459 if ((NULL == fl) || (NULL == fl->f))
1462 * Either there are no filter files
1463 * left, or this filter file just
1464 * contains no valid filters.
1466 * Continue to be sure we don't miss
1467 * valid filter files that are chained
1468 * after empty or invalid ones.
1473 * For all applying +filter actions, look if a filter by that
1474 * name exists and if yes, execute its pcrs_joblist on the
1477 for (b = fl->f; b; b = b->next)
1479 if (b->type != wanted_filter_type)
1481 /* Skip other filter types */
1485 for (filtername = csp->action->multi[multi_action_index]->first;
1486 filtername ; filtername = filtername->next)
1488 if (strcmp(b->name, filtername->str) == 0)
1490 int current_hits = 0;
1491 pcrs_job *joblist = b->joblist;
1493 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1495 if (NULL == joblist)
1497 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1501 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1502 *header, size, b->name);
1504 /* Apply all jobs from the joblist */
1505 for (job = joblist; NULL != job; job = job->next)
1507 matches = pcrs_execute(job, *header, size, &newheader, &size);
1510 current_hits += matches;
1511 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1513 *header = newheader;
1515 else if ( 0 == matches )
1517 /* Filter doesn't change header */
1523 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1524 *header, b->name, pcrs_strerror(matches));
1525 if (newheader != NULL)
1527 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1533 if (b->dynamic) pcrs_free_joblist(joblist);
1535 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1536 hits += current_hits;
1543 * Additionally checking for hits is important because if
1544 * the continue hack is triggered, server headers can
1545 * arrive empty to separate multiple heads from each other.
1547 if ((0 == size) && hits)
1549 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1557 /*********************************************************************
1559 * Function : server_connection
1561 * Description : Makes sure a proper "Connection:" header is
1562 * set and signals connection_header_adder to
1566 * 1 : csp = Current client state (buffers, headers, etc...)
1567 * 2 : header = On input, pointer to header to modify.
1568 * On output, pointer to the modified header, or NULL
1569 * to remove the header. This function frees the
1570 * original string if necessary.
1572 * Returns : JB_ERR_OK on success, or
1573 * JB_ERR_MEMORY on out-of-memory error.
1575 *********************************************************************/
1576 static jb_err server_connection(struct client_state *csp, char **header)
1578 if (!strcmpic(*header, "Connection: keep-alive")
1579 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1580 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1584 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1585 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1587 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1590 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1592 log_error(LOG_LEVEL_HEADER,
1593 "Keeping the server header '%s' around.", *header);
1596 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1598 char *old_header = *header;
1600 *header = strdup("Connection: close");
1603 return JB_ERR_MEMORY;
1605 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1610 /* Signal server_connection_adder() to return early. */
1611 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1617 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1618 /*********************************************************************
1620 * Function : server_keep_alive
1622 * Description : Stores the server's keep alive timeout.
1625 * 1 : csp = Current client state (buffers, headers, etc...)
1626 * 2 : header = On input, pointer to header to modify.
1627 * On output, pointer to the modified header, or NULL
1628 * to remove the header. This function frees the
1629 * original string if necessary.
1631 * Returns : JB_ERR_OK.
1633 *********************************************************************/
1634 static jb_err server_keep_alive(struct client_state *csp, char **header)
1636 unsigned int keep_alive_timeout;
1637 const char *timeout_position = strstr(*header, "timeout=");
1639 if ((NULL == timeout_position)
1640 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1642 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1646 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1648 log_error(LOG_LEVEL_HEADER,
1649 "Reducing keep-alive timeout from %u to %u.",
1650 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1651 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1655 /* XXX: Is this log worthy? */
1656 log_error(LOG_LEVEL_HEADER,
1657 "Server keep-alive timeout is %u. Sticking with %u.",
1658 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1660 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1667 /*********************************************************************
1669 * Function : server_proxy_connection
1671 * Description : Figures out whether or not we should add a
1672 * Proxy-Connection header.
1675 * 1 : csp = Current client state (buffers, headers, etc...)
1676 * 2 : header = On input, pointer to header to modify.
1677 * On output, pointer to the modified header, or NULL
1678 * to remove the header. This function frees the
1679 * original string if necessary.
1681 * Returns : JB_ERR_OK.
1683 *********************************************************************/
1684 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1686 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1691 /*********************************************************************
1693 * Function : client_keep_alive
1695 * Description : Stores the client's keep alive timeout.
1698 * 1 : csp = Current client state (buffers, headers, etc...)
1699 * 2 : header = On input, pointer to header to modify.
1700 * On output, pointer to the modified header, or NULL
1701 * to remove the header. This function frees the
1702 * original string if necessary.
1704 * Returns : JB_ERR_OK.
1706 *********************************************************************/
1707 static jb_err client_keep_alive(struct client_state *csp, char **header)
1709 unsigned int keep_alive_timeout;
1710 const char *timeout_position = strstr(*header, ": ");
1712 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1714 log_error(LOG_LEVEL_HEADER,
1715 "keep-alive support is disabled. Crunching: %s.", *header);
1720 if ((NULL == timeout_position)
1721 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1723 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1727 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1729 log_error(LOG_LEVEL_HEADER,
1730 "Reducing keep-alive timeout from %u to %u.",
1731 csp->config->keep_alive_timeout, keep_alive_timeout);
1732 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1736 /* XXX: Is this log worthy? */
1737 log_error(LOG_LEVEL_HEADER,
1738 "Client keep-alive timeout is %u. Sticking with %u.",
1739 keep_alive_timeout, csp->config->keep_alive_timeout);
1747 /*********************************************************************
1749 * Function : get_content_length
1751 * Description : Gets the content length specified in a
1752 * Content-Length header.
1755 * 1 : header = The Content-Length header.
1756 * 2 : length = Storage to return the value.
1758 * Returns : JB_ERR_OK on success, or
1759 * JB_ERR_PARSE if no value is recognized.
1761 *********************************************************************/
1762 static jb_err get_content_length(const char *header, unsigned long long *length)
1764 assert(header[14] == ':');
1767 assert(sizeof(unsigned long long) > 4);
1768 if (1 != sscanf(header+14, ": %I64u", length))
1770 if (1 != sscanf(header+14, ": %llu", length))
1773 return JB_ERR_PARSE;
1780 /*********************************************************************
1782 * Function : client_save_content_length
1784 * Description : Save the Content-Length sent by the client.
1787 * 1 : csp = Current client state (buffers, headers, etc...)
1788 * 2 : header = On input, pointer to header to modify.
1789 * On output, pointer to the modified header, or NULL
1790 * to remove the header. This function frees the
1791 * original string if necessary.
1793 * Returns : JB_ERR_OK on success, or
1794 * JB_ERR_MEMORY on out-of-memory error.
1796 *********************************************************************/
1797 static jb_err client_save_content_length(struct client_state *csp, char **header)
1799 unsigned long long content_length = 0;
1801 assert(*(*header+14) == ':');
1803 if (JB_ERR_OK != get_content_length(*header, &content_length))
1805 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1810 csp->expected_client_content_length = content_length;
1815 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1819 /*********************************************************************
1821 * Function : client_connection
1823 * Description : Makes sure a proper "Connection:" header is
1824 * set and signals connection_header_adder
1828 * 1 : csp = Current client state (buffers, headers, etc...)
1829 * 2 : header = On input, pointer to header to modify.
1830 * On output, pointer to the modified header, or NULL
1831 * to remove the header. This function frees the
1832 * original string if necessary.
1834 * Returns : JB_ERR_OK on success, or
1835 * JB_ERR_MEMORY on out-of-memory error.
1837 *********************************************************************/
1838 static jb_err client_connection(struct client_state *csp, char **header)
1840 static const char connection_close[] = "Connection: close";
1842 if (!strcmpic(*header, connection_close))
1844 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1845 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1847 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1849 log_error(LOG_LEVEL_HEADER,
1850 "Removing \'%s\' to imply keep-alive.", *header);
1853 * While we imply keep-alive to the server,
1854 * we have to remember that the client didn't.
1856 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1860 char *old_header = *header;
1862 *header = strdup("Connection: keep-alive");
1865 return JB_ERR_MEMORY;
1867 log_error(LOG_LEVEL_HEADER,
1868 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1874 log_error(LOG_LEVEL_HEADER,
1875 "Keeping the client header '%s' around. "
1876 "The connection will not be kept alive.",
1878 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1881 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1883 log_error(LOG_LEVEL_HEADER,
1884 "Keeping the client header '%s' around. "
1885 "The server connection will be kept alive if possible.",
1887 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1888 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1892 char *old_header = *header;
1894 *header = strdup(connection_close);
1897 return JB_ERR_MEMORY;
1899 log_error(LOG_LEVEL_HEADER,
1900 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1904 /* Signal client_connection_adder() to return early. */
1905 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1911 /*********************************************************************
1913 * Function : crumble
1915 * Description : This is called if a header matches a pattern to "crunch"
1918 * 1 : csp = Current client state (buffers, headers, etc...)
1919 * 2 : header = On input, pointer to header to modify.
1920 * On output, pointer to the modified header, or NULL
1921 * to remove the header. This function frees the
1922 * original string if necessary.
1924 * Returns : JB_ERR_OK on success, or
1925 * JB_ERR_MEMORY on out-of-memory error.
1927 *********************************************************************/
1928 static jb_err crumble(struct client_state *csp, char **header)
1931 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1937 /*********************************************************************
1939 * Function : crunch_server_header
1941 * Description : Crunch server header if it matches a string supplied by the
1942 * user. Called from `sed'.
1945 * 1 : csp = Current client state (buffers, headers, etc...)
1946 * 2 : header = On input, pointer to header to modify.
1947 * On output, pointer to the modified header, or NULL
1948 * to remove the header. This function frees the
1949 * original string if necessary.
1951 * Returns : JB_ERR_OK on success and always succeeds
1953 *********************************************************************/
1954 static jb_err crunch_server_header(struct client_state *csp, char **header)
1956 const char *crunch_pattern;
1958 /* Do we feel like crunching? */
1959 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1961 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1963 /* Is the current header the lucky one? */
1964 if (strstr(*header, crunch_pattern))
1966 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1975 /*********************************************************************
1977 * Function : server_content_type
1979 * Description : Set the content-type for filterable types (text/.*,
1980 * .*xml.*, .*script.* and image/gif) unless filtering has been
1981 * forbidden (CT_TABOO) while parsing earlier headers.
1982 * NOTE: Since text/plain is commonly used by web servers
1983 * for files whose correct type is unknown, we don't
1984 * set CT_TEXT for it.
1987 * 1 : csp = Current client state (buffers, headers, etc...)
1988 * 2 : header = On input, pointer to header to modify.
1989 * On output, pointer to the modified header, or NULL
1990 * to remove the header. This function frees the
1991 * original string if necessary.
1993 * Returns : JB_ERR_OK on success, or
1994 * JB_ERR_MEMORY on out-of-memory error.
1996 *********************************************************************/
1997 static jb_err server_content_type(struct client_state *csp, char **header)
1999 /* Remove header if it isn't the first Content-Type header */
2000 if ((csp->content_type & CT_DECLARED))
2003 * Another, slightly slower, way to see if
2004 * we already parsed another Content-Type header.
2006 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2008 log_error(LOG_LEVEL_ERROR,
2009 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2017 * Signal that the Content-Type has been set.
2019 csp->content_type |= CT_DECLARED;
2021 if (!(csp->content_type & CT_TABOO))
2024 * XXX: The assumption that text/plain is a sign of
2025 * binary data seems to be somewhat unreasonable nowadays
2026 * and should be dropped after 3.0.8 is out.
2028 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2029 || strstr(*header, "xml")
2030 || strstr(*header, "script"))
2032 csp->content_type |= CT_TEXT;
2034 else if (strstr(*header, "image/gif"))
2036 csp->content_type |= CT_GIF;
2041 * Are we messing with the content type?
2043 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2046 * Make sure the user doesn't accidentally
2047 * change the content type of binary documents.
2049 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2052 *header = strdup("Content-Type: ");
2053 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2057 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2058 return JB_ERR_MEMORY;
2060 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2064 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2065 "It doesn't look like a content type that should be filtered. "
2066 "Enable force-text-mode if you know what you're doing.", *header);
2074 /*********************************************************************
2076 * Function : server_transfer_coding
2078 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2079 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2080 * - Remove header if body was chunked but has been
2081 * de-chunked for filtering.
2084 * 1 : csp = Current client state (buffers, headers, etc...)
2085 * 2 : header = On input, pointer to header to modify.
2086 * On output, pointer to the modified header, or NULL
2087 * to remove the header. This function frees the
2088 * original string if necessary.
2090 * Returns : JB_ERR_OK on success, or
2091 * JB_ERR_MEMORY on out-of-memory error.
2093 *********************************************************************/
2094 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2097 * Turn off pcrs and gif filtering if body compressed
2099 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2103 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2105 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2106 csp->http->cmd, *header);
2107 #endif /* def FEATURE_ZLIB */
2108 csp->content_type = CT_TABOO;
2112 * Raise flag if body chunked
2114 if (strstr(*header, "chunked"))
2116 csp->flags |= CSP_FLAG_CHUNKED;
2119 * If the body was modified, it has been de-chunked first
2120 * and the header must be removed.
2122 * FIXME: If there is more than one transfer encoding,
2123 * only the "chunked" part should be removed here.
2125 if (csp->flags & CSP_FLAG_MODIFIED)
2127 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2136 /*********************************************************************
2138 * Function : server_content_encoding
2140 * Description : Used to check if the content is compressed, and if
2141 * FEATURE_ZLIB is disabled, filtering is disabled as
2144 * If FEATURE_ZLIB is enabled and the compression type
2145 * supported, the content is marked for decompression.
2147 * XXX: Doesn't properly deal with multiple or with
2148 * unsupported but unknown encodings.
2149 * Is case-sensitive but shouldn't be.
2152 * 1 : csp = Current client state (buffers, headers, etc...)
2153 * 2 : header = On input, pointer to header to modify.
2154 * On output, pointer to the modified header, or NULL
2155 * to remove the header. This function frees the
2156 * original string if necessary.
2158 * Returns : JB_ERR_OK on success, or
2159 * JB_ERR_MEMORY on out-of-memory error.
2161 *********************************************************************/
2162 static jb_err server_content_encoding(struct client_state *csp, char **header)
2165 if (strstr(*header, "sdch"))
2168 * Shared Dictionary Compression over HTTP isn't supported,
2169 * filtering it anyway is pretty much guaranteed to mess up
2172 csp->content_type |= CT_TABOO;
2175 * Log a warning if the user expects the content to be filtered.
2177 if ((csp->rlist != NULL) &&
2178 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2180 log_error(LOG_LEVEL_INFO,
2181 "SDCH-compressed content detected, content filtering disabled. "
2182 "Consider suppressing SDCH offers made by the client.");
2185 else if (strstr(*header, "gzip"))
2187 /* Mark for gzip decompression */
2188 csp->content_type |= CT_GZIP;
2190 else if (strstr(*header, "deflate"))
2192 /* Mark for zlib decompression */
2193 csp->content_type |= CT_DEFLATE;
2195 else if (strstr(*header, "compress"))
2198 * We can't decompress this; therefore we can't filter
2201 csp->content_type |= CT_TABOO;
2203 #else /* !defined(FEATURE_ZLIB) */
2205 * XXX: Using a black list here isn't the right approach.
2207 * In case of SDCH, building with zlib support isn't
2210 if (strstr(*header, "gzip") ||
2211 strstr(*header, "compress") ||
2212 strstr(*header, "deflate") ||
2213 strstr(*header, "sdch"))
2216 * Body is compressed, turn off pcrs and gif filtering.
2218 csp->content_type |= CT_TABOO;
2221 * Log a warning if the user expects the content to be filtered.
2223 if ((csp->rlist != NULL) &&
2224 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2226 log_error(LOG_LEVEL_INFO,
2227 "Compressed content detected, content filtering disabled. "
2228 "Consider recompiling Privoxy with zlib support or "
2229 "enable the prevent-compression action.");
2232 #endif /* defined(FEATURE_ZLIB) */
2240 /*********************************************************************
2242 * Function : server_adjust_content_encoding
2244 * Description : Remove the Content-Encoding header if the
2245 * decompression was successful and the content
2249 * 1 : csp = Current client state (buffers, headers, etc...)
2250 * 2 : header = On input, pointer to header to modify.
2251 * On output, pointer to the modified header, or NULL
2252 * to remove the header. This function frees the
2253 * original string if necessary.
2255 * Returns : JB_ERR_OK on success, or
2256 * JB_ERR_MEMORY on out-of-memory error.
2258 *********************************************************************/
2259 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2261 if ((csp->flags & CSP_FLAG_MODIFIED)
2262 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2265 * We successfully decompressed the content,
2266 * and have to clean the header now, so the
2267 * client no longer expects compressed data.
2269 * XXX: There is a difference between cleaning
2270 * and removing it completely.
2272 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2279 #endif /* defined(FEATURE_ZLIB) */
2282 /*********************************************************************
2284 * Function : server_adjust_content_length
2286 * Description : Adjust Content-Length header if we modified
2290 * 1 : csp = Current client state (buffers, headers, etc...)
2291 * 2 : header = On input, pointer to header to modify.
2292 * On output, pointer to the modified header, or NULL
2293 * to remove the header. This function frees the
2294 * original string if necessary.
2296 * Returns : JB_ERR_OK on success, or
2297 * JB_ERR_MEMORY on out-of-memory error.
2299 *********************************************************************/
2300 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2302 /* Regenerate header if the content was modified. */
2303 if (csp->flags & CSP_FLAG_MODIFIED)
2305 const size_t header_length = 50;
2307 *header = malloc(header_length);
2308 if (*header == NULL)
2310 return JB_ERR_MEMORY;
2312 create_content_length_header(csp->content_length, *header, header_length);
2313 log_error(LOG_LEVEL_HEADER,
2314 "Adjusted Content-Length to %llu", csp->content_length);
2321 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2322 /*********************************************************************
2324 * Function : server_save_content_length
2326 * Description : Save the Content-Length sent by the server.
2329 * 1 : csp = Current client state (buffers, headers, etc...)
2330 * 2 : header = On input, pointer to header to modify.
2331 * On output, pointer to the modified header, or NULL
2332 * to remove the header. This function frees the
2333 * original string if necessary.
2335 * Returns : JB_ERR_OK on success, or
2336 * JB_ERR_MEMORY on out-of-memory error.
2338 *********************************************************************/
2339 static jb_err server_save_content_length(struct client_state *csp, char **header)
2341 unsigned long long content_length = 0;
2343 assert(*(*header+14) == ':');
2345 if (JB_ERR_OK != get_content_length(*header, &content_length))
2347 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2352 csp->expected_content_length = content_length;
2353 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2354 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2359 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2362 /*********************************************************************
2364 * Function : server_content_md5
2366 * Description : Crumble any Content-MD5 headers if the document was
2367 * modified. FIXME: Should we re-compute instead?
2370 * 1 : csp = Current client state (buffers, headers, etc...)
2371 * 2 : header = On input, pointer to header to modify.
2372 * On output, pointer to the modified header, or NULL
2373 * to remove the header. This function frees the
2374 * original string if necessary.
2376 * Returns : JB_ERR_OK on success, or
2377 * JB_ERR_MEMORY on out-of-memory error.
2379 *********************************************************************/
2380 static jb_err server_content_md5(struct client_state *csp, char **header)
2382 if (csp->flags & CSP_FLAG_MODIFIED)
2384 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2392 /*********************************************************************
2394 * Function : server_content_disposition
2396 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2397 * Called from `sed'.
2400 * 1 : csp = Current client state (buffers, headers, etc...)
2401 * 2 : header = On input, pointer to header to modify.
2402 * On output, pointer to the modified header, or NULL
2403 * to remove the header. This function frees the
2404 * original string if necessary.
2406 * Returns : JB_ERR_OK on success, or
2407 * JB_ERR_MEMORY on out-of-memory error.
2409 *********************************************************************/
2410 static jb_err server_content_disposition(struct client_state *csp, char **header)
2415 * Are we messing with the Content-Disposition header?
2417 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2423 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2425 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2428 * Blocking content-disposition header
2430 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2437 * Replacing Content-Disposition header
2440 *header = strdup("Content-Disposition: ");
2441 string_append(header, newval);
2443 if (*header != NULL)
2445 log_error(LOG_LEVEL_HEADER,
2446 "Content-Disposition header crunched and replaced with: %s", *header);
2449 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2453 /*********************************************************************
2455 * Function : server_last_modified
2457 * Description : Changes Last-Modified header to the actual date
2458 * to help hide-if-modified-since.
2459 * Called from `sed'.
2462 * 1 : csp = Current client state (buffers, headers, etc...)
2463 * 2 : header = On input, pointer to header to modify.
2464 * On output, pointer to the modified header, or NULL
2465 * to remove the header. This function frees the
2466 * original string if necessary.
2468 * Returns : JB_ERR_OK on success, or
2469 * JB_ERR_MEMORY on out-of-memory error.
2471 *********************************************************************/
2472 static jb_err server_last_modified(struct client_state *csp, char **header)
2475 time_t last_modified;
2479 * Are we messing with the Last-Modified header?
2481 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2487 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2489 if (0 == strcmpic(newval, "block") )
2492 * Blocking Last-Modified header. Useless but why not.
2494 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2498 else if (0 == strcmpic(newval, "reset-to-request-time"))
2501 * Setting Last-Modified Header to now.
2504 get_http_time(0, buf, sizeof(buf));
2506 *header = strdup("Last-Modified: ");
2507 string_append(header, buf);
2509 if (*header == NULL)
2511 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2515 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2518 else if (0 == strcmpic(newval, "randomize"))
2520 const char *header_time = *header + sizeof("Last-Modified:");
2522 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2524 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2526 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2532 struct tm *timeptr = NULL;
2534 #ifdef HAVE_GMTIME_R
2538 rtime = (long int)difftime(now, last_modified);
2541 long int days, hours, minutes, seconds;
2542 const int negative_delta = (rtime < 0);
2547 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2549 rtime = pick_from_range(rtime);
2554 last_modified += rtime;
2555 #ifdef HAVE_GMTIME_R
2556 timeptr = gmtime_r(&last_modified, &gmt);
2557 #elif defined(MUTEX_LOCKS_AVAILABLE)
2558 privoxy_mutex_lock(&gmtime_mutex);
2559 timeptr = gmtime(&last_modified);
2560 privoxy_mutex_unlock(&gmtime_mutex);
2562 timeptr = gmtime(&last_modified);
2564 if ((NULL == timeptr) || !strftime(newheader,
2565 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2567 log_error(LOG_LEVEL_ERROR,
2568 "Randomizing '%s' failed. Crunching the header without replacement.",
2575 *header = strdup("Last-Modified: ");
2576 string_append(header, newheader);
2578 if (*header == NULL)
2580 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2581 return JB_ERR_MEMORY;
2584 days = rtime / (3600 * 24);
2585 hours = rtime / 3600 % 24;
2586 minutes = rtime / 60 % 60;
2587 seconds = rtime % 60;
2589 log_error(LOG_LEVEL_HEADER,
2590 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2591 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2592 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2596 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2605 /*********************************************************************
2607 * Function : client_accept_encoding
2609 * Description : Rewrite the client's Accept-Encoding header so that
2610 * if doesn't allow compression, if the action applies.
2611 * Note: For HTTP/1.0 the absence of the header is enough.
2614 * 1 : csp = Current client state (buffers, headers, etc...)
2615 * 2 : header = On input, pointer to header to modify.
2616 * On output, pointer to the modified header, or NULL
2617 * to remove the header. This function frees the
2618 * original string if necessary.
2620 * Returns : JB_ERR_OK on success, or
2621 * JB_ERR_MEMORY on out-of-memory error.
2623 *********************************************************************/
2624 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2626 #ifdef FEATURE_COMPRESSION
2627 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2628 && strstr(*header, "deflate"))
2630 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2633 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2635 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2643 /*********************************************************************
2645 * Function : client_te
2647 * Description : Rewrite the client's TE header so that
2648 * if doesn't allow compression, if the action applies.
2651 * 1 : csp = Current client state (buffers, headers, etc...)
2652 * 2 : header = On input, pointer to header to modify.
2653 * On output, pointer to the modified header, or NULL
2654 * to remove the header. This function frees the
2655 * original string if necessary.
2657 * Returns : JB_ERR_OK on success, or
2658 * JB_ERR_MEMORY on out-of-memory error.
2660 *********************************************************************/
2661 static jb_err client_te(struct client_state *csp, char **header)
2663 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2666 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2673 /*********************************************************************
2675 * Function : client_referrer
2677 * Description : Handle the "referer" config setting properly.
2678 * Called from `sed'.
2681 * 1 : csp = Current client state (buffers, headers, etc...)
2682 * 2 : header = On input, pointer to header to modify.
2683 * On output, pointer to the modified header, or NULL
2684 * to remove the header. This function frees the
2685 * original string if necessary.
2687 * Returns : JB_ERR_OK on success, or
2688 * JB_ERR_MEMORY on out-of-memory error.
2690 *********************************************************************/
2691 static jb_err client_referrer(struct client_state *csp, char **header)
2693 const char *parameter;
2694 /* booleans for parameters we have to check multiple times */
2695 int parameter_conditional_block;
2696 int parameter_conditional_forge;
2698 #ifdef FEATURE_FORCE_LOAD
2700 * Since the referrer can include the prefix even
2701 * if the request itself is non-forced, we must
2702 * clean it unconditionally.
2704 * XXX: strclean is too broad
2706 strclean(*header, FORCE_PREFIX);
2707 #endif /* def FEATURE_FORCE_LOAD */
2709 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2711 /* Nothing left to do */
2715 parameter = csp->action->string[ACTION_STRING_REFERER];
2716 assert(parameter != NULL);
2717 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2718 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2720 if (!parameter_conditional_block && !parameter_conditional_forge)
2723 * As conditional-block and conditional-forge are the only
2724 * parameters that rely on the original referrer, we can
2725 * remove it now for all the others.
2730 if (0 == strcmpic(parameter, "block"))
2732 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2735 else if (parameter_conditional_block || parameter_conditional_forge)
2737 return handle_conditional_hide_referrer_parameter(header,
2738 csp->http->hostport, parameter_conditional_block);
2740 else if (0 == strcmpic(parameter, "forge"))
2742 return create_forged_referrer(header, csp->http->hostport);
2746 /* interpret parameter as user-supplied referer to fake */
2747 return create_fake_referrer(header, parameter);
2752 /*********************************************************************
2754 * Function : client_accept_language
2756 * Description : Handle the "Accept-Language" config setting properly.
2757 * Called from `sed'.
2760 * 1 : csp = Current client state (buffers, headers, etc...)
2761 * 2 : header = On input, pointer to header to modify.
2762 * On output, pointer to the modified header, or NULL
2763 * to remove the header. This function frees the
2764 * original string if necessary.
2766 * Returns : JB_ERR_OK on success, or
2767 * JB_ERR_MEMORY on out-of-memory error.
2769 *********************************************************************/
2770 static jb_err client_accept_language(struct client_state *csp, char **header)
2775 * Are we messing with the Accept-Language?
2777 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2779 /*I don't think so*/
2783 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2785 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2788 * Blocking Accept-Language header
2790 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2797 * Replacing Accept-Language header
2800 *header = strdup("Accept-Language: ");
2801 string_append(header, newval);
2803 if (*header == NULL)
2805 log_error(LOG_LEVEL_ERROR,
2806 "Insufficient memory. Accept-Language header crunched without replacement.");
2810 log_error(LOG_LEVEL_HEADER,
2811 "Accept-Language header crunched and replaced with: %s", *header);
2814 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2818 /*********************************************************************
2820 * Function : crunch_client_header
2822 * Description : Crunch client header if it matches a string supplied by the
2823 * user. Called from `sed'.
2826 * 1 : csp = Current client state (buffers, headers, etc...)
2827 * 2 : header = On input, pointer to header to modify.
2828 * On output, pointer to the modified header, or NULL
2829 * to remove the header. This function frees the
2830 * original string if necessary.
2832 * Returns : JB_ERR_OK on success and always succeeds
2834 *********************************************************************/
2835 static jb_err crunch_client_header(struct client_state *csp, char **header)
2837 const char *crunch_pattern;
2839 /* Do we feel like crunching? */
2840 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2842 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2844 /* Is the current header the lucky one? */
2845 if (strstr(*header, crunch_pattern))
2847 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2855 /*********************************************************************
2857 * Function : client_uagent
2859 * Description : Handle the "user-agent" config setting properly
2860 * and remember its original value to enable browser
2861 * bug workarounds. Called from `sed'.
2864 * 1 : csp = Current client state (buffers, headers, etc...)
2865 * 2 : header = On input, pointer to header to modify.
2866 * On output, pointer to the modified header, or NULL
2867 * to remove the header. This function frees the
2868 * original string if necessary.
2870 * Returns : JB_ERR_OK on success, or
2871 * JB_ERR_MEMORY on out-of-memory error.
2873 *********************************************************************/
2874 static jb_err client_uagent(struct client_state *csp, char **header)
2878 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2883 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2890 *header = strdup("User-Agent: ");
2891 string_append(header, newval);
2893 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2895 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2899 /*********************************************************************
2901 * Function : client_ua
2903 * Description : Handle "ua-" headers properly. Called from `sed'.
2906 * 1 : csp = Current client state (buffers, headers, etc...)
2907 * 2 : header = On input, pointer to header to modify.
2908 * On output, pointer to the modified header, or NULL
2909 * to remove the header. This function frees the
2910 * original string if necessary.
2912 * Returns : JB_ERR_OK on success, or
2913 * JB_ERR_MEMORY on out-of-memory error.
2915 *********************************************************************/
2916 static jb_err client_ua(struct client_state *csp, char **header)
2918 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2920 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2928 /*********************************************************************
2930 * Function : client_from
2932 * Description : Handle the "from" config setting properly.
2933 * Called from `sed'.
2936 * 1 : csp = Current client state (buffers, headers, etc...)
2937 * 2 : header = On input, pointer to header to modify.
2938 * On output, pointer to the modified header, or NULL
2939 * to remove the header. This function frees the
2940 * original string if necessary.
2942 * Returns : JB_ERR_OK on success, or
2943 * JB_ERR_MEMORY on out-of-memory error.
2945 *********************************************************************/
2946 static jb_err client_from(struct client_state *csp, char **header)
2950 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2957 newval = csp->action->string[ACTION_STRING_FROM];
2960 * Are we blocking the e-mail address?
2962 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2964 log_error(LOG_LEVEL_HEADER, "crunched From!");
2968 log_error(LOG_LEVEL_HEADER, " modified");
2970 *header = strdup("From: ");
2971 string_append(header, newval);
2973 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2977 /*********************************************************************
2979 * Function : client_send_cookie
2981 * Description : Crunches the "cookie" header if necessary.
2982 * Called from `sed'.
2984 * XXX: Stupid name, doesn't send squat.
2987 * 1 : csp = Current client state (buffers, headers, etc...)
2988 * 2 : header = On input, pointer to header to modify.
2989 * On output, pointer to the modified header, or NULL
2990 * to remove the header. This function frees the
2991 * original string if necessary.
2993 * Returns : JB_ERR_OK on success, or
2994 * JB_ERR_MEMORY on out-of-memory error.
2996 *********************************************************************/
2997 static jb_err client_send_cookie(struct client_state *csp, char **header)
2999 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3001 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3009 /*********************************************************************
3011 * Function : client_x_forwarded
3013 * Description : Handle the "x-forwarded-for" config setting properly,
3014 * also used in the add_client_headers list. Called from `sed'.
3017 * 1 : csp = Current client state (buffers, headers, etc...)
3018 * 2 : header = On input, pointer to header to modify.
3019 * On output, pointer to the modified header, or NULL
3020 * to remove the header. This function frees the
3021 * original string if necessary.
3023 * Returns : JB_ERR_OK on success, or
3024 * JB_ERR_MEMORY on out-of-memory error.
3026 *********************************************************************/
3027 jb_err client_x_forwarded(struct client_state *csp, char **header)
3029 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3031 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3033 if (0 == strcmpic(parameter, "block"))
3036 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3038 else if (0 == strcmpic(parameter, "add"))
3040 string_append(header, ", ");
3041 string_append(header, csp->ip_addr_str);
3043 if (*header == NULL)
3045 return JB_ERR_MEMORY;
3047 log_error(LOG_LEVEL_HEADER,
3048 "Appended client IP address to %s", *header);
3049 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3053 log_error(LOG_LEVEL_FATAL,
3054 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3062 /*********************************************************************
3064 * Function : client_max_forwards
3066 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3067 * from the value of the Max-Forwards header field.
3070 * 1 : csp = Current client state (buffers, headers, etc...)
3071 * 2 : header = On input, pointer to header to modify.
3072 * On output, pointer to the modified header, or NULL
3073 * to remove the header. This function frees the
3074 * original string if necessary.
3076 * Returns : JB_ERR_OK on success, or
3077 * JB_ERR_MEMORY on out-of-memory error.
3079 *********************************************************************/
3080 static jb_err client_max_forwards(struct client_state *csp, char **header)
3084 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3085 (0 == strcmpic(csp->http->gpc, "options")))
3087 assert(*(*header+12) == ':');
3088 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3090 if (max_forwards > 0)
3092 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3093 log_error(LOG_LEVEL_HEADER,
3094 "Max-Forwards value for %s request reduced to %d.",
3095 csp->http->gpc, max_forwards);
3097 else if (max_forwards < 0)
3099 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3105 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3114 /*********************************************************************
3116 * Function : client_host
3118 * Description : If the request URI did not contain host and
3119 * port information, parse and evaluate the Host
3122 * Also, kill ill-formed HOST: headers as sent by
3123 * Apple's iTunes software when used with a proxy.
3126 * 1 : csp = Current client state (buffers, headers, etc...)
3127 * 2 : header = On input, pointer to header to modify.
3128 * On output, pointer to the modified header, or NULL
3129 * to remove the header. This function frees the
3130 * original string if necessary.
3132 * Returns : JB_ERR_OK on success, or
3133 * JB_ERR_MEMORY on out-of-memory error.
3135 *********************************************************************/
3136 static jb_err client_host(struct client_state *csp, char **header)
3141 * If the header field name is all upper-case, chances are that it's
3142 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3143 * not a problem -- they are regenerated later.
3145 if ((*header)[1] == 'O')
3147 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3152 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3153 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3156 if (NULL == (p = strdup((*header)+6)))
3158 return JB_ERR_MEMORY;
3161 if (NULL == (q = strdup(p)))
3164 return JB_ERR_MEMORY;
3167 freez(csp->http->hostport);
3168 csp->http->hostport = p;
3169 freez(csp->http->host);
3170 csp->http->host = q;
3171 q = strchr(csp->http->host, ':');
3174 /* Terminate hostname and evaluate port string */
3176 csp->http->port = atoi(q);
3180 csp->http->port = csp->http->ssl ? 443 : 80;
3183 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3184 csp->http->hostport, csp->http->host, csp->http->port);
3187 /* Signal client_host_adder() to return right away */
3188 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3194 /*********************************************************************
3196 * Function : client_if_modified_since
3198 * Description : Remove or modify the If-Modified-Since header.
3201 * 1 : csp = Current client state (buffers, headers, etc...)
3202 * 2 : header = On input, pointer to header to modify.
3203 * On output, pointer to the modified header, or NULL
3204 * to remove the header. This function frees the
3205 * original string if necessary.
3207 * Returns : JB_ERR_OK on success, or
3208 * JB_ERR_MEMORY on out-of-memory error.
3210 *********************************************************************/
3211 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3214 #ifdef HAVE_GMTIME_R
3217 struct tm *timeptr = NULL;
3222 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3225 * The client got an error message because of a temporary problem,
3226 * the problem is gone and the client now tries to revalidate our
3227 * error message on the real server. The revalidation would always
3228 * end with the transmission of the whole document and there is
3229 * no need to expose the bogus If-Modified-Since header.
3231 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3234 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3236 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3238 if ((0 == strcmpic(newval, "block")))
3240 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3243 else /* add random value */
3245 const char *header_time = *header + sizeof("If-Modified-Since:");
3247 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3249 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3254 long int hours, minutes, seconds;
3255 long int rtime = strtol(newval, &endptr, 0);
3256 const int negative_range = (rtime < 0);
3260 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3261 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3267 rtime = pick_from_range(rtime);
3271 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3274 tm += rtime * (negative_range ? -1 : 1);
3275 #ifdef HAVE_GMTIME_R
3276 timeptr = gmtime_r(&tm, &gmt);
3277 #elif defined(MUTEX_LOCKS_AVAILABLE)
3278 privoxy_mutex_lock(&gmtime_mutex);
3279 timeptr = gmtime(&tm);
3280 privoxy_mutex_unlock(&gmtime_mutex);
3282 timeptr = gmtime(&tm);
3284 if ((NULL == timeptr) || !strftime(newheader,
3285 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3287 log_error(LOG_LEVEL_ERROR,
3288 "Randomizing '%s' failed. Crunching the header without replacement.",
3295 *header = strdup("If-Modified-Since: ");
3296 string_append(header, newheader);
3298 if (*header == NULL)
3300 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3301 return JB_ERR_MEMORY;
3304 hours = rtime / 3600;
3305 minutes = rtime / 60 % 60;
3306 seconds = rtime % 60;
3308 log_error(LOG_LEVEL_HEADER,
3309 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3310 *header, (negative_range) ? "subtracted" : "added", hours,
3311 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3312 seconds, (seconds == 1) ? ")" : "s)");
3321 /*********************************************************************
3323 * Function : client_if_none_match
3325 * Description : Remove the If-None-Match header.
3328 * 1 : csp = Current client state (buffers, headers, etc...)
3329 * 2 : header = On input, pointer to header to modify.
3330 * On output, pointer to the modified header, or NULL
3331 * to remove the header. This function frees the
3332 * original string if necessary.
3334 * Returns : JB_ERR_OK on success, or
3335 * JB_ERR_MEMORY on out-of-memory error.
3337 *********************************************************************/
3338 static jb_err client_if_none_match(struct client_state *csp, char **header)
3340 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3342 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3350 /*********************************************************************
3352 * Function : client_x_filter
3354 * Description : Disables filtering if the client set "X-Filter: No".
3355 * Called from `sed'.
3358 * 1 : csp = Current client state (buffers, headers, etc...)
3359 * 2 : header = On input, pointer to header to modify.
3360 * On output, pointer to the modified header, or NULL
3361 * to remove the header. This function frees the
3362 * original string if necessary.
3364 * Returns : JB_ERR_OK on success
3366 *********************************************************************/
3367 jb_err client_x_filter(struct client_state *csp, char **header)
3369 if ( 0 == strcmpic(*header, "X-Filter: No"))
3371 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3373 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3377 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3379 log_error(LOG_LEVEL_HEADER,
3380 "force-text-mode overruled the client's request to fetch without filtering!");
3384 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3385 csp->flags |= CSP_FLAG_NO_FILTERING;
3386 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3388 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3396 /*********************************************************************
3398 * Function : client_range
3400 * Description : Removes Range, Request-Range and If-Range headers if
3401 * content filtering is enabled. If the client's version
3402 * of the document has been altered by Privoxy, the server
3403 * could interpret the range differently than the client
3404 * intended in which case the user could end up with
3405 * corrupted content.
3408 * 1 : csp = Current client state (buffers, headers, etc...)
3409 * 2 : header = On input, pointer to header to modify.
3410 * On output, pointer to the modified header, or NULL
3411 * to remove the header. This function frees the
3412 * original string if necessary.
3414 * Returns : JB_ERR_OK
3416 *********************************************************************/
3417 static jb_err client_range(struct client_state *csp, char **header)
3419 if (content_filters_enabled(csp->action))
3421 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3422 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3429 /* the following functions add headers directly to the header list */
3431 /*********************************************************************
3433 * Function : client_host_adder
3435 * Description : Adds the Host: header field if it is missing.
3436 * Called from `sed'.
3439 * 1 : csp = Current client state (buffers, headers, etc...)
3441 * Returns : JB_ERR_OK on success, or
3442 * JB_ERR_MEMORY on out-of-memory error.
3444 *********************************************************************/
3445 static jb_err client_host_adder(struct client_state *csp)
3450 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3452 /* Header already set by the client, nothing to do. */
3456 if ( !csp->http->hostport || !*(csp->http->hostport))
3458 /* XXX: When does this happen and why is it OK? */
3459 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3464 * remove 'user:pass@' from 'proto://user:pass@host'
3466 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3472 p = csp->http->hostport;
3475 /* XXX: Just add it, we already made sure that it will be unique */
3476 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3477 err = enlist_unique_header(csp->headers, "Host", p);
3483 /*********************************************************************
3485 * Function : client_xtra_adder
3487 * Description : Used in the add_client_headers list. Called from `sed'.
3490 * 1 : csp = Current client state (buffers, headers, etc...)
3492 * Returns : JB_ERR_OK on success, or
3493 * JB_ERR_MEMORY on out-of-memory error.
3495 *********************************************************************/
3496 static jb_err client_xtra_adder(struct client_state *csp)
3498 struct list_entry *lst;
3501 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3502 lst ; lst = lst->next)
3504 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3505 err = enlist(csp->headers, lst->str);
3517 /*********************************************************************
3519 * Function : client_x_forwarded_for_adder
3521 * Description : Used in the add_client_headers list. Called from `sed'.
3524 * 1 : csp = Current client state (buffers, headers, etc...)
3526 * Returns : JB_ERR_OK on success, or
3527 * JB_ERR_MEMORY on out-of-memory error.
3529 *********************************************************************/
3530 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3532 char *header = NULL;
3535 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3536 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3537 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3540 * If we aren't adding X-Forwarded-For headers,
3541 * or we already appended an existing X-Forwarded-For
3542 * header, there's nothing left to do here.
3547 header = strdup("X-Forwarded-For: ");
3548 string_append(&header, csp->ip_addr_str);
3552 return JB_ERR_MEMORY;
3555 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3556 err = enlist(csp->headers, header);
3563 /*********************************************************************
3565 * Function : server_connection_adder
3567 * Description : Adds an appropriate "Connection:" header to csp->headers
3568 * unless the header was already present. Called from `sed'.
3571 * 1 : csp = Current client state (buffers, headers, etc...)
3573 * Returns : JB_ERR_OK on success, or
3574 * JB_ERR_MEMORY on out-of-memory error.
3576 *********************************************************************/
3577 static jb_err server_connection_adder(struct client_state *csp)
3579 const unsigned int flags = csp->flags;
3580 const char *response_status_line = csp->headers->first->str;
3581 static const char connection_close[] = "Connection: close";
3583 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3584 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3590 * XXX: if we downgraded the response, this check will fail.
3592 if ((csp->config->feature_flags &
3593 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3594 && (NULL != response_status_line)
3595 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3596 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3597 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3601 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3602 "without Connection header implies keep-alive.");
3603 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3607 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3609 return enlist(csp->headers, connection_close);
3613 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3614 /*********************************************************************
3616 * Function : server_proxy_connection_adder
3618 * Description : Adds a "Proxy-Connection: keep-alive" header to
3619 * csp->headers if the client asked for keep-alive.
3620 * XXX: We should reuse existent ones.
3623 * 1 : csp = Current client state (buffers, headers, etc...)
3625 * Returns : JB_ERR_OK on success, or
3626 * JB_ERR_MEMORY on out-of-memory error.
3628 *********************************************************************/
3629 static jb_err server_proxy_connection_adder(struct client_state *csp)
3631 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3632 jb_err err = JB_ERR_OK;
3634 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3635 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3636 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET))
3638 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3639 err = enlist(csp->headers, proxy_connection_header);
3644 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3647 /*********************************************************************
3649 * Function : client_connection_header_adder
3651 * Description : Adds a proper "Connection:" header to csp->headers
3652 * unless the header was already present. Called from `sed'.
3655 * 1 : csp = Current client state (buffers, headers, etc...)
3657 * Returns : JB_ERR_OK on success, or
3658 * JB_ERR_MEMORY on out-of-memory error.
3660 *********************************************************************/
3661 static jb_err client_connection_header_adder(struct client_state *csp)
3663 static const char connection_close[] = "Connection: close";
3665 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3666 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3671 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3672 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3673 && (csp->http->ssl == 0)
3674 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3676 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3679 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3681 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3683 return enlist(csp->headers, connection_close);
3687 /*********************************************************************
3689 * Function : server_http
3691 * Description : - Save the HTTP Status into csp->http->status
3692 * - Set CT_TABOO to prevent filtering if the answer
3693 * is a partial range (HTTP status 206)
3694 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3698 * 1 : csp = Current client state (buffers, headers, etc...)
3699 * 2 : header = On input, pointer to header to modify.
3700 * On output, pointer to the modified header, or NULL
3701 * to remove the header. This function frees the
3702 * original string if necessary.
3704 * Returns : JB_ERR_OK on success, or
3705 * JB_ERR_MEMORY on out-of-memory error.
3707 *********************************************************************/
3708 static jb_err server_http(struct client_state *csp, char **header)
3710 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3711 if (csp->http->status == 206)
3713 csp->content_type = CT_TABOO;
3716 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3718 /* XXX: Should we do a real validity check here? */
3719 if (strlen(*header) > 8)
3722 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3727 * XXX: Should we block the request or
3728 * enlist a valid status code line here?
3730 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3731 "Downgrading to HTTP/1.0 impossible.");
3739 /*********************************************************************
3741 * Function : server_set_cookie
3743 * Description : Handle the server "cookie" header properly.
3744 * Crunch, accept or rewrite it to a session cookie.
3745 * Called from `sed'.
3747 * TODO: Allow the user to specify a new expiration
3748 * time to cause the cookie to expire even before the
3749 * browser is closed.
3752 * 1 : csp = Current client state (buffers, headers, etc...)
3753 * 2 : header = On input, pointer to header to modify.
3754 * On output, pointer to the modified header, or NULL
3755 * to remove the header. This function frees the
3756 * original string if necessary.
3758 * Returns : JB_ERR_OK on success, or
3759 * JB_ERR_MEMORY on out-of-memory error.
3761 *********************************************************************/
3762 static jb_err server_set_cookie(struct client_state *csp, char **header)
3769 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3771 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3774 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3776 /* Flag whether or not to log a message */
3779 /* A variable to store the tag we're working on */
3782 /* Skip "Set-Cookie:" (11 characters) in header */
3783 cur_tag = *header + 11;
3785 /* skip whitespace between "Set-Cookie:" and value */
3786 while (*cur_tag && ijb_isspace(*cur_tag))
3791 /* Loop through each tag in the cookie */
3795 char *next_tag = strchr(cur_tag, ';');
3796 if (next_tag != NULL)
3798 /* Skip the ';' character itself */
3801 /* skip whitespace ";" and start of tag */
3802 while (*next_tag && ijb_isspace(*next_tag))
3809 /* "Next tag" is the end of the string */
3810 next_tag = cur_tag + strlen(cur_tag);
3814 * Check the expiration date to see
3815 * if the cookie is still valid, if yes,
3816 * rewrite it to a session cookie.
3818 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3820 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3822 if ((expiration_date[0] == '"')
3823 && (expiration_date[1] != '\0'))
3826 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
3827 * that the expiration date isn't supposed to be quoted,
3828 * but some servers do it anyway.
3833 /* Did we detect the date properly? */
3834 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3837 * Nope, treat it as if it was still valid.
3839 * XXX: Should we remove the whole cookie instead?
3841 log_error(LOG_LEVEL_ERROR,
3842 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3843 string_move(cur_tag, next_tag);
3849 * Yes. Check if the cookie is still valid.
3851 * If the cookie is already expired it's probably
3852 * a delete cookie and even if it isn't, the browser
3853 * will discard it anyway.
3857 * XXX: timegm() isn't available on some AmigaOS
3858 * versions and our replacement doesn't work.
3860 * Our options are to either:
3862 * - disable session-cookies-only completely if timegm
3865 * - to simply remove all expired tags, like it has
3866 * been done until Privoxy 3.0.6 and to live with
3867 * the consequence that it can cause login/logout
3868 * problems on servers that don't validate their
3869 * input properly, or
3871 * - to replace it with mktime in which
3872 * case there is a slight chance of valid cookies
3873 * passing as already expired.
3875 * This is the way it's currently done and it's not
3876 * as bad as it sounds. If the missing GMT offset is
3877 * enough to change the result of the expiration check
3878 * the cookie will be only valid for a few hours
3879 * anyway, which in many cases will be shorter
3880 * than a browser session.
3882 if (cookie_time - now < 0)
3884 log_error(LOG_LEVEL_HEADER,
3885 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3886 /* Just in case some clown sets more then one expiration date */
3892 * Still valid, delete expiration date by copying
3893 * the rest of the string over it.
3895 string_move(cur_tag, next_tag);
3897 /* That changed the header, need to issue a log message */
3901 * Note that the next tag has now been moved to *cur_tag,
3902 * so we do not need to update the cur_tag pointer.
3910 /* Move on to next cookie tag */
3917 assert(NULL != *header);
3918 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3927 #ifdef FEATURE_FORCE_LOAD
3928 /*********************************************************************
3930 * Function : strclean
3932 * Description : In-Situ-Eliminate all occurrences of substring in
3936 * 1 : string = string to clean
3937 * 2 : substring = substring to eliminate
3939 * Returns : Number of eliminations
3941 *********************************************************************/
3942 int strclean(char *string, const char *substring)
3948 len = strlen(substring);
3950 while((pos = strstr(string, substring)) != NULL)
3957 while (*p++ != '\0');
3964 #endif /* def FEATURE_FORCE_LOAD */
3967 /*********************************************************************
3969 * Function : parse_header_time
3971 * Description : Parses time formats used in HTTP header strings
3972 * to get the numerical respresentation.
3975 * 1 : header_time = HTTP header time as string.
3976 * 2 : result = storage for header_time in seconds
3978 * Returns : JB_ERR_OK if the time format was recognized, or
3979 * JB_ERR_PARSE otherwise.
3981 *********************************************************************/
3982 static jb_err parse_header_time(const char *header_time, time_t *result)
3986 * Checking for two-digit years first in an
3987 * attempt to work around GNU libc's strptime()
3988 * reporting negative year values when using %Y.
3990 static const char * const time_formats[] = {
3991 /* Tue, 02-Jun-37 20:00:00 */
3992 "%a, %d-%b-%y %H:%M:%S",
3993 /* Tue, 02 Jun 2037 20:00:00 */
3994 "%a, %d %b %Y %H:%M:%S",
3995 /* Tue, 02-Jun-2037 20:00:00 */
3996 "%a, %d-%b-%Y %H:%M:%S",
3997 /* Tuesday, 02-Jun-2037 20:00:00 */
3998 "%A, %d-%b-%Y %H:%M:%S",
3999 /* Tuesday Jun 02 20:00:00 2037 */
4000 "%A %b %d %H:%M:%S %Y"
4004 for (i = 0; i < SZ(time_formats); i++)
4007 * Zero out gmt to prevent time zone offsets.
4008 * Documented to be required for GNU libc.
4010 memset(&gmt, 0, sizeof(gmt));
4012 if (NULL != strptime(header_time, time_formats[i], &gmt))
4014 /* Sanity check for GNU libc. */
4015 if (gmt.tm_year < 0)
4017 log_error(LOG_LEVEL_HEADER,
4018 "Failed to parse '%s' using '%s'. Moving on.",
4019 header_time, time_formats[i]);
4022 *result = timegm(&gmt);
4027 return JB_ERR_PARSE;
4032 /*********************************************************************
4034 * Function : get_destination_from_headers
4036 * Description : Parse the "Host:" header to get the request's destination.
4037 * Only needed if the client's request was forcefully
4038 * redirected into Privoxy.
4040 * Code mainly copied from client_host() which is currently
4041 * run too late for this purpose.
4044 * 1 : headers = List of headers (one of them hopefully being
4045 * the "Host:" header)
4046 * 2 : http = storage for the result (host, port and hostport).
4048 * Returns : JB_ERR_MEMORY in case of memory problems,
4049 * JB_ERR_PARSE if the host header couldn't be found,
4050 * JB_ERR_OK otherwise.
4052 *********************************************************************/
4053 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4059 host = get_header_value(headers, "Host:");
4063 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4064 return JB_ERR_PARSE;
4070 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4071 return JB_ERR_MEMORY;
4074 if (NULL == (q = strdup(p)))
4077 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4078 return JB_ERR_MEMORY;
4081 freez(http->hostport);
4085 q = strchr(http->host, ':');
4088 /* Terminate hostname and evaluate port string */
4090 http->port = atoi(q);
4094 http->port = http->ssl ? 443 : 80;
4097 /* Rebuild request URL */
4099 http->url = strdup(http->ssl ? "https://" : "http://");
4100 string_append(&http->url, http->hostport);
4101 string_append(&http->url, http->path);
4102 if (http->url == NULL)
4104 return JB_ERR_MEMORY;
4107 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4115 /*********************************************************************
4117 * Function : create_forged_referrer
4119 * Description : Helper for client_referrer to forge a referer as
4120 * 'http://[hostname:port/' to fool stupid
4121 * checks for in-site links
4124 * 1 : header = Pointer to header pointer
4125 * 2 : hostport = Host and optionally port as string
4127 * Returns : JB_ERR_OK in case of success, or
4128 * JB_ERR_MEMORY in case of memory problems.
4130 *********************************************************************/
4131 static jb_err create_forged_referrer(char **header, const char *hostport)
4133 assert(NULL == *header);
4135 *header = strdup("Referer: http://");
4136 string_append(header, hostport);
4137 string_append(header, "/");
4139 if (NULL == *header)
4141 return JB_ERR_MEMORY;
4144 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4151 /*********************************************************************
4153 * Function : create_fake_referrer
4155 * Description : Helper for client_referrer to create a fake referrer
4156 * based on a string supplied by the user.
4159 * 1 : header = Pointer to header pointer
4160 * 2 : hosthost = Referrer to fake
4162 * Returns : JB_ERR_OK in case of success, or
4163 * JB_ERR_MEMORY in case of memory problems.
4165 *********************************************************************/
4166 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4168 assert(NULL == *header);
4170 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4172 log_error(LOG_LEVEL_HEADER,
4173 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4175 *header = strdup("Referer: ");
4176 string_append(header, fake_referrer);
4178 if (NULL == *header)
4180 return JB_ERR_MEMORY;
4183 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4190 /*********************************************************************
4192 * Function : handle_conditional_hide_referrer_parameter
4194 * Description : Helper for client_referrer to crunch or forge
4195 * the referrer header if the host has changed.
4198 * 1 : header = Pointer to header pointer
4199 * 2 : host = The target host (may include the port)
4200 * 3 : parameter_conditional_block = Boolean to signal
4201 * if we're in conditional-block mode. If not set,
4202 * we're in conditional-forge mode.
4204 * Returns : JB_ERR_OK in case of success, or
4205 * JB_ERR_MEMORY in case of memory problems.
4207 *********************************************************************/
4208 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4209 const char *host, const int parameter_conditional_block)
4211 char *referer = strdup(*header);
4212 const size_t hostlength = strlen(host);
4213 const char *referer_url = NULL;
4215 if (NULL == referer)
4218 return JB_ERR_MEMORY;
4221 /* referer begins with 'Referer: http[s]://' */
4222 if ((hostlength+17) < strlen(referer))
4225 * Shorten referer to make sure the referer is blocked
4226 * if www.example.org/www.example.com-shall-see-the-referer/
4227 * links to www.example.com/
4229 referer[hostlength+17] = '\0';
4231 referer_url = strstr(referer, "http://");
4232 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4234 /* Host has changed, Referer is invalid or a https URL. */
4235 if (parameter_conditional_block)
4237 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4244 return create_forged_referrer(header, host);
4254 /*********************************************************************
4256 * Function : create_content_length_header
4258 * Description : Creates a Content-Length header.
4261 * 1 : content_length = The content length to be used in the header.
4262 * 2 : header = Allocated space to safe the header.
4263 * 3 : buffer_length = The length of the allocated space.
4267 *********************************************************************/
4268 static void create_content_length_header(unsigned long long content_length,
4269 char *header, size_t buffer_length)
4271 snprintf(header, buffer_length, "Content-Length: %llu", content_length);