1 const char parsers_rcs[] = "$Id: parsers.c,v 1.248 2012/09/04 08:32:32 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
8 * Copyright : Written by and Copyright (C) 2001-2012 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
40 #include <sys/types.h>
50 * Convince GNU's libc to provide a strptime prototype.
59 #define GZIP_IDENTIFIER_1 0x1f
60 #define GZIP_IDENTIFIER_2 0x8b
62 #define GZIP_FLAG_CHECKSUM 0x02
63 #define GZIP_FLAG_EXTRA_FIELDS 0x04
64 #define GZIP_FLAG_FILE_NAME 0x08
65 #define GZIP_FLAG_COMMENT 0x10
66 #define GZIP_FLAG_RESERVED_BITS 0xe0
69 #if !defined(_WIN32) && !defined(__OS2__)
75 #ifdef FEATURE_PTHREAD
77 /* jcc.h is for mutex semapores only */
78 #endif /* def FEATURE_PTHREAD */
83 #include "jbsockets.h"
93 const char parsers_h_rcs[] = PARSERS_H_VERSION;
95 static char *get_header_line(struct iob *iob);
96 static jb_err scan_headers(struct client_state *csp);
97 static jb_err header_tagger(struct client_state *csp, char *header);
98 static jb_err parse_header_time(const char *header_time, time_t *result);
100 static jb_err crumble (struct client_state *csp, char **header);
101 static jb_err filter_header (struct client_state *csp, char **header);
102 static jb_err client_connection (struct client_state *csp, char **header);
103 static jb_err client_referrer (struct client_state *csp, char **header);
104 static jb_err client_uagent (struct client_state *csp, char **header);
105 static jb_err client_ua (struct client_state *csp, char **header);
106 static jb_err client_from (struct client_state *csp, char **header);
107 static jb_err client_send_cookie (struct client_state *csp, char **header);
108 static jb_err client_x_forwarded (struct client_state *csp, char **header);
109 static jb_err client_accept_encoding (struct client_state *csp, char **header);
110 static jb_err client_te (struct client_state *csp, char **header);
111 static jb_err client_max_forwards (struct client_state *csp, char **header);
112 static jb_err client_host (struct client_state *csp, char **header);
113 static jb_err client_if_modified_since (struct client_state *csp, char **header);
114 static jb_err client_accept_language (struct client_state *csp, char **header);
115 static jb_err client_if_none_match (struct client_state *csp, char **header);
116 static jb_err crunch_client_header (struct client_state *csp, char **header);
117 static jb_err client_x_filter (struct client_state *csp, char **header);
118 static jb_err client_range (struct client_state *csp, char **header);
119 static jb_err server_set_cookie (struct client_state *csp, char **header);
120 static jb_err server_connection (struct client_state *csp, char **header);
121 static jb_err server_content_type (struct client_state *csp, char **header);
122 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
123 static jb_err server_content_md5 (struct client_state *csp, char **header);
124 static jb_err server_content_encoding (struct client_state *csp, char **header);
125 static jb_err server_transfer_coding (struct client_state *csp, char **header);
126 static jb_err server_http (struct client_state *csp, char **header);
127 static jb_err crunch_server_header (struct client_state *csp, char **header);
128 static jb_err server_last_modified (struct client_state *csp, char **header);
129 static jb_err server_content_disposition(struct client_state *csp, char **header);
131 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
134 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
135 static jb_err server_save_content_length(struct client_state *csp, char **header);
136 static jb_err server_keep_alive(struct client_state *csp, char **header);
137 static jb_err server_proxy_connection(struct client_state *csp, char **header);
138 static jb_err client_keep_alive(struct client_state *csp, char **header);
139 static jb_err client_save_content_length(struct client_state *csp, char **header);
140 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
142 static jb_err client_host_adder (struct client_state *csp);
143 static jb_err client_xtra_adder (struct client_state *csp);
144 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
145 static jb_err client_connection_header_adder(struct client_state *csp);
146 static jb_err server_connection_adder(struct client_state *csp);
147 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
148 static jb_err server_proxy_connection_adder(struct client_state *csp);
149 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
151 static jb_err create_forged_referrer(char **header, const char *hostport);
152 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
153 static jb_err handle_conditional_hide_referrer_parameter(char **header,
154 const char *host, const int parameter_conditional_block);
155 static void create_content_length_header(unsigned long long content_length,
156 char *header, size_t buffer_length);
159 * List of functions to run on a list of headers.
163 /** The header prefix to match */
166 /** The length of the prefix to match */
169 /** The function to apply to this line */
170 const parser_func_ptr parser;
173 static const struct parsers client_patterns[] = {
174 { "referer:", 8, client_referrer },
175 { "user-agent:", 11, client_uagent },
176 { "ua-", 3, client_ua },
177 { "from:", 5, client_from },
178 { "cookie:", 7, client_send_cookie },
179 { "x-forwarded-for:", 16, client_x_forwarded },
180 { "Accept-Encoding:", 16, client_accept_encoding },
181 { "TE:", 3, client_te },
182 { "Host:", 5, client_host },
183 { "if-modified-since:", 18, client_if_modified_since },
184 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
185 { "Keep-Alive:", 11, client_keep_alive },
186 { "Content-Length:", 15, client_save_content_length },
188 { "Keep-Alive:", 11, crumble },
190 { "connection:", 11, client_connection },
191 { "proxy-connection:", 17, crumble },
192 { "max-forwards:", 13, client_max_forwards },
193 { "Accept-Language:", 16, client_accept_language },
194 { "if-none-match:", 14, client_if_none_match },
195 { "Range:", 6, client_range },
196 { "Request-Range:", 14, client_range },
197 { "If-Range:", 9, client_range },
198 { "X-Filter:", 9, client_x_filter },
199 { "*", 0, crunch_client_header },
200 { "*", 0, filter_header },
204 static const struct parsers server_patterns[] = {
205 { "HTTP/", 5, server_http },
206 { "set-cookie:", 11, server_set_cookie },
207 { "connection:", 11, server_connection },
208 { "Content-Type:", 13, server_content_type },
209 { "Content-MD5:", 12, server_content_md5 },
210 { "Content-Encoding:", 17, server_content_encoding },
211 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
212 { "Content-Length:", 15, server_save_content_length },
213 { "Keep-Alive:", 11, server_keep_alive },
214 { "Proxy-Connection:", 17, server_proxy_connection },
216 { "Keep-Alive:", 11, crumble },
217 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
218 { "Transfer-Encoding:", 18, server_transfer_coding },
219 { "content-disposition:", 20, server_content_disposition },
220 { "Last-Modified:", 14, server_last_modified },
221 { "*", 0, crunch_server_header },
222 { "*", 0, filter_header },
226 static const add_header_func_ptr add_client_headers[] = {
228 client_x_forwarded_for_adder,
230 client_connection_header_adder,
234 static const add_header_func_ptr add_server_headers[] = {
235 server_connection_adder,
236 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
237 server_proxy_connection_adder,
238 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
242 /*********************************************************************
244 * Function : flush_socket
246 * Description : Write any pending "buffered" content.
249 * 1 : fd = file descriptor of the socket to read
250 * 2 : iob = The I/O buffer to flush, usually csp->iob.
252 * Returns : On success, the number of bytes written are returned (zero
253 * indicates nothing was written). On error, -1 is returned,
254 * and errno is set appropriately. If count is zero and the
255 * file descriptor refers to a regular file, 0 will be
256 * returned without causing any other effect. For a special
257 * file, the results are not portable.
259 *********************************************************************/
260 long flush_socket(jb_socket fd, struct iob *iob)
262 long len = iob->eod - iob->cur;
269 if (write_socket(fd, iob->cur, (size_t)len))
273 iob->eod = iob->cur = iob->buf;
279 /*********************************************************************
281 * Function : add_to_iob
283 * Description : Add content to the buffered page, expanding the
284 * buffer if necessary.
287 * 1 : csp = Current client state (buffers, headers, etc...)
288 * 2 : buf = holds the content to be added to the page
289 * 3 : n = number of bytes to be added
291 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
292 * or buffer limit reached.
294 *********************************************************************/
295 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
297 struct iob *iob = csp->iob;
298 size_t used, offset, need;
301 if (n <= 0) return JB_ERR_OK;
303 used = (size_t)(iob->eod - iob->buf);
304 offset = (size_t)(iob->cur - iob->buf);
305 need = used + (size_t)n + 1;
308 * If the buffer can't hold the new data, extend it first.
309 * Use the next power of two if possible, else use the actual need.
311 if (need > csp->config->buffer_limit)
313 log_error(LOG_LEVEL_INFO,
314 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
315 need, csp->config->buffer_limit);
316 return JB_ERR_MEMORY;
319 if (need > iob->size)
321 size_t want = csp->iob->size ? csp->iob->size : 512;
328 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
332 else if (NULL != (p = (char *)realloc(iob->buf, need)))
338 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
339 return JB_ERR_MEMORY;
342 /* Update the iob pointers */
343 iob->cur = p + offset;
348 /* copy the new data into the iob buffer */
349 memcpy(iob->eod, buf, (size_t)n);
351 /* point to the end of the data */
354 /* null terminate == cheap insurance */
363 /*********************************************************************
365 * Function : decompress_iob
367 * Description : Decompress buffered page, expanding the
368 * buffer as necessary. csp->iob->cur
369 * should point to the the beginning of the
370 * compressed data block.
373 * 1 : csp = Current client state (buffers, headers, etc...)
375 * Returns : JB_ERR_OK on success,
376 * JB_ERR_MEMORY if out-of-memory limit reached, and
377 * JB_ERR_COMPRESS if error decompressing buffer.
379 *********************************************************************/
380 jb_err decompress_iob(struct client_state *csp)
382 char *buf; /* new, uncompressed buffer */
383 char *cur; /* Current iob position (to keep the original
384 * iob->cur unmodified if we return early) */
385 size_t bufsize; /* allocated size of the new buffer */
386 size_t old_size; /* Content size before decompression */
387 size_t skip_size; /* Number of bytes at the beginning of the iob
388 that we should NOT decompress. */
389 int status; /* return status of the inflate() call */
390 z_stream zstr; /* used by calls to zlib */
392 assert(csp->iob->cur - csp->iob->buf > 0);
393 assert(csp->iob->eod - csp->iob->cur > 0);
395 bufsize = csp->iob->size;
396 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
397 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
401 if (bufsize < (size_t)10)
404 * This is to protect the parsing of gzipped data,
405 * but it should(?) be valid for deflated data also.
407 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
408 return JB_ERR_COMPRESS;
411 if (csp->content_type & CT_GZIP)
414 * Our task is slightly complicated by the facts that data
415 * compressed by gzip does not include a zlib header, and
416 * that there is no easily accessible interface in zlib to
417 * handle a gzip header. We strip off the gzip header by
418 * hand, and later inform zlib not to expect a header.
422 * Strip off the gzip header. Please see RFC 1952 for more
423 * explanation of the appropriate fields.
425 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
426 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
427 || (*cur++ != Z_DEFLATED))
429 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
430 return JB_ERR_COMPRESS;
435 if (flags & GZIP_FLAG_RESERVED_BITS)
437 /* The gzip header has reserved bits set; bail out. */
438 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
439 return JB_ERR_COMPRESS;
443 * Skip mtime (4 bytes), extra flags (1 byte)
444 * and OS type (1 byte).
448 /* Skip extra fields if necessary. */
449 if (flags & GZIP_FLAG_EXTRA_FIELDS)
452 * Skip a given number of bytes, specified
453 * as a 16-bit little-endian value.
455 * XXX: this code is untested and should probably be removed.
459 skip_bytes += *cur++ << 8;
462 * The number of bytes to skip should be positive
463 * and we'd like to stay in the buffer.
465 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
467 log_error(LOG_LEVEL_ERROR,
468 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
470 return JB_ERR_COMPRESS;
472 log_error(LOG_LEVEL_INFO,
473 "Skipping %d bytes for gzip compression. Does this sound right?",
478 /* Skip the filename if necessary. */
479 if (flags & GZIP_FLAG_FILE_NAME)
481 /* A null-terminated string is supposed to follow. */
482 while (*cur++ && (cur < csp->iob->eod));
485 /* Skip the comment if necessary. */
486 if (flags & GZIP_FLAG_COMMENT)
488 /* A null-terminated string is supposed to follow. */
489 while (*cur++ && (cur < csp->iob->eod));
492 /* Skip the CRC if necessary. */
493 if (flags & GZIP_FLAG_CHECKSUM)
498 if (cur >= csp->iob->eod)
501 * If the current position pointer reached or passed
502 * the buffer end, we were obviously tricked to skip
505 log_error(LOG_LEVEL_ERROR,
506 "Malformed gzip header detected. Aborting decompression.");
507 return JB_ERR_COMPRESS;
511 else if (csp->content_type & CT_DEFLATE)
514 * XXX: The debug level should be lowered
515 * before the next stable release.
517 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
519 * In theory (that is, according to RFC 1950), deflate-compressed
520 * data should begin with a two-byte zlib header and have an
521 * adler32 checksum at the end. It seems that in practice only
522 * the raw compressed data is sent. Note that this means that
523 * we are not RFC 1950-compliant here, but the advantage is that
524 * this actually works. :)
526 * We add a dummy null byte to tell zlib where the data ends,
527 * and later inform it not to expect a header.
529 * Fortunately, add_to_iob() has thoughtfully null-terminated
530 * the buffer; we can just increment the end pointer to include
537 log_error(LOG_LEVEL_ERROR,
538 "Unable to determine compression format for decompression");
539 return JB_ERR_COMPRESS;
542 /* Set up the fields required by zlib. */
543 zstr.next_in = (Bytef *)cur;
544 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
545 zstr.zalloc = Z_NULL;
547 zstr.opaque = Z_NULL;
550 * Passing -MAX_WBITS to inflateInit2 tells the library
551 * that there is no zlib header.
553 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
555 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
556 return JB_ERR_COMPRESS;
560 * Next, we allocate new storage for the inflated data.
561 * We don't modify the existing iob yet, so in case there
562 * is error in decompression we can recover gracefully.
564 buf = zalloc(bufsize);
567 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
568 return JB_ERR_MEMORY;
571 assert(bufsize >= skip_size);
572 memcpy(buf, csp->iob->buf, skip_size);
573 zstr.avail_out = (uInt)(bufsize - skip_size);
574 zstr.next_out = (Bytef *)buf + skip_size;
576 /* Try to decompress the whole stream in one shot. */
577 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
579 /* We need to allocate more memory for the output buffer. */
581 char *tmpbuf; /* used for realloc'ing the buffer */
582 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
584 if (0 == zstr.avail_in)
587 * If zlib wants more data then there's a problem, because
588 * the complete compressed file should have been buffered.
590 log_error(LOG_LEVEL_ERROR,
591 "Unexpected end of compressed iob. Using what we got so far.");
596 * If we reached the buffer limit and still didn't have enough
597 * memory, just give up. Due to the ceiling enforced by the next
598 * if block we could actually check for equality here, but as it
599 * can be easily mistaken for a bug we don't.
601 if (bufsize >= csp->config->buffer_limit)
603 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
604 return JB_ERR_MEMORY;
607 /* Try doubling the buffer size each time. */
610 /* Don't exceed the buffer limit. */
611 if (bufsize > csp->config->buffer_limit)
613 bufsize = csp->config->buffer_limit;
616 /* Try to allocate the new buffer. */
617 tmpbuf = realloc(buf, bufsize);
620 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
622 return JB_ERR_MEMORY;
626 char *oldnext_out = (char *)zstr.next_out;
629 * Update the fields for inflate() to use the new
630 * buffer, which may be in a location different from
633 zstr.avail_out += (uInt)(bufsize - oldbufsize);
634 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
637 * Compare with an uglier method of calculating these values
638 * that doesn't require the extra oldbufsize variable.
640 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
641 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
647 if (Z_STREAM_ERROR == inflateEnd(&zstr))
649 log_error(LOG_LEVEL_ERROR,
650 "Inconsistent stream state after decompression: %s", zstr.msg);
652 * XXX: Intentionally no return.
654 * According to zlib.h, Z_STREAM_ERROR is returned
655 * "if the stream state was inconsistent".
657 * I assume in this case inflate()'s status
658 * would also be something different than Z_STREAM_END
659 * so this check should be redundant, but lets see.
663 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
666 * We failed to decompress the stream and it's
667 * not simply because of missing data.
669 log_error(LOG_LEVEL_ERROR,
670 "Unexpected error while decompressing to the buffer (iob): %s",
672 return JB_ERR_COMPRESS;
676 * Finally, we can actually update the iob, since the
677 * decompression was successful. First, free the old
680 freez(csp->iob->buf);
682 /* Now, update the iob to use the new buffer. */
684 csp->iob->cur = csp->iob->buf + skip_size;
685 csp->iob->eod = (char *)zstr.next_out;
686 csp->iob->size = bufsize;
689 * Make sure the new uncompressed iob obeys some minimal
690 * consistency conditions.
692 if ((csp->iob->buf < csp->iob->cur)
693 && (csp->iob->cur <= csp->iob->eod)
694 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
696 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
697 if (new_size > (size_t)0)
699 log_error(LOG_LEVEL_RE_FILTER,
700 "Decompression successful. Old size: %d, new size: %d.",
705 /* zlib thinks this is OK, so lets do the same. */
706 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
711 /* It seems that zlib did something weird. */
712 log_error(LOG_LEVEL_ERROR,
713 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
714 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
715 csp->iob->eod, csp->iob->buf + csp->iob->size);
716 return JB_ERR_COMPRESS;
722 #endif /* defined(FEATURE_ZLIB) */
725 /*********************************************************************
727 * Function : string_move
729 * Description : memmove wrapper to move the last part of a string
730 * towards the beginning, overwriting the part in
731 * the middle. strlcpy() can't be used here as the
735 * 1 : dst = Destination to overwrite
736 * 2 : src = Source to move.
740 *********************************************************************/
741 static void string_move(char *dst, char *src)
745 /* +1 to copy the terminating nul as well. */
746 memmove(dst, src, strlen(src)+1);
750 /*********************************************************************
752 * Function : normalize_lws
754 * Description : Reduces unquoted linear white space in headers
755 * to a single space in accordance with RFC 2616 2.2.
756 * This simplifies parsing and filtering later on.
758 * XXX: Remove log messages before
759 * the next stable release?
762 * 1 : header = A header with linear white space to reduce.
766 *********************************************************************/
767 static void normalize_lws(char *header)
773 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
777 while (privoxy_isspace(*q))
781 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
787 log_error(LOG_LEVEL_HEADER,
788 "Converting tab to space in '%s'", header);
793 char *end_of_token = strstr(p+1, "\"");
795 if (NULL != end_of_token)
797 /* Don't mess with quoted text. */
802 log_error(LOG_LEVEL_HEADER,
803 "Ignoring single quote in '%s'", header);
809 p = strchr(header, ':');
810 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
813 * There's still space before the colon.
821 /*********************************************************************
823 * Function : get_header
825 * Description : This (odd) routine will parse the csp->iob
826 * to get the next complete header.
829 * 1 : iob = The I/O buffer to parse, usually csp->iob.
831 * Returns : Any one of the following:
833 * 1) a pointer to a dynamically allocated string that contains a header line
834 * 2) NULL indicating that the end of the header was reached
835 * 3) "" indicating that the end of the iob was reached before finding
836 * a complete header line.
838 *********************************************************************/
839 char *get_header(struct iob *iob)
843 header = get_header_line(iob);
845 if ((header == NULL) || (*header == '\0'))
848 * No complete header read yet, tell the client.
853 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
856 * Header spans multiple lines, append the next one.
858 char *continued_header;
860 continued_header = get_header_line(iob);
861 if ((continued_header == NULL) || (*continued_header == '\0'))
864 * No complete header read yet, return what we got.
865 * XXX: Should "unread" header instead.
867 log_error(LOG_LEVEL_INFO,
868 "Failed to read a multi-line header properly: '%s'",
873 if (JB_ERR_OK != string_join(&header, continued_header))
875 log_error(LOG_LEVEL_FATAL,
876 "Out of memory while appending multiple headers.");
880 /* XXX: remove before next stable release. */
881 log_error(LOG_LEVEL_HEADER,
882 "Merged multiple header lines to: '%s'",
887 normalize_lws(header);
894 /*********************************************************************
896 * Function : get_header_line
898 * Description : This (odd) routine will parse the csp->iob
899 * to get the next header line.
902 * 1 : iob = The I/O buffer to parse, usually csp->iob.
904 * Returns : Any one of the following:
906 * 1) a pointer to a dynamically allocated string that contains a header line
907 * 2) NULL indicating that the end of the header was reached
908 * 3) "" indicating that the end of the iob was reached before finding
909 * a complete header line.
911 *********************************************************************/
912 static char *get_header_line(struct iob *iob)
916 if ((iob->cur == NULL)
917 || ((p = strchr(iob->cur, '\n')) == NULL))
919 return(""); /* couldn't find a complete header */
924 ret = strdup(iob->cur);
927 /* FIXME No way to handle error properly */
928 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
934 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
936 /* is this a blank line (i.e. the end of the header) ? */
948 /*********************************************************************
950 * Function : get_header_value
952 * Description : Get the value of a given header from a chained list
953 * of header lines or return NULL if no such header is
954 * present in the list.
957 * 1 : header_list = pointer to list
958 * 2 : header_name = string with name of header to look for.
959 * Trailing colon required, capitalization
962 * Returns : NULL if not found, else value of header
964 *********************************************************************/
965 char *get_header_value(const struct list *header_list, const char *header_name)
967 struct list_entry *cur_entry;
973 length = strlen(header_name);
975 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
979 if (!strncmpic(cur_entry->str, header_name, length))
982 * Found: return pointer to start of value
984 ret = cur_entry->str + length;
985 while (*ret && privoxy_isspace(*ret)) ret++;
999 /*********************************************************************
1001 * Function : scan_headers
1003 * Description : Scans headers, applies tags and updates action bits.
1006 * 1 : csp = Current client state (buffers, headers, etc...)
1008 * Returns : JB_ERR_OK
1010 *********************************************************************/
1011 static jb_err scan_headers(struct client_state *csp)
1013 struct list_entry *h; /* Header */
1014 jb_err err = JB_ERR_OK;
1016 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1018 /* Header crunch()ed in previous run? -> ignore */
1019 if (h->str == NULL) continue;
1020 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1021 err = header_tagger(csp, h->str);
1028 /*********************************************************************
1030 * Function : enforce_header_order
1032 * Description : Enforces a given header order.
1035 * 1 : headers = List of headers to order.
1036 * 2 : ordered_headers = List of ordered header names.
1040 *********************************************************************/
1041 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1043 struct list_entry *sorted_header;
1044 struct list new_headers[1];
1045 struct list_entry *header;
1047 init_list(new_headers);
1049 /* The request line is always the first "header" */
1051 assert(NULL != headers->first->str);
1052 enlist(new_headers, headers->first->str);
1053 freez(headers->first->str)
1055 /* Enlist the specified headers in the given order */
1057 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1058 sorted_header = sorted_header->next)
1060 const size_t sorted_header_length = strlen(sorted_header->str);
1061 for (header = headers->first; header != NULL; header = header->next)
1063 /* Header enlisted in previous run? -> ignore */
1064 if (header->str == NULL) continue;
1066 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1067 && (header->str[sorted_header_length] == ':'))
1069 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1070 if (JB_ERR_OK != enlist(new_headers, header->str))
1072 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1079 /* Enlist the rest of the headers behind the ordered ones */
1080 for (header = headers->first; header != NULL; header = header->next)
1082 /* Header enlisted in previous run? -> ignore */
1083 if (header->str == NULL) continue;
1085 log_error(LOG_LEVEL_HEADER,
1086 "Enlisting left-over header %s", header->str);
1087 if (JB_ERR_OK != enlist(new_headers, header->str))
1089 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1094 list_remove_all(headers);
1095 list_duplicate(headers, new_headers);
1096 list_remove_all(new_headers);
1101 /*********************************************************************
1105 * Description : add, delete or modify lines in the HTTP header streams.
1106 * On entry, it receives a linked list of headers space
1107 * that was allocated dynamically (both the list nodes
1108 * and the header contents).
1110 * As a side effect it frees the space used by the original
1114 * 1 : csp = Current client state (buffers, headers, etc...)
1115 * 2 : filter_server_headers = Boolean to switch between
1116 * server and header filtering.
1118 * Returns : JB_ERR_OK in case off success, or
1119 * JB_ERR_MEMORY on out-of-memory error.
1121 *********************************************************************/
1122 jb_err sed(struct client_state *csp, int filter_server_headers)
1124 /* XXX: use more descriptive names. */
1125 struct list_entry *p;
1126 const struct parsers *v;
1127 const add_header_func_ptr *f;
1128 jb_err err = JB_ERR_OK;
1130 if (filter_server_headers)
1132 v = server_patterns;
1133 f = add_server_headers;
1137 v = client_patterns;
1138 f = add_client_headers;
1143 while ((err == JB_ERR_OK) && (v->str != NULL))
1145 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1147 /* Header crunch()ed in previous run? -> ignore */
1148 if (p->str == NULL) continue;
1150 /* Does the current parser handle this header? */
1151 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1152 (v->len == CHECK_EVERY_HEADER_REMAINING))
1154 err = v->parser(csp, &(p->str));
1160 /* place additional headers on the csp->headers list */
1161 while ((err == JB_ERR_OK) && (*f))
1167 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1169 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1176 /*********************************************************************
1178 * Function : update_server_headers
1180 * Description : Updates server headers after the body has been modified.
1183 * 1 : csp = Current client state (buffers, headers, etc...)
1185 * Returns : JB_ERR_OK in case off success, or
1186 * JB_ERR_MEMORY on out-of-memory error.
1188 *********************************************************************/
1189 jb_err update_server_headers(struct client_state *csp)
1191 jb_err err = JB_ERR_OK;
1193 static const struct parsers server_patterns_light[] = {
1194 { "Content-Length:", 15, server_adjust_content_length },
1195 { "Transfer-Encoding:", 18, server_transfer_coding },
1197 { "Content-Encoding:", 17, server_adjust_content_encoding },
1198 #endif /* def FEATURE_ZLIB */
1202 if (strncmpic(csp->http->cmd, "HEAD", 4))
1204 const struct parsers *v;
1205 struct list_entry *p;
1207 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1209 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1211 /* Header crunch()ed in previous run? -> ignore */
1212 if (p->str == NULL) continue;
1214 /* Does the current parser handle this header? */
1215 if (strncmpic(p->str, v->str, v->len) == 0)
1217 err = v->parser(csp, (char **)&(p->str));
1223 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1224 if ((JB_ERR_OK == err)
1225 && (csp->flags & CSP_FLAG_MODIFIED)
1226 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1227 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1231 create_content_length_header(csp->content_length, header, sizeof(header));
1232 err = enlist(csp->headers, header);
1233 if (JB_ERR_OK == err)
1235 log_error(LOG_LEVEL_HEADER,
1236 "Content modified with no Content-Length header set. "
1237 "Created: %s.", header);
1240 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1242 #ifdef FEATURE_COMPRESSION
1243 if ((JB_ERR_OK == err)
1244 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1246 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1247 if (JB_ERR_OK == err)
1249 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1258 /*********************************************************************
1260 * Function : header_tagger
1262 * Description : Executes all text substitutions from applying
1263 * tag actions and saves the result as tag.
1265 * XXX: Shares enough code with filter_header() and
1266 * pcrs_filter_response() to warrant some helper functions.
1269 * 1 : csp = Current client state (buffers, headers, etc...)
1270 * 2 : header = Header that is used as tagger input
1272 * Returns : JB_ERR_OK on success and always succeeds
1274 *********************************************************************/
1275 static jb_err header_tagger(struct client_state *csp, char *header)
1277 int wanted_filter_type;
1278 int multi_action_index;
1282 struct file_list *fl;
1283 struct re_filterfile_spec *b;
1284 struct list_entry *tag_name;
1286 const size_t header_length = strlen(header);
1288 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1290 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1291 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1295 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1296 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1299 if (filters_available(csp) == FALSE)
1301 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1302 "tagging enabled, but no taggers available.");
1306 for (i = 0; i < MAX_AF_FILES; i++)
1309 if ((NULL == fl) || (NULL == fl->f))
1312 * Either there are no filter files
1313 * left, or this filter file just
1314 * contains no valid filters.
1316 * Continue to be sure we don't miss
1317 * valid filter files that are chained
1318 * after empty or invalid ones.
1323 /* For all filters, */
1324 for (b = fl->f; b; b = b->next)
1326 if (b->type != wanted_filter_type)
1328 /* skip the ones we don't care about, */
1331 /* leaving only taggers that could apply, of which we use the ones, */
1332 for (tag_name = csp->action->multi[multi_action_index]->first;
1333 NULL != tag_name; tag_name = tag_name->next)
1335 /* that do apply, and */
1336 if (strcmp(b->name, tag_name->str) == 0)
1338 char *modified_tag = NULL;
1340 size_t size = header_length;
1341 pcrs_job *joblist = b->joblist;
1343 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1345 if (NULL == joblist)
1347 log_error(LOG_LEVEL_RE_FILTER,
1348 "Tagger %s has empty joblist. Nothing to do.", b->name);
1352 /* execute their pcrs_joblist on the header. */
1353 for (job = joblist; NULL != job; job = job->next)
1355 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1359 /* Success, continue with the modified version. */
1368 /* Tagger doesn't match */
1371 /* Regex failure, log it but continue anyway. */
1372 assert(NULL != header);
1373 log_error(LOG_LEVEL_ERROR,
1374 "Problems with tagger \'%s\' and header \'%s\': %s",
1375 b->name, *header, pcrs_strerror(hits));
1377 freez(modified_tag);
1381 if (b->dynamic) pcrs_free_joblist(joblist);
1383 /* If this tagger matched */
1389 * There is to technical limitation which makes
1390 * it impossible to use empty tags, but I assume
1391 * no one would do it intentionally.
1394 log_error(LOG_LEVEL_INFO,
1395 "Tagger \'%s\' created an empty tag. Ignored.",
1400 if (!list_contains_item(csp->tags, tag))
1402 if (JB_ERR_OK != enlist(csp->tags, tag))
1404 log_error(LOG_LEVEL_ERROR,
1405 "Insufficient memory to add tag \'%s\', "
1406 "based on tagger \'%s\' and header \'%s\'",
1407 tag, b->name, *header);
1411 char *action_message;
1413 * update the action bits right away, to make
1414 * tagging based on tags set by earlier taggers
1415 * of the same kind possible.
1417 if (update_action_bits_for_tag(csp, tag))
1419 action_message = "Action bits updated accordingly.";
1423 action_message = "No action bits update necessary.";
1426 log_error(LOG_LEVEL_HEADER,
1427 "Tagger \'%s\' added tag \'%s\'. %s",
1428 b->name, tag, action_message);
1433 /* XXX: Is this log-worthy? */
1434 log_error(LOG_LEVEL_HEADER,
1435 "Tagger \'%s\' didn't add tag \'%s\'. "
1436 "Tag already present", b->name, tag);
1439 } /* if the tagger matched */
1440 } /* if the tagger applies */
1441 } /* for every tagger that could apply */
1442 } /* for all filters */
1443 } /* for all filter files */
1448 /* here begins the family of parser functions that reformat header lines */
1450 /*********************************************************************
1452 * Function : filter_header
1454 * Description : Executes all text substitutions from all applying
1455 * +(server|client)-header-filter actions on the header.
1456 * Most of the code was copied from pcrs_filter_response,
1457 * including the rather short variable names
1460 * 1 : csp = Current client state (buffers, headers, etc...)
1461 * 2 : header = On input, pointer to header to modify.
1462 * On output, pointer to the modified header, or NULL
1463 * to remove the header. This function frees the
1464 * original string if necessary.
1466 * Returns : JB_ERR_OK on success and always succeeds
1468 *********************************************************************/
1469 static jb_err filter_header(struct client_state *csp, char **header)
1473 size_t size = strlen(*header);
1475 char *newheader = NULL;
1478 struct file_list *fl;
1479 struct re_filterfile_spec *b;
1480 struct list_entry *filtername;
1483 int wanted_filter_type;
1484 int multi_action_index;
1486 if (csp->flags & CSP_FLAG_NO_FILTERING)
1491 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1493 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1494 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1498 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1499 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1502 if (filters_available(csp) == FALSE)
1504 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1505 "header filtering enabled, but no matching filters available.");
1509 for (i = 0; i < MAX_AF_FILES; i++)
1512 if ((NULL == fl) || (NULL == fl->f))
1515 * Either there are no filter files
1516 * left, or this filter file just
1517 * contains no valid filters.
1519 * Continue to be sure we don't miss
1520 * valid filter files that are chained
1521 * after empty or invalid ones.
1526 * For all applying +filter actions, look if a filter by that
1527 * name exists and if yes, execute its pcrs_joblist on the
1530 for (b = fl->f; b; b = b->next)
1532 if (b->type != wanted_filter_type)
1534 /* Skip other filter types */
1538 for (filtername = csp->action->multi[multi_action_index]->first;
1539 filtername ; filtername = filtername->next)
1541 if (strcmp(b->name, filtername->str) == 0)
1543 int current_hits = 0;
1544 pcrs_job *joblist = b->joblist;
1546 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1548 if (NULL == joblist)
1550 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1554 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1555 *header, size, b->name);
1557 /* Apply all jobs from the joblist */
1558 for (job = joblist; NULL != job; job = job->next)
1560 matches = pcrs_execute(job, *header, size, &newheader, &size);
1563 current_hits += matches;
1564 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1566 *header = newheader;
1568 else if (0 == matches)
1570 /* Filter doesn't change header */
1576 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1577 *header, b->name, pcrs_strerror(matches));
1578 if (newheader != NULL)
1580 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1586 if (b->dynamic) pcrs_free_joblist(joblist);
1588 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1589 hits += current_hits;
1596 * Additionally checking for hits is important because if
1597 * the continue hack is triggered, server headers can
1598 * arrive empty to separate multiple heads from each other.
1600 if ((0 == size) && hits)
1602 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1610 /*********************************************************************
1612 * Function : server_connection
1614 * Description : Makes sure a proper "Connection:" header is
1615 * set and signals connection_header_adder to
1619 * 1 : csp = Current client state (buffers, headers, etc...)
1620 * 2 : header = On input, pointer to header to modify.
1621 * On output, pointer to the modified header, or NULL
1622 * to remove the header. This function frees the
1623 * original string if necessary.
1625 * Returns : JB_ERR_OK on success.
1627 *********************************************************************/
1628 static jb_err server_connection(struct client_state *csp, char **header)
1630 if (!strcmpic(*header, "Connection: keep-alive")
1631 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1632 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1636 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1637 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1639 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1642 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1644 log_error(LOG_LEVEL_HEADER,
1645 "Keeping the server header '%s' around.", *header);
1648 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1650 char *old_header = *header;
1652 *header = strdup_or_die("Connection: close");
1653 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1658 /* Signal server_connection_adder() to return early. */
1659 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1665 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1666 /*********************************************************************
1668 * Function : server_keep_alive
1670 * Description : Stores the server's keep alive timeout.
1673 * 1 : csp = Current client state (buffers, headers, etc...)
1674 * 2 : header = On input, pointer to header to modify.
1675 * On output, pointer to the modified header, or NULL
1676 * to remove the header. This function frees the
1677 * original string if necessary.
1679 * Returns : JB_ERR_OK.
1681 *********************************************************************/
1682 static jb_err server_keep_alive(struct client_state *csp, char **header)
1684 unsigned int keep_alive_timeout;
1685 const char *timeout_position = strstr(*header, "timeout=");
1687 if ((NULL == timeout_position)
1688 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1690 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1694 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1696 log_error(LOG_LEVEL_HEADER,
1697 "Reducing keep-alive timeout from %u to %u.",
1698 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1699 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1703 /* XXX: Is this log worthy? */
1704 log_error(LOG_LEVEL_HEADER,
1705 "Server keep-alive timeout is %u. Sticking with %u.",
1706 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1708 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1715 /*********************************************************************
1717 * Function : server_proxy_connection
1719 * Description : Figures out whether or not we should add a
1720 * Proxy-Connection header.
1723 * 1 : csp = Current client state (buffers, headers, etc...)
1724 * 2 : header = On input, pointer to header to modify.
1725 * On output, pointer to the modified header, or NULL
1726 * to remove the header. This function frees the
1727 * original string if necessary.
1729 * Returns : JB_ERR_OK.
1731 *********************************************************************/
1732 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1734 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1739 /*********************************************************************
1741 * Function : client_keep_alive
1743 * Description : Stores the client's keep alive timeout.
1746 * 1 : csp = Current client state (buffers, headers, etc...)
1747 * 2 : header = On input, pointer to header to modify.
1748 * On output, pointer to the modified header, or NULL
1749 * to remove the header. This function frees the
1750 * original string if necessary.
1752 * Returns : JB_ERR_OK.
1754 *********************************************************************/
1755 static jb_err client_keep_alive(struct client_state *csp, char **header)
1757 unsigned int keep_alive_timeout;
1758 const char *timeout_position = strstr(*header, ": ");
1760 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1762 log_error(LOG_LEVEL_HEADER,
1763 "keep-alive support is disabled. Crunching: %s.", *header);
1768 if ((NULL == timeout_position)
1769 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1771 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1775 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1777 log_error(LOG_LEVEL_HEADER,
1778 "Reducing keep-alive timeout from %u to %u.",
1779 csp->config->keep_alive_timeout, keep_alive_timeout);
1780 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1784 /* XXX: Is this log worthy? */
1785 log_error(LOG_LEVEL_HEADER,
1786 "Client keep-alive timeout is %u. Sticking with %u.",
1787 keep_alive_timeout, csp->config->keep_alive_timeout);
1795 /*********************************************************************
1797 * Function : get_content_length
1799 * Description : Gets the content length specified in a
1800 * Content-Length header.
1803 * 1 : header_value = The Content-Length header value.
1804 * 2 : length = Storage to return the value.
1806 * Returns : JB_ERR_OK on success, or
1807 * JB_ERR_PARSE if no value is recognized.
1809 *********************************************************************/
1810 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1813 assert(sizeof(unsigned long long) > 4);
1814 if (1 != sscanf(header_value, "%I64u", length))
1816 if (1 != sscanf(header_value, "%llu", length))
1819 return JB_ERR_PARSE;
1826 /*********************************************************************
1828 * Function : client_save_content_length
1830 * Description : Save the Content-Length sent by the client.
1833 * 1 : csp = Current client state (buffers, headers, etc...)
1834 * 2 : header = On input, pointer to header to modify.
1835 * On output, pointer to the modified header, or NULL
1836 * to remove the header. This function frees the
1837 * original string if necessary.
1839 * Returns : JB_ERR_OK on success, or
1840 * JB_ERR_MEMORY on out-of-memory error.
1842 *********************************************************************/
1843 static jb_err client_save_content_length(struct client_state *csp, char **header)
1845 unsigned long long content_length = 0;
1846 const char *header_value;
1848 assert(*(*header+14) == ':');
1850 header_value = *header + 15;
1851 if (JB_ERR_OK != get_content_length(header_value, &content_length))
1853 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1858 csp->expected_client_content_length = content_length;
1863 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1867 /*********************************************************************
1869 * Function : client_connection
1871 * Description : Makes sure a proper "Connection:" header is
1872 * set and signals connection_header_adder
1876 * 1 : csp = Current client state (buffers, headers, etc...)
1877 * 2 : header = On input, pointer to header to modify.
1878 * On output, pointer to the modified header, or NULL
1879 * to remove the header. This function frees the
1880 * original string if necessary.
1882 * Returns : JB_ERR_OK on success.
1884 *********************************************************************/
1885 static jb_err client_connection(struct client_state *csp, char **header)
1887 static const char connection_close[] = "Connection: close";
1889 if (!strcmpic(*header, connection_close))
1891 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1892 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1894 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1896 log_error(LOG_LEVEL_HEADER,
1897 "Removing \'%s\' to imply keep-alive.", *header);
1900 * While we imply keep-alive to the server,
1901 * we have to remember that the client didn't.
1903 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1907 char *old_header = *header;
1909 *header = strdup_or_die("Connection: keep-alive");
1910 log_error(LOG_LEVEL_HEADER,
1911 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1917 log_error(LOG_LEVEL_HEADER,
1918 "Keeping the client header '%s' around. "
1919 "The connection will not be kept alive.",
1921 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1924 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1926 log_error(LOG_LEVEL_HEADER,
1927 "Keeping the client header '%s' around. "
1928 "The server connection will be kept alive if possible.",
1930 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1931 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1935 char *old_header = *header;
1937 *header = strdup_or_die(connection_close);
1938 log_error(LOG_LEVEL_HEADER,
1939 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1943 /* Signal client_connection_adder() to return early. */
1944 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1950 /*********************************************************************
1952 * Function : crumble
1954 * Description : This is called if a header matches a pattern to "crunch"
1957 * 1 : csp = Current client state (buffers, headers, etc...)
1958 * 2 : header = On input, pointer to header to modify.
1959 * On output, pointer to the modified header, or NULL
1960 * to remove the header. This function frees the
1961 * original string if necessary.
1963 * Returns : JB_ERR_OK on success, or
1964 * JB_ERR_MEMORY on out-of-memory error.
1966 *********************************************************************/
1967 static jb_err crumble(struct client_state *csp, char **header)
1970 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1976 /*********************************************************************
1978 * Function : crunch_server_header
1980 * Description : Crunch server header if it matches a string supplied by the
1981 * user. Called from `sed'.
1984 * 1 : csp = Current client state (buffers, headers, etc...)
1985 * 2 : header = On input, pointer to header to modify.
1986 * On output, pointer to the modified header, or NULL
1987 * to remove the header. This function frees the
1988 * original string if necessary.
1990 * Returns : JB_ERR_OK on success and always succeeds
1992 *********************************************************************/
1993 static jb_err crunch_server_header(struct client_state *csp, char **header)
1995 const char *crunch_pattern;
1997 /* Do we feel like crunching? */
1998 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2000 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2002 /* Is the current header the lucky one? */
2003 if (strstr(*header, crunch_pattern))
2005 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2014 /*********************************************************************
2016 * Function : server_content_type
2018 * Description : Set the content-type for filterable types (text/.*,
2019 * .*xml.*, .*script.* and image/gif) unless filtering has been
2020 * forbidden (CT_TABOO) while parsing earlier headers.
2021 * NOTE: Since text/plain is commonly used by web servers
2022 * for files whose correct type is unknown, we don't
2023 * set CT_TEXT for it.
2026 * 1 : csp = Current client state (buffers, headers, etc...)
2027 * 2 : header = On input, pointer to header to modify.
2028 * On output, pointer to the modified header, or NULL
2029 * to remove the header. This function frees the
2030 * original string if necessary.
2032 * Returns : JB_ERR_OK on success, or
2033 * JB_ERR_MEMORY on out-of-memory error.
2035 *********************************************************************/
2036 static jb_err server_content_type(struct client_state *csp, char **header)
2038 /* Remove header if it isn't the first Content-Type header */
2039 if ((csp->content_type & CT_DECLARED))
2042 * Another, slightly slower, way to see if
2043 * we already parsed another Content-Type header.
2045 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2047 log_error(LOG_LEVEL_ERROR,
2048 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2056 * Signal that the Content-Type has been set.
2058 csp->content_type |= CT_DECLARED;
2060 if (!(csp->content_type & CT_TABOO))
2063 * XXX: The assumption that text/plain is a sign of
2064 * binary data seems to be somewhat unreasonable nowadays
2065 * and should be dropped after 3.0.8 is out.
2067 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2068 || strstr(*header, "xml")
2069 || strstr(*header, "script"))
2071 csp->content_type |= CT_TEXT;
2073 else if (strstr(*header, "image/gif"))
2075 csp->content_type |= CT_GIF;
2080 * Are we messing with the content type?
2082 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2085 * Make sure the user doesn't accidentally
2086 * change the content type of binary documents.
2088 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2091 *header = strdup_or_die("Content-Type: ");
2092 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2096 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2097 return JB_ERR_MEMORY;
2099 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2103 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2104 "It doesn't look like a content type that should be filtered. "
2105 "Enable force-text-mode if you know what you're doing.", *header);
2113 /*********************************************************************
2115 * Function : server_transfer_coding
2117 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2118 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2119 * - Remove header if body was chunked but has been
2120 * de-chunked for filtering.
2123 * 1 : csp = Current client state (buffers, headers, etc...)
2124 * 2 : header = On input, pointer to header to modify.
2125 * On output, pointer to the modified header, or NULL
2126 * to remove the header. This function frees the
2127 * original string if necessary.
2129 * Returns : JB_ERR_OK on success, or
2130 * JB_ERR_MEMORY on out-of-memory error.
2132 *********************************************************************/
2133 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2136 * Turn off pcrs and gif filtering if body compressed
2138 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2142 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2144 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2145 csp->http->cmd, *header);
2146 #endif /* def FEATURE_ZLIB */
2147 csp->content_type = CT_TABOO;
2151 * Raise flag if body chunked
2153 if (strstr(*header, "chunked"))
2155 csp->flags |= CSP_FLAG_CHUNKED;
2158 * If the body was modified, it has been de-chunked first
2159 * and the header must be removed.
2161 * FIXME: If there is more than one transfer encoding,
2162 * only the "chunked" part should be removed here.
2164 if (csp->flags & CSP_FLAG_MODIFIED)
2166 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2175 /*********************************************************************
2177 * Function : server_content_encoding
2179 * Description : Used to check if the content is compressed, and if
2180 * FEATURE_ZLIB is disabled, filtering is disabled as
2183 * If FEATURE_ZLIB is enabled and the compression type
2184 * supported, the content is marked for decompression.
2186 * XXX: Doesn't properly deal with multiple or with
2187 * unsupported but unknown encodings.
2188 * Is case-sensitive but shouldn't be.
2191 * 1 : csp = Current client state (buffers, headers, etc...)
2192 * 2 : header = On input, pointer to header to modify.
2193 * On output, pointer to the modified header, or NULL
2194 * to remove the header. This function frees the
2195 * original string if necessary.
2197 * Returns : JB_ERR_OK on success, or
2198 * JB_ERR_MEMORY on out-of-memory error.
2200 *********************************************************************/
2201 static jb_err server_content_encoding(struct client_state *csp, char **header)
2204 if (strstr(*header, "sdch"))
2207 * Shared Dictionary Compression over HTTP isn't supported,
2208 * filtering it anyway is pretty much guaranteed to mess up
2211 csp->content_type |= CT_TABOO;
2214 * Log a warning if the user expects the content to be filtered.
2216 if ((csp->rlist != NULL) &&
2217 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2219 log_error(LOG_LEVEL_INFO,
2220 "SDCH-compressed content detected, content filtering disabled. "
2221 "Consider suppressing SDCH offers made by the client.");
2224 else if (strstr(*header, "gzip"))
2226 /* Mark for gzip decompression */
2227 csp->content_type |= CT_GZIP;
2229 else if (strstr(*header, "deflate"))
2231 /* Mark for zlib decompression */
2232 csp->content_type |= CT_DEFLATE;
2234 else if (strstr(*header, "compress"))
2237 * We can't decompress this; therefore we can't filter
2240 csp->content_type |= CT_TABOO;
2242 #else /* !defined(FEATURE_ZLIB) */
2244 * XXX: Using a black list here isn't the right approach.
2246 * In case of SDCH, building with zlib support isn't
2249 if (strstr(*header, "gzip") ||
2250 strstr(*header, "compress") ||
2251 strstr(*header, "deflate") ||
2252 strstr(*header, "sdch"))
2255 * Body is compressed, turn off pcrs and gif filtering.
2257 csp->content_type |= CT_TABOO;
2260 * Log a warning if the user expects the content to be filtered.
2262 if ((csp->rlist != NULL) &&
2263 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2265 log_error(LOG_LEVEL_INFO,
2266 "Compressed content detected, content filtering disabled. "
2267 "Consider recompiling Privoxy with zlib support or "
2268 "enable the prevent-compression action.");
2271 #endif /* defined(FEATURE_ZLIB) */
2279 /*********************************************************************
2281 * Function : server_adjust_content_encoding
2283 * Description : Remove the Content-Encoding header if the
2284 * decompression was successful and the content
2288 * 1 : csp = Current client state (buffers, headers, etc...)
2289 * 2 : header = On input, pointer to header to modify.
2290 * On output, pointer to the modified header, or NULL
2291 * to remove the header. This function frees the
2292 * original string if necessary.
2294 * Returns : JB_ERR_OK on success, or
2295 * JB_ERR_MEMORY on out-of-memory error.
2297 *********************************************************************/
2298 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2300 if ((csp->flags & CSP_FLAG_MODIFIED)
2301 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2304 * We successfully decompressed the content,
2305 * and have to clean the header now, so the
2306 * client no longer expects compressed data.
2308 * XXX: There is a difference between cleaning
2309 * and removing it completely.
2311 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2318 #endif /* defined(FEATURE_ZLIB) */
2321 /*********************************************************************
2323 * Function : server_adjust_content_length
2325 * Description : Adjust Content-Length header if we modified
2329 * 1 : csp = Current client state (buffers, headers, etc...)
2330 * 2 : header = On input, pointer to header to modify.
2331 * On output, pointer to the modified header, or NULL
2332 * to remove the header. This function frees the
2333 * original string if necessary.
2335 * Returns : JB_ERR_OK on success, or
2336 * JB_ERR_MEMORY on out-of-memory error.
2338 *********************************************************************/
2339 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2341 /* Regenerate header if the content was modified. */
2342 if (csp->flags & CSP_FLAG_MODIFIED)
2344 const size_t header_length = 50;
2346 *header = malloc(header_length);
2347 if (*header == NULL)
2349 return JB_ERR_MEMORY;
2351 create_content_length_header(csp->content_length, *header, header_length);
2352 log_error(LOG_LEVEL_HEADER,
2353 "Adjusted Content-Length to %llu", csp->content_length);
2360 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2361 /*********************************************************************
2363 * Function : server_save_content_length
2365 * Description : Save the Content-Length sent by the server.
2368 * 1 : csp = Current client state (buffers, headers, etc...)
2369 * 2 : header = On input, pointer to header to modify.
2370 * On output, pointer to the modified header, or NULL
2371 * to remove the header. This function frees the
2372 * original string if necessary.
2374 * Returns : JB_ERR_OK on success, or
2375 * JB_ERR_MEMORY on out-of-memory error.
2377 *********************************************************************/
2378 static jb_err server_save_content_length(struct client_state *csp, char **header)
2380 unsigned long long content_length = 0;
2381 const char *header_value;
2383 assert(*(*header+14) == ':');
2385 header_value = *header + 15;
2386 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2388 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2393 csp->expected_content_length = content_length;
2394 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2395 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2400 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2403 /*********************************************************************
2405 * Function : server_content_md5
2407 * Description : Crumble any Content-MD5 headers if the document was
2408 * modified. FIXME: Should we re-compute instead?
2411 * 1 : csp = Current client state (buffers, headers, etc...)
2412 * 2 : header = On input, pointer to header to modify.
2413 * On output, pointer to the modified header, or NULL
2414 * to remove the header. This function frees the
2415 * original string if necessary.
2417 * Returns : JB_ERR_OK on success, or
2418 * JB_ERR_MEMORY on out-of-memory error.
2420 *********************************************************************/
2421 static jb_err server_content_md5(struct client_state *csp, char **header)
2423 if (csp->flags & CSP_FLAG_MODIFIED)
2425 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2433 /*********************************************************************
2435 * Function : server_content_disposition
2437 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2438 * Called from `sed'.
2441 * 1 : csp = Current client state (buffers, headers, etc...)
2442 * 2 : header = On input, pointer to header to modify.
2443 * On output, pointer to the modified header, or NULL
2444 * to remove the header. This function frees the
2445 * original string if necessary.
2447 * Returns : JB_ERR_OK on success, or
2448 * JB_ERR_MEMORY on out-of-memory error.
2450 *********************************************************************/
2451 static jb_err server_content_disposition(struct client_state *csp, char **header)
2456 * Are we messing with the Content-Disposition header?
2458 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2464 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2466 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2469 * Blocking content-disposition header
2471 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2478 * Replacing Content-Disposition header
2481 *header = strdup("Content-Disposition: ");
2482 string_append(header, newval);
2484 if (*header != NULL)
2486 log_error(LOG_LEVEL_HEADER,
2487 "Content-Disposition header crunched and replaced with: %s", *header);
2490 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2494 /*********************************************************************
2496 * Function : server_last_modified
2498 * Description : Changes Last-Modified header to the actual date
2499 * to help hide-if-modified-since.
2500 * Called from `sed'.
2503 * 1 : csp = Current client state (buffers, headers, etc...)
2504 * 2 : header = On input, pointer to header to modify.
2505 * On output, pointer to the modified header, or NULL
2506 * to remove the header. This function frees the
2507 * original string if necessary.
2509 * Returns : JB_ERR_OK on success, or
2510 * JB_ERR_MEMORY on out-of-memory error.
2512 *********************************************************************/
2513 static jb_err server_last_modified(struct client_state *csp, char **header)
2516 time_t last_modified;
2520 * Are we messing with the Last-Modified header?
2522 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2528 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2530 if (0 == strcmpic(newval, "block"))
2533 * Blocking Last-Modified header. Useless but why not.
2535 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2539 else if (0 == strcmpic(newval, "reset-to-request-time"))
2542 * Setting Last-Modified Header to now.
2545 get_http_time(0, buf, sizeof(buf));
2547 *header = strdup("Last-Modified: ");
2548 string_append(header, buf);
2550 if (*header == NULL)
2552 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2556 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2559 else if (0 == strcmpic(newval, "randomize"))
2561 const char *header_time = *header + sizeof("Last-Modified:");
2563 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2565 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2567 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2573 struct tm *timeptr = NULL;
2575 #ifdef HAVE_GMTIME_R
2579 rtime = (long int)difftime(now, last_modified);
2582 long int days, hours, minutes, seconds;
2583 const int negative_delta = (rtime < 0);
2588 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2590 rtime = pick_from_range(rtime);
2595 last_modified += rtime;
2596 #ifdef HAVE_GMTIME_R
2597 timeptr = gmtime_r(&last_modified, &gmt);
2598 #elif defined(MUTEX_LOCKS_AVAILABLE)
2599 privoxy_mutex_lock(&gmtime_mutex);
2600 timeptr = gmtime(&last_modified);
2601 privoxy_mutex_unlock(&gmtime_mutex);
2603 timeptr = gmtime(&last_modified);
2605 if ((NULL == timeptr) || !strftime(newheader,
2606 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2608 log_error(LOG_LEVEL_ERROR,
2609 "Randomizing '%s' failed. Crunching the header without replacement.",
2616 *header = strdup("Last-Modified: ");
2617 string_append(header, newheader);
2619 if (*header == NULL)
2621 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2622 return JB_ERR_MEMORY;
2625 days = rtime / (3600 * 24);
2626 hours = rtime / 3600 % 24;
2627 minutes = rtime / 60 % 60;
2628 seconds = rtime % 60;
2630 log_error(LOG_LEVEL_HEADER,
2631 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2632 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2633 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2637 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2646 /*********************************************************************
2648 * Function : client_accept_encoding
2650 * Description : Rewrite the client's Accept-Encoding header so that
2651 * if doesn't allow compression, if the action applies.
2652 * Note: For HTTP/1.0 the absence of the header is enough.
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_encoding(struct client_state *csp, char **header)
2667 #ifdef FEATURE_COMPRESSION
2668 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2669 && strstr(*header, "deflate"))
2671 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2674 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2676 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2684 /*********************************************************************
2686 * Function : client_te
2688 * Description : Rewrite the client's TE header so that
2689 * if doesn't allow compression, if the action applies.
2692 * 1 : csp = Current client state (buffers, headers, etc...)
2693 * 2 : header = On input, pointer to header to modify.
2694 * On output, pointer to the modified header, or NULL
2695 * to remove the header. This function frees the
2696 * original string if necessary.
2698 * Returns : JB_ERR_OK on success, or
2699 * JB_ERR_MEMORY on out-of-memory error.
2701 *********************************************************************/
2702 static jb_err client_te(struct client_state *csp, char **header)
2704 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2707 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2714 /*********************************************************************
2716 * Function : client_referrer
2718 * Description : Handle the "referer" config setting properly.
2719 * Called from `sed'.
2722 * 1 : csp = Current client state (buffers, headers, etc...)
2723 * 2 : header = On input, pointer to header to modify.
2724 * On output, pointer to the modified header, or NULL
2725 * to remove the header. This function frees the
2726 * original string if necessary.
2728 * Returns : JB_ERR_OK on success, or
2729 * JB_ERR_MEMORY on out-of-memory error.
2731 *********************************************************************/
2732 static jb_err client_referrer(struct client_state *csp, char **header)
2734 const char *parameter;
2735 /* booleans for parameters we have to check multiple times */
2736 int parameter_conditional_block;
2737 int parameter_conditional_forge;
2739 #ifdef FEATURE_FORCE_LOAD
2741 * Since the referrer can include the prefix even
2742 * if the request itself is non-forced, we must
2743 * clean it unconditionally.
2745 * XXX: strclean is too broad
2747 strclean(*header, FORCE_PREFIX);
2748 #endif /* def FEATURE_FORCE_LOAD */
2750 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2752 /* Nothing left to do */
2756 parameter = csp->action->string[ACTION_STRING_REFERER];
2757 assert(parameter != NULL);
2758 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2759 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2761 if (!parameter_conditional_block && !parameter_conditional_forge)
2764 * As conditional-block and conditional-forge are the only
2765 * parameters that rely on the original referrer, we can
2766 * remove it now for all the others.
2771 if (0 == strcmpic(parameter, "block"))
2773 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2776 else if (parameter_conditional_block || parameter_conditional_forge)
2778 return handle_conditional_hide_referrer_parameter(header,
2779 csp->http->hostport, parameter_conditional_block);
2781 else if (0 == strcmpic(parameter, "forge"))
2783 return create_forged_referrer(header, csp->http->hostport);
2787 /* interpret parameter as user-supplied referer to fake */
2788 return create_fake_referrer(header, parameter);
2793 /*********************************************************************
2795 * Function : client_accept_language
2797 * Description : Handle the "Accept-Language" config setting properly.
2798 * 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_accept_language(struct client_state *csp, char **header)
2816 * Are we messing with the Accept-Language?
2818 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2820 /*I don't think so*/
2824 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2826 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2829 * Blocking Accept-Language header
2831 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2838 * Replacing Accept-Language header
2841 *header = strdup("Accept-Language: ");
2842 string_append(header, newval);
2844 if (*header == NULL)
2846 log_error(LOG_LEVEL_ERROR,
2847 "Insufficient memory. Accept-Language header crunched without replacement.");
2851 log_error(LOG_LEVEL_HEADER,
2852 "Accept-Language header crunched and replaced with: %s", *header);
2855 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2859 /*********************************************************************
2861 * Function : crunch_client_header
2863 * Description : Crunch client header if it matches a string supplied by the
2864 * user. Called from `sed'.
2867 * 1 : csp = Current client state (buffers, headers, etc...)
2868 * 2 : header = On input, pointer to header to modify.
2869 * On output, pointer to the modified header, or NULL
2870 * to remove the header. This function frees the
2871 * original string if necessary.
2873 * Returns : JB_ERR_OK on success and always succeeds
2875 *********************************************************************/
2876 static jb_err crunch_client_header(struct client_state *csp, char **header)
2878 const char *crunch_pattern;
2880 /* Do we feel like crunching? */
2881 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2883 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2885 /* Is the current header the lucky one? */
2886 if (strstr(*header, crunch_pattern))
2888 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2896 /*********************************************************************
2898 * Function : client_uagent
2900 * Description : Handle the "user-agent" config setting properly
2901 * and remember its original value to enable browser
2902 * bug workarounds. Called from `sed'.
2905 * 1 : csp = Current client state (buffers, headers, etc...)
2906 * 2 : header = On input, pointer to header to modify.
2907 * On output, pointer to the modified header, or NULL
2908 * to remove the header. This function frees the
2909 * original string if necessary.
2911 * Returns : JB_ERR_OK on success, or
2912 * JB_ERR_MEMORY on out-of-memory error.
2914 *********************************************************************/
2915 static jb_err client_uagent(struct client_state *csp, char **header)
2919 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2924 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2931 *header = strdup("User-Agent: ");
2932 string_append(header, newval);
2934 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2936 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2940 /*********************************************************************
2942 * Function : client_ua
2944 * Description : Handle "ua-" headers properly. Called from `sed'.
2947 * 1 : csp = Current client state (buffers, headers, etc...)
2948 * 2 : header = On input, pointer to header to modify.
2949 * On output, pointer to the modified header, or NULL
2950 * to remove the header. This function frees the
2951 * original string if necessary.
2953 * Returns : JB_ERR_OK on success, or
2954 * JB_ERR_MEMORY on out-of-memory error.
2956 *********************************************************************/
2957 static jb_err client_ua(struct client_state *csp, char **header)
2959 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2961 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2969 /*********************************************************************
2971 * Function : client_from
2973 * Description : Handle the "from" config setting properly.
2974 * Called from `sed'.
2977 * 1 : csp = Current client state (buffers, headers, etc...)
2978 * 2 : header = On input, pointer to header to modify.
2979 * On output, pointer to the modified header, or NULL
2980 * to remove the header. This function frees the
2981 * original string if necessary.
2983 * Returns : JB_ERR_OK on success, or
2984 * JB_ERR_MEMORY on out-of-memory error.
2986 *********************************************************************/
2987 static jb_err client_from(struct client_state *csp, char **header)
2991 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2998 newval = csp->action->string[ACTION_STRING_FROM];
3001 * Are we blocking the e-mail address?
3003 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3005 log_error(LOG_LEVEL_HEADER, "crunched From!");
3009 log_error(LOG_LEVEL_HEADER, " modified");
3011 *header = strdup("From: ");
3012 string_append(header, newval);
3014 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3018 /*********************************************************************
3020 * Function : client_send_cookie
3022 * Description : Crunches the "cookie" header if necessary.
3023 * Called from `sed'.
3025 * XXX: Stupid name, doesn't send squat.
3028 * 1 : csp = Current client state (buffers, headers, etc...)
3029 * 2 : header = On input, pointer to header to modify.
3030 * On output, pointer to the modified header, or NULL
3031 * to remove the header. This function frees the
3032 * original string if necessary.
3034 * Returns : JB_ERR_OK on success, or
3035 * JB_ERR_MEMORY on out-of-memory error.
3037 *********************************************************************/
3038 static jb_err client_send_cookie(struct client_state *csp, char **header)
3040 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3042 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3050 /*********************************************************************
3052 * Function : client_x_forwarded
3054 * Description : Handle the "x-forwarded-for" config setting properly,
3055 * also used in the add_client_headers list. Called from `sed'.
3058 * 1 : csp = Current client state (buffers, headers, etc...)
3059 * 2 : header = On input, pointer to header to modify.
3060 * On output, pointer to the modified header, or NULL
3061 * to remove the header. This function frees the
3062 * original string if necessary.
3064 * Returns : JB_ERR_OK on success, or
3065 * JB_ERR_MEMORY on out-of-memory error.
3067 *********************************************************************/
3068 jb_err client_x_forwarded(struct client_state *csp, char **header)
3070 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3072 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3074 if (0 == strcmpic(parameter, "block"))
3077 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3079 else if (0 == strcmpic(parameter, "add"))
3081 string_append(header, ", ");
3082 string_append(header, csp->ip_addr_str);
3084 if (*header == NULL)
3086 return JB_ERR_MEMORY;
3088 log_error(LOG_LEVEL_HEADER,
3089 "Appended client IP address to %s", *header);
3090 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3094 log_error(LOG_LEVEL_FATAL,
3095 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3103 /*********************************************************************
3105 * Function : client_max_forwards
3107 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3108 * from the value of the Max-Forwards header field.
3111 * 1 : csp = Current client state (buffers, headers, etc...)
3112 * 2 : header = On input, pointer to header to modify.
3113 * On output, pointer to the modified header, or NULL
3114 * to remove the header. This function frees the
3115 * original string if necessary.
3117 * Returns : JB_ERR_OK on success, or
3118 * JB_ERR_MEMORY on out-of-memory error.
3120 *********************************************************************/
3121 static jb_err client_max_forwards(struct client_state *csp, char **header)
3125 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3126 (0 == strcmpic(csp->http->gpc, "options")))
3128 assert(*(*header+12) == ':');
3129 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3131 if (max_forwards > 0)
3133 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3134 log_error(LOG_LEVEL_HEADER,
3135 "Max-Forwards value for %s request reduced to %d.",
3136 csp->http->gpc, max_forwards);
3138 else if (max_forwards < 0)
3140 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3146 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3155 /*********************************************************************
3157 * Function : client_host
3159 * Description : If the request URI did not contain host and
3160 * port information, parse and evaluate the Host
3163 * Also, kill ill-formed HOST: headers as sent by
3164 * Apple's iTunes software when used with a proxy.
3167 * 1 : csp = Current client state (buffers, headers, etc...)
3168 * 2 : header = On input, pointer to header to modify.
3169 * On output, pointer to the modified header, or NULL
3170 * to remove the header. This function frees the
3171 * original string if necessary.
3173 * Returns : JB_ERR_OK on success, or
3174 * JB_ERR_MEMORY on out-of-memory error.
3176 *********************************************************************/
3177 static jb_err client_host(struct client_state *csp, char **header)
3182 * If the header field name is all upper-case, chances are that it's
3183 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3184 * not a problem -- they are regenerated later.
3186 if ((*header)[1] == 'O')
3188 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3193 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3194 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3197 p = strdup_or_die((*header)+6);
3199 q = strdup_or_die(p);
3201 freez(csp->http->hostport);
3202 csp->http->hostport = p;
3203 freez(csp->http->host);
3204 csp->http->host = q;
3205 q = strchr(csp->http->host, ':');
3208 /* Terminate hostname and evaluate port string */
3210 csp->http->port = atoi(q);
3214 csp->http->port = csp->http->ssl ? 443 : 80;
3217 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3218 csp->http->hostport, csp->http->host, csp->http->port);
3221 /* Signal client_host_adder() to return right away */
3222 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3228 /*********************************************************************
3230 * Function : client_if_modified_since
3232 * Description : Remove or modify the If-Modified-Since header.
3235 * 1 : csp = Current client state (buffers, headers, etc...)
3236 * 2 : header = On input, pointer to header to modify.
3237 * On output, pointer to the modified header, or NULL
3238 * to remove the header. This function frees the
3239 * original string if necessary.
3241 * Returns : JB_ERR_OK on success, or
3242 * JB_ERR_MEMORY on out-of-memory error.
3244 *********************************************************************/
3245 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3248 #ifdef HAVE_GMTIME_R
3251 struct tm *timeptr = NULL;
3256 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3259 * The client got an error message because of a temporary problem,
3260 * the problem is gone and the client now tries to revalidate our
3261 * error message on the real server. The revalidation would always
3262 * end with the transmission of the whole document and there is
3263 * no need to expose the bogus If-Modified-Since header.
3265 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3268 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3270 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3272 if ((0 == strcmpic(newval, "block")))
3274 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3277 else /* add random value */
3279 const char *header_time = *header + sizeof("If-Modified-Since:");
3281 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3283 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3288 long int hours, minutes, seconds;
3289 long int rtime = strtol(newval, &endptr, 0);
3290 const int negative_range = (rtime < 0);
3294 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3295 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3301 rtime = pick_from_range(rtime);
3305 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3308 tm += rtime * (negative_range ? -1 : 1);
3309 #ifdef HAVE_GMTIME_R
3310 timeptr = gmtime_r(&tm, &gmt);
3311 #elif defined(MUTEX_LOCKS_AVAILABLE)
3312 privoxy_mutex_lock(&gmtime_mutex);
3313 timeptr = gmtime(&tm);
3314 privoxy_mutex_unlock(&gmtime_mutex);
3316 timeptr = gmtime(&tm);
3318 if ((NULL == timeptr) || !strftime(newheader,
3319 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3321 log_error(LOG_LEVEL_ERROR,
3322 "Randomizing '%s' failed. Crunching the header without replacement.",
3329 *header = strdup("If-Modified-Since: ");
3330 string_append(header, newheader);
3332 if (*header == NULL)
3334 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3335 return JB_ERR_MEMORY;
3338 hours = rtime / 3600;
3339 minutes = rtime / 60 % 60;
3340 seconds = rtime % 60;
3342 log_error(LOG_LEVEL_HEADER,
3343 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3344 *header, (negative_range) ? "subtracted" : "added", hours,
3345 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3346 seconds, (seconds == 1) ? ")" : "s)");
3355 /*********************************************************************
3357 * Function : client_if_none_match
3359 * Description : Remove the If-None-Match header.
3362 * 1 : csp = Current client state (buffers, headers, etc...)
3363 * 2 : header = On input, pointer to header to modify.
3364 * On output, pointer to the modified header, or NULL
3365 * to remove the header. This function frees the
3366 * original string if necessary.
3368 * Returns : JB_ERR_OK on success, or
3369 * JB_ERR_MEMORY on out-of-memory error.
3371 *********************************************************************/
3372 static jb_err client_if_none_match(struct client_state *csp, char **header)
3374 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3376 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3384 /*********************************************************************
3386 * Function : client_x_filter
3388 * Description : Disables filtering if the client set "X-Filter: No".
3389 * Called from `sed'.
3392 * 1 : csp = Current client state (buffers, headers, etc...)
3393 * 2 : header = On input, pointer to header to modify.
3394 * On output, pointer to the modified header, or NULL
3395 * to remove the header. This function frees the
3396 * original string if necessary.
3398 * Returns : JB_ERR_OK on success
3400 *********************************************************************/
3401 jb_err client_x_filter(struct client_state *csp, char **header)
3403 if (0 == strcmpic(*header, "X-Filter: No"))
3405 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3407 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3411 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3413 log_error(LOG_LEVEL_HEADER,
3414 "force-text-mode overruled the client's request to fetch without filtering!");
3418 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3419 csp->flags |= CSP_FLAG_NO_FILTERING;
3420 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3422 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3430 /*********************************************************************
3432 * Function : client_range
3434 * Description : Removes Range, Request-Range and If-Range headers if
3435 * content filtering is enabled and the range doesn't
3438 * If the client's version of the document has been
3439 * altered by Privoxy, the server could interpret the
3440 * range differently than the client intended in which
3441 * case the user could end up with corrupted content.
3443 * If the range starts at byte 0 this isn't an issue
3444 * so the header can pass. Partial requests like this
3445 * are used to render preview images for videos without
3446 * downloading the whole video.
3448 * While HTTP doesn't require that range requests are
3449 * honoured and the client could simply abort the download
3450 * after receiving a sufficient amount of data, various
3451 * clients don't handle complete responses to range
3452 * requests gracefully and emit misleading error messages
3456 * 1 : csp = Current client state (buffers, headers, etc...)
3457 * 2 : header = On input, pointer to header to modify.
3458 * On output, pointer to the modified header, or NULL
3459 * to remove the header. This function frees the
3460 * original string if necessary.
3462 * Returns : JB_ERR_OK
3464 *********************************************************************/
3465 static jb_err client_range(struct client_state *csp, char **header)
3467 if (content_filters_enabled(csp->action)
3468 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3470 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3471 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3478 /* the following functions add headers directly to the header list */
3480 /*********************************************************************
3482 * Function : client_host_adder
3484 * Description : Adds the Host: header field if it is missing.
3485 * Called from `sed'.
3488 * 1 : csp = Current client state (buffers, headers, etc...)
3490 * Returns : JB_ERR_OK on success, or
3491 * JB_ERR_MEMORY on out-of-memory error.
3493 *********************************************************************/
3494 static jb_err client_host_adder(struct client_state *csp)
3499 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3501 /* Header already set by the client, nothing to do. */
3505 if (!csp->http->hostport || !*(csp->http->hostport))
3507 /* XXX: When does this happen and why is it OK? */
3508 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3513 * remove 'user:pass@' from 'proto://user:pass@host'
3515 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3521 p = csp->http->hostport;
3524 /* XXX: Just add it, we already made sure that it will be unique */
3525 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3526 err = enlist_unique_header(csp->headers, "Host", p);
3532 /*********************************************************************
3534 * Function : client_xtra_adder
3536 * Description : Used in the add_client_headers list. Called from `sed'.
3539 * 1 : csp = Current client state (buffers, headers, etc...)
3541 * Returns : JB_ERR_OK on success, or
3542 * JB_ERR_MEMORY on out-of-memory error.
3544 *********************************************************************/
3545 static jb_err client_xtra_adder(struct client_state *csp)
3547 struct list_entry *lst;
3550 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3551 lst ; lst = lst->next)
3553 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3554 err = enlist(csp->headers, lst->str);
3566 /*********************************************************************
3568 * Function : client_x_forwarded_for_adder
3570 * Description : Used in the add_client_headers list. Called from `sed'.
3573 * 1 : csp = Current client state (buffers, headers, etc...)
3575 * Returns : JB_ERR_OK on success, or
3576 * JB_ERR_MEMORY on out-of-memory error.
3578 *********************************************************************/
3579 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3581 char *header = NULL;
3584 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3585 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3586 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3589 * If we aren't adding X-Forwarded-For headers,
3590 * or we already appended an existing X-Forwarded-For
3591 * header, there's nothing left to do here.
3596 header = strdup("X-Forwarded-For: ");
3597 string_append(&header, csp->ip_addr_str);
3601 return JB_ERR_MEMORY;
3604 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3605 err = enlist(csp->headers, header);
3612 /*********************************************************************
3614 * Function : server_connection_adder
3616 * Description : Adds an appropriate "Connection:" header to csp->headers
3617 * unless the header was already present. Called from `sed'.
3620 * 1 : csp = Current client state (buffers, headers, etc...)
3622 * Returns : JB_ERR_OK on success, or
3623 * JB_ERR_MEMORY on out-of-memory error.
3625 *********************************************************************/
3626 static jb_err server_connection_adder(struct client_state *csp)
3628 const unsigned int flags = csp->flags;
3629 const char *response_status_line = csp->headers->first->str;
3630 static const char connection_close[] = "Connection: close";
3632 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3633 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3639 * XXX: if we downgraded the response, this check will fail.
3641 if ((csp->config->feature_flags &
3642 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3643 && (NULL != response_status_line)
3644 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3645 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3646 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3650 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3651 "without Connection header implies keep-alive.");
3652 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3656 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3658 return enlist(csp->headers, connection_close);
3662 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3663 /*********************************************************************
3665 * Function : server_proxy_connection_adder
3667 * Description : Adds a "Proxy-Connection: keep-alive" header to
3668 * csp->headers if the client asked for keep-alive.
3669 * XXX: We should reuse existent ones.
3672 * 1 : csp = Current client state (buffers, headers, etc...)
3674 * Returns : JB_ERR_OK on success, or
3675 * JB_ERR_MEMORY on out-of-memory error.
3677 *********************************************************************/
3678 static jb_err server_proxy_connection_adder(struct client_state *csp)
3680 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3681 jb_err err = JB_ERR_OK;
3683 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3684 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3685 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET))
3687 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3688 err = enlist(csp->headers, proxy_connection_header);
3693 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3696 /*********************************************************************
3698 * Function : client_connection_header_adder
3700 * Description : Adds a proper "Connection:" header to csp->headers
3701 * unless the header was already present. Called from `sed'.
3704 * 1 : csp = Current client state (buffers, headers, etc...)
3706 * Returns : JB_ERR_OK on success, or
3707 * JB_ERR_MEMORY on out-of-memory error.
3709 *********************************************************************/
3710 static jb_err client_connection_header_adder(struct client_state *csp)
3712 static const char connection_close[] = "Connection: close";
3714 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3715 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3720 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3721 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3722 && (csp->http->ssl == 0)
3723 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3725 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3728 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3730 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3732 return enlist(csp->headers, connection_close);
3736 /*********************************************************************
3738 * Function : server_http
3740 * Description : - Save the HTTP Status into csp->http->status
3741 * - Set CT_TABOO to prevent filtering if the answer
3742 * is a partial range (HTTP status 206)
3743 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3747 * 1 : csp = Current client state (buffers, headers, etc...)
3748 * 2 : header = On input, pointer to header to modify.
3749 * On output, pointer to the modified header, or NULL
3750 * to remove the header. This function frees the
3751 * original string if necessary.
3753 * Returns : JB_ERR_OK on success, or
3754 * JB_ERR_MEMORY on out-of-memory error.
3756 *********************************************************************/
3757 static jb_err server_http(struct client_state *csp, char **header)
3759 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3760 if (csp->http->status == 206)
3762 csp->content_type = CT_TABOO;
3765 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3767 /* XXX: Should we do a real validity check here? */
3768 if (strlen(*header) > 8)
3771 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3776 * XXX: Should we block the request or
3777 * enlist a valid status code line here?
3779 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3780 "Downgrading to HTTP/1.0 impossible.");
3788 /*********************************************************************
3790 * Function : server_set_cookie
3792 * Description : Handle the server "cookie" header properly.
3793 * Crunch, accept or rewrite it to a session cookie.
3794 * Called from `sed'.
3796 * TODO: Allow the user to specify a new expiration
3797 * time to cause the cookie to expire even before the
3798 * browser is closed.
3801 * 1 : csp = Current client state (buffers, headers, etc...)
3802 * 2 : header = On input, pointer to header to modify.
3803 * On output, pointer to the modified header, or NULL
3804 * to remove the header. This function frees the
3805 * original string if necessary.
3807 * Returns : JB_ERR_OK on success, or
3808 * JB_ERR_MEMORY on out-of-memory error.
3810 *********************************************************************/
3811 static jb_err server_set_cookie(struct client_state *csp, char **header)
3818 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3820 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3823 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3825 /* Flag whether or not to log a message */
3828 /* A variable to store the tag we're working on */
3831 /* Skip "Set-Cookie:" (11 characters) in header */
3832 cur_tag = *header + 11;
3834 /* skip whitespace between "Set-Cookie:" and value */
3835 while (*cur_tag && privoxy_isspace(*cur_tag))
3840 /* Loop through each tag in the cookie */
3844 char *next_tag = strchr(cur_tag, ';');
3845 if (next_tag != NULL)
3847 /* Skip the ';' character itself */
3850 /* skip whitespace ";" and start of tag */
3851 while (*next_tag && privoxy_isspace(*next_tag))
3858 /* "Next tag" is the end of the string */
3859 next_tag = cur_tag + strlen(cur_tag);
3863 * Check the expiration date to see
3864 * if the cookie is still valid, if yes,
3865 * rewrite it to a session cookie.
3867 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3869 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3871 if ((expiration_date[0] == '"')
3872 && (expiration_date[1] != '\0'))
3875 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
3876 * that the expiration date isn't supposed to be quoted,
3877 * but some servers do it anyway.
3882 /* Did we detect the date properly? */
3883 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3886 * Nope, treat it as if it was still valid.
3888 * XXX: Should we remove the whole cookie instead?
3890 log_error(LOG_LEVEL_ERROR,
3891 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3892 string_move(cur_tag, next_tag);
3898 * Yes. Check if the cookie is still valid.
3900 * If the cookie is already expired it's probably
3901 * a delete cookie and even if it isn't, the browser
3902 * will discard it anyway.
3906 * XXX: timegm() isn't available on some AmigaOS
3907 * versions and our replacement doesn't work.
3909 * Our options are to either:
3911 * - disable session-cookies-only completely if timegm
3914 * - to simply remove all expired tags, like it has
3915 * been done until Privoxy 3.0.6 and to live with
3916 * the consequence that it can cause login/logout
3917 * problems on servers that don't validate their
3918 * input properly, or
3920 * - to replace it with mktime in which
3921 * case there is a slight chance of valid cookies
3922 * passing as already expired.
3924 * This is the way it's currently done and it's not
3925 * as bad as it sounds. If the missing GMT offset is
3926 * enough to change the result of the expiration check
3927 * the cookie will be only valid for a few hours
3928 * anyway, which in many cases will be shorter
3929 * than a browser session.
3931 if (cookie_time - now < 0)
3933 log_error(LOG_LEVEL_HEADER,
3934 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3935 /* Just in case some clown sets more then one expiration date */
3941 * Still valid, delete expiration date by copying
3942 * the rest of the string over it.
3944 string_move(cur_tag, next_tag);
3946 /* That changed the header, need to issue a log message */
3950 * Note that the next tag has now been moved to *cur_tag,
3951 * so we do not need to update the cur_tag pointer.
3959 /* Move on to next cookie tag */
3966 assert(NULL != *header);
3967 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3976 #ifdef FEATURE_FORCE_LOAD
3977 /*********************************************************************
3979 * Function : strclean
3981 * Description : In-Situ-Eliminate all occurrences of substring in
3985 * 1 : string = string to clean
3986 * 2 : substring = substring to eliminate
3988 * Returns : Number of eliminations
3990 *********************************************************************/
3991 int strclean(char *string, const char *substring)
3997 len = strlen(substring);
3999 while((pos = strstr(string, substring)) != NULL)
4006 while (*p++ != '\0');
4013 #endif /* def FEATURE_FORCE_LOAD */
4016 /*********************************************************************
4018 * Function : parse_header_time
4020 * Description : Parses time formats used in HTTP header strings
4021 * to get the numerical respresentation.
4024 * 1 : header_time = HTTP header time as string.
4025 * 2 : result = storage for header_time in seconds
4027 * Returns : JB_ERR_OK if the time format was recognized, or
4028 * JB_ERR_PARSE otherwise.
4030 *********************************************************************/
4031 static jb_err parse_header_time(const char *header_time, time_t *result)
4035 * Checking for two-digit years first in an
4036 * attempt to work around GNU libc's strptime()
4037 * reporting negative year values when using %Y.
4039 static const char * const time_formats[] = {
4040 /* Tue, 02-Jun-37 20:00:00 */
4041 "%a, %d-%b-%y %H:%M:%S",
4042 /* Tue, 02 Jun 2037 20:00:00 */
4043 "%a, %d %b %Y %H:%M:%S",
4044 /* Tue, 02-Jun-2037 20:00:00 */
4045 "%a, %d-%b-%Y %H:%M:%S",
4046 /* Tuesday, 02-Jun-2037 20:00:00 */
4047 "%A, %d-%b-%Y %H:%M:%S",
4048 /* Tuesday Jun 02 20:00:00 2037 */
4049 "%A %b %d %H:%M:%S %Y"
4053 for (i = 0; i < SZ(time_formats); i++)
4056 * Zero out gmt to prevent time zone offsets.
4057 * Documented to be required for GNU libc.
4059 memset(&gmt, 0, sizeof(gmt));
4061 if (NULL != strptime(header_time, time_formats[i], &gmt))
4063 /* Sanity check for GNU libc. */
4064 if (gmt.tm_year < 0)
4066 log_error(LOG_LEVEL_HEADER,
4067 "Failed to parse '%s' using '%s'. Moving on.",
4068 header_time, time_formats[i]);
4071 *result = timegm(&gmt);
4076 return JB_ERR_PARSE;
4081 /*********************************************************************
4083 * Function : get_destination_from_headers
4085 * Description : Parse the "Host:" header to get the request's destination.
4086 * Only needed if the client's request was forcefully
4087 * redirected into Privoxy.
4089 * Code mainly copied from client_host() which is currently
4090 * run too late for this purpose.
4093 * 1 : headers = List of headers (one of them hopefully being
4094 * the "Host:" header)
4095 * 2 : http = storage for the result (host, port and hostport).
4097 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4098 * JB_ERR_PARSE if the host header couldn't be found,
4099 * JB_ERR_OK otherwise.
4101 *********************************************************************/
4102 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4108 host = get_header_value(headers, "Host:");
4112 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4113 return JB_ERR_PARSE;
4116 p = strdup_or_die(host);
4118 q = strdup_or_die(p);
4120 freez(http->hostport);
4124 q = strchr(http->host, ':');
4127 /* Terminate hostname and evaluate port string */
4129 http->port = atoi(q);
4133 http->port = http->ssl ? 443 : 80;
4136 /* Rebuild request URL */
4138 http->url = strdup(http->ssl ? "https://" : "http://");
4139 string_append(&http->url, http->hostport);
4140 string_append(&http->url, http->path);
4141 if (http->url == NULL)
4143 return JB_ERR_MEMORY;
4146 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4154 /*********************************************************************
4156 * Function : create_forged_referrer
4158 * Description : Helper for client_referrer to forge a referer as
4159 * 'http://hostname[:port]/' to fool stupid
4160 * checks for in-site links
4163 * 1 : header = Pointer to header pointer
4164 * 2 : hostport = Host and optionally port as string
4166 * Returns : JB_ERR_OK in case of success, or
4167 * JB_ERR_MEMORY in case of memory problems.
4169 *********************************************************************/
4170 static jb_err create_forged_referrer(char **header, const char *hostport)
4172 assert(NULL == *header);
4174 *header = strdup("Referer: http://");
4175 string_append(header, hostport);
4176 string_append(header, "/");
4178 if (NULL == *header)
4180 return JB_ERR_MEMORY;
4183 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4190 /*********************************************************************
4192 * Function : create_fake_referrer
4194 * Description : Helper for client_referrer to create a fake referrer
4195 * based on a string supplied by the user.
4198 * 1 : header = Pointer to header pointer
4199 * 2 : hosthost = Referrer to fake
4201 * Returns : JB_ERR_OK in case of success, or
4202 * JB_ERR_MEMORY in case of memory problems.
4204 *********************************************************************/
4205 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4207 assert(NULL == *header);
4209 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4211 log_error(LOG_LEVEL_HEADER,
4212 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4214 *header = strdup("Referer: ");
4215 string_append(header, fake_referrer);
4217 if (NULL == *header)
4219 return JB_ERR_MEMORY;
4222 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4229 /*********************************************************************
4231 * Function : handle_conditional_hide_referrer_parameter
4233 * Description : Helper for client_referrer to crunch or forge
4234 * the referrer header if the host has changed.
4237 * 1 : header = Pointer to header pointer
4238 * 2 : host = The target host (may include the port)
4239 * 3 : parameter_conditional_block = Boolean to signal
4240 * if we're in conditional-block mode. If not set,
4241 * we're in conditional-forge mode.
4243 * Returns : JB_ERR_OK in case of success, or
4244 * JB_ERR_MEMORY in case of memory problems.
4246 *********************************************************************/
4247 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4248 const char *host, const int parameter_conditional_block)
4250 char *referer = strdup_or_die(*header);
4251 const size_t hostlength = strlen(host);
4252 const char *referer_url = NULL;
4254 /* referer begins with 'Referer: http[s]://' */
4255 if ((hostlength+17) < strlen(referer))
4258 * Shorten referer to make sure the referer is blocked
4259 * if www.example.org/www.example.com-shall-see-the-referer/
4260 * links to www.example.com/
4262 referer[hostlength+17] = '\0';
4264 referer_url = strstr(referer, "http://");
4265 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4267 /* Host has changed, Referer is invalid or a https URL. */
4268 if (parameter_conditional_block)
4270 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4277 return create_forged_referrer(header, host);
4287 /*********************************************************************
4289 * Function : create_content_length_header
4291 * Description : Creates a Content-Length header.
4294 * 1 : content_length = The content length to be used in the header.
4295 * 2 : header = Allocated space to safe the header.
4296 * 3 : buffer_length = The length of the allocated space.
4300 *********************************************************************/
4301 static void create_content_length_header(unsigned long long content_length,
4302 char *header, size_t buffer_length)
4304 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4308 /*********************************************************************
4310 * Function : get_expected_content_length
4312 * Description : Figures out the content length from a list of headers.
4315 * 1 : headers = List of headers
4317 * Returns : Number of bytes to expect
4319 *********************************************************************/
4320 unsigned long long get_expected_content_length(struct list *headers)
4322 const char *content_length_header;
4323 unsigned long long content_length = 0;
4325 content_length_header = get_header_value(headers, "Content-Length:");
4326 if (content_length_header != NULL)
4328 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4330 log_error(LOG_LEVEL_ERROR,
4331 "Failed to get the Content-Length in %s", content_length_header);
4332 /* XXX: The header will be removed later on */
4337 return content_length;