1 const char parsers_rcs[] = "$Id: parsers.c,v 1.265 2012/11/24 13:57:30 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
8 * Copyright : Written by and Copyright (C) 2001-2012 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
40 #include <sys/types.h>
50 * Convince GNU's libc to provide a strptime prototype.
59 #define GZIP_IDENTIFIER_1 0x1f
60 #define GZIP_IDENTIFIER_2 0x8b
62 #define GZIP_FLAG_CHECKSUM 0x02
63 #define GZIP_FLAG_EXTRA_FIELDS 0x04
64 #define GZIP_FLAG_FILE_NAME 0x08
65 #define GZIP_FLAG_COMMENT 0x10
66 #define GZIP_FLAG_RESERVED_BITS 0xe0
69 #if !defined(_WIN32) && !defined(__OS2__)
75 #ifdef FEATURE_PTHREAD
77 /* jcc.h is for mutex semapores only */
78 #endif /* def FEATURE_PTHREAD */
83 #include "jbsockets.h"
93 const char parsers_h_rcs[] = PARSERS_H_VERSION;
95 static char *get_header_line(struct iob *iob);
96 static jb_err scan_headers(struct client_state *csp);
97 static jb_err header_tagger(struct client_state *csp, char *header);
98 static jb_err parse_header_time(const char *header_time, time_t *result);
100 static jb_err crumble (struct client_state *csp, char **header);
101 static jb_err filter_header (struct client_state *csp, char **header);
102 static jb_err client_connection (struct client_state *csp, char **header);
103 static jb_err client_referrer (struct client_state *csp, char **header);
104 static jb_err client_uagent (struct client_state *csp, char **header);
105 static jb_err client_ua (struct client_state *csp, char **header);
106 static jb_err client_from (struct client_state *csp, char **header);
107 static jb_err client_send_cookie (struct client_state *csp, char **header);
108 static jb_err client_x_forwarded (struct client_state *csp, char **header);
109 static jb_err client_accept_encoding (struct client_state *csp, char **header);
110 static jb_err client_te (struct client_state *csp, char **header);
111 static jb_err client_max_forwards (struct client_state *csp, char **header);
112 static jb_err client_host (struct client_state *csp, char **header);
113 static jb_err client_if_modified_since (struct client_state *csp, char **header);
114 static jb_err client_accept_language (struct client_state *csp, char **header);
115 static jb_err client_if_none_match (struct client_state *csp, char **header);
116 static jb_err crunch_client_header (struct client_state *csp, char **header);
117 static jb_err client_x_filter (struct client_state *csp, char **header);
118 static jb_err client_range (struct client_state *csp, char **header);
119 static jb_err server_set_cookie (struct client_state *csp, char **header);
120 static jb_err server_connection (struct client_state *csp, char **header);
121 static jb_err server_content_type (struct client_state *csp, char **header);
122 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
123 static jb_err server_content_md5 (struct client_state *csp, char **header);
124 static jb_err server_content_encoding (struct client_state *csp, char **header);
125 static jb_err server_transfer_coding (struct client_state *csp, char **header);
126 static jb_err server_http (struct client_state *csp, char **header);
127 static jb_err crunch_server_header (struct client_state *csp, char **header);
128 static jb_err server_last_modified (struct client_state *csp, char **header);
129 static jb_err server_content_disposition(struct client_state *csp, char **header);
131 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
134 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
135 static jb_err server_save_content_length(struct client_state *csp, char **header);
136 static jb_err server_keep_alive(struct client_state *csp, char **header);
137 static jb_err server_proxy_connection(struct client_state *csp, char **header);
138 static jb_err client_keep_alive(struct client_state *csp, char **header);
139 static jb_err client_save_content_length(struct client_state *csp, char **header);
140 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
142 static jb_err client_host_adder (struct client_state *csp);
143 static jb_err client_xtra_adder (struct client_state *csp);
144 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
145 static jb_err client_connection_header_adder(struct client_state *csp);
146 static jb_err server_connection_adder(struct client_state *csp);
147 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
148 static jb_err server_proxy_connection_adder(struct client_state *csp);
149 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
151 static jb_err create_forged_referrer(char **header, const char *hostport);
152 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
153 static jb_err handle_conditional_hide_referrer_parameter(char **header,
154 const char *host, const int parameter_conditional_block);
155 static void create_content_length_header(unsigned long long content_length,
156 char *header, size_t buffer_length);
159 * List of functions to run on a list of headers.
163 /** The header prefix to match */
166 /** The length of the prefix to match */
169 /** The function to apply to this line */
170 const parser_func_ptr parser;
173 static const struct parsers client_patterns[] = {
174 { "referer:", 8, client_referrer },
175 { "user-agent:", 11, client_uagent },
176 { "ua-", 3, client_ua },
177 { "from:", 5, client_from },
178 { "cookie:", 7, client_send_cookie },
179 { "x-forwarded-for:", 16, client_x_forwarded },
180 { "Accept-Encoding:", 16, client_accept_encoding },
181 { "TE:", 3, client_te },
182 { "Host:", 5, client_host },
183 { "if-modified-since:", 18, client_if_modified_since },
184 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
185 { "Keep-Alive:", 11, client_keep_alive },
186 { "Content-Length:", 15, client_save_content_length },
188 { "Keep-Alive:", 11, crumble },
190 { "connection:", 11, client_connection },
191 { "proxy-connection:", 17, crumble },
192 { "max-forwards:", 13, client_max_forwards },
193 { "Accept-Language:", 16, client_accept_language },
194 { "if-none-match:", 14, client_if_none_match },
195 { "Range:", 6, client_range },
196 { "Request-Range:", 14, client_range },
197 { "If-Range:", 9, client_range },
198 { "X-Filter:", 9, client_x_filter },
199 { "*", 0, crunch_client_header },
200 { "*", 0, filter_header },
204 static const struct parsers server_patterns[] = {
205 { "HTTP/", 5, server_http },
206 { "set-cookie:", 11, server_set_cookie },
207 { "connection:", 11, server_connection },
208 { "Content-Type:", 13, server_content_type },
209 { "Content-MD5:", 12, server_content_md5 },
210 { "Content-Encoding:", 17, server_content_encoding },
211 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
212 { "Content-Length:", 15, server_save_content_length },
213 { "Keep-Alive:", 11, server_keep_alive },
214 { "Proxy-Connection:", 17, server_proxy_connection },
216 { "Keep-Alive:", 11, crumble },
217 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
218 { "Transfer-Encoding:", 18, server_transfer_coding },
219 { "content-disposition:", 20, server_content_disposition },
220 { "Last-Modified:", 14, server_last_modified },
221 { "*", 0, crunch_server_header },
222 { "*", 0, filter_header },
226 static const add_header_func_ptr add_client_headers[] = {
228 client_x_forwarded_for_adder,
230 client_connection_header_adder,
234 static const add_header_func_ptr add_server_headers[] = {
235 server_connection_adder,
236 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
237 server_proxy_connection_adder,
238 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
242 /*********************************************************************
244 * Function : flush_socket
246 * Description : Write any pending "buffered" content.
249 * 1 : fd = file descriptor of the socket to read
250 * 2 : iob = The I/O buffer to flush, usually csp->iob.
252 * Returns : On success, the number of bytes written are returned (zero
253 * indicates nothing was written). On error, -1 is returned,
254 * and errno is set appropriately. If count is zero and the
255 * file descriptor refers to a regular file, 0 will be
256 * returned without causing any other effect. For a special
257 * file, the results are not portable.
259 *********************************************************************/
260 long flush_socket(jb_socket fd, struct iob *iob)
262 long len = iob->eod - iob->cur;
269 if (write_socket(fd, iob->cur, (size_t)len))
273 iob->eod = iob->cur = iob->buf;
279 /*********************************************************************
281 * Function : add_to_iob
283 * Description : Add content to the buffer, expanding the
284 * buffer if necessary.
287 * 1 : iob = Destination buffer.
288 * 2 : buffer_limit = Limit to which the destination may grow
289 * 3 : src = holds the content to be added
290 * 4 : n = number of bytes to be added
292 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
293 * or buffer limit reached.
295 *********************************************************************/
296 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
298 size_t used, offset, need;
301 if (n <= 0) return JB_ERR_OK;
303 used = (size_t)(iob->eod - iob->buf);
304 offset = (size_t)(iob->cur - iob->buf);
305 need = used + (size_t)n + 1;
308 * If the buffer can't hold the new data, extend it first.
309 * Use the next power of two if possible, else use the actual need.
311 if (need > buffer_limit)
313 log_error(LOG_LEVEL_INFO,
314 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
316 return JB_ERR_MEMORY;
319 if (need > iob->size)
321 size_t want = iob->size ? iob->size : 512;
328 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
332 else if (NULL != (p = (char *)realloc(iob->buf, need)))
338 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
339 return JB_ERR_MEMORY;
342 /* Update the iob pointers */
343 iob->cur = p + offset;
348 /* copy the new data into the iob buffer */
349 memcpy(iob->eod, src, (size_t)n);
351 /* point to the end of the data */
354 /* null terminate == cheap insurance */
362 /*********************************************************************
364 * Function : clear_iob
366 * Description : Frees the memory allocated for an I/O buffer and
367 * resets the structure.
370 * 1 : iob = I/O buffer to clear.
372 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
373 * or buffer limit reached.
375 *********************************************************************/
376 void clear_iob(struct iob *iob)
379 memset(iob, '\0', sizeof(*iob));;
384 /*********************************************************************
386 * Function : decompress_iob
388 * Description : Decompress buffered page, expanding the
389 * buffer as necessary. csp->iob->cur
390 * should point to the the beginning of the
391 * compressed data block.
394 * 1 : csp = Current client state (buffers, headers, etc...)
396 * Returns : JB_ERR_OK on success,
397 * JB_ERR_MEMORY if out-of-memory limit reached, and
398 * JB_ERR_COMPRESS if error decompressing buffer.
400 *********************************************************************/
401 jb_err decompress_iob(struct client_state *csp)
403 char *buf; /* new, uncompressed buffer */
404 char *cur; /* Current iob position (to keep the original
405 * iob->cur unmodified if we return early) */
406 size_t bufsize; /* allocated size of the new buffer */
407 size_t old_size; /* Content size before decompression */
408 size_t skip_size; /* Number of bytes at the beginning of the iob
409 that we should NOT decompress. */
410 int status; /* return status of the inflate() call */
411 z_stream zstr; /* used by calls to zlib */
413 assert(csp->iob->cur - csp->iob->buf > 0);
414 assert(csp->iob->eod - csp->iob->cur > 0);
416 bufsize = csp->iob->size;
417 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
418 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
422 if (bufsize < (size_t)10)
425 * This is to protect the parsing of gzipped data,
426 * but it should(?) be valid for deflated data also.
428 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
429 return JB_ERR_COMPRESS;
432 if (csp->content_type & CT_GZIP)
435 * Our task is slightly complicated by the facts that data
436 * compressed by gzip does not include a zlib header, and
437 * that there is no easily accessible interface in zlib to
438 * handle a gzip header. We strip off the gzip header by
439 * hand, and later inform zlib not to expect a header.
443 * Strip off the gzip header. Please see RFC 1952 for more
444 * explanation of the appropriate fields.
446 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
447 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
448 || (*cur++ != Z_DEFLATED))
450 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
451 return JB_ERR_COMPRESS;
456 if (flags & GZIP_FLAG_RESERVED_BITS)
458 /* The gzip header has reserved bits set; bail out. */
459 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
460 return JB_ERR_COMPRESS;
464 * Skip mtime (4 bytes), extra flags (1 byte)
465 * and OS type (1 byte).
469 /* Skip extra fields if necessary. */
470 if (flags & GZIP_FLAG_EXTRA_FIELDS)
473 * Skip a given number of bytes, specified
474 * as a 16-bit little-endian value.
476 * XXX: this code is untested and should probably be removed.
480 skip_bytes += *cur++ << 8;
483 * The number of bytes to skip should be positive
484 * and we'd like to stay in the buffer.
486 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
488 log_error(LOG_LEVEL_ERROR,
489 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
491 return JB_ERR_COMPRESS;
493 log_error(LOG_LEVEL_INFO,
494 "Skipping %d bytes for gzip compression. Does this sound right?",
499 /* Skip the filename if necessary. */
500 if (flags & GZIP_FLAG_FILE_NAME)
502 /* A null-terminated string is supposed to follow. */
503 while (*cur++ && (cur < csp->iob->eod));
506 /* Skip the comment if necessary. */
507 if (flags & GZIP_FLAG_COMMENT)
509 /* A null-terminated string is supposed to follow. */
510 while (*cur++ && (cur < csp->iob->eod));
513 /* Skip the CRC if necessary. */
514 if (flags & GZIP_FLAG_CHECKSUM)
519 if (cur >= csp->iob->eod)
522 * If the current position pointer reached or passed
523 * the buffer end, we were obviously tricked to skip
526 log_error(LOG_LEVEL_ERROR,
527 "Malformed gzip header detected. Aborting decompression.");
528 return JB_ERR_COMPRESS;
532 else if (csp->content_type & CT_DEFLATE)
535 * In theory (that is, according to RFC 1950), deflate-compressed
536 * data should begin with a two-byte zlib header and have an
537 * adler32 checksum at the end. It seems that in practice only
538 * the raw compressed data is sent. Note that this means that
539 * we are not RFC 1950-compliant here, but the advantage is that
540 * this actually works. :)
542 * We add a dummy null byte to tell zlib where the data ends,
543 * and later inform it not to expect a header.
545 * Fortunately, add_to_iob() has thoughtfully null-terminated
546 * the buffer; we can just increment the end pointer to include
553 log_error(LOG_LEVEL_ERROR,
554 "Unable to determine compression format for decompression");
555 return JB_ERR_COMPRESS;
558 /* Set up the fields required by zlib. */
559 zstr.next_in = (Bytef *)cur;
560 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
561 zstr.zalloc = Z_NULL;
563 zstr.opaque = Z_NULL;
566 * Passing -MAX_WBITS to inflateInit2 tells the library
567 * that there is no zlib header.
569 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
571 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
572 return JB_ERR_COMPRESS;
576 * Next, we allocate new storage for the inflated data.
577 * We don't modify the existing iob yet, so in case there
578 * is error in decompression we can recover gracefully.
580 buf = zalloc(bufsize);
583 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
584 return JB_ERR_MEMORY;
587 assert(bufsize >= skip_size);
588 memcpy(buf, csp->iob->buf, skip_size);
589 zstr.avail_out = (uInt)(bufsize - skip_size);
590 zstr.next_out = (Bytef *)buf + skip_size;
592 /* Try to decompress the whole stream in one shot. */
593 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
595 /* We need to allocate more memory for the output buffer. */
597 char *tmpbuf; /* used for realloc'ing the buffer */
598 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
600 if (0 == zstr.avail_in)
603 * If zlib wants more data then there's a problem, because
604 * the complete compressed file should have been buffered.
606 log_error(LOG_LEVEL_ERROR,
607 "Unexpected end of compressed iob. Using what we got so far.");
612 * If we reached the buffer limit and still didn't have enough
613 * memory, just give up. Due to the ceiling enforced by the next
614 * if block we could actually check for equality here, but as it
615 * can be easily mistaken for a bug we don't.
617 if (bufsize >= csp->config->buffer_limit)
619 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
620 return JB_ERR_MEMORY;
623 /* Try doubling the buffer size each time. */
626 /* Don't exceed the buffer limit. */
627 if (bufsize > csp->config->buffer_limit)
629 bufsize = csp->config->buffer_limit;
632 /* Try to allocate the new buffer. */
633 tmpbuf = realloc(buf, bufsize);
636 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
638 return JB_ERR_MEMORY;
642 char *oldnext_out = (char *)zstr.next_out;
645 * Update the fields for inflate() to use the new
646 * buffer, which may be in a location different from
649 zstr.avail_out += (uInt)(bufsize - oldbufsize);
650 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
653 * Compare with an uglier method of calculating these values
654 * that doesn't require the extra oldbufsize variable.
656 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
657 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
663 if (Z_STREAM_ERROR == inflateEnd(&zstr))
665 log_error(LOG_LEVEL_ERROR,
666 "Inconsistent stream state after decompression: %s", zstr.msg);
668 * XXX: Intentionally no return.
670 * According to zlib.h, Z_STREAM_ERROR is returned
671 * "if the stream state was inconsistent".
673 * I assume in this case inflate()'s status
674 * would also be something different than Z_STREAM_END
675 * so this check should be redundant, but lets see.
679 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
682 * We failed to decompress the stream and it's
683 * not simply because of missing data.
685 log_error(LOG_LEVEL_ERROR,
686 "Unexpected error while decompressing to the buffer (iob): %s",
688 return JB_ERR_COMPRESS;
692 * Finally, we can actually update the iob, since the
693 * decompression was successful. First, free the old
696 freez(csp->iob->buf);
698 /* Now, update the iob to use the new buffer. */
700 csp->iob->cur = csp->iob->buf + skip_size;
701 csp->iob->eod = (char *)zstr.next_out;
702 csp->iob->size = bufsize;
705 * Make sure the new uncompressed iob obeys some minimal
706 * consistency conditions.
708 if ((csp->iob->buf < csp->iob->cur)
709 && (csp->iob->cur <= csp->iob->eod)
710 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
712 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
713 if (new_size > (size_t)0)
715 log_error(LOG_LEVEL_RE_FILTER,
716 "Decompression successful. Old size: %d, new size: %d.",
721 /* zlib thinks this is OK, so lets do the same. */
722 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
727 /* It seems that zlib did something weird. */
728 log_error(LOG_LEVEL_ERROR,
729 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
730 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
731 csp->iob->eod, csp->iob->buf + csp->iob->size);
732 return JB_ERR_COMPRESS;
738 #endif /* defined(FEATURE_ZLIB) */
741 /*********************************************************************
743 * Function : normalize_lws
745 * Description : Reduces unquoted linear white space in headers
746 * to a single space in accordance with RFC 2616 2.2.
747 * This simplifies parsing and filtering later on.
749 * XXX: Remove log messages before
750 * the next stable release?
753 * 1 : header = A header with linear white space to reduce.
757 *********************************************************************/
758 static void normalize_lws(char *header)
764 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
768 while (privoxy_isspace(*q))
772 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
778 log_error(LOG_LEVEL_HEADER,
779 "Converting tab to space in '%s'", header);
784 char *end_of_token = strstr(p+1, "\"");
786 if (NULL != end_of_token)
788 /* Don't mess with quoted text. */
793 log_error(LOG_LEVEL_HEADER,
794 "Ignoring single quote in '%s'", header);
800 p = strchr(header, ':');
801 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
804 * There's still space before the colon.
812 /*********************************************************************
814 * Function : get_header
816 * Description : This (odd) routine will parse the csp->iob
817 * to get the next complete header.
820 * 1 : iob = The I/O buffer to parse, usually csp->iob.
822 * Returns : Any one of the following:
824 * 1) a pointer to a dynamically allocated string that contains a header line
825 * 2) NULL indicating that the end of the header was reached
826 * 3) "" indicating that the end of the iob was reached before finding
827 * a complete header line.
829 *********************************************************************/
830 char *get_header(struct iob *iob)
834 header = get_header_line(iob);
836 if ((header == NULL) || (*header == '\0'))
839 * No complete header read yet, tell the client.
844 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
847 * Header spans multiple lines, append the next one.
849 char *continued_header;
851 continued_header = get_header_line(iob);
852 if ((continued_header == NULL) || (*continued_header == '\0'))
855 * No complete header read yet, return what we got.
856 * XXX: Should "unread" header instead.
858 log_error(LOG_LEVEL_INFO,
859 "Failed to read a multi-line header properly: '%s'",
864 if (JB_ERR_OK != string_join(&header, continued_header))
866 log_error(LOG_LEVEL_FATAL,
867 "Out of memory while appending multiple headers.");
871 /* XXX: remove before next stable release. */
872 log_error(LOG_LEVEL_HEADER,
873 "Merged multiple header lines to: '%s'",
878 normalize_lws(header);
885 /*********************************************************************
887 * Function : get_header_line
889 * Description : This (odd) routine will parse the csp->iob
890 * to get the next header line.
893 * 1 : iob = The I/O buffer to parse, usually csp->iob.
895 * Returns : Any one of the following:
897 * 1) a pointer to a dynamically allocated string that contains a header line
898 * 2) NULL indicating that the end of the header was reached
899 * 3) "" indicating that the end of the iob was reached before finding
900 * a complete header line.
902 *********************************************************************/
903 static char *get_header_line(struct iob *iob)
907 if ((iob->cur == NULL)
908 || ((p = strchr(iob->cur, '\n')) == NULL))
910 return(""); /* couldn't find a complete header */
915 ret = strdup(iob->cur);
918 /* FIXME No way to handle error properly */
919 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
925 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
927 /* is this a blank line (i.e. the end of the header) ? */
939 /*********************************************************************
941 * Function : get_header_value
943 * Description : Get the value of a given header from a chained list
944 * of header lines or return NULL if no such header is
945 * present in the list.
948 * 1 : header_list = pointer to list
949 * 2 : header_name = string with name of header to look for.
950 * Trailing colon required, capitalization
953 * Returns : NULL if not found, else value of header
955 *********************************************************************/
956 char *get_header_value(const struct list *header_list, const char *header_name)
958 struct list_entry *cur_entry;
964 length = strlen(header_name);
966 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
970 if (!strncmpic(cur_entry->str, header_name, length))
973 * Found: return pointer to start of value
975 ret = cur_entry->str + length;
976 while (*ret && privoxy_isspace(*ret)) ret++;
990 /*********************************************************************
992 * Function : scan_headers
994 * Description : Scans headers, applies tags and updates action bits.
997 * 1 : csp = Current client state (buffers, headers, etc...)
999 * Returns : JB_ERR_OK
1001 *********************************************************************/
1002 static jb_err scan_headers(struct client_state *csp)
1004 struct list_entry *h; /* Header */
1005 jb_err err = JB_ERR_OK;
1007 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1009 /* Header crunch()ed in previous run? -> ignore */
1010 if (h->str == NULL) continue;
1011 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1012 err = header_tagger(csp, h->str);
1019 /*********************************************************************
1021 * Function : enforce_header_order
1023 * Description : Enforces a given header order.
1026 * 1 : headers = List of headers to order.
1027 * 2 : ordered_headers = List of ordered header names.
1031 *********************************************************************/
1032 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1034 struct list_entry *sorted_header;
1035 struct list new_headers[1];
1036 struct list_entry *header;
1038 init_list(new_headers);
1040 /* The request line is always the first "header" */
1042 assert(NULL != headers->first->str);
1043 enlist(new_headers, headers->first->str);
1044 freez(headers->first->str)
1046 /* Enlist the specified headers in the given order */
1048 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1049 sorted_header = sorted_header->next)
1051 const size_t sorted_header_length = strlen(sorted_header->str);
1052 for (header = headers->first; header != NULL; header = header->next)
1054 /* Header enlisted in previous run? -> ignore */
1055 if (header->str == NULL) continue;
1057 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1058 && (header->str[sorted_header_length] == ':'))
1060 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1061 if (JB_ERR_OK != enlist(new_headers, header->str))
1063 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1070 /* Enlist the rest of the headers behind the ordered ones */
1071 for (header = headers->first; header != NULL; header = header->next)
1073 /* Header enlisted in previous run? -> ignore */
1074 if (header->str == NULL) continue;
1076 log_error(LOG_LEVEL_HEADER,
1077 "Enlisting left-over header %s", header->str);
1078 if (JB_ERR_OK != enlist(new_headers, header->str))
1080 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1085 list_remove_all(headers);
1086 list_duplicate(headers, new_headers);
1087 list_remove_all(new_headers);
1092 /*********************************************************************
1096 * Description : add, delete or modify lines in the HTTP header streams.
1097 * On entry, it receives a linked list of headers space
1098 * that was allocated dynamically (both the list nodes
1099 * and the header contents).
1101 * As a side effect it frees the space used by the original
1105 * 1 : csp = Current client state (buffers, headers, etc...)
1106 * 2 : filter_server_headers = Boolean to switch between
1107 * server and header filtering.
1109 * Returns : JB_ERR_OK in case off success, or
1110 * JB_ERR_MEMORY on out-of-memory error.
1112 *********************************************************************/
1113 jb_err sed(struct client_state *csp, int filter_server_headers)
1115 /* XXX: use more descriptive names. */
1116 struct list_entry *p;
1117 const struct parsers *v;
1118 const add_header_func_ptr *f;
1119 jb_err err = JB_ERR_OK;
1121 if (filter_server_headers)
1123 v = server_patterns;
1124 f = add_server_headers;
1128 v = client_patterns;
1129 f = add_client_headers;
1134 while ((err == JB_ERR_OK) && (v->str != NULL))
1136 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1138 /* Header crunch()ed in previous run? -> ignore */
1139 if (p->str == NULL) continue;
1141 /* Does the current parser handle this header? */
1142 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1143 (v->len == CHECK_EVERY_HEADER_REMAINING))
1145 err = v->parser(csp, &(p->str));
1151 /* place additional headers on the csp->headers list */
1152 while ((err == JB_ERR_OK) && (*f))
1158 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1160 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1167 /*********************************************************************
1169 * Function : update_server_headers
1171 * Description : Updates server headers after the body has been modified.
1174 * 1 : csp = Current client state (buffers, headers, etc...)
1176 * Returns : JB_ERR_OK in case off success, or
1177 * JB_ERR_MEMORY on out-of-memory error.
1179 *********************************************************************/
1180 jb_err update_server_headers(struct client_state *csp)
1182 jb_err err = JB_ERR_OK;
1184 static const struct parsers server_patterns_light[] = {
1185 { "Content-Length:", 15, server_adjust_content_length },
1186 { "Transfer-Encoding:", 18, server_transfer_coding },
1188 { "Content-Encoding:", 17, server_adjust_content_encoding },
1189 #endif /* def FEATURE_ZLIB */
1193 if (strncmpic(csp->http->cmd, "HEAD", 4))
1195 const struct parsers *v;
1196 struct list_entry *p;
1198 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1200 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1202 /* Header crunch()ed in previous run? -> ignore */
1203 if (p->str == NULL) continue;
1205 /* Does the current parser handle this header? */
1206 if (strncmpic(p->str, v->str, v->len) == 0)
1208 err = v->parser(csp, (char **)&(p->str));
1214 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1215 if ((JB_ERR_OK == err)
1216 && (csp->flags & CSP_FLAG_MODIFIED)
1217 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1218 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1222 create_content_length_header(csp->content_length, header, sizeof(header));
1223 err = enlist(csp->headers, header);
1224 if (JB_ERR_OK == err)
1226 log_error(LOG_LEVEL_HEADER,
1227 "Content modified with no Content-Length header set. "
1228 "Created: %s.", header);
1231 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1233 #ifdef FEATURE_COMPRESSION
1234 if ((JB_ERR_OK == err)
1235 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1237 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1238 if (JB_ERR_OK == err)
1240 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1249 /*********************************************************************
1251 * Function : header_tagger
1253 * Description : Executes all text substitutions from applying
1254 * tag actions and saves the result as tag.
1256 * XXX: Shares enough code with filter_header() and
1257 * pcrs_filter_response() to warrant some helper functions.
1260 * 1 : csp = Current client state (buffers, headers, etc...)
1261 * 2 : header = Header that is used as tagger input
1263 * Returns : JB_ERR_OK on success and always succeeds
1265 *********************************************************************/
1266 static jb_err header_tagger(struct client_state *csp, char *header)
1268 int wanted_filter_type;
1269 int multi_action_index;
1273 struct file_list *fl;
1274 struct re_filterfile_spec *b;
1275 struct list_entry *tag_name;
1277 const size_t header_length = strlen(header);
1279 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1281 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1282 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1286 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1287 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1290 if (filters_available(csp) == FALSE)
1292 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1293 "tagging enabled, but no taggers available.");
1297 for (i = 0; i < MAX_AF_FILES; i++)
1300 if ((NULL == fl) || (NULL == fl->f))
1303 * Either there are no filter files
1304 * left, or this filter file just
1305 * contains no valid filters.
1307 * Continue to be sure we don't miss
1308 * valid filter files that are chained
1309 * after empty or invalid ones.
1314 /* For all filters, */
1315 for (b = fl->f; b; b = b->next)
1317 if (b->type != wanted_filter_type)
1319 /* skip the ones we don't care about, */
1322 /* leaving only taggers that could apply, of which we use the ones, */
1323 for (tag_name = csp->action->multi[multi_action_index]->first;
1324 NULL != tag_name; tag_name = tag_name->next)
1326 /* that do apply, and */
1327 if (strcmp(b->name, tag_name->str) == 0)
1329 char *modified_tag = NULL;
1331 size_t size = header_length;
1332 pcrs_job *joblist = b->joblist;
1334 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1336 if (NULL == joblist)
1338 log_error(LOG_LEVEL_RE_FILTER,
1339 "Tagger %s has empty joblist. Nothing to do.", b->name);
1343 /* execute their pcrs_joblist on the header. */
1344 for (job = joblist; NULL != job; job = job->next)
1346 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1350 /* Success, continue with the modified version. */
1359 /* Tagger doesn't match */
1362 /* Regex failure, log it but continue anyway. */
1363 assert(NULL != header);
1364 log_error(LOG_LEVEL_ERROR,
1365 "Problems with tagger \'%s\' and header \'%s\': %s",
1366 b->name, *header, pcrs_strerror(hits));
1368 freez(modified_tag);
1372 if (b->dynamic) pcrs_free_joblist(joblist);
1374 /* If this tagger matched */
1380 * There is to technical limitation which makes
1381 * it impossible to use empty tags, but I assume
1382 * no one would do it intentionally.
1385 log_error(LOG_LEVEL_INFO,
1386 "Tagger \'%s\' created an empty tag. Ignored.",
1391 if (!list_contains_item(csp->tags, tag))
1393 if (JB_ERR_OK != enlist(csp->tags, tag))
1395 log_error(LOG_LEVEL_ERROR,
1396 "Insufficient memory to add tag \'%s\', "
1397 "based on tagger \'%s\' and header \'%s\'",
1398 tag, b->name, *header);
1402 char *action_message;
1404 * update the action bits right away, to make
1405 * tagging based on tags set by earlier taggers
1406 * of the same kind possible.
1408 if (update_action_bits_for_tag(csp, tag))
1410 action_message = "Action bits updated accordingly.";
1414 action_message = "No action bits update necessary.";
1417 log_error(LOG_LEVEL_HEADER,
1418 "Tagger \'%s\' added tag \'%s\'. %s",
1419 b->name, tag, action_message);
1424 /* XXX: Is this log-worthy? */
1425 log_error(LOG_LEVEL_HEADER,
1426 "Tagger \'%s\' didn't add tag \'%s\'. "
1427 "Tag already present", b->name, tag);
1430 } /* if the tagger matched */
1431 } /* if the tagger applies */
1432 } /* for every tagger that could apply */
1433 } /* for all filters */
1434 } /* for all filter files */
1439 /* here begins the family of parser functions that reformat header lines */
1441 /*********************************************************************
1443 * Function : filter_header
1445 * Description : Executes all text substitutions from all applying
1446 * +(server|client)-header-filter actions on the header.
1447 * Most of the code was copied from pcrs_filter_response,
1448 * including the rather short variable names
1451 * 1 : csp = Current client state (buffers, headers, etc...)
1452 * 2 : header = On input, pointer to header to modify.
1453 * On output, pointer to the modified header, or NULL
1454 * to remove the header. This function frees the
1455 * original string if necessary.
1457 * Returns : JB_ERR_OK on success and always succeeds
1459 *********************************************************************/
1460 static jb_err filter_header(struct client_state *csp, char **header)
1464 size_t size = strlen(*header);
1466 char *newheader = NULL;
1469 struct file_list *fl;
1470 struct re_filterfile_spec *b;
1471 struct list_entry *filtername;
1474 int wanted_filter_type;
1475 int multi_action_index;
1477 if (csp->flags & CSP_FLAG_NO_FILTERING)
1482 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1484 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1485 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1489 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1490 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1493 if (filters_available(csp) == FALSE)
1495 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1496 "header filtering enabled, but no matching filters available.");
1500 for (i = 0; i < MAX_AF_FILES; i++)
1503 if ((NULL == fl) || (NULL == fl->f))
1506 * Either there are no filter files
1507 * left, or this filter file just
1508 * contains no valid filters.
1510 * Continue to be sure we don't miss
1511 * valid filter files that are chained
1512 * after empty or invalid ones.
1517 * For all applying +filter actions, look if a filter by that
1518 * name exists and if yes, execute its pcrs_joblist on the
1521 for (b = fl->f; b; b = b->next)
1523 if (b->type != wanted_filter_type)
1525 /* Skip other filter types */
1529 for (filtername = csp->action->multi[multi_action_index]->first;
1530 filtername ; filtername = filtername->next)
1532 if (strcmp(b->name, filtername->str) == 0)
1534 int current_hits = 0;
1535 pcrs_job *joblist = b->joblist;
1537 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1539 if (NULL == joblist)
1541 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1545 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1546 *header, size, b->name);
1548 /* Apply all jobs from the joblist */
1549 for (job = joblist; NULL != job; job = job->next)
1551 matches = pcrs_execute(job, *header, size, &newheader, &size);
1554 current_hits += matches;
1555 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1557 *header = newheader;
1559 else if (0 == matches)
1561 /* Filter doesn't change header */
1567 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1568 *header, b->name, pcrs_strerror(matches));
1569 if (newheader != NULL)
1571 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1577 if (b->dynamic) pcrs_free_joblist(joblist);
1579 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1580 hits += current_hits;
1587 * Additionally checking for hits is important because if
1588 * the continue hack is triggered, server headers can
1589 * arrive empty to separate multiple heads from each other.
1591 if ((0 == size) && hits)
1593 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1601 /*********************************************************************
1603 * Function : server_connection
1605 * Description : Makes sure a proper "Connection:" header is
1606 * set and signals connection_header_adder to
1610 * 1 : csp = Current client state (buffers, headers, etc...)
1611 * 2 : header = On input, pointer to header to modify.
1612 * On output, pointer to the modified header, or NULL
1613 * to remove the header. This function frees the
1614 * original string if necessary.
1616 * Returns : JB_ERR_OK on success.
1618 *********************************************************************/
1619 static jb_err server_connection(struct client_state *csp, char **header)
1621 if (!strcmpic(*header, "Connection: keep-alive")
1622 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1623 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1627 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1628 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1630 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1633 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1635 log_error(LOG_LEVEL_HEADER,
1636 "Keeping the server header '%s' around.", *header);
1639 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1641 char *old_header = *header;
1643 *header = strdup_or_die("Connection: close");
1644 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1649 /* Signal server_connection_adder() to return early. */
1650 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1656 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1657 /*********************************************************************
1659 * Function : server_keep_alive
1661 * Description : Stores the server's keep alive timeout.
1664 * 1 : csp = Current client state (buffers, headers, etc...)
1665 * 2 : header = On input, pointer to header to modify.
1666 * On output, pointer to the modified header, or NULL
1667 * to remove the header. This function frees the
1668 * original string if necessary.
1670 * Returns : JB_ERR_OK.
1672 *********************************************************************/
1673 static jb_err server_keep_alive(struct client_state *csp, char **header)
1675 unsigned int keep_alive_timeout;
1676 const char *timeout_position = strstr(*header, "timeout=");
1678 if ((NULL == timeout_position)
1679 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1681 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1685 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1687 log_error(LOG_LEVEL_HEADER,
1688 "Reducing keep-alive timeout from %u to %u.",
1689 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1690 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1694 /* XXX: Is this log worthy? */
1695 log_error(LOG_LEVEL_HEADER,
1696 "Server keep-alive timeout is %u. Sticking with %u.",
1697 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1699 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1706 /*********************************************************************
1708 * Function : server_proxy_connection
1710 * Description : Figures out whether or not we should add a
1711 * Proxy-Connection header.
1714 * 1 : csp = Current client state (buffers, headers, etc...)
1715 * 2 : header = On input, pointer to header to modify.
1716 * On output, pointer to the modified header, or NULL
1717 * to remove the header. This function frees the
1718 * original string if necessary.
1720 * Returns : JB_ERR_OK.
1722 *********************************************************************/
1723 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1725 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1730 /*********************************************************************
1732 * Function : client_keep_alive
1734 * Description : Stores the client's keep alive timeout.
1737 * 1 : csp = Current client state (buffers, headers, etc...)
1738 * 2 : header = On input, pointer to header to modify.
1739 * On output, pointer to the modified header, or NULL
1740 * to remove the header. This function frees the
1741 * original string if necessary.
1743 * Returns : JB_ERR_OK.
1745 *********************************************************************/
1746 static jb_err client_keep_alive(struct client_state *csp, char **header)
1748 unsigned int keep_alive_timeout;
1749 const char *timeout_position = strstr(*header, ": ");
1751 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1753 log_error(LOG_LEVEL_HEADER,
1754 "keep-alive support is disabled. Crunching: %s.", *header);
1759 if ((NULL == timeout_position)
1760 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1762 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1766 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1768 log_error(LOG_LEVEL_HEADER,
1769 "Reducing keep-alive timeout from %u to %u.",
1770 csp->config->keep_alive_timeout, keep_alive_timeout);
1771 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1775 /* XXX: Is this log worthy? */
1776 log_error(LOG_LEVEL_HEADER,
1777 "Client keep-alive timeout is %u. Sticking with %u.",
1778 keep_alive_timeout, csp->config->keep_alive_timeout);
1786 /*********************************************************************
1788 * Function : get_content_length
1790 * Description : Gets the content length specified in a
1791 * Content-Length header.
1794 * 1 : header_value = The Content-Length header value.
1795 * 2 : length = Storage to return the value.
1797 * Returns : JB_ERR_OK on success, or
1798 * JB_ERR_PARSE if no value is recognized.
1800 *********************************************************************/
1801 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1804 assert(sizeof(unsigned long long) > 4);
1805 if (1 != sscanf(header_value, "%I64u", length))
1807 if (1 != sscanf(header_value, "%llu", length))
1810 return JB_ERR_PARSE;
1817 /*********************************************************************
1819 * Function : client_save_content_length
1821 * Description : Save the Content-Length sent by the client.
1824 * 1 : csp = Current client state (buffers, headers, etc...)
1825 * 2 : header = On input, pointer to header to modify.
1826 * On output, pointer to the modified header, or NULL
1827 * to remove the header. This function frees the
1828 * original string if necessary.
1830 * Returns : JB_ERR_OK on success, or
1831 * JB_ERR_MEMORY on out-of-memory error.
1833 *********************************************************************/
1834 static jb_err client_save_content_length(struct client_state *csp, char **header)
1836 unsigned long long content_length = 0;
1837 const char *header_value;
1839 assert(*(*header+14) == ':');
1841 header_value = *header + 15;
1842 if (JB_ERR_OK != get_content_length(header_value, &content_length))
1844 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1849 csp->expected_client_content_length = content_length;
1854 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1858 /*********************************************************************
1860 * Function : client_connection
1862 * Description : Makes sure a proper "Connection:" header is
1863 * set and signals connection_header_adder
1867 * 1 : csp = Current client state (buffers, headers, etc...)
1868 * 2 : header = On input, pointer to header to modify.
1869 * On output, pointer to the modified header, or NULL
1870 * to remove the header. This function frees the
1871 * original string if necessary.
1873 * Returns : JB_ERR_OK on success.
1875 *********************************************************************/
1876 static jb_err client_connection(struct client_state *csp, char **header)
1878 static const char connection_close[] = "Connection: close";
1880 if (!strcmpic(*header, connection_close))
1882 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1883 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1884 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1886 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1888 log_error(LOG_LEVEL_HEADER,
1889 "Removing \'%s\' to imply keep-alive.", *header);
1892 * While we imply keep-alive to the server,
1893 * we have to remember that the client didn't.
1895 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1899 char *old_header = *header;
1901 *header = strdup_or_die("Connection: keep-alive");
1902 log_error(LOG_LEVEL_HEADER,
1903 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1909 log_error(LOG_LEVEL_HEADER,
1910 "Keeping the client header '%s' around. "
1911 "The connection will not be kept alive.",
1913 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1916 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1917 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1919 log_error(LOG_LEVEL_HEADER,
1920 "Keeping the client header '%s' around. "
1921 "The server connection will be kept alive if possible.",
1923 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1924 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1928 char *old_header = *header;
1930 *header = strdup_or_die(connection_close);
1931 log_error(LOG_LEVEL_HEADER,
1932 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1936 /* Signal client_connection_header_adder() to return early. */
1937 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1943 /*********************************************************************
1945 * Function : crumble
1947 * Description : This is called if a header matches a pattern to "crunch"
1950 * 1 : csp = Current client state (buffers, headers, etc...)
1951 * 2 : header = On input, pointer to header to modify.
1952 * On output, pointer to the modified header, or NULL
1953 * to remove the header. This function frees the
1954 * original string if necessary.
1956 * Returns : JB_ERR_OK on success, or
1957 * JB_ERR_MEMORY on out-of-memory error.
1959 *********************************************************************/
1960 static jb_err crumble(struct client_state *csp, char **header)
1963 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1969 /*********************************************************************
1971 * Function : crunch_server_header
1973 * Description : Crunch server header if it matches a string supplied by the
1974 * user. Called from `sed'.
1977 * 1 : csp = Current client state (buffers, headers, etc...)
1978 * 2 : header = On input, pointer to header to modify.
1979 * On output, pointer to the modified header, or NULL
1980 * to remove the header. This function frees the
1981 * original string if necessary.
1983 * Returns : JB_ERR_OK on success and always succeeds
1985 *********************************************************************/
1986 static jb_err crunch_server_header(struct client_state *csp, char **header)
1988 const char *crunch_pattern;
1990 /* Do we feel like crunching? */
1991 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1993 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1995 /* Is the current header the lucky one? */
1996 if (strstr(*header, crunch_pattern))
1998 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2007 /*********************************************************************
2009 * Function : server_content_type
2011 * Description : Set the content-type for filterable types (text/.*,
2012 * .*xml.*, .*script.* and image/gif) unless filtering has been
2013 * forbidden (CT_TABOO) while parsing earlier headers.
2014 * NOTE: Since text/plain is commonly used by web servers
2015 * for files whose correct type is unknown, we don't
2016 * set CT_TEXT for it.
2019 * 1 : csp = Current client state (buffers, headers, etc...)
2020 * 2 : header = On input, pointer to header to modify.
2021 * On output, pointer to the modified header, or NULL
2022 * to remove the header. This function frees the
2023 * original string if necessary.
2025 * Returns : JB_ERR_OK on success, or
2026 * JB_ERR_MEMORY on out-of-memory error.
2028 *********************************************************************/
2029 static jb_err server_content_type(struct client_state *csp, char **header)
2031 /* Remove header if it isn't the first Content-Type header */
2032 if ((csp->content_type & CT_DECLARED))
2035 * Another, slightly slower, way to see if
2036 * we already parsed another Content-Type header.
2038 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2040 log_error(LOG_LEVEL_ERROR,
2041 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2049 * Signal that the Content-Type has been set.
2051 csp->content_type |= CT_DECLARED;
2053 if (!(csp->content_type & CT_TABOO))
2056 * XXX: The assumption that text/plain is a sign of
2057 * binary data seems to be somewhat unreasonable nowadays
2058 * and should be dropped after 3.0.8 is out.
2060 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2061 || strstr(*header, "xml")
2062 || strstr(*header, "script"))
2064 csp->content_type |= CT_TEXT;
2066 else if (strstr(*header, "image/gif"))
2068 csp->content_type |= CT_GIF;
2073 * Are we messing with the content type?
2075 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2078 * Make sure the user doesn't accidentally
2079 * change the content type of binary documents.
2081 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2084 *header = strdup_or_die("Content-Type: ");
2085 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2089 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2090 return JB_ERR_MEMORY;
2092 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2096 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2097 "It doesn't look like a content type that should be filtered. "
2098 "Enable force-text-mode if you know what you're doing.", *header);
2106 /*********************************************************************
2108 * Function : server_transfer_coding
2110 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2111 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2112 * - Remove header if body was chunked but has been
2113 * de-chunked for filtering.
2116 * 1 : csp = Current client state (buffers, headers, etc...)
2117 * 2 : header = On input, pointer to header to modify.
2118 * On output, pointer to the modified header, or NULL
2119 * to remove the header. This function frees the
2120 * original string if necessary.
2122 * Returns : JB_ERR_OK on success, or
2123 * JB_ERR_MEMORY on out-of-memory error.
2125 *********************************************************************/
2126 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2129 * Turn off pcrs and gif filtering if body compressed
2131 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2135 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2137 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2138 csp->http->cmd, *header);
2139 #endif /* def FEATURE_ZLIB */
2140 csp->content_type = CT_TABOO;
2144 * Raise flag if body chunked
2146 if (strstr(*header, "chunked"))
2148 csp->flags |= CSP_FLAG_CHUNKED;
2151 * If the body was modified, it has been de-chunked first
2152 * and the header must be removed.
2154 * FIXME: If there is more than one transfer encoding,
2155 * only the "chunked" part should be removed here.
2157 if (csp->flags & CSP_FLAG_MODIFIED)
2159 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2168 /*********************************************************************
2170 * Function : server_content_encoding
2172 * Description : Used to check if the content is compressed, and if
2173 * FEATURE_ZLIB is disabled, filtering is disabled as
2176 * If FEATURE_ZLIB is enabled and the compression type
2177 * supported, the content is marked for decompression.
2179 * XXX: Doesn't properly deal with multiple or with
2180 * unsupported but unknown encodings.
2181 * Is case-sensitive but shouldn't be.
2184 * 1 : csp = Current client state (buffers, headers, etc...)
2185 * 2 : header = On input, pointer to header to modify.
2186 * On output, pointer to the modified header, or NULL
2187 * to remove the header. This function frees the
2188 * original string if necessary.
2190 * Returns : JB_ERR_OK on success, or
2191 * JB_ERR_MEMORY on out-of-memory error.
2193 *********************************************************************/
2194 static jb_err server_content_encoding(struct client_state *csp, char **header)
2197 if (strstr(*header, "sdch"))
2200 * Shared Dictionary Compression over HTTP isn't supported,
2201 * filtering it anyway is pretty much guaranteed to mess up
2204 csp->content_type |= CT_TABOO;
2207 * Log a warning if the user expects the content to be filtered.
2209 if ((csp->rlist != NULL) &&
2210 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2212 log_error(LOG_LEVEL_INFO,
2213 "SDCH-compressed content detected, content filtering disabled. "
2214 "Consider suppressing SDCH offers made by the client.");
2217 else if (strstr(*header, "gzip"))
2219 /* Mark for gzip decompression */
2220 csp->content_type |= CT_GZIP;
2222 else if (strstr(*header, "deflate"))
2224 /* Mark for zlib decompression */
2225 csp->content_type |= CT_DEFLATE;
2227 else if (strstr(*header, "compress"))
2230 * We can't decompress this; therefore we can't filter
2233 csp->content_type |= CT_TABOO;
2235 #else /* !defined(FEATURE_ZLIB) */
2237 * XXX: Using a black list here isn't the right approach.
2239 * In case of SDCH, building with zlib support isn't
2242 if (strstr(*header, "gzip") ||
2243 strstr(*header, "compress") ||
2244 strstr(*header, "deflate") ||
2245 strstr(*header, "sdch"))
2248 * Body is compressed, turn off pcrs and gif filtering.
2250 csp->content_type |= CT_TABOO;
2253 * Log a warning if the user expects the content to be filtered.
2255 if ((csp->rlist != NULL) &&
2256 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2258 log_error(LOG_LEVEL_INFO,
2259 "Compressed content detected, content filtering disabled. "
2260 "Consider recompiling Privoxy with zlib support or "
2261 "enable the prevent-compression action.");
2264 #endif /* defined(FEATURE_ZLIB) */
2272 /*********************************************************************
2274 * Function : server_adjust_content_encoding
2276 * Description : Remove the Content-Encoding header if the
2277 * decompression was successful and the content
2281 * 1 : csp = Current client state (buffers, headers, etc...)
2282 * 2 : header = On input, pointer to header to modify.
2283 * On output, pointer to the modified header, or NULL
2284 * to remove the header. This function frees the
2285 * original string if necessary.
2287 * Returns : JB_ERR_OK on success, or
2288 * JB_ERR_MEMORY on out-of-memory error.
2290 *********************************************************************/
2291 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2293 if ((csp->flags & CSP_FLAG_MODIFIED)
2294 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2297 * We successfully decompressed the content,
2298 * and have to clean the header now, so the
2299 * client no longer expects compressed data.
2301 * XXX: There is a difference between cleaning
2302 * and removing it completely.
2304 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2311 #endif /* defined(FEATURE_ZLIB) */
2314 /*********************************************************************
2316 * Function : server_adjust_content_length
2318 * Description : Adjust Content-Length header if we modified
2322 * 1 : csp = Current client state (buffers, headers, etc...)
2323 * 2 : header = On input, pointer to header to modify.
2324 * On output, pointer to the modified header, or NULL
2325 * to remove the header. This function frees the
2326 * original string if necessary.
2328 * Returns : JB_ERR_OK on success, or
2329 * JB_ERR_MEMORY on out-of-memory error.
2331 *********************************************************************/
2332 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2334 /* Regenerate header if the content was modified. */
2335 if (csp->flags & CSP_FLAG_MODIFIED)
2337 const size_t header_length = 50;
2339 *header = malloc(header_length);
2340 if (*header == NULL)
2342 return JB_ERR_MEMORY;
2344 create_content_length_header(csp->content_length, *header, header_length);
2345 log_error(LOG_LEVEL_HEADER,
2346 "Adjusted Content-Length to %llu", csp->content_length);
2353 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2354 /*********************************************************************
2356 * Function : server_save_content_length
2358 * Description : Save the Content-Length sent by the server.
2361 * 1 : csp = Current client state (buffers, headers, etc...)
2362 * 2 : header = On input, pointer to header to modify.
2363 * On output, pointer to the modified header, or NULL
2364 * to remove the header. This function frees the
2365 * original string if necessary.
2367 * Returns : JB_ERR_OK on success, or
2368 * JB_ERR_MEMORY on out-of-memory error.
2370 *********************************************************************/
2371 static jb_err server_save_content_length(struct client_state *csp, char **header)
2373 unsigned long long content_length = 0;
2374 const char *header_value;
2376 assert(*(*header+14) == ':');
2378 header_value = *header + 15;
2379 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2381 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2386 csp->expected_content_length = content_length;
2387 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2388 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2393 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2396 /*********************************************************************
2398 * Function : server_content_md5
2400 * Description : Crumble any Content-MD5 headers if the document was
2401 * modified. FIXME: Should we re-compute instead?
2404 * 1 : csp = Current client state (buffers, headers, etc...)
2405 * 2 : header = On input, pointer to header to modify.
2406 * On output, pointer to the modified header, or NULL
2407 * to remove the header. This function frees the
2408 * original string if necessary.
2410 * Returns : JB_ERR_OK on success, or
2411 * JB_ERR_MEMORY on out-of-memory error.
2413 *********************************************************************/
2414 static jb_err server_content_md5(struct client_state *csp, char **header)
2416 if (csp->flags & CSP_FLAG_MODIFIED)
2418 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2426 /*********************************************************************
2428 * Function : server_content_disposition
2430 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2431 * Called from `sed'.
2434 * 1 : csp = Current client state (buffers, headers, etc...)
2435 * 2 : header = On input, pointer to header to modify.
2436 * On output, pointer to the modified header, or NULL
2437 * to remove the header. This function frees the
2438 * original string if necessary.
2440 * Returns : JB_ERR_OK on success, or
2441 * JB_ERR_MEMORY on out-of-memory error.
2443 *********************************************************************/
2444 static jb_err server_content_disposition(struct client_state *csp, char **header)
2449 * Are we messing with the Content-Disposition header?
2451 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2457 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2459 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2462 * Blocking content-disposition header
2464 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2471 * Replacing Content-Disposition header
2474 *header = strdup("Content-Disposition: ");
2475 string_append(header, newval);
2477 if (*header != NULL)
2479 log_error(LOG_LEVEL_HEADER,
2480 "Content-Disposition header crunched and replaced with: %s", *header);
2483 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2487 /*********************************************************************
2489 * Function : server_last_modified
2491 * Description : Changes Last-Modified header to the actual date
2492 * to help hide-if-modified-since.
2493 * Called from `sed'.
2496 * 1 : csp = Current client state (buffers, headers, etc...)
2497 * 2 : header = On input, pointer to header to modify.
2498 * On output, pointer to the modified header, or NULL
2499 * to remove the header. This function frees the
2500 * original string if necessary.
2502 * Returns : JB_ERR_OK on success, or
2503 * JB_ERR_MEMORY on out-of-memory error.
2505 *********************************************************************/
2506 static jb_err server_last_modified(struct client_state *csp, char **header)
2509 time_t last_modified;
2513 * Are we messing with the Last-Modified header?
2515 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2521 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2523 if (0 == strcmpic(newval, "block"))
2526 * Blocking Last-Modified header. Useless but why not.
2528 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2532 else if (0 == strcmpic(newval, "reset-to-request-time"))
2535 * Setting Last-Modified Header to now.
2538 get_http_time(0, buf, sizeof(buf));
2540 *header = strdup("Last-Modified: ");
2541 string_append(header, buf);
2543 if (*header == NULL)
2545 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2549 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2552 else if (0 == strcmpic(newval, "randomize"))
2554 const char *header_time = *header + sizeof("Last-Modified:");
2556 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2558 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2560 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2566 struct tm *timeptr = NULL;
2568 #ifdef HAVE_GMTIME_R
2572 rtime = (long int)difftime(now, last_modified);
2575 long int days, hours, minutes, seconds;
2576 const int negative_delta = (rtime < 0);
2581 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2583 rtime = pick_from_range(rtime);
2588 last_modified += rtime;
2589 #ifdef HAVE_GMTIME_R
2590 timeptr = gmtime_r(&last_modified, &gmt);
2591 #elif defined(MUTEX_LOCKS_AVAILABLE)
2592 privoxy_mutex_lock(&gmtime_mutex);
2593 timeptr = gmtime(&last_modified);
2594 privoxy_mutex_unlock(&gmtime_mutex);
2596 timeptr = gmtime(&last_modified);
2598 if ((NULL == timeptr) || !strftime(newheader,
2599 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2601 log_error(LOG_LEVEL_ERROR,
2602 "Randomizing '%s' failed. Crunching the header without replacement.",
2609 *header = strdup("Last-Modified: ");
2610 string_append(header, newheader);
2612 if (*header == NULL)
2614 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2615 return JB_ERR_MEMORY;
2618 days = rtime / (3600 * 24);
2619 hours = rtime / 3600 % 24;
2620 minutes = rtime / 60 % 60;
2621 seconds = rtime % 60;
2623 log_error(LOG_LEVEL_HEADER,
2624 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2625 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2626 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2630 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2639 /*********************************************************************
2641 * Function : client_accept_encoding
2643 * Description : Rewrite the client's Accept-Encoding header so that
2644 * if doesn't allow compression, if the action applies.
2645 * Note: For HTTP/1.0 the absence of the header is enough.
2648 * 1 : csp = Current client state (buffers, headers, etc...)
2649 * 2 : header = On input, pointer to header to modify.
2650 * On output, pointer to the modified header, or NULL
2651 * to remove the header. This function frees the
2652 * original string if necessary.
2654 * Returns : JB_ERR_OK on success, or
2655 * JB_ERR_MEMORY on out-of-memory error.
2657 *********************************************************************/
2658 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2660 #ifdef FEATURE_COMPRESSION
2661 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2662 && strstr(*header, "deflate"))
2664 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2667 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2669 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2677 /*********************************************************************
2679 * Function : client_te
2681 * Description : Rewrite the client's TE header so that
2682 * if doesn't allow compression, if the action applies.
2685 * 1 : csp = Current client state (buffers, headers, etc...)
2686 * 2 : header = On input, pointer to header to modify.
2687 * On output, pointer to the modified header, or NULL
2688 * to remove the header. This function frees the
2689 * original string if necessary.
2691 * Returns : JB_ERR_OK on success, or
2692 * JB_ERR_MEMORY on out-of-memory error.
2694 *********************************************************************/
2695 static jb_err client_te(struct client_state *csp, char **header)
2697 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2700 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2707 /*********************************************************************
2709 * Function : client_referrer
2711 * Description : Handle the "referer" config setting properly.
2712 * Called from `sed'.
2715 * 1 : csp = Current client state (buffers, headers, etc...)
2716 * 2 : header = On input, pointer to header to modify.
2717 * On output, pointer to the modified header, or NULL
2718 * to remove the header. This function frees the
2719 * original string if necessary.
2721 * Returns : JB_ERR_OK on success, or
2722 * JB_ERR_MEMORY on out-of-memory error.
2724 *********************************************************************/
2725 static jb_err client_referrer(struct client_state *csp, char **header)
2727 const char *parameter;
2728 /* booleans for parameters we have to check multiple times */
2729 int parameter_conditional_block;
2730 int parameter_conditional_forge;
2732 #ifdef FEATURE_FORCE_LOAD
2734 * Since the referrer can include the prefix even
2735 * if the request itself is non-forced, we must
2736 * clean it unconditionally.
2738 * XXX: strclean is too broad
2740 strclean(*header, FORCE_PREFIX);
2741 #endif /* def FEATURE_FORCE_LOAD */
2743 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2745 /* Nothing left to do */
2749 parameter = csp->action->string[ACTION_STRING_REFERER];
2750 assert(parameter != NULL);
2751 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2752 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2754 if (!parameter_conditional_block && !parameter_conditional_forge)
2757 * As conditional-block and conditional-forge are the only
2758 * parameters that rely on the original referrer, we can
2759 * remove it now for all the others.
2764 if (0 == strcmpic(parameter, "block"))
2766 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2769 else if (parameter_conditional_block || parameter_conditional_forge)
2771 return handle_conditional_hide_referrer_parameter(header,
2772 csp->http->hostport, parameter_conditional_block);
2774 else if (0 == strcmpic(parameter, "forge"))
2776 return create_forged_referrer(header, csp->http->hostport);
2780 /* interpret parameter as user-supplied referer to fake */
2781 return create_fake_referrer(header, parameter);
2786 /*********************************************************************
2788 * Function : client_accept_language
2790 * Description : Handle the "Accept-Language" config setting properly.
2791 * Called from `sed'.
2794 * 1 : csp = Current client state (buffers, headers, etc...)
2795 * 2 : header = On input, pointer to header to modify.
2796 * On output, pointer to the modified header, or NULL
2797 * to remove the header. This function frees the
2798 * original string if necessary.
2800 * Returns : JB_ERR_OK on success, or
2801 * JB_ERR_MEMORY on out-of-memory error.
2803 *********************************************************************/
2804 static jb_err client_accept_language(struct client_state *csp, char **header)
2809 * Are we messing with the Accept-Language?
2811 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2813 /*I don't think so*/
2817 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2819 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2822 * Blocking Accept-Language header
2824 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2831 * Replacing Accept-Language header
2834 *header = strdup("Accept-Language: ");
2835 string_append(header, newval);
2837 if (*header == NULL)
2839 log_error(LOG_LEVEL_ERROR,
2840 "Insufficient memory. Accept-Language header crunched without replacement.");
2844 log_error(LOG_LEVEL_HEADER,
2845 "Accept-Language header crunched and replaced with: %s", *header);
2848 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2852 /*********************************************************************
2854 * Function : crunch_client_header
2856 * Description : Crunch client header if it matches a string supplied by the
2857 * user. Called from `sed'.
2860 * 1 : csp = Current client state (buffers, headers, etc...)
2861 * 2 : header = On input, pointer to header to modify.
2862 * On output, pointer to the modified header, or NULL
2863 * to remove the header. This function frees the
2864 * original string if necessary.
2866 * Returns : JB_ERR_OK on success and always succeeds
2868 *********************************************************************/
2869 static jb_err crunch_client_header(struct client_state *csp, char **header)
2871 const char *crunch_pattern;
2873 /* Do we feel like crunching? */
2874 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2876 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2878 /* Is the current header the lucky one? */
2879 if (strstr(*header, crunch_pattern))
2881 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2889 /*********************************************************************
2891 * Function : client_uagent
2893 * Description : Handle the "user-agent" config setting properly
2894 * and remember its original value to enable browser
2895 * bug workarounds. 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, or
2905 * JB_ERR_MEMORY on out-of-memory error.
2907 *********************************************************************/
2908 static jb_err client_uagent(struct client_state *csp, char **header)
2912 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2917 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2924 *header = strdup("User-Agent: ");
2925 string_append(header, newval);
2927 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2929 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2933 /*********************************************************************
2935 * Function : client_ua
2937 * Description : Handle "ua-" headers properly. Called from `sed'.
2940 * 1 : csp = Current client state (buffers, headers, etc...)
2941 * 2 : header = On input, pointer to header to modify.
2942 * On output, pointer to the modified header, or NULL
2943 * to remove the header. This function frees the
2944 * original string if necessary.
2946 * Returns : JB_ERR_OK on success, or
2947 * JB_ERR_MEMORY on out-of-memory error.
2949 *********************************************************************/
2950 static jb_err client_ua(struct client_state *csp, char **header)
2952 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2954 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2962 /*********************************************************************
2964 * Function : client_from
2966 * Description : Handle the "from" config setting properly.
2967 * Called from `sed'.
2970 * 1 : csp = Current client state (buffers, headers, etc...)
2971 * 2 : header = On input, pointer to header to modify.
2972 * On output, pointer to the modified header, or NULL
2973 * to remove the header. This function frees the
2974 * original string if necessary.
2976 * Returns : JB_ERR_OK on success, or
2977 * JB_ERR_MEMORY on out-of-memory error.
2979 *********************************************************************/
2980 static jb_err client_from(struct client_state *csp, char **header)
2984 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2991 newval = csp->action->string[ACTION_STRING_FROM];
2994 * Are we blocking the e-mail address?
2996 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2998 log_error(LOG_LEVEL_HEADER, "crunched From!");
3002 log_error(LOG_LEVEL_HEADER, " modified");
3004 *header = strdup("From: ");
3005 string_append(header, newval);
3007 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3011 /*********************************************************************
3013 * Function : client_send_cookie
3015 * Description : Crunches the "cookie" header if necessary.
3016 * Called from `sed'.
3018 * XXX: Stupid name, doesn't send squat.
3021 * 1 : csp = Current client state (buffers, headers, etc...)
3022 * 2 : header = On input, pointer to header to modify.
3023 * On output, pointer to the modified header, or NULL
3024 * to remove the header. This function frees the
3025 * original string if necessary.
3027 * Returns : JB_ERR_OK on success, or
3028 * JB_ERR_MEMORY on out-of-memory error.
3030 *********************************************************************/
3031 static jb_err client_send_cookie(struct client_state *csp, char **header)
3033 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3035 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3043 /*********************************************************************
3045 * Function : client_x_forwarded
3047 * Description : Handle the "x-forwarded-for" config setting properly,
3048 * also used in the add_client_headers list. Called from `sed'.
3051 * 1 : csp = Current client state (buffers, headers, etc...)
3052 * 2 : header = On input, pointer to header to modify.
3053 * On output, pointer to the modified header, or NULL
3054 * to remove the header. This function frees the
3055 * original string if necessary.
3057 * Returns : JB_ERR_OK on success, or
3058 * JB_ERR_MEMORY on out-of-memory error.
3060 *********************************************************************/
3061 jb_err client_x_forwarded(struct client_state *csp, char **header)
3063 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3065 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3067 if (0 == strcmpic(parameter, "block"))
3070 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3072 else if (0 == strcmpic(parameter, "add"))
3074 string_append(header, ", ");
3075 string_append(header, csp->ip_addr_str);
3077 if (*header == NULL)
3079 return JB_ERR_MEMORY;
3081 log_error(LOG_LEVEL_HEADER,
3082 "Appended client IP address to %s", *header);
3083 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3087 log_error(LOG_LEVEL_FATAL,
3088 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3096 /*********************************************************************
3098 * Function : client_max_forwards
3100 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3101 * from the value of the Max-Forwards header field.
3104 * 1 : csp = Current client state (buffers, headers, etc...)
3105 * 2 : header = On input, pointer to header to modify.
3106 * On output, pointer to the modified header, or NULL
3107 * to remove the header. This function frees the
3108 * original string if necessary.
3110 * Returns : JB_ERR_OK on success, or
3111 * JB_ERR_MEMORY on out-of-memory error.
3113 *********************************************************************/
3114 static jb_err client_max_forwards(struct client_state *csp, char **header)
3118 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3119 (0 == strcmpic(csp->http->gpc, "options")))
3121 assert(*(*header+12) == ':');
3122 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3124 if (max_forwards > 0)
3126 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3127 log_error(LOG_LEVEL_HEADER,
3128 "Max-Forwards value for %s request reduced to %d.",
3129 csp->http->gpc, max_forwards);
3131 else if (max_forwards < 0)
3133 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3139 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3148 /*********************************************************************
3150 * Function : client_host
3152 * Description : If the request URI did not contain host and
3153 * port information, parse and evaluate the Host
3156 * Also, kill ill-formed HOST: headers as sent by
3157 * Apple's iTunes software when used with a proxy.
3160 * 1 : csp = Current client state (buffers, headers, etc...)
3161 * 2 : header = On input, pointer to header to modify.
3162 * On output, pointer to the modified header, or NULL
3163 * to remove the header. This function frees the
3164 * original string if necessary.
3166 * Returns : JB_ERR_OK on success, or
3167 * JB_ERR_MEMORY on out-of-memory error.
3169 *********************************************************************/
3170 static jb_err client_host(struct client_state *csp, char **header)
3175 * If the header field name is all upper-case, chances are that it's
3176 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3177 * not a problem -- they are regenerated later.
3179 if ((*header)[1] == 'O')
3181 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3186 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3187 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3190 p = strdup_or_die((*header)+6);
3192 q = strdup_or_die(p);
3194 freez(csp->http->hostport);
3195 csp->http->hostport = p;
3196 freez(csp->http->host);
3197 csp->http->host = q;
3198 q = strchr(csp->http->host, ':');
3201 /* Terminate hostname and evaluate port string */
3203 csp->http->port = atoi(q);
3207 csp->http->port = csp->http->ssl ? 443 : 80;
3210 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3211 csp->http->hostport, csp->http->host, csp->http->port);
3214 /* Signal client_host_adder() to return right away */
3215 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3221 /*********************************************************************
3223 * Function : client_if_modified_since
3225 * Description : Remove or modify the If-Modified-Since header.
3228 * 1 : csp = Current client state (buffers, headers, etc...)
3229 * 2 : header = On input, pointer to header to modify.
3230 * On output, pointer to the modified header, or NULL
3231 * to remove the header. This function frees the
3232 * original string if necessary.
3234 * Returns : JB_ERR_OK on success, or
3235 * JB_ERR_MEMORY on out-of-memory error.
3237 *********************************************************************/
3238 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3241 #ifdef HAVE_GMTIME_R
3244 struct tm *timeptr = NULL;
3249 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3252 * The client got an error message because of a temporary problem,
3253 * the problem is gone and the client now tries to revalidate our
3254 * error message on the real server. The revalidation would always
3255 * end with the transmission of the whole document and there is
3256 * no need to expose the bogus If-Modified-Since header.
3258 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3261 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3263 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3265 if ((0 == strcmpic(newval, "block")))
3267 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3270 else /* add random value */
3272 const char *header_time = *header + sizeof("If-Modified-Since:");
3274 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3276 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3281 long int hours, minutes, seconds;
3282 long int rtime = strtol(newval, &endptr, 0);
3283 const int negative_range = (rtime < 0);
3287 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3288 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3294 rtime = pick_from_range(rtime);
3298 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3301 tm += rtime * (negative_range ? -1 : 1);
3302 #ifdef HAVE_GMTIME_R
3303 timeptr = gmtime_r(&tm, &gmt);
3304 #elif defined(MUTEX_LOCKS_AVAILABLE)
3305 privoxy_mutex_lock(&gmtime_mutex);
3306 timeptr = gmtime(&tm);
3307 privoxy_mutex_unlock(&gmtime_mutex);
3309 timeptr = gmtime(&tm);
3311 if ((NULL == timeptr) || !strftime(newheader,
3312 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3314 log_error(LOG_LEVEL_ERROR,
3315 "Randomizing '%s' failed. Crunching the header without replacement.",
3322 *header = strdup("If-Modified-Since: ");
3323 string_append(header, newheader);
3325 if (*header == NULL)
3327 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3328 return JB_ERR_MEMORY;
3331 hours = rtime / 3600;
3332 minutes = rtime / 60 % 60;
3333 seconds = rtime % 60;
3335 log_error(LOG_LEVEL_HEADER,
3336 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3337 *header, (negative_range) ? "subtracted" : "added", hours,
3338 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3339 seconds, (seconds == 1) ? ")" : "s)");
3348 /*********************************************************************
3350 * Function : client_if_none_match
3352 * Description : Remove the If-None-Match header.
3355 * 1 : csp = Current client state (buffers, headers, etc...)
3356 * 2 : header = On input, pointer to header to modify.
3357 * On output, pointer to the modified header, or NULL
3358 * to remove the header. This function frees the
3359 * original string if necessary.
3361 * Returns : JB_ERR_OK on success, or
3362 * JB_ERR_MEMORY on out-of-memory error.
3364 *********************************************************************/
3365 static jb_err client_if_none_match(struct client_state *csp, char **header)
3367 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3369 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3377 /*********************************************************************
3379 * Function : client_x_filter
3381 * Description : Disables filtering if the client set "X-Filter: No".
3382 * Called from `sed'.
3385 * 1 : csp = Current client state (buffers, headers, etc...)
3386 * 2 : header = On input, pointer to header to modify.
3387 * On output, pointer to the modified header, or NULL
3388 * to remove the header. This function frees the
3389 * original string if necessary.
3391 * Returns : JB_ERR_OK on success
3393 *********************************************************************/
3394 jb_err client_x_filter(struct client_state *csp, char **header)
3396 if (0 == strcmpic(*header, "X-Filter: No"))
3398 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3400 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3404 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3406 log_error(LOG_LEVEL_HEADER,
3407 "force-text-mode overruled the client's request to fetch without filtering!");
3411 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3412 csp->flags |= CSP_FLAG_NO_FILTERING;
3413 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3415 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3423 /*********************************************************************
3425 * Function : client_range
3427 * Description : Removes Range, Request-Range and If-Range headers if
3428 * content filtering is enabled and the range doesn't
3431 * If the client's version of the document has been
3432 * altered by Privoxy, the server could interpret the
3433 * range differently than the client intended in which
3434 * case the user could end up with corrupted content.
3436 * If the range starts at byte 0 this isn't an issue
3437 * so the header can pass. Partial requests like this
3438 * are used to render preview images for videos without
3439 * downloading the whole video.
3441 * While HTTP doesn't require that range requests are
3442 * honoured and the client could simply abort the download
3443 * after receiving a sufficient amount of data, various
3444 * clients don't handle complete responses to range
3445 * requests gracefully and emit misleading error messages
3449 * 1 : csp = Current client state (buffers, headers, etc...)
3450 * 2 : header = On input, pointer to header to modify.
3451 * On output, pointer to the modified header, or NULL
3452 * to remove the header. This function frees the
3453 * original string if necessary.
3455 * Returns : JB_ERR_OK
3457 *********************************************************************/
3458 static jb_err client_range(struct client_state *csp, char **header)
3460 if (content_filters_enabled(csp->action)
3461 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3463 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3464 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3471 /* the following functions add headers directly to the header list */
3473 /*********************************************************************
3475 * Function : client_host_adder
3477 * Description : Adds the Host: header field if it is missing.
3478 * Called from `sed'.
3481 * 1 : csp = Current client state (buffers, headers, etc...)
3483 * Returns : JB_ERR_OK on success, or
3484 * JB_ERR_MEMORY on out-of-memory error.
3486 *********************************************************************/
3487 static jb_err client_host_adder(struct client_state *csp)
3492 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3494 /* Header already set by the client, nothing to do. */
3498 if (!csp->http->hostport || !*(csp->http->hostport))
3500 /* XXX: When does this happen and why is it OK? */
3501 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3506 * remove 'user:pass@' from 'proto://user:pass@host'
3508 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3514 p = csp->http->hostport;
3517 /* XXX: Just add it, we already made sure that it will be unique */
3518 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3519 err = enlist_unique_header(csp->headers, "Host", p);
3525 /*********************************************************************
3527 * Function : client_xtra_adder
3529 * Description : Used in the add_client_headers list. Called from `sed'.
3532 * 1 : csp = Current client state (buffers, headers, etc...)
3534 * Returns : JB_ERR_OK on success, or
3535 * JB_ERR_MEMORY on out-of-memory error.
3537 *********************************************************************/
3538 static jb_err client_xtra_adder(struct client_state *csp)
3540 struct list_entry *lst;
3543 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3544 lst ; lst = lst->next)
3546 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3547 err = enlist(csp->headers, lst->str);
3559 /*********************************************************************
3561 * Function : client_x_forwarded_for_adder
3563 * Description : Used in the add_client_headers list. Called from `sed'.
3566 * 1 : csp = Current client state (buffers, headers, etc...)
3568 * Returns : JB_ERR_OK on success, or
3569 * JB_ERR_MEMORY on out-of-memory error.
3571 *********************************************************************/
3572 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3574 char *header = NULL;
3577 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3578 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3579 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3582 * If we aren't adding X-Forwarded-For headers,
3583 * or we already appended an existing X-Forwarded-For
3584 * header, there's nothing left to do here.
3589 header = strdup("X-Forwarded-For: ");
3590 string_append(&header, csp->ip_addr_str);
3594 return JB_ERR_MEMORY;
3597 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3598 err = enlist(csp->headers, header);
3605 /*********************************************************************
3607 * Function : server_connection_adder
3609 * Description : Adds an appropriate "Connection:" header to csp->headers
3610 * unless the header was already present. Called from `sed'.
3613 * 1 : csp = Current client state (buffers, headers, etc...)
3615 * Returns : JB_ERR_OK on success, or
3616 * JB_ERR_MEMORY on out-of-memory error.
3618 *********************************************************************/
3619 static jb_err server_connection_adder(struct client_state *csp)
3621 const unsigned int flags = csp->flags;
3622 const char *response_status_line = csp->headers->first->str;
3623 static const char connection_close[] = "Connection: close";
3625 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3626 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3632 * XXX: if we downgraded the response, this check will fail.
3634 if ((csp->config->feature_flags &
3635 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3636 && (NULL != response_status_line)
3637 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3638 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3639 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3643 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3644 "without Connection header implies keep-alive.");
3645 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3649 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3651 return enlist(csp->headers, connection_close);
3655 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3656 /*********************************************************************
3658 * Function : server_proxy_connection_adder
3660 * Description : Adds a "Proxy-Connection: keep-alive" header to
3661 * csp->headers when appropriate.
3664 * 1 : csp = Current client state (buffers, headers, etc...)
3666 * Returns : JB_ERR_OK on success, or
3667 * JB_ERR_MEMORY on out-of-memory error.
3669 *********************************************************************/
3670 static jb_err server_proxy_connection_adder(struct client_state *csp)
3672 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3673 jb_err err = JB_ERR_OK;
3675 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3676 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3677 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3678 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3679 || (csp->flags & CSP_FLAG_CHUNKED)))
3681 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3682 err = enlist(csp->headers, proxy_connection_header);
3687 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3690 /*********************************************************************
3692 * Function : client_connection_header_adder
3694 * Description : Adds a proper "Connection:" header to csp->headers
3695 * unless the header was already present. Called from `sed'.
3698 * 1 : csp = Current client state (buffers, headers, etc...)
3700 * Returns : JB_ERR_OK on success, or
3701 * JB_ERR_MEMORY on out-of-memory error.
3703 *********************************************************************/
3704 static jb_err client_connection_header_adder(struct client_state *csp)
3706 static const char connection_close[] = "Connection: close";
3708 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3709 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3714 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3715 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3716 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3717 && (csp->http->ssl == 0)
3718 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3720 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3723 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3725 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3727 return enlist(csp->headers, connection_close);
3731 /*********************************************************************
3733 * Function : server_http
3735 * Description : - Save the HTTP Status into csp->http->status
3736 * - Set CT_TABOO to prevent filtering if the answer
3737 * is a partial range (HTTP status 206)
3738 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3742 * 1 : csp = Current client state (buffers, headers, etc...)
3743 * 2 : header = On input, pointer to header to modify.
3744 * On output, pointer to the modified header, or NULL
3745 * to remove the header. This function frees the
3746 * original string if necessary.
3748 * Returns : JB_ERR_OK on success, or
3749 * JB_ERR_MEMORY on out-of-memory error.
3751 *********************************************************************/
3752 static jb_err server_http(struct client_state *csp, char **header)
3754 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3755 if (csp->http->status == 206)
3757 csp->content_type = CT_TABOO;
3760 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3762 /* XXX: Should we do a real validity check here? */
3763 if (strlen(*header) > 8)
3766 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3771 * XXX: Should we block the request or
3772 * enlist a valid status code line here?
3774 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3775 "Downgrading to HTTP/1.0 impossible.");
3782 /*********************************************************************
3784 * Function : add_cooky_expiry_date
3786 * Description : Adds a cookie expiry date to a string.
3789 * 1 : cookie = On input, pointer to cookie to modify.
3790 * On output, pointer to the modified header.
3791 * The original string is freed.
3792 * 2 : lifetime = Seconds the cookie should be valid
3796 *********************************************************************/
3797 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
3800 struct tm *timeptr = NULL;
3801 time_t expiry_date = time(NULL) + lifetime;
3802 #ifdef HAVE_GMTIME_R
3805 timeptr = gmtime_r(&expiry_date, &gmt);
3806 #elif defined(MUTEX_LOCKS_AVAILABLE)
3807 privoxy_mutex_lock(&gmtime_mutex);
3808 timeptr = gmtime(&expiry_date);
3809 privoxy_mutex_unlock(&gmtime_mutex);
3811 timeptr = gmtime(&expiry_date);
3814 if (NULL == timeptr)
3816 log_error(LOG_LEVEL_FATAL,
3817 "Failed to get the time in add_cooky_expiry_date()");
3819 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
3820 if (JB_ERR_OK != string_append(cookie, tmp))
3822 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
3827 /*********************************************************************
3829 * Function : server_set_cookie
3831 * Description : Handle the server "cookie" header properly.
3832 * Crunch, accept or rewrite it to a session cookie.
3833 * Called from `sed'.
3836 * 1 : csp = Current client state (buffers, headers, etc...)
3837 * 2 : header = On input, pointer to header to modify.
3838 * On output, pointer to the modified header, or NULL
3839 * to remove the header. This function frees the
3840 * original string if necessary.
3842 * Returns : JB_ERR_OK on success, or
3843 * JB_ERR_MEMORY on out-of-memory error.
3845 *********************************************************************/
3846 static jb_err server_set_cookie(struct client_state *csp, char **header)
3848 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
3850 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3853 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
3854 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
3858 long cookie_lifetime = 0;
3859 int expiry_date_acceptable = 0;
3861 /* A variable to store the tag we're working on */
3864 /* Skip "Set-Cookie:" (11 characters) in header */
3865 cur_tag = *header + 11;
3867 /* skip whitespace between "Set-Cookie:" and value */
3868 while (*cur_tag && privoxy_isspace(*cur_tag))
3875 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
3877 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
3879 cookie_lifetime = strtol(param, NULL, 0);
3880 if (cookie_lifetime < 0)
3882 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
3884 cookie_lifetime *= 60U;
3887 /* Loop through each tag in the cookie */
3891 char *next_tag = strchr(cur_tag, ';');
3892 if (next_tag != NULL)
3894 /* Skip the ';' character itself */
3897 /* skip whitespace ";" and start of tag */
3898 while (*next_tag && privoxy_isspace(*next_tag))
3905 /* "Next tag" is the end of the string */
3906 next_tag = cur_tag + strlen(cur_tag);
3910 * Check the expiration date to see
3911 * if the cookie is still valid, if yes,
3912 * rewrite it to a session cookie.
3914 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3916 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3918 if ((expiration_date[0] == '"')
3919 && (expiration_date[1] != '\0'))
3922 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
3923 * that the expiration date isn't supposed to be quoted,
3924 * but some servers do it anyway.
3929 /* Did we detect the date properly? */
3930 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3933 * Nope, treat it as if it was still valid.
3935 * XXX: Should we remove the whole cookie instead?
3937 log_error(LOG_LEVEL_ERROR,
3938 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3939 string_move(cur_tag, next_tag);
3940 expiry_date_acceptable = 0;
3945 * Yes. Check if the cookie is still valid.
3947 * If the cookie is already expired it's probably
3948 * a delete cookie and even if it isn't, the browser
3949 * will discard it anyway.
3953 * XXX: timegm() isn't available on some AmigaOS
3954 * versions and our replacement doesn't work.
3956 * Our options are to either:
3958 * - disable session-cookies-only completely if timegm
3961 * - to simply remove all expired tags, like it has
3962 * been done until Privoxy 3.0.6 and to live with
3963 * the consequence that it can cause login/logout
3964 * problems on servers that don't validate their
3965 * input properly, or
3967 * - to replace it with mktime in which
3968 * case there is a slight chance of valid cookies
3969 * passing as already expired.
3971 * This is the way it's currently done and it's not
3972 * as bad as it sounds. If the missing GMT offset is
3973 * enough to change the result of the expiration check
3974 * the cookie will be only valid for a few hours
3975 * anyway, which in many cases will be shorter
3976 * than a browser session.
3978 if (cookie_time < now)
3980 log_error(LOG_LEVEL_HEADER,
3981 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3982 /* Just in case some clown sets more then one expiration date */
3984 expiry_date_acceptable = 1;
3986 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
3988 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
3989 "Its lifetime is below the limit.", *header);
3990 /* Just in case some clown sets more then one expiration date */
3992 expiry_date_acceptable = 1;
3997 * Still valid, delete expiration date by copying
3998 * the rest of the string over it.
4000 string_move(cur_tag, next_tag);
4002 /* That changed the header, need to issue a log message */
4003 expiry_date_acceptable = 0;
4006 * Note that the next tag has now been moved to *cur_tag,
4007 * so we do not need to update the cur_tag pointer.
4015 /* Move on to next cookie tag */
4020 if (!expiry_date_acceptable)
4022 assert(NULL != *header);
4023 if (cookie_lifetime == 0)
4025 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
4030 add_cookie_expiry_date(header, cookie_lifetime);
4031 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4040 #ifdef FEATURE_FORCE_LOAD
4041 /*********************************************************************
4043 * Function : strclean
4045 * Description : In-Situ-Eliminate all occurrences of substring in
4049 * 1 : string = string to clean
4050 * 2 : substring = substring to eliminate
4052 * Returns : Number of eliminations
4054 *********************************************************************/
4055 int strclean(char *string, const char *substring)
4061 len = strlen(substring);
4063 while((pos = strstr(string, substring)) != NULL)
4070 while (*p++ != '\0');
4077 #endif /* def FEATURE_FORCE_LOAD */
4080 /*********************************************************************
4082 * Function : parse_header_time
4084 * Description : Parses time formats used in HTTP header strings
4085 * to get the numerical respresentation.
4088 * 1 : header_time = HTTP header time as string.
4089 * 2 : result = storage for header_time in seconds
4091 * Returns : JB_ERR_OK if the time format was recognized, or
4092 * JB_ERR_PARSE otherwise.
4094 *********************************************************************/
4095 static jb_err parse_header_time(const char *header_time, time_t *result)
4099 * Checking for two-digit years first in an
4100 * attempt to work around GNU libc's strptime()
4101 * reporting negative year values when using %Y.
4103 static const char time_formats[][22] = {
4104 /* Tue, 02-Jun-37 20:00:00 */
4105 "%a, %d-%b-%y %H:%M:%S",
4106 /* Tue, 02 Jun 2037 20:00:00 */
4107 "%a, %d %b %Y %H:%M:%S",
4108 /* Tue, 02-Jun-2037 20:00:00 */
4109 "%a, %d-%b-%Y %H:%M:%S",
4110 /* Tuesday, 02-Jun-2037 20:00:00 */
4111 "%A, %d-%b-%Y %H:%M:%S",
4112 /* Tuesday Jun 02 20:00:00 2037 */
4113 "%A %b %d %H:%M:%S %Y"
4117 for (i = 0; i < SZ(time_formats); i++)
4120 * Zero out gmt to prevent time zone offsets.
4121 * Documented to be required for GNU libc.
4123 memset(&gmt, 0, sizeof(gmt));
4125 if (NULL != strptime(header_time, time_formats[i], &gmt))
4127 /* Sanity check for GNU libc. */
4128 if (gmt.tm_year < 0)
4130 log_error(LOG_LEVEL_HEADER,
4131 "Failed to parse '%s' using '%s'. Moving on.",
4132 header_time, time_formats[i]);
4135 *result = timegm(&gmt);
4140 return JB_ERR_PARSE;
4145 /*********************************************************************
4147 * Function : get_destination_from_headers
4149 * Description : Parse the "Host:" header to get the request's destination.
4150 * Only needed if the client's request was forcefully
4151 * redirected into Privoxy.
4153 * Code mainly copied from client_host() which is currently
4154 * run too late for this purpose.
4157 * 1 : headers = List of headers (one of them hopefully being
4158 * the "Host:" header)
4159 * 2 : http = storage for the result (host, port and hostport).
4161 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4162 * JB_ERR_PARSE if the host header couldn't be found,
4163 * JB_ERR_OK otherwise.
4165 *********************************************************************/
4166 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4172 host = get_header_value(headers, "Host:");
4176 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4177 return JB_ERR_PARSE;
4180 p = strdup_or_die(host);
4182 q = strdup_or_die(p);
4184 freez(http->hostport);
4188 q = strchr(http->host, ':');
4191 /* Terminate hostname and evaluate port string */
4193 http->port = atoi(q);
4197 http->port = http->ssl ? 443 : 80;
4200 /* Rebuild request URL */
4202 http->url = strdup(http->ssl ? "https://" : "http://");
4203 string_append(&http->url, http->hostport);
4204 string_append(&http->url, http->path);
4205 if (http->url == NULL)
4207 return JB_ERR_MEMORY;
4210 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4218 /*********************************************************************
4220 * Function : create_forged_referrer
4222 * Description : Helper for client_referrer to forge a referer as
4223 * 'http://hostname[:port]/' to fool stupid
4224 * checks for in-site links
4227 * 1 : header = Pointer to header pointer
4228 * 2 : hostport = Host and optionally port as string
4230 * Returns : JB_ERR_OK in case of success, or
4231 * JB_ERR_MEMORY in case of memory problems.
4233 *********************************************************************/
4234 static jb_err create_forged_referrer(char **header, const char *hostport)
4236 assert(NULL == *header);
4238 *header = strdup("Referer: http://");
4239 string_append(header, hostport);
4240 string_append(header, "/");
4242 if (NULL == *header)
4244 return JB_ERR_MEMORY;
4247 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4254 /*********************************************************************
4256 * Function : create_fake_referrer
4258 * Description : Helper for client_referrer to create a fake referrer
4259 * based on a string supplied by the user.
4262 * 1 : header = Pointer to header pointer
4263 * 2 : hosthost = Referrer to fake
4265 * Returns : JB_ERR_OK in case of success, or
4266 * JB_ERR_MEMORY in case of memory problems.
4268 *********************************************************************/
4269 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4271 assert(NULL == *header);
4273 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4275 log_error(LOG_LEVEL_HEADER,
4276 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4278 *header = strdup("Referer: ");
4279 string_append(header, fake_referrer);
4281 if (NULL == *header)
4283 return JB_ERR_MEMORY;
4286 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4293 /*********************************************************************
4295 * Function : handle_conditional_hide_referrer_parameter
4297 * Description : Helper for client_referrer to crunch or forge
4298 * the referrer header if the host has changed.
4301 * 1 : header = Pointer to header pointer
4302 * 2 : host = The target host (may include the port)
4303 * 3 : parameter_conditional_block = Boolean to signal
4304 * if we're in conditional-block mode. If not set,
4305 * we're in conditional-forge mode.
4307 * Returns : JB_ERR_OK in case of success, or
4308 * JB_ERR_MEMORY in case of memory problems.
4310 *********************************************************************/
4311 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4312 const char *host, const int parameter_conditional_block)
4314 char *referer = strdup_or_die(*header);
4315 const size_t hostlength = strlen(host);
4316 const char *referer_url = NULL;
4318 /* referer begins with 'Referer: http[s]://' */
4319 if ((hostlength+17) < strlen(referer))
4322 * Shorten referer to make sure the referer is blocked
4323 * if www.example.org/www.example.com-shall-see-the-referer/
4324 * links to www.example.com/
4326 referer[hostlength+17] = '\0';
4328 referer_url = strstr(referer, "http://");
4329 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4331 /* Host has changed, Referer is invalid or a https URL. */
4332 if (parameter_conditional_block)
4334 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4341 return create_forged_referrer(header, host);
4351 /*********************************************************************
4353 * Function : create_content_length_header
4355 * Description : Creates a Content-Length header.
4358 * 1 : content_length = The content length to be used in the header.
4359 * 2 : header = Allocated space to safe the header.
4360 * 3 : buffer_length = The length of the allocated space.
4364 *********************************************************************/
4365 static void create_content_length_header(unsigned long long content_length,
4366 char *header, size_t buffer_length)
4368 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4372 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4373 /*********************************************************************
4375 * Function : get_expected_content_length
4377 * Description : Figures out the content length from a list of headers.
4380 * 1 : headers = List of headers
4382 * Returns : Number of bytes to expect
4384 *********************************************************************/
4385 unsigned long long get_expected_content_length(struct list *headers)
4387 const char *content_length_header;
4388 unsigned long long content_length = 0;
4390 content_length_header = get_header_value(headers, "Content-Length:");
4391 if (content_length_header != NULL)
4393 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4395 log_error(LOG_LEVEL_ERROR,
4396 "Failed to get the Content-Length in %s", content_length_header);
4397 /* XXX: The header will be removed later on */
4402 return content_length;