1 const char parsers_rcs[] = "$Id: parsers.c,v 1.172 2009/06/01 16:34:48 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2009 the
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
45 *********************************************************************/
52 #include <sys/types.h>
62 * Convince GNU's libc to provide a strptime prototype.
71 #define GZIP_IDENTIFIER_1 0x1f
72 #define GZIP_IDENTIFIER_2 0x8b
74 #define GZIP_FLAG_CHECKSUM 0x02
75 #define GZIP_FLAG_EXTRA_FIELDS 0x04
76 #define GZIP_FLAG_FILE_NAME 0x08
77 #define GZIP_FLAG_COMMENT 0x10
78 #define GZIP_FLAG_RESERVED_BITS 0xe0
81 #if !defined(_WIN32) && !defined(__OS2__)
87 #ifdef FEATURE_PTHREAD
89 /* jcc.h is for mutex semapores only */
90 #endif /* def FEATURE_PTHREAD */
95 #include "jbsockets.h"
101 #ifndef HAVE_STRPTIME
102 #include "strptime.h"
105 const char parsers_h_rcs[] = PARSERS_H_VERSION;
107 /* Fix a problem with Solaris. There should be no effect on other
109 * Solaris's isspace() is a macro which uses its argument directly
110 * as an array index. Therefore we need to make sure that high-bit
111 * characters generate +ve values, and ideally we also want to make
112 * the argument match the declared parameter type of "int".
114 * Why did they write a character function that can't take a simple
115 * "char" argument? Doh!
117 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
118 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
120 static char *get_header_line(struct iob *iob);
121 static jb_err scan_headers(struct client_state *csp);
122 static jb_err header_tagger(struct client_state *csp, char *header);
123 static jb_err parse_header_time(const char *header_time, time_t *result);
125 static jb_err crumble (struct client_state *csp, char **header);
126 static jb_err filter_header (struct client_state *csp, char **header);
127 static jb_err client_connection (struct client_state *csp, char **header);
128 static jb_err client_referrer (struct client_state *csp, char **header);
129 static jb_err client_uagent (struct client_state *csp, char **header);
130 static jb_err client_ua (struct client_state *csp, char **header);
131 static jb_err client_from (struct client_state *csp, char **header);
132 static jb_err client_send_cookie (struct client_state *csp, char **header);
133 static jb_err client_x_forwarded (struct client_state *csp, char **header);
134 static jb_err client_accept_encoding (struct client_state *csp, char **header);
135 static jb_err client_te (struct client_state *csp, char **header);
136 static jb_err client_max_forwards (struct client_state *csp, char **header);
137 static jb_err client_host (struct client_state *csp, char **header);
138 static jb_err client_if_modified_since (struct client_state *csp, char **header);
139 static jb_err client_accept_language (struct client_state *csp, char **header);
140 static jb_err client_if_none_match (struct client_state *csp, char **header);
141 static jb_err crunch_client_header (struct client_state *csp, char **header);
142 static jb_err client_x_filter (struct client_state *csp, char **header);
143 static jb_err client_range (struct client_state *csp, char **header);
144 static jb_err server_set_cookie (struct client_state *csp, char **header);
145 static jb_err server_connection (struct client_state *csp, char **header);
146 static jb_err server_content_type (struct client_state *csp, char **header);
147 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
148 static jb_err server_content_md5 (struct client_state *csp, char **header);
149 static jb_err server_content_encoding (struct client_state *csp, char **header);
150 static jb_err server_transfer_coding (struct client_state *csp, char **header);
151 static jb_err server_http (struct client_state *csp, char **header);
152 static jb_err crunch_server_header (struct client_state *csp, char **header);
153 static jb_err server_last_modified (struct client_state *csp, char **header);
154 static jb_err server_content_disposition(struct client_state *csp, char **header);
156 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
157 static jb_err server_save_content_length(struct client_state *csp, char **header);
158 static jb_err server_keep_alive(struct client_state *csp, char **header);
159 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
161 static jb_err client_host_adder (struct client_state *csp);
162 static jb_err client_xtra_adder (struct client_state *csp);
163 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
164 static jb_err client_connection_header_adder(struct client_state *csp);
165 static jb_err server_connection_adder(struct client_state *csp);
166 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
167 static jb_err server_proxy_connection_adder(struct client_state *csp);
168 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
170 static jb_err create_forged_referrer(char **header, const char *hostport);
171 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
172 static jb_err handle_conditional_hide_referrer_parameter(char **header,
173 const char *host, const int parameter_conditional_block);
174 static const char *get_appropiate_connection_header(const struct client_state *csp);
177 * List of functions to run on a list of headers.
181 /** The header prefix to match */
184 /** The length of the prefix to match */
187 /** The function to apply to this line */
188 const parser_func_ptr parser;
191 static const struct parsers client_patterns[] = {
192 { "referer:", 8, client_referrer },
193 { "user-agent:", 11, client_uagent },
194 { "ua-", 3, client_ua },
195 { "from:", 5, client_from },
196 { "cookie:", 7, client_send_cookie },
197 { "x-forwarded-for:", 16, client_x_forwarded },
198 { "Accept-Encoding:", 16, client_accept_encoding },
199 { "TE:", 3, client_te },
200 { "Host:", 5, client_host },
201 { "if-modified-since:", 18, client_if_modified_since },
202 #ifndef FEATURE_CONNECTION_KEEP_ALIVE
203 { "Keep-Alive:", 11, crumble },
205 { "connection:", 11, client_connection },
206 { "proxy-connection:", 17, crumble },
207 { "max-forwards:", 13, client_max_forwards },
208 { "Accept-Language:", 16, client_accept_language },
209 { "if-none-match:", 14, client_if_none_match },
210 { "Range:", 6, client_range },
211 { "Request-Range:", 14, client_range },
212 { "If-Range:", 9, client_range },
213 { "X-Filter:", 9, client_x_filter },
214 { "*", 0, crunch_client_header },
215 { "*", 0, filter_header },
219 static const struct parsers server_patterns[] = {
220 { "HTTP/", 5, server_http },
221 { "set-cookie:", 11, server_set_cookie },
222 { "connection:", 11, server_connection },
223 { "Content-Type:", 13, server_content_type },
224 { "Content-MD5:", 12, server_content_md5 },
225 { "Content-Encoding:", 17, server_content_encoding },
226 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
227 { "Content-Length:", 15, server_save_content_length },
228 { "Keep-Alive:", 11, server_keep_alive },
230 { "Keep-Alive:", 11, crumble },
231 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
232 { "Transfer-Encoding:", 18, server_transfer_coding },
233 { "content-disposition:", 20, server_content_disposition },
234 { "Last-Modified:", 14, server_last_modified },
235 { "*", 0, crunch_server_header },
236 { "*", 0, filter_header },
240 static const add_header_func_ptr add_client_headers[] = {
242 client_x_forwarded_for_adder,
244 /* Temporarily disabled: client_accept_encoding_adder, */
245 client_connection_header_adder,
249 static const add_header_func_ptr add_server_headers[] = {
250 server_connection_adder,
251 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
252 server_proxy_connection_adder,
253 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
257 /*********************************************************************
259 * Function : flush_socket
261 * Description : Write any pending "buffered" content.
264 * 1 : fd = file descriptor of the socket to read
265 * 2 : iob = The I/O buffer to flush, usually csp->iob.
267 * Returns : On success, the number of bytes written are returned (zero
268 * indicates nothing was written). On error, -1 is returned,
269 * and errno is set appropriately. If count is zero and the
270 * file descriptor refers to a regular file, 0 will be
271 * returned without causing any other effect. For a special
272 * file, the results are not portable.
274 *********************************************************************/
275 long flush_socket(jb_socket fd, struct iob *iob)
277 long len = iob->eod - iob->cur;
284 if (write_socket(fd, iob->cur, (size_t)len))
288 iob->eod = iob->cur = iob->buf;
294 /*********************************************************************
296 * Function : add_to_iob
298 * Description : Add content to the buffered page, expanding the
299 * buffer if necessary.
302 * 1 : csp = Current client state (buffers, headers, etc...)
303 * 2 : buf = holds the content to be added to the page
304 * 3 : n = number of bytes to be added
306 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
307 * or buffer limit reached.
309 *********************************************************************/
310 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
312 struct iob *iob = csp->iob;
313 size_t used, offset, need, want;
316 if (n <= 0) return JB_ERR_OK;
318 used = (size_t)(iob->eod - iob->buf);
319 offset = (size_t)(iob->cur - iob->buf);
320 need = used + (size_t)n + 1;
323 * If the buffer can't hold the new data, extend it first.
324 * Use the next power of two if possible, else use the actual need.
326 if (need > csp->config->buffer_limit)
328 log_error(LOG_LEVEL_INFO,
329 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
330 need, csp->config->buffer_limit);
331 return JB_ERR_MEMORY;
334 if (need > iob->size)
336 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
338 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
342 else if (NULL != (p = (char *)realloc(iob->buf, need)))
348 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
349 return JB_ERR_MEMORY;
352 /* Update the iob pointers */
353 iob->cur = p + offset;
358 /* copy the new data into the iob buffer */
359 memcpy(iob->eod, buf, (size_t)n);
361 /* point to the end of the data */
364 /* null terminate == cheap insurance */
373 /*********************************************************************
375 * Function : decompress_iob
377 * Description : Decompress buffered page, expanding the
378 * buffer as necessary. csp->iob->cur
379 * should point to the the beginning of the
380 * compressed data block.
383 * 1 : csp = Current client state (buffers, headers, etc...)
385 * Returns : JB_ERR_OK on success,
386 * JB_ERR_MEMORY if out-of-memory limit reached, and
387 * JB_ERR_COMPRESS if error decompressing buffer.
389 *********************************************************************/
390 jb_err decompress_iob(struct client_state *csp)
392 char *buf; /* new, uncompressed buffer */
393 char *cur; /* Current iob position (to keep the original
394 * iob->cur unmodified if we return early) */
395 size_t bufsize; /* allocated size of the new buffer */
396 size_t old_size; /* Content size before decompression */
397 size_t skip_size; /* Number of bytes at the beginning of the iob
398 that we should NOT decompress. */
399 int status; /* return status of the inflate() call */
400 z_stream zstr; /* used by calls to zlib */
402 assert(csp->iob->cur - csp->iob->buf > 0);
403 assert(csp->iob->eod - csp->iob->cur > 0);
405 bufsize = csp->iob->size;
406 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
407 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
411 if (bufsize < (size_t)10)
414 * This is to protect the parsing of gzipped data,
415 * but it should(?) be valid for deflated data also.
417 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
418 return JB_ERR_COMPRESS;
421 if (csp->content_type & CT_GZIP)
424 * Our task is slightly complicated by the facts that data
425 * compressed by gzip does not include a zlib header, and
426 * that there is no easily accessible interface in zlib to
427 * handle a gzip header. We strip off the gzip header by
428 * hand, and later inform zlib not to expect a header.
432 * Strip off the gzip header. Please see RFC 1952 for more
433 * explanation of the appropriate fields.
435 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
436 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
437 || (*cur++ != Z_DEFLATED))
439 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
440 return JB_ERR_COMPRESS;
445 if (flags & GZIP_FLAG_RESERVED_BITS)
447 /* The gzip header has reserved bits set; bail out. */
448 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
449 return JB_ERR_COMPRESS;
453 /* Skip extra fields if necessary. */
454 if (flags & GZIP_FLAG_EXTRA_FIELDS)
457 * Skip a given number of bytes, specified
458 * as a 16-bit little-endian value.
460 * XXX: this code is untested and should probably be removed.
464 skip_bytes += *cur++ << 8;
467 * The number of bytes to skip should be positive
468 * and we'd like to stay in the buffer.
470 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
472 log_error(LOG_LEVEL_ERROR,
473 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
475 return JB_ERR_COMPRESS;
477 log_error(LOG_LEVEL_INFO,
478 "Skipping %d bytes for gzip compression. Does this sound right?",
483 /* Skip the filename if necessary. */
484 if (flags & GZIP_FLAG_FILE_NAME)
486 /* A null-terminated string is supposed to follow. */
487 while (*cur++ && (cur < csp->iob->eod));
491 /* Skip the comment if necessary. */
492 if (flags & GZIP_FLAG_COMMENT)
494 /* A null-terminated string is supposed to follow. */
495 while (*cur++ && (cur < csp->iob->eod));
498 /* Skip the CRC if necessary. */
499 if (flags & GZIP_FLAG_CHECKSUM)
504 if (cur >= csp->iob->eod)
507 * If the current position pointer reached or passed
508 * the buffer end, we were obviously tricked to skip
511 log_error(LOG_LEVEL_ERROR,
512 "Malformed gzip header detected. Aborting decompression.");
513 return JB_ERR_COMPRESS;
517 else if (csp->content_type & CT_DEFLATE)
520 * XXX: The debug level should be lowered
521 * before the next stable release.
523 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
525 * In theory (that is, according to RFC 1950), deflate-compressed
526 * data should begin with a two-byte zlib header and have an
527 * adler32 checksum at the end. It seems that in practice only
528 * the raw compressed data is sent. Note that this means that
529 * we are not RFC 1950-compliant here, but the advantage is that
530 * this actually works. :)
532 * We add a dummy null byte to tell zlib where the data ends,
533 * and later inform it not to expect a header.
535 * Fortunately, add_to_iob() has thoughtfully null-terminated
536 * the buffer; we can just increment the end pointer to include
543 log_error(LOG_LEVEL_ERROR,
544 "Unable to determine compression format for decompression");
545 return JB_ERR_COMPRESS;
548 /* Set up the fields required by zlib. */
549 zstr.next_in = (Bytef *)cur;
550 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
551 zstr.zalloc = Z_NULL;
553 zstr.opaque = Z_NULL;
556 * Passing -MAX_WBITS to inflateInit2 tells the library
557 * that there is no zlib header.
559 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
561 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
562 return JB_ERR_COMPRESS;
566 * Next, we allocate new storage for the inflated data.
567 * We don't modify the existing iob yet, so in case there
568 * is error in decompression we can recover gracefully.
570 buf = zalloc(bufsize);
573 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
574 return JB_ERR_MEMORY;
577 assert(bufsize >= skip_size);
578 memcpy(buf, csp->iob->buf, skip_size);
579 zstr.avail_out = bufsize - skip_size;
580 zstr.next_out = (Bytef *)buf + skip_size;
582 /* Try to decompress the whole stream in one shot. */
583 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
585 /* We need to allocate more memory for the output buffer. */
587 char *tmpbuf; /* used for realloc'ing the buffer */
588 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
590 if (0 == zstr.avail_in)
593 * If zlib wants more data then there's a problem, because
594 * the complete compressed file should have been buffered.
596 log_error(LOG_LEVEL_ERROR,
597 "Unexpected end of compressed iob. Using what we got so far.");
602 * If we tried the limit and still didn't have enough
603 * memory, just give up.
605 if (bufsize == csp->config->buffer_limit)
607 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
608 return JB_ERR_MEMORY;
611 /* Try doubling the buffer size each time. */
614 /* Don't exceed the buffer limit. */
615 if (bufsize > csp->config->buffer_limit)
617 bufsize = csp->config->buffer_limit;
620 /* Try to allocate the new buffer. */
621 tmpbuf = realloc(buf, bufsize);
624 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
626 return JB_ERR_MEMORY;
630 char *oldnext_out = (char *)zstr.next_out;
633 * Update the fields for inflate() to use the new
634 * buffer, which may be in a location different from
637 zstr.avail_out += bufsize - oldbufsize;
638 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
641 * Compare with an uglier method of calculating these values
642 * that doesn't require the extra oldbufsize variable.
644 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
645 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
646 assert(zstr.avail_out > 0U);
652 if (Z_STREAM_ERROR == inflateEnd(&zstr))
654 log_error(LOG_LEVEL_ERROR,
655 "Inconsistent stream state after decompression: %s", zstr.msg);
657 * XXX: Intentionally no return.
659 * According to zlib.h, Z_STREAM_ERROR is returned
660 * "if the stream state was inconsistent".
662 * I assume in this case inflate()'s status
663 * would also be something different than Z_STREAM_END
664 * so this check should be redundant, but lets see.
668 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
671 * We failed to decompress the stream and it's
672 * not simply because of missing data.
674 log_error(LOG_LEVEL_ERROR,
675 "Unexpected error while decompressing to the buffer (iob): %s",
677 return JB_ERR_COMPRESS;
681 * Finally, we can actually update the iob, since the
682 * decompression was successful. First, free the old
685 freez(csp->iob->buf);
687 /* Now, update the iob to use the new buffer. */
689 csp->iob->cur = csp->iob->buf + skip_size;
690 csp->iob->eod = (char *)zstr.next_out;
691 csp->iob->size = bufsize;
694 * Make sure the new uncompressed iob obeys some minimal
695 * consistency conditions.
697 if ((csp->iob->buf < csp->iob->cur)
698 && (csp->iob->cur <= csp->iob->eod)
699 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
701 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
702 if (new_size > (size_t)0)
704 log_error(LOG_LEVEL_RE_FILTER,
705 "Decompression successful. Old size: %d, new size: %d.",
710 /* zlib thinks this is OK, so lets do the same. */
711 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
716 /* It seems that zlib did something weird. */
717 log_error(LOG_LEVEL_ERROR,
718 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
719 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
720 csp->iob->eod, csp->iob->buf + csp->iob->size);
721 return JB_ERR_COMPRESS;
727 #endif /* defined(FEATURE_ZLIB) */
730 /*********************************************************************
732 * Function : string_move
734 * Description : memmove wrapper to move the last part of a string
735 * towards the beginning, overwriting the part in
736 * the middle. strlcpy() can't be used here as the
740 * 1 : dst = Destination to overwrite
741 * 2 : src = Source to move.
745 *********************************************************************/
746 static void string_move(char *dst, char *src)
750 /* +1 to copy the terminating nul as well. */
751 memmove(dst, src, strlen(src)+1);
755 /*********************************************************************
757 * Function : normalize_lws
759 * Description : Reduces unquoted linear white space in headers
760 * to a single space in accordance with RFC 2616 2.2.
761 * This simplifies parsing and filtering later on.
763 * XXX: Remove log messages before
764 * the next stable release?
767 * 1 : header = A header with linear white space to reduce.
771 *********************************************************************/
772 static void normalize_lws(char *header)
778 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
782 while (ijb_isspace(*q))
786 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
792 log_error(LOG_LEVEL_HEADER,
793 "Converting tab to space in '%s'", header);
798 char *end_of_token = strstr(p+1, "\"");
800 if (NULL != end_of_token)
802 /* Don't mess with quoted text. */
807 log_error(LOG_LEVEL_HEADER,
808 "Ignoring single quote in '%s'", header);
814 p = strchr(header, ':');
815 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
818 * There's still space before the colon.
826 /*********************************************************************
828 * Function : get_header
830 * Description : This (odd) routine will parse the csp->iob
831 * to get the next complete header.
834 * 1 : iob = The I/O buffer to parse, usually csp->iob.
836 * Returns : Any one of the following:
838 * 1) a pointer to a dynamically allocated string that contains a header line
839 * 2) NULL indicating that the end of the header was reached
840 * 3) "" indicating that the end of the iob was reached before finding
841 * a complete header line.
843 *********************************************************************/
844 char *get_header(struct iob *iob)
848 header = get_header_line(iob);
850 if ((header == NULL) || (*header == '\0'))
853 * No complete header read yet, tell the client.
858 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
861 * Header spans multiple lines, append the next one.
863 char *continued_header;
865 continued_header = get_header_line(iob);
866 if ((continued_header == NULL) || (*continued_header == '\0'))
869 * No complete header read yet, return what we got.
870 * XXX: Should "unread" header instead.
872 log_error(LOG_LEVEL_INFO,
873 "Failed to read a multi-line header properly: '%s'",
878 if (JB_ERR_OK != string_join(&header, continued_header))
880 log_error(LOG_LEVEL_FATAL,
881 "Out of memory while appending multiple headers.");
885 /* XXX: remove before next stable release. */
886 log_error(LOG_LEVEL_HEADER,
887 "Merged multiple header lines to: '%s'",
892 normalize_lws(header);
899 /*********************************************************************
901 * Function : get_header_line
903 * Description : This (odd) routine will parse the csp->iob
904 * to get the next header line.
907 * 1 : iob = The I/O buffer to parse, usually csp->iob.
909 * Returns : Any one of the following:
911 * 1) a pointer to a dynamically allocated string that contains a header line
912 * 2) NULL indicating that the end of the header was reached
913 * 3) "" indicating that the end of the iob was reached before finding
914 * a complete header line.
916 *********************************************************************/
917 static char *get_header_line(struct iob *iob)
921 if ((iob->cur == NULL)
922 || ((p = strchr(iob->cur, '\n')) == NULL))
924 return(""); /* couldn't find a complete header */
929 ret = strdup(iob->cur);
932 /* FIXME No way to handle error properly */
933 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
939 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
941 /* is this a blank line (i.e. the end of the header) ? */
953 /*********************************************************************
955 * Function : get_header_value
957 * Description : Get the value of a given header from a chained list
958 * of header lines or return NULL if no such header is
959 * present in the list.
962 * 1 : header_list = pointer to list
963 * 2 : header_name = string with name of header to look for.
964 * Trailing colon required, capitalization
967 * Returns : NULL if not found, else value of header
969 *********************************************************************/
970 char *get_header_value(const struct list *header_list, const char *header_name)
972 struct list_entry *cur_entry;
978 length = strlen(header_name);
980 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
984 if (!strncmpic(cur_entry->str, header_name, length))
987 * Found: return pointer to start of value
989 ret = cur_entry->str + length;
990 while (*ret && ijb_isspace(*ret)) ret++;
1004 /*********************************************************************
1006 * Function : scan_headers
1008 * Description : Scans headers, applies tags and updates action bits.
1011 * 1 : csp = Current client state (buffers, headers, etc...)
1013 * Returns : JB_ERR_OK
1015 *********************************************************************/
1016 static jb_err scan_headers(struct client_state *csp)
1018 struct list_entry *h; /* Header */
1019 jb_err err = JB_ERR_OK;
1021 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1023 /* Header crunch()ed in previous run? -> ignore */
1024 if (h->str == NULL) continue;
1025 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1026 err = header_tagger(csp, h->str);
1033 /*********************************************************************
1037 * Description : add, delete or modify lines in the HTTP header streams.
1038 * On entry, it receives a linked list of headers space
1039 * that was allocated dynamically (both the list nodes
1040 * and the header contents).
1042 * As a side effect it frees the space used by the original
1046 * 1 : csp = Current client state (buffers, headers, etc...)
1047 * 2 : filter_server_headers = Boolean to switch between
1048 * server and header filtering.
1050 * Returns : JB_ERR_OK in case off success, or
1051 * JB_ERR_MEMORY on out-of-memory error.
1053 *********************************************************************/
1054 jb_err sed(struct client_state *csp, int filter_server_headers)
1056 /* XXX: use more descriptive names. */
1057 struct list_entry *p;
1058 const struct parsers *v;
1059 const add_header_func_ptr *f;
1060 jb_err err = JB_ERR_OK;
1062 if (filter_server_headers)
1064 v = server_patterns;
1065 f = add_server_headers;
1069 v = client_patterns;
1070 f = add_client_headers;
1075 while ((err == JB_ERR_OK) && (v->str != NULL))
1077 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1079 /* Header crunch()ed in previous run? -> ignore */
1080 if (p->str == NULL) continue;
1082 /* Does the current parser handle this header? */
1083 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1084 (v->len == CHECK_EVERY_HEADER_REMAINING))
1086 err = v->parser(csp, &(p->str));
1092 /* place additional headers on the csp->headers list */
1093 while ((err == JB_ERR_OK) && (*f))
1103 /*********************************************************************
1105 * Function : update_server_headers
1107 * Description : Updates server headers after the body has been modified.
1110 * 1 : csp = Current client state (buffers, headers, etc...)
1112 * Returns : JB_ERR_OK in case off success, or
1113 * JB_ERR_MEMORY on out-of-memory error.
1115 *********************************************************************/
1116 jb_err update_server_headers(struct client_state *csp)
1118 jb_err err = JB_ERR_OK;
1120 static const struct parsers server_patterns_light[] = {
1121 { "Content-Length:", 15, server_adjust_content_length },
1122 { "Transfer-Encoding:", 18, server_transfer_coding },
1124 { "Content-Encoding:", 17, server_content_encoding },
1125 #endif /* def FEATURE_ZLIB */
1129 if (strncmpic(csp->http->cmd, "HEAD", 4))
1131 const struct parsers *v;
1132 struct list_entry *p;
1134 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1136 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1138 /* Header crunch()ed in previous run? -> ignore */
1139 if (p->str == NULL) continue;
1141 /* Does the current parser handle this header? */
1142 if (strncmpic(p->str, v->str, v->len) == 0)
1144 err = v->parser(csp, (char **)&(p->str));
1154 /*********************************************************************
1156 * Function : header_tagger
1158 * Description : Executes all text substitutions from applying
1159 * tag actions and saves the result as tag.
1161 * XXX: Shares enough code with filter_header() and
1162 * pcrs_filter_response() to warrant some helper functions.
1165 * 1 : csp = Current client state (buffers, headers, etc...)
1166 * 2 : header = Header that is used as tagger input
1168 * Returns : JB_ERR_OK on success and always succeeds
1170 *********************************************************************/
1171 static jb_err header_tagger(struct client_state *csp, char *header)
1173 int wanted_filter_type;
1174 int multi_action_index;
1178 struct file_list *fl;
1179 struct re_filterfile_spec *b;
1180 struct list_entry *tag_name;
1182 int found_filters = 0;
1183 const size_t header_length = strlen(header);
1185 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1187 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1188 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1192 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1193 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1196 /* Check if there are any filters */
1197 for (i = 0; i < MAX_AF_FILES; i++)
1210 if (0 == found_filters)
1212 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1213 "tagging enabled, but no taggers available.");
1217 for (i = 0; i < MAX_AF_FILES; i++)
1220 if ((NULL == fl) || (NULL == fl->f))
1223 * Either there are no filter files
1224 * left, or this filter file just
1225 * contains no valid filters.
1227 * Continue to be sure we don't miss
1228 * valid filter files that are chained
1229 * after empty or invalid ones.
1234 /* For all filters, */
1235 for (b = fl->f; b; b = b->next)
1237 if (b->type != wanted_filter_type)
1239 /* skip the ones we don't care about, */
1242 /* leaving only taggers that could apply, of which we use the ones, */
1243 for (tag_name = csp->action->multi[multi_action_index]->first;
1244 NULL != tag_name; tag_name = tag_name->next)
1246 /* that do apply, and */
1247 if (strcmp(b->name, tag_name->str) == 0)
1249 char *modified_tag = NULL;
1251 size_t size = header_length;
1252 pcrs_job *joblist = b->joblist;
1254 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1256 if (NULL == joblist)
1258 log_error(LOG_LEVEL_RE_FILTER,
1259 "Tagger %s has empty joblist. Nothing to do.", b->name);
1263 /* execute their pcrs_joblist on the header. */
1264 for (job = joblist; NULL != job; job = job->next)
1266 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1270 /* Success, continue with the modified version. */
1279 /* Tagger doesn't match */
1282 /* Regex failure, log it but continue anyway. */
1283 assert(NULL != header);
1284 log_error(LOG_LEVEL_ERROR,
1285 "Problems with tagger \'%s\' and header \'%s\': %s",
1286 b->name, *header, pcrs_strerror(hits));
1288 freez(modified_tag);
1292 if (b->dynamic) pcrs_free_joblist(joblist);
1294 /* If this tagger matched */
1300 * There is to technical limitation which makes
1301 * it impossible to use empty tags, but I assume
1302 * no one would do it intentionally.
1305 log_error(LOG_LEVEL_INFO,
1306 "Tagger \'%s\' created an empty tag. Ignored.",
1311 if (!list_contains_item(csp->tags, tag))
1313 if (JB_ERR_OK != enlist(csp->tags, tag))
1315 log_error(LOG_LEVEL_ERROR,
1316 "Insufficient memory to add tag \'%s\', "
1317 "based on tagger \'%s\' and header \'%s\'",
1318 tag, b->name, *header);
1322 char *action_message;
1324 * update the action bits right away, to make
1325 * tagging based on tags set by earlier taggers
1326 * of the same kind possible.
1328 if (update_action_bits_for_tag(csp, tag))
1330 action_message = "Action bits updated accordingly.";
1334 action_message = "No action bits update necessary.";
1337 log_error(LOG_LEVEL_HEADER,
1338 "Tagger \'%s\' added tag \'%s\'. %s",
1339 b->name, tag, action_message);
1344 /* XXX: Is this log-worthy? */
1345 log_error(LOG_LEVEL_HEADER,
1346 "Tagger \'%s\' didn't add tag \'%s\'. "
1347 "Tag already present", b->name, tag);
1350 } /* if the tagger matched */
1351 } /* if the tagger applies */
1352 } /* for every tagger that could apply */
1353 } /* for all filters */
1354 } /* for all filter files */
1359 /* here begins the family of parser functions that reformat header lines */
1361 /*********************************************************************
1363 * Function : filter_header
1365 * Description : Executes all text substitutions from all applying
1366 * +(server|client)-header-filter actions on the header.
1367 * Most of the code was copied from pcrs_filter_response,
1368 * including the rather short variable names
1371 * 1 : csp = Current client state (buffers, headers, etc...)
1372 * 2 : header = On input, pointer to header to modify.
1373 * On output, pointer to the modified header, or NULL
1374 * to remove the header. This function frees the
1375 * original string if necessary.
1377 * Returns : JB_ERR_OK on success and always succeeds
1379 *********************************************************************/
1380 static jb_err filter_header(struct client_state *csp, char **header)
1384 size_t size = strlen(*header);
1386 char *newheader = NULL;
1389 struct file_list *fl;
1390 struct re_filterfile_spec *b;
1391 struct list_entry *filtername;
1393 int i, found_filters = 0;
1394 int wanted_filter_type;
1395 int multi_action_index;
1397 if (csp->flags & CSP_FLAG_NO_FILTERING)
1402 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1404 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1405 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1409 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1410 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1414 * Need to check the set of re_filterfiles...
1416 for (i = 0; i < MAX_AF_FILES; i++)
1429 if (0 == found_filters)
1431 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1432 "header filtering enabled, but no matching filters available.");
1436 for (i = 0; i < MAX_AF_FILES; i++)
1439 if ((NULL == fl) || (NULL == fl->f))
1442 * Either there are no filter files
1443 * left, or this filter file just
1444 * contains no valid filters.
1446 * Continue to be sure we don't miss
1447 * valid filter files that are chained
1448 * after empty or invalid ones.
1453 * For all applying +filter actions, look if a filter by that
1454 * name exists and if yes, execute its pcrs_joblist on the
1457 for (b = fl->f; b; b = b->next)
1459 if (b->type != wanted_filter_type)
1461 /* Skip other filter types */
1465 for (filtername = csp->action->multi[multi_action_index]->first;
1466 filtername ; filtername = filtername->next)
1468 if (strcmp(b->name, filtername->str) == 0)
1470 int current_hits = 0;
1471 pcrs_job *joblist = b->joblist;
1473 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1475 if (NULL == joblist)
1477 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1481 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1482 *header, size, b->name);
1484 /* Apply all jobs from the joblist */
1485 for (job = joblist; NULL != job; job = job->next)
1487 matches = pcrs_execute(job, *header, size, &newheader, &size);
1490 current_hits += matches;
1491 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1493 *header = newheader;
1495 else if ( 0 == matches )
1497 /* Filter doesn't change header */
1503 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1504 *header, b->name, pcrs_strerror(matches));
1505 if (newheader != NULL)
1507 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1513 if (b->dynamic) pcrs_free_joblist(joblist);
1515 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1516 hits += current_hits;
1523 * Additionally checking for hits is important because if
1524 * the continue hack is triggered, server headers can
1525 * arrive empty to separate multiple heads from each other.
1527 if ((0 == size) && hits)
1529 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1537 /*********************************************************************
1539 * Function : server_connection
1541 * Description : Makes sure a proper "Connection:" header is
1542 * set and signals connection_header_adder to
1546 * 1 : csp = Current client state (buffers, headers, etc...)
1547 * 2 : header = On input, pointer to header to modify.
1548 * On output, pointer to the modified header, or NULL
1549 * to remove the header. This function frees the
1550 * original string if necessary.
1552 * Returns : JB_ERR_OK on success, or
1553 * JB_ERR_MEMORY on out-of-memory error.
1555 *********************************************************************/
1556 static jb_err server_connection(struct client_state *csp, char **header)
1558 if (!strcmpic(*header, "Connection: keep-alive"))
1560 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1561 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1563 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1566 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1568 log_error(LOG_LEVEL_HEADER,
1569 "Keeping the server header '%s' around.", *header);
1572 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1574 char *old_header = *header;
1576 *header = strdup("Connection: close");
1579 return JB_ERR_MEMORY;
1581 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1586 /* Signal server_connection_adder() to return early. */
1587 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1593 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1594 /*********************************************************************
1596 * Function : server_keep_alive
1598 * Description : Stores the servers keep alive timeout.
1601 * 1 : csp = Current client state (buffers, headers, etc...)
1602 * 2 : header = On input, pointer to header to modify.
1603 * On output, pointer to the modified header, or NULL
1604 * to remove the header. This function frees the
1605 * original string if necessary.
1607 * Returns : JB_ERR_OK.
1609 *********************************************************************/
1610 static jb_err server_keep_alive(struct client_state *csp, char **header)
1612 unsigned int keep_alive_timeout;
1613 const char *timeout_position = strstr(*header, "timeout=");
1615 if ((NULL == timeout_position)
1616 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1618 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1622 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1624 log_error(LOG_LEVEL_HEADER,
1625 "Reducing keep-alive timeout from %u to %u.",
1626 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1627 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1631 /* XXX: Is this log worthy? */
1632 log_error(LOG_LEVEL_HEADER,
1633 "Server keep-alive timeout is %u. Sticking with %u.",
1634 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1640 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1644 /*********************************************************************
1646 * Function : client_connection
1648 * Description : Makes sure a proper "Connection:" header is
1649 * set and signals connection_header_adder
1653 * 1 : csp = Current client state (buffers, headers, etc...)
1654 * 2 : header = On input, pointer to header to modify.
1655 * On output, pointer to the modified header, or NULL
1656 * to remove the header. This function frees the
1657 * original string if necessary.
1659 * Returns : JB_ERR_OK on success, or
1660 * JB_ERR_MEMORY on out-of-memory error.
1662 *********************************************************************/
1663 static jb_err client_connection(struct client_state *csp, char **header)
1665 const char *wanted_header = get_appropiate_connection_header(csp);
1667 if (strcmpic(*header, wanted_header))
1669 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1670 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1672 log_error(LOG_LEVEL_HEADER,
1673 "Keeping the client header '%s' around. "
1674 "The connection will not be kept alive.",
1678 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1680 char *old_header = *header;
1682 *header = strdup(wanted_header);
1685 return JB_ERR_MEMORY;
1687 log_error(LOG_LEVEL_HEADER,
1688 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1692 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1695 log_error(LOG_LEVEL_HEADER,
1696 "Keeping the client header '%s' around. "
1697 "The server connection will be kept alive if possible.",
1699 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1701 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1703 /* Signal client_connection_adder() to return early. */
1704 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1710 /*********************************************************************
1712 * Function : crumble
1714 * Description : This is called if a header matches a pattern to "crunch"
1717 * 1 : csp = Current client state (buffers, headers, etc...)
1718 * 2 : header = On input, pointer to header to modify.
1719 * On output, pointer to the modified header, or NULL
1720 * to remove the header. This function frees the
1721 * original string if necessary.
1723 * Returns : JB_ERR_OK on success, or
1724 * JB_ERR_MEMORY on out-of-memory error.
1726 *********************************************************************/
1727 static jb_err crumble(struct client_state *csp, char **header)
1730 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1736 /*********************************************************************
1738 * Function : crunch_server_header
1740 * Description : Crunch server header if it matches a string supplied by the
1741 * user. Called from `sed'.
1744 * 1 : csp = Current client state (buffers, headers, etc...)
1745 * 2 : header = On input, pointer to header to modify.
1746 * On output, pointer to the modified header, or NULL
1747 * to remove the header. This function frees the
1748 * original string if necessary.
1750 * Returns : JB_ERR_OK on success and always succeeds
1752 *********************************************************************/
1753 static jb_err crunch_server_header(struct client_state *csp, char **header)
1755 const char *crunch_pattern;
1757 /* Do we feel like crunching? */
1758 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1760 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1762 /* Is the current header the lucky one? */
1763 if (strstr(*header, crunch_pattern))
1765 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1774 /*********************************************************************
1776 * Function : server_content_type
1778 * Description : Set the content-type for filterable types (text/.*,
1779 * .*xml.*, javascript and image/gif) unless filtering has been
1780 * forbidden (CT_TABOO) while parsing earlier headers.
1781 * NOTE: Since text/plain is commonly used by web servers
1782 * for files whose correct type is unknown, we don't
1783 * set CT_TEXT for it.
1786 * 1 : csp = Current client state (buffers, headers, etc...)
1787 * 2 : header = On input, pointer to header to modify.
1788 * On output, pointer to the modified header, or NULL
1789 * to remove the header. This function frees the
1790 * original string if necessary.
1792 * Returns : JB_ERR_OK on success, or
1793 * JB_ERR_MEMORY on out-of-memory error.
1795 *********************************************************************/
1796 static jb_err server_content_type(struct client_state *csp, char **header)
1798 /* Remove header if it isn't the first Content-Type header */
1799 if ((csp->content_type & CT_DECLARED))
1802 * Another, slightly slower, way to see if
1803 * we already parsed another Content-Type header.
1805 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1807 log_error(LOG_LEVEL_ERROR,
1808 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1816 * Signal that the Content-Type has been set.
1818 csp->content_type |= CT_DECLARED;
1820 if (!(csp->content_type & CT_TABOO))
1823 * XXX: The assumption that text/plain is a sign of
1824 * binary data seems to be somewhat unreasonable nowadays
1825 * and should be dropped after 3.0.8 is out.
1827 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
1828 || strstr(*header, "xml")
1829 || strstr(*header, "application/x-javascript"))
1831 csp->content_type |= CT_TEXT;
1833 else if (strstr(*header, "image/gif"))
1835 csp->content_type |= CT_GIF;
1840 * Are we messing with the content type?
1842 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1845 * Make sure the user doesn't accidently
1846 * change the content type of binary documents.
1848 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
1851 *header = strdup("Content-Type: ");
1852 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1856 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1857 return JB_ERR_MEMORY;
1859 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1863 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
1864 "It doesn't look like a content type that should be filtered. "
1865 "Enable force-text-mode if you know what you're doing.", *header);
1873 /*********************************************************************
1875 * Function : server_transfer_coding
1877 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1878 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1879 * - Remove header if body was chunked but has been
1880 * de-chunked for filtering.
1883 * 1 : csp = Current client state (buffers, headers, etc...)
1884 * 2 : header = On input, pointer to header to modify.
1885 * On output, pointer to the modified header, or NULL
1886 * to remove the header. This function frees the
1887 * original string if necessary.
1889 * Returns : JB_ERR_OK on success, or
1890 * JB_ERR_MEMORY on out-of-memory error.
1892 *********************************************************************/
1893 static jb_err server_transfer_coding(struct client_state *csp, char **header)
1896 * Turn off pcrs and gif filtering if body compressed
1898 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1902 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1904 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1905 csp->http->cmd, *header);
1906 #endif /* def FEATURE_ZLIB */
1907 csp->content_type = CT_TABOO;
1911 * Raise flag if body chunked
1913 if (strstr(*header, "chunked"))
1915 csp->flags |= CSP_FLAG_CHUNKED;
1918 * If the body was modified, it has been de-chunked first
1919 * and the header must be removed.
1921 * FIXME: If there is more than one transfer encoding,
1922 * only the "chunked" part should be removed here.
1924 if (csp->flags & CSP_FLAG_MODIFIED)
1926 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1935 /*********************************************************************
1937 * Function : server_content_encoding
1939 * Description : This function is run twice for each request,
1940 * unless FEATURE_ZLIB and filtering are disabled.
1942 * The first run is used to check if the content
1943 * is compressed, if FEATURE_ZLIB is disabled
1944 * filtering is then disabled as well, if FEATURE_ZLIB
1945 * is enabled the content is marked for decompression.
1947 * The second run is used to remove the Content-Encoding
1948 * header if the decompression was successful.
1951 * 1 : csp = Current client state (buffers, headers, etc...)
1952 * 2 : header = On input, pointer to header to modify.
1953 * On output, pointer to the modified header, or NULL
1954 * to remove the header. This function frees the
1955 * original string if necessary.
1957 * Returns : JB_ERR_OK on success, or
1958 * JB_ERR_MEMORY on out-of-memory error.
1960 *********************************************************************/
1961 static jb_err server_content_encoding(struct client_state *csp, char **header)
1964 if ((csp->flags & CSP_FLAG_MODIFIED)
1965 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1968 * We successfully decompressed the content,
1969 * and have to clean the header now, so the
1970 * client no longer expects compressed data..
1972 * XXX: There is a difference between cleaning
1973 * and removing it completely.
1975 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1978 else if (strstr(*header, "gzip"))
1980 /* Mark for gzip decompression */
1981 csp->content_type |= CT_GZIP;
1983 else if (strstr(*header, "deflate"))
1985 /* Mark for zlib decompression */
1986 csp->content_type |= CT_DEFLATE;
1988 else if (strstr(*header, "compress"))
1991 * We can't decompress this; therefore we can't filter
1994 csp->content_type |= CT_TABOO;
1996 #else /* !defined(FEATURE_ZLIB) */
1997 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2000 * Body is compressed, turn off pcrs and gif filtering.
2002 csp->content_type |= CT_TABOO;
2005 * Log a warning if the user expects the content to be filtered.
2007 if ((csp->rlist != NULL) &&
2008 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2010 log_error(LOG_LEVEL_INFO,
2011 "Compressed content detected, content filtering disabled. "
2012 "Consider recompiling Privoxy with zlib support or "
2013 "enable the prevent-compression action.");
2016 #endif /* defined(FEATURE_ZLIB) */
2023 /*********************************************************************
2025 * Function : server_adjust_content_length
2027 * Description : Adjust Content-Length header if we modified
2031 * 1 : csp = Current client state (buffers, headers, etc...)
2032 * 2 : header = On input, pointer to header to modify.
2033 * On output, pointer to the modified header, or NULL
2034 * to remove the header. This function frees the
2035 * original string if necessary.
2037 * Returns : JB_ERR_OK on success, or
2038 * JB_ERR_MEMORY on out-of-memory error.
2040 *********************************************************************/
2041 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2043 const size_t max_header_length = 80;
2045 /* Regenerate header if the content was modified. */
2046 if (csp->flags & CSP_FLAG_MODIFIED)
2049 *header = (char *) zalloc(max_header_length);
2050 if (*header == NULL)
2052 return JB_ERR_MEMORY;
2055 snprintf(*header, max_header_length, "Content-Length: %d",
2056 (int)csp->content_length);
2057 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2058 (int)csp->content_length);
2065 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2066 /*********************************************************************
2068 * Function : server_save_content_length
2070 * Description : Save the Content-Length sent by the server.
2073 * 1 : csp = Current client state (buffers, headers, etc...)
2074 * 2 : header = On input, pointer to header to modify.
2075 * On output, pointer to the modified header, or NULL
2076 * to remove the header. This function frees the
2077 * original string if necessary.
2079 * Returns : JB_ERR_OK on success, or
2080 * JB_ERR_MEMORY on out-of-memory error.
2082 *********************************************************************/
2083 static jb_err server_save_content_length(struct client_state *csp, char **header)
2085 unsigned long long content_length = 0;
2087 assert(*(*header+14) == ':');
2089 if (1 != sscanf(*header+14, ": %llu", &content_length))
2091 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2096 csp->expected_content_length = content_length;
2097 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2102 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2105 /*********************************************************************
2107 * Function : server_content_md5
2109 * Description : Crumble any Content-MD5 headers if the document was
2110 * modified. FIXME: Should we re-compute instead?
2113 * 1 : csp = Current client state (buffers, headers, etc...)
2114 * 2 : header = On input, pointer to header to modify.
2115 * On output, pointer to the modified header, or NULL
2116 * to remove the header. This function frees the
2117 * original string if necessary.
2119 * Returns : JB_ERR_OK on success, or
2120 * JB_ERR_MEMORY on out-of-memory error.
2122 *********************************************************************/
2123 static jb_err server_content_md5(struct client_state *csp, char **header)
2125 if (csp->flags & CSP_FLAG_MODIFIED)
2127 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2135 /*********************************************************************
2137 * Function : server_content_disposition
2139 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2140 * Called from `sed'.
2143 * 1 : csp = Current client state (buffers, headers, etc...)
2144 * 2 : header = On input, pointer to header to modify.
2145 * On output, pointer to the modified header, or NULL
2146 * to remove the header. This function frees the
2147 * original string if necessary.
2149 * Returns : JB_ERR_OK on success, or
2150 * JB_ERR_MEMORY on out-of-memory error.
2152 *********************************************************************/
2153 static jb_err server_content_disposition(struct client_state *csp, char **header)
2158 * Are we messing with the Content-Disposition header?
2160 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2166 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2168 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2171 * Blocking content-disposition header
2173 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2180 * Replacing Content-Disposition header
2183 *header = strdup("Content-Disposition: ");
2184 string_append(header, newval);
2186 if (*header != NULL)
2188 log_error(LOG_LEVEL_HEADER,
2189 "Content-Disposition header crunched and replaced with: %s", *header);
2192 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2196 /*********************************************************************
2198 * Function : server_last_modified
2200 * Description : Changes Last-Modified header to the actual date
2201 * to help hide-if-modified-since.
2202 * Called from `sed'.
2205 * 1 : csp = Current client state (buffers, headers, etc...)
2206 * 2 : header = On input, pointer to header to modify.
2207 * On output, pointer to the modified header, or NULL
2208 * to remove the header. This function frees the
2209 * original string if necessary.
2211 * Returns : JB_ERR_OK on success, or
2212 * JB_ERR_MEMORY on out-of-memory error.
2214 *********************************************************************/
2215 static jb_err server_last_modified(struct client_state *csp, char **header)
2218 char buf[BUFFER_SIZE];
2221 #ifdef HAVE_GMTIME_R
2224 struct tm *timeptr = NULL;
2225 time_t now, last_modified;
2226 long int days, hours, minutes, seconds;
2229 * Are we messing with the Last-Modified header?
2231 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2237 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2239 if (0 == strcmpic(newval, "block") )
2242 * Blocking Last-Modified header. Useless but why not.
2244 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2248 else if (0 == strcmpic(newval, "reset-to-request-time"))
2251 * Setting Last-Modified Header to now.
2253 get_http_time(0, buf, sizeof(buf));
2255 *header = strdup("Last-Modified: ");
2256 string_append(header, buf);
2258 if (*header == NULL)
2260 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2264 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2267 else if (0 == strcmpic(newval, "randomize"))
2269 const char *header_time = *header + sizeof("Last-Modified:");
2271 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2273 #ifdef HAVE_GMTIME_R
2274 gmtime_r(&now, &gmt);
2275 #elif defined(MUTEX_LOCKS_AVAILABLE)
2276 privoxy_mutex_lock(&gmtime_mutex);
2278 privoxy_mutex_unlock(&gmtime_mutex);
2282 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2284 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2289 long int rtime = (long int)difftime(now, last_modified);
2292 const int negative_delta = (rtime < 0);
2297 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2299 rtime = pick_from_range(rtime);
2304 last_modified += rtime;
2305 #ifdef HAVE_GMTIME_R
2306 timeptr = gmtime_r(&last_modified, &gmt);
2307 #elif defined(MUTEX_LOCKS_AVAILABLE)
2308 privoxy_mutex_lock(&gmtime_mutex);
2309 timeptr = gmtime(&last_modified);
2310 privoxy_mutex_unlock(&gmtime_mutex);
2312 timeptr = gmtime(&last_modified);
2314 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2316 *header = strdup("Last-Modified: ");
2317 string_append(header, newheader);
2319 if (*header == NULL)
2321 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2322 return JB_ERR_MEMORY;
2325 days = rtime / (3600 * 24);
2326 hours = rtime / 3600 % 24;
2327 minutes = rtime / 60 % 60;
2328 seconds = rtime % 60;
2330 log_error(LOG_LEVEL_HEADER,
2331 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2332 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2333 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2337 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2346 /*********************************************************************
2348 * Function : client_accept_encoding
2350 * Description : Rewrite the client's Accept-Encoding header so that
2351 * if doesn't allow compression, if the action applies.
2352 * Note: For HTTP/1.0 the absence of the header is enough.
2355 * 1 : csp = Current client state (buffers, headers, etc...)
2356 * 2 : header = On input, pointer to header to modify.
2357 * On output, pointer to the modified header, or NULL
2358 * to remove the header. This function frees the
2359 * original string if necessary.
2361 * Returns : JB_ERR_OK on success, or
2362 * JB_ERR_MEMORY on out-of-memory error.
2364 *********************************************************************/
2365 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2367 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2369 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2373 /* Temporarily disable the correct behaviour to
2374 * work around a PHP bug.
2376 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2378 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2379 * if (*header == NULL)
2381 * return JB_ERR_MEMORY;
2392 /*********************************************************************
2394 * Function : client_te
2396 * Description : Rewrite the client's TE header so that
2397 * if doesn't allow compression, if the action applies.
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 client_te(struct client_state *csp, char **header)
2412 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2415 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2422 /*********************************************************************
2424 * Function : client_referrer
2426 * Description : Handle the "referer" config setting properly.
2427 * Called from `sed'.
2430 * 1 : csp = Current client state (buffers, headers, etc...)
2431 * 2 : header = On input, pointer to header to modify.
2432 * On output, pointer to the modified header, or NULL
2433 * to remove the header. This function frees the
2434 * original string if necessary.
2436 * Returns : JB_ERR_OK on success, or
2437 * JB_ERR_MEMORY on out-of-memory error.
2439 *********************************************************************/
2440 static jb_err client_referrer(struct client_state *csp, char **header)
2442 const char *parameter;
2443 /* booleans for parameters we have to check multiple times */
2444 int parameter_conditional_block;
2445 int parameter_conditional_forge;
2447 #ifdef FEATURE_FORCE_LOAD
2449 * Since the referrer can include the prefix even
2450 * if the request itself is non-forced, we must
2451 * clean it unconditionally.
2453 * XXX: strclean is too broad
2455 strclean(*header, FORCE_PREFIX);
2456 #endif /* def FEATURE_FORCE_LOAD */
2458 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2460 /* Nothing left to do */
2464 parameter = csp->action->string[ACTION_STRING_REFERER];
2465 assert(parameter != NULL);
2466 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2467 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2469 if (!parameter_conditional_block && !parameter_conditional_forge)
2472 * As conditional-block and conditional-forge are the only
2473 * parameters that rely on the original referrer, we can
2474 * remove it now for all the others.
2479 if (0 == strcmpic(parameter, "block"))
2481 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2484 else if (parameter_conditional_block || parameter_conditional_forge)
2486 return handle_conditional_hide_referrer_parameter(header,
2487 csp->http->hostport, parameter_conditional_block);
2489 else if (0 == strcmpic(parameter, "forge"))
2491 return create_forged_referrer(header, csp->http->hostport);
2495 /* interpret parameter as user-supplied referer to fake */
2496 return create_fake_referrer(header, parameter);
2501 /*********************************************************************
2503 * Function : client_accept_language
2505 * Description : Handle the "Accept-Language" config setting properly.
2506 * Called from `sed'.
2509 * 1 : csp = Current client state (buffers, headers, etc...)
2510 * 2 : header = On input, pointer to header to modify.
2511 * On output, pointer to the modified header, or NULL
2512 * to remove the header. This function frees the
2513 * original string if necessary.
2515 * Returns : JB_ERR_OK on success, or
2516 * JB_ERR_MEMORY on out-of-memory error.
2518 *********************************************************************/
2519 static jb_err client_accept_language(struct client_state *csp, char **header)
2524 * Are we messing with the Accept-Language?
2526 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2528 /*I don't think so*/
2532 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2534 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2537 * Blocking Accept-Language header
2539 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2546 * Replacing Accept-Language header
2549 *header = strdup("Accept-Language: ");
2550 string_append(header, newval);
2552 if (*header == NULL)
2554 log_error(LOG_LEVEL_ERROR,
2555 "Insufficient memory. Accept-Language header crunched without replacement.");
2559 log_error(LOG_LEVEL_HEADER,
2560 "Accept-Language header crunched and replaced with: %s", *header);
2563 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2567 /*********************************************************************
2569 * Function : crunch_client_header
2571 * Description : Crunch client header if it matches a string supplied by the
2572 * user. Called from `sed'.
2575 * 1 : csp = Current client state (buffers, headers, etc...)
2576 * 2 : header = On input, pointer to header to modify.
2577 * On output, pointer to the modified header, or NULL
2578 * to remove the header. This function frees the
2579 * original string if necessary.
2581 * Returns : JB_ERR_OK on success and always succeeds
2583 *********************************************************************/
2584 static jb_err crunch_client_header(struct client_state *csp, char **header)
2586 const char *crunch_pattern;
2588 /* Do we feel like crunching? */
2589 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2591 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2593 /* Is the current header the lucky one? */
2594 if (strstr(*header, crunch_pattern))
2596 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2604 /*********************************************************************
2606 * Function : client_uagent
2608 * Description : Handle the "user-agent" config setting properly
2609 * and remember its original value to enable browser
2610 * bug workarounds. Called from `sed'.
2613 * 1 : csp = Current client state (buffers, headers, etc...)
2614 * 2 : header = On input, pointer to header to modify.
2615 * On output, pointer to the modified header, or NULL
2616 * to remove the header. This function frees the
2617 * original string if necessary.
2619 * Returns : JB_ERR_OK on success, or
2620 * JB_ERR_MEMORY on out-of-memory error.
2622 *********************************************************************/
2623 static jb_err client_uagent(struct client_state *csp, char **header)
2627 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2632 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2639 *header = strdup("User-Agent: ");
2640 string_append(header, newval);
2642 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2644 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2648 /*********************************************************************
2650 * Function : client_ua
2652 * Description : Handle "ua-" headers properly. Called from `sed'.
2655 * 1 : csp = Current client state (buffers, headers, etc...)
2656 * 2 : header = On input, pointer to header to modify.
2657 * On output, pointer to the modified header, or NULL
2658 * to remove the header. This function frees the
2659 * original string if necessary.
2661 * Returns : JB_ERR_OK on success, or
2662 * JB_ERR_MEMORY on out-of-memory error.
2664 *********************************************************************/
2665 static jb_err client_ua(struct client_state *csp, char **header)
2667 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2669 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2677 /*********************************************************************
2679 * Function : client_from
2681 * Description : Handle the "from" config setting properly.
2682 * Called from `sed'.
2685 * 1 : csp = Current client state (buffers, headers, etc...)
2686 * 2 : header = On input, pointer to header to modify.
2687 * On output, pointer to the modified header, or NULL
2688 * to remove the header. This function frees the
2689 * original string if necessary.
2691 * Returns : JB_ERR_OK on success, or
2692 * JB_ERR_MEMORY on out-of-memory error.
2694 *********************************************************************/
2695 static jb_err client_from(struct client_state *csp, char **header)
2699 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2706 newval = csp->action->string[ACTION_STRING_FROM];
2709 * Are we blocking the e-mail address?
2711 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2713 log_error(LOG_LEVEL_HEADER, "crunched From!");
2717 log_error(LOG_LEVEL_HEADER, " modified");
2719 *header = strdup("From: ");
2720 string_append(header, newval);
2722 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2726 /*********************************************************************
2728 * Function : client_send_cookie
2730 * Description : Crunches the "cookie" header if necessary.
2731 * Called from `sed'.
2733 * XXX: Stupid name, doesn't send squat.
2736 * 1 : csp = Current client state (buffers, headers, etc...)
2737 * 2 : header = On input, pointer to header to modify.
2738 * On output, pointer to the modified header, or NULL
2739 * to remove the header. This function frees the
2740 * original string if necessary.
2742 * Returns : JB_ERR_OK on success, or
2743 * JB_ERR_MEMORY on out-of-memory error.
2745 *********************************************************************/
2746 static jb_err client_send_cookie(struct client_state *csp, char **header)
2748 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2750 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2758 /*********************************************************************
2760 * Function : client_x_forwarded
2762 * Description : Handle the "x-forwarded-for" config setting properly,
2763 * also used in the add_client_headers list. Called from `sed'.
2766 * 1 : csp = Current client state (buffers, headers, etc...)
2767 * 2 : header = On input, pointer to header to modify.
2768 * On output, pointer to the modified header, or NULL
2769 * to remove the header. This function frees the
2770 * original string if necessary.
2772 * Returns : JB_ERR_OK on success, or
2773 * JB_ERR_MEMORY on out-of-memory error.
2775 *********************************************************************/
2776 jb_err client_x_forwarded(struct client_state *csp, char **header)
2778 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
2780 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
2782 if (0 == strcmpic(parameter, "block"))
2785 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2787 else if (0 == strcmpic(parameter, "add"))
2789 string_append(header, ", ");
2790 string_append(header, csp->ip_addr_str);
2792 if (*header == NULL)
2794 return JB_ERR_MEMORY;
2796 log_error(LOG_LEVEL_HEADER,
2797 "Appended client IP address to %s", *header);
2798 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
2802 log_error(LOG_LEVEL_FATAL,
2803 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
2811 /*********************************************************************
2813 * Function : client_max_forwards
2815 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2816 * from the value of the Max-Forwards header field.
2819 * 1 : csp = Current client state (buffers, headers, etc...)
2820 * 2 : header = On input, pointer to header to modify.
2821 * On output, pointer to the modified header, or NULL
2822 * to remove the header. This function frees the
2823 * original string if necessary.
2825 * Returns : JB_ERR_OK on success, or
2826 * JB_ERR_MEMORY on out-of-memory error.
2828 *********************************************************************/
2829 static jb_err client_max_forwards(struct client_state *csp, char **header)
2833 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2834 (0 == strcmpic(csp->http->gpc, "options")))
2836 assert(*(*header+12) == ':');
2837 if (1 == sscanf(*header+12, ": %d", &max_forwards))
2839 if (max_forwards > 0)
2841 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
2842 log_error(LOG_LEVEL_HEADER,
2843 "Max-Forwards value for %s request reduced to %d.",
2844 csp->http->gpc, max_forwards);
2846 else if (max_forwards < 0)
2848 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2854 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2863 /*********************************************************************
2865 * Function : client_host
2867 * Description : If the request URI did not contain host and
2868 * port information, parse and evaluate the Host
2871 * Also, kill ill-formed HOST: headers as sent by
2872 * Apple's iTunes software when used with a proxy.
2875 * 1 : csp = Current client state (buffers, headers, etc...)
2876 * 2 : header = On input, pointer to header to modify.
2877 * On output, pointer to the modified header, or NULL
2878 * to remove the header. This function frees the
2879 * original string if necessary.
2881 * Returns : JB_ERR_OK on success, or
2882 * JB_ERR_MEMORY on out-of-memory error.
2884 *********************************************************************/
2885 static jb_err client_host(struct client_state *csp, char **header)
2890 * If the header field name is all upper-case, chances are that it's
2891 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2892 * not a problem -- they are regenerated later.
2894 if ((*header)[1] == 'O')
2896 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2901 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2902 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2905 if (NULL == (p = strdup((*header)+6)))
2907 return JB_ERR_MEMORY;
2910 if (NULL == (q = strdup(p)))
2913 return JB_ERR_MEMORY;
2916 freez(csp->http->hostport);
2917 csp->http->hostport = p;
2918 freez(csp->http->host);
2919 csp->http->host = q;
2920 q = strchr(csp->http->host, ':');
2923 /* Terminate hostname and evaluate port string */
2925 csp->http->port = atoi(q);
2929 csp->http->port = csp->http->ssl ? 443 : 80;
2932 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2933 csp->http->hostport, csp->http->host, csp->http->port);
2936 /* Signal client_host_adder() to return right away */
2937 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
2943 /*********************************************************************
2945 * Function : client_if_modified_since
2947 * Description : Remove or modify the If-Modified-Since header.
2950 * 1 : csp = Current client state (buffers, headers, etc...)
2951 * 2 : header = On input, pointer to header to modify.
2952 * On output, pointer to the modified header, or NULL
2953 * to remove the header. This function frees the
2954 * original string if necessary.
2956 * Returns : JB_ERR_OK on success, or
2957 * JB_ERR_MEMORY on out-of-memory error.
2959 *********************************************************************/
2960 static jb_err client_if_modified_since(struct client_state *csp, char **header)
2963 #ifdef HAVE_GMTIME_R
2966 struct tm *timeptr = NULL;
2969 long int hours, minutes, seconds;
2972 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2975 * The client got an error message because of a temporary problem,
2976 * the problem is gone and the client now tries to revalidate our
2977 * error message on the real server. The revalidation would always
2978 * end with the transmission of the whole document and there is
2979 * no need to expose the bogus If-Modified-Since header.
2981 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2984 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2986 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2988 if ((0 == strcmpic(newval, "block")))
2990 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2993 else /* add random value */
2995 const char *header_time = *header + sizeof("If-Modified-Since:");
2997 if (JB_ERR_OK != parse_header_time(header_time, &tm))
2999 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3004 long int rtime = strtol(newval, &endptr, 0);
3005 const int negative_range = (rtime < 0);
3009 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3010 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3016 rtime = pick_from_range(rtime);
3020 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3023 tm += rtime * (negative_range ? -1 : 1);
3024 #ifdef HAVE_GMTIME_R
3025 timeptr = gmtime_r(&tm, &gmt);
3026 #elif defined(MUTEX_LOCKS_AVAILABLE)
3027 privoxy_mutex_lock(&gmtime_mutex);
3028 timeptr = gmtime(&tm);
3029 privoxy_mutex_unlock(&gmtime_mutex);
3031 timeptr = gmtime(&tm);
3033 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3036 *header = strdup("If-Modified-Since: ");
3037 string_append(header, newheader);
3039 if (*header == NULL)
3041 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3042 return JB_ERR_MEMORY;
3045 hours = rtime / 3600;
3046 minutes = rtime / 60 % 60;
3047 seconds = rtime % 60;
3049 log_error(LOG_LEVEL_HEADER,
3050 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3051 *header, (negative_range) ? "subtracted" : "added", hours,
3052 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3053 seconds, (seconds == 1) ? ")" : "s)");
3062 /*********************************************************************
3064 * Function : client_if_none_match
3066 * Description : Remove the If-None-Match header.
3069 * 1 : csp = Current client state (buffers, headers, etc...)
3070 * 2 : header = On input, pointer to header to modify.
3071 * On output, pointer to the modified header, or NULL
3072 * to remove the header. This function frees the
3073 * original string if necessary.
3075 * Returns : JB_ERR_OK on success, or
3076 * JB_ERR_MEMORY on out-of-memory error.
3078 *********************************************************************/
3079 static jb_err client_if_none_match(struct client_state *csp, char **header)
3081 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3083 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3091 /*********************************************************************
3093 * Function : client_x_filter
3095 * Description : Disables filtering if the client set "X-Filter: No".
3096 * Called from `sed'.
3099 * 1 : csp = Current client state (buffers, headers, etc...)
3100 * 2 : header = On input, pointer to header to modify.
3101 * On output, pointer to the modified header, or NULL
3102 * to remove the header. This function frees the
3103 * original string if necessary.
3105 * Returns : JB_ERR_OK on success
3107 *********************************************************************/
3108 jb_err client_x_filter(struct client_state *csp, char **header)
3110 if ( 0 == strcmpic(*header, "X-Filter: No"))
3112 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3114 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3118 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3120 log_error(LOG_LEVEL_HEADER,
3121 "force-text-mode overruled the client's request to fetch without filtering!");
3125 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3126 csp->flags |= CSP_FLAG_NO_FILTERING;
3127 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3129 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3137 /*********************************************************************
3139 * Function : client_range
3141 * Description : Removes Range, Request-Range and If-Range headers if
3142 * content filtering is enabled. If the client's version
3143 * of the document has been altered by Privoxy, the server
3144 * could interpret the range differently than the client
3145 * intended in which case the user could end up with
3146 * corrupted content.
3149 * 1 : csp = Current client state (buffers, headers, etc...)
3150 * 2 : header = On input, pointer to header to modify.
3151 * On output, pointer to the modified header, or NULL
3152 * to remove the header. This function frees the
3153 * original string if necessary.
3155 * Returns : JB_ERR_OK
3157 *********************************************************************/
3158 static jb_err client_range(struct client_state *csp, char **header)
3160 if (content_filters_enabled(csp->action))
3162 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3163 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3170 /* the following functions add headers directly to the header list */
3172 /*********************************************************************
3174 * Function : client_host_adder
3176 * Description : Adds the Host: header field if it is missing.
3177 * Called from `sed'.
3180 * 1 : csp = Current client state (buffers, headers, etc...)
3182 * Returns : JB_ERR_OK on success, or
3183 * JB_ERR_MEMORY on out-of-memory error.
3185 *********************************************************************/
3186 static jb_err client_host_adder(struct client_state *csp)
3191 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3193 /* Header already set by the client, nothing to do. */
3197 if ( !csp->http->hostport || !*(csp->http->hostport))
3199 /* XXX: When does this happen and why is it OK? */
3200 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3205 * remove 'user:pass@' from 'proto://user:pass@host'
3207 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3213 p = csp->http->hostport;
3216 /* XXX: Just add it, we already made sure that it will be unique */
3217 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3218 err = enlist_unique_header(csp->headers, "Host", p);
3225 /*********************************************************************
3227 * Function : client_accept_encoding_adder
3229 * Description : Add an Accept-Encoding header to the client's request
3230 * that disables compression if the action applies, and
3231 * the header is not already there. Called from `sed'.
3232 * Note: For HTTP/1.0, the absence of the header is enough.
3235 * 1 : csp = Current client state (buffers, headers, etc...)
3237 * Returns : JB_ERR_OK on success, or
3238 * JB_ERR_MEMORY on out-of-memory error.
3240 *********************************************************************/
3241 static jb_err client_accept_encoding_adder(struct client_state *csp)
3243 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3244 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3246 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3254 /*********************************************************************
3256 * Function : client_xtra_adder
3258 * Description : Used in the add_client_headers list. Called from `sed'.
3261 * 1 : csp = Current client state (buffers, headers, etc...)
3263 * Returns : JB_ERR_OK on success, or
3264 * JB_ERR_MEMORY on out-of-memory error.
3266 *********************************************************************/
3267 static jb_err client_xtra_adder(struct client_state *csp)
3269 struct list_entry *lst;
3272 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3273 lst ; lst = lst->next)
3275 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3276 err = enlist(csp->headers, lst->str);
3288 /*********************************************************************
3290 * Function : client_x_forwarded_for_adder
3292 * Description : Used in the add_client_headers list. Called from `sed'.
3295 * 1 : csp = Current client state (buffers, headers, etc...)
3297 * Returns : JB_ERR_OK on success, or
3298 * JB_ERR_MEMORY on out-of-memory error.
3300 *********************************************************************/
3301 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3303 char *header = NULL;
3306 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3307 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3308 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3311 * If we aren't adding X-Forwarded-For headers,
3312 * or we already appended an existing X-Forwarded-For
3313 * header, there's nothing left to do here.
3318 header = strdup("X-Forwarded-For: ");
3319 string_append(&header, csp->ip_addr_str);
3323 return JB_ERR_MEMORY;
3326 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3327 err = enlist(csp->headers, header);
3334 /*********************************************************************
3336 * Function : server_connection_adder
3338 * Description : Adds an appropiate "Connection:" header to csp->headers
3339 * unless the header was already present. Called from `sed'.
3342 * 1 : csp = Current client state (buffers, headers, etc...)
3344 * Returns : JB_ERR_OK on success, or
3345 * JB_ERR_MEMORY on out-of-memory error.
3347 *********************************************************************/
3348 static jb_err server_connection_adder(struct client_state *csp)
3350 const unsigned int flags = csp->flags;
3351 const char *response_status_line = csp->headers->first->str;
3352 const char *wanted_header = get_appropiate_connection_header(csp);
3354 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3355 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3361 * XXX: if we downgraded the response, this check will fail.
3363 if ((csp->config->feature_flags &
3364 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3365 && (NULL != response_status_line)
3366 && !strncmpic(response_status_line, "HTTP/1.1", 8))
3368 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3369 "without Connection header implies keep-alive.");
3370 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3373 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3375 return enlist(csp->headers, wanted_header);
3379 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3380 /*********************************************************************
3382 * Function : server_proxy_connection_adder
3384 * Description : Adds a "Proxy-Connection: keep-alive" header to
3385 * csp->headers if the client asked for keep-alive.
3386 * XXX: We should reuse existant ones.
3389 * 1 : csp = Current client state (buffers, headers, etc...)
3391 * Returns : JB_ERR_OK on success, or
3392 * JB_ERR_MEMORY on out-of-memory error.
3394 *********************************************************************/
3395 static jb_err server_proxy_connection_adder(struct client_state *csp)
3397 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3398 jb_err err = JB_ERR_OK;
3400 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3402 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3403 err = enlist(csp->headers, proxy_connection_header);
3408 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3411 /*********************************************************************
3413 * Function : client_connection_header_adder
3415 * Description : Adds a proper "Connection:" header to csp->headers
3416 * unless the header was already present. Called from `sed'.
3419 * 1 : csp = Current client state (buffers, headers, etc...)
3421 * Returns : JB_ERR_OK on success, or
3422 * JB_ERR_MEMORY on out-of-memory error.
3424 *********************************************************************/
3425 static jb_err client_connection_header_adder(struct client_state *csp)
3427 const char *wanted_header = get_appropiate_connection_header(csp);
3429 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3430 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3435 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3436 && (csp->http->ssl == 0))
3438 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3441 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3443 return enlist(csp->headers, wanted_header);
3447 /*********************************************************************
3449 * Function : server_http
3451 * Description : - Save the HTTP Status into csp->http->status
3452 * - Set CT_TABOO to prevent filtering if the answer
3453 * is a partial range (HTTP status 206)
3454 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3458 * 1 : csp = Current client state (buffers, headers, etc...)
3459 * 2 : header = On input, pointer to header to modify.
3460 * On output, pointer to the modified header, or NULL
3461 * to remove the header. This function frees the
3462 * original string if necessary.
3464 * Returns : JB_ERR_OK on success, or
3465 * JB_ERR_MEMORY on out-of-memory error.
3467 *********************************************************************/
3468 static jb_err server_http(struct client_state *csp, char **header)
3470 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3471 if (csp->http->status == 206)
3473 csp->content_type = CT_TABOO;
3476 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3478 /* XXX: Should we do a real validity check here? */
3479 if (strlen(*header) > 8)
3482 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3487 * XXX: Should we block the request or
3488 * enlist a valid status code line here?
3490 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3491 "Downgrading to HTTP/1.0 impossible.");
3499 /*********************************************************************
3501 * Function : server_set_cookie
3503 * Description : Handle the server "cookie" header properly.
3504 * Log cookie to the jar file. Then "crunch",
3505 * accept or rewrite it to a session cookie.
3506 * Called from `sed'.
3508 * TODO: Allow the user to specify a new expiration
3509 * time to cause the cookie to expire even before the
3510 * browser is closed.
3513 * 1 : csp = Current client state (buffers, headers, etc...)
3514 * 2 : header = On input, pointer to header to modify.
3515 * On output, pointer to the modified header, or NULL
3516 * to remove the header. This function frees the
3517 * original string if necessary.
3519 * Returns : JB_ERR_OK on success, or
3520 * JB_ERR_MEMORY on out-of-memory error.
3522 *********************************************************************/
3523 static jb_err server_set_cookie(struct client_state *csp, char **header)
3530 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3532 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3535 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3537 /* Flag whether or not to log a message */
3540 /* A variable to store the tag we're working on */
3543 /* Skip "Set-Cookie:" (11 characters) in header */
3544 cur_tag = *header + 11;
3546 /* skip whitespace between "Set-Cookie:" and value */
3547 while (*cur_tag && ijb_isspace(*cur_tag))
3552 /* Loop through each tag in the cookie */
3556 char *next_tag = strchr(cur_tag, ';');
3557 if (next_tag != NULL)
3559 /* Skip the ';' character itself */
3562 /* skip whitespace ";" and start of tag */
3563 while (*next_tag && ijb_isspace(*next_tag))
3570 /* "Next tag" is the end of the string */
3571 next_tag = cur_tag + strlen(cur_tag);
3575 * Check the expiration date to see
3576 * if the cookie is still valid, if yes,
3577 * rewrite it to a session cookie.
3579 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3581 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3583 /* Did we detect the date properly? */
3584 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3587 * Nope, treat it as if it was still valid.
3589 * XXX: Should we remove the whole cookie instead?
3591 log_error(LOG_LEVEL_ERROR,
3592 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3593 string_move(cur_tag, next_tag);
3599 * Yes. Check if the cookie is still valid.
3601 * If the cookie is already expired it's probably
3602 * a delete cookie and even if it isn't, the browser
3603 * will discard it anyway.
3607 * XXX: timegm() isn't available on some AmigaOS
3608 * versions and our replacement doesn't work.
3610 * Our options are to either:
3612 * - disable session-cookies-only completely if timegm
3615 * - to simply remove all expired tags, like it has
3616 * been done until Privoxy 3.0.6 and to live with
3617 * the consequence that it can cause login/logout
3618 * problems on servers that don't validate their
3619 * input properly, or
3621 * - to replace it with mktime in which
3622 * case there is a slight chance of valid cookies
3623 * passing as already expired.
3625 * This is the way it's currently done and it's not
3626 * as bad as it sounds. If the missing GMT offset is
3627 * enough to change the result of the expiration check
3628 * the cookie will be only valid for a few hours
3629 * anyway, which in many cases will be shorter
3630 * than a browser session.
3632 if (cookie_time - now < 0)
3634 log_error(LOG_LEVEL_HEADER,
3635 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3636 /* Just in case some clown sets more then one expiration date */
3642 * Still valid, delete expiration date by copying
3643 * the rest of the string over it.
3645 string_move(cur_tag, next_tag);
3647 /* That changed the header, need to issue a log message */
3651 * Note that the next tag has now been moved to *cur_tag,
3652 * so we do not need to update the cur_tag pointer.
3660 /* Move on to next cookie tag */
3667 assert(NULL != *header);
3668 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3677 #ifdef FEATURE_FORCE_LOAD
3678 /*********************************************************************
3680 * Function : strclean
3682 * Description : In-Situ-Eliminate all occurances of substring in
3686 * 1 : string = string to clean
3687 * 2 : substring = substring to eliminate
3689 * Returns : Number of eliminations
3691 *********************************************************************/
3692 int strclean(char *string, const char *substring)
3698 len = strlen(substring);
3700 while((pos = strstr(string, substring)) != NULL)
3707 while (*p++ != '\0');
3714 #endif /* def FEATURE_FORCE_LOAD */
3717 /*********************************************************************
3719 * Function : parse_header_time
3721 * Description : Parses time formats used in HTTP header strings
3722 * to get the numerical respresentation.
3725 * 1 : header_time = HTTP header time as string.
3726 * 2 : result = storage for header_time in seconds
3728 * Returns : JB_ERR_OK if the time format was recognized, or
3729 * JB_ERR_PARSE otherwise.
3731 *********************************************************************/
3732 static jb_err parse_header_time(const char *header_time, time_t *result)
3737 * Zero out gmt to prevent time zone offsets.
3739 * While this is only necessary on some platforms
3740 * (mingw32 for example), I don't know how to
3741 * detect these automatically and doing it everywhere
3744 memset(&gmt, 0, sizeof(gmt));
3746 /* Tue, 02 Jun 2037 20:00:00 */
3747 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3748 /* Tue, 02-Jun-2037 20:00:00 */
3749 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3750 /* Tue, 02-Jun-37 20:00:00 */
3751 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3752 /* Tuesday, 02-Jun-2037 20:00:00 */
3753 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3754 /* Tuesday Jun 02 20:00:00 2037 */
3755 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3757 return JB_ERR_PARSE;
3760 *result = timegm(&gmt);
3767 /*********************************************************************
3769 * Function : get_destination_from_headers
3771 * Description : Parse the "Host:" header to get the request's destination.
3772 * Only needed if the client's request was forcefully
3773 * redirected into Privoxy.
3775 * Code mainly copied from client_host() which is currently
3776 * run too late for this purpose.
3779 * 1 : headers = List of headers (one of them hopefully being
3780 * the "Host:" header)
3781 * 2 : http = storage for the result (host, port and hostport).
3783 * Returns : JB_ERR_MEMORY in case of memory problems,
3784 * JB_ERR_PARSE if the host header couldn't be found,
3785 * JB_ERR_OK otherwise.
3787 *********************************************************************/
3788 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3794 host = get_header_value(headers, "Host:");
3798 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3799 return JB_ERR_PARSE;
3802 if (NULL == (p = strdup((host))))
3804 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3805 return JB_ERR_MEMORY;
3808 if (NULL == (q = strdup(p)))
3811 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3812 return JB_ERR_MEMORY;
3815 freez(http->hostport);
3819 q = strchr(http->host, ':');
3822 /* Terminate hostname and evaluate port string */
3824 http->port = atoi(q);
3828 http->port = http->ssl ? 443 : 80;
3831 /* Rebuild request URL */
3833 http->url = strdup(http->ssl ? "https://" : "http://");
3834 string_append(&http->url, http->hostport);
3835 string_append(&http->url, http->path);
3836 if (http->url == NULL)
3838 return JB_ERR_MEMORY;
3841 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
3849 /*********************************************************************
3851 * Function : create_forged_referrer
3853 * Description : Helper for client_referrer to forge a referer as
3854 * 'http://[hostname:port/' to fool stupid
3855 * checks for in-site links
3858 * 1 : header = Pointer to header pointer
3859 * 2 : hostport = Host and optionally port as string
3861 * Returns : JB_ERR_OK in case of success, or
3862 * JB_ERR_MEMORY in case of memory problems.
3864 *********************************************************************/
3865 static jb_err create_forged_referrer(char **header, const char *hostport)
3867 assert(NULL == *header);
3869 *header = strdup("Referer: http://");
3870 string_append(header, hostport);
3871 string_append(header, "/");
3873 if (NULL == *header)
3875 return JB_ERR_MEMORY;
3878 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
3885 /*********************************************************************
3887 * Function : create_fake_referrer
3889 * Description : Helper for client_referrer to create a fake referrer
3890 * based on a string supplied by the user.
3893 * 1 : header = Pointer to header pointer
3894 * 2 : hosthost = Referrer to fake
3896 * Returns : JB_ERR_OK in case of success, or
3897 * JB_ERR_MEMORY in case of memory problems.
3899 *********************************************************************/
3900 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
3902 assert(NULL == *header);
3904 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
3906 log_error(LOG_LEVEL_HEADER,
3907 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
3909 *header = strdup("Referer: ");
3910 string_append(header, fake_referrer);
3912 if (NULL == *header)
3914 return JB_ERR_MEMORY;
3917 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
3924 /*********************************************************************
3926 * Function : handle_conditional_hide_referrer_parameter
3928 * Description : Helper for client_referrer to crunch or forge
3929 * the referrer header if the host has changed.
3932 * 1 : header = Pointer to header pointer
3933 * 2 : host = The target host (may include the port)
3934 * 3 : parameter_conditional_block = Boolean to signal
3935 * if we're in conditional-block mode. If not set,
3936 * we're in conditional-forge mode.
3938 * Returns : JB_ERR_OK in case of success, or
3939 * JB_ERR_MEMORY in case of memory problems.
3941 *********************************************************************/
3942 static jb_err handle_conditional_hide_referrer_parameter(char **header,
3943 const char *host, const int parameter_conditional_block)
3945 char *referer = strdup(*header);
3946 const size_t hostlenght = strlen(host);
3947 const char *referer_url = NULL;
3949 if (NULL == referer)
3952 return JB_ERR_MEMORY;
3955 /* referer begins with 'Referer: http[s]://' */
3956 if ((hostlenght+17) < strlen(referer))
3959 * Shorten referer to make sure the referer is blocked
3960 * if www.example.org/www.example.com-shall-see-the-referer/
3961 * links to www.example.com/
3963 referer[hostlenght+17] = '\0';
3965 referer_url = strstr(referer, "http://");
3966 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
3968 /* Host has changed, Referer is invalid or a https URL. */
3969 if (parameter_conditional_block)
3971 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
3978 return create_forged_referrer(header, host);
3988 /*********************************************************************
3990 * Function : get_appropiate_connection_header
3992 * Description : Returns an appropiate Connection header
3993 * depending on whether or not we try to keep
3994 * the connection to the server alive.
3997 * 1 : csp = Current client state (buffers, headers, etc...)
3999 * Returns : Pointer to statically allocated header buffer.
4001 *********************************************************************/
4002 static const char *get_appropiate_connection_header(const struct client_state *csp)
4004 static const char connection_keep_alive[] = "Connection: keep-alive";
4005 static const char connection_close[] = "Connection: close";
4007 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4008 && (csp->http->ssl == 0))
4010 return connection_keep_alive;
4012 return connection_close;