1 const char parsers_rcs[] = "$Id: parsers.c,v 1.266 2012/11/24 13:58:17 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 static jb_err client_proxy_connection(struct client_state *csp, char **header);
141 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
143 static jb_err client_host_adder (struct client_state *csp);
144 static jb_err client_xtra_adder (struct client_state *csp);
145 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
146 static jb_err client_connection_header_adder(struct client_state *csp);
147 static jb_err server_connection_adder(struct client_state *csp);
148 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
149 static jb_err server_proxy_connection_adder(struct client_state *csp);
150 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
152 static jb_err create_forged_referrer(char **header, const char *hostport);
153 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
154 static jb_err handle_conditional_hide_referrer_parameter(char **header,
155 const char *host, const int parameter_conditional_block);
156 static void create_content_length_header(unsigned long long content_length,
157 char *header, size_t buffer_length);
160 * List of functions to run on a list of headers.
164 /** The header prefix to match */
167 /** The length of the prefix to match */
170 /** The function to apply to this line */
171 const parser_func_ptr parser;
174 static const struct parsers client_patterns[] = {
175 { "referer:", 8, client_referrer },
176 { "user-agent:", 11, client_uagent },
177 { "ua-", 3, client_ua },
178 { "from:", 5, client_from },
179 { "cookie:", 7, client_send_cookie },
180 { "x-forwarded-for:", 16, client_x_forwarded },
181 { "Accept-Encoding:", 16, client_accept_encoding },
182 { "TE:", 3, client_te },
183 { "Host:", 5, client_host },
184 { "if-modified-since:", 18, client_if_modified_since },
185 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
186 { "Keep-Alive:", 11, client_keep_alive },
187 { "Content-Length:", 15, client_save_content_length },
188 { "Proxy-Connection:", 17, client_proxy_connection },
190 { "Keep-Alive:", 11, crumble },
191 { "Proxy-Connection:", 17, crumble },
193 { "connection:", 11, client_connection },
194 { "max-forwards:", 13, client_max_forwards },
195 { "Accept-Language:", 16, client_accept_language },
196 { "if-none-match:", 14, client_if_none_match },
197 { "Range:", 6, client_range },
198 { "Request-Range:", 14, client_range },
199 { "If-Range:", 9, client_range },
200 { "X-Filter:", 9, client_x_filter },
201 { "*", 0, crunch_client_header },
202 { "*", 0, filter_header },
206 static const struct parsers server_patterns[] = {
207 { "HTTP/", 5, server_http },
208 { "set-cookie:", 11, server_set_cookie },
209 { "connection:", 11, server_connection },
210 { "Content-Type:", 13, server_content_type },
211 { "Content-MD5:", 12, server_content_md5 },
212 { "Content-Encoding:", 17, server_content_encoding },
213 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
214 { "Content-Length:", 15, server_save_content_length },
215 { "Keep-Alive:", 11, server_keep_alive },
216 { "Proxy-Connection:", 17, server_proxy_connection },
218 { "Keep-Alive:", 11, crumble },
219 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
220 { "Transfer-Encoding:", 18, server_transfer_coding },
221 { "content-disposition:", 20, server_content_disposition },
222 { "Last-Modified:", 14, server_last_modified },
223 { "*", 0, crunch_server_header },
224 { "*", 0, filter_header },
228 static const add_header_func_ptr add_client_headers[] = {
230 client_x_forwarded_for_adder,
232 client_connection_header_adder,
236 static const add_header_func_ptr add_server_headers[] = {
237 server_connection_adder,
238 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
239 server_proxy_connection_adder,
240 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
244 /*********************************************************************
246 * Function : flush_socket
248 * Description : Write any pending "buffered" content.
251 * 1 : fd = file descriptor of the socket to read
252 * 2 : iob = The I/O buffer to flush, usually csp->iob.
254 * Returns : On success, the number of bytes written are returned (zero
255 * indicates nothing was written). On error, -1 is returned,
256 * and errno is set appropriately. If count is zero and the
257 * file descriptor refers to a regular file, 0 will be
258 * returned without causing any other effect. For a special
259 * file, the results are not portable.
261 *********************************************************************/
262 long flush_socket(jb_socket fd, struct iob *iob)
264 long len = iob->eod - iob->cur;
271 if (write_socket(fd, iob->cur, (size_t)len))
275 iob->eod = iob->cur = iob->buf;
281 /*********************************************************************
283 * Function : add_to_iob
285 * Description : Add content to the buffer, expanding the
286 * buffer if necessary.
289 * 1 : iob = Destination buffer.
290 * 2 : buffer_limit = Limit to which the destination may grow
291 * 3 : src = holds the content to be added
292 * 4 : n = number of bytes to be added
294 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
295 * or buffer limit reached.
297 *********************************************************************/
298 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
300 size_t used, offset, need;
303 if (n <= 0) return JB_ERR_OK;
305 used = (size_t)(iob->eod - iob->buf);
306 offset = (size_t)(iob->cur - iob->buf);
307 need = used + (size_t)n + 1;
310 * If the buffer can't hold the new data, extend it first.
311 * Use the next power of two if possible, else use the actual need.
313 if (need > buffer_limit)
315 log_error(LOG_LEVEL_INFO,
316 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
318 return JB_ERR_MEMORY;
321 if (need > iob->size)
323 size_t want = iob->size ? iob->size : 512;
330 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
334 else if (NULL != (p = (char *)realloc(iob->buf, need)))
340 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
341 return JB_ERR_MEMORY;
344 /* Update the iob pointers */
345 iob->cur = p + offset;
350 /* copy the new data into the iob buffer */
351 memcpy(iob->eod, src, (size_t)n);
353 /* point to the end of the data */
356 /* null terminate == cheap insurance */
364 /*********************************************************************
366 * Function : clear_iob
368 * Description : Frees the memory allocated for an I/O buffer and
369 * resets the structure.
372 * 1 : iob = I/O buffer to clear.
374 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
375 * or buffer limit reached.
377 *********************************************************************/
378 void clear_iob(struct iob *iob)
381 memset(iob, '\0', sizeof(*iob));;
386 /*********************************************************************
388 * Function : decompress_iob
390 * Description : Decompress buffered page, expanding the
391 * buffer as necessary. csp->iob->cur
392 * should point to the the beginning of the
393 * compressed data block.
396 * 1 : csp = Current client state (buffers, headers, etc...)
398 * Returns : JB_ERR_OK on success,
399 * JB_ERR_MEMORY if out-of-memory limit reached, and
400 * JB_ERR_COMPRESS if error decompressing buffer.
402 *********************************************************************/
403 jb_err decompress_iob(struct client_state *csp)
405 char *buf; /* new, uncompressed buffer */
406 char *cur; /* Current iob position (to keep the original
407 * iob->cur unmodified if we return early) */
408 size_t bufsize; /* allocated size of the new buffer */
409 size_t old_size; /* Content size before decompression */
410 size_t skip_size; /* Number of bytes at the beginning of the iob
411 that we should NOT decompress. */
412 int status; /* return status of the inflate() call */
413 z_stream zstr; /* used by calls to zlib */
415 assert(csp->iob->cur - csp->iob->buf > 0);
416 assert(csp->iob->eod - csp->iob->cur > 0);
418 bufsize = csp->iob->size;
419 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
420 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
424 if (bufsize < (size_t)10)
427 * This is to protect the parsing of gzipped data,
428 * but it should(?) be valid for deflated data also.
430 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
431 return JB_ERR_COMPRESS;
434 if (csp->content_type & CT_GZIP)
437 * Our task is slightly complicated by the facts that data
438 * compressed by gzip does not include a zlib header, and
439 * that there is no easily accessible interface in zlib to
440 * handle a gzip header. We strip off the gzip header by
441 * hand, and later inform zlib not to expect a header.
445 * Strip off the gzip header. Please see RFC 1952 for more
446 * explanation of the appropriate fields.
448 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
449 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
450 || (*cur++ != Z_DEFLATED))
452 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
453 return JB_ERR_COMPRESS;
458 if (flags & GZIP_FLAG_RESERVED_BITS)
460 /* The gzip header has reserved bits set; bail out. */
461 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
462 return JB_ERR_COMPRESS;
466 * Skip mtime (4 bytes), extra flags (1 byte)
467 * and OS type (1 byte).
471 /* Skip extra fields if necessary. */
472 if (flags & GZIP_FLAG_EXTRA_FIELDS)
475 * Skip a given number of bytes, specified
476 * as a 16-bit little-endian value.
478 * XXX: this code is untested and should probably be removed.
482 skip_bytes += *cur++ << 8;
485 * The number of bytes to skip should be positive
486 * and we'd like to stay in the buffer.
488 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
490 log_error(LOG_LEVEL_ERROR,
491 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
493 return JB_ERR_COMPRESS;
495 log_error(LOG_LEVEL_INFO,
496 "Skipping %d bytes for gzip compression. Does this sound right?",
501 /* Skip the filename if necessary. */
502 if (flags & GZIP_FLAG_FILE_NAME)
504 /* A null-terminated string is supposed to follow. */
505 while (*cur++ && (cur < csp->iob->eod));
508 /* Skip the comment if necessary. */
509 if (flags & GZIP_FLAG_COMMENT)
511 /* A null-terminated string is supposed to follow. */
512 while (*cur++ && (cur < csp->iob->eod));
515 /* Skip the CRC if necessary. */
516 if (flags & GZIP_FLAG_CHECKSUM)
521 if (cur >= csp->iob->eod)
524 * If the current position pointer reached or passed
525 * the buffer end, we were obviously tricked to skip
528 log_error(LOG_LEVEL_ERROR,
529 "Malformed gzip header detected. Aborting decompression.");
530 return JB_ERR_COMPRESS;
534 else if (csp->content_type & CT_DEFLATE)
537 * In theory (that is, according to RFC 1950), deflate-compressed
538 * data should begin with a two-byte zlib header and have an
539 * adler32 checksum at the end. It seems that in practice only
540 * the raw compressed data is sent. Note that this means that
541 * we are not RFC 1950-compliant here, but the advantage is that
542 * this actually works. :)
544 * We add a dummy null byte to tell zlib where the data ends,
545 * and later inform it not to expect a header.
547 * Fortunately, add_to_iob() has thoughtfully null-terminated
548 * the buffer; we can just increment the end pointer to include
555 log_error(LOG_LEVEL_ERROR,
556 "Unable to determine compression format for decompression");
557 return JB_ERR_COMPRESS;
560 /* Set up the fields required by zlib. */
561 zstr.next_in = (Bytef *)cur;
562 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
563 zstr.zalloc = Z_NULL;
565 zstr.opaque = Z_NULL;
568 * Passing -MAX_WBITS to inflateInit2 tells the library
569 * that there is no zlib header.
571 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
573 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
574 return JB_ERR_COMPRESS;
578 * Next, we allocate new storage for the inflated data.
579 * We don't modify the existing iob yet, so in case there
580 * is error in decompression we can recover gracefully.
582 buf = zalloc(bufsize);
585 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
586 return JB_ERR_MEMORY;
589 assert(bufsize >= skip_size);
590 memcpy(buf, csp->iob->buf, skip_size);
591 zstr.avail_out = (uInt)(bufsize - skip_size);
592 zstr.next_out = (Bytef *)buf + skip_size;
594 /* Try to decompress the whole stream in one shot. */
595 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
597 /* We need to allocate more memory for the output buffer. */
599 char *tmpbuf; /* used for realloc'ing the buffer */
600 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
602 if (0 == zstr.avail_in)
605 * If zlib wants more data then there's a problem, because
606 * the complete compressed file should have been buffered.
608 log_error(LOG_LEVEL_ERROR,
609 "Unexpected end of compressed iob. Using what we got so far.");
614 * If we reached the buffer limit and still didn't have enough
615 * memory, just give up. Due to the ceiling enforced by the next
616 * if block we could actually check for equality here, but as it
617 * can be easily mistaken for a bug we don't.
619 if (bufsize >= csp->config->buffer_limit)
621 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
622 return JB_ERR_MEMORY;
625 /* Try doubling the buffer size each time. */
628 /* Don't exceed the buffer limit. */
629 if (bufsize > csp->config->buffer_limit)
631 bufsize = csp->config->buffer_limit;
634 /* Try to allocate the new buffer. */
635 tmpbuf = realloc(buf, bufsize);
638 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
640 return JB_ERR_MEMORY;
644 char *oldnext_out = (char *)zstr.next_out;
647 * Update the fields for inflate() to use the new
648 * buffer, which may be in a location different from
651 zstr.avail_out += (uInt)(bufsize - oldbufsize);
652 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
655 * Compare with an uglier method of calculating these values
656 * that doesn't require the extra oldbufsize variable.
658 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
659 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
665 if (Z_STREAM_ERROR == inflateEnd(&zstr))
667 log_error(LOG_LEVEL_ERROR,
668 "Inconsistent stream state after decompression: %s", zstr.msg);
670 * XXX: Intentionally no return.
672 * According to zlib.h, Z_STREAM_ERROR is returned
673 * "if the stream state was inconsistent".
675 * I assume in this case inflate()'s status
676 * would also be something different than Z_STREAM_END
677 * so this check should be redundant, but lets see.
681 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
684 * We failed to decompress the stream and it's
685 * not simply because of missing data.
687 log_error(LOG_LEVEL_ERROR,
688 "Unexpected error while decompressing to the buffer (iob): %s",
690 return JB_ERR_COMPRESS;
694 * Finally, we can actually update the iob, since the
695 * decompression was successful. First, free the old
698 freez(csp->iob->buf);
700 /* Now, update the iob to use the new buffer. */
702 csp->iob->cur = csp->iob->buf + skip_size;
703 csp->iob->eod = (char *)zstr.next_out;
704 csp->iob->size = bufsize;
707 * Make sure the new uncompressed iob obeys some minimal
708 * consistency conditions.
710 if ((csp->iob->buf < csp->iob->cur)
711 && (csp->iob->cur <= csp->iob->eod)
712 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
714 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
715 if (new_size > (size_t)0)
717 log_error(LOG_LEVEL_RE_FILTER,
718 "Decompression successful. Old size: %d, new size: %d.",
723 /* zlib thinks this is OK, so lets do the same. */
724 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
729 /* It seems that zlib did something weird. */
730 log_error(LOG_LEVEL_ERROR,
731 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
732 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
733 csp->iob->eod, csp->iob->buf + csp->iob->size);
734 return JB_ERR_COMPRESS;
740 #endif /* defined(FEATURE_ZLIB) */
743 /*********************************************************************
745 * Function : normalize_lws
747 * Description : Reduces unquoted linear white space in headers
748 * to a single space in accordance with RFC 2616 2.2.
749 * This simplifies parsing and filtering later on.
751 * XXX: Remove log messages before
752 * the next stable release?
755 * 1 : header = A header with linear white space to reduce.
759 *********************************************************************/
760 static void normalize_lws(char *header)
766 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
770 while (privoxy_isspace(*q))
774 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
780 log_error(LOG_LEVEL_HEADER,
781 "Converting tab to space in '%s'", header);
786 char *end_of_token = strstr(p+1, "\"");
788 if (NULL != end_of_token)
790 /* Don't mess with quoted text. */
795 log_error(LOG_LEVEL_HEADER,
796 "Ignoring single quote in '%s'", header);
802 p = strchr(header, ':');
803 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
806 * There's still space before the colon.
814 /*********************************************************************
816 * Function : get_header
818 * Description : This (odd) routine will parse the csp->iob
819 * to get the next complete header.
822 * 1 : iob = The I/O buffer to parse, usually csp->iob.
824 * Returns : Any one of the following:
826 * 1) a pointer to a dynamically allocated string that contains a header line
827 * 2) NULL indicating that the end of the header was reached
828 * 3) "" indicating that the end of the iob was reached before finding
829 * a complete header line.
831 *********************************************************************/
832 char *get_header(struct iob *iob)
836 header = get_header_line(iob);
838 if ((header == NULL) || (*header == '\0'))
841 * No complete header read yet, tell the client.
846 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
849 * Header spans multiple lines, append the next one.
851 char *continued_header;
853 continued_header = get_header_line(iob);
854 if ((continued_header == NULL) || (*continued_header == '\0'))
857 * No complete header read yet, return what we got.
858 * XXX: Should "unread" header instead.
860 log_error(LOG_LEVEL_INFO,
861 "Failed to read a multi-line header properly: '%s'",
866 if (JB_ERR_OK != string_join(&header, continued_header))
868 log_error(LOG_LEVEL_FATAL,
869 "Out of memory while appending multiple headers.");
873 /* XXX: remove before next stable release. */
874 log_error(LOG_LEVEL_HEADER,
875 "Merged multiple header lines to: '%s'",
880 normalize_lws(header);
887 /*********************************************************************
889 * Function : get_header_line
891 * Description : This (odd) routine will parse the csp->iob
892 * to get the next header line.
895 * 1 : iob = The I/O buffer to parse, usually csp->iob.
897 * Returns : Any one of the following:
899 * 1) a pointer to a dynamically allocated string that contains a header line
900 * 2) NULL indicating that the end of the header was reached
901 * 3) "" indicating that the end of the iob was reached before finding
902 * a complete header line.
904 *********************************************************************/
905 static char *get_header_line(struct iob *iob)
909 if ((iob->cur == NULL)
910 || ((p = strchr(iob->cur, '\n')) == NULL))
912 return(""); /* couldn't find a complete header */
917 ret = strdup(iob->cur);
920 /* FIXME No way to handle error properly */
921 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
927 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
929 /* is this a blank line (i.e. the end of the header) ? */
941 /*********************************************************************
943 * Function : get_header_value
945 * Description : Get the value of a given header from a chained list
946 * of header lines or return NULL if no such header is
947 * present in the list.
950 * 1 : header_list = pointer to list
951 * 2 : header_name = string with name of header to look for.
952 * Trailing colon required, capitalization
955 * Returns : NULL if not found, else value of header
957 *********************************************************************/
958 char *get_header_value(const struct list *header_list, const char *header_name)
960 struct list_entry *cur_entry;
966 length = strlen(header_name);
968 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
972 if (!strncmpic(cur_entry->str, header_name, length))
975 * Found: return pointer to start of value
977 ret = cur_entry->str + length;
978 while (*ret && privoxy_isspace(*ret)) ret++;
992 /*********************************************************************
994 * Function : scan_headers
996 * Description : Scans headers, applies tags and updates action bits.
999 * 1 : csp = Current client state (buffers, headers, etc...)
1001 * Returns : JB_ERR_OK
1003 *********************************************************************/
1004 static jb_err scan_headers(struct client_state *csp)
1006 struct list_entry *h; /* Header */
1007 jb_err err = JB_ERR_OK;
1009 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1011 /* Header crunch()ed in previous run? -> ignore */
1012 if (h->str == NULL) continue;
1013 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1014 err = header_tagger(csp, h->str);
1021 /*********************************************************************
1023 * Function : enforce_header_order
1025 * Description : Enforces a given header order.
1028 * 1 : headers = List of headers to order.
1029 * 2 : ordered_headers = List of ordered header names.
1033 *********************************************************************/
1034 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1036 struct list_entry *sorted_header;
1037 struct list new_headers[1];
1038 struct list_entry *header;
1040 init_list(new_headers);
1042 /* The request line is always the first "header" */
1044 assert(NULL != headers->first->str);
1045 enlist(new_headers, headers->first->str);
1046 freez(headers->first->str)
1048 /* Enlist the specified headers in the given order */
1050 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1051 sorted_header = sorted_header->next)
1053 const size_t sorted_header_length = strlen(sorted_header->str);
1054 for (header = headers->first; header != NULL; header = header->next)
1056 /* Header enlisted in previous run? -> ignore */
1057 if (header->str == NULL) continue;
1059 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1060 && (header->str[sorted_header_length] == ':'))
1062 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1063 if (JB_ERR_OK != enlist(new_headers, header->str))
1065 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1072 /* Enlist the rest of the headers behind the ordered ones */
1073 for (header = headers->first; header != NULL; header = header->next)
1075 /* Header enlisted in previous run? -> ignore */
1076 if (header->str == NULL) continue;
1078 log_error(LOG_LEVEL_HEADER,
1079 "Enlisting left-over header %s", header->str);
1080 if (JB_ERR_OK != enlist(new_headers, header->str))
1082 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1087 list_remove_all(headers);
1088 list_duplicate(headers, new_headers);
1089 list_remove_all(new_headers);
1094 /*********************************************************************
1098 * Description : add, delete or modify lines in the HTTP header streams.
1099 * On entry, it receives a linked list of headers space
1100 * that was allocated dynamically (both the list nodes
1101 * and the header contents).
1103 * As a side effect it frees the space used by the original
1107 * 1 : csp = Current client state (buffers, headers, etc...)
1108 * 2 : filter_server_headers = Boolean to switch between
1109 * server and header filtering.
1111 * Returns : JB_ERR_OK in case off success, or
1112 * JB_ERR_MEMORY on out-of-memory error.
1114 *********************************************************************/
1115 jb_err sed(struct client_state *csp, int filter_server_headers)
1117 /* XXX: use more descriptive names. */
1118 struct list_entry *p;
1119 const struct parsers *v;
1120 const add_header_func_ptr *f;
1121 jb_err err = JB_ERR_OK;
1123 if (filter_server_headers)
1125 v = server_patterns;
1126 f = add_server_headers;
1130 v = client_patterns;
1131 f = add_client_headers;
1136 while ((err == JB_ERR_OK) && (v->str != NULL))
1138 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1140 /* Header crunch()ed in previous run? -> ignore */
1141 if (p->str == NULL) continue;
1143 /* Does the current parser handle this header? */
1144 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1145 (v->len == CHECK_EVERY_HEADER_REMAINING))
1147 err = v->parser(csp, &(p->str));
1153 /* place additional headers on the csp->headers list */
1154 while ((err == JB_ERR_OK) && (*f))
1160 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1162 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1169 /*********************************************************************
1171 * Function : update_server_headers
1173 * Description : Updates server headers after the body has been modified.
1176 * 1 : csp = Current client state (buffers, headers, etc...)
1178 * Returns : JB_ERR_OK in case off success, or
1179 * JB_ERR_MEMORY on out-of-memory error.
1181 *********************************************************************/
1182 jb_err update_server_headers(struct client_state *csp)
1184 jb_err err = JB_ERR_OK;
1186 static const struct parsers server_patterns_light[] = {
1187 { "Content-Length:", 15, server_adjust_content_length },
1188 { "Transfer-Encoding:", 18, server_transfer_coding },
1190 { "Content-Encoding:", 17, server_adjust_content_encoding },
1191 #endif /* def FEATURE_ZLIB */
1195 if (strncmpic(csp->http->cmd, "HEAD", 4))
1197 const struct parsers *v;
1198 struct list_entry *p;
1200 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1202 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1204 /* Header crunch()ed in previous run? -> ignore */
1205 if (p->str == NULL) continue;
1207 /* Does the current parser handle this header? */
1208 if (strncmpic(p->str, v->str, v->len) == 0)
1210 err = v->parser(csp, (char **)&(p->str));
1216 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1217 if ((JB_ERR_OK == err)
1218 && (csp->flags & CSP_FLAG_MODIFIED)
1219 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1220 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1224 create_content_length_header(csp->content_length, header, sizeof(header));
1225 err = enlist(csp->headers, header);
1226 if (JB_ERR_OK == err)
1228 log_error(LOG_LEVEL_HEADER,
1229 "Content modified with no Content-Length header set. "
1230 "Created: %s.", header);
1233 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1235 #ifdef FEATURE_COMPRESSION
1236 if ((JB_ERR_OK == err)
1237 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1239 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1240 if (JB_ERR_OK == err)
1242 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1251 /*********************************************************************
1253 * Function : header_tagger
1255 * Description : Executes all text substitutions from applying
1256 * tag actions and saves the result as tag.
1258 * XXX: Shares enough code with filter_header() and
1259 * pcrs_filter_response() to warrant some helper functions.
1262 * 1 : csp = Current client state (buffers, headers, etc...)
1263 * 2 : header = Header that is used as tagger input
1265 * Returns : JB_ERR_OK on success and always succeeds
1267 *********************************************************************/
1268 static jb_err header_tagger(struct client_state *csp, char *header)
1270 int wanted_filter_type;
1271 int multi_action_index;
1275 struct file_list *fl;
1276 struct re_filterfile_spec *b;
1277 struct list_entry *tag_name;
1279 const size_t header_length = strlen(header);
1281 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1283 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1284 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1288 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1289 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1292 if (filters_available(csp) == FALSE)
1294 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1295 "tagging enabled, but no taggers available.");
1299 for (i = 0; i < MAX_AF_FILES; i++)
1302 if ((NULL == fl) || (NULL == fl->f))
1305 * Either there are no filter files
1306 * left, or this filter file just
1307 * contains no valid filters.
1309 * Continue to be sure we don't miss
1310 * valid filter files that are chained
1311 * after empty or invalid ones.
1316 /* For all filters, */
1317 for (b = fl->f; b; b = b->next)
1319 if (b->type != wanted_filter_type)
1321 /* skip the ones we don't care about, */
1324 /* leaving only taggers that could apply, of which we use the ones, */
1325 for (tag_name = csp->action->multi[multi_action_index]->first;
1326 NULL != tag_name; tag_name = tag_name->next)
1328 /* that do apply, and */
1329 if (strcmp(b->name, tag_name->str) == 0)
1331 char *modified_tag = NULL;
1333 size_t size = header_length;
1334 pcrs_job *joblist = b->joblist;
1336 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1338 if (NULL == joblist)
1340 log_error(LOG_LEVEL_RE_FILTER,
1341 "Tagger %s has empty joblist. Nothing to do.", b->name);
1345 /* execute their pcrs_joblist on the header. */
1346 for (job = joblist; NULL != job; job = job->next)
1348 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1352 /* Success, continue with the modified version. */
1361 /* Tagger doesn't match */
1364 /* Regex failure, log it but continue anyway. */
1365 assert(NULL != header);
1366 log_error(LOG_LEVEL_ERROR,
1367 "Problems with tagger \'%s\' and header \'%s\': %s",
1368 b->name, *header, pcrs_strerror(hits));
1370 freez(modified_tag);
1374 if (b->dynamic) pcrs_free_joblist(joblist);
1376 /* If this tagger matched */
1382 * There is to technical limitation which makes
1383 * it impossible to use empty tags, but I assume
1384 * no one would do it intentionally.
1387 log_error(LOG_LEVEL_INFO,
1388 "Tagger \'%s\' created an empty tag. Ignored.",
1393 if (!list_contains_item(csp->tags, tag))
1395 if (JB_ERR_OK != enlist(csp->tags, tag))
1397 log_error(LOG_LEVEL_ERROR,
1398 "Insufficient memory to add tag \'%s\', "
1399 "based on tagger \'%s\' and header \'%s\'",
1400 tag, b->name, *header);
1404 char *action_message;
1406 * update the action bits right away, to make
1407 * tagging based on tags set by earlier taggers
1408 * of the same kind possible.
1410 if (update_action_bits_for_tag(csp, tag))
1412 action_message = "Action bits updated accordingly.";
1416 action_message = "No action bits update necessary.";
1419 log_error(LOG_LEVEL_HEADER,
1420 "Tagger \'%s\' added tag \'%s\'. %s",
1421 b->name, tag, action_message);
1426 /* XXX: Is this log-worthy? */
1427 log_error(LOG_LEVEL_HEADER,
1428 "Tagger \'%s\' didn't add tag \'%s\'. "
1429 "Tag already present", b->name, tag);
1432 } /* if the tagger matched */
1433 } /* if the tagger applies */
1434 } /* for every tagger that could apply */
1435 } /* for all filters */
1436 } /* for all filter files */
1441 /* here begins the family of parser functions that reformat header lines */
1443 /*********************************************************************
1445 * Function : filter_header
1447 * Description : Executes all text substitutions from all applying
1448 * +(server|client)-header-filter actions on the header.
1449 * Most of the code was copied from pcrs_filter_response,
1450 * including the rather short variable names
1453 * 1 : csp = Current client state (buffers, headers, etc...)
1454 * 2 : header = On input, pointer to header to modify.
1455 * On output, pointer to the modified header, or NULL
1456 * to remove the header. This function frees the
1457 * original string if necessary.
1459 * Returns : JB_ERR_OK on success and always succeeds
1461 *********************************************************************/
1462 static jb_err filter_header(struct client_state *csp, char **header)
1466 size_t size = strlen(*header);
1468 char *newheader = NULL;
1471 struct file_list *fl;
1472 struct re_filterfile_spec *b;
1473 struct list_entry *filtername;
1476 int wanted_filter_type;
1477 int multi_action_index;
1479 if (csp->flags & CSP_FLAG_NO_FILTERING)
1484 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1486 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1487 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1491 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1492 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1495 if (filters_available(csp) == FALSE)
1497 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1498 "header filtering enabled, but no matching filters available.");
1502 for (i = 0; i < MAX_AF_FILES; i++)
1505 if ((NULL == fl) || (NULL == fl->f))
1508 * Either there are no filter files
1509 * left, or this filter file just
1510 * contains no valid filters.
1512 * Continue to be sure we don't miss
1513 * valid filter files that are chained
1514 * after empty or invalid ones.
1519 * For all applying +filter actions, look if a filter by that
1520 * name exists and if yes, execute its pcrs_joblist on the
1523 for (b = fl->f; b; b = b->next)
1525 if (b->type != wanted_filter_type)
1527 /* Skip other filter types */
1531 for (filtername = csp->action->multi[multi_action_index]->first;
1532 filtername ; filtername = filtername->next)
1534 if (strcmp(b->name, filtername->str) == 0)
1536 int current_hits = 0;
1537 pcrs_job *joblist = b->joblist;
1539 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1541 if (NULL == joblist)
1543 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1547 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1548 *header, size, b->name);
1550 /* Apply all jobs from the joblist */
1551 for (job = joblist; NULL != job; job = job->next)
1553 matches = pcrs_execute(job, *header, size, &newheader, &size);
1556 current_hits += matches;
1557 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1559 *header = newheader;
1561 else if (0 == matches)
1563 /* Filter doesn't change header */
1569 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1570 *header, b->name, pcrs_strerror(matches));
1571 if (newheader != NULL)
1573 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1579 if (b->dynamic) pcrs_free_joblist(joblist);
1581 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1582 hits += current_hits;
1589 * Additionally checking for hits is important because if
1590 * the continue hack is triggered, server headers can
1591 * arrive empty to separate multiple heads from each other.
1593 if ((0 == size) && hits)
1595 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1603 /*********************************************************************
1605 * Function : server_connection
1607 * Description : Makes sure a proper "Connection:" header is
1608 * set and signals connection_header_adder to
1612 * 1 : csp = Current client state (buffers, headers, etc...)
1613 * 2 : header = On input, pointer to header to modify.
1614 * On output, pointer to the modified header, or NULL
1615 * to remove the header. This function frees the
1616 * original string if necessary.
1618 * Returns : JB_ERR_OK on success.
1620 *********************************************************************/
1621 static jb_err server_connection(struct client_state *csp, char **header)
1623 if (!strcmpic(*header, "Connection: keep-alive")
1624 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1625 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1629 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1630 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1632 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1635 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1637 log_error(LOG_LEVEL_HEADER,
1638 "Keeping the server header '%s' around.", *header);
1641 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1643 char *old_header = *header;
1645 *header = strdup_or_die("Connection: close");
1646 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1651 /* Signal server_connection_adder() to return early. */
1652 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1658 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1659 /*********************************************************************
1661 * Function : server_keep_alive
1663 * Description : Stores the server's keep alive timeout.
1666 * 1 : csp = Current client state (buffers, headers, etc...)
1667 * 2 : header = On input, pointer to header to modify.
1668 * On output, pointer to the modified header, or NULL
1669 * to remove the header. This function frees the
1670 * original string if necessary.
1672 * Returns : JB_ERR_OK.
1674 *********************************************************************/
1675 static jb_err server_keep_alive(struct client_state *csp, char **header)
1677 unsigned int keep_alive_timeout;
1678 const char *timeout_position = strstr(*header, "timeout=");
1680 if ((NULL == timeout_position)
1681 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1683 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1687 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1689 log_error(LOG_LEVEL_HEADER,
1690 "Reducing keep-alive timeout from %u to %u.",
1691 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1692 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1696 /* XXX: Is this log worthy? */
1697 log_error(LOG_LEVEL_HEADER,
1698 "Server keep-alive timeout is %u. Sticking with %u.",
1699 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1701 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1708 /*********************************************************************
1710 * Function : server_proxy_connection
1712 * Description : Figures out whether or not we should add a
1713 * Proxy-Connection header.
1716 * 1 : csp = Current client state (buffers, headers, etc...)
1717 * 2 : header = On input, pointer to header to modify.
1718 * On output, pointer to the modified header, or NULL
1719 * to remove the header. This function frees the
1720 * original string if necessary.
1722 * Returns : JB_ERR_OK.
1724 *********************************************************************/
1725 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1727 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1732 /*********************************************************************
1734 * Function : client_keep_alive
1736 * Description : Stores the client's keep alive timeout.
1739 * 1 : csp = Current client state (buffers, headers, etc...)
1740 * 2 : header = On input, pointer to header to modify.
1741 * On output, pointer to the modified header, or NULL
1742 * to remove the header. This function frees the
1743 * original string if necessary.
1745 * Returns : JB_ERR_OK.
1747 *********************************************************************/
1748 static jb_err client_keep_alive(struct client_state *csp, char **header)
1750 unsigned int keep_alive_timeout;
1751 const char *timeout_position = strstr(*header, ": ");
1753 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1755 log_error(LOG_LEVEL_HEADER,
1756 "keep-alive support is disabled. Crunching: %s.", *header);
1761 if ((NULL == timeout_position)
1762 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1764 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1768 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1770 log_error(LOG_LEVEL_HEADER,
1771 "Reducing keep-alive timeout from %u to %u.",
1772 csp->config->keep_alive_timeout, keep_alive_timeout);
1773 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1777 /* XXX: Is this log worthy? */
1778 log_error(LOG_LEVEL_HEADER,
1779 "Client keep-alive timeout is %u. Sticking with %u.",
1780 keep_alive_timeout, csp->config->keep_alive_timeout);
1788 /*********************************************************************
1790 * Function : get_content_length
1792 * Description : Gets the content length specified in a
1793 * Content-Length header.
1796 * 1 : header_value = The Content-Length header value.
1797 * 2 : length = Storage to return the value.
1799 * Returns : JB_ERR_OK on success, or
1800 * JB_ERR_PARSE if no value is recognized.
1802 *********************************************************************/
1803 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1806 assert(sizeof(unsigned long long) > 4);
1807 if (1 != sscanf(header_value, "%I64u", length))
1809 if (1 != sscanf(header_value, "%llu", length))
1812 return JB_ERR_PARSE;
1819 /*********************************************************************
1821 * Function : client_save_content_length
1823 * Description : Save the Content-Length sent by the client.
1826 * 1 : csp = Current client state (buffers, headers, etc...)
1827 * 2 : header = On input, pointer to header to modify.
1828 * On output, pointer to the modified header, or NULL
1829 * to remove the header. This function frees the
1830 * original string if necessary.
1832 * Returns : JB_ERR_OK on success, or
1833 * JB_ERR_MEMORY on out-of-memory error.
1835 *********************************************************************/
1836 static jb_err client_save_content_length(struct client_state *csp, char **header)
1838 unsigned long long content_length = 0;
1839 const char *header_value;
1841 assert(*(*header+14) == ':');
1843 header_value = *header + 15;
1844 if (JB_ERR_OK != get_content_length(header_value, &content_length))
1846 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1851 csp->expected_client_content_length = content_length;
1856 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1860 /*********************************************************************
1862 * Function : client_connection
1864 * Description : Makes sure a proper "Connection:" header is
1865 * set and signals connection_header_adder
1869 * 1 : csp = Current client state (buffers, headers, etc...)
1870 * 2 : header = On input, pointer to header to modify.
1871 * On output, pointer to the modified header, or NULL
1872 * to remove the header. This function frees the
1873 * original string if necessary.
1875 * Returns : JB_ERR_OK on success.
1877 *********************************************************************/
1878 static jb_err client_connection(struct client_state *csp, char **header)
1880 static const char connection_close[] = "Connection: close";
1882 if (!strcmpic(*header, connection_close))
1884 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1885 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1886 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1888 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1890 log_error(LOG_LEVEL_HEADER,
1891 "Removing \'%s\' to imply keep-alive.", *header);
1894 * While we imply keep-alive to the server,
1895 * we have to remember that the client didn't.
1897 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1901 char *old_header = *header;
1903 *header = strdup_or_die("Connection: keep-alive");
1904 log_error(LOG_LEVEL_HEADER,
1905 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1911 log_error(LOG_LEVEL_HEADER,
1912 "Keeping the client header '%s' around. "
1913 "The connection will not be kept alive.",
1915 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1918 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1919 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1921 log_error(LOG_LEVEL_HEADER,
1922 "Keeping the client header '%s' around. "
1923 "The server connection will be kept alive if possible.",
1925 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1926 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1930 char *old_header = *header;
1932 *header = strdup_or_die(connection_close);
1933 log_error(LOG_LEVEL_HEADER,
1934 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1938 /* Signal client_connection_header_adder() to return early. */
1939 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1945 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1946 /*********************************************************************
1948 * Function : client_proxy_connection
1950 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
1951 * appropriate and removes the Proxy-Connection
1955 * 1 : csp = Current client state (buffers, headers, etc...)
1956 * 2 : header = On input, pointer to header to modify.
1957 * On output, pointer to the modified header, or NULL
1958 * to remove the header. This function frees the
1959 * original string if necessary.
1961 * Returns : JB_ERR_OK
1963 *********************************************************************/
1964 static jb_err client_proxy_connection(struct client_state *csp, char **header)
1966 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1967 && (csp->http->ssl == 0)
1968 && (NULL == strstr(*header, "close")))
1970 log_error(LOG_LEVEL_HEADER,
1971 "The client connection can be kept alive due to: %s", *header);
1972 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1974 crumble(csp, header);
1978 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1981 /*********************************************************************
1983 * Function : crumble
1985 * Description : This is called if a header matches a pattern to "crunch"
1988 * 1 : csp = Current client state (buffers, headers, etc...)
1989 * 2 : header = On input, pointer to header to modify.
1990 * On output, pointer to the modified header, or NULL
1991 * to remove the header. This function frees the
1992 * original string if necessary.
1994 * Returns : JB_ERR_OK on success, or
1995 * JB_ERR_MEMORY on out-of-memory error.
1997 *********************************************************************/
1998 static jb_err crumble(struct client_state *csp, char **header)
2001 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2007 /*********************************************************************
2009 * Function : crunch_server_header
2011 * Description : Crunch server header if it matches a string supplied by the
2012 * user. Called from `sed'.
2015 * 1 : csp = Current client state (buffers, headers, etc...)
2016 * 2 : header = On input, pointer to header to modify.
2017 * On output, pointer to the modified header, or NULL
2018 * to remove the header. This function frees the
2019 * original string if necessary.
2021 * Returns : JB_ERR_OK on success and always succeeds
2023 *********************************************************************/
2024 static jb_err crunch_server_header(struct client_state *csp, char **header)
2026 const char *crunch_pattern;
2028 /* Do we feel like crunching? */
2029 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2031 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2033 /* Is the current header the lucky one? */
2034 if (strstr(*header, crunch_pattern))
2036 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2045 /*********************************************************************
2047 * Function : server_content_type
2049 * Description : Set the content-type for filterable types (text/.*,
2050 * .*xml.*, .*script.* and image/gif) unless filtering has been
2051 * forbidden (CT_TABOO) while parsing earlier headers.
2052 * NOTE: Since text/plain is commonly used by web servers
2053 * for files whose correct type is unknown, we don't
2054 * set CT_TEXT for it.
2057 * 1 : csp = Current client state (buffers, headers, etc...)
2058 * 2 : header = On input, pointer to header to modify.
2059 * On output, pointer to the modified header, or NULL
2060 * to remove the header. This function frees the
2061 * original string if necessary.
2063 * Returns : JB_ERR_OK on success, or
2064 * JB_ERR_MEMORY on out-of-memory error.
2066 *********************************************************************/
2067 static jb_err server_content_type(struct client_state *csp, char **header)
2069 /* Remove header if it isn't the first Content-Type header */
2070 if ((csp->content_type & CT_DECLARED))
2073 * Another, slightly slower, way to see if
2074 * we already parsed another Content-Type header.
2076 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2078 log_error(LOG_LEVEL_ERROR,
2079 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2087 * Signal that the Content-Type has been set.
2089 csp->content_type |= CT_DECLARED;
2091 if (!(csp->content_type & CT_TABOO))
2094 * XXX: The assumption that text/plain is a sign of
2095 * binary data seems to be somewhat unreasonable nowadays
2096 * and should be dropped after 3.0.8 is out.
2098 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2099 || strstr(*header, "xml")
2100 || strstr(*header, "script"))
2102 csp->content_type |= CT_TEXT;
2104 else if (strstr(*header, "image/gif"))
2106 csp->content_type |= CT_GIF;
2111 * Are we messing with the content type?
2113 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2116 * Make sure the user doesn't accidentally
2117 * change the content type of binary documents.
2119 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2122 *header = strdup_or_die("Content-Type: ");
2123 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2127 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2128 return JB_ERR_MEMORY;
2130 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2134 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2135 "It doesn't look like a content type that should be filtered. "
2136 "Enable force-text-mode if you know what you're doing.", *header);
2144 /*********************************************************************
2146 * Function : server_transfer_coding
2148 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2149 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2150 * - Remove header if body was chunked but has been
2151 * de-chunked for filtering.
2154 * 1 : csp = Current client state (buffers, headers, etc...)
2155 * 2 : header = On input, pointer to header to modify.
2156 * On output, pointer to the modified header, or NULL
2157 * to remove the header. This function frees the
2158 * original string if necessary.
2160 * Returns : JB_ERR_OK on success, or
2161 * JB_ERR_MEMORY on out-of-memory error.
2163 *********************************************************************/
2164 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2167 * Turn off pcrs and gif filtering if body compressed
2169 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2173 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2175 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2176 csp->http->cmd, *header);
2177 #endif /* def FEATURE_ZLIB */
2178 csp->content_type = CT_TABOO;
2182 * Raise flag if body chunked
2184 if (strstr(*header, "chunked"))
2186 csp->flags |= CSP_FLAG_CHUNKED;
2189 * If the body was modified, it has been de-chunked first
2190 * and the header must be removed.
2192 * FIXME: If there is more than one transfer encoding,
2193 * only the "chunked" part should be removed here.
2195 if (csp->flags & CSP_FLAG_MODIFIED)
2197 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2206 /*********************************************************************
2208 * Function : server_content_encoding
2210 * Description : Used to check if the content is compressed, and if
2211 * FEATURE_ZLIB is disabled, filtering is disabled as
2214 * If FEATURE_ZLIB is enabled and the compression type
2215 * supported, the content is marked for decompression.
2217 * XXX: Doesn't properly deal with multiple or with
2218 * unsupported but unknown encodings.
2219 * Is case-sensitive but shouldn't be.
2222 * 1 : csp = Current client state (buffers, headers, etc...)
2223 * 2 : header = On input, pointer to header to modify.
2224 * On output, pointer to the modified header, or NULL
2225 * to remove the header. This function frees the
2226 * original string if necessary.
2228 * Returns : JB_ERR_OK on success, or
2229 * JB_ERR_MEMORY on out-of-memory error.
2231 *********************************************************************/
2232 static jb_err server_content_encoding(struct client_state *csp, char **header)
2235 if (strstr(*header, "sdch"))
2238 * Shared Dictionary Compression over HTTP isn't supported,
2239 * filtering it anyway is pretty much guaranteed to mess up
2242 csp->content_type |= CT_TABOO;
2245 * Log a warning if the user expects the content to be filtered.
2247 if ((csp->rlist != NULL) &&
2248 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2250 log_error(LOG_LEVEL_INFO,
2251 "SDCH-compressed content detected, content filtering disabled. "
2252 "Consider suppressing SDCH offers made by the client.");
2255 else if (strstr(*header, "gzip"))
2257 /* Mark for gzip decompression */
2258 csp->content_type |= CT_GZIP;
2260 else if (strstr(*header, "deflate"))
2262 /* Mark for zlib decompression */
2263 csp->content_type |= CT_DEFLATE;
2265 else if (strstr(*header, "compress"))
2268 * We can't decompress this; therefore we can't filter
2271 csp->content_type |= CT_TABOO;
2273 #else /* !defined(FEATURE_ZLIB) */
2275 * XXX: Using a black list here isn't the right approach.
2277 * In case of SDCH, building with zlib support isn't
2280 if (strstr(*header, "gzip") ||
2281 strstr(*header, "compress") ||
2282 strstr(*header, "deflate") ||
2283 strstr(*header, "sdch"))
2286 * Body is compressed, turn off pcrs and gif filtering.
2288 csp->content_type |= CT_TABOO;
2291 * Log a warning if the user expects the content to be filtered.
2293 if ((csp->rlist != NULL) &&
2294 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2296 log_error(LOG_LEVEL_INFO,
2297 "Compressed content detected, content filtering disabled. "
2298 "Consider recompiling Privoxy with zlib support or "
2299 "enable the prevent-compression action.");
2302 #endif /* defined(FEATURE_ZLIB) */
2310 /*********************************************************************
2312 * Function : server_adjust_content_encoding
2314 * Description : Remove the Content-Encoding header if the
2315 * decompression was successful and the content
2319 * 1 : csp = Current client state (buffers, headers, etc...)
2320 * 2 : header = On input, pointer to header to modify.
2321 * On output, pointer to the modified header, or NULL
2322 * to remove the header. This function frees the
2323 * original string if necessary.
2325 * Returns : JB_ERR_OK on success, or
2326 * JB_ERR_MEMORY on out-of-memory error.
2328 *********************************************************************/
2329 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2331 if ((csp->flags & CSP_FLAG_MODIFIED)
2332 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2335 * We successfully decompressed the content,
2336 * and have to clean the header now, so the
2337 * client no longer expects compressed data.
2339 * XXX: There is a difference between cleaning
2340 * and removing it completely.
2342 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2349 #endif /* defined(FEATURE_ZLIB) */
2352 /*********************************************************************
2354 * Function : server_adjust_content_length
2356 * Description : Adjust Content-Length header if we modified
2360 * 1 : csp = Current client state (buffers, headers, etc...)
2361 * 2 : header = On input, pointer to header to modify.
2362 * On output, pointer to the modified header, or NULL
2363 * to remove the header. This function frees the
2364 * original string if necessary.
2366 * Returns : JB_ERR_OK on success, or
2367 * JB_ERR_MEMORY on out-of-memory error.
2369 *********************************************************************/
2370 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2372 /* Regenerate header if the content was modified. */
2373 if (csp->flags & CSP_FLAG_MODIFIED)
2375 const size_t header_length = 50;
2377 *header = malloc(header_length);
2378 if (*header == NULL)
2380 return JB_ERR_MEMORY;
2382 create_content_length_header(csp->content_length, *header, header_length);
2383 log_error(LOG_LEVEL_HEADER,
2384 "Adjusted Content-Length to %llu", csp->content_length);
2391 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2392 /*********************************************************************
2394 * Function : server_save_content_length
2396 * Description : Save the Content-Length sent by the server.
2399 * 1 : csp = Current client state (buffers, headers, etc...)
2400 * 2 : header = On input, pointer to header to modify.
2401 * On output, pointer to the modified header, or NULL
2402 * to remove the header. This function frees the
2403 * original string if necessary.
2405 * Returns : JB_ERR_OK on success, or
2406 * JB_ERR_MEMORY on out-of-memory error.
2408 *********************************************************************/
2409 static jb_err server_save_content_length(struct client_state *csp, char **header)
2411 unsigned long long content_length = 0;
2412 const char *header_value;
2414 assert(*(*header+14) == ':');
2416 header_value = *header + 15;
2417 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2419 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2424 csp->expected_content_length = content_length;
2425 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2426 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2431 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2434 /*********************************************************************
2436 * Function : server_content_md5
2438 * Description : Crumble any Content-MD5 headers if the document was
2439 * modified. FIXME: Should we re-compute instead?
2442 * 1 : csp = Current client state (buffers, headers, etc...)
2443 * 2 : header = On input, pointer to header to modify.
2444 * On output, pointer to the modified header, or NULL
2445 * to remove the header. This function frees the
2446 * original string if necessary.
2448 * Returns : JB_ERR_OK on success, or
2449 * JB_ERR_MEMORY on out-of-memory error.
2451 *********************************************************************/
2452 static jb_err server_content_md5(struct client_state *csp, char **header)
2454 if (csp->flags & CSP_FLAG_MODIFIED)
2456 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2464 /*********************************************************************
2466 * Function : server_content_disposition
2468 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2469 * Called from `sed'.
2472 * 1 : csp = Current client state (buffers, headers, etc...)
2473 * 2 : header = On input, pointer to header to modify.
2474 * On output, pointer to the modified header, or NULL
2475 * to remove the header. This function frees the
2476 * original string if necessary.
2478 * Returns : JB_ERR_OK on success, or
2479 * JB_ERR_MEMORY on out-of-memory error.
2481 *********************************************************************/
2482 static jb_err server_content_disposition(struct client_state *csp, char **header)
2487 * Are we messing with the Content-Disposition header?
2489 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2495 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2497 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2500 * Blocking content-disposition header
2502 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2509 * Replacing Content-Disposition header
2512 *header = strdup("Content-Disposition: ");
2513 string_append(header, newval);
2515 if (*header != NULL)
2517 log_error(LOG_LEVEL_HEADER,
2518 "Content-Disposition header crunched and replaced with: %s", *header);
2521 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2525 /*********************************************************************
2527 * Function : server_last_modified
2529 * Description : Changes Last-Modified header to the actual date
2530 * to help hide-if-modified-since.
2531 * Called from `sed'.
2534 * 1 : csp = Current client state (buffers, headers, etc...)
2535 * 2 : header = On input, pointer to header to modify.
2536 * On output, pointer to the modified header, or NULL
2537 * to remove the header. This function frees the
2538 * original string if necessary.
2540 * Returns : JB_ERR_OK on success, or
2541 * JB_ERR_MEMORY on out-of-memory error.
2543 *********************************************************************/
2544 static jb_err server_last_modified(struct client_state *csp, char **header)
2547 time_t last_modified;
2551 * Are we messing with the Last-Modified header?
2553 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2559 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2561 if (0 == strcmpic(newval, "block"))
2564 * Blocking Last-Modified header. Useless but why not.
2566 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2570 else if (0 == strcmpic(newval, "reset-to-request-time"))
2573 * Setting Last-Modified Header to now.
2576 get_http_time(0, buf, sizeof(buf));
2578 *header = strdup("Last-Modified: ");
2579 string_append(header, buf);
2581 if (*header == NULL)
2583 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2587 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2590 else if (0 == strcmpic(newval, "randomize"))
2592 const char *header_time = *header + sizeof("Last-Modified:");
2594 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2596 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2598 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2604 struct tm *timeptr = NULL;
2606 #ifdef HAVE_GMTIME_R
2610 rtime = (long int)difftime(now, last_modified);
2613 long int days, hours, minutes, seconds;
2614 const int negative_delta = (rtime < 0);
2619 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2621 rtime = pick_from_range(rtime);
2626 last_modified += rtime;
2627 #ifdef HAVE_GMTIME_R
2628 timeptr = gmtime_r(&last_modified, &gmt);
2629 #elif defined(MUTEX_LOCKS_AVAILABLE)
2630 privoxy_mutex_lock(&gmtime_mutex);
2631 timeptr = gmtime(&last_modified);
2632 privoxy_mutex_unlock(&gmtime_mutex);
2634 timeptr = gmtime(&last_modified);
2636 if ((NULL == timeptr) || !strftime(newheader,
2637 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2639 log_error(LOG_LEVEL_ERROR,
2640 "Randomizing '%s' failed. Crunching the header without replacement.",
2647 *header = strdup("Last-Modified: ");
2648 string_append(header, newheader);
2650 if (*header == NULL)
2652 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2653 return JB_ERR_MEMORY;
2656 days = rtime / (3600 * 24);
2657 hours = rtime / 3600 % 24;
2658 minutes = rtime / 60 % 60;
2659 seconds = rtime % 60;
2661 log_error(LOG_LEVEL_HEADER,
2662 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2663 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2664 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2668 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2677 /*********************************************************************
2679 * Function : client_accept_encoding
2681 * Description : Rewrite the client's Accept-Encoding header so that
2682 * if doesn't allow compression, if the action applies.
2683 * Note: For HTTP/1.0 the absence of the header is enough.
2686 * 1 : csp = Current client state (buffers, headers, etc...)
2687 * 2 : header = On input, pointer to header to modify.
2688 * On output, pointer to the modified header, or NULL
2689 * to remove the header. This function frees the
2690 * original string if necessary.
2692 * Returns : JB_ERR_OK on success, or
2693 * JB_ERR_MEMORY on out-of-memory error.
2695 *********************************************************************/
2696 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2698 #ifdef FEATURE_COMPRESSION
2699 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2700 && strstr(*header, "deflate"))
2702 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2705 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2707 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2715 /*********************************************************************
2717 * Function : client_te
2719 * Description : Rewrite the client's TE header so that
2720 * if doesn't allow compression, if the action applies.
2723 * 1 : csp = Current client state (buffers, headers, etc...)
2724 * 2 : header = On input, pointer to header to modify.
2725 * On output, pointer to the modified header, or NULL
2726 * to remove the header. This function frees the
2727 * original string if necessary.
2729 * Returns : JB_ERR_OK on success, or
2730 * JB_ERR_MEMORY on out-of-memory error.
2732 *********************************************************************/
2733 static jb_err client_te(struct client_state *csp, char **header)
2735 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2738 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2745 /*********************************************************************
2747 * Function : client_referrer
2749 * Description : Handle the "referer" config setting properly.
2750 * Called from `sed'.
2753 * 1 : csp = Current client state (buffers, headers, etc...)
2754 * 2 : header = On input, pointer to header to modify.
2755 * On output, pointer to the modified header, or NULL
2756 * to remove the header. This function frees the
2757 * original string if necessary.
2759 * Returns : JB_ERR_OK on success, or
2760 * JB_ERR_MEMORY on out-of-memory error.
2762 *********************************************************************/
2763 static jb_err client_referrer(struct client_state *csp, char **header)
2765 const char *parameter;
2766 /* booleans for parameters we have to check multiple times */
2767 int parameter_conditional_block;
2768 int parameter_conditional_forge;
2770 #ifdef FEATURE_FORCE_LOAD
2772 * Since the referrer can include the prefix even
2773 * if the request itself is non-forced, we must
2774 * clean it unconditionally.
2776 * XXX: strclean is too broad
2778 strclean(*header, FORCE_PREFIX);
2779 #endif /* def FEATURE_FORCE_LOAD */
2781 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2783 /* Nothing left to do */
2787 parameter = csp->action->string[ACTION_STRING_REFERER];
2788 assert(parameter != NULL);
2789 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2790 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2792 if (!parameter_conditional_block && !parameter_conditional_forge)
2795 * As conditional-block and conditional-forge are the only
2796 * parameters that rely on the original referrer, we can
2797 * remove it now for all the others.
2802 if (0 == strcmpic(parameter, "block"))
2804 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2807 else if (parameter_conditional_block || parameter_conditional_forge)
2809 return handle_conditional_hide_referrer_parameter(header,
2810 csp->http->hostport, parameter_conditional_block);
2812 else if (0 == strcmpic(parameter, "forge"))
2814 return create_forged_referrer(header, csp->http->hostport);
2818 /* interpret parameter as user-supplied referer to fake */
2819 return create_fake_referrer(header, parameter);
2824 /*********************************************************************
2826 * Function : client_accept_language
2828 * Description : Handle the "Accept-Language" config setting properly.
2829 * Called from `sed'.
2832 * 1 : csp = Current client state (buffers, headers, etc...)
2833 * 2 : header = On input, pointer to header to modify.
2834 * On output, pointer to the modified header, or NULL
2835 * to remove the header. This function frees the
2836 * original string if necessary.
2838 * Returns : JB_ERR_OK on success, or
2839 * JB_ERR_MEMORY on out-of-memory error.
2841 *********************************************************************/
2842 static jb_err client_accept_language(struct client_state *csp, char **header)
2847 * Are we messing with the Accept-Language?
2849 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2851 /*I don't think so*/
2855 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2857 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2860 * Blocking Accept-Language header
2862 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2869 * Replacing Accept-Language header
2872 *header = strdup("Accept-Language: ");
2873 string_append(header, newval);
2875 if (*header == NULL)
2877 log_error(LOG_LEVEL_ERROR,
2878 "Insufficient memory. Accept-Language header crunched without replacement.");
2882 log_error(LOG_LEVEL_HEADER,
2883 "Accept-Language header crunched and replaced with: %s", *header);
2886 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2890 /*********************************************************************
2892 * Function : crunch_client_header
2894 * Description : Crunch client header if it matches a string supplied by the
2895 * user. Called from `sed'.
2898 * 1 : csp = Current client state (buffers, headers, etc...)
2899 * 2 : header = On input, pointer to header to modify.
2900 * On output, pointer to the modified header, or NULL
2901 * to remove the header. This function frees the
2902 * original string if necessary.
2904 * Returns : JB_ERR_OK on success and always succeeds
2906 *********************************************************************/
2907 static jb_err crunch_client_header(struct client_state *csp, char **header)
2909 const char *crunch_pattern;
2911 /* Do we feel like crunching? */
2912 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2914 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2916 /* Is the current header the lucky one? */
2917 if (strstr(*header, crunch_pattern))
2919 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2927 /*********************************************************************
2929 * Function : client_uagent
2931 * Description : Handle the "user-agent" config setting properly
2932 * and remember its original value to enable browser
2933 * bug workarounds. Called from `sed'.
2936 * 1 : csp = Current client state (buffers, headers, etc...)
2937 * 2 : header = On input, pointer to header to modify.
2938 * On output, pointer to the modified header, or NULL
2939 * to remove the header. This function frees the
2940 * original string if necessary.
2942 * Returns : JB_ERR_OK on success, or
2943 * JB_ERR_MEMORY on out-of-memory error.
2945 *********************************************************************/
2946 static jb_err client_uagent(struct client_state *csp, char **header)
2950 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2955 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2962 *header = strdup("User-Agent: ");
2963 string_append(header, newval);
2965 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2967 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2971 /*********************************************************************
2973 * Function : client_ua
2975 * Description : Handle "ua-" headers properly. Called from `sed'.
2978 * 1 : csp = Current client state (buffers, headers, etc...)
2979 * 2 : header = On input, pointer to header to modify.
2980 * On output, pointer to the modified header, or NULL
2981 * to remove the header. This function frees the
2982 * original string if necessary.
2984 * Returns : JB_ERR_OK on success, or
2985 * JB_ERR_MEMORY on out-of-memory error.
2987 *********************************************************************/
2988 static jb_err client_ua(struct client_state *csp, char **header)
2990 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2992 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3000 /*********************************************************************
3002 * Function : client_from
3004 * Description : Handle the "from" config setting properly.
3005 * Called from `sed'.
3008 * 1 : csp = Current client state (buffers, headers, etc...)
3009 * 2 : header = On input, pointer to header to modify.
3010 * On output, pointer to the modified header, or NULL
3011 * to remove the header. This function frees the
3012 * original string if necessary.
3014 * Returns : JB_ERR_OK on success, or
3015 * JB_ERR_MEMORY on out-of-memory error.
3017 *********************************************************************/
3018 static jb_err client_from(struct client_state *csp, char **header)
3022 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3029 newval = csp->action->string[ACTION_STRING_FROM];
3032 * Are we blocking the e-mail address?
3034 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3036 log_error(LOG_LEVEL_HEADER, "crunched From!");
3040 log_error(LOG_LEVEL_HEADER, " modified");
3042 *header = strdup("From: ");
3043 string_append(header, newval);
3045 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3049 /*********************************************************************
3051 * Function : client_send_cookie
3053 * Description : Crunches the "cookie" header if necessary.
3054 * Called from `sed'.
3056 * XXX: Stupid name, doesn't send squat.
3059 * 1 : csp = Current client state (buffers, headers, etc...)
3060 * 2 : header = On input, pointer to header to modify.
3061 * On output, pointer to the modified header, or NULL
3062 * to remove the header. This function frees the
3063 * original string if necessary.
3065 * Returns : JB_ERR_OK on success, or
3066 * JB_ERR_MEMORY on out-of-memory error.
3068 *********************************************************************/
3069 static jb_err client_send_cookie(struct client_state *csp, char **header)
3071 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3073 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3081 /*********************************************************************
3083 * Function : client_x_forwarded
3085 * Description : Handle the "x-forwarded-for" config setting properly,
3086 * also used in the add_client_headers list. Called from `sed'.
3089 * 1 : csp = Current client state (buffers, headers, etc...)
3090 * 2 : header = On input, pointer to header to modify.
3091 * On output, pointer to the modified header, or NULL
3092 * to remove the header. This function frees the
3093 * original string if necessary.
3095 * Returns : JB_ERR_OK on success, or
3096 * JB_ERR_MEMORY on out-of-memory error.
3098 *********************************************************************/
3099 jb_err client_x_forwarded(struct client_state *csp, char **header)
3101 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3103 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3105 if (0 == strcmpic(parameter, "block"))
3108 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3110 else if (0 == strcmpic(parameter, "add"))
3112 string_append(header, ", ");
3113 string_append(header, csp->ip_addr_str);
3115 if (*header == NULL)
3117 return JB_ERR_MEMORY;
3119 log_error(LOG_LEVEL_HEADER,
3120 "Appended client IP address to %s", *header);
3121 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3125 log_error(LOG_LEVEL_FATAL,
3126 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3134 /*********************************************************************
3136 * Function : client_max_forwards
3138 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3139 * from the value of the Max-Forwards header field.
3142 * 1 : csp = Current client state (buffers, headers, etc...)
3143 * 2 : header = On input, pointer to header to modify.
3144 * On output, pointer to the modified header, or NULL
3145 * to remove the header. This function frees the
3146 * original string if necessary.
3148 * Returns : JB_ERR_OK on success, or
3149 * JB_ERR_MEMORY on out-of-memory error.
3151 *********************************************************************/
3152 static jb_err client_max_forwards(struct client_state *csp, char **header)
3156 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3157 (0 == strcmpic(csp->http->gpc, "options")))
3159 assert(*(*header+12) == ':');
3160 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3162 if (max_forwards > 0)
3164 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3165 log_error(LOG_LEVEL_HEADER,
3166 "Max-Forwards value for %s request reduced to %d.",
3167 csp->http->gpc, max_forwards);
3169 else if (max_forwards < 0)
3171 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3177 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3186 /*********************************************************************
3188 * Function : client_host
3190 * Description : If the request URI did not contain host and
3191 * port information, parse and evaluate the Host
3194 * Also, kill ill-formed HOST: headers as sent by
3195 * Apple's iTunes software when used with a proxy.
3198 * 1 : csp = Current client state (buffers, headers, etc...)
3199 * 2 : header = On input, pointer to header to modify.
3200 * On output, pointer to the modified header, or NULL
3201 * to remove the header. This function frees the
3202 * original string if necessary.
3204 * Returns : JB_ERR_OK on success, or
3205 * JB_ERR_MEMORY on out-of-memory error.
3207 *********************************************************************/
3208 static jb_err client_host(struct client_state *csp, char **header)
3213 * If the header field name is all upper-case, chances are that it's
3214 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3215 * not a problem -- they are regenerated later.
3217 if ((*header)[1] == 'O')
3219 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3224 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3225 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3228 p = strdup_or_die((*header)+6);
3230 q = strdup_or_die(p);
3232 freez(csp->http->hostport);
3233 csp->http->hostport = p;
3234 freez(csp->http->host);
3235 csp->http->host = q;
3236 q = strchr(csp->http->host, ':');
3239 /* Terminate hostname and evaluate port string */
3241 csp->http->port = atoi(q);
3245 csp->http->port = csp->http->ssl ? 443 : 80;
3248 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3249 csp->http->hostport, csp->http->host, csp->http->port);
3252 /* Signal client_host_adder() to return right away */
3253 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3259 /*********************************************************************
3261 * Function : client_if_modified_since
3263 * Description : Remove or modify the If-Modified-Since header.
3266 * 1 : csp = Current client state (buffers, headers, etc...)
3267 * 2 : header = On input, pointer to header to modify.
3268 * On output, pointer to the modified header, or NULL
3269 * to remove the header. This function frees the
3270 * original string if necessary.
3272 * Returns : JB_ERR_OK on success, or
3273 * JB_ERR_MEMORY on out-of-memory error.
3275 *********************************************************************/
3276 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3279 #ifdef HAVE_GMTIME_R
3282 struct tm *timeptr = NULL;
3287 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3290 * The client got an error message because of a temporary problem,
3291 * the problem is gone and the client now tries to revalidate our
3292 * error message on the real server. The revalidation would always
3293 * end with the transmission of the whole document and there is
3294 * no need to expose the bogus If-Modified-Since header.
3296 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3299 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3301 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3303 if ((0 == strcmpic(newval, "block")))
3305 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3308 else /* add random value */
3310 const char *header_time = *header + sizeof("If-Modified-Since:");
3312 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3314 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3319 long int hours, minutes, seconds;
3320 long int rtime = strtol(newval, &endptr, 0);
3321 const int negative_range = (rtime < 0);
3325 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3326 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3332 rtime = pick_from_range(rtime);
3336 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3339 tm += rtime * (negative_range ? -1 : 1);
3340 #ifdef HAVE_GMTIME_R
3341 timeptr = gmtime_r(&tm, &gmt);
3342 #elif defined(MUTEX_LOCKS_AVAILABLE)
3343 privoxy_mutex_lock(&gmtime_mutex);
3344 timeptr = gmtime(&tm);
3345 privoxy_mutex_unlock(&gmtime_mutex);
3347 timeptr = gmtime(&tm);
3349 if ((NULL == timeptr) || !strftime(newheader,
3350 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3352 log_error(LOG_LEVEL_ERROR,
3353 "Randomizing '%s' failed. Crunching the header without replacement.",
3360 *header = strdup("If-Modified-Since: ");
3361 string_append(header, newheader);
3363 if (*header == NULL)
3365 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3366 return JB_ERR_MEMORY;
3369 hours = rtime / 3600;
3370 minutes = rtime / 60 % 60;
3371 seconds = rtime % 60;
3373 log_error(LOG_LEVEL_HEADER,
3374 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3375 *header, (negative_range) ? "subtracted" : "added", hours,
3376 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3377 seconds, (seconds == 1) ? ")" : "s)");
3386 /*********************************************************************
3388 * Function : client_if_none_match
3390 * Description : Remove the If-None-Match header.
3393 * 1 : csp = Current client state (buffers, headers, etc...)
3394 * 2 : header = On input, pointer to header to modify.
3395 * On output, pointer to the modified header, or NULL
3396 * to remove the header. This function frees the
3397 * original string if necessary.
3399 * Returns : JB_ERR_OK on success, or
3400 * JB_ERR_MEMORY on out-of-memory error.
3402 *********************************************************************/
3403 static jb_err client_if_none_match(struct client_state *csp, char **header)
3405 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3407 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3415 /*********************************************************************
3417 * Function : client_x_filter
3419 * Description : Disables filtering if the client set "X-Filter: No".
3420 * Called from `sed'.
3423 * 1 : csp = Current client state (buffers, headers, etc...)
3424 * 2 : header = On input, pointer to header to modify.
3425 * On output, pointer to the modified header, or NULL
3426 * to remove the header. This function frees the
3427 * original string if necessary.
3429 * Returns : JB_ERR_OK on success
3431 *********************************************************************/
3432 jb_err client_x_filter(struct client_state *csp, char **header)
3434 if (0 == strcmpic(*header, "X-Filter: No"))
3436 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3438 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3442 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3444 log_error(LOG_LEVEL_HEADER,
3445 "force-text-mode overruled the client's request to fetch without filtering!");
3449 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3450 csp->flags |= CSP_FLAG_NO_FILTERING;
3451 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3453 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3461 /*********************************************************************
3463 * Function : client_range
3465 * Description : Removes Range, Request-Range and If-Range headers if
3466 * content filtering is enabled and the range doesn't
3469 * If the client's version of the document has been
3470 * altered by Privoxy, the server could interpret the
3471 * range differently than the client intended in which
3472 * case the user could end up with corrupted content.
3474 * If the range starts at byte 0 this isn't an issue
3475 * so the header can pass. Partial requests like this
3476 * are used to render preview images for videos without
3477 * downloading the whole video.
3479 * While HTTP doesn't require that range requests are
3480 * honoured and the client could simply abort the download
3481 * after receiving a sufficient amount of data, various
3482 * clients don't handle complete responses to range
3483 * requests gracefully and emit misleading error messages
3487 * 1 : csp = Current client state (buffers, headers, etc...)
3488 * 2 : header = On input, pointer to header to modify.
3489 * On output, pointer to the modified header, or NULL
3490 * to remove the header. This function frees the
3491 * original string if necessary.
3493 * Returns : JB_ERR_OK
3495 *********************************************************************/
3496 static jb_err client_range(struct client_state *csp, char **header)
3498 if (content_filters_enabled(csp->action)
3499 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3501 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3502 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3509 /* the following functions add headers directly to the header list */
3511 /*********************************************************************
3513 * Function : client_host_adder
3515 * Description : Adds the Host: header field if it is missing.
3516 * Called from `sed'.
3519 * 1 : csp = Current client state (buffers, headers, etc...)
3521 * Returns : JB_ERR_OK on success, or
3522 * JB_ERR_MEMORY on out-of-memory error.
3524 *********************************************************************/
3525 static jb_err client_host_adder(struct client_state *csp)
3530 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3532 /* Header already set by the client, nothing to do. */
3536 if (!csp->http->hostport || !*(csp->http->hostport))
3538 /* XXX: When does this happen and why is it OK? */
3539 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3544 * remove 'user:pass@' from 'proto://user:pass@host'
3546 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3552 p = csp->http->hostport;
3555 /* XXX: Just add it, we already made sure that it will be unique */
3556 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3557 err = enlist_unique_header(csp->headers, "Host", p);
3563 /*********************************************************************
3565 * Function : client_xtra_adder
3567 * Description : Used in the add_client_headers list. Called from `sed'.
3570 * 1 : csp = Current client state (buffers, headers, etc...)
3572 * Returns : JB_ERR_OK on success, or
3573 * JB_ERR_MEMORY on out-of-memory error.
3575 *********************************************************************/
3576 static jb_err client_xtra_adder(struct client_state *csp)
3578 struct list_entry *lst;
3581 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3582 lst ; lst = lst->next)
3584 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3585 err = enlist(csp->headers, lst->str);
3597 /*********************************************************************
3599 * Function : client_x_forwarded_for_adder
3601 * Description : Used in the add_client_headers list. Called from `sed'.
3604 * 1 : csp = Current client state (buffers, headers, etc...)
3606 * Returns : JB_ERR_OK on success, or
3607 * JB_ERR_MEMORY on out-of-memory error.
3609 *********************************************************************/
3610 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3612 char *header = NULL;
3615 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3616 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3617 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3620 * If we aren't adding X-Forwarded-For headers,
3621 * or we already appended an existing X-Forwarded-For
3622 * header, there's nothing left to do here.
3627 header = strdup("X-Forwarded-For: ");
3628 string_append(&header, csp->ip_addr_str);
3632 return JB_ERR_MEMORY;
3635 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3636 err = enlist(csp->headers, header);
3643 /*********************************************************************
3645 * Function : server_connection_adder
3647 * Description : Adds an appropriate "Connection:" header to csp->headers
3648 * unless the header was already present. Called from `sed'.
3651 * 1 : csp = Current client state (buffers, headers, etc...)
3653 * Returns : JB_ERR_OK on success, or
3654 * JB_ERR_MEMORY on out-of-memory error.
3656 *********************************************************************/
3657 static jb_err server_connection_adder(struct client_state *csp)
3659 const unsigned int flags = csp->flags;
3660 const char *response_status_line = csp->headers->first->str;
3661 static const char connection_close[] = "Connection: close";
3663 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3664 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3670 * XXX: if we downgraded the response, this check will fail.
3672 if ((csp->config->feature_flags &
3673 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3674 && (NULL != response_status_line)
3675 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3676 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3677 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3681 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3682 "without Connection header implies keep-alive.");
3683 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3687 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3689 return enlist(csp->headers, connection_close);
3693 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3694 /*********************************************************************
3696 * Function : server_proxy_connection_adder
3698 * Description : Adds a "Proxy-Connection: keep-alive" header to
3699 * csp->headers when appropriate.
3702 * 1 : csp = Current client state (buffers, headers, etc...)
3704 * Returns : JB_ERR_OK on success, or
3705 * JB_ERR_MEMORY on out-of-memory error.
3707 *********************************************************************/
3708 static jb_err server_proxy_connection_adder(struct client_state *csp)
3710 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3711 jb_err err = JB_ERR_OK;
3713 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3714 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3715 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3716 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3717 || (csp->flags & CSP_FLAG_CHUNKED)))
3719 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3720 err = enlist(csp->headers, proxy_connection_header);
3725 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3728 /*********************************************************************
3730 * Function : client_connection_header_adder
3732 * Description : Adds a proper "Connection:" header to csp->headers
3733 * unless the header was already present. Called from `sed'.
3736 * 1 : csp = Current client state (buffers, headers, etc...)
3738 * Returns : JB_ERR_OK on success, or
3739 * JB_ERR_MEMORY on out-of-memory error.
3741 *********************************************************************/
3742 static jb_err client_connection_header_adder(struct client_state *csp)
3744 static const char connection_close[] = "Connection: close";
3746 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3747 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3752 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3753 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3754 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3755 && (csp->http->ssl == 0)
3756 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3758 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3761 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3763 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3765 return enlist(csp->headers, connection_close);
3769 /*********************************************************************
3771 * Function : server_http
3773 * Description : - Save the HTTP Status into csp->http->status
3774 * - Set CT_TABOO to prevent filtering if the answer
3775 * is a partial range (HTTP status 206)
3776 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3780 * 1 : csp = Current client state (buffers, headers, etc...)
3781 * 2 : header = On input, pointer to header to modify.
3782 * On output, pointer to the modified header, or NULL
3783 * to remove the header. This function frees the
3784 * original string if necessary.
3786 * Returns : JB_ERR_OK on success, or
3787 * JB_ERR_MEMORY on out-of-memory error.
3789 *********************************************************************/
3790 static jb_err server_http(struct client_state *csp, char **header)
3792 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3793 if (csp->http->status == 206)
3795 csp->content_type = CT_TABOO;
3798 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3800 /* XXX: Should we do a real validity check here? */
3801 if (strlen(*header) > 8)
3804 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3809 * XXX: Should we block the request or
3810 * enlist a valid status code line here?
3812 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3813 "Downgrading to HTTP/1.0 impossible.");
3820 /*********************************************************************
3822 * Function : add_cooky_expiry_date
3824 * Description : Adds a cookie expiry date to a string.
3827 * 1 : cookie = On input, pointer to cookie to modify.
3828 * On output, pointer to the modified header.
3829 * The original string is freed.
3830 * 2 : lifetime = Seconds the cookie should be valid
3834 *********************************************************************/
3835 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
3838 struct tm *timeptr = NULL;
3839 time_t expiry_date = time(NULL) + lifetime;
3840 #ifdef HAVE_GMTIME_R
3843 timeptr = gmtime_r(&expiry_date, &gmt);
3844 #elif defined(MUTEX_LOCKS_AVAILABLE)
3845 privoxy_mutex_lock(&gmtime_mutex);
3846 timeptr = gmtime(&expiry_date);
3847 privoxy_mutex_unlock(&gmtime_mutex);
3849 timeptr = gmtime(&expiry_date);
3852 if (NULL == timeptr)
3854 log_error(LOG_LEVEL_FATAL,
3855 "Failed to get the time in add_cooky_expiry_date()");
3857 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
3858 if (JB_ERR_OK != string_append(cookie, tmp))
3860 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
3865 /*********************************************************************
3867 * Function : server_set_cookie
3869 * Description : Handle the server "cookie" header properly.
3870 * Crunch, accept or rewrite it to a session cookie.
3871 * Called from `sed'.
3874 * 1 : csp = Current client state (buffers, headers, etc...)
3875 * 2 : header = On input, pointer to header to modify.
3876 * On output, pointer to the modified header, or NULL
3877 * to remove the header. This function frees the
3878 * original string if necessary.
3880 * Returns : JB_ERR_OK on success, or
3881 * JB_ERR_MEMORY on out-of-memory error.
3883 *********************************************************************/
3884 static jb_err server_set_cookie(struct client_state *csp, char **header)
3886 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
3888 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3891 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
3892 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
3896 long cookie_lifetime = 0;
3897 int expiry_date_acceptable = 0;
3899 /* A variable to store the tag we're working on */
3902 /* Skip "Set-Cookie:" (11 characters) in header */
3903 cur_tag = *header + 11;
3905 /* skip whitespace between "Set-Cookie:" and value */
3906 while (*cur_tag && privoxy_isspace(*cur_tag))
3913 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
3915 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
3917 cookie_lifetime = strtol(param, NULL, 0);
3918 if (cookie_lifetime < 0)
3920 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
3922 cookie_lifetime *= 60U;
3925 /* Loop through each tag in the cookie */
3929 char *next_tag = strchr(cur_tag, ';');
3930 if (next_tag != NULL)
3932 /* Skip the ';' character itself */
3935 /* skip whitespace ";" and start of tag */
3936 while (*next_tag && privoxy_isspace(*next_tag))
3943 /* "Next tag" is the end of the string */
3944 next_tag = cur_tag + strlen(cur_tag);
3948 * Check the expiration date to see
3949 * if the cookie is still valid, if yes,
3950 * rewrite it to a session cookie.
3952 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3954 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3956 if ((expiration_date[0] == '"')
3957 && (expiration_date[1] != '\0'))
3960 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
3961 * that the expiration date isn't supposed to be quoted,
3962 * but some servers do it anyway.
3967 /* Did we detect the date properly? */
3968 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3971 * Nope, treat it as if it was still valid.
3973 * XXX: Should we remove the whole cookie instead?
3975 log_error(LOG_LEVEL_ERROR,
3976 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3977 string_move(cur_tag, next_tag);
3978 expiry_date_acceptable = 0;
3983 * Yes. Check if the cookie is still valid.
3985 * If the cookie is already expired it's probably
3986 * a delete cookie and even if it isn't, the browser
3987 * will discard it anyway.
3991 * XXX: timegm() isn't available on some AmigaOS
3992 * versions and our replacement doesn't work.
3994 * Our options are to either:
3996 * - disable session-cookies-only completely if timegm
3999 * - to simply remove all expired tags, like it has
4000 * been done until Privoxy 3.0.6 and to live with
4001 * the consequence that it can cause login/logout
4002 * problems on servers that don't validate their
4003 * input properly, or
4005 * - to replace it with mktime in which
4006 * case there is a slight chance of valid cookies
4007 * passing as already expired.
4009 * This is the way it's currently done and it's not
4010 * as bad as it sounds. If the missing GMT offset is
4011 * enough to change the result of the expiration check
4012 * the cookie will be only valid for a few hours
4013 * anyway, which in many cases will be shorter
4014 * than a browser session.
4016 if (cookie_time < now)
4018 log_error(LOG_LEVEL_HEADER,
4019 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4020 /* Just in case some clown sets more then one expiration date */
4022 expiry_date_acceptable = 1;
4024 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4026 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4027 "Its lifetime is below the limit.", *header);
4028 /* Just in case some clown sets more then one expiration date */
4030 expiry_date_acceptable = 1;
4035 * Still valid, delete expiration date by copying
4036 * the rest of the string over it.
4038 string_move(cur_tag, next_tag);
4040 /* That changed the header, need to issue a log message */
4041 expiry_date_acceptable = 0;
4044 * Note that the next tag has now been moved to *cur_tag,
4045 * so we do not need to update the cur_tag pointer.
4053 /* Move on to next cookie tag */
4058 if (!expiry_date_acceptable)
4060 assert(NULL != *header);
4061 if (cookie_lifetime == 0)
4063 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4068 add_cookie_expiry_date(header, cookie_lifetime);
4069 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4078 #ifdef FEATURE_FORCE_LOAD
4079 /*********************************************************************
4081 * Function : strclean
4083 * Description : In-Situ-Eliminate all occurrences of substring in
4087 * 1 : string = string to clean
4088 * 2 : substring = substring to eliminate
4090 * Returns : Number of eliminations
4092 *********************************************************************/
4093 int strclean(char *string, const char *substring)
4099 len = strlen(substring);
4101 while((pos = strstr(string, substring)) != NULL)
4108 while (*p++ != '\0');
4115 #endif /* def FEATURE_FORCE_LOAD */
4118 /*********************************************************************
4120 * Function : parse_header_time
4122 * Description : Parses time formats used in HTTP header strings
4123 * to get the numerical respresentation.
4126 * 1 : header_time = HTTP header time as string.
4127 * 2 : result = storage for header_time in seconds
4129 * Returns : JB_ERR_OK if the time format was recognized, or
4130 * JB_ERR_PARSE otherwise.
4132 *********************************************************************/
4133 static jb_err parse_header_time(const char *header_time, time_t *result)
4137 * Checking for two-digit years first in an
4138 * attempt to work around GNU libc's strptime()
4139 * reporting negative year values when using %Y.
4141 static const char time_formats[][22] = {
4142 /* Tue, 02-Jun-37 20:00:00 */
4143 "%a, %d-%b-%y %H:%M:%S",
4144 /* Tue, 02 Jun 2037 20:00:00 */
4145 "%a, %d %b %Y %H:%M:%S",
4146 /* Tue, 02-Jun-2037 20:00:00 */
4147 "%a, %d-%b-%Y %H:%M:%S",
4148 /* Tuesday, 02-Jun-2037 20:00:00 */
4149 "%A, %d-%b-%Y %H:%M:%S",
4150 /* Tuesday Jun 02 20:00:00 2037 */
4151 "%A %b %d %H:%M:%S %Y"
4155 for (i = 0; i < SZ(time_formats); i++)
4158 * Zero out gmt to prevent time zone offsets.
4159 * Documented to be required for GNU libc.
4161 memset(&gmt, 0, sizeof(gmt));
4163 if (NULL != strptime(header_time, time_formats[i], &gmt))
4165 /* Sanity check for GNU libc. */
4166 if (gmt.tm_year < 0)
4168 log_error(LOG_LEVEL_HEADER,
4169 "Failed to parse '%s' using '%s'. Moving on.",
4170 header_time, time_formats[i]);
4173 *result = timegm(&gmt);
4178 return JB_ERR_PARSE;
4183 /*********************************************************************
4185 * Function : get_destination_from_headers
4187 * Description : Parse the "Host:" header to get the request's destination.
4188 * Only needed if the client's request was forcefully
4189 * redirected into Privoxy.
4191 * Code mainly copied from client_host() which is currently
4192 * run too late for this purpose.
4195 * 1 : headers = List of headers (one of them hopefully being
4196 * the "Host:" header)
4197 * 2 : http = storage for the result (host, port and hostport).
4199 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4200 * JB_ERR_PARSE if the host header couldn't be found,
4201 * JB_ERR_OK otherwise.
4203 *********************************************************************/
4204 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4210 host = get_header_value(headers, "Host:");
4214 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4215 return JB_ERR_PARSE;
4218 p = strdup_or_die(host);
4220 q = strdup_or_die(p);
4222 freez(http->hostport);
4226 q = strchr(http->host, ':');
4229 /* Terminate hostname and evaluate port string */
4231 http->port = atoi(q);
4235 http->port = http->ssl ? 443 : 80;
4238 /* Rebuild request URL */
4240 http->url = strdup(http->ssl ? "https://" : "http://");
4241 string_append(&http->url, http->hostport);
4242 string_append(&http->url, http->path);
4243 if (http->url == NULL)
4245 return JB_ERR_MEMORY;
4248 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4256 /*********************************************************************
4258 * Function : create_forged_referrer
4260 * Description : Helper for client_referrer to forge a referer as
4261 * 'http://hostname[:port]/' to fool stupid
4262 * checks for in-site links
4265 * 1 : header = Pointer to header pointer
4266 * 2 : hostport = Host and optionally port as string
4268 * Returns : JB_ERR_OK in case of success, or
4269 * JB_ERR_MEMORY in case of memory problems.
4271 *********************************************************************/
4272 static jb_err create_forged_referrer(char **header, const char *hostport)
4274 assert(NULL == *header);
4276 *header = strdup("Referer: http://");
4277 string_append(header, hostport);
4278 string_append(header, "/");
4280 if (NULL == *header)
4282 return JB_ERR_MEMORY;
4285 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4292 /*********************************************************************
4294 * Function : create_fake_referrer
4296 * Description : Helper for client_referrer to create a fake referrer
4297 * based on a string supplied by the user.
4300 * 1 : header = Pointer to header pointer
4301 * 2 : hosthost = Referrer to fake
4303 * Returns : JB_ERR_OK in case of success, or
4304 * JB_ERR_MEMORY in case of memory problems.
4306 *********************************************************************/
4307 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4309 assert(NULL == *header);
4311 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4313 log_error(LOG_LEVEL_HEADER,
4314 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4316 *header = strdup("Referer: ");
4317 string_append(header, fake_referrer);
4319 if (NULL == *header)
4321 return JB_ERR_MEMORY;
4324 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4331 /*********************************************************************
4333 * Function : handle_conditional_hide_referrer_parameter
4335 * Description : Helper for client_referrer to crunch or forge
4336 * the referrer header if the host has changed.
4339 * 1 : header = Pointer to header pointer
4340 * 2 : host = The target host (may include the port)
4341 * 3 : parameter_conditional_block = Boolean to signal
4342 * if we're in conditional-block mode. If not set,
4343 * we're in conditional-forge mode.
4345 * Returns : JB_ERR_OK in case of success, or
4346 * JB_ERR_MEMORY in case of memory problems.
4348 *********************************************************************/
4349 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4350 const char *host, const int parameter_conditional_block)
4352 char *referer = strdup_or_die(*header);
4353 const size_t hostlength = strlen(host);
4354 const char *referer_url = NULL;
4356 /* referer begins with 'Referer: http[s]://' */
4357 if ((hostlength+17) < strlen(referer))
4360 * Shorten referer to make sure the referer is blocked
4361 * if www.example.org/www.example.com-shall-see-the-referer/
4362 * links to www.example.com/
4364 referer[hostlength+17] = '\0';
4366 referer_url = strstr(referer, "http://");
4367 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4369 /* Host has changed, Referer is invalid or a https URL. */
4370 if (parameter_conditional_block)
4372 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4379 return create_forged_referrer(header, host);
4389 /*********************************************************************
4391 * Function : create_content_length_header
4393 * Description : Creates a Content-Length header.
4396 * 1 : content_length = The content length to be used in the header.
4397 * 2 : header = Allocated space to safe the header.
4398 * 3 : buffer_length = The length of the allocated space.
4402 *********************************************************************/
4403 static void create_content_length_header(unsigned long long content_length,
4404 char *header, size_t buffer_length)
4406 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4410 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4411 /*********************************************************************
4413 * Function : get_expected_content_length
4415 * Description : Figures out the content length from a list of headers.
4418 * 1 : headers = List of headers
4420 * Returns : Number of bytes to expect
4422 *********************************************************************/
4423 unsigned long long get_expected_content_length(struct list *headers)
4425 const char *content_length_header;
4426 unsigned long long content_length = 0;
4428 content_length_header = get_header_value(headers, "Content-Length:");
4429 if (content_length_header != NULL)
4431 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4433 log_error(LOG_LEVEL_ERROR,
4434 "Failed to get the Content-Length in %s", content_length_header);
4435 /* XXX: The header will be removed later on */
4440 return content_length;