1 const char parsers_rcs[] = "$Id: parsers.c,v 1.173 2009/06/05 16:53:55 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2009 the
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
45 *********************************************************************/
52 #include <sys/types.h>
62 * Convince GNU's libc to provide a strptime prototype.
71 #define GZIP_IDENTIFIER_1 0x1f
72 #define GZIP_IDENTIFIER_2 0x8b
74 #define GZIP_FLAG_CHECKSUM 0x02
75 #define GZIP_FLAG_EXTRA_FIELDS 0x04
76 #define GZIP_FLAG_FILE_NAME 0x08
77 #define GZIP_FLAG_COMMENT 0x10
78 #define GZIP_FLAG_RESERVED_BITS 0xe0
81 #if !defined(_WIN32) && !defined(__OS2__)
87 #ifdef FEATURE_PTHREAD
89 /* jcc.h is for mutex semapores only */
90 #endif /* def FEATURE_PTHREAD */
95 #include "jbsockets.h"
101 #ifndef HAVE_STRPTIME
102 #include "strptime.h"
105 const char parsers_h_rcs[] = PARSERS_H_VERSION;
107 /* Fix a problem with Solaris. There should be no effect on other
109 * Solaris's isspace() is a macro which uses its argument directly
110 * as an array index. Therefore we need to make sure that high-bit
111 * characters generate +ve values, and ideally we also want to make
112 * the argument match the declared parameter type of "int".
114 * Why did they write a character function that can't take a simple
115 * "char" argument? Doh!
117 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
118 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
120 static char *get_header_line(struct iob *iob);
121 static jb_err scan_headers(struct client_state *csp);
122 static jb_err header_tagger(struct client_state *csp, char *header);
123 static jb_err parse_header_time(const char *header_time, time_t *result);
125 static jb_err crumble (struct client_state *csp, char **header);
126 static jb_err filter_header (struct client_state *csp, char **header);
127 static jb_err client_connection (struct client_state *csp, char **header);
128 static jb_err client_referrer (struct client_state *csp, char **header);
129 static jb_err client_uagent (struct client_state *csp, char **header);
130 static jb_err client_ua (struct client_state *csp, char **header);
131 static jb_err client_from (struct client_state *csp, char **header);
132 static jb_err client_send_cookie (struct client_state *csp, char **header);
133 static jb_err client_x_forwarded (struct client_state *csp, char **header);
134 static jb_err client_accept_encoding (struct client_state *csp, char **header);
135 static jb_err client_te (struct client_state *csp, char **header);
136 static jb_err client_max_forwards (struct client_state *csp, char **header);
137 static jb_err client_host (struct client_state *csp, char **header);
138 static jb_err client_if_modified_since (struct client_state *csp, char **header);
139 static jb_err client_accept_language (struct client_state *csp, char **header);
140 static jb_err client_if_none_match (struct client_state *csp, char **header);
141 static jb_err crunch_client_header (struct client_state *csp, char **header);
142 static jb_err client_x_filter (struct client_state *csp, char **header);
143 static jb_err client_range (struct client_state *csp, char **header);
144 static jb_err server_set_cookie (struct client_state *csp, char **header);
145 static jb_err server_connection (struct client_state *csp, char **header);
146 static jb_err server_content_type (struct client_state *csp, char **header);
147 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
148 static jb_err server_content_md5 (struct client_state *csp, char **header);
149 static jb_err server_content_encoding (struct client_state *csp, char **header);
150 static jb_err server_transfer_coding (struct client_state *csp, char **header);
151 static jb_err server_http (struct client_state *csp, char **header);
152 static jb_err crunch_server_header (struct client_state *csp, char **header);
153 static jb_err server_last_modified (struct client_state *csp, char **header);
154 static jb_err server_content_disposition(struct client_state *csp, char **header);
156 #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));
490 /* Skip the comment if necessary. */
491 if (flags & GZIP_FLAG_COMMENT)
493 /* A null-terminated string is supposed to follow. */
494 while (*cur++ && (cur < csp->iob->eod));
497 /* Skip the CRC if necessary. */
498 if (flags & GZIP_FLAG_CHECKSUM)
503 if (cur >= csp->iob->eod)
506 * If the current position pointer reached or passed
507 * the buffer end, we were obviously tricked to skip
510 log_error(LOG_LEVEL_ERROR,
511 "Malformed gzip header detected. Aborting decompression.");
512 return JB_ERR_COMPRESS;
516 else if (csp->content_type & CT_DEFLATE)
519 * XXX: The debug level should be lowered
520 * before the next stable release.
522 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
524 * In theory (that is, according to RFC 1950), deflate-compressed
525 * data should begin with a two-byte zlib header and have an
526 * adler32 checksum at the end. It seems that in practice only
527 * the raw compressed data is sent. Note that this means that
528 * we are not RFC 1950-compliant here, but the advantage is that
529 * this actually works. :)
531 * We add a dummy null byte to tell zlib where the data ends,
532 * and later inform it not to expect a header.
534 * Fortunately, add_to_iob() has thoughtfully null-terminated
535 * the buffer; we can just increment the end pointer to include
542 log_error(LOG_LEVEL_ERROR,
543 "Unable to determine compression format for decompression");
544 return JB_ERR_COMPRESS;
547 /* Set up the fields required by zlib. */
548 zstr.next_in = (Bytef *)cur;
549 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
550 zstr.zalloc = Z_NULL;
552 zstr.opaque = Z_NULL;
555 * Passing -MAX_WBITS to inflateInit2 tells the library
556 * that there is no zlib header.
558 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
560 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
561 return JB_ERR_COMPRESS;
565 * Next, we allocate new storage for the inflated data.
566 * We don't modify the existing iob yet, so in case there
567 * is error in decompression we can recover gracefully.
569 buf = zalloc(bufsize);
572 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
573 return JB_ERR_MEMORY;
576 assert(bufsize >= skip_size);
577 memcpy(buf, csp->iob->buf, skip_size);
578 zstr.avail_out = bufsize - skip_size;
579 zstr.next_out = (Bytef *)buf + skip_size;
581 /* Try to decompress the whole stream in one shot. */
582 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
584 /* We need to allocate more memory for the output buffer. */
586 char *tmpbuf; /* used for realloc'ing the buffer */
587 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
589 if (0 == zstr.avail_in)
592 * If zlib wants more data then there's a problem, because
593 * the complete compressed file should have been buffered.
595 log_error(LOG_LEVEL_ERROR,
596 "Unexpected end of compressed iob. Using what we got so far.");
601 * If we tried the limit and still didn't have enough
602 * memory, just give up.
604 if (bufsize == csp->config->buffer_limit)
606 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
607 return JB_ERR_MEMORY;
610 /* Try doubling the buffer size each time. */
613 /* Don't exceed the buffer limit. */
614 if (bufsize > csp->config->buffer_limit)
616 bufsize = csp->config->buffer_limit;
619 /* Try to allocate the new buffer. */
620 tmpbuf = realloc(buf, bufsize);
623 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
625 return JB_ERR_MEMORY;
629 char *oldnext_out = (char *)zstr.next_out;
632 * Update the fields for inflate() to use the new
633 * buffer, which may be in a location different from
636 zstr.avail_out += bufsize - oldbufsize;
637 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
640 * Compare with an uglier method of calculating these values
641 * that doesn't require the extra oldbufsize variable.
643 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
644 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
645 assert(zstr.avail_out > 0U);
651 if (Z_STREAM_ERROR == inflateEnd(&zstr))
653 log_error(LOG_LEVEL_ERROR,
654 "Inconsistent stream state after decompression: %s", zstr.msg);
656 * XXX: Intentionally no return.
658 * According to zlib.h, Z_STREAM_ERROR is returned
659 * "if the stream state was inconsistent".
661 * I assume in this case inflate()'s status
662 * would also be something different than Z_STREAM_END
663 * so this check should be redundant, but lets see.
667 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
670 * We failed to decompress the stream and it's
671 * not simply because of missing data.
673 log_error(LOG_LEVEL_ERROR,
674 "Unexpected error while decompressing to the buffer (iob): %s",
676 return JB_ERR_COMPRESS;
680 * Finally, we can actually update the iob, since the
681 * decompression was successful. First, free the old
684 freez(csp->iob->buf);
686 /* Now, update the iob to use the new buffer. */
688 csp->iob->cur = csp->iob->buf + skip_size;
689 csp->iob->eod = (char *)zstr.next_out;
690 csp->iob->size = bufsize;
693 * Make sure the new uncompressed iob obeys some minimal
694 * consistency conditions.
696 if ((csp->iob->buf < csp->iob->cur)
697 && (csp->iob->cur <= csp->iob->eod)
698 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
700 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
701 if (new_size > (size_t)0)
703 log_error(LOG_LEVEL_RE_FILTER,
704 "Decompression successful. Old size: %d, new size: %d.",
709 /* zlib thinks this is OK, so lets do the same. */
710 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
715 /* It seems that zlib did something weird. */
716 log_error(LOG_LEVEL_ERROR,
717 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
718 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
719 csp->iob->eod, csp->iob->buf + csp->iob->size);
720 return JB_ERR_COMPRESS;
726 #endif /* defined(FEATURE_ZLIB) */
729 /*********************************************************************
731 * Function : string_move
733 * Description : memmove wrapper to move the last part of a string
734 * towards the beginning, overwriting the part in
735 * the middle. strlcpy() can't be used here as the
739 * 1 : dst = Destination to overwrite
740 * 2 : src = Source to move.
744 *********************************************************************/
745 static void string_move(char *dst, char *src)
749 /* +1 to copy the terminating nul as well. */
750 memmove(dst, src, strlen(src)+1);
754 /*********************************************************************
756 * Function : normalize_lws
758 * Description : Reduces unquoted linear white space in headers
759 * to a single space in accordance with RFC 2616 2.2.
760 * This simplifies parsing and filtering later on.
762 * XXX: Remove log messages before
763 * the next stable release?
766 * 1 : header = A header with linear white space to reduce.
770 *********************************************************************/
771 static void normalize_lws(char *header)
777 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
781 while (ijb_isspace(*q))
785 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
791 log_error(LOG_LEVEL_HEADER,
792 "Converting tab to space in '%s'", header);
797 char *end_of_token = strstr(p+1, "\"");
799 if (NULL != end_of_token)
801 /* Don't mess with quoted text. */
806 log_error(LOG_LEVEL_HEADER,
807 "Ignoring single quote in '%s'", header);
813 p = strchr(header, ':');
814 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
817 * There's still space before the colon.
825 /*********************************************************************
827 * Function : get_header
829 * Description : This (odd) routine will parse the csp->iob
830 * to get the next complete header.
833 * 1 : iob = The I/O buffer to parse, usually csp->iob.
835 * Returns : Any one of the following:
837 * 1) a pointer to a dynamically allocated string that contains a header line
838 * 2) NULL indicating that the end of the header was reached
839 * 3) "" indicating that the end of the iob was reached before finding
840 * a complete header line.
842 *********************************************************************/
843 char *get_header(struct iob *iob)
847 header = get_header_line(iob);
849 if ((header == NULL) || (*header == '\0'))
852 * No complete header read yet, tell the client.
857 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
860 * Header spans multiple lines, append the next one.
862 char *continued_header;
864 continued_header = get_header_line(iob);
865 if ((continued_header == NULL) || (*continued_header == '\0'))
868 * No complete header read yet, return what we got.
869 * XXX: Should "unread" header instead.
871 log_error(LOG_LEVEL_INFO,
872 "Failed to read a multi-line header properly: '%s'",
877 if (JB_ERR_OK != string_join(&header, continued_header))
879 log_error(LOG_LEVEL_FATAL,
880 "Out of memory while appending multiple headers.");
884 /* XXX: remove before next stable release. */
885 log_error(LOG_LEVEL_HEADER,
886 "Merged multiple header lines to: '%s'",
891 normalize_lws(header);
898 /*********************************************************************
900 * Function : get_header_line
902 * Description : This (odd) routine will parse the csp->iob
903 * to get the next header line.
906 * 1 : iob = The I/O buffer to parse, usually csp->iob.
908 * Returns : Any one of the following:
910 * 1) a pointer to a dynamically allocated string that contains a header line
911 * 2) NULL indicating that the end of the header was reached
912 * 3) "" indicating that the end of the iob was reached before finding
913 * a complete header line.
915 *********************************************************************/
916 static char *get_header_line(struct iob *iob)
920 if ((iob->cur == NULL)
921 || ((p = strchr(iob->cur, '\n')) == NULL))
923 return(""); /* couldn't find a complete header */
928 ret = strdup(iob->cur);
931 /* FIXME No way to handle error properly */
932 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
938 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
940 /* is this a blank line (i.e. the end of the header) ? */
952 /*********************************************************************
954 * Function : get_header_value
956 * Description : Get the value of a given header from a chained list
957 * of header lines or return NULL if no such header is
958 * present in the list.
961 * 1 : header_list = pointer to list
962 * 2 : header_name = string with name of header to look for.
963 * Trailing colon required, capitalization
966 * Returns : NULL if not found, else value of header
968 *********************************************************************/
969 char *get_header_value(const struct list *header_list, const char *header_name)
971 struct list_entry *cur_entry;
977 length = strlen(header_name);
979 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
983 if (!strncmpic(cur_entry->str, header_name, length))
986 * Found: return pointer to start of value
988 ret = cur_entry->str + length;
989 while (*ret && ijb_isspace(*ret)) ret++;
1003 /*********************************************************************
1005 * Function : scan_headers
1007 * Description : Scans headers, applies tags and updates action bits.
1010 * 1 : csp = Current client state (buffers, headers, etc...)
1012 * Returns : JB_ERR_OK
1014 *********************************************************************/
1015 static jb_err scan_headers(struct client_state *csp)
1017 struct list_entry *h; /* Header */
1018 jb_err err = JB_ERR_OK;
1020 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1022 /* Header crunch()ed in previous run? -> ignore */
1023 if (h->str == NULL) continue;
1024 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1025 err = header_tagger(csp, h->str);
1032 /*********************************************************************
1036 * Description : add, delete or modify lines in the HTTP header streams.
1037 * On entry, it receives a linked list of headers space
1038 * that was allocated dynamically (both the list nodes
1039 * and the header contents).
1041 * As a side effect it frees the space used by the original
1045 * 1 : csp = Current client state (buffers, headers, etc...)
1046 * 2 : filter_server_headers = Boolean to switch between
1047 * server and header filtering.
1049 * Returns : JB_ERR_OK in case off success, or
1050 * JB_ERR_MEMORY on out-of-memory error.
1052 *********************************************************************/
1053 jb_err sed(struct client_state *csp, int filter_server_headers)
1055 /* XXX: use more descriptive names. */
1056 struct list_entry *p;
1057 const struct parsers *v;
1058 const add_header_func_ptr *f;
1059 jb_err err = JB_ERR_OK;
1061 if (filter_server_headers)
1063 v = server_patterns;
1064 f = add_server_headers;
1068 v = client_patterns;
1069 f = add_client_headers;
1074 while ((err == JB_ERR_OK) && (v->str != NULL))
1076 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1078 /* Header crunch()ed in previous run? -> ignore */
1079 if (p->str == NULL) continue;
1081 /* Does the current parser handle this header? */
1082 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1083 (v->len == CHECK_EVERY_HEADER_REMAINING))
1085 err = v->parser(csp, &(p->str));
1091 /* place additional headers on the csp->headers list */
1092 while ((err == JB_ERR_OK) && (*f))
1102 /*********************************************************************
1104 * Function : update_server_headers
1106 * Description : Updates server headers after the body has been modified.
1109 * 1 : csp = Current client state (buffers, headers, etc...)
1111 * Returns : JB_ERR_OK in case off success, or
1112 * JB_ERR_MEMORY on out-of-memory error.
1114 *********************************************************************/
1115 jb_err update_server_headers(struct client_state *csp)
1117 jb_err err = JB_ERR_OK;
1119 static const struct parsers server_patterns_light[] = {
1120 { "Content-Length:", 15, server_adjust_content_length },
1121 { "Transfer-Encoding:", 18, server_transfer_coding },
1123 { "Content-Encoding:", 17, server_content_encoding },
1124 #endif /* def FEATURE_ZLIB */
1128 if (strncmpic(csp->http->cmd, "HEAD", 4))
1130 const struct parsers *v;
1131 struct list_entry *p;
1133 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1135 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1137 /* Header crunch()ed in previous run? -> ignore */
1138 if (p->str == NULL) continue;
1140 /* Does the current parser handle this header? */
1141 if (strncmpic(p->str, v->str, v->len) == 0)
1143 err = v->parser(csp, (char **)&(p->str));
1153 /*********************************************************************
1155 * Function : header_tagger
1157 * Description : Executes all text substitutions from applying
1158 * tag actions and saves the result as tag.
1160 * XXX: Shares enough code with filter_header() and
1161 * pcrs_filter_response() to warrant some helper functions.
1164 * 1 : csp = Current client state (buffers, headers, etc...)
1165 * 2 : header = Header that is used as tagger input
1167 * Returns : JB_ERR_OK on success and always succeeds
1169 *********************************************************************/
1170 static jb_err header_tagger(struct client_state *csp, char *header)
1172 int wanted_filter_type;
1173 int multi_action_index;
1177 struct file_list *fl;
1178 struct re_filterfile_spec *b;
1179 struct list_entry *tag_name;
1181 int found_filters = 0;
1182 const size_t header_length = strlen(header);
1184 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1186 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1187 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1191 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1192 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1195 /* Check if there are any filters */
1196 for (i = 0; i < MAX_AF_FILES; i++)
1209 if (0 == found_filters)
1211 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1212 "tagging enabled, but no taggers available.");
1216 for (i = 0; i < MAX_AF_FILES; i++)
1219 if ((NULL == fl) || (NULL == fl->f))
1222 * Either there are no filter files
1223 * left, or this filter file just
1224 * contains no valid filters.
1226 * Continue to be sure we don't miss
1227 * valid filter files that are chained
1228 * after empty or invalid ones.
1233 /* For all filters, */
1234 for (b = fl->f; b; b = b->next)
1236 if (b->type != wanted_filter_type)
1238 /* skip the ones we don't care about, */
1241 /* leaving only taggers that could apply, of which we use the ones, */
1242 for (tag_name = csp->action->multi[multi_action_index]->first;
1243 NULL != tag_name; tag_name = tag_name->next)
1245 /* that do apply, and */
1246 if (strcmp(b->name, tag_name->str) == 0)
1248 char *modified_tag = NULL;
1250 size_t size = header_length;
1251 pcrs_job *joblist = b->joblist;
1253 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1255 if (NULL == joblist)
1257 log_error(LOG_LEVEL_RE_FILTER,
1258 "Tagger %s has empty joblist. Nothing to do.", b->name);
1262 /* execute their pcrs_joblist on the header. */
1263 for (job = joblist; NULL != job; job = job->next)
1265 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1269 /* Success, continue with the modified version. */
1278 /* Tagger doesn't match */
1281 /* Regex failure, log it but continue anyway. */
1282 assert(NULL != header);
1283 log_error(LOG_LEVEL_ERROR,
1284 "Problems with tagger \'%s\' and header \'%s\': %s",
1285 b->name, *header, pcrs_strerror(hits));
1287 freez(modified_tag);
1291 if (b->dynamic) pcrs_free_joblist(joblist);
1293 /* If this tagger matched */
1299 * There is to technical limitation which makes
1300 * it impossible to use empty tags, but I assume
1301 * no one would do it intentionally.
1304 log_error(LOG_LEVEL_INFO,
1305 "Tagger \'%s\' created an empty tag. Ignored.",
1310 if (!list_contains_item(csp->tags, tag))
1312 if (JB_ERR_OK != enlist(csp->tags, tag))
1314 log_error(LOG_LEVEL_ERROR,
1315 "Insufficient memory to add tag \'%s\', "
1316 "based on tagger \'%s\' and header \'%s\'",
1317 tag, b->name, *header);
1321 char *action_message;
1323 * update the action bits right away, to make
1324 * tagging based on tags set by earlier taggers
1325 * of the same kind possible.
1327 if (update_action_bits_for_tag(csp, tag))
1329 action_message = "Action bits updated accordingly.";
1333 action_message = "No action bits update necessary.";
1336 log_error(LOG_LEVEL_HEADER,
1337 "Tagger \'%s\' added tag \'%s\'. %s",
1338 b->name, tag, action_message);
1343 /* XXX: Is this log-worthy? */
1344 log_error(LOG_LEVEL_HEADER,
1345 "Tagger \'%s\' didn't add tag \'%s\'. "
1346 "Tag already present", b->name, tag);
1349 } /* if the tagger matched */
1350 } /* if the tagger applies */
1351 } /* for every tagger that could apply */
1352 } /* for all filters */
1353 } /* for all filter files */
1358 /* here begins the family of parser functions that reformat header lines */
1360 /*********************************************************************
1362 * Function : filter_header
1364 * Description : Executes all text substitutions from all applying
1365 * +(server|client)-header-filter actions on the header.
1366 * Most of the code was copied from pcrs_filter_response,
1367 * including the rather short variable names
1370 * 1 : csp = Current client state (buffers, headers, etc...)
1371 * 2 : header = On input, pointer to header to modify.
1372 * On output, pointer to the modified header, or NULL
1373 * to remove the header. This function frees the
1374 * original string if necessary.
1376 * Returns : JB_ERR_OK on success and always succeeds
1378 *********************************************************************/
1379 static jb_err filter_header(struct client_state *csp, char **header)
1383 size_t size = strlen(*header);
1385 char *newheader = NULL;
1388 struct file_list *fl;
1389 struct re_filterfile_spec *b;
1390 struct list_entry *filtername;
1392 int i, found_filters = 0;
1393 int wanted_filter_type;
1394 int multi_action_index;
1396 if (csp->flags & CSP_FLAG_NO_FILTERING)
1401 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1403 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1404 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1408 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1409 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1413 * Need to check the set of re_filterfiles...
1415 for (i = 0; i < MAX_AF_FILES; i++)
1428 if (0 == found_filters)
1430 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1431 "header filtering enabled, but no matching filters available.");
1435 for (i = 0; i < MAX_AF_FILES; i++)
1438 if ((NULL == fl) || (NULL == fl->f))
1441 * Either there are no filter files
1442 * left, or this filter file just
1443 * contains no valid filters.
1445 * Continue to be sure we don't miss
1446 * valid filter files that are chained
1447 * after empty or invalid ones.
1452 * For all applying +filter actions, look if a filter by that
1453 * name exists and if yes, execute its pcrs_joblist on the
1456 for (b = fl->f; b; b = b->next)
1458 if (b->type != wanted_filter_type)
1460 /* Skip other filter types */
1464 for (filtername = csp->action->multi[multi_action_index]->first;
1465 filtername ; filtername = filtername->next)
1467 if (strcmp(b->name, filtername->str) == 0)
1469 int current_hits = 0;
1470 pcrs_job *joblist = b->joblist;
1472 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1474 if (NULL == joblist)
1476 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1480 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1481 *header, size, b->name);
1483 /* Apply all jobs from the joblist */
1484 for (job = joblist; NULL != job; job = job->next)
1486 matches = pcrs_execute(job, *header, size, &newheader, &size);
1489 current_hits += matches;
1490 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1492 *header = newheader;
1494 else if ( 0 == matches )
1496 /* Filter doesn't change header */
1502 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1503 *header, b->name, pcrs_strerror(matches));
1504 if (newheader != NULL)
1506 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1512 if (b->dynamic) pcrs_free_joblist(joblist);
1514 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1515 hits += current_hits;
1522 * Additionally checking for hits is important because if
1523 * the continue hack is triggered, server headers can
1524 * arrive empty to separate multiple heads from each other.
1526 if ((0 == size) && hits)
1528 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1536 /*********************************************************************
1538 * Function : server_connection
1540 * Description : Makes sure a proper "Connection:" header is
1541 * set and signals connection_header_adder to
1545 * 1 : csp = Current client state (buffers, headers, etc...)
1546 * 2 : header = On input, pointer to header to modify.
1547 * On output, pointer to the modified header, or NULL
1548 * to remove the header. This function frees the
1549 * original string if necessary.
1551 * Returns : JB_ERR_OK on success, or
1552 * JB_ERR_MEMORY on out-of-memory error.
1554 *********************************************************************/
1555 static jb_err server_connection(struct client_state *csp, char **header)
1557 if (!strcmpic(*header, "Connection: keep-alive"))
1559 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1560 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1562 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1565 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1567 log_error(LOG_LEVEL_HEADER,
1568 "Keeping the server header '%s' around.", *header);
1571 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1573 char *old_header = *header;
1575 *header = strdup("Connection: close");
1578 return JB_ERR_MEMORY;
1580 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1585 /* Signal server_connection_adder() to return early. */
1586 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1592 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1593 /*********************************************************************
1595 * Function : server_keep_alive
1597 * Description : Stores the servers keep alive timeout.
1600 * 1 : csp = Current client state (buffers, headers, etc...)
1601 * 2 : header = On input, pointer to header to modify.
1602 * On output, pointer to the modified header, or NULL
1603 * to remove the header. This function frees the
1604 * original string if necessary.
1606 * Returns : JB_ERR_OK.
1608 *********************************************************************/
1609 static jb_err server_keep_alive(struct client_state *csp, char **header)
1611 unsigned int keep_alive_timeout;
1612 const char *timeout_position = strstr(*header, "timeout=");
1614 if ((NULL == timeout_position)
1615 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1617 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1621 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1623 log_error(LOG_LEVEL_HEADER,
1624 "Reducing keep-alive timeout from %u to %u.",
1625 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1626 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1630 /* XXX: Is this log worthy? */
1631 log_error(LOG_LEVEL_HEADER,
1632 "Server keep-alive timeout is %u. Sticking with %u.",
1633 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1639 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1643 /*********************************************************************
1645 * Function : client_connection
1647 * Description : Makes sure a proper "Connection:" header is
1648 * set and signals connection_header_adder
1652 * 1 : csp = Current client state (buffers, headers, etc...)
1653 * 2 : header = On input, pointer to header to modify.
1654 * On output, pointer to the modified header, or NULL
1655 * to remove the header. This function frees the
1656 * original string if necessary.
1658 * Returns : JB_ERR_OK on success, or
1659 * JB_ERR_MEMORY on out-of-memory error.
1661 *********************************************************************/
1662 static jb_err client_connection(struct client_state *csp, char **header)
1664 const char *wanted_header = get_appropiate_connection_header(csp);
1666 if (strcmpic(*header, wanted_header))
1668 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1669 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1671 log_error(LOG_LEVEL_HEADER,
1672 "Keeping the client header '%s' around. "
1673 "The connection will not be kept alive.",
1677 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1679 char *old_header = *header;
1681 *header = strdup(wanted_header);
1684 return JB_ERR_MEMORY;
1686 log_error(LOG_LEVEL_HEADER,
1687 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1691 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1694 log_error(LOG_LEVEL_HEADER,
1695 "Keeping the client header '%s' around. "
1696 "The server connection will be kept alive if possible.",
1698 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1700 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1702 /* Signal client_connection_adder() to return early. */
1703 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1709 /*********************************************************************
1711 * Function : crumble
1713 * Description : This is called if a header matches a pattern to "crunch"
1716 * 1 : csp = Current client state (buffers, headers, etc...)
1717 * 2 : header = On input, pointer to header to modify.
1718 * On output, pointer to the modified header, or NULL
1719 * to remove the header. This function frees the
1720 * original string if necessary.
1722 * Returns : JB_ERR_OK on success, or
1723 * JB_ERR_MEMORY on out-of-memory error.
1725 *********************************************************************/
1726 static jb_err crumble(struct client_state *csp, char **header)
1729 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1735 /*********************************************************************
1737 * Function : crunch_server_header
1739 * Description : Crunch server header if it matches a string supplied by the
1740 * user. Called from `sed'.
1743 * 1 : csp = Current client state (buffers, headers, etc...)
1744 * 2 : header = On input, pointer to header to modify.
1745 * On output, pointer to the modified header, or NULL
1746 * to remove the header. This function frees the
1747 * original string if necessary.
1749 * Returns : JB_ERR_OK on success and always succeeds
1751 *********************************************************************/
1752 static jb_err crunch_server_header(struct client_state *csp, char **header)
1754 const char *crunch_pattern;
1756 /* Do we feel like crunching? */
1757 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1759 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1761 /* Is the current header the lucky one? */
1762 if (strstr(*header, crunch_pattern))
1764 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1773 /*********************************************************************
1775 * Function : server_content_type
1777 * Description : Set the content-type for filterable types (text/.*,
1778 * .*xml.*, javascript and image/gif) unless filtering has been
1779 * forbidden (CT_TABOO) while parsing earlier headers.
1780 * NOTE: Since text/plain is commonly used by web servers
1781 * for files whose correct type is unknown, we don't
1782 * set CT_TEXT for it.
1785 * 1 : csp = Current client state (buffers, headers, etc...)
1786 * 2 : header = On input, pointer to header to modify.
1787 * On output, pointer to the modified header, or NULL
1788 * to remove the header. This function frees the
1789 * original string if necessary.
1791 * Returns : JB_ERR_OK on success, or
1792 * JB_ERR_MEMORY on out-of-memory error.
1794 *********************************************************************/
1795 static jb_err server_content_type(struct client_state *csp, char **header)
1797 /* Remove header if it isn't the first Content-Type header */
1798 if ((csp->content_type & CT_DECLARED))
1801 * Another, slightly slower, way to see if
1802 * we already parsed another Content-Type header.
1804 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1806 log_error(LOG_LEVEL_ERROR,
1807 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1815 * Signal that the Content-Type has been set.
1817 csp->content_type |= CT_DECLARED;
1819 if (!(csp->content_type & CT_TABOO))
1822 * XXX: The assumption that text/plain is a sign of
1823 * binary data seems to be somewhat unreasonable nowadays
1824 * and should be dropped after 3.0.8 is out.
1826 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
1827 || strstr(*header, "xml")
1828 || strstr(*header, "application/x-javascript"))
1830 csp->content_type |= CT_TEXT;
1832 else if (strstr(*header, "image/gif"))
1834 csp->content_type |= CT_GIF;
1839 * Are we messing with the content type?
1841 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1844 * Make sure the user doesn't accidently
1845 * change the content type of binary documents.
1847 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
1850 *header = strdup("Content-Type: ");
1851 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1855 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1856 return JB_ERR_MEMORY;
1858 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1862 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
1863 "It doesn't look like a content type that should be filtered. "
1864 "Enable force-text-mode if you know what you're doing.", *header);
1872 /*********************************************************************
1874 * Function : server_transfer_coding
1876 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1877 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1878 * - Remove header if body was chunked but has been
1879 * de-chunked for filtering.
1882 * 1 : csp = Current client state (buffers, headers, etc...)
1883 * 2 : header = On input, pointer to header to modify.
1884 * On output, pointer to the modified header, or NULL
1885 * to remove the header. This function frees the
1886 * original string if necessary.
1888 * Returns : JB_ERR_OK on success, or
1889 * JB_ERR_MEMORY on out-of-memory error.
1891 *********************************************************************/
1892 static jb_err server_transfer_coding(struct client_state *csp, char **header)
1895 * Turn off pcrs and gif filtering if body compressed
1897 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1901 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1903 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1904 csp->http->cmd, *header);
1905 #endif /* def FEATURE_ZLIB */
1906 csp->content_type = CT_TABOO;
1910 * Raise flag if body chunked
1912 if (strstr(*header, "chunked"))
1914 csp->flags |= CSP_FLAG_CHUNKED;
1917 * If the body was modified, it has been de-chunked first
1918 * and the header must be removed.
1920 * FIXME: If there is more than one transfer encoding,
1921 * only the "chunked" part should be removed here.
1923 if (csp->flags & CSP_FLAG_MODIFIED)
1925 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1934 /*********************************************************************
1936 * Function : server_content_encoding
1938 * Description : This function is run twice for each request,
1939 * unless FEATURE_ZLIB and filtering are disabled.
1941 * The first run is used to check if the content
1942 * is compressed, if FEATURE_ZLIB is disabled
1943 * filtering is then disabled as well, if FEATURE_ZLIB
1944 * is enabled the content is marked for decompression.
1946 * The second run is used to remove the Content-Encoding
1947 * header if the decompression was successful.
1950 * 1 : csp = Current client state (buffers, headers, etc...)
1951 * 2 : header = On input, pointer to header to modify.
1952 * On output, pointer to the modified header, or NULL
1953 * to remove the header. This function frees the
1954 * original string if necessary.
1956 * Returns : JB_ERR_OK on success, or
1957 * JB_ERR_MEMORY on out-of-memory error.
1959 *********************************************************************/
1960 static jb_err server_content_encoding(struct client_state *csp, char **header)
1963 if ((csp->flags & CSP_FLAG_MODIFIED)
1964 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1967 * We successfully decompressed the content,
1968 * and have to clean the header now, so the
1969 * client no longer expects compressed data..
1971 * XXX: There is a difference between cleaning
1972 * and removing it completely.
1974 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1977 else if (strstr(*header, "gzip"))
1979 /* Mark for gzip decompression */
1980 csp->content_type |= CT_GZIP;
1982 else if (strstr(*header, "deflate"))
1984 /* Mark for zlib decompression */
1985 csp->content_type |= CT_DEFLATE;
1987 else if (strstr(*header, "compress"))
1990 * We can't decompress this; therefore we can't filter
1993 csp->content_type |= CT_TABOO;
1995 #else /* !defined(FEATURE_ZLIB) */
1996 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1999 * Body is compressed, turn off pcrs and gif filtering.
2001 csp->content_type |= CT_TABOO;
2004 * Log a warning if the user expects the content to be filtered.
2006 if ((csp->rlist != NULL) &&
2007 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2009 log_error(LOG_LEVEL_INFO,
2010 "Compressed content detected, content filtering disabled. "
2011 "Consider recompiling Privoxy with zlib support or "
2012 "enable the prevent-compression action.");
2015 #endif /* defined(FEATURE_ZLIB) */
2022 /*********************************************************************
2024 * Function : server_adjust_content_length
2026 * Description : Adjust Content-Length header if we modified
2030 * 1 : csp = Current client state (buffers, headers, etc...)
2031 * 2 : header = On input, pointer to header to modify.
2032 * On output, pointer to the modified header, or NULL
2033 * to remove the header. This function frees the
2034 * original string if necessary.
2036 * Returns : JB_ERR_OK on success, or
2037 * JB_ERR_MEMORY on out-of-memory error.
2039 *********************************************************************/
2040 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2042 const size_t max_header_length = 80;
2044 /* Regenerate header if the content was modified. */
2045 if (csp->flags & CSP_FLAG_MODIFIED)
2048 *header = (char *) zalloc(max_header_length);
2049 if (*header == NULL)
2051 return JB_ERR_MEMORY;
2054 snprintf(*header, max_header_length, "Content-Length: %d",
2055 (int)csp->content_length);
2056 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2057 (int)csp->content_length);
2064 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2065 /*********************************************************************
2067 * Function : server_save_content_length
2069 * Description : Save the Content-Length sent by the server.
2072 * 1 : csp = Current client state (buffers, headers, etc...)
2073 * 2 : header = On input, pointer to header to modify.
2074 * On output, pointer to the modified header, or NULL
2075 * to remove the header. This function frees the
2076 * original string if necessary.
2078 * Returns : JB_ERR_OK on success, or
2079 * JB_ERR_MEMORY on out-of-memory error.
2081 *********************************************************************/
2082 static jb_err server_save_content_length(struct client_state *csp, char **header)
2084 unsigned long long content_length = 0;
2086 assert(*(*header+14) == ':');
2088 if (1 != sscanf(*header+14, ": %llu", &content_length))
2090 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2095 csp->expected_content_length = content_length;
2096 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2101 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2104 /*********************************************************************
2106 * Function : server_content_md5
2108 * Description : Crumble any Content-MD5 headers if the document was
2109 * modified. FIXME: Should we re-compute instead?
2112 * 1 : csp = Current client state (buffers, headers, etc...)
2113 * 2 : header = On input, pointer to header to modify.
2114 * On output, pointer to the modified header, or NULL
2115 * to remove the header. This function frees the
2116 * original string if necessary.
2118 * Returns : JB_ERR_OK on success, or
2119 * JB_ERR_MEMORY on out-of-memory error.
2121 *********************************************************************/
2122 static jb_err server_content_md5(struct client_state *csp, char **header)
2124 if (csp->flags & CSP_FLAG_MODIFIED)
2126 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2134 /*********************************************************************
2136 * Function : server_content_disposition
2138 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2139 * Called from `sed'.
2142 * 1 : csp = Current client state (buffers, headers, etc...)
2143 * 2 : header = On input, pointer to header to modify.
2144 * On output, pointer to the modified header, or NULL
2145 * to remove the header. This function frees the
2146 * original string if necessary.
2148 * Returns : JB_ERR_OK on success, or
2149 * JB_ERR_MEMORY on out-of-memory error.
2151 *********************************************************************/
2152 static jb_err server_content_disposition(struct client_state *csp, char **header)
2157 * Are we messing with the Content-Disposition header?
2159 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2165 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2167 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2170 * Blocking content-disposition header
2172 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2179 * Replacing Content-Disposition header
2182 *header = strdup("Content-Disposition: ");
2183 string_append(header, newval);
2185 if (*header != NULL)
2187 log_error(LOG_LEVEL_HEADER,
2188 "Content-Disposition header crunched and replaced with: %s", *header);
2191 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2195 /*********************************************************************
2197 * Function : server_last_modified
2199 * Description : Changes Last-Modified header to the actual date
2200 * to help hide-if-modified-since.
2201 * Called from `sed'.
2204 * 1 : csp = Current client state (buffers, headers, etc...)
2205 * 2 : header = On input, pointer to header to modify.
2206 * On output, pointer to the modified header, or NULL
2207 * to remove the header. This function frees the
2208 * original string if necessary.
2210 * Returns : JB_ERR_OK on success, or
2211 * JB_ERR_MEMORY on out-of-memory error.
2213 *********************************************************************/
2214 static jb_err server_last_modified(struct client_state *csp, char **header)
2217 char buf[BUFFER_SIZE];
2220 #ifdef HAVE_GMTIME_R
2223 struct tm *timeptr = NULL;
2224 time_t now, last_modified;
2225 long int days, hours, minutes, seconds;
2228 * Are we messing with the Last-Modified header?
2230 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2236 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2238 if (0 == strcmpic(newval, "block") )
2241 * Blocking Last-Modified header. Useless but why not.
2243 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2247 else if (0 == strcmpic(newval, "reset-to-request-time"))
2250 * Setting Last-Modified Header to now.
2252 get_http_time(0, buf, sizeof(buf));
2254 *header = strdup("Last-Modified: ");
2255 string_append(header, buf);
2257 if (*header == NULL)
2259 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2263 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2266 else if (0 == strcmpic(newval, "randomize"))
2268 const char *header_time = *header + sizeof("Last-Modified:");
2270 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2272 #ifdef HAVE_GMTIME_R
2273 gmtime_r(&now, &gmt);
2274 #elif defined(MUTEX_LOCKS_AVAILABLE)
2275 privoxy_mutex_lock(&gmtime_mutex);
2277 privoxy_mutex_unlock(&gmtime_mutex);
2281 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2283 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2288 long int rtime = (long int)difftime(now, last_modified);
2291 const int negative_delta = (rtime < 0);
2296 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2298 rtime = pick_from_range(rtime);
2303 last_modified += rtime;
2304 #ifdef HAVE_GMTIME_R
2305 timeptr = gmtime_r(&last_modified, &gmt);
2306 #elif defined(MUTEX_LOCKS_AVAILABLE)
2307 privoxy_mutex_lock(&gmtime_mutex);
2308 timeptr = gmtime(&last_modified);
2309 privoxy_mutex_unlock(&gmtime_mutex);
2311 timeptr = gmtime(&last_modified);
2313 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2315 *header = strdup("Last-Modified: ");
2316 string_append(header, newheader);
2318 if (*header == NULL)
2320 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2321 return JB_ERR_MEMORY;
2324 days = rtime / (3600 * 24);
2325 hours = rtime / 3600 % 24;
2326 minutes = rtime / 60 % 60;
2327 seconds = rtime % 60;
2329 log_error(LOG_LEVEL_HEADER,
2330 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2331 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2332 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2336 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2345 /*********************************************************************
2347 * Function : client_accept_encoding
2349 * Description : Rewrite the client's Accept-Encoding header so that
2350 * if doesn't allow compression, if the action applies.
2351 * Note: For HTTP/1.0 the absence of the header is enough.
2354 * 1 : csp = Current client state (buffers, headers, etc...)
2355 * 2 : header = On input, pointer to header to modify.
2356 * On output, pointer to the modified header, or NULL
2357 * to remove the header. This function frees the
2358 * original string if necessary.
2360 * Returns : JB_ERR_OK on success, or
2361 * JB_ERR_MEMORY on out-of-memory error.
2363 *********************************************************************/
2364 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2366 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2368 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2372 /* Temporarily disable the correct behaviour to
2373 * work around a PHP bug.
2375 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2377 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2378 * if (*header == NULL)
2380 * return JB_ERR_MEMORY;
2391 /*********************************************************************
2393 * Function : client_te
2395 * Description : Rewrite the client's TE header so that
2396 * if doesn't allow compression, if the action applies.
2399 * 1 : csp = Current client state (buffers, headers, etc...)
2400 * 2 : header = On input, pointer to header to modify.
2401 * On output, pointer to the modified header, or NULL
2402 * to remove the header. This function frees the
2403 * original string if necessary.
2405 * Returns : JB_ERR_OK on success, or
2406 * JB_ERR_MEMORY on out-of-memory error.
2408 *********************************************************************/
2409 static jb_err client_te(struct client_state *csp, char **header)
2411 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2414 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2421 /*********************************************************************
2423 * Function : client_referrer
2425 * Description : Handle the "referer" config setting properly.
2426 * Called from `sed'.
2429 * 1 : csp = Current client state (buffers, headers, etc...)
2430 * 2 : header = On input, pointer to header to modify.
2431 * On output, pointer to the modified header, or NULL
2432 * to remove the header. This function frees the
2433 * original string if necessary.
2435 * Returns : JB_ERR_OK on success, or
2436 * JB_ERR_MEMORY on out-of-memory error.
2438 *********************************************************************/
2439 static jb_err client_referrer(struct client_state *csp, char **header)
2441 const char *parameter;
2442 /* booleans for parameters we have to check multiple times */
2443 int parameter_conditional_block;
2444 int parameter_conditional_forge;
2446 #ifdef FEATURE_FORCE_LOAD
2448 * Since the referrer can include the prefix even
2449 * if the request itself is non-forced, we must
2450 * clean it unconditionally.
2452 * XXX: strclean is too broad
2454 strclean(*header, FORCE_PREFIX);
2455 #endif /* def FEATURE_FORCE_LOAD */
2457 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2459 /* Nothing left to do */
2463 parameter = csp->action->string[ACTION_STRING_REFERER];
2464 assert(parameter != NULL);
2465 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2466 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2468 if (!parameter_conditional_block && !parameter_conditional_forge)
2471 * As conditional-block and conditional-forge are the only
2472 * parameters that rely on the original referrer, we can
2473 * remove it now for all the others.
2478 if (0 == strcmpic(parameter, "block"))
2480 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2483 else if (parameter_conditional_block || parameter_conditional_forge)
2485 return handle_conditional_hide_referrer_parameter(header,
2486 csp->http->hostport, parameter_conditional_block);
2488 else if (0 == strcmpic(parameter, "forge"))
2490 return create_forged_referrer(header, csp->http->hostport);
2494 /* interpret parameter as user-supplied referer to fake */
2495 return create_fake_referrer(header, parameter);
2500 /*********************************************************************
2502 * Function : client_accept_language
2504 * Description : Handle the "Accept-Language" config setting properly.
2505 * Called from `sed'.
2508 * 1 : csp = Current client state (buffers, headers, etc...)
2509 * 2 : header = On input, pointer to header to modify.
2510 * On output, pointer to the modified header, or NULL
2511 * to remove the header. This function frees the
2512 * original string if necessary.
2514 * Returns : JB_ERR_OK on success, or
2515 * JB_ERR_MEMORY on out-of-memory error.
2517 *********************************************************************/
2518 static jb_err client_accept_language(struct client_state *csp, char **header)
2523 * Are we messing with the Accept-Language?
2525 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2527 /*I don't think so*/
2531 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2533 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2536 * Blocking Accept-Language header
2538 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2545 * Replacing Accept-Language header
2548 *header = strdup("Accept-Language: ");
2549 string_append(header, newval);
2551 if (*header == NULL)
2553 log_error(LOG_LEVEL_ERROR,
2554 "Insufficient memory. Accept-Language header crunched without replacement.");
2558 log_error(LOG_LEVEL_HEADER,
2559 "Accept-Language header crunched and replaced with: %s", *header);
2562 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2566 /*********************************************************************
2568 * Function : crunch_client_header
2570 * Description : Crunch client header if it matches a string supplied by the
2571 * user. Called from `sed'.
2574 * 1 : csp = Current client state (buffers, headers, etc...)
2575 * 2 : header = On input, pointer to header to modify.
2576 * On output, pointer to the modified header, or NULL
2577 * to remove the header. This function frees the
2578 * original string if necessary.
2580 * Returns : JB_ERR_OK on success and always succeeds
2582 *********************************************************************/
2583 static jb_err crunch_client_header(struct client_state *csp, char **header)
2585 const char *crunch_pattern;
2587 /* Do we feel like crunching? */
2588 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2590 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2592 /* Is the current header the lucky one? */
2593 if (strstr(*header, crunch_pattern))
2595 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2603 /*********************************************************************
2605 * Function : client_uagent
2607 * Description : Handle the "user-agent" config setting properly
2608 * and remember its original value to enable browser
2609 * bug workarounds. Called from `sed'.
2612 * 1 : csp = Current client state (buffers, headers, etc...)
2613 * 2 : header = On input, pointer to header to modify.
2614 * On output, pointer to the modified header, or NULL
2615 * to remove the header. This function frees the
2616 * original string if necessary.
2618 * Returns : JB_ERR_OK on success, or
2619 * JB_ERR_MEMORY on out-of-memory error.
2621 *********************************************************************/
2622 static jb_err client_uagent(struct client_state *csp, char **header)
2626 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2631 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2638 *header = strdup("User-Agent: ");
2639 string_append(header, newval);
2641 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2643 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2647 /*********************************************************************
2649 * Function : client_ua
2651 * Description : Handle "ua-" headers properly. Called from `sed'.
2654 * 1 : csp = Current client state (buffers, headers, etc...)
2655 * 2 : header = On input, pointer to header to modify.
2656 * On output, pointer to the modified header, or NULL
2657 * to remove the header. This function frees the
2658 * original string if necessary.
2660 * Returns : JB_ERR_OK on success, or
2661 * JB_ERR_MEMORY on out-of-memory error.
2663 *********************************************************************/
2664 static jb_err client_ua(struct client_state *csp, char **header)
2666 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2668 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2676 /*********************************************************************
2678 * Function : client_from
2680 * Description : Handle the "from" config setting properly.
2681 * Called from `sed'.
2684 * 1 : csp = Current client state (buffers, headers, etc...)
2685 * 2 : header = On input, pointer to header to modify.
2686 * On output, pointer to the modified header, or NULL
2687 * to remove the header. This function frees the
2688 * original string if necessary.
2690 * Returns : JB_ERR_OK on success, or
2691 * JB_ERR_MEMORY on out-of-memory error.
2693 *********************************************************************/
2694 static jb_err client_from(struct client_state *csp, char **header)
2698 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2705 newval = csp->action->string[ACTION_STRING_FROM];
2708 * Are we blocking the e-mail address?
2710 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2712 log_error(LOG_LEVEL_HEADER, "crunched From!");
2716 log_error(LOG_LEVEL_HEADER, " modified");
2718 *header = strdup("From: ");
2719 string_append(header, newval);
2721 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2725 /*********************************************************************
2727 * Function : client_send_cookie
2729 * Description : Crunches the "cookie" header if necessary.
2730 * Called from `sed'.
2732 * XXX: Stupid name, doesn't send squat.
2735 * 1 : csp = Current client state (buffers, headers, etc...)
2736 * 2 : header = On input, pointer to header to modify.
2737 * On output, pointer to the modified header, or NULL
2738 * to remove the header. This function frees the
2739 * original string if necessary.
2741 * Returns : JB_ERR_OK on success, or
2742 * JB_ERR_MEMORY on out-of-memory error.
2744 *********************************************************************/
2745 static jb_err client_send_cookie(struct client_state *csp, char **header)
2747 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2749 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2757 /*********************************************************************
2759 * Function : client_x_forwarded
2761 * Description : Handle the "x-forwarded-for" config setting properly,
2762 * also used in the add_client_headers list. Called from `sed'.
2765 * 1 : csp = Current client state (buffers, headers, etc...)
2766 * 2 : header = On input, pointer to header to modify.
2767 * On output, pointer to the modified header, or NULL
2768 * to remove the header. This function frees the
2769 * original string if necessary.
2771 * Returns : JB_ERR_OK on success, or
2772 * JB_ERR_MEMORY on out-of-memory error.
2774 *********************************************************************/
2775 jb_err client_x_forwarded(struct client_state *csp, char **header)
2777 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
2779 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
2781 if (0 == strcmpic(parameter, "block"))
2784 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2786 else if (0 == strcmpic(parameter, "add"))
2788 string_append(header, ", ");
2789 string_append(header, csp->ip_addr_str);
2791 if (*header == NULL)
2793 return JB_ERR_MEMORY;
2795 log_error(LOG_LEVEL_HEADER,
2796 "Appended client IP address to %s", *header);
2797 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
2801 log_error(LOG_LEVEL_FATAL,
2802 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
2810 /*********************************************************************
2812 * Function : client_max_forwards
2814 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2815 * from the value of the Max-Forwards header field.
2818 * 1 : csp = Current client state (buffers, headers, etc...)
2819 * 2 : header = On input, pointer to header to modify.
2820 * On output, pointer to the modified header, or NULL
2821 * to remove the header. This function frees the
2822 * original string if necessary.
2824 * Returns : JB_ERR_OK on success, or
2825 * JB_ERR_MEMORY on out-of-memory error.
2827 *********************************************************************/
2828 static jb_err client_max_forwards(struct client_state *csp, char **header)
2832 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2833 (0 == strcmpic(csp->http->gpc, "options")))
2835 assert(*(*header+12) == ':');
2836 if (1 == sscanf(*header+12, ": %d", &max_forwards))
2838 if (max_forwards > 0)
2840 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
2841 log_error(LOG_LEVEL_HEADER,
2842 "Max-Forwards value for %s request reduced to %d.",
2843 csp->http->gpc, max_forwards);
2845 else if (max_forwards < 0)
2847 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2853 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2862 /*********************************************************************
2864 * Function : client_host
2866 * Description : If the request URI did not contain host and
2867 * port information, parse and evaluate the Host
2870 * Also, kill ill-formed HOST: headers as sent by
2871 * Apple's iTunes software when used with a proxy.
2874 * 1 : csp = Current client state (buffers, headers, etc...)
2875 * 2 : header = On input, pointer to header to modify.
2876 * On output, pointer to the modified header, or NULL
2877 * to remove the header. This function frees the
2878 * original string if necessary.
2880 * Returns : JB_ERR_OK on success, or
2881 * JB_ERR_MEMORY on out-of-memory error.
2883 *********************************************************************/
2884 static jb_err client_host(struct client_state *csp, char **header)
2889 * If the header field name is all upper-case, chances are that it's
2890 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2891 * not a problem -- they are regenerated later.
2893 if ((*header)[1] == 'O')
2895 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2900 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2901 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2904 if (NULL == (p = strdup((*header)+6)))
2906 return JB_ERR_MEMORY;
2909 if (NULL == (q = strdup(p)))
2912 return JB_ERR_MEMORY;
2915 freez(csp->http->hostport);
2916 csp->http->hostport = p;
2917 freez(csp->http->host);
2918 csp->http->host = q;
2919 q = strchr(csp->http->host, ':');
2922 /* Terminate hostname and evaluate port string */
2924 csp->http->port = atoi(q);
2928 csp->http->port = csp->http->ssl ? 443 : 80;
2931 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2932 csp->http->hostport, csp->http->host, csp->http->port);
2935 /* Signal client_host_adder() to return right away */
2936 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
2942 /*********************************************************************
2944 * Function : client_if_modified_since
2946 * Description : Remove or modify the If-Modified-Since header.
2949 * 1 : csp = Current client state (buffers, headers, etc...)
2950 * 2 : header = On input, pointer to header to modify.
2951 * On output, pointer to the modified header, or NULL
2952 * to remove the header. This function frees the
2953 * original string if necessary.
2955 * Returns : JB_ERR_OK on success, or
2956 * JB_ERR_MEMORY on out-of-memory error.
2958 *********************************************************************/
2959 static jb_err client_if_modified_since(struct client_state *csp, char **header)
2962 #ifdef HAVE_GMTIME_R
2965 struct tm *timeptr = NULL;
2968 long int hours, minutes, seconds;
2971 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2974 * The client got an error message because of a temporary problem,
2975 * the problem is gone and the client now tries to revalidate our
2976 * error message on the real server. The revalidation would always
2977 * end with the transmission of the whole document and there is
2978 * no need to expose the bogus If-Modified-Since header.
2980 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2983 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2985 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2987 if ((0 == strcmpic(newval, "block")))
2989 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2992 else /* add random value */
2994 const char *header_time = *header + sizeof("If-Modified-Since:");
2996 if (JB_ERR_OK != parse_header_time(header_time, &tm))
2998 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3003 long int rtime = strtol(newval, &endptr, 0);
3004 const int negative_range = (rtime < 0);
3008 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3009 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3015 rtime = pick_from_range(rtime);
3019 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3022 tm += rtime * (negative_range ? -1 : 1);
3023 #ifdef HAVE_GMTIME_R
3024 timeptr = gmtime_r(&tm, &gmt);
3025 #elif defined(MUTEX_LOCKS_AVAILABLE)
3026 privoxy_mutex_lock(&gmtime_mutex);
3027 timeptr = gmtime(&tm);
3028 privoxy_mutex_unlock(&gmtime_mutex);
3030 timeptr = gmtime(&tm);
3032 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3035 *header = strdup("If-Modified-Since: ");
3036 string_append(header, newheader);
3038 if (*header == NULL)
3040 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3041 return JB_ERR_MEMORY;
3044 hours = rtime / 3600;
3045 minutes = rtime / 60 % 60;
3046 seconds = rtime % 60;
3048 log_error(LOG_LEVEL_HEADER,
3049 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3050 *header, (negative_range) ? "subtracted" : "added", hours,
3051 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3052 seconds, (seconds == 1) ? ")" : "s)");
3061 /*********************************************************************
3063 * Function : client_if_none_match
3065 * Description : Remove the If-None-Match header.
3068 * 1 : csp = Current client state (buffers, headers, etc...)
3069 * 2 : header = On input, pointer to header to modify.
3070 * On output, pointer to the modified header, or NULL
3071 * to remove the header. This function frees the
3072 * original string if necessary.
3074 * Returns : JB_ERR_OK on success, or
3075 * JB_ERR_MEMORY on out-of-memory error.
3077 *********************************************************************/
3078 static jb_err client_if_none_match(struct client_state *csp, char **header)
3080 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3082 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3090 /*********************************************************************
3092 * Function : client_x_filter
3094 * Description : Disables filtering if the client set "X-Filter: No".
3095 * Called from `sed'.
3098 * 1 : csp = Current client state (buffers, headers, etc...)
3099 * 2 : header = On input, pointer to header to modify.
3100 * On output, pointer to the modified header, or NULL
3101 * to remove the header. This function frees the
3102 * original string if necessary.
3104 * Returns : JB_ERR_OK on success
3106 *********************************************************************/
3107 jb_err client_x_filter(struct client_state *csp, char **header)
3109 if ( 0 == strcmpic(*header, "X-Filter: No"))
3111 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3113 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3117 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3119 log_error(LOG_LEVEL_HEADER,
3120 "force-text-mode overruled the client's request to fetch without filtering!");
3124 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3125 csp->flags |= CSP_FLAG_NO_FILTERING;
3126 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3128 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3136 /*********************************************************************
3138 * Function : client_range
3140 * Description : Removes Range, Request-Range and If-Range headers if
3141 * content filtering is enabled. If the client's version
3142 * of the document has been altered by Privoxy, the server
3143 * could interpret the range differently than the client
3144 * intended in which case the user could end up with
3145 * corrupted content.
3148 * 1 : csp = Current client state (buffers, headers, etc...)
3149 * 2 : header = On input, pointer to header to modify.
3150 * On output, pointer to the modified header, or NULL
3151 * to remove the header. This function frees the
3152 * original string if necessary.
3154 * Returns : JB_ERR_OK
3156 *********************************************************************/
3157 static jb_err client_range(struct client_state *csp, char **header)
3159 if (content_filters_enabled(csp->action))
3161 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3162 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3169 /* the following functions add headers directly to the header list */
3171 /*********************************************************************
3173 * Function : client_host_adder
3175 * Description : Adds the Host: header field if it is missing.
3176 * Called from `sed'.
3179 * 1 : csp = Current client state (buffers, headers, etc...)
3181 * Returns : JB_ERR_OK on success, or
3182 * JB_ERR_MEMORY on out-of-memory error.
3184 *********************************************************************/
3185 static jb_err client_host_adder(struct client_state *csp)
3190 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3192 /* Header already set by the client, nothing to do. */
3196 if ( !csp->http->hostport || !*(csp->http->hostport))
3198 /* XXX: When does this happen and why is it OK? */
3199 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3204 * remove 'user:pass@' from 'proto://user:pass@host'
3206 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3212 p = csp->http->hostport;
3215 /* XXX: Just add it, we already made sure that it will be unique */
3216 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3217 err = enlist_unique_header(csp->headers, "Host", p);
3224 /*********************************************************************
3226 * Function : client_accept_encoding_adder
3228 * Description : Add an Accept-Encoding header to the client's request
3229 * that disables compression if the action applies, and
3230 * the header is not already there. Called from `sed'.
3231 * Note: For HTTP/1.0, the absence of the header is enough.
3234 * 1 : csp = Current client state (buffers, headers, etc...)
3236 * Returns : JB_ERR_OK on success, or
3237 * JB_ERR_MEMORY on out-of-memory error.
3239 *********************************************************************/
3240 static jb_err client_accept_encoding_adder(struct client_state *csp)
3242 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3243 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3245 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3253 /*********************************************************************
3255 * Function : client_xtra_adder
3257 * Description : Used in the add_client_headers list. Called from `sed'.
3260 * 1 : csp = Current client state (buffers, headers, etc...)
3262 * Returns : JB_ERR_OK on success, or
3263 * JB_ERR_MEMORY on out-of-memory error.
3265 *********************************************************************/
3266 static jb_err client_xtra_adder(struct client_state *csp)
3268 struct list_entry *lst;
3271 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3272 lst ; lst = lst->next)
3274 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3275 err = enlist(csp->headers, lst->str);
3287 /*********************************************************************
3289 * Function : client_x_forwarded_for_adder
3291 * Description : Used in the add_client_headers list. Called from `sed'.
3294 * 1 : csp = Current client state (buffers, headers, etc...)
3296 * Returns : JB_ERR_OK on success, or
3297 * JB_ERR_MEMORY on out-of-memory error.
3299 *********************************************************************/
3300 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3302 char *header = NULL;
3305 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3306 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3307 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3310 * If we aren't adding X-Forwarded-For headers,
3311 * or we already appended an existing X-Forwarded-For
3312 * header, there's nothing left to do here.
3317 header = strdup("X-Forwarded-For: ");
3318 string_append(&header, csp->ip_addr_str);
3322 return JB_ERR_MEMORY;
3325 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3326 err = enlist(csp->headers, header);
3333 /*********************************************************************
3335 * Function : server_connection_adder
3337 * Description : Adds an appropiate "Connection:" header to csp->headers
3338 * unless the header was already present. Called from `sed'.
3341 * 1 : csp = Current client state (buffers, headers, etc...)
3343 * Returns : JB_ERR_OK on success, or
3344 * JB_ERR_MEMORY on out-of-memory error.
3346 *********************************************************************/
3347 static jb_err server_connection_adder(struct client_state *csp)
3349 const unsigned int flags = csp->flags;
3350 const char *response_status_line = csp->headers->first->str;
3351 const char *wanted_header = get_appropiate_connection_header(csp);
3353 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3354 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3360 * XXX: if we downgraded the response, this check will fail.
3362 if ((csp->config->feature_flags &
3363 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3364 && (NULL != response_status_line)
3365 && !strncmpic(response_status_line, "HTTP/1.1", 8))
3367 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3368 "without Connection header implies keep-alive.");
3369 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3372 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3374 return enlist(csp->headers, wanted_header);
3378 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3379 /*********************************************************************
3381 * Function : server_proxy_connection_adder
3383 * Description : Adds a "Proxy-Connection: keep-alive" header to
3384 * csp->headers if the client asked for keep-alive.
3385 * XXX: We should reuse existant ones.
3388 * 1 : csp = Current client state (buffers, headers, etc...)
3390 * Returns : JB_ERR_OK on success, or
3391 * JB_ERR_MEMORY on out-of-memory error.
3393 *********************************************************************/
3394 static jb_err server_proxy_connection_adder(struct client_state *csp)
3396 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3397 jb_err err = JB_ERR_OK;
3399 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3401 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3402 err = enlist(csp->headers, proxy_connection_header);
3407 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3410 /*********************************************************************
3412 * Function : client_connection_header_adder
3414 * Description : Adds a proper "Connection:" header to csp->headers
3415 * unless the header was already present. Called from `sed'.
3418 * 1 : csp = Current client state (buffers, headers, etc...)
3420 * Returns : JB_ERR_OK on success, or
3421 * JB_ERR_MEMORY on out-of-memory error.
3423 *********************************************************************/
3424 static jb_err client_connection_header_adder(struct client_state *csp)
3426 const char *wanted_header = get_appropiate_connection_header(csp);
3428 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3429 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3434 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3435 && (csp->http->ssl == 0))
3437 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3440 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3442 return enlist(csp->headers, wanted_header);
3446 /*********************************************************************
3448 * Function : server_http
3450 * Description : - Save the HTTP Status into csp->http->status
3451 * - Set CT_TABOO to prevent filtering if the answer
3452 * is a partial range (HTTP status 206)
3453 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3457 * 1 : csp = Current client state (buffers, headers, etc...)
3458 * 2 : header = On input, pointer to header to modify.
3459 * On output, pointer to the modified header, or NULL
3460 * to remove the header. This function frees the
3461 * original string if necessary.
3463 * Returns : JB_ERR_OK on success, or
3464 * JB_ERR_MEMORY on out-of-memory error.
3466 *********************************************************************/
3467 static jb_err server_http(struct client_state *csp, char **header)
3469 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3470 if (csp->http->status == 206)
3472 csp->content_type = CT_TABOO;
3475 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3477 /* XXX: Should we do a real validity check here? */
3478 if (strlen(*header) > 8)
3481 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3486 * XXX: Should we block the request or
3487 * enlist a valid status code line here?
3489 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3490 "Downgrading to HTTP/1.0 impossible.");
3498 /*********************************************************************
3500 * Function : server_set_cookie
3502 * Description : Handle the server "cookie" header properly.
3503 * Log cookie to the jar file. Then "crunch",
3504 * accept or rewrite it to a session cookie.
3505 * Called from `sed'.
3507 * TODO: Allow the user to specify a new expiration
3508 * time to cause the cookie to expire even before the
3509 * browser is closed.
3512 * 1 : csp = Current client state (buffers, headers, etc...)
3513 * 2 : header = On input, pointer to header to modify.
3514 * On output, pointer to the modified header, or NULL
3515 * to remove the header. This function frees the
3516 * original string if necessary.
3518 * Returns : JB_ERR_OK on success, or
3519 * JB_ERR_MEMORY on out-of-memory error.
3521 *********************************************************************/
3522 static jb_err server_set_cookie(struct client_state *csp, char **header)
3529 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3531 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3534 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3536 /* Flag whether or not to log a message */
3539 /* A variable to store the tag we're working on */
3542 /* Skip "Set-Cookie:" (11 characters) in header */
3543 cur_tag = *header + 11;
3545 /* skip whitespace between "Set-Cookie:" and value */
3546 while (*cur_tag && ijb_isspace(*cur_tag))
3551 /* Loop through each tag in the cookie */
3555 char *next_tag = strchr(cur_tag, ';');
3556 if (next_tag != NULL)
3558 /* Skip the ';' character itself */
3561 /* skip whitespace ";" and start of tag */
3562 while (*next_tag && ijb_isspace(*next_tag))
3569 /* "Next tag" is the end of the string */
3570 next_tag = cur_tag + strlen(cur_tag);
3574 * Check the expiration date to see
3575 * if the cookie is still valid, if yes,
3576 * rewrite it to a session cookie.
3578 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3580 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3582 /* Did we detect the date properly? */
3583 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3586 * Nope, treat it as if it was still valid.
3588 * XXX: Should we remove the whole cookie instead?
3590 log_error(LOG_LEVEL_ERROR,
3591 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3592 string_move(cur_tag, next_tag);
3598 * Yes. Check if the cookie is still valid.
3600 * If the cookie is already expired it's probably
3601 * a delete cookie and even if it isn't, the browser
3602 * will discard it anyway.
3606 * XXX: timegm() isn't available on some AmigaOS
3607 * versions and our replacement doesn't work.
3609 * Our options are to either:
3611 * - disable session-cookies-only completely if timegm
3614 * - to simply remove all expired tags, like it has
3615 * been done until Privoxy 3.0.6 and to live with
3616 * the consequence that it can cause login/logout
3617 * problems on servers that don't validate their
3618 * input properly, or
3620 * - to replace it with mktime in which
3621 * case there is a slight chance of valid cookies
3622 * passing as already expired.
3624 * This is the way it's currently done and it's not
3625 * as bad as it sounds. If the missing GMT offset is
3626 * enough to change the result of the expiration check
3627 * the cookie will be only valid for a few hours
3628 * anyway, which in many cases will be shorter
3629 * than a browser session.
3631 if (cookie_time - now < 0)
3633 log_error(LOG_LEVEL_HEADER,
3634 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3635 /* Just in case some clown sets more then one expiration date */
3641 * Still valid, delete expiration date by copying
3642 * the rest of the string over it.
3644 string_move(cur_tag, next_tag);
3646 /* That changed the header, need to issue a log message */
3650 * Note that the next tag has now been moved to *cur_tag,
3651 * so we do not need to update the cur_tag pointer.
3659 /* Move on to next cookie tag */
3666 assert(NULL != *header);
3667 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3676 #ifdef FEATURE_FORCE_LOAD
3677 /*********************************************************************
3679 * Function : strclean
3681 * Description : In-Situ-Eliminate all occurances of substring in
3685 * 1 : string = string to clean
3686 * 2 : substring = substring to eliminate
3688 * Returns : Number of eliminations
3690 *********************************************************************/
3691 int strclean(char *string, const char *substring)
3697 len = strlen(substring);
3699 while((pos = strstr(string, substring)) != NULL)
3706 while (*p++ != '\0');
3713 #endif /* def FEATURE_FORCE_LOAD */
3716 /*********************************************************************
3718 * Function : parse_header_time
3720 * Description : Parses time formats used in HTTP header strings
3721 * to get the numerical respresentation.
3724 * 1 : header_time = HTTP header time as string.
3725 * 2 : result = storage for header_time in seconds
3727 * Returns : JB_ERR_OK if the time format was recognized, or
3728 * JB_ERR_PARSE otherwise.
3730 *********************************************************************/
3731 static jb_err parse_header_time(const char *header_time, time_t *result)
3736 * Zero out gmt to prevent time zone offsets.
3738 * While this is only necessary on some platforms
3739 * (mingw32 for example), I don't know how to
3740 * detect these automatically and doing it everywhere
3743 memset(&gmt, 0, sizeof(gmt));
3745 /* Tue, 02 Jun 2037 20:00:00 */
3746 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3747 /* Tue, 02-Jun-2037 20:00:00 */
3748 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3749 /* Tue, 02-Jun-37 20:00:00 */
3750 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3751 /* Tuesday, 02-Jun-2037 20:00:00 */
3752 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3753 /* Tuesday Jun 02 20:00:00 2037 */
3754 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3756 return JB_ERR_PARSE;
3759 *result = timegm(&gmt);
3766 /*********************************************************************
3768 * Function : get_destination_from_headers
3770 * Description : Parse the "Host:" header to get the request's destination.
3771 * Only needed if the client's request was forcefully
3772 * redirected into Privoxy.
3774 * Code mainly copied from client_host() which is currently
3775 * run too late for this purpose.
3778 * 1 : headers = List of headers (one of them hopefully being
3779 * the "Host:" header)
3780 * 2 : http = storage for the result (host, port and hostport).
3782 * Returns : JB_ERR_MEMORY in case of memory problems,
3783 * JB_ERR_PARSE if the host header couldn't be found,
3784 * JB_ERR_OK otherwise.
3786 *********************************************************************/
3787 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3793 host = get_header_value(headers, "Host:");
3797 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3798 return JB_ERR_PARSE;
3801 if (NULL == (p = strdup((host))))
3803 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3804 return JB_ERR_MEMORY;
3807 if (NULL == (q = strdup(p)))
3810 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3811 return JB_ERR_MEMORY;
3814 freez(http->hostport);
3818 q = strchr(http->host, ':');
3821 /* Terminate hostname and evaluate port string */
3823 http->port = atoi(q);
3827 http->port = http->ssl ? 443 : 80;
3830 /* Rebuild request URL */
3832 http->url = strdup(http->ssl ? "https://" : "http://");
3833 string_append(&http->url, http->hostport);
3834 string_append(&http->url, http->path);
3835 if (http->url == NULL)
3837 return JB_ERR_MEMORY;
3840 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
3848 /*********************************************************************
3850 * Function : create_forged_referrer
3852 * Description : Helper for client_referrer to forge a referer as
3853 * 'http://[hostname:port/' to fool stupid
3854 * checks for in-site links
3857 * 1 : header = Pointer to header pointer
3858 * 2 : hostport = Host and optionally port as string
3860 * Returns : JB_ERR_OK in case of success, or
3861 * JB_ERR_MEMORY in case of memory problems.
3863 *********************************************************************/
3864 static jb_err create_forged_referrer(char **header, const char *hostport)
3866 assert(NULL == *header);
3868 *header = strdup("Referer: http://");
3869 string_append(header, hostport);
3870 string_append(header, "/");
3872 if (NULL == *header)
3874 return JB_ERR_MEMORY;
3877 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
3884 /*********************************************************************
3886 * Function : create_fake_referrer
3888 * Description : Helper for client_referrer to create a fake referrer
3889 * based on a string supplied by the user.
3892 * 1 : header = Pointer to header pointer
3893 * 2 : hosthost = Referrer to fake
3895 * Returns : JB_ERR_OK in case of success, or
3896 * JB_ERR_MEMORY in case of memory problems.
3898 *********************************************************************/
3899 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
3901 assert(NULL == *header);
3903 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
3905 log_error(LOG_LEVEL_HEADER,
3906 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
3908 *header = strdup("Referer: ");
3909 string_append(header, fake_referrer);
3911 if (NULL == *header)
3913 return JB_ERR_MEMORY;
3916 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
3923 /*********************************************************************
3925 * Function : handle_conditional_hide_referrer_parameter
3927 * Description : Helper for client_referrer to crunch or forge
3928 * the referrer header if the host has changed.
3931 * 1 : header = Pointer to header pointer
3932 * 2 : host = The target host (may include the port)
3933 * 3 : parameter_conditional_block = Boolean to signal
3934 * if we're in conditional-block mode. If not set,
3935 * we're in conditional-forge mode.
3937 * Returns : JB_ERR_OK in case of success, or
3938 * JB_ERR_MEMORY in case of memory problems.
3940 *********************************************************************/
3941 static jb_err handle_conditional_hide_referrer_parameter(char **header,
3942 const char *host, const int parameter_conditional_block)
3944 char *referer = strdup(*header);
3945 const size_t hostlenght = strlen(host);
3946 const char *referer_url = NULL;
3948 if (NULL == referer)
3951 return JB_ERR_MEMORY;
3954 /* referer begins with 'Referer: http[s]://' */
3955 if ((hostlenght+17) < strlen(referer))
3958 * Shorten referer to make sure the referer is blocked
3959 * if www.example.org/www.example.com-shall-see-the-referer/
3960 * links to www.example.com/
3962 referer[hostlenght+17] = '\0';
3964 referer_url = strstr(referer, "http://");
3965 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
3967 /* Host has changed, Referer is invalid or a https URL. */
3968 if (parameter_conditional_block)
3970 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
3977 return create_forged_referrer(header, host);
3987 /*********************************************************************
3989 * Function : get_appropiate_connection_header
3991 * Description : Returns an appropiate Connection header
3992 * depending on whether or not we try to keep
3993 * the connection to the server alive.
3996 * 1 : csp = Current client state (buffers, headers, etc...)
3998 * Returns : Pointer to statically allocated header buffer.
4000 *********************************************************************/
4001 static const char *get_appropiate_connection_header(const struct client_state *csp)
4003 static const char connection_keep_alive[] = "Connection: keep-alive";
4004 static const char connection_close[] = "Connection: close";
4006 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4007 && (csp->http->ssl == 0))
4009 return connection_keep_alive;
4011 return connection_close;