1 const char parsers_rcs[] = "$Id: parsers.c,v 1.203 2009/08/01 11:46:59 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 static jb_err server_proxy_connection(struct client_state *csp, char **header);
160 static jb_err client_keep_alive(struct client_state *csp, char **header);
161 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
163 static jb_err client_host_adder (struct client_state *csp);
164 static jb_err client_xtra_adder (struct client_state *csp);
165 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
166 static jb_err client_connection_header_adder(struct client_state *csp);
167 static jb_err server_connection_adder(struct client_state *csp);
168 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
169 static jb_err server_proxy_connection_adder(struct client_state *csp);
170 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
172 static jb_err create_forged_referrer(char **header, const char *hostport);
173 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
174 static jb_err handle_conditional_hide_referrer_parameter(char **header,
175 const char *host, const int parameter_conditional_block);
176 static void create_content_length_header(unsigned long long content_length,
177 char *header, size_t buffer_length);
180 * List of functions to run on a list of headers.
184 /** The header prefix to match */
187 /** The length of the prefix to match */
190 /** The function to apply to this line */
191 const parser_func_ptr parser;
194 static const struct parsers client_patterns[] = {
195 { "referer:", 8, client_referrer },
196 { "user-agent:", 11, client_uagent },
197 { "ua-", 3, client_ua },
198 { "from:", 5, client_from },
199 { "cookie:", 7, client_send_cookie },
200 { "x-forwarded-for:", 16, client_x_forwarded },
201 { "Accept-Encoding:", 16, client_accept_encoding },
202 { "TE:", 3, client_te },
203 { "Host:", 5, client_host },
204 { "if-modified-since:", 18, client_if_modified_since },
205 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
206 { "Keep-Alive:", 11, client_keep_alive },
208 { "Keep-Alive:", 11, crumble },
210 { "connection:", 11, client_connection },
211 { "proxy-connection:", 17, crumble },
212 { "max-forwards:", 13, client_max_forwards },
213 { "Accept-Language:", 16, client_accept_language },
214 { "if-none-match:", 14, client_if_none_match },
215 { "Range:", 6, client_range },
216 { "Request-Range:", 14, client_range },
217 { "If-Range:", 9, client_range },
218 { "X-Filter:", 9, client_x_filter },
219 { "*", 0, crunch_client_header },
220 { "*", 0, filter_header },
224 static const struct parsers server_patterns[] = {
225 { "HTTP/", 5, server_http },
226 { "set-cookie:", 11, server_set_cookie },
227 { "connection:", 11, server_connection },
228 { "Content-Type:", 13, server_content_type },
229 { "Content-MD5:", 12, server_content_md5 },
230 { "Content-Encoding:", 17, server_content_encoding },
231 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
232 { "Content-Length:", 15, server_save_content_length },
233 { "Keep-Alive:", 11, server_keep_alive },
234 { "Proxy-Connection:", 17, server_proxy_connection },
236 { "Keep-Alive:", 11, crumble },
237 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
238 { "Transfer-Encoding:", 18, server_transfer_coding },
239 { "content-disposition:", 20, server_content_disposition },
240 { "Last-Modified:", 14, server_last_modified },
241 { "*", 0, crunch_server_header },
242 { "*", 0, filter_header },
246 static const add_header_func_ptr add_client_headers[] = {
248 client_x_forwarded_for_adder,
250 /* Temporarily disabled: client_accept_encoding_adder, */
251 client_connection_header_adder,
255 static const add_header_func_ptr add_server_headers[] = {
256 server_connection_adder,
257 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
258 server_proxy_connection_adder,
259 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
263 /*********************************************************************
265 * Function : flush_socket
267 * Description : Write any pending "buffered" content.
270 * 1 : fd = file descriptor of the socket to read
271 * 2 : iob = The I/O buffer to flush, usually csp->iob.
273 * Returns : On success, the number of bytes written are returned (zero
274 * indicates nothing was written). On error, -1 is returned,
275 * and errno is set appropriately. If count is zero and the
276 * file descriptor refers to a regular file, 0 will be
277 * returned without causing any other effect. For a special
278 * file, the results are not portable.
280 *********************************************************************/
281 long flush_socket(jb_socket fd, struct iob *iob)
283 long len = iob->eod - iob->cur;
290 if (write_socket(fd, iob->cur, (size_t)len))
294 iob->eod = iob->cur = iob->buf;
300 /*********************************************************************
302 * Function : add_to_iob
304 * Description : Add content to the buffered page, expanding the
305 * buffer if necessary.
308 * 1 : csp = Current client state (buffers, headers, etc...)
309 * 2 : buf = holds the content to be added to the page
310 * 3 : n = number of bytes to be added
312 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
313 * or buffer limit reached.
315 *********************************************************************/
316 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
318 struct iob *iob = csp->iob;
319 size_t used, offset, need, want;
322 if (n <= 0) return JB_ERR_OK;
324 used = (size_t)(iob->eod - iob->buf);
325 offset = (size_t)(iob->cur - iob->buf);
326 need = used + (size_t)n + 1;
329 * If the buffer can't hold the new data, extend it first.
330 * Use the next power of two if possible, else use the actual need.
332 if (need > csp->config->buffer_limit)
334 log_error(LOG_LEVEL_INFO,
335 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
336 need, csp->config->buffer_limit);
337 return JB_ERR_MEMORY;
340 if (need > iob->size)
342 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
344 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
348 else if (NULL != (p = (char *)realloc(iob->buf, need)))
354 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
355 return JB_ERR_MEMORY;
358 /* Update the iob pointers */
359 iob->cur = p + offset;
364 /* copy the new data into the iob buffer */
365 memcpy(iob->eod, buf, (size_t)n);
367 /* point to the end of the data */
370 /* null terminate == cheap insurance */
379 /*********************************************************************
381 * Function : decompress_iob
383 * Description : Decompress buffered page, expanding the
384 * buffer as necessary. csp->iob->cur
385 * should point to the the beginning of the
386 * compressed data block.
389 * 1 : csp = Current client state (buffers, headers, etc...)
391 * Returns : JB_ERR_OK on success,
392 * JB_ERR_MEMORY if out-of-memory limit reached, and
393 * JB_ERR_COMPRESS if error decompressing buffer.
395 *********************************************************************/
396 jb_err decompress_iob(struct client_state *csp)
398 char *buf; /* new, uncompressed buffer */
399 char *cur; /* Current iob position (to keep the original
400 * iob->cur unmodified if we return early) */
401 size_t bufsize; /* allocated size of the new buffer */
402 size_t old_size; /* Content size before decompression */
403 size_t skip_size; /* Number of bytes at the beginning of the iob
404 that we should NOT decompress. */
405 int status; /* return status of the inflate() call */
406 z_stream zstr; /* used by calls to zlib */
408 assert(csp->iob->cur - csp->iob->buf > 0);
409 assert(csp->iob->eod - csp->iob->cur > 0);
411 bufsize = csp->iob->size;
412 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
413 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
417 if (bufsize < (size_t)10)
420 * This is to protect the parsing of gzipped data,
421 * but it should(?) be valid for deflated data also.
423 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
424 return JB_ERR_COMPRESS;
427 if (csp->content_type & CT_GZIP)
430 * Our task is slightly complicated by the facts that data
431 * compressed by gzip does not include a zlib header, and
432 * that there is no easily accessible interface in zlib to
433 * handle a gzip header. We strip off the gzip header by
434 * hand, and later inform zlib not to expect a header.
438 * Strip off the gzip header. Please see RFC 1952 for more
439 * explanation of the appropriate fields.
441 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
442 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
443 || (*cur++ != Z_DEFLATED))
445 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
446 return JB_ERR_COMPRESS;
451 if (flags & GZIP_FLAG_RESERVED_BITS)
453 /* The gzip header has reserved bits set; bail out. */
454 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
455 return JB_ERR_COMPRESS;
459 * Skip mtime (4 bytes), extra flags (1 byte)
460 * and OS type (1 byte).
464 /* Skip extra fields if necessary. */
465 if (flags & GZIP_FLAG_EXTRA_FIELDS)
468 * Skip a given number of bytes, specified
469 * as a 16-bit little-endian value.
471 * XXX: this code is untested and should probably be removed.
475 skip_bytes += *cur++ << 8;
478 * The number of bytes to skip should be positive
479 * and we'd like to stay in the buffer.
481 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
483 log_error(LOG_LEVEL_ERROR,
484 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
486 return JB_ERR_COMPRESS;
488 log_error(LOG_LEVEL_INFO,
489 "Skipping %d bytes for gzip compression. Does this sound right?",
494 /* Skip the filename if necessary. */
495 if (flags & GZIP_FLAG_FILE_NAME)
497 /* A null-terminated string is supposed to follow. */
498 while (*cur++ && (cur < csp->iob->eod));
501 /* Skip the comment if necessary. */
502 if (flags & GZIP_FLAG_COMMENT)
504 /* A null-terminated string is supposed to follow. */
505 while (*cur++ && (cur < csp->iob->eod));
508 /* Skip the CRC if necessary. */
509 if (flags & GZIP_FLAG_CHECKSUM)
514 if (cur >= csp->iob->eod)
517 * If the current position pointer reached or passed
518 * the buffer end, we were obviously tricked to skip
521 log_error(LOG_LEVEL_ERROR,
522 "Malformed gzip header detected. Aborting decompression.");
523 return JB_ERR_COMPRESS;
527 else if (csp->content_type & CT_DEFLATE)
530 * XXX: The debug level should be lowered
531 * before the next stable release.
533 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
535 * In theory (that is, according to RFC 1950), deflate-compressed
536 * data should begin with a two-byte zlib header and have an
537 * adler32 checksum at the end. It seems that in practice only
538 * the raw compressed data is sent. Note that this means that
539 * we are not RFC 1950-compliant here, but the advantage is that
540 * this actually works. :)
542 * We add a dummy null byte to tell zlib where the data ends,
543 * and later inform it not to expect a header.
545 * Fortunately, add_to_iob() has thoughtfully null-terminated
546 * the buffer; we can just increment the end pointer to include
553 log_error(LOG_LEVEL_ERROR,
554 "Unable to determine compression format for decompression");
555 return JB_ERR_COMPRESS;
558 /* Set up the fields required by zlib. */
559 zstr.next_in = (Bytef *)cur;
560 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
561 zstr.zalloc = Z_NULL;
563 zstr.opaque = Z_NULL;
566 * Passing -MAX_WBITS to inflateInit2 tells the library
567 * that there is no zlib header.
569 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
571 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
572 return JB_ERR_COMPRESS;
576 * Next, we allocate new storage for the inflated data.
577 * We don't modify the existing iob yet, so in case there
578 * is error in decompression we can recover gracefully.
580 buf = zalloc(bufsize);
583 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
584 return JB_ERR_MEMORY;
587 assert(bufsize >= skip_size);
588 memcpy(buf, csp->iob->buf, skip_size);
589 zstr.avail_out = (uInt)(bufsize - skip_size);
590 zstr.next_out = (Bytef *)buf + skip_size;
592 /* Try to decompress the whole stream in one shot. */
593 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
595 /* We need to allocate more memory for the output buffer. */
597 char *tmpbuf; /* used for realloc'ing the buffer */
598 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
600 if (0 == zstr.avail_in)
603 * If zlib wants more data then there's a problem, because
604 * the complete compressed file should have been buffered.
606 log_error(LOG_LEVEL_ERROR,
607 "Unexpected end of compressed iob. Using what we got so far.");
612 * If we tried the limit and still didn't have enough
613 * memory, just give up.
615 if (bufsize == csp->config->buffer_limit)
617 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
618 return JB_ERR_MEMORY;
621 /* Try doubling the buffer size each time. */
624 /* Don't exceed the buffer limit. */
625 if (bufsize > csp->config->buffer_limit)
627 bufsize = csp->config->buffer_limit;
630 /* Try to allocate the new buffer. */
631 tmpbuf = realloc(buf, bufsize);
634 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
636 return JB_ERR_MEMORY;
640 char *oldnext_out = (char *)zstr.next_out;
643 * Update the fields for inflate() to use the new
644 * buffer, which may be in a location different from
647 zstr.avail_out += (uInt)(bufsize - oldbufsize);
648 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
651 * Compare with an uglier method of calculating these values
652 * that doesn't require the extra oldbufsize variable.
654 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
655 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
656 assert(zstr.avail_out > 0U);
662 if (Z_STREAM_ERROR == inflateEnd(&zstr))
664 log_error(LOG_LEVEL_ERROR,
665 "Inconsistent stream state after decompression: %s", zstr.msg);
667 * XXX: Intentionally no return.
669 * According to zlib.h, Z_STREAM_ERROR is returned
670 * "if the stream state was inconsistent".
672 * I assume in this case inflate()'s status
673 * would also be something different than Z_STREAM_END
674 * so this check should be redundant, but lets see.
678 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
681 * We failed to decompress the stream and it's
682 * not simply because of missing data.
684 log_error(LOG_LEVEL_ERROR,
685 "Unexpected error while decompressing to the buffer (iob): %s",
687 return JB_ERR_COMPRESS;
691 * Finally, we can actually update the iob, since the
692 * decompression was successful. First, free the old
695 freez(csp->iob->buf);
697 /* Now, update the iob to use the new buffer. */
699 csp->iob->cur = csp->iob->buf + skip_size;
700 csp->iob->eod = (char *)zstr.next_out;
701 csp->iob->size = bufsize;
704 * Make sure the new uncompressed iob obeys some minimal
705 * consistency conditions.
707 if ((csp->iob->buf < csp->iob->cur)
708 && (csp->iob->cur <= csp->iob->eod)
709 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
711 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
712 if (new_size > (size_t)0)
714 log_error(LOG_LEVEL_RE_FILTER,
715 "Decompression successful. Old size: %d, new size: %d.",
720 /* zlib thinks this is OK, so lets do the same. */
721 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
726 /* It seems that zlib did something weird. */
727 log_error(LOG_LEVEL_ERROR,
728 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
729 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
730 csp->iob->eod, csp->iob->buf + csp->iob->size);
731 return JB_ERR_COMPRESS;
737 #endif /* defined(FEATURE_ZLIB) */
740 /*********************************************************************
742 * Function : string_move
744 * Description : memmove wrapper to move the last part of a string
745 * towards the beginning, overwriting the part in
746 * the middle. strlcpy() can't be used here as the
750 * 1 : dst = Destination to overwrite
751 * 2 : src = Source to move.
755 *********************************************************************/
756 static void string_move(char *dst, char *src)
760 /* +1 to copy the terminating nul as well. */
761 memmove(dst, src, strlen(src)+1);
765 /*********************************************************************
767 * Function : normalize_lws
769 * Description : Reduces unquoted linear white space in headers
770 * to a single space in accordance with RFC 2616 2.2.
771 * This simplifies parsing and filtering later on.
773 * XXX: Remove log messages before
774 * the next stable release?
777 * 1 : header = A header with linear white space to reduce.
781 *********************************************************************/
782 static void normalize_lws(char *header)
788 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
792 while (ijb_isspace(*q))
796 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
802 log_error(LOG_LEVEL_HEADER,
803 "Converting tab to space in '%s'", header);
808 char *end_of_token = strstr(p+1, "\"");
810 if (NULL != end_of_token)
812 /* Don't mess with quoted text. */
817 log_error(LOG_LEVEL_HEADER,
818 "Ignoring single quote in '%s'", header);
824 p = strchr(header, ':');
825 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
828 * There's still space before the colon.
836 /*********************************************************************
838 * Function : get_header
840 * Description : This (odd) routine will parse the csp->iob
841 * to get the next complete header.
844 * 1 : iob = The I/O buffer to parse, usually csp->iob.
846 * Returns : Any one of the following:
848 * 1) a pointer to a dynamically allocated string that contains a header line
849 * 2) NULL indicating that the end of the header was reached
850 * 3) "" indicating that the end of the iob was reached before finding
851 * a complete header line.
853 *********************************************************************/
854 char *get_header(struct iob *iob)
858 header = get_header_line(iob);
860 if ((header == NULL) || (*header == '\0'))
863 * No complete header read yet, tell the client.
868 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
871 * Header spans multiple lines, append the next one.
873 char *continued_header;
875 continued_header = get_header_line(iob);
876 if ((continued_header == NULL) || (*continued_header == '\0'))
879 * No complete header read yet, return what we got.
880 * XXX: Should "unread" header instead.
882 log_error(LOG_LEVEL_INFO,
883 "Failed to read a multi-line header properly: '%s'",
888 if (JB_ERR_OK != string_join(&header, continued_header))
890 log_error(LOG_LEVEL_FATAL,
891 "Out of memory while appending multiple headers.");
895 /* XXX: remove before next stable release. */
896 log_error(LOG_LEVEL_HEADER,
897 "Merged multiple header lines to: '%s'",
902 normalize_lws(header);
909 /*********************************************************************
911 * Function : get_header_line
913 * Description : This (odd) routine will parse the csp->iob
914 * to get the next header line.
917 * 1 : iob = The I/O buffer to parse, usually csp->iob.
919 * Returns : Any one of the following:
921 * 1) a pointer to a dynamically allocated string that contains a header line
922 * 2) NULL indicating that the end of the header was reached
923 * 3) "" indicating that the end of the iob was reached before finding
924 * a complete header line.
926 *********************************************************************/
927 static char *get_header_line(struct iob *iob)
931 if ((iob->cur == NULL)
932 || ((p = strchr(iob->cur, '\n')) == NULL))
934 return(""); /* couldn't find a complete header */
939 ret = strdup(iob->cur);
942 /* FIXME No way to handle error properly */
943 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
949 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
951 /* is this a blank line (i.e. the end of the header) ? */
963 /*********************************************************************
965 * Function : get_header_value
967 * Description : Get the value of a given header from a chained list
968 * of header lines or return NULL if no such header is
969 * present in the list.
972 * 1 : header_list = pointer to list
973 * 2 : header_name = string with name of header to look for.
974 * Trailing colon required, capitalization
977 * Returns : NULL if not found, else value of header
979 *********************************************************************/
980 char *get_header_value(const struct list *header_list, const char *header_name)
982 struct list_entry *cur_entry;
988 length = strlen(header_name);
990 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
994 if (!strncmpic(cur_entry->str, header_name, length))
997 * Found: return pointer to start of value
999 ret = cur_entry->str + length;
1000 while (*ret && ijb_isspace(*ret)) ret++;
1014 /*********************************************************************
1016 * Function : scan_headers
1018 * Description : Scans headers, applies tags and updates action bits.
1021 * 1 : csp = Current client state (buffers, headers, etc...)
1023 * Returns : JB_ERR_OK
1025 *********************************************************************/
1026 static jb_err scan_headers(struct client_state *csp)
1028 struct list_entry *h; /* Header */
1029 jb_err err = JB_ERR_OK;
1031 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1033 /* Header crunch()ed in previous run? -> ignore */
1034 if (h->str == NULL) continue;
1035 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1036 err = header_tagger(csp, h->str);
1043 /*********************************************************************
1047 * Description : add, delete or modify lines in the HTTP header streams.
1048 * On entry, it receives a linked list of headers space
1049 * that was allocated dynamically (both the list nodes
1050 * and the header contents).
1052 * As a side effect it frees the space used by the original
1056 * 1 : csp = Current client state (buffers, headers, etc...)
1057 * 2 : filter_server_headers = Boolean to switch between
1058 * server and header filtering.
1060 * Returns : JB_ERR_OK in case off success, or
1061 * JB_ERR_MEMORY on out-of-memory error.
1063 *********************************************************************/
1064 jb_err sed(struct client_state *csp, int filter_server_headers)
1066 /* XXX: use more descriptive names. */
1067 struct list_entry *p;
1068 const struct parsers *v;
1069 const add_header_func_ptr *f;
1070 jb_err err = JB_ERR_OK;
1072 if (filter_server_headers)
1074 v = server_patterns;
1075 f = add_server_headers;
1079 v = client_patterns;
1080 f = add_client_headers;
1085 while ((err == JB_ERR_OK) && (v->str != NULL))
1087 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1089 /* Header crunch()ed in previous run? -> ignore */
1090 if (p->str == NULL) continue;
1092 /* Does the current parser handle this header? */
1093 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1094 (v->len == CHECK_EVERY_HEADER_REMAINING))
1096 err = v->parser(csp, &(p->str));
1102 /* place additional headers on the csp->headers list */
1103 while ((err == JB_ERR_OK) && (*f))
1113 /*********************************************************************
1115 * Function : update_server_headers
1117 * Description : Updates server headers after the body has been modified.
1120 * 1 : csp = Current client state (buffers, headers, etc...)
1122 * Returns : JB_ERR_OK in case off success, or
1123 * JB_ERR_MEMORY on out-of-memory error.
1125 *********************************************************************/
1126 jb_err update_server_headers(struct client_state *csp)
1128 jb_err err = JB_ERR_OK;
1130 static const struct parsers server_patterns_light[] = {
1131 { "Content-Length:", 15, server_adjust_content_length },
1132 { "Transfer-Encoding:", 18, server_transfer_coding },
1134 { "Content-Encoding:", 17, server_content_encoding },
1135 #endif /* def FEATURE_ZLIB */
1139 if (strncmpic(csp->http->cmd, "HEAD", 4))
1141 const struct parsers *v;
1142 struct list_entry *p;
1144 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1146 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1148 /* Header crunch()ed in previous run? -> ignore */
1149 if (p->str == NULL) continue;
1151 /* Does the current parser handle this header? */
1152 if (strncmpic(p->str, v->str, v->len) == 0)
1154 err = v->parser(csp, (char **)&(p->str));
1160 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1161 if ((JB_ERR_OK == err)
1162 && (csp->flags & CSP_FLAG_MODIFIED)
1163 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1164 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1168 create_content_length_header(csp->content_length, header, sizeof(header));
1169 err = enlist(csp->headers, header);
1170 if (JB_ERR_OK == err)
1172 log_error(LOG_LEVEL_HEADER,
1173 "Content modified with no Content-Length header set. "
1174 "Created: %s.", header);
1177 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1183 /*********************************************************************
1185 * Function : header_tagger
1187 * Description : Executes all text substitutions from applying
1188 * tag actions and saves the result as tag.
1190 * XXX: Shares enough code with filter_header() and
1191 * pcrs_filter_response() to warrant some helper functions.
1194 * 1 : csp = Current client state (buffers, headers, etc...)
1195 * 2 : header = Header that is used as tagger input
1197 * Returns : JB_ERR_OK on success and always succeeds
1199 *********************************************************************/
1200 static jb_err header_tagger(struct client_state *csp, char *header)
1202 int wanted_filter_type;
1203 int multi_action_index;
1207 struct file_list *fl;
1208 struct re_filterfile_spec *b;
1209 struct list_entry *tag_name;
1211 int found_filters = 0;
1212 const size_t header_length = strlen(header);
1214 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1216 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1217 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1221 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1222 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1225 /* Check if there are any filters */
1226 for (i = 0; i < MAX_AF_FILES; i++)
1239 if (0 == found_filters)
1241 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1242 "tagging enabled, but no taggers available.");
1246 for (i = 0; i < MAX_AF_FILES; i++)
1249 if ((NULL == fl) || (NULL == fl->f))
1252 * Either there are no filter files
1253 * left, or this filter file just
1254 * contains no valid filters.
1256 * Continue to be sure we don't miss
1257 * valid filter files that are chained
1258 * after empty or invalid ones.
1263 /* For all filters, */
1264 for (b = fl->f; b; b = b->next)
1266 if (b->type != wanted_filter_type)
1268 /* skip the ones we don't care about, */
1271 /* leaving only taggers that could apply, of which we use the ones, */
1272 for (tag_name = csp->action->multi[multi_action_index]->first;
1273 NULL != tag_name; tag_name = tag_name->next)
1275 /* that do apply, and */
1276 if (strcmp(b->name, tag_name->str) == 0)
1278 char *modified_tag = NULL;
1280 size_t size = header_length;
1281 pcrs_job *joblist = b->joblist;
1283 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1285 if (NULL == joblist)
1287 log_error(LOG_LEVEL_RE_FILTER,
1288 "Tagger %s has empty joblist. Nothing to do.", b->name);
1292 /* execute their pcrs_joblist on the header. */
1293 for (job = joblist; NULL != job; job = job->next)
1295 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1299 /* Success, continue with the modified version. */
1308 /* Tagger doesn't match */
1311 /* Regex failure, log it but continue anyway. */
1312 assert(NULL != header);
1313 log_error(LOG_LEVEL_ERROR,
1314 "Problems with tagger \'%s\' and header \'%s\': %s",
1315 b->name, *header, pcrs_strerror(hits));
1317 freez(modified_tag);
1321 if (b->dynamic) pcrs_free_joblist(joblist);
1323 /* If this tagger matched */
1329 * There is to technical limitation which makes
1330 * it impossible to use empty tags, but I assume
1331 * no one would do it intentionally.
1334 log_error(LOG_LEVEL_INFO,
1335 "Tagger \'%s\' created an empty tag. Ignored.",
1340 if (!list_contains_item(csp->tags, tag))
1342 if (JB_ERR_OK != enlist(csp->tags, tag))
1344 log_error(LOG_LEVEL_ERROR,
1345 "Insufficient memory to add tag \'%s\', "
1346 "based on tagger \'%s\' and header \'%s\'",
1347 tag, b->name, *header);
1351 char *action_message;
1353 * update the action bits right away, to make
1354 * tagging based on tags set by earlier taggers
1355 * of the same kind possible.
1357 if (update_action_bits_for_tag(csp, tag))
1359 action_message = "Action bits updated accordingly.";
1363 action_message = "No action bits update necessary.";
1366 log_error(LOG_LEVEL_HEADER,
1367 "Tagger \'%s\' added tag \'%s\'. %s",
1368 b->name, tag, action_message);
1373 /* XXX: Is this log-worthy? */
1374 log_error(LOG_LEVEL_HEADER,
1375 "Tagger \'%s\' didn't add tag \'%s\'. "
1376 "Tag already present", b->name, tag);
1379 } /* if the tagger matched */
1380 } /* if the tagger applies */
1381 } /* for every tagger that could apply */
1382 } /* for all filters */
1383 } /* for all filter files */
1388 /* here begins the family of parser functions that reformat header lines */
1390 /*********************************************************************
1392 * Function : filter_header
1394 * Description : Executes all text substitutions from all applying
1395 * +(server|client)-header-filter actions on the header.
1396 * Most of the code was copied from pcrs_filter_response,
1397 * including the rather short variable names
1400 * 1 : csp = Current client state (buffers, headers, etc...)
1401 * 2 : header = On input, pointer to header to modify.
1402 * On output, pointer to the modified header, or NULL
1403 * to remove the header. This function frees the
1404 * original string if necessary.
1406 * Returns : JB_ERR_OK on success and always succeeds
1408 *********************************************************************/
1409 static jb_err filter_header(struct client_state *csp, char **header)
1413 size_t size = strlen(*header);
1415 char *newheader = NULL;
1418 struct file_list *fl;
1419 struct re_filterfile_spec *b;
1420 struct list_entry *filtername;
1422 int i, found_filters = 0;
1423 int wanted_filter_type;
1424 int multi_action_index;
1426 if (csp->flags & CSP_FLAG_NO_FILTERING)
1431 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1433 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1434 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1438 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1439 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1443 * Need to check the set of re_filterfiles...
1445 for (i = 0; i < MAX_AF_FILES; i++)
1458 if (0 == found_filters)
1460 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1461 "header filtering enabled, but no matching filters available.");
1465 for (i = 0; i < MAX_AF_FILES; i++)
1468 if ((NULL == fl) || (NULL == fl->f))
1471 * Either there are no filter files
1472 * left, or this filter file just
1473 * contains no valid filters.
1475 * Continue to be sure we don't miss
1476 * valid filter files that are chained
1477 * after empty or invalid ones.
1482 * For all applying +filter actions, look if a filter by that
1483 * name exists and if yes, execute its pcrs_joblist on the
1486 for (b = fl->f; b; b = b->next)
1488 if (b->type != wanted_filter_type)
1490 /* Skip other filter types */
1494 for (filtername = csp->action->multi[multi_action_index]->first;
1495 filtername ; filtername = filtername->next)
1497 if (strcmp(b->name, filtername->str) == 0)
1499 int current_hits = 0;
1500 pcrs_job *joblist = b->joblist;
1502 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1504 if (NULL == joblist)
1506 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1510 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1511 *header, size, b->name);
1513 /* Apply all jobs from the joblist */
1514 for (job = joblist; NULL != job; job = job->next)
1516 matches = pcrs_execute(job, *header, size, &newheader, &size);
1519 current_hits += matches;
1520 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1522 *header = newheader;
1524 else if ( 0 == matches )
1526 /* Filter doesn't change header */
1532 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1533 *header, b->name, pcrs_strerror(matches));
1534 if (newheader != NULL)
1536 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1542 if (b->dynamic) pcrs_free_joblist(joblist);
1544 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1545 hits += current_hits;
1552 * Additionally checking for hits is important because if
1553 * the continue hack is triggered, server headers can
1554 * arrive empty to separate multiple heads from each other.
1556 if ((0 == size) && hits)
1558 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1566 /*********************************************************************
1568 * Function : server_connection
1570 * Description : Makes sure a proper "Connection:" header is
1571 * set and signals connection_header_adder to
1575 * 1 : csp = Current client state (buffers, headers, etc...)
1576 * 2 : header = On input, pointer to header to modify.
1577 * On output, pointer to the modified header, or NULL
1578 * to remove the header. This function frees the
1579 * original string if necessary.
1581 * Returns : JB_ERR_OK on success, or
1582 * JB_ERR_MEMORY on out-of-memory error.
1584 *********************************************************************/
1585 static jb_err server_connection(struct client_state *csp, char **header)
1587 if (!strcmpic(*header, "Connection: keep-alive")
1588 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1589 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1593 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1594 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1596 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1599 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1601 log_error(LOG_LEVEL_HEADER,
1602 "Keeping the server header '%s' around.", *header);
1605 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1607 char *old_header = *header;
1609 *header = strdup("Connection: close");
1612 return JB_ERR_MEMORY;
1614 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1619 /* Signal server_connection_adder() to return early. */
1620 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1626 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1627 /*********************************************************************
1629 * Function : server_keep_alive
1631 * Description : Stores the server's keep alive timeout.
1634 * 1 : csp = Current client state (buffers, headers, etc...)
1635 * 2 : header = On input, pointer to header to modify.
1636 * On output, pointer to the modified header, or NULL
1637 * to remove the header. This function frees the
1638 * original string if necessary.
1640 * Returns : JB_ERR_OK.
1642 *********************************************************************/
1643 static jb_err server_keep_alive(struct client_state *csp, char **header)
1645 unsigned int keep_alive_timeout;
1646 const char *timeout_position = strstr(*header, "timeout=");
1648 if ((NULL == timeout_position)
1649 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1651 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1655 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1657 log_error(LOG_LEVEL_HEADER,
1658 "Reducing keep-alive timeout from %u to %u.",
1659 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1660 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1664 /* XXX: Is this log worthy? */
1665 log_error(LOG_LEVEL_HEADER,
1666 "Server keep-alive timeout is %u. Sticking with %u.",
1667 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1669 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1676 /*********************************************************************
1678 * Function : server_proxy_connection
1680 * Description : Figures out whether or not we should add a
1681 * Proxy-Connection header.
1684 * 1 : csp = Current client state (buffers, headers, etc...)
1685 * 2 : header = On input, pointer to header to modify.
1686 * On output, pointer to the modified header, or NULL
1687 * to remove the header. This function frees the
1688 * original string if necessary.
1690 * Returns : JB_ERR_OK.
1692 *********************************************************************/
1693 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1695 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1700 /*********************************************************************
1702 * Function : client_keep_alive
1704 * Description : Stores the client's keep alive timeout.
1707 * 1 : csp = Current client state (buffers, headers, etc...)
1708 * 2 : header = On input, pointer to header to modify.
1709 * On output, pointer to the modified header, or NULL
1710 * to remove the header. This function frees the
1711 * original string if necessary.
1713 * Returns : JB_ERR_OK.
1715 *********************************************************************/
1716 static jb_err client_keep_alive(struct client_state *csp, char **header)
1718 unsigned int keep_alive_timeout;
1719 const char *timeout_position = strstr(*header, ": ");
1721 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1723 log_error(LOG_LEVEL_HEADER,
1724 "keep-alive support is disabled. Crunching: %s.", *header);
1729 if ((NULL == timeout_position)
1730 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1732 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1736 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1738 log_error(LOG_LEVEL_HEADER,
1739 "Reducing keep-alive timeout from %u to %u.",
1740 csp->config->keep_alive_timeout, keep_alive_timeout);
1741 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1745 /* XXX: Is this log worthy? */
1746 log_error(LOG_LEVEL_HEADER,
1747 "Client keep-alive timeout is %u. Sticking with %u.",
1748 keep_alive_timeout, csp->config->keep_alive_timeout);
1754 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1758 /*********************************************************************
1760 * Function : client_connection
1762 * Description : Makes sure a proper "Connection:" header is
1763 * set and signals connection_header_adder
1767 * 1 : csp = Current client state (buffers, headers, etc...)
1768 * 2 : header = On input, pointer to header to modify.
1769 * On output, pointer to the modified header, or NULL
1770 * to remove the header. This function frees the
1771 * original string if necessary.
1773 * Returns : JB_ERR_OK on success, or
1774 * JB_ERR_MEMORY on out-of-memory error.
1776 *********************************************************************/
1777 static jb_err client_connection(struct client_state *csp, char **header)
1779 static const char connection_close[] = "Connection: close";
1781 if (!strcmpic(*header, connection_close))
1783 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1784 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1786 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1788 log_error(LOG_LEVEL_HEADER,
1789 "Removing \'%s\' to imply keep-alive.", *header);
1794 char *old_header = *header;
1796 *header = strdup("Connection: keep-alive");
1799 return JB_ERR_MEMORY;
1801 log_error(LOG_LEVEL_HEADER,
1802 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1808 log_error(LOG_LEVEL_HEADER,
1809 "Keeping the client header '%s' around. "
1810 "The connection will not be kept alive.",
1812 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1815 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1817 log_error(LOG_LEVEL_HEADER,
1818 "Keeping the client header '%s' around. "
1819 "The server connection will be kept alive if possible.",
1821 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1822 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1826 char *old_header = *header;
1828 *header = strdup(connection_close);
1831 return JB_ERR_MEMORY;
1833 log_error(LOG_LEVEL_HEADER,
1834 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1838 /* Signal client_connection_adder() to return early. */
1839 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1845 /*********************************************************************
1847 * Function : crumble
1849 * Description : This is called if a header matches a pattern to "crunch"
1852 * 1 : csp = Current client state (buffers, headers, etc...)
1853 * 2 : header = On input, pointer to header to modify.
1854 * On output, pointer to the modified header, or NULL
1855 * to remove the header. This function frees the
1856 * original string if necessary.
1858 * Returns : JB_ERR_OK on success, or
1859 * JB_ERR_MEMORY on out-of-memory error.
1861 *********************************************************************/
1862 static jb_err crumble(struct client_state *csp, char **header)
1865 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1871 /*********************************************************************
1873 * Function : crunch_server_header
1875 * Description : Crunch server header if it matches a string supplied by the
1876 * user. Called from `sed'.
1879 * 1 : csp = Current client state (buffers, headers, etc...)
1880 * 2 : header = On input, pointer to header to modify.
1881 * On output, pointer to the modified header, or NULL
1882 * to remove the header. This function frees the
1883 * original string if necessary.
1885 * Returns : JB_ERR_OK on success and always succeeds
1887 *********************************************************************/
1888 static jb_err crunch_server_header(struct client_state *csp, char **header)
1890 const char *crunch_pattern;
1892 /* Do we feel like crunching? */
1893 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1895 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1897 /* Is the current header the lucky one? */
1898 if (strstr(*header, crunch_pattern))
1900 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1909 /*********************************************************************
1911 * Function : server_content_type
1913 * Description : Set the content-type for filterable types (text/.*,
1914 * .*xml.*, javascript and image/gif) unless filtering has been
1915 * forbidden (CT_TABOO) while parsing earlier headers.
1916 * NOTE: Since text/plain is commonly used by web servers
1917 * for files whose correct type is unknown, we don't
1918 * set CT_TEXT for it.
1921 * 1 : csp = Current client state (buffers, headers, etc...)
1922 * 2 : header = On input, pointer to header to modify.
1923 * On output, pointer to the modified header, or NULL
1924 * to remove the header. This function frees the
1925 * original string if necessary.
1927 * Returns : JB_ERR_OK on success, or
1928 * JB_ERR_MEMORY on out-of-memory error.
1930 *********************************************************************/
1931 static jb_err server_content_type(struct client_state *csp, char **header)
1933 /* Remove header if it isn't the first Content-Type header */
1934 if ((csp->content_type & CT_DECLARED))
1937 * Another, slightly slower, way to see if
1938 * we already parsed another Content-Type header.
1940 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1942 log_error(LOG_LEVEL_ERROR,
1943 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1951 * Signal that the Content-Type has been set.
1953 csp->content_type |= CT_DECLARED;
1955 if (!(csp->content_type & CT_TABOO))
1958 * XXX: The assumption that text/plain is a sign of
1959 * binary data seems to be somewhat unreasonable nowadays
1960 * and should be dropped after 3.0.8 is out.
1962 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
1963 || strstr(*header, "xml")
1964 || strstr(*header, "application/x-javascript"))
1966 csp->content_type |= CT_TEXT;
1968 else if (strstr(*header, "image/gif"))
1970 csp->content_type |= CT_GIF;
1975 * Are we messing with the content type?
1977 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1980 * Make sure the user doesn't accidently
1981 * change the content type of binary documents.
1983 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
1986 *header = strdup("Content-Type: ");
1987 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1991 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1992 return JB_ERR_MEMORY;
1994 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1998 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
1999 "It doesn't look like a content type that should be filtered. "
2000 "Enable force-text-mode if you know what you're doing.", *header);
2008 /*********************************************************************
2010 * Function : server_transfer_coding
2012 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2013 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2014 * - Remove header if body was chunked but has been
2015 * de-chunked for filtering.
2018 * 1 : csp = Current client state (buffers, headers, etc...)
2019 * 2 : header = On input, pointer to header to modify.
2020 * On output, pointer to the modified header, or NULL
2021 * to remove the header. This function frees the
2022 * original string if necessary.
2024 * Returns : JB_ERR_OK on success, or
2025 * JB_ERR_MEMORY on out-of-memory error.
2027 *********************************************************************/
2028 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2031 * Turn off pcrs and gif filtering if body compressed
2033 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2037 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2039 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2040 csp->http->cmd, *header);
2041 #endif /* def FEATURE_ZLIB */
2042 csp->content_type = CT_TABOO;
2046 * Raise flag if body chunked
2048 if (strstr(*header, "chunked"))
2050 csp->flags |= CSP_FLAG_CHUNKED;
2053 * If the body was modified, it has been de-chunked first
2054 * and the header must be removed.
2056 * FIXME: If there is more than one transfer encoding,
2057 * only the "chunked" part should be removed here.
2059 if (csp->flags & CSP_FLAG_MODIFIED)
2061 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2070 /*********************************************************************
2072 * Function : server_content_encoding
2074 * Description : This function is run twice for each request,
2075 * unless FEATURE_ZLIB and filtering are disabled.
2077 * The first run is used to check if the content
2078 * is compressed, if FEATURE_ZLIB is disabled
2079 * filtering is then disabled as well, if FEATURE_ZLIB
2080 * is enabled the content is marked for decompression.
2082 * The second run is used to remove the Content-Encoding
2083 * header if the decompression was successful.
2086 * 1 : csp = Current client state (buffers, headers, etc...)
2087 * 2 : header = On input, pointer to header to modify.
2088 * On output, pointer to the modified header, or NULL
2089 * to remove the header. This function frees the
2090 * original string if necessary.
2092 * Returns : JB_ERR_OK on success, or
2093 * JB_ERR_MEMORY on out-of-memory error.
2095 *********************************************************************/
2096 static jb_err server_content_encoding(struct client_state *csp, char **header)
2099 if ((csp->flags & CSP_FLAG_MODIFIED)
2100 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2103 * We successfully decompressed the content,
2104 * and have to clean the header now, so the
2105 * client no longer expects compressed data..
2107 * XXX: There is a difference between cleaning
2108 * and removing it completely.
2110 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2113 else if (strstr(*header, "gzip"))
2115 /* Mark for gzip decompression */
2116 csp->content_type |= CT_GZIP;
2118 else if (strstr(*header, "deflate"))
2120 /* Mark for zlib decompression */
2121 csp->content_type |= CT_DEFLATE;
2123 else if (strstr(*header, "compress"))
2126 * We can't decompress this; therefore we can't filter
2129 csp->content_type |= CT_TABOO;
2131 #else /* !defined(FEATURE_ZLIB) */
2132 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2135 * Body is compressed, turn off pcrs and gif filtering.
2137 csp->content_type |= CT_TABOO;
2140 * Log a warning if the user expects the content to be filtered.
2142 if ((csp->rlist != NULL) &&
2143 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2145 log_error(LOG_LEVEL_INFO,
2146 "Compressed content detected, content filtering disabled. "
2147 "Consider recompiling Privoxy with zlib support or "
2148 "enable the prevent-compression action.");
2151 #endif /* defined(FEATURE_ZLIB) */
2158 /*********************************************************************
2160 * Function : server_adjust_content_length
2162 * Description : Adjust Content-Length header if we modified
2166 * 1 : csp = Current client state (buffers, headers, etc...)
2167 * 2 : header = On input, pointer to header to modify.
2168 * On output, pointer to the modified header, or NULL
2169 * to remove the header. This function frees the
2170 * original string if necessary.
2172 * Returns : JB_ERR_OK on success, or
2173 * JB_ERR_MEMORY on out-of-memory error.
2175 *********************************************************************/
2176 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2178 /* Regenerate header if the content was modified. */
2179 if (csp->flags & CSP_FLAG_MODIFIED)
2181 const size_t header_length = 50;
2183 *header = malloc(header_length);
2184 if (*header == NULL)
2186 return JB_ERR_MEMORY;
2188 create_content_length_header(csp->content_length, *header, header_length);
2189 log_error(LOG_LEVEL_HEADER,
2190 "Adjusted Content-Length to %llu", csp->content_length);
2197 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2198 /*********************************************************************
2200 * Function : server_save_content_length
2202 * Description : Save the Content-Length sent by the server.
2205 * 1 : csp = Current client state (buffers, headers, etc...)
2206 * 2 : header = On input, pointer to header to modify.
2207 * On output, pointer to the modified header, or NULL
2208 * to remove the header. This function frees the
2209 * original string if necessary.
2211 * Returns : JB_ERR_OK on success, or
2212 * JB_ERR_MEMORY on out-of-memory error.
2214 *********************************************************************/
2215 static jb_err server_save_content_length(struct client_state *csp, char **header)
2217 unsigned long long content_length = 0;
2219 assert(*(*header+14) == ':');
2222 if (1 != sscanf(*header+14, ": %I64u", &content_length))
2224 if (1 != sscanf(*header+14, ": %llu", &content_length))
2227 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2232 csp->expected_content_length = content_length;
2233 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2234 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2239 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2242 /*********************************************************************
2244 * Function : server_content_md5
2246 * Description : Crumble any Content-MD5 headers if the document was
2247 * modified. FIXME: Should we re-compute instead?
2250 * 1 : csp = Current client state (buffers, headers, etc...)
2251 * 2 : header = On input, pointer to header to modify.
2252 * On output, pointer to the modified header, or NULL
2253 * to remove the header. This function frees the
2254 * original string if necessary.
2256 * Returns : JB_ERR_OK on success, or
2257 * JB_ERR_MEMORY on out-of-memory error.
2259 *********************************************************************/
2260 static jb_err server_content_md5(struct client_state *csp, char **header)
2262 if (csp->flags & CSP_FLAG_MODIFIED)
2264 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2272 /*********************************************************************
2274 * Function : server_content_disposition
2276 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2277 * Called from `sed'.
2280 * 1 : csp = Current client state (buffers, headers, etc...)
2281 * 2 : header = On input, pointer to header to modify.
2282 * On output, pointer to the modified header, or NULL
2283 * to remove the header. This function frees the
2284 * original string if necessary.
2286 * Returns : JB_ERR_OK on success, or
2287 * JB_ERR_MEMORY on out-of-memory error.
2289 *********************************************************************/
2290 static jb_err server_content_disposition(struct client_state *csp, char **header)
2295 * Are we messing with the Content-Disposition header?
2297 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2303 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2305 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2308 * Blocking content-disposition header
2310 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2317 * Replacing Content-Disposition header
2320 *header = strdup("Content-Disposition: ");
2321 string_append(header, newval);
2323 if (*header != NULL)
2325 log_error(LOG_LEVEL_HEADER,
2326 "Content-Disposition header crunched and replaced with: %s", *header);
2329 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2333 /*********************************************************************
2335 * Function : server_last_modified
2337 * Description : Changes Last-Modified header to the actual date
2338 * to help hide-if-modified-since.
2339 * Called from `sed'.
2342 * 1 : csp = Current client state (buffers, headers, etc...)
2343 * 2 : header = On input, pointer to header to modify.
2344 * On output, pointer to the modified header, or NULL
2345 * to remove the header. This function frees the
2346 * original string if necessary.
2348 * Returns : JB_ERR_OK on success, or
2349 * JB_ERR_MEMORY on out-of-memory error.
2351 *********************************************************************/
2352 static jb_err server_last_modified(struct client_state *csp, char **header)
2355 char buf[BUFFER_SIZE];
2358 #ifdef HAVE_GMTIME_R
2361 struct tm *timeptr = NULL;
2362 time_t now, last_modified;
2363 long int days, hours, minutes, seconds;
2366 * Are we messing with the Last-Modified header?
2368 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2374 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2376 if (0 == strcmpic(newval, "block") )
2379 * Blocking Last-Modified header. Useless but why not.
2381 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2385 else if (0 == strcmpic(newval, "reset-to-request-time"))
2388 * Setting Last-Modified Header to now.
2390 get_http_time(0, buf, sizeof(buf));
2392 *header = strdup("Last-Modified: ");
2393 string_append(header, buf);
2395 if (*header == NULL)
2397 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2401 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2404 else if (0 == strcmpic(newval, "randomize"))
2406 const char *header_time = *header + sizeof("Last-Modified:");
2408 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2410 #ifdef HAVE_GMTIME_R
2411 gmtime_r(&now, &gmt);
2412 #elif defined(MUTEX_LOCKS_AVAILABLE)
2413 privoxy_mutex_lock(&gmtime_mutex);
2415 privoxy_mutex_unlock(&gmtime_mutex);
2419 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2421 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2426 long int rtime = (long int)difftime(now, last_modified);
2429 const int negative_delta = (rtime < 0);
2434 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2436 rtime = pick_from_range(rtime);
2441 last_modified += rtime;
2442 #ifdef HAVE_GMTIME_R
2443 timeptr = gmtime_r(&last_modified, &gmt);
2444 #elif defined(MUTEX_LOCKS_AVAILABLE)
2445 privoxy_mutex_lock(&gmtime_mutex);
2446 timeptr = gmtime(&last_modified);
2447 privoxy_mutex_unlock(&gmtime_mutex);
2449 timeptr = gmtime(&last_modified);
2451 if ((NULL == timeptr) || !strftime(newheader,
2452 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2454 log_error(LOG_LEVEL_ERROR,
2455 "Randomizing '%s' failed. Crunching the header without replacement.",
2462 *header = strdup("Last-Modified: ");
2463 string_append(header, newheader);
2465 if (*header == NULL)
2467 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2468 return JB_ERR_MEMORY;
2471 days = rtime / (3600 * 24);
2472 hours = rtime / 3600 % 24;
2473 minutes = rtime / 60 % 60;
2474 seconds = rtime % 60;
2476 log_error(LOG_LEVEL_HEADER,
2477 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2478 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2479 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2483 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2492 /*********************************************************************
2494 * Function : client_accept_encoding
2496 * Description : Rewrite the client's Accept-Encoding header so that
2497 * if doesn't allow compression, if the action applies.
2498 * Note: For HTTP/1.0 the absence of the header is enough.
2501 * 1 : csp = Current client state (buffers, headers, etc...)
2502 * 2 : header = On input, pointer to header to modify.
2503 * On output, pointer to the modified header, or NULL
2504 * to remove the header. This function frees the
2505 * original string if necessary.
2507 * Returns : JB_ERR_OK on success, or
2508 * JB_ERR_MEMORY on out-of-memory error.
2510 *********************************************************************/
2511 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2513 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2515 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2519 /* Temporarily disable the correct behaviour to
2520 * work around a PHP bug.
2522 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2524 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2525 * if (*header == NULL)
2527 * return JB_ERR_MEMORY;
2538 /*********************************************************************
2540 * Function : client_te
2542 * Description : Rewrite the client's TE header so that
2543 * if doesn't allow compression, if the action applies.
2546 * 1 : csp = Current client state (buffers, headers, etc...)
2547 * 2 : header = On input, pointer to header to modify.
2548 * On output, pointer to the modified header, or NULL
2549 * to remove the header. This function frees the
2550 * original string if necessary.
2552 * Returns : JB_ERR_OK on success, or
2553 * JB_ERR_MEMORY on out-of-memory error.
2555 *********************************************************************/
2556 static jb_err client_te(struct client_state *csp, char **header)
2558 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2561 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2568 /*********************************************************************
2570 * Function : client_referrer
2572 * Description : Handle the "referer" config setting properly.
2573 * Called from `sed'.
2576 * 1 : csp = Current client state (buffers, headers, etc...)
2577 * 2 : header = On input, pointer to header to modify.
2578 * On output, pointer to the modified header, or NULL
2579 * to remove the header. This function frees the
2580 * original string if necessary.
2582 * Returns : JB_ERR_OK on success, or
2583 * JB_ERR_MEMORY on out-of-memory error.
2585 *********************************************************************/
2586 static jb_err client_referrer(struct client_state *csp, char **header)
2588 const char *parameter;
2589 /* booleans for parameters we have to check multiple times */
2590 int parameter_conditional_block;
2591 int parameter_conditional_forge;
2593 #ifdef FEATURE_FORCE_LOAD
2595 * Since the referrer can include the prefix even
2596 * if the request itself is non-forced, we must
2597 * clean it unconditionally.
2599 * XXX: strclean is too broad
2601 strclean(*header, FORCE_PREFIX);
2602 #endif /* def FEATURE_FORCE_LOAD */
2604 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2606 /* Nothing left to do */
2610 parameter = csp->action->string[ACTION_STRING_REFERER];
2611 assert(parameter != NULL);
2612 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2613 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2615 if (!parameter_conditional_block && !parameter_conditional_forge)
2618 * As conditional-block and conditional-forge are the only
2619 * parameters that rely on the original referrer, we can
2620 * remove it now for all the others.
2625 if (0 == strcmpic(parameter, "block"))
2627 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2630 else if (parameter_conditional_block || parameter_conditional_forge)
2632 return handle_conditional_hide_referrer_parameter(header,
2633 csp->http->hostport, parameter_conditional_block);
2635 else if (0 == strcmpic(parameter, "forge"))
2637 return create_forged_referrer(header, csp->http->hostport);
2641 /* interpret parameter as user-supplied referer to fake */
2642 return create_fake_referrer(header, parameter);
2647 /*********************************************************************
2649 * Function : client_accept_language
2651 * Description : Handle the "Accept-Language" config setting properly.
2652 * Called from `sed'.
2655 * 1 : csp = Current client state (buffers, headers, etc...)
2656 * 2 : header = On input, pointer to header to modify.
2657 * On output, pointer to the modified header, or NULL
2658 * to remove the header. This function frees the
2659 * original string if necessary.
2661 * Returns : JB_ERR_OK on success, or
2662 * JB_ERR_MEMORY on out-of-memory error.
2664 *********************************************************************/
2665 static jb_err client_accept_language(struct client_state *csp, char **header)
2670 * Are we messing with the Accept-Language?
2672 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2674 /*I don't think so*/
2678 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2680 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2683 * Blocking Accept-Language header
2685 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2692 * Replacing Accept-Language header
2695 *header = strdup("Accept-Language: ");
2696 string_append(header, newval);
2698 if (*header == NULL)
2700 log_error(LOG_LEVEL_ERROR,
2701 "Insufficient memory. Accept-Language header crunched without replacement.");
2705 log_error(LOG_LEVEL_HEADER,
2706 "Accept-Language header crunched and replaced with: %s", *header);
2709 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2713 /*********************************************************************
2715 * Function : crunch_client_header
2717 * Description : Crunch client header if it matches a string supplied by the
2718 * user. Called from `sed'.
2721 * 1 : csp = Current client state (buffers, headers, etc...)
2722 * 2 : header = On input, pointer to header to modify.
2723 * On output, pointer to the modified header, or NULL
2724 * to remove the header. This function frees the
2725 * original string if necessary.
2727 * Returns : JB_ERR_OK on success and always succeeds
2729 *********************************************************************/
2730 static jb_err crunch_client_header(struct client_state *csp, char **header)
2732 const char *crunch_pattern;
2734 /* Do we feel like crunching? */
2735 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2737 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2739 /* Is the current header the lucky one? */
2740 if (strstr(*header, crunch_pattern))
2742 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2750 /*********************************************************************
2752 * Function : client_uagent
2754 * Description : Handle the "user-agent" config setting properly
2755 * and remember its original value to enable browser
2756 * bug workarounds. Called from `sed'.
2759 * 1 : csp = Current client state (buffers, headers, etc...)
2760 * 2 : header = On input, pointer to header to modify.
2761 * On output, pointer to the modified header, or NULL
2762 * to remove the header. This function frees the
2763 * original string if necessary.
2765 * Returns : JB_ERR_OK on success, or
2766 * JB_ERR_MEMORY on out-of-memory error.
2768 *********************************************************************/
2769 static jb_err client_uagent(struct client_state *csp, char **header)
2773 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2778 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2785 *header = strdup("User-Agent: ");
2786 string_append(header, newval);
2788 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2790 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2794 /*********************************************************************
2796 * Function : client_ua
2798 * Description : Handle "ua-" headers properly. Called from `sed'.
2801 * 1 : csp = Current client state (buffers, headers, etc...)
2802 * 2 : header = On input, pointer to header to modify.
2803 * On output, pointer to the modified header, or NULL
2804 * to remove the header. This function frees the
2805 * original string if necessary.
2807 * Returns : JB_ERR_OK on success, or
2808 * JB_ERR_MEMORY on out-of-memory error.
2810 *********************************************************************/
2811 static jb_err client_ua(struct client_state *csp, char **header)
2813 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2815 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2823 /*********************************************************************
2825 * Function : client_from
2827 * Description : Handle the "from" config setting properly.
2828 * Called from `sed'.
2831 * 1 : csp = Current client state (buffers, headers, etc...)
2832 * 2 : header = On input, pointer to header to modify.
2833 * On output, pointer to the modified header, or NULL
2834 * to remove the header. This function frees the
2835 * original string if necessary.
2837 * Returns : JB_ERR_OK on success, or
2838 * JB_ERR_MEMORY on out-of-memory error.
2840 *********************************************************************/
2841 static jb_err client_from(struct client_state *csp, char **header)
2845 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2852 newval = csp->action->string[ACTION_STRING_FROM];
2855 * Are we blocking the e-mail address?
2857 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2859 log_error(LOG_LEVEL_HEADER, "crunched From!");
2863 log_error(LOG_LEVEL_HEADER, " modified");
2865 *header = strdup("From: ");
2866 string_append(header, newval);
2868 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2872 /*********************************************************************
2874 * Function : client_send_cookie
2876 * Description : Crunches the "cookie" header if necessary.
2877 * Called from `sed'.
2879 * XXX: Stupid name, doesn't send squat.
2882 * 1 : csp = Current client state (buffers, headers, etc...)
2883 * 2 : header = On input, pointer to header to modify.
2884 * On output, pointer to the modified header, or NULL
2885 * to remove the header. This function frees the
2886 * original string if necessary.
2888 * Returns : JB_ERR_OK on success, or
2889 * JB_ERR_MEMORY on out-of-memory error.
2891 *********************************************************************/
2892 static jb_err client_send_cookie(struct client_state *csp, char **header)
2894 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2896 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2904 /*********************************************************************
2906 * Function : client_x_forwarded
2908 * Description : Handle the "x-forwarded-for" config setting properly,
2909 * also used in the add_client_headers list. Called from `sed'.
2912 * 1 : csp = Current client state (buffers, headers, etc...)
2913 * 2 : header = On input, pointer to header to modify.
2914 * On output, pointer to the modified header, or NULL
2915 * to remove the header. This function frees the
2916 * original string if necessary.
2918 * Returns : JB_ERR_OK on success, or
2919 * JB_ERR_MEMORY on out-of-memory error.
2921 *********************************************************************/
2922 jb_err client_x_forwarded(struct client_state *csp, char **header)
2924 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
2926 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
2928 if (0 == strcmpic(parameter, "block"))
2931 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2933 else if (0 == strcmpic(parameter, "add"))
2935 string_append(header, ", ");
2936 string_append(header, csp->ip_addr_str);
2938 if (*header == NULL)
2940 return JB_ERR_MEMORY;
2942 log_error(LOG_LEVEL_HEADER,
2943 "Appended client IP address to %s", *header);
2944 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
2948 log_error(LOG_LEVEL_FATAL,
2949 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
2957 /*********************************************************************
2959 * Function : client_max_forwards
2961 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2962 * from the value of the Max-Forwards header field.
2965 * 1 : csp = Current client state (buffers, headers, etc...)
2966 * 2 : header = On input, pointer to header to modify.
2967 * On output, pointer to the modified header, or NULL
2968 * to remove the header. This function frees the
2969 * original string if necessary.
2971 * Returns : JB_ERR_OK on success, or
2972 * JB_ERR_MEMORY on out-of-memory error.
2974 *********************************************************************/
2975 static jb_err client_max_forwards(struct client_state *csp, char **header)
2979 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2980 (0 == strcmpic(csp->http->gpc, "options")))
2982 assert(*(*header+12) == ':');
2983 if (1 == sscanf(*header+12, ": %d", &max_forwards))
2985 if (max_forwards > 0)
2987 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
2988 log_error(LOG_LEVEL_HEADER,
2989 "Max-Forwards value for %s request reduced to %d.",
2990 csp->http->gpc, max_forwards);
2992 else if (max_forwards < 0)
2994 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3000 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3009 /*********************************************************************
3011 * Function : client_host
3013 * Description : If the request URI did not contain host and
3014 * port information, parse and evaluate the Host
3017 * Also, kill ill-formed HOST: headers as sent by
3018 * Apple's iTunes software when used with a proxy.
3021 * 1 : csp = Current client state (buffers, headers, etc...)
3022 * 2 : header = On input, pointer to header to modify.
3023 * On output, pointer to the modified header, or NULL
3024 * to remove the header. This function frees the
3025 * original string if necessary.
3027 * Returns : JB_ERR_OK on success, or
3028 * JB_ERR_MEMORY on out-of-memory error.
3030 *********************************************************************/
3031 static jb_err client_host(struct client_state *csp, char **header)
3036 * If the header field name is all upper-case, chances are that it's
3037 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3038 * not a problem -- they are regenerated later.
3040 if ((*header)[1] == 'O')
3042 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3047 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3048 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3051 if (NULL == (p = strdup((*header)+6)))
3053 return JB_ERR_MEMORY;
3056 if (NULL == (q = strdup(p)))
3059 return JB_ERR_MEMORY;
3062 freez(csp->http->hostport);
3063 csp->http->hostport = p;
3064 freez(csp->http->host);
3065 csp->http->host = q;
3066 q = strchr(csp->http->host, ':');
3069 /* Terminate hostname and evaluate port string */
3071 csp->http->port = atoi(q);
3075 csp->http->port = csp->http->ssl ? 443 : 80;
3078 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3079 csp->http->hostport, csp->http->host, csp->http->port);
3082 /* Signal client_host_adder() to return right away */
3083 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3089 /*********************************************************************
3091 * Function : client_if_modified_since
3093 * Description : Remove or modify the If-Modified-Since header.
3096 * 1 : csp = Current client state (buffers, headers, etc...)
3097 * 2 : header = On input, pointer to header to modify.
3098 * On output, pointer to the modified header, or NULL
3099 * to remove the header. This function frees the
3100 * original string if necessary.
3102 * Returns : JB_ERR_OK on success, or
3103 * JB_ERR_MEMORY on out-of-memory error.
3105 *********************************************************************/
3106 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3109 #ifdef HAVE_GMTIME_R
3112 struct tm *timeptr = NULL;
3115 long int hours, minutes, seconds;
3118 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3121 * The client got an error message because of a temporary problem,
3122 * the problem is gone and the client now tries to revalidate our
3123 * error message on the real server. The revalidation would always
3124 * end with the transmission of the whole document and there is
3125 * no need to expose the bogus If-Modified-Since header.
3127 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3130 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3132 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3134 if ((0 == strcmpic(newval, "block")))
3136 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3139 else /* add random value */
3141 const char *header_time = *header + sizeof("If-Modified-Since:");
3143 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3145 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3150 long int rtime = strtol(newval, &endptr, 0);
3151 const int negative_range = (rtime < 0);
3155 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3156 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3162 rtime = pick_from_range(rtime);
3166 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3169 tm += rtime * (negative_range ? -1 : 1);
3170 #ifdef HAVE_GMTIME_R
3171 timeptr = gmtime_r(&tm, &gmt);
3172 #elif defined(MUTEX_LOCKS_AVAILABLE)
3173 privoxy_mutex_lock(&gmtime_mutex);
3174 timeptr = gmtime(&tm);
3175 privoxy_mutex_unlock(&gmtime_mutex);
3177 timeptr = gmtime(&tm);
3179 if ((NULL == timeptr) || !strftime(newheader,
3180 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3182 log_error(LOG_LEVEL_ERROR,
3183 "Randomizing '%s' failed. Crunching the header without replacement.",
3190 *header = strdup("If-Modified-Since: ");
3191 string_append(header, newheader);
3193 if (*header == NULL)
3195 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3196 return JB_ERR_MEMORY;
3199 hours = rtime / 3600;
3200 minutes = rtime / 60 % 60;
3201 seconds = rtime % 60;
3203 log_error(LOG_LEVEL_HEADER,
3204 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3205 *header, (negative_range) ? "subtracted" : "added", hours,
3206 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3207 seconds, (seconds == 1) ? ")" : "s)");
3216 /*********************************************************************
3218 * Function : client_if_none_match
3220 * Description : Remove the If-None-Match header.
3223 * 1 : csp = Current client state (buffers, headers, etc...)
3224 * 2 : header = On input, pointer to header to modify.
3225 * On output, pointer to the modified header, or NULL
3226 * to remove the header. This function frees the
3227 * original string if necessary.
3229 * Returns : JB_ERR_OK on success, or
3230 * JB_ERR_MEMORY on out-of-memory error.
3232 *********************************************************************/
3233 static jb_err client_if_none_match(struct client_state *csp, char **header)
3235 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3237 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3245 /*********************************************************************
3247 * Function : client_x_filter
3249 * Description : Disables filtering if the client set "X-Filter: No".
3250 * Called from `sed'.
3253 * 1 : csp = Current client state (buffers, headers, etc...)
3254 * 2 : header = On input, pointer to header to modify.
3255 * On output, pointer to the modified header, or NULL
3256 * to remove the header. This function frees the
3257 * original string if necessary.
3259 * Returns : JB_ERR_OK on success
3261 *********************************************************************/
3262 jb_err client_x_filter(struct client_state *csp, char **header)
3264 if ( 0 == strcmpic(*header, "X-Filter: No"))
3266 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3268 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3272 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3274 log_error(LOG_LEVEL_HEADER,
3275 "force-text-mode overruled the client's request to fetch without filtering!");
3279 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3280 csp->flags |= CSP_FLAG_NO_FILTERING;
3281 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3283 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3291 /*********************************************************************
3293 * Function : client_range
3295 * Description : Removes Range, Request-Range and If-Range headers if
3296 * content filtering is enabled. If the client's version
3297 * of the document has been altered by Privoxy, the server
3298 * could interpret the range differently than the client
3299 * intended in which case the user could end up with
3300 * corrupted content.
3303 * 1 : csp = Current client state (buffers, headers, etc...)
3304 * 2 : header = On input, pointer to header to modify.
3305 * On output, pointer to the modified header, or NULL
3306 * to remove the header. This function frees the
3307 * original string if necessary.
3309 * Returns : JB_ERR_OK
3311 *********************************************************************/
3312 static jb_err client_range(struct client_state *csp, char **header)
3314 if (content_filters_enabled(csp->action))
3316 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3317 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3324 /* the following functions add headers directly to the header list */
3326 /*********************************************************************
3328 * Function : client_host_adder
3330 * Description : Adds the Host: header field if it is missing.
3331 * Called from `sed'.
3334 * 1 : csp = Current client state (buffers, headers, etc...)
3336 * Returns : JB_ERR_OK on success, or
3337 * JB_ERR_MEMORY on out-of-memory error.
3339 *********************************************************************/
3340 static jb_err client_host_adder(struct client_state *csp)
3345 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3347 /* Header already set by the client, nothing to do. */
3351 if ( !csp->http->hostport || !*(csp->http->hostport))
3353 /* XXX: When does this happen and why is it OK? */
3354 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3359 * remove 'user:pass@' from 'proto://user:pass@host'
3361 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3367 p = csp->http->hostport;
3370 /* XXX: Just add it, we already made sure that it will be unique */
3371 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3372 err = enlist_unique_header(csp->headers, "Host", p);
3379 /*********************************************************************
3381 * Function : client_accept_encoding_adder
3383 * Description : Add an Accept-Encoding header to the client's request
3384 * that disables compression if the action applies, and
3385 * the header is not already there. Called from `sed'.
3386 * Note: For HTTP/1.0, the absence of the header is enough.
3389 * 1 : csp = Current client state (buffers, headers, etc...)
3391 * Returns : JB_ERR_OK on success, or
3392 * JB_ERR_MEMORY on out-of-memory error.
3394 *********************************************************************/
3395 static jb_err client_accept_encoding_adder(struct client_state *csp)
3397 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3398 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3400 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3408 /*********************************************************************
3410 * Function : client_xtra_adder
3412 * Description : Used in the add_client_headers list. Called from `sed'.
3415 * 1 : csp = Current client state (buffers, headers, etc...)
3417 * Returns : JB_ERR_OK on success, or
3418 * JB_ERR_MEMORY on out-of-memory error.
3420 *********************************************************************/
3421 static jb_err client_xtra_adder(struct client_state *csp)
3423 struct list_entry *lst;
3426 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3427 lst ; lst = lst->next)
3429 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3430 err = enlist(csp->headers, lst->str);
3442 /*********************************************************************
3444 * Function : client_x_forwarded_for_adder
3446 * Description : Used in the add_client_headers list. Called from `sed'.
3449 * 1 : csp = Current client state (buffers, headers, etc...)
3451 * Returns : JB_ERR_OK on success, or
3452 * JB_ERR_MEMORY on out-of-memory error.
3454 *********************************************************************/
3455 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3457 char *header = NULL;
3460 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3461 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3462 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3465 * If we aren't adding X-Forwarded-For headers,
3466 * or we already appended an existing X-Forwarded-For
3467 * header, there's nothing left to do here.
3472 header = strdup("X-Forwarded-For: ");
3473 string_append(&header, csp->ip_addr_str);
3477 return JB_ERR_MEMORY;
3480 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3481 err = enlist(csp->headers, header);
3488 /*********************************************************************
3490 * Function : server_connection_adder
3492 * Description : Adds an appropiate "Connection:" header to csp->headers
3493 * unless the header was already present. Called from `sed'.
3496 * 1 : csp = Current client state (buffers, headers, etc...)
3498 * Returns : JB_ERR_OK on success, or
3499 * JB_ERR_MEMORY on out-of-memory error.
3501 *********************************************************************/
3502 static jb_err server_connection_adder(struct client_state *csp)
3504 const unsigned int flags = csp->flags;
3505 const char *response_status_line = csp->headers->first->str;
3506 static const char connection_close[] = "Connection: close";
3508 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3509 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3515 * XXX: if we downgraded the response, this check will fail.
3517 if ((csp->config->feature_flags &
3518 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3519 && (NULL != response_status_line)
3520 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3521 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3522 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3526 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3527 "without Connection header implies keep-alive.");
3528 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3532 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3534 return enlist(csp->headers, connection_close);
3538 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3539 /*********************************************************************
3541 * Function : server_proxy_connection_adder
3543 * Description : Adds a "Proxy-Connection: keep-alive" header to
3544 * csp->headers if the client asked for keep-alive.
3545 * XXX: We should reuse existant ones.
3548 * 1 : csp = Current client state (buffers, headers, etc...)
3550 * Returns : JB_ERR_OK on success, or
3551 * JB_ERR_MEMORY on out-of-memory error.
3553 *********************************************************************/
3554 static jb_err server_proxy_connection_adder(struct client_state *csp)
3556 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3557 jb_err err = JB_ERR_OK;
3559 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3560 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3561 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET))
3563 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3564 err = enlist(csp->headers, proxy_connection_header);
3569 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3572 /*********************************************************************
3574 * Function : client_connection_header_adder
3576 * Description : Adds a proper "Connection:" header to csp->headers
3577 * unless the header was already present. Called from `sed'.
3580 * 1 : csp = Current client state (buffers, headers, etc...)
3582 * Returns : JB_ERR_OK on success, or
3583 * JB_ERR_MEMORY on out-of-memory error.
3585 *********************************************************************/
3586 static jb_err client_connection_header_adder(struct client_state *csp)
3588 static const char connection_close[] = "Connection: close";
3590 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3591 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3596 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3597 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3598 && (csp->http->ssl == 0)
3599 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3601 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3604 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3606 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3608 return enlist(csp->headers, connection_close);
3612 /*********************************************************************
3614 * Function : server_http
3616 * Description : - Save the HTTP Status into csp->http->status
3617 * - Set CT_TABOO to prevent filtering if the answer
3618 * is a partial range (HTTP status 206)
3619 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3623 * 1 : csp = Current client state (buffers, headers, etc...)
3624 * 2 : header = On input, pointer to header to modify.
3625 * On output, pointer to the modified header, or NULL
3626 * to remove the header. This function frees the
3627 * original string if necessary.
3629 * Returns : JB_ERR_OK on success, or
3630 * JB_ERR_MEMORY on out-of-memory error.
3632 *********************************************************************/
3633 static jb_err server_http(struct client_state *csp, char **header)
3635 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3636 if (csp->http->status == 206)
3638 csp->content_type = CT_TABOO;
3641 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3643 /* XXX: Should we do a real validity check here? */
3644 if (strlen(*header) > 8)
3647 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3652 * XXX: Should we block the request or
3653 * enlist a valid status code line here?
3655 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3656 "Downgrading to HTTP/1.0 impossible.");
3664 /*********************************************************************
3666 * Function : server_set_cookie
3668 * Description : Handle the server "cookie" header properly.
3669 * Crunch, accept or rewrite it to a session cookie.
3670 * Called from `sed'.
3672 * TODO: Allow the user to specify a new expiration
3673 * time to cause the cookie to expire even before the
3674 * browser is closed.
3677 * 1 : csp = Current client state (buffers, headers, etc...)
3678 * 2 : header = On input, pointer to header to modify.
3679 * On output, pointer to the modified header, or NULL
3680 * to remove the header. This function frees the
3681 * original string if necessary.
3683 * Returns : JB_ERR_OK on success, or
3684 * JB_ERR_MEMORY on out-of-memory error.
3686 *********************************************************************/
3687 static jb_err server_set_cookie(struct client_state *csp, char **header)
3694 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3696 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3699 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3701 /* Flag whether or not to log a message */
3704 /* A variable to store the tag we're working on */
3707 /* Skip "Set-Cookie:" (11 characters) in header */
3708 cur_tag = *header + 11;
3710 /* skip whitespace between "Set-Cookie:" and value */
3711 while (*cur_tag && ijb_isspace(*cur_tag))
3716 /* Loop through each tag in the cookie */
3720 char *next_tag = strchr(cur_tag, ';');
3721 if (next_tag != NULL)
3723 /* Skip the ';' character itself */
3726 /* skip whitespace ";" and start of tag */
3727 while (*next_tag && ijb_isspace(*next_tag))
3734 /* "Next tag" is the end of the string */
3735 next_tag = cur_tag + strlen(cur_tag);
3739 * Check the expiration date to see
3740 * if the cookie is still valid, if yes,
3741 * rewrite it to a session cookie.
3743 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3745 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3747 /* Did we detect the date properly? */
3748 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3751 * Nope, treat it as if it was still valid.
3753 * XXX: Should we remove the whole cookie instead?
3755 log_error(LOG_LEVEL_ERROR,
3756 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3757 string_move(cur_tag, next_tag);
3763 * Yes. Check if the cookie is still valid.
3765 * If the cookie is already expired it's probably
3766 * a delete cookie and even if it isn't, the browser
3767 * will discard it anyway.
3771 * XXX: timegm() isn't available on some AmigaOS
3772 * versions and our replacement doesn't work.
3774 * Our options are to either:
3776 * - disable session-cookies-only completely if timegm
3779 * - to simply remove all expired tags, like it has
3780 * been done until Privoxy 3.0.6 and to live with
3781 * the consequence that it can cause login/logout
3782 * problems on servers that don't validate their
3783 * input properly, or
3785 * - to replace it with mktime in which
3786 * case there is a slight chance of valid cookies
3787 * passing as already expired.
3789 * This is the way it's currently done and it's not
3790 * as bad as it sounds. If the missing GMT offset is
3791 * enough to change the result of the expiration check
3792 * the cookie will be only valid for a few hours
3793 * anyway, which in many cases will be shorter
3794 * than a browser session.
3796 if (cookie_time - now < 0)
3798 log_error(LOG_LEVEL_HEADER,
3799 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3800 /* Just in case some clown sets more then one expiration date */
3806 * Still valid, delete expiration date by copying
3807 * the rest of the string over it.
3809 string_move(cur_tag, next_tag);
3811 /* That changed the header, need to issue a log message */
3815 * Note that the next tag has now been moved to *cur_tag,
3816 * so we do not need to update the cur_tag pointer.
3824 /* Move on to next cookie tag */
3831 assert(NULL != *header);
3832 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3841 #ifdef FEATURE_FORCE_LOAD
3842 /*********************************************************************
3844 * Function : strclean
3846 * Description : In-Situ-Eliminate all occurances of substring in
3850 * 1 : string = string to clean
3851 * 2 : substring = substring to eliminate
3853 * Returns : Number of eliminations
3855 *********************************************************************/
3856 int strclean(char *string, const char *substring)
3862 len = strlen(substring);
3864 while((pos = strstr(string, substring)) != NULL)
3871 while (*p++ != '\0');
3878 #endif /* def FEATURE_FORCE_LOAD */
3881 /*********************************************************************
3883 * Function : parse_header_time
3885 * Description : Parses time formats used in HTTP header strings
3886 * to get the numerical respresentation.
3889 * 1 : header_time = HTTP header time as string.
3890 * 2 : result = storage for header_time in seconds
3892 * Returns : JB_ERR_OK if the time format was recognized, or
3893 * JB_ERR_PARSE otherwise.
3895 *********************************************************************/
3896 static jb_err parse_header_time(const char *header_time, time_t *result)
3901 * Zero out gmt to prevent time zone offsets.
3903 * While this is only necessary on some platforms
3904 * (mingw32 for example), I don't know how to
3905 * detect these automatically and doing it everywhere
3908 memset(&gmt, 0, sizeof(gmt));
3910 /* Tue, 02 Jun 2037 20:00:00 */
3911 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3912 /* Tue, 02-Jun-2037 20:00:00 */
3913 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3914 /* Tue, 02-Jun-37 20:00:00 */
3915 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3916 /* Tuesday, 02-Jun-2037 20:00:00 */
3917 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3918 /* Tuesday Jun 02 20:00:00 2037 */
3919 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3921 return JB_ERR_PARSE;
3924 *result = timegm(&gmt);
3931 /*********************************************************************
3933 * Function : get_destination_from_headers
3935 * Description : Parse the "Host:" header to get the request's destination.
3936 * Only needed if the client's request was forcefully
3937 * redirected into Privoxy.
3939 * Code mainly copied from client_host() which is currently
3940 * run too late for this purpose.
3943 * 1 : headers = List of headers (one of them hopefully being
3944 * the "Host:" header)
3945 * 2 : http = storage for the result (host, port and hostport).
3947 * Returns : JB_ERR_MEMORY in case of memory problems,
3948 * JB_ERR_PARSE if the host header couldn't be found,
3949 * JB_ERR_OK otherwise.
3951 *********************************************************************/
3952 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3958 host = get_header_value(headers, "Host:");
3962 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3963 return JB_ERR_PARSE;
3966 if (NULL == (p = strdup((host))))
3968 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3969 return JB_ERR_MEMORY;
3972 if (NULL == (q = strdup(p)))
3975 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3976 return JB_ERR_MEMORY;
3979 freez(http->hostport);
3983 q = strchr(http->host, ':');
3986 /* Terminate hostname and evaluate port string */
3988 http->port = atoi(q);
3992 http->port = http->ssl ? 443 : 80;
3995 /* Rebuild request URL */
3997 http->url = strdup(http->ssl ? "https://" : "http://");
3998 string_append(&http->url, http->hostport);
3999 string_append(&http->url, http->path);
4000 if (http->url == NULL)
4002 return JB_ERR_MEMORY;
4005 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4013 /*********************************************************************
4015 * Function : create_forged_referrer
4017 * Description : Helper for client_referrer to forge a referer as
4018 * 'http://[hostname:port/' to fool stupid
4019 * checks for in-site links
4022 * 1 : header = Pointer to header pointer
4023 * 2 : hostport = Host and optionally port as string
4025 * Returns : JB_ERR_OK in case of success, or
4026 * JB_ERR_MEMORY in case of memory problems.
4028 *********************************************************************/
4029 static jb_err create_forged_referrer(char **header, const char *hostport)
4031 assert(NULL == *header);
4033 *header = strdup("Referer: http://");
4034 string_append(header, hostport);
4035 string_append(header, "/");
4037 if (NULL == *header)
4039 return JB_ERR_MEMORY;
4042 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4049 /*********************************************************************
4051 * Function : create_fake_referrer
4053 * Description : Helper for client_referrer to create a fake referrer
4054 * based on a string supplied by the user.
4057 * 1 : header = Pointer to header pointer
4058 * 2 : hosthost = Referrer to fake
4060 * Returns : JB_ERR_OK in case of success, or
4061 * JB_ERR_MEMORY in case of memory problems.
4063 *********************************************************************/
4064 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4066 assert(NULL == *header);
4068 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4070 log_error(LOG_LEVEL_HEADER,
4071 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4073 *header = strdup("Referer: ");
4074 string_append(header, fake_referrer);
4076 if (NULL == *header)
4078 return JB_ERR_MEMORY;
4081 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4088 /*********************************************************************
4090 * Function : handle_conditional_hide_referrer_parameter
4092 * Description : Helper for client_referrer to crunch or forge
4093 * the referrer header if the host has changed.
4096 * 1 : header = Pointer to header pointer
4097 * 2 : host = The target host (may include the port)
4098 * 3 : parameter_conditional_block = Boolean to signal
4099 * if we're in conditional-block mode. If not set,
4100 * we're in conditional-forge mode.
4102 * Returns : JB_ERR_OK in case of success, or
4103 * JB_ERR_MEMORY in case of memory problems.
4105 *********************************************************************/
4106 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4107 const char *host, const int parameter_conditional_block)
4109 char *referer = strdup(*header);
4110 const size_t hostlenght = strlen(host);
4111 const char *referer_url = NULL;
4113 if (NULL == referer)
4116 return JB_ERR_MEMORY;
4119 /* referer begins with 'Referer: http[s]://' */
4120 if ((hostlenght+17) < strlen(referer))
4123 * Shorten referer to make sure the referer is blocked
4124 * if www.example.org/www.example.com-shall-see-the-referer/
4125 * links to www.example.com/
4127 referer[hostlenght+17] = '\0';
4129 referer_url = strstr(referer, "http://");
4130 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4132 /* Host has changed, Referer is invalid or a https URL. */
4133 if (parameter_conditional_block)
4135 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4142 return create_forged_referrer(header, host);
4152 /*********************************************************************
4154 * Function : create_content_length_header
4156 * Description : Creates a Content-Length header.
4159 * 1 : content_length = The content length to be used in the header.
4160 * 2 : header = Allocated space to safe the header.
4161 * 3 : buffer_length = The length of the allocated space.
4165 *********************************************************************/
4166 static void create_content_length_header(unsigned long long content_length,
4167 char *header, size_t buffer_length)
4169 snprintf(header, buffer_length, "Content-Length: %llu", content_length);