1 const char parsers_rcs[] = "$Id: parsers.c,v 1.268 2012/11/24 14:07:57 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
8 * Copyright : Written by and Copyright (C) 2001-2012 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
40 #include <sys/types.h>
50 * Convince GNU's libc to provide a strptime prototype.
59 #define GZIP_IDENTIFIER_1 0x1f
60 #define GZIP_IDENTIFIER_2 0x8b
62 #define GZIP_FLAG_CHECKSUM 0x02
63 #define GZIP_FLAG_EXTRA_FIELDS 0x04
64 #define GZIP_FLAG_FILE_NAME 0x08
65 #define GZIP_FLAG_COMMENT 0x10
66 #define GZIP_FLAG_RESERVED_BITS 0xe0
69 #if !defined(_WIN32) && !defined(__OS2__)
75 #ifdef FEATURE_PTHREAD
77 /* jcc.h is for mutex semapores only */
78 #endif /* def FEATURE_PTHREAD */
83 #include "jbsockets.h"
93 const char parsers_h_rcs[] = PARSERS_H_VERSION;
95 static char *get_header_line(struct iob *iob);
96 static jb_err scan_headers(struct client_state *csp);
97 static jb_err header_tagger(struct client_state *csp, char *header);
98 static jb_err parse_header_time(const char *header_time, time_t *result);
100 static jb_err crumble (struct client_state *csp, char **header);
101 static jb_err filter_header (struct client_state *csp, char **header);
102 static jb_err client_connection (struct client_state *csp, char **header);
103 static jb_err client_referrer (struct client_state *csp, char **header);
104 static jb_err client_uagent (struct client_state *csp, char **header);
105 static jb_err client_ua (struct client_state *csp, char **header);
106 static jb_err client_from (struct client_state *csp, char **header);
107 static jb_err client_send_cookie (struct client_state *csp, char **header);
108 static jb_err client_x_forwarded (struct client_state *csp, char **header);
109 static jb_err client_accept_encoding (struct client_state *csp, char **header);
110 static jb_err client_te (struct client_state *csp, char **header);
111 static jb_err client_max_forwards (struct client_state *csp, char **header);
112 static jb_err client_host (struct client_state *csp, char **header);
113 static jb_err client_if_modified_since (struct client_state *csp, char **header);
114 static jb_err client_accept_language (struct client_state *csp, char **header);
115 static jb_err client_if_none_match (struct client_state *csp, char **header);
116 static jb_err crunch_client_header (struct client_state *csp, char **header);
117 static jb_err client_x_filter (struct client_state *csp, char **header);
118 static jb_err client_range (struct client_state *csp, char **header);
119 static jb_err server_set_cookie (struct client_state *csp, char **header);
120 static jb_err server_connection (struct client_state *csp, char **header);
121 static jb_err server_content_type (struct client_state *csp, char **header);
122 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
123 static jb_err server_content_md5 (struct client_state *csp, char **header);
124 static jb_err server_content_encoding (struct client_state *csp, char **header);
125 static jb_err server_transfer_coding (struct client_state *csp, char **header);
126 static jb_err server_http (struct client_state *csp, char **header);
127 static jb_err crunch_server_header (struct client_state *csp, char **header);
128 static jb_err server_last_modified (struct client_state *csp, char **header);
129 static jb_err server_content_disposition(struct client_state *csp, char **header);
131 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
134 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
135 static jb_err server_save_content_length(struct client_state *csp, char **header);
136 static jb_err server_keep_alive(struct client_state *csp, char **header);
137 static jb_err server_proxy_connection(struct client_state *csp, char **header);
138 static jb_err client_keep_alive(struct client_state *csp, char **header);
139 static jb_err client_save_content_length(struct client_state *csp, char **header);
140 static jb_err client_proxy_connection(struct client_state *csp, char **header);
141 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
143 static jb_err client_host_adder (struct client_state *csp);
144 static jb_err client_xtra_adder (struct client_state *csp);
145 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
146 static jb_err client_connection_header_adder(struct client_state *csp);
147 static jb_err server_connection_adder(struct client_state *csp);
148 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
149 static jb_err server_proxy_connection_adder(struct client_state *csp);
150 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
152 static jb_err create_forged_referrer(char **header, const char *hostport);
153 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
154 static jb_err handle_conditional_hide_referrer_parameter(char **header,
155 const char *host, const int parameter_conditional_block);
156 static void create_content_length_header(unsigned long long content_length,
157 char *header, size_t buffer_length);
160 * List of functions to run on a list of headers.
164 /** The header prefix to match */
167 /** The length of the prefix to match */
170 /** The function to apply to this line */
171 const parser_func_ptr parser;
174 static const struct parsers client_patterns[] = {
175 { "referer:", 8, client_referrer },
176 { "user-agent:", 11, client_uagent },
177 { "ua-", 3, client_ua },
178 { "from:", 5, client_from },
179 { "cookie:", 7, client_send_cookie },
180 { "x-forwarded-for:", 16, client_x_forwarded },
181 { "Accept-Encoding:", 16, client_accept_encoding },
182 { "TE:", 3, client_te },
183 { "Host:", 5, client_host },
184 { "if-modified-since:", 18, client_if_modified_since },
185 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
186 { "Keep-Alive:", 11, client_keep_alive },
187 { "Content-Length:", 15, client_save_content_length },
188 { "Proxy-Connection:", 17, client_proxy_connection },
190 { "Keep-Alive:", 11, crumble },
191 { "Proxy-Connection:", 17, crumble },
193 { "connection:", 11, client_connection },
194 { "max-forwards:", 13, client_max_forwards },
195 { "Accept-Language:", 16, client_accept_language },
196 { "if-none-match:", 14, client_if_none_match },
197 { "Range:", 6, client_range },
198 { "Request-Range:", 14, client_range },
199 { "If-Range:", 9, client_range },
200 { "X-Filter:", 9, client_x_filter },
201 { "*", 0, crunch_client_header },
202 { "*", 0, filter_header },
206 static const struct parsers server_patterns[] = {
207 { "HTTP/", 5, server_http },
208 { "set-cookie:", 11, server_set_cookie },
209 { "connection:", 11, server_connection },
210 { "Content-Type:", 13, server_content_type },
211 { "Content-MD5:", 12, server_content_md5 },
212 { "Content-Encoding:", 17, server_content_encoding },
213 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
214 { "Content-Length:", 15, server_save_content_length },
215 { "Keep-Alive:", 11, server_keep_alive },
216 { "Proxy-Connection:", 17, server_proxy_connection },
218 { "Keep-Alive:", 11, crumble },
219 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
220 { "Transfer-Encoding:", 18, server_transfer_coding },
221 { "content-disposition:", 20, server_content_disposition },
222 { "Last-Modified:", 14, server_last_modified },
223 { "*", 0, crunch_server_header },
224 { "*", 0, filter_header },
228 static const add_header_func_ptr add_client_headers[] = {
230 client_x_forwarded_for_adder,
232 client_connection_header_adder,
236 static const add_header_func_ptr add_server_headers[] = {
237 server_connection_adder,
238 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
239 server_proxy_connection_adder,
240 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
244 /*********************************************************************
246 * Function : flush_socket
248 * Description : Write any pending "buffered" content.
251 * 1 : fd = file descriptor of the socket to read
252 * 2 : iob = The I/O buffer to flush, usually csp->iob.
254 * Returns : On success, the number of bytes written are returned (zero
255 * indicates nothing was written). On error, -1 is returned,
256 * and errno is set appropriately. If count is zero and the
257 * file descriptor refers to a regular file, 0 will be
258 * returned without causing any other effect. For a special
259 * file, the results are not portable.
261 *********************************************************************/
262 long flush_socket(jb_socket fd, struct iob *iob)
264 long len = iob->eod - iob->cur;
271 if (write_socket(fd, iob->cur, (size_t)len))
275 iob->eod = iob->cur = iob->buf;
281 /*********************************************************************
283 * Function : add_to_iob
285 * Description : Add content to the buffer, expanding the
286 * buffer if necessary.
289 * 1 : iob = Destination buffer.
290 * 2 : buffer_limit = Limit to which the destination may grow
291 * 3 : src = holds the content to be added
292 * 4 : n = number of bytes to be added
294 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
295 * or buffer limit reached.
297 *********************************************************************/
298 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
300 size_t used, offset, need;
303 if (n <= 0) return JB_ERR_OK;
305 used = (size_t)(iob->eod - iob->buf);
306 offset = (size_t)(iob->cur - iob->buf);
307 need = used + (size_t)n + 1;
310 * If the buffer can't hold the new data, extend it first.
311 * Use the next power of two if possible, else use the actual need.
313 if (need > buffer_limit)
315 log_error(LOG_LEVEL_INFO,
316 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
318 return JB_ERR_MEMORY;
321 if (need > iob->size)
323 size_t want = iob->size ? iob->size : 512;
330 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
334 else if (NULL != (p = (char *)realloc(iob->buf, need)))
340 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
341 return JB_ERR_MEMORY;
344 /* Update the iob pointers */
345 iob->cur = p + offset;
350 /* copy the new data into the iob buffer */
351 memcpy(iob->eod, src, (size_t)n);
353 /* point to the end of the data */
356 /* null terminate == cheap insurance */
364 /*********************************************************************
366 * Function : clear_iob
368 * Description : Frees the memory allocated for an I/O buffer and
369 * resets the structure.
372 * 1 : iob = I/O buffer to clear.
374 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
375 * or buffer limit reached.
377 *********************************************************************/
378 void clear_iob(struct iob *iob)
381 memset(iob, '\0', sizeof(*iob));;
386 /*********************************************************************
388 * Function : decompress_iob
390 * Description : Decompress buffered page, expanding the
391 * buffer as necessary. csp->iob->cur
392 * should point to the the beginning of the
393 * compressed data block.
396 * 1 : csp = Current client state (buffers, headers, etc...)
398 * Returns : JB_ERR_OK on success,
399 * JB_ERR_MEMORY if out-of-memory limit reached, and
400 * JB_ERR_COMPRESS if error decompressing buffer.
402 *********************************************************************/
403 jb_err decompress_iob(struct client_state *csp)
405 char *buf; /* new, uncompressed buffer */
406 char *cur; /* Current iob position (to keep the original
407 * iob->cur unmodified if we return early) */
408 size_t bufsize; /* allocated size of the new buffer */
409 size_t old_size; /* Content size before decompression */
410 size_t skip_size; /* Number of bytes at the beginning of the iob
411 that we should NOT decompress. */
412 int status; /* return status of the inflate() call */
413 z_stream zstr; /* used by calls to zlib */
415 assert(csp->iob->cur - csp->iob->buf > 0);
416 assert(csp->iob->eod - csp->iob->cur > 0);
418 bufsize = csp->iob->size;
419 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
420 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
424 if (bufsize < (size_t)10)
427 * This is to protect the parsing of gzipped data,
428 * but it should(?) be valid for deflated data also.
430 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
431 return JB_ERR_COMPRESS;
434 if (csp->content_type & CT_GZIP)
437 * Our task is slightly complicated by the facts that data
438 * compressed by gzip does not include a zlib header, and
439 * that there is no easily accessible interface in zlib to
440 * handle a gzip header. We strip off the gzip header by
441 * hand, and later inform zlib not to expect a header.
445 * Strip off the gzip header. Please see RFC 1952 for more
446 * explanation of the appropriate fields.
448 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
449 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
450 || (*cur++ != Z_DEFLATED))
452 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
453 return JB_ERR_COMPRESS;
458 if (flags & GZIP_FLAG_RESERVED_BITS)
460 /* The gzip header has reserved bits set; bail out. */
461 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
462 return JB_ERR_COMPRESS;
466 * Skip mtime (4 bytes), extra flags (1 byte)
467 * and OS type (1 byte).
471 /* Skip extra fields if necessary. */
472 if (flags & GZIP_FLAG_EXTRA_FIELDS)
475 * Skip a given number of bytes, specified
476 * as a 16-bit little-endian value.
478 * XXX: this code is untested and should probably be removed.
482 skip_bytes += *cur++ << 8;
485 * The number of bytes to skip should be positive
486 * and we'd like to stay in the buffer.
488 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
490 log_error(LOG_LEVEL_ERROR,
491 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
493 return JB_ERR_COMPRESS;
495 log_error(LOG_LEVEL_INFO,
496 "Skipping %d bytes for gzip compression. Does this sound right?",
501 /* Skip the filename if necessary. */
502 if (flags & GZIP_FLAG_FILE_NAME)
504 /* A null-terminated string is supposed to follow. */
505 while (*cur++ && (cur < csp->iob->eod));
508 /* Skip the comment if necessary. */
509 if (flags & GZIP_FLAG_COMMENT)
511 /* A null-terminated string is supposed to follow. */
512 while (*cur++ && (cur < csp->iob->eod));
515 /* Skip the CRC if necessary. */
516 if (flags & GZIP_FLAG_CHECKSUM)
521 if (cur >= csp->iob->eod)
524 * If the current position pointer reached or passed
525 * the buffer end, we were obviously tricked to skip
528 log_error(LOG_LEVEL_ERROR,
529 "Malformed gzip header detected. Aborting decompression.");
530 return JB_ERR_COMPRESS;
534 else if (csp->content_type & CT_DEFLATE)
537 * In theory (that is, according to RFC 1950), deflate-compressed
538 * data should begin with a two-byte zlib header and have an
539 * adler32 checksum at the end. It seems that in practice only
540 * the raw compressed data is sent. Note that this means that
541 * we are not RFC 1950-compliant here, but the advantage is that
542 * this actually works. :)
544 * We add a dummy null byte to tell zlib where the data ends,
545 * and later inform it not to expect a header.
547 * Fortunately, add_to_iob() has thoughtfully null-terminated
548 * the buffer; we can just increment the end pointer to include
555 log_error(LOG_LEVEL_ERROR,
556 "Unable to determine compression format for decompression");
557 return JB_ERR_COMPRESS;
560 /* Set up the fields required by zlib. */
561 zstr.next_in = (Bytef *)cur;
562 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
563 zstr.zalloc = Z_NULL;
565 zstr.opaque = Z_NULL;
568 * Passing -MAX_WBITS to inflateInit2 tells the library
569 * that there is no zlib header.
571 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
573 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
574 return JB_ERR_COMPRESS;
578 * Next, we allocate new storage for the inflated data.
579 * We don't modify the existing iob yet, so in case there
580 * is error in decompression we can recover gracefully.
582 buf = zalloc(bufsize);
585 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
586 return JB_ERR_MEMORY;
589 assert(bufsize >= skip_size);
590 memcpy(buf, csp->iob->buf, skip_size);
591 zstr.avail_out = (uInt)(bufsize - skip_size);
592 zstr.next_out = (Bytef *)buf + skip_size;
594 /* Try to decompress the whole stream in one shot. */
595 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
597 /* We need to allocate more memory for the output buffer. */
599 char *tmpbuf; /* used for realloc'ing the buffer */
600 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
602 if (0 == zstr.avail_in)
605 * If zlib wants more data then there's a problem, because
606 * the complete compressed file should have been buffered.
608 log_error(LOG_LEVEL_ERROR,
609 "Unexpected end of compressed iob. Using what we got so far.");
614 * If we reached the buffer limit and still didn't have enough
615 * memory, just give up. Due to the ceiling enforced by the next
616 * if block we could actually check for equality here, but as it
617 * can be easily mistaken for a bug we don't.
619 if (bufsize >= csp->config->buffer_limit)
621 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
622 return JB_ERR_MEMORY;
625 /* Try doubling the buffer size each time. */
628 /* Don't exceed the buffer limit. */
629 if (bufsize > csp->config->buffer_limit)
631 bufsize = csp->config->buffer_limit;
634 /* Try to allocate the new buffer. */
635 tmpbuf = realloc(buf, bufsize);
638 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
640 return JB_ERR_MEMORY;
644 char *oldnext_out = (char *)zstr.next_out;
647 * Update the fields for inflate() to use the new
648 * buffer, which may be in a location different from
651 zstr.avail_out += (uInt)(bufsize - oldbufsize);
652 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
655 * Compare with an uglier method of calculating these values
656 * that doesn't require the extra oldbufsize variable.
658 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
659 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
665 if (Z_STREAM_ERROR == inflateEnd(&zstr))
667 log_error(LOG_LEVEL_ERROR,
668 "Inconsistent stream state after decompression: %s", zstr.msg);
670 * XXX: Intentionally no return.
672 * According to zlib.h, Z_STREAM_ERROR is returned
673 * "if the stream state was inconsistent".
675 * I assume in this case inflate()'s status
676 * would also be something different than Z_STREAM_END
677 * so this check should be redundant, but lets see.
681 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
684 * We failed to decompress the stream and it's
685 * not simply because of missing data.
687 log_error(LOG_LEVEL_ERROR,
688 "Unexpected error while decompressing to the buffer (iob): %s",
690 return JB_ERR_COMPRESS;
694 * Finally, we can actually update the iob, since the
695 * decompression was successful. First, free the old
698 freez(csp->iob->buf);
700 /* Now, update the iob to use the new buffer. */
702 csp->iob->cur = csp->iob->buf + skip_size;
703 csp->iob->eod = (char *)zstr.next_out;
704 csp->iob->size = bufsize;
707 * Make sure the new uncompressed iob obeys some minimal
708 * consistency conditions.
710 if ((csp->iob->buf < csp->iob->cur)
711 && (csp->iob->cur <= csp->iob->eod)
712 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
714 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
715 if (new_size > (size_t)0)
717 log_error(LOG_LEVEL_RE_FILTER,
718 "Decompression successful. Old size: %d, new size: %d.",
723 /* zlib thinks this is OK, so lets do the same. */
724 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
729 /* It seems that zlib did something weird. */
730 log_error(LOG_LEVEL_ERROR,
731 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
732 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
733 csp->iob->eod, csp->iob->buf + csp->iob->size);
734 return JB_ERR_COMPRESS;
740 #endif /* defined(FEATURE_ZLIB) */
743 /*********************************************************************
745 * Function : normalize_lws
747 * Description : Reduces unquoted linear white space in headers
748 * to a single space in accordance with RFC 2616 2.2.
749 * This simplifies parsing and filtering later on.
751 * XXX: Remove log messages before
752 * the next stable release?
755 * 1 : header = A header with linear white space to reduce.
759 *********************************************************************/
760 static void normalize_lws(char *header)
766 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
770 while (privoxy_isspace(*q))
774 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
780 log_error(LOG_LEVEL_HEADER,
781 "Converting tab to space in '%s'", header);
786 char *end_of_token = strstr(p+1, "\"");
788 if (NULL != end_of_token)
790 /* Don't mess with quoted text. */
795 log_error(LOG_LEVEL_HEADER,
796 "Ignoring single quote in '%s'", header);
802 p = strchr(header, ':');
803 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
806 * There's still space before the colon.
814 /*********************************************************************
816 * Function : get_header
818 * Description : This (odd) routine will parse the csp->iob
819 * to get the next complete header.
822 * 1 : iob = The I/O buffer to parse, usually csp->iob.
824 * Returns : Any one of the following:
826 * 1) a pointer to a dynamically allocated string that contains a header line
827 * 2) NULL indicating that the end of the header was reached
828 * 3) "" indicating that the end of the iob was reached before finding
829 * a complete header line.
831 *********************************************************************/
832 char *get_header(struct iob *iob)
836 header = get_header_line(iob);
838 if ((header == NULL) || (*header == '\0'))
841 * No complete header read yet, tell the client.
846 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
849 * Header spans multiple lines, append the next one.
851 char *continued_header;
853 continued_header = get_header_line(iob);
854 if ((continued_header == NULL) || (*continued_header == '\0'))
857 * No complete header read yet, return what we got.
858 * XXX: Should "unread" header instead.
860 log_error(LOG_LEVEL_INFO,
861 "Failed to read a multi-line header properly: '%s'",
866 if (JB_ERR_OK != string_join(&header, continued_header))
868 log_error(LOG_LEVEL_FATAL,
869 "Out of memory while appending multiple headers.");
873 /* XXX: remove before next stable release. */
874 log_error(LOG_LEVEL_HEADER,
875 "Merged multiple header lines to: '%s'",
880 normalize_lws(header);
887 /*********************************************************************
889 * Function : get_header_line
891 * Description : This (odd) routine will parse the csp->iob
892 * to get the next header line.
895 * 1 : iob = The I/O buffer to parse, usually csp->iob.
897 * Returns : Any one of the following:
899 * 1) a pointer to a dynamically allocated string that contains a header line
900 * 2) NULL indicating that the end of the header was reached
901 * 3) "" indicating that the end of the iob was reached before finding
902 * a complete header line.
904 *********************************************************************/
905 static char *get_header_line(struct iob *iob)
909 if ((iob->cur == NULL)
910 || ((p = strchr(iob->cur, '\n')) == NULL))
912 return(""); /* couldn't find a complete header */
917 ret = strdup(iob->cur);
920 /* FIXME No way to handle error properly */
921 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
927 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
929 /* is this a blank line (i.e. the end of the header) ? */
941 /*********************************************************************
943 * Function : get_header_value
945 * Description : Get the value of a given header from a chained list
946 * of header lines or return NULL if no such header is
947 * present in the list.
950 * 1 : header_list = pointer to list
951 * 2 : header_name = string with name of header to look for.
952 * Trailing colon required, capitalization
955 * Returns : NULL if not found, else value of header
957 *********************************************************************/
958 char *get_header_value(const struct list *header_list, const char *header_name)
960 struct list_entry *cur_entry;
966 length = strlen(header_name);
968 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
972 if (!strncmpic(cur_entry->str, header_name, length))
975 * Found: return pointer to start of value
977 ret = cur_entry->str + length;
978 while (*ret && privoxy_isspace(*ret)) ret++;
992 /*********************************************************************
994 * Function : scan_headers
996 * Description : Scans headers, applies tags and updates action bits.
999 * 1 : csp = Current client state (buffers, headers, etc...)
1001 * Returns : JB_ERR_OK
1003 *********************************************************************/
1004 static jb_err scan_headers(struct client_state *csp)
1006 struct list_entry *h; /* Header */
1007 jb_err err = JB_ERR_OK;
1009 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1011 /* Header crunch()ed in previous run? -> ignore */
1012 if (h->str == NULL) continue;
1013 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1014 err = header_tagger(csp, h->str);
1021 /*********************************************************************
1023 * Function : enforce_header_order
1025 * Description : Enforces a given header order.
1028 * 1 : headers = List of headers to order.
1029 * 2 : ordered_headers = List of ordered header names.
1033 *********************************************************************/
1034 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1036 struct list_entry *sorted_header;
1037 struct list new_headers[1];
1038 struct list_entry *header;
1040 init_list(new_headers);
1042 /* The request line is always the first "header" */
1044 assert(NULL != headers->first->str);
1045 enlist(new_headers, headers->first->str);
1046 freez(headers->first->str)
1048 /* Enlist the specified headers in the given order */
1050 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1051 sorted_header = sorted_header->next)
1053 const size_t sorted_header_length = strlen(sorted_header->str);
1054 for (header = headers->first; header != NULL; header = header->next)
1056 /* Header enlisted in previous run? -> ignore */
1057 if (header->str == NULL) continue;
1059 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1060 && (header->str[sorted_header_length] == ':'))
1062 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1063 if (JB_ERR_OK != enlist(new_headers, header->str))
1065 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1072 /* Enlist the rest of the headers behind the ordered ones */
1073 for (header = headers->first; header != NULL; header = header->next)
1075 /* Header enlisted in previous run? -> ignore */
1076 if (header->str == NULL) continue;
1078 log_error(LOG_LEVEL_HEADER,
1079 "Enlisting left-over header %s", header->str);
1080 if (JB_ERR_OK != enlist(new_headers, header->str))
1082 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1087 list_remove_all(headers);
1088 list_duplicate(headers, new_headers);
1089 list_remove_all(new_headers);
1094 /*********************************************************************
1098 * Description : add, delete or modify lines in the HTTP header streams.
1099 * On entry, it receives a linked list of headers space
1100 * that was allocated dynamically (both the list nodes
1101 * and the header contents).
1103 * As a side effect it frees the space used by the original
1107 * 1 : csp = Current client state (buffers, headers, etc...)
1108 * 2 : filter_server_headers = Boolean to switch between
1109 * server and header filtering.
1111 * Returns : JB_ERR_OK in case off success, or
1112 * JB_ERR_MEMORY on out-of-memory error.
1114 *********************************************************************/
1115 jb_err sed(struct client_state *csp, int filter_server_headers)
1117 /* XXX: use more descriptive names. */
1118 struct list_entry *p;
1119 const struct parsers *v;
1120 const add_header_func_ptr *f;
1121 jb_err err = JB_ERR_OK;
1123 if (filter_server_headers)
1125 v = server_patterns;
1126 f = add_server_headers;
1130 v = client_patterns;
1131 f = add_client_headers;
1136 while ((err == JB_ERR_OK) && (v->str != NULL))
1138 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1140 /* Header crunch()ed in previous run? -> ignore */
1141 if (p->str == NULL) continue;
1143 /* Does the current parser handle this header? */
1144 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1145 (v->len == CHECK_EVERY_HEADER_REMAINING))
1147 err = v->parser(csp, &(p->str));
1153 /* place additional headers on the csp->headers list */
1154 while ((err == JB_ERR_OK) && (*f))
1160 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1162 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1169 /*********************************************************************
1171 * Function : update_server_headers
1173 * Description : Updates server headers after the body has been modified.
1176 * 1 : csp = Current client state (buffers, headers, etc...)
1178 * Returns : JB_ERR_OK in case off success, or
1179 * JB_ERR_MEMORY on out-of-memory error.
1181 *********************************************************************/
1182 jb_err update_server_headers(struct client_state *csp)
1184 jb_err err = JB_ERR_OK;
1186 static const struct parsers server_patterns_light[] = {
1187 { "Content-Length:", 15, server_adjust_content_length },
1188 { "Transfer-Encoding:", 18, server_transfer_coding },
1190 { "Content-Encoding:", 17, server_adjust_content_encoding },
1191 #endif /* def FEATURE_ZLIB */
1195 if (strncmpic(csp->http->cmd, "HEAD", 4))
1197 const struct parsers *v;
1198 struct list_entry *p;
1200 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1202 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1204 /* Header crunch()ed in previous run? -> ignore */
1205 if (p->str == NULL) continue;
1207 /* Does the current parser handle this header? */
1208 if (strncmpic(p->str, v->str, v->len) == 0)
1210 err = v->parser(csp, (char **)&(p->str));
1216 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1217 if ((JB_ERR_OK == err)
1218 && (csp->flags & CSP_FLAG_MODIFIED)
1219 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1220 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1224 create_content_length_header(csp->content_length, header, sizeof(header));
1225 err = enlist(csp->headers, header);
1226 if (JB_ERR_OK == err)
1228 log_error(LOG_LEVEL_HEADER,
1229 "Content modified with no Content-Length header set. "
1230 "Created: %s.", header);
1231 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1234 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1236 #ifdef FEATURE_COMPRESSION
1237 if ((JB_ERR_OK == err)
1238 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1240 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1241 if (JB_ERR_OK == err)
1243 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1252 /*********************************************************************
1254 * Function : header_tagger
1256 * Description : Executes all text substitutions from applying
1257 * tag actions and saves the result as tag.
1259 * XXX: Shares enough code with filter_header() and
1260 * pcrs_filter_response() to warrant some helper functions.
1263 * 1 : csp = Current client state (buffers, headers, etc...)
1264 * 2 : header = Header that is used as tagger input
1266 * Returns : JB_ERR_OK on success and always succeeds
1268 *********************************************************************/
1269 static jb_err header_tagger(struct client_state *csp, char *header)
1271 int wanted_filter_type;
1272 int multi_action_index;
1276 struct file_list *fl;
1277 struct re_filterfile_spec *b;
1278 struct list_entry *tag_name;
1280 const size_t header_length = strlen(header);
1282 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1284 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1285 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1289 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1290 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1293 if (filters_available(csp) == FALSE)
1295 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1296 "tagging enabled, but no taggers available.");
1300 for (i = 0; i < MAX_AF_FILES; i++)
1303 if ((NULL == fl) || (NULL == fl->f))
1306 * Either there are no filter files
1307 * left, or this filter file just
1308 * contains no valid filters.
1310 * Continue to be sure we don't miss
1311 * valid filter files that are chained
1312 * after empty or invalid ones.
1317 /* For all filters, */
1318 for (b = fl->f; b; b = b->next)
1320 if (b->type != wanted_filter_type)
1322 /* skip the ones we don't care about, */
1325 /* leaving only taggers that could apply, of which we use the ones, */
1326 for (tag_name = csp->action->multi[multi_action_index]->first;
1327 NULL != tag_name; tag_name = tag_name->next)
1329 /* that do apply, and */
1330 if (strcmp(b->name, tag_name->str) == 0)
1332 char *modified_tag = NULL;
1334 size_t size = header_length;
1335 pcrs_job *joblist = b->joblist;
1337 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1339 if (NULL == joblist)
1341 log_error(LOG_LEVEL_RE_FILTER,
1342 "Tagger %s has empty joblist. Nothing to do.", b->name);
1346 /* execute their pcrs_joblist on the header. */
1347 for (job = joblist; NULL != job; job = job->next)
1349 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1353 /* Success, continue with the modified version. */
1362 /* Tagger doesn't match */
1365 /* Regex failure, log it but continue anyway. */
1366 assert(NULL != header);
1367 log_error(LOG_LEVEL_ERROR,
1368 "Problems with tagger \'%s\' and header \'%s\': %s",
1369 b->name, *header, pcrs_strerror(hits));
1371 freez(modified_tag);
1375 if (b->dynamic) pcrs_free_joblist(joblist);
1377 /* If this tagger matched */
1383 * There is to technical limitation which makes
1384 * it impossible to use empty tags, but I assume
1385 * no one would do it intentionally.
1388 log_error(LOG_LEVEL_INFO,
1389 "Tagger \'%s\' created an empty tag. Ignored.",
1394 if (!list_contains_item(csp->tags, tag))
1396 if (JB_ERR_OK != enlist(csp->tags, tag))
1398 log_error(LOG_LEVEL_ERROR,
1399 "Insufficient memory to add tag \'%s\', "
1400 "based on tagger \'%s\' and header \'%s\'",
1401 tag, b->name, *header);
1405 char *action_message;
1407 * update the action bits right away, to make
1408 * tagging based on tags set by earlier taggers
1409 * of the same kind possible.
1411 if (update_action_bits_for_tag(csp, tag))
1413 action_message = "Action bits updated accordingly.";
1417 action_message = "No action bits update necessary.";
1420 log_error(LOG_LEVEL_HEADER,
1421 "Tagger \'%s\' added tag \'%s\'. %s",
1422 b->name, tag, action_message);
1427 /* XXX: Is this log-worthy? */
1428 log_error(LOG_LEVEL_HEADER,
1429 "Tagger \'%s\' didn't add tag \'%s\'. "
1430 "Tag already present", b->name, tag);
1433 } /* if the tagger matched */
1434 } /* if the tagger applies */
1435 } /* for every tagger that could apply */
1436 } /* for all filters */
1437 } /* for all filter files */
1442 /* here begins the family of parser functions that reformat header lines */
1444 /*********************************************************************
1446 * Function : filter_header
1448 * Description : Executes all text substitutions from all applying
1449 * +(server|client)-header-filter actions on the header.
1450 * Most of the code was copied from pcrs_filter_response,
1451 * including the rather short variable names
1454 * 1 : csp = Current client state (buffers, headers, etc...)
1455 * 2 : header = On input, pointer to header to modify.
1456 * On output, pointer to the modified header, or NULL
1457 * to remove the header. This function frees the
1458 * original string if necessary.
1460 * Returns : JB_ERR_OK on success and always succeeds
1462 *********************************************************************/
1463 static jb_err filter_header(struct client_state *csp, char **header)
1467 size_t size = strlen(*header);
1469 char *newheader = NULL;
1472 struct file_list *fl;
1473 struct re_filterfile_spec *b;
1474 struct list_entry *filtername;
1477 int wanted_filter_type;
1478 int multi_action_index;
1480 if (csp->flags & CSP_FLAG_NO_FILTERING)
1485 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1487 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1488 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1492 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1493 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1496 if (filters_available(csp) == FALSE)
1498 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1499 "header filtering enabled, but no matching filters available.");
1503 for (i = 0; i < MAX_AF_FILES; i++)
1506 if ((NULL == fl) || (NULL == fl->f))
1509 * Either there are no filter files
1510 * left, or this filter file just
1511 * contains no valid filters.
1513 * Continue to be sure we don't miss
1514 * valid filter files that are chained
1515 * after empty or invalid ones.
1520 * For all applying +filter actions, look if a filter by that
1521 * name exists and if yes, execute its pcrs_joblist on the
1524 for (b = fl->f; b; b = b->next)
1526 if (b->type != wanted_filter_type)
1528 /* Skip other filter types */
1532 for (filtername = csp->action->multi[multi_action_index]->first;
1533 filtername ; filtername = filtername->next)
1535 if (strcmp(b->name, filtername->str) == 0)
1537 int current_hits = 0;
1538 pcrs_job *joblist = b->joblist;
1540 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1542 if (NULL == joblist)
1544 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1548 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1549 *header, size, b->name);
1551 /* Apply all jobs from the joblist */
1552 for (job = joblist; NULL != job; job = job->next)
1554 matches = pcrs_execute(job, *header, size, &newheader, &size);
1557 current_hits += matches;
1558 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1560 *header = newheader;
1562 else if (0 == matches)
1564 /* Filter doesn't change header */
1570 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1571 *header, b->name, pcrs_strerror(matches));
1572 if (newheader != NULL)
1574 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1580 if (b->dynamic) pcrs_free_joblist(joblist);
1582 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1583 hits += current_hits;
1590 * Additionally checking for hits is important because if
1591 * the continue hack is triggered, server headers can
1592 * arrive empty to separate multiple heads from each other.
1594 if ((0 == size) && hits)
1596 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1604 /*********************************************************************
1606 * Function : server_connection
1608 * Description : Makes sure a proper "Connection:" header is
1609 * set and signals connection_header_adder to
1613 * 1 : csp = Current client state (buffers, headers, etc...)
1614 * 2 : header = On input, pointer to header to modify.
1615 * On output, pointer to the modified header, or NULL
1616 * to remove the header. This function frees the
1617 * original string if necessary.
1619 * Returns : JB_ERR_OK on success.
1621 *********************************************************************/
1622 static jb_err server_connection(struct client_state *csp, char **header)
1624 if (!strcmpic(*header, "Connection: keep-alive")
1625 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1626 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1630 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1631 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1633 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1636 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1638 log_error(LOG_LEVEL_HEADER,
1639 "Keeping the server header '%s' around.", *header);
1642 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1644 char *old_header = *header;
1646 *header = strdup_or_die("Connection: close");
1647 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1652 /* Signal server_connection_adder() to return early. */
1653 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1659 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1660 /*********************************************************************
1662 * Function : server_keep_alive
1664 * Description : Stores the server's keep alive timeout.
1667 * 1 : csp = Current client state (buffers, headers, etc...)
1668 * 2 : header = On input, pointer to header to modify.
1669 * On output, pointer to the modified header, or NULL
1670 * to remove the header. This function frees the
1671 * original string if necessary.
1673 * Returns : JB_ERR_OK.
1675 *********************************************************************/
1676 static jb_err server_keep_alive(struct client_state *csp, char **header)
1678 unsigned int keep_alive_timeout;
1679 const char *timeout_position = strstr(*header, "timeout=");
1681 if ((NULL == timeout_position)
1682 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1684 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1688 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1690 log_error(LOG_LEVEL_HEADER,
1691 "Reducing keep-alive timeout from %u to %u.",
1692 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1693 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1697 /* XXX: Is this log worthy? */
1698 log_error(LOG_LEVEL_HEADER,
1699 "Server keep-alive timeout is %u. Sticking with %u.",
1700 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1702 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1709 /*********************************************************************
1711 * Function : server_proxy_connection
1713 * Description : Figures out whether or not we should add a
1714 * Proxy-Connection header.
1717 * 1 : csp = Current client state (buffers, headers, etc...)
1718 * 2 : header = On input, pointer to header to modify.
1719 * On output, pointer to the modified header, or NULL
1720 * to remove the header. This function frees the
1721 * original string if necessary.
1723 * Returns : JB_ERR_OK.
1725 *********************************************************************/
1726 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1728 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1733 /*********************************************************************
1735 * Function : client_keep_alive
1737 * Description : Stores the client's keep alive timeout.
1740 * 1 : csp = Current client state (buffers, headers, etc...)
1741 * 2 : header = On input, pointer to header to modify.
1742 * On output, pointer to the modified header, or NULL
1743 * to remove the header. This function frees the
1744 * original string if necessary.
1746 * Returns : JB_ERR_OK.
1748 *********************************************************************/
1749 static jb_err client_keep_alive(struct client_state *csp, char **header)
1751 unsigned int keep_alive_timeout;
1752 const char *timeout_position = strstr(*header, ": ");
1754 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1756 log_error(LOG_LEVEL_HEADER,
1757 "keep-alive support is disabled. Crunching: %s.", *header);
1762 if ((NULL == timeout_position)
1763 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1765 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1769 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1771 log_error(LOG_LEVEL_HEADER,
1772 "Reducing keep-alive timeout from %u to %u.",
1773 csp->config->keep_alive_timeout, keep_alive_timeout);
1774 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1778 /* XXX: Is this log worthy? */
1779 log_error(LOG_LEVEL_HEADER,
1780 "Client keep-alive timeout is %u. Sticking with %u.",
1781 keep_alive_timeout, csp->config->keep_alive_timeout);
1789 /*********************************************************************
1791 * Function : get_content_length
1793 * Description : Gets the content length specified in a
1794 * Content-Length header.
1797 * 1 : header_value = The Content-Length header value.
1798 * 2 : length = Storage to return the value.
1800 * Returns : JB_ERR_OK on success, or
1801 * JB_ERR_PARSE if no value is recognized.
1803 *********************************************************************/
1804 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1807 assert(sizeof(unsigned long long) > 4);
1808 if (1 != sscanf(header_value, "%I64u", length))
1810 if (1 != sscanf(header_value, "%llu", length))
1813 return JB_ERR_PARSE;
1820 /*********************************************************************
1822 * Function : client_save_content_length
1824 * Description : Save the Content-Length sent by the client.
1827 * 1 : csp = Current client state (buffers, headers, etc...)
1828 * 2 : header = On input, pointer to header to modify.
1829 * On output, pointer to the modified header, or NULL
1830 * to remove the header. This function frees the
1831 * original string if necessary.
1833 * Returns : JB_ERR_OK on success, or
1834 * JB_ERR_MEMORY on out-of-memory error.
1836 *********************************************************************/
1837 static jb_err client_save_content_length(struct client_state *csp, char **header)
1839 unsigned long long content_length = 0;
1840 const char *header_value;
1842 assert(*(*header+14) == ':');
1844 header_value = *header + 15;
1845 if (JB_ERR_OK != get_content_length(header_value, &content_length))
1847 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1852 csp->expected_client_content_length = content_length;
1857 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1861 /*********************************************************************
1863 * Function : client_connection
1865 * Description : Makes sure a proper "Connection:" header is
1866 * set and signals connection_header_adder
1870 * 1 : csp = Current client state (buffers, headers, etc...)
1871 * 2 : header = On input, pointer to header to modify.
1872 * On output, pointer to the modified header, or NULL
1873 * to remove the header. This function frees the
1874 * original string if necessary.
1876 * Returns : JB_ERR_OK on success.
1878 *********************************************************************/
1879 static jb_err client_connection(struct client_state *csp, char **header)
1881 static const char connection_close[] = "Connection: close";
1883 if (!strcmpic(*header, connection_close))
1885 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1886 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1887 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1889 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1891 log_error(LOG_LEVEL_HEADER,
1892 "Removing \'%s\' to imply keep-alive.", *header);
1895 * While we imply keep-alive to the server,
1896 * we have to remember that the client didn't.
1898 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1902 char *old_header = *header;
1904 *header = strdup_or_die("Connection: keep-alive");
1905 log_error(LOG_LEVEL_HEADER,
1906 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1912 log_error(LOG_LEVEL_HEADER,
1913 "Keeping the client header '%s' around. "
1914 "The connection will not be kept alive.",
1916 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1919 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1920 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1922 log_error(LOG_LEVEL_HEADER,
1923 "Keeping the client header '%s' around. "
1924 "The server connection will be kept alive if possible.",
1926 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1927 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1931 char *old_header = *header;
1933 *header = strdup_or_die(connection_close);
1934 log_error(LOG_LEVEL_HEADER,
1935 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1939 /* Signal client_connection_header_adder() to return early. */
1940 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1946 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1947 /*********************************************************************
1949 * Function : client_proxy_connection
1951 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
1952 * appropriate and removes the Proxy-Connection
1956 * 1 : csp = Current client state (buffers, headers, etc...)
1957 * 2 : header = On input, pointer to header to modify.
1958 * On output, pointer to the modified header, or NULL
1959 * to remove the header. This function frees the
1960 * original string if necessary.
1962 * Returns : JB_ERR_OK
1964 *********************************************************************/
1965 static jb_err client_proxy_connection(struct client_state *csp, char **header)
1967 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1968 && (csp->http->ssl == 0)
1969 && (NULL == strstr(*header, "close")))
1971 log_error(LOG_LEVEL_HEADER,
1972 "The client connection can be kept alive due to: %s", *header);
1973 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1975 crumble(csp, header);
1979 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1982 /*********************************************************************
1984 * Function : crumble
1986 * Description : This is called if a header matches a pattern to "crunch"
1989 * 1 : csp = Current client state (buffers, headers, etc...)
1990 * 2 : header = On input, pointer to header to modify.
1991 * On output, pointer to the modified header, or NULL
1992 * to remove the header. This function frees the
1993 * original string if necessary.
1995 * Returns : JB_ERR_OK on success, or
1996 * JB_ERR_MEMORY on out-of-memory error.
1998 *********************************************************************/
1999 static jb_err crumble(struct client_state *csp, char **header)
2002 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2008 /*********************************************************************
2010 * Function : crunch_server_header
2012 * Description : Crunch server header if it matches a string supplied by the
2013 * user. Called from `sed'.
2016 * 1 : csp = Current client state (buffers, headers, etc...)
2017 * 2 : header = On input, pointer to header to modify.
2018 * On output, pointer to the modified header, or NULL
2019 * to remove the header. This function frees the
2020 * original string if necessary.
2022 * Returns : JB_ERR_OK on success and always succeeds
2024 *********************************************************************/
2025 static jb_err crunch_server_header(struct client_state *csp, char **header)
2027 const char *crunch_pattern;
2029 /* Do we feel like crunching? */
2030 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2032 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2034 /* Is the current header the lucky one? */
2035 if (strstr(*header, crunch_pattern))
2037 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2046 /*********************************************************************
2048 * Function : server_content_type
2050 * Description : Set the content-type for filterable types (text/.*,
2051 * .*xml.*, .*script.* and image/gif) unless filtering has been
2052 * forbidden (CT_TABOO) while parsing earlier headers.
2053 * NOTE: Since text/plain is commonly used by web servers
2054 * for files whose correct type is unknown, we don't
2055 * set CT_TEXT for it.
2058 * 1 : csp = Current client state (buffers, headers, etc...)
2059 * 2 : header = On input, pointer to header to modify.
2060 * On output, pointer to the modified header, or NULL
2061 * to remove the header. This function frees the
2062 * original string if necessary.
2064 * Returns : JB_ERR_OK on success, or
2065 * JB_ERR_MEMORY on out-of-memory error.
2067 *********************************************************************/
2068 static jb_err server_content_type(struct client_state *csp, char **header)
2070 /* Remove header if it isn't the first Content-Type header */
2071 if ((csp->content_type & CT_DECLARED))
2074 * Another, slightly slower, way to see if
2075 * we already parsed another Content-Type header.
2077 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2079 log_error(LOG_LEVEL_ERROR,
2080 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2088 * Signal that the Content-Type has been set.
2090 csp->content_type |= CT_DECLARED;
2092 if (!(csp->content_type & CT_TABOO))
2095 * XXX: The assumption that text/plain is a sign of
2096 * binary data seems to be somewhat unreasonable nowadays
2097 * and should be dropped after 3.0.8 is out.
2099 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2100 || strstr(*header, "xml")
2101 || strstr(*header, "script"))
2103 csp->content_type |= CT_TEXT;
2105 else if (strstr(*header, "image/gif"))
2107 csp->content_type |= CT_GIF;
2112 * Are we messing with the content type?
2114 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2117 * Make sure the user doesn't accidentally
2118 * change the content type of binary documents.
2120 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2123 *header = strdup_or_die("Content-Type: ");
2124 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2128 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2129 return JB_ERR_MEMORY;
2131 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2135 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2136 "It doesn't look like a content type that should be filtered. "
2137 "Enable force-text-mode if you know what you're doing.", *header);
2145 /*********************************************************************
2147 * Function : server_transfer_coding
2149 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2150 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2151 * - Remove header if body was chunked but has been
2152 * de-chunked for filtering.
2155 * 1 : csp = Current client state (buffers, headers, etc...)
2156 * 2 : header = On input, pointer to header to modify.
2157 * On output, pointer to the modified header, or NULL
2158 * to remove the header. This function frees the
2159 * original string if necessary.
2161 * Returns : JB_ERR_OK on success, or
2162 * JB_ERR_MEMORY on out-of-memory error.
2164 *********************************************************************/
2165 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2168 * Turn off pcrs and gif filtering if body compressed
2170 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2174 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2176 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2177 csp->http->cmd, *header);
2178 #endif /* def FEATURE_ZLIB */
2179 csp->content_type = CT_TABOO;
2183 * Raise flag if body chunked
2185 if (strstr(*header, "chunked"))
2187 csp->flags |= CSP_FLAG_CHUNKED;
2190 * If the body was modified, it has been de-chunked first
2191 * and the header must be removed.
2193 * FIXME: If there is more than one transfer encoding,
2194 * only the "chunked" part should be removed here.
2196 if (csp->flags & CSP_FLAG_MODIFIED)
2198 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2207 /*********************************************************************
2209 * Function : server_content_encoding
2211 * Description : Used to check if the content is compressed, and if
2212 * FEATURE_ZLIB is disabled, filtering is disabled as
2215 * If FEATURE_ZLIB is enabled and the compression type
2216 * supported, the content is marked for decompression.
2218 * XXX: Doesn't properly deal with multiple or with
2219 * unsupported but unknown encodings.
2220 * Is case-sensitive but shouldn't be.
2223 * 1 : csp = Current client state (buffers, headers, etc...)
2224 * 2 : header = On input, pointer to header to modify.
2225 * On output, pointer to the modified header, or NULL
2226 * to remove the header. This function frees the
2227 * original string if necessary.
2229 * Returns : JB_ERR_OK on success, or
2230 * JB_ERR_MEMORY on out-of-memory error.
2232 *********************************************************************/
2233 static jb_err server_content_encoding(struct client_state *csp, char **header)
2236 if (strstr(*header, "sdch"))
2239 * Shared Dictionary Compression over HTTP isn't supported,
2240 * filtering it anyway is pretty much guaranteed to mess up
2243 csp->content_type |= CT_TABOO;
2246 * Log a warning if the user expects the content to be filtered.
2248 if ((csp->rlist != NULL) &&
2249 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2251 log_error(LOG_LEVEL_INFO,
2252 "SDCH-compressed content detected, content filtering disabled. "
2253 "Consider suppressing SDCH offers made by the client.");
2256 else if (strstr(*header, "gzip"))
2258 /* Mark for gzip decompression */
2259 csp->content_type |= CT_GZIP;
2261 else if (strstr(*header, "deflate"))
2263 /* Mark for zlib decompression */
2264 csp->content_type |= CT_DEFLATE;
2266 else if (strstr(*header, "compress"))
2269 * We can't decompress this; therefore we can't filter
2272 csp->content_type |= CT_TABOO;
2274 #else /* !defined(FEATURE_ZLIB) */
2276 * XXX: Using a black list here isn't the right approach.
2278 * In case of SDCH, building with zlib support isn't
2281 if (strstr(*header, "gzip") ||
2282 strstr(*header, "compress") ||
2283 strstr(*header, "deflate") ||
2284 strstr(*header, "sdch"))
2287 * Body is compressed, turn off pcrs and gif filtering.
2289 csp->content_type |= CT_TABOO;
2292 * Log a warning if the user expects the content to be filtered.
2294 if ((csp->rlist != NULL) &&
2295 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2297 log_error(LOG_LEVEL_INFO,
2298 "Compressed content detected, content filtering disabled. "
2299 "Consider recompiling Privoxy with zlib support or "
2300 "enable the prevent-compression action.");
2303 #endif /* defined(FEATURE_ZLIB) */
2311 /*********************************************************************
2313 * Function : server_adjust_content_encoding
2315 * Description : Remove the Content-Encoding header if the
2316 * decompression was successful and the content
2320 * 1 : csp = Current client state (buffers, headers, etc...)
2321 * 2 : header = On input, pointer to header to modify.
2322 * On output, pointer to the modified header, or NULL
2323 * to remove the header. This function frees the
2324 * original string if necessary.
2326 * Returns : JB_ERR_OK on success, or
2327 * JB_ERR_MEMORY on out-of-memory error.
2329 *********************************************************************/
2330 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2332 if ((csp->flags & CSP_FLAG_MODIFIED)
2333 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2336 * We successfully decompressed the content,
2337 * and have to clean the header now, so the
2338 * client no longer expects compressed data.
2340 * XXX: There is a difference between cleaning
2341 * and removing it completely.
2343 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2350 #endif /* defined(FEATURE_ZLIB) */
2353 /*********************************************************************
2355 * Function : server_adjust_content_length
2357 * Description : Adjust Content-Length header if we modified
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_adjust_content_length(struct client_state *csp, char **header)
2373 /* Regenerate header if the content was modified. */
2374 if (csp->flags & CSP_FLAG_MODIFIED)
2376 const size_t header_length = 50;
2378 *header = malloc(header_length);
2379 if (*header == NULL)
2381 return JB_ERR_MEMORY;
2383 create_content_length_header(csp->content_length, *header, header_length);
2384 log_error(LOG_LEVEL_HEADER,
2385 "Adjusted Content-Length to %llu", csp->content_length);
2392 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2393 /*********************************************************************
2395 * Function : server_save_content_length
2397 * Description : Save the Content-Length sent by the server.
2400 * 1 : csp = Current client state (buffers, headers, etc...)
2401 * 2 : header = On input, pointer to header to modify.
2402 * On output, pointer to the modified header, or NULL
2403 * to remove the header. This function frees the
2404 * original string if necessary.
2406 * Returns : JB_ERR_OK on success, or
2407 * JB_ERR_MEMORY on out-of-memory error.
2409 *********************************************************************/
2410 static jb_err server_save_content_length(struct client_state *csp, char **header)
2412 unsigned long long content_length = 0;
2413 const char *header_value;
2415 assert(*(*header+14) == ':');
2417 header_value = *header + 15;
2418 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2420 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2425 csp->expected_content_length = content_length;
2426 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2427 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2432 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2435 /*********************************************************************
2437 * Function : server_content_md5
2439 * Description : Crumble any Content-MD5 headers if the document was
2440 * modified. FIXME: Should we re-compute instead?
2443 * 1 : csp = Current client state (buffers, headers, etc...)
2444 * 2 : header = On input, pointer to header to modify.
2445 * On output, pointer to the modified header, or NULL
2446 * to remove the header. This function frees the
2447 * original string if necessary.
2449 * Returns : JB_ERR_OK on success, or
2450 * JB_ERR_MEMORY on out-of-memory error.
2452 *********************************************************************/
2453 static jb_err server_content_md5(struct client_state *csp, char **header)
2455 if (csp->flags & CSP_FLAG_MODIFIED)
2457 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2465 /*********************************************************************
2467 * Function : server_content_disposition
2469 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2470 * Called from `sed'.
2473 * 1 : csp = Current client state (buffers, headers, etc...)
2474 * 2 : header = On input, pointer to header to modify.
2475 * On output, pointer to the modified header, or NULL
2476 * to remove the header. This function frees the
2477 * original string if necessary.
2479 * Returns : JB_ERR_OK on success, or
2480 * JB_ERR_MEMORY on out-of-memory error.
2482 *********************************************************************/
2483 static jb_err server_content_disposition(struct client_state *csp, char **header)
2488 * Are we messing with the Content-Disposition header?
2490 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2496 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2498 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2501 * Blocking content-disposition header
2503 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2510 * Replacing Content-Disposition header
2513 *header = strdup("Content-Disposition: ");
2514 string_append(header, newval);
2516 if (*header != NULL)
2518 log_error(LOG_LEVEL_HEADER,
2519 "Content-Disposition header crunched and replaced with: %s", *header);
2522 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2526 /*********************************************************************
2528 * Function : server_last_modified
2530 * Description : Changes Last-Modified header to the actual date
2531 * to help hide-if-modified-since.
2532 * Called from `sed'.
2535 * 1 : csp = Current client state (buffers, headers, etc...)
2536 * 2 : header = On input, pointer to header to modify.
2537 * On output, pointer to the modified header, or NULL
2538 * to remove the header. This function frees the
2539 * original string if necessary.
2541 * Returns : JB_ERR_OK on success, or
2542 * JB_ERR_MEMORY on out-of-memory error.
2544 *********************************************************************/
2545 static jb_err server_last_modified(struct client_state *csp, char **header)
2548 time_t last_modified;
2552 * Are we messing with the Last-Modified header?
2554 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2560 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2562 if (0 == strcmpic(newval, "block"))
2565 * Blocking Last-Modified header. Useless but why not.
2567 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2571 else if (0 == strcmpic(newval, "reset-to-request-time"))
2574 * Setting Last-Modified Header to now.
2577 get_http_time(0, buf, sizeof(buf));
2579 *header = strdup("Last-Modified: ");
2580 string_append(header, buf);
2582 if (*header == NULL)
2584 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2588 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2591 else if (0 == strcmpic(newval, "randomize"))
2593 const char *header_time = *header + sizeof("Last-Modified:");
2595 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2597 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2599 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2605 struct tm *timeptr = NULL;
2607 #ifdef HAVE_GMTIME_R
2611 rtime = (long int)difftime(now, last_modified);
2614 long int days, hours, minutes, seconds;
2615 const int negative_delta = (rtime < 0);
2620 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2622 rtime = pick_from_range(rtime);
2627 last_modified += rtime;
2628 #ifdef HAVE_GMTIME_R
2629 timeptr = gmtime_r(&last_modified, &gmt);
2630 #elif defined(MUTEX_LOCKS_AVAILABLE)
2631 privoxy_mutex_lock(&gmtime_mutex);
2632 timeptr = gmtime(&last_modified);
2633 privoxy_mutex_unlock(&gmtime_mutex);
2635 timeptr = gmtime(&last_modified);
2637 if ((NULL == timeptr) || !strftime(newheader,
2638 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2640 log_error(LOG_LEVEL_ERROR,
2641 "Randomizing '%s' failed. Crunching the header without replacement.",
2648 *header = strdup("Last-Modified: ");
2649 string_append(header, newheader);
2651 if (*header == NULL)
2653 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2654 return JB_ERR_MEMORY;
2657 days = rtime / (3600 * 24);
2658 hours = rtime / 3600 % 24;
2659 minutes = rtime / 60 % 60;
2660 seconds = rtime % 60;
2662 log_error(LOG_LEVEL_HEADER,
2663 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2664 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2665 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2669 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2678 /*********************************************************************
2680 * Function : client_accept_encoding
2682 * Description : Rewrite the client's Accept-Encoding header so that
2683 * if doesn't allow compression, if the action applies.
2684 * Note: For HTTP/1.0 the absence of the header is enough.
2687 * 1 : csp = Current client state (buffers, headers, etc...)
2688 * 2 : header = On input, pointer to header to modify.
2689 * On output, pointer to the modified header, or NULL
2690 * to remove the header. This function frees the
2691 * original string if necessary.
2693 * Returns : JB_ERR_OK on success, or
2694 * JB_ERR_MEMORY on out-of-memory error.
2696 *********************************************************************/
2697 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2699 #ifdef FEATURE_COMPRESSION
2700 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2701 && strstr(*header, "deflate"))
2703 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2706 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2708 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2716 /*********************************************************************
2718 * Function : client_te
2720 * Description : Rewrite the client's TE header so that
2721 * if doesn't allow compression, if the action applies.
2724 * 1 : csp = Current client state (buffers, headers, etc...)
2725 * 2 : header = On input, pointer to header to modify.
2726 * On output, pointer to the modified header, or NULL
2727 * to remove the header. This function frees the
2728 * original string if necessary.
2730 * Returns : JB_ERR_OK on success, or
2731 * JB_ERR_MEMORY on out-of-memory error.
2733 *********************************************************************/
2734 static jb_err client_te(struct client_state *csp, char **header)
2736 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2739 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2746 /*********************************************************************
2748 * Function : client_referrer
2750 * Description : Handle the "referer" config setting properly.
2751 * Called from `sed'.
2754 * 1 : csp = Current client state (buffers, headers, etc...)
2755 * 2 : header = On input, pointer to header to modify.
2756 * On output, pointer to the modified header, or NULL
2757 * to remove the header. This function frees the
2758 * original string if necessary.
2760 * Returns : JB_ERR_OK on success, or
2761 * JB_ERR_MEMORY on out-of-memory error.
2763 *********************************************************************/
2764 static jb_err client_referrer(struct client_state *csp, char **header)
2766 const char *parameter;
2767 /* booleans for parameters we have to check multiple times */
2768 int parameter_conditional_block;
2769 int parameter_conditional_forge;
2771 #ifdef FEATURE_FORCE_LOAD
2773 * Since the referrer can include the prefix even
2774 * if the request itself is non-forced, we must
2775 * clean it unconditionally.
2777 * XXX: strclean is too broad
2779 strclean(*header, FORCE_PREFIX);
2780 #endif /* def FEATURE_FORCE_LOAD */
2782 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2784 /* Nothing left to do */
2788 parameter = csp->action->string[ACTION_STRING_REFERER];
2789 assert(parameter != NULL);
2790 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2791 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2793 if (!parameter_conditional_block && !parameter_conditional_forge)
2796 * As conditional-block and conditional-forge are the only
2797 * parameters that rely on the original referrer, we can
2798 * remove it now for all the others.
2803 if (0 == strcmpic(parameter, "block"))
2805 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2808 else if (parameter_conditional_block || parameter_conditional_forge)
2810 return handle_conditional_hide_referrer_parameter(header,
2811 csp->http->hostport, parameter_conditional_block);
2813 else if (0 == strcmpic(parameter, "forge"))
2815 return create_forged_referrer(header, csp->http->hostport);
2819 /* interpret parameter as user-supplied referer to fake */
2820 return create_fake_referrer(header, parameter);
2825 /*********************************************************************
2827 * Function : client_accept_language
2829 * Description : Handle the "Accept-Language" config setting properly.
2830 * Called from `sed'.
2833 * 1 : csp = Current client state (buffers, headers, etc...)
2834 * 2 : header = On input, pointer to header to modify.
2835 * On output, pointer to the modified header, or NULL
2836 * to remove the header. This function frees the
2837 * original string if necessary.
2839 * Returns : JB_ERR_OK on success, or
2840 * JB_ERR_MEMORY on out-of-memory error.
2842 *********************************************************************/
2843 static jb_err client_accept_language(struct client_state *csp, char **header)
2848 * Are we messing with the Accept-Language?
2850 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2852 /*I don't think so*/
2856 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2858 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2861 * Blocking Accept-Language header
2863 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2870 * Replacing Accept-Language header
2873 *header = strdup("Accept-Language: ");
2874 string_append(header, newval);
2876 if (*header == NULL)
2878 log_error(LOG_LEVEL_ERROR,
2879 "Insufficient memory. Accept-Language header crunched without replacement.");
2883 log_error(LOG_LEVEL_HEADER,
2884 "Accept-Language header crunched and replaced with: %s", *header);
2887 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2891 /*********************************************************************
2893 * Function : crunch_client_header
2895 * Description : Crunch client header if it matches a string supplied by the
2896 * user. Called from `sed'.
2899 * 1 : csp = Current client state (buffers, headers, etc...)
2900 * 2 : header = On input, pointer to header to modify.
2901 * On output, pointer to the modified header, or NULL
2902 * to remove the header. This function frees the
2903 * original string if necessary.
2905 * Returns : JB_ERR_OK on success and always succeeds
2907 *********************************************************************/
2908 static jb_err crunch_client_header(struct client_state *csp, char **header)
2910 const char *crunch_pattern;
2912 /* Do we feel like crunching? */
2913 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2915 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2917 /* Is the current header the lucky one? */
2918 if (strstr(*header, crunch_pattern))
2920 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2928 /*********************************************************************
2930 * Function : client_uagent
2932 * Description : Handle the "user-agent" config setting properly
2933 * and remember its original value to enable browser
2934 * bug workarounds. Called from `sed'.
2937 * 1 : csp = Current client state (buffers, headers, etc...)
2938 * 2 : header = On input, pointer to header to modify.
2939 * On output, pointer to the modified header, or NULL
2940 * to remove the header. This function frees the
2941 * original string if necessary.
2943 * Returns : JB_ERR_OK on success, or
2944 * JB_ERR_MEMORY on out-of-memory error.
2946 *********************************************************************/
2947 static jb_err client_uagent(struct client_state *csp, char **header)
2951 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2956 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2963 *header = strdup("User-Agent: ");
2964 string_append(header, newval);
2966 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2968 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2972 /*********************************************************************
2974 * Function : client_ua
2976 * Description : Handle "ua-" headers properly. Called from `sed'.
2979 * 1 : csp = Current client state (buffers, headers, etc...)
2980 * 2 : header = On input, pointer to header to modify.
2981 * On output, pointer to the modified header, or NULL
2982 * to remove the header. This function frees the
2983 * original string if necessary.
2985 * Returns : JB_ERR_OK on success, or
2986 * JB_ERR_MEMORY on out-of-memory error.
2988 *********************************************************************/
2989 static jb_err client_ua(struct client_state *csp, char **header)
2991 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2993 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3001 /*********************************************************************
3003 * Function : client_from
3005 * Description : Handle the "from" config setting properly.
3006 * Called from `sed'.
3009 * 1 : csp = Current client state (buffers, headers, etc...)
3010 * 2 : header = On input, pointer to header to modify.
3011 * On output, pointer to the modified header, or NULL
3012 * to remove the header. This function frees the
3013 * original string if necessary.
3015 * Returns : JB_ERR_OK on success, or
3016 * JB_ERR_MEMORY on out-of-memory error.
3018 *********************************************************************/
3019 static jb_err client_from(struct client_state *csp, char **header)
3023 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3030 newval = csp->action->string[ACTION_STRING_FROM];
3033 * Are we blocking the e-mail address?
3035 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3037 log_error(LOG_LEVEL_HEADER, "crunched From!");
3041 log_error(LOG_LEVEL_HEADER, " modified");
3043 *header = strdup("From: ");
3044 string_append(header, newval);
3046 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3050 /*********************************************************************
3052 * Function : client_send_cookie
3054 * Description : Crunches the "cookie" header if necessary.
3055 * Called from `sed'.
3057 * XXX: Stupid name, doesn't send squat.
3060 * 1 : csp = Current client state (buffers, headers, etc...)
3061 * 2 : header = On input, pointer to header to modify.
3062 * On output, pointer to the modified header, or NULL
3063 * to remove the header. This function frees the
3064 * original string if necessary.
3066 * Returns : JB_ERR_OK on success, or
3067 * JB_ERR_MEMORY on out-of-memory error.
3069 *********************************************************************/
3070 static jb_err client_send_cookie(struct client_state *csp, char **header)
3072 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3074 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3082 /*********************************************************************
3084 * Function : client_x_forwarded
3086 * Description : Handle the "x-forwarded-for" config setting properly,
3087 * also used in the add_client_headers list. Called from `sed'.
3090 * 1 : csp = Current client state (buffers, headers, etc...)
3091 * 2 : header = On input, pointer to header to modify.
3092 * On output, pointer to the modified header, or NULL
3093 * to remove the header. This function frees the
3094 * original string if necessary.
3096 * Returns : JB_ERR_OK on success, or
3097 * JB_ERR_MEMORY on out-of-memory error.
3099 *********************************************************************/
3100 jb_err client_x_forwarded(struct client_state *csp, char **header)
3102 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3104 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3106 if (0 == strcmpic(parameter, "block"))
3109 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3111 else if (0 == strcmpic(parameter, "add"))
3113 string_append(header, ", ");
3114 string_append(header, csp->ip_addr_str);
3116 if (*header == NULL)
3118 return JB_ERR_MEMORY;
3120 log_error(LOG_LEVEL_HEADER,
3121 "Appended client IP address to %s", *header);
3122 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3126 log_error(LOG_LEVEL_FATAL,
3127 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3135 /*********************************************************************
3137 * Function : client_max_forwards
3139 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3140 * from the value of the Max-Forwards header field.
3143 * 1 : csp = Current client state (buffers, headers, etc...)
3144 * 2 : header = On input, pointer to header to modify.
3145 * On output, pointer to the modified header, or NULL
3146 * to remove the header. This function frees the
3147 * original string if necessary.
3149 * Returns : JB_ERR_OK on success, or
3150 * JB_ERR_MEMORY on out-of-memory error.
3152 *********************************************************************/
3153 static jb_err client_max_forwards(struct client_state *csp, char **header)
3157 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3158 (0 == strcmpic(csp->http->gpc, "options")))
3160 assert(*(*header+12) == ':');
3161 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3163 if (max_forwards > 0)
3165 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3166 log_error(LOG_LEVEL_HEADER,
3167 "Max-Forwards value for %s request reduced to %d.",
3168 csp->http->gpc, max_forwards);
3170 else if (max_forwards < 0)
3172 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3178 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3187 /*********************************************************************
3189 * Function : client_host
3191 * Description : If the request URI did not contain host and
3192 * port information, parse and evaluate the Host
3195 * Also, kill ill-formed HOST: headers as sent by
3196 * Apple's iTunes software when used with a proxy.
3199 * 1 : csp = Current client state (buffers, headers, etc...)
3200 * 2 : header = On input, pointer to header to modify.
3201 * On output, pointer to the modified header, or NULL
3202 * to remove the header. This function frees the
3203 * original string if necessary.
3205 * Returns : JB_ERR_OK on success, or
3206 * JB_ERR_MEMORY on out-of-memory error.
3208 *********************************************************************/
3209 static jb_err client_host(struct client_state *csp, char **header)
3214 * If the header field name is all upper-case, chances are that it's
3215 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3216 * not a problem -- they are regenerated later.
3218 if ((*header)[1] == 'O')
3220 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3225 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3226 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3229 p = strdup_or_die((*header)+6);
3231 q = strdup_or_die(p);
3233 freez(csp->http->hostport);
3234 csp->http->hostport = p;
3235 freez(csp->http->host);
3236 csp->http->host = q;
3237 q = strchr(csp->http->host, ':');
3240 /* Terminate hostname and evaluate port string */
3242 csp->http->port = atoi(q);
3246 csp->http->port = csp->http->ssl ? 443 : 80;
3249 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3250 csp->http->hostport, csp->http->host, csp->http->port);
3253 /* Signal client_host_adder() to return right away */
3254 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3260 /*********************************************************************
3262 * Function : client_if_modified_since
3264 * Description : Remove or modify the If-Modified-Since header.
3267 * 1 : csp = Current client state (buffers, headers, etc...)
3268 * 2 : header = On input, pointer to header to modify.
3269 * On output, pointer to the modified header, or NULL
3270 * to remove the header. This function frees the
3271 * original string if necessary.
3273 * Returns : JB_ERR_OK on success, or
3274 * JB_ERR_MEMORY on out-of-memory error.
3276 *********************************************************************/
3277 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3280 #ifdef HAVE_GMTIME_R
3283 struct tm *timeptr = NULL;
3288 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3291 * The client got an error message because of a temporary problem,
3292 * the problem is gone and the client now tries to revalidate our
3293 * error message on the real server. The revalidation would always
3294 * end with the transmission of the whole document and there is
3295 * no need to expose the bogus If-Modified-Since header.
3297 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3300 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3302 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3304 if ((0 == strcmpic(newval, "block")))
3306 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3309 else /* add random value */
3311 const char *header_time = *header + sizeof("If-Modified-Since:");
3313 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3315 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3320 long int hours, minutes, seconds;
3321 long int rtime = strtol(newval, &endptr, 0);
3322 const int negative_range = (rtime < 0);
3326 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3327 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3333 rtime = pick_from_range(rtime);
3337 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3340 tm += rtime * (negative_range ? -1 : 1);
3341 #ifdef HAVE_GMTIME_R
3342 timeptr = gmtime_r(&tm, &gmt);
3343 #elif defined(MUTEX_LOCKS_AVAILABLE)
3344 privoxy_mutex_lock(&gmtime_mutex);
3345 timeptr = gmtime(&tm);
3346 privoxy_mutex_unlock(&gmtime_mutex);
3348 timeptr = gmtime(&tm);
3350 if ((NULL == timeptr) || !strftime(newheader,
3351 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3353 log_error(LOG_LEVEL_ERROR,
3354 "Randomizing '%s' failed. Crunching the header without replacement.",
3361 *header = strdup("If-Modified-Since: ");
3362 string_append(header, newheader);
3364 if (*header == NULL)
3366 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3367 return JB_ERR_MEMORY;
3370 hours = rtime / 3600;
3371 minutes = rtime / 60 % 60;
3372 seconds = rtime % 60;
3374 log_error(LOG_LEVEL_HEADER,
3375 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3376 *header, (negative_range) ? "subtracted" : "added", hours,
3377 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3378 seconds, (seconds == 1) ? ")" : "s)");
3387 /*********************************************************************
3389 * Function : client_if_none_match
3391 * Description : Remove the If-None-Match header.
3394 * 1 : csp = Current client state (buffers, headers, etc...)
3395 * 2 : header = On input, pointer to header to modify.
3396 * On output, pointer to the modified header, or NULL
3397 * to remove the header. This function frees the
3398 * original string if necessary.
3400 * Returns : JB_ERR_OK on success, or
3401 * JB_ERR_MEMORY on out-of-memory error.
3403 *********************************************************************/
3404 static jb_err client_if_none_match(struct client_state *csp, char **header)
3406 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3408 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3416 /*********************************************************************
3418 * Function : client_x_filter
3420 * Description : Disables filtering if the client set "X-Filter: No".
3421 * Called from `sed'.
3424 * 1 : csp = Current client state (buffers, headers, etc...)
3425 * 2 : header = On input, pointer to header to modify.
3426 * On output, pointer to the modified header, or NULL
3427 * to remove the header. This function frees the
3428 * original string if necessary.
3430 * Returns : JB_ERR_OK on success
3432 *********************************************************************/
3433 jb_err client_x_filter(struct client_state *csp, char **header)
3435 if (0 == strcmpic(*header, "X-Filter: No"))
3437 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3439 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3443 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3445 log_error(LOG_LEVEL_HEADER,
3446 "force-text-mode overruled the client's request to fetch without filtering!");
3450 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3451 csp->flags |= CSP_FLAG_NO_FILTERING;
3452 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3454 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3462 /*********************************************************************
3464 * Function : client_range
3466 * Description : Removes Range, Request-Range and If-Range headers if
3467 * content filtering is enabled and the range doesn't
3470 * If the client's version of the document has been
3471 * altered by Privoxy, the server could interpret the
3472 * range differently than the client intended in which
3473 * case the user could end up with corrupted content.
3475 * If the range starts at byte 0 this isn't an issue
3476 * so the header can pass. Partial requests like this
3477 * are used to render preview images for videos without
3478 * downloading the whole video.
3480 * While HTTP doesn't require that range requests are
3481 * honoured and the client could simply abort the download
3482 * after receiving a sufficient amount of data, various
3483 * clients don't handle complete responses to range
3484 * requests gracefully and emit misleading error messages
3488 * 1 : csp = Current client state (buffers, headers, etc...)
3489 * 2 : header = On input, pointer to header to modify.
3490 * On output, pointer to the modified header, or NULL
3491 * to remove the header. This function frees the
3492 * original string if necessary.
3494 * Returns : JB_ERR_OK
3496 *********************************************************************/
3497 static jb_err client_range(struct client_state *csp, char **header)
3499 if (content_filters_enabled(csp->action)
3500 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3502 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3503 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3510 /* the following functions add headers directly to the header list */
3512 /*********************************************************************
3514 * Function : client_host_adder
3516 * Description : Adds the Host: header field if it is missing.
3517 * Called from `sed'.
3520 * 1 : csp = Current client state (buffers, headers, etc...)
3522 * Returns : JB_ERR_OK on success, or
3523 * JB_ERR_MEMORY on out-of-memory error.
3525 *********************************************************************/
3526 static jb_err client_host_adder(struct client_state *csp)
3531 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3533 /* Header already set by the client, nothing to do. */
3537 if (!csp->http->hostport || !*(csp->http->hostport))
3539 /* XXX: When does this happen and why is it OK? */
3540 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3545 * remove 'user:pass@' from 'proto://user:pass@host'
3547 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3553 p = csp->http->hostport;
3556 /* XXX: Just add it, we already made sure that it will be unique */
3557 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3558 err = enlist_unique_header(csp->headers, "Host", p);
3564 /*********************************************************************
3566 * Function : client_xtra_adder
3568 * Description : Used in the add_client_headers list. Called from `sed'.
3571 * 1 : csp = Current client state (buffers, headers, etc...)
3573 * Returns : JB_ERR_OK on success, or
3574 * JB_ERR_MEMORY on out-of-memory error.
3576 *********************************************************************/
3577 static jb_err client_xtra_adder(struct client_state *csp)
3579 struct list_entry *lst;
3582 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3583 lst ; lst = lst->next)
3585 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3586 err = enlist(csp->headers, lst->str);
3598 /*********************************************************************
3600 * Function : client_x_forwarded_for_adder
3602 * Description : Used in the add_client_headers list. Called from `sed'.
3605 * 1 : csp = Current client state (buffers, headers, etc...)
3607 * Returns : JB_ERR_OK on success, or
3608 * JB_ERR_MEMORY on out-of-memory error.
3610 *********************************************************************/
3611 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3613 char *header = NULL;
3616 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3617 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3618 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3621 * If we aren't adding X-Forwarded-For headers,
3622 * or we already appended an existing X-Forwarded-For
3623 * header, there's nothing left to do here.
3628 header = strdup("X-Forwarded-For: ");
3629 string_append(&header, csp->ip_addr_str);
3633 return JB_ERR_MEMORY;
3636 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3637 err = enlist(csp->headers, header);
3644 /*********************************************************************
3646 * Function : server_connection_adder
3648 * Description : Adds an appropriate "Connection:" header to csp->headers
3649 * unless the header was already present. Called from `sed'.
3652 * 1 : csp = Current client state (buffers, headers, etc...)
3654 * Returns : JB_ERR_OK on success, or
3655 * JB_ERR_MEMORY on out-of-memory error.
3657 *********************************************************************/
3658 static jb_err server_connection_adder(struct client_state *csp)
3660 const unsigned int flags = csp->flags;
3661 const char *response_status_line = csp->headers->first->str;
3662 static const char connection_close[] = "Connection: close";
3664 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3665 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3671 * XXX: if we downgraded the response, this check will fail.
3673 if ((csp->config->feature_flags &
3674 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3675 && (NULL != response_status_line)
3676 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3677 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3678 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3682 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3683 "without Connection header implies keep-alive.");
3684 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3688 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3690 return enlist(csp->headers, connection_close);
3694 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3695 /*********************************************************************
3697 * Function : server_proxy_connection_adder
3699 * Description : Adds a "Proxy-Connection: keep-alive" header to
3700 * csp->headers when appropriate.
3703 * 1 : csp = Current client state (buffers, headers, etc...)
3705 * Returns : JB_ERR_OK on success, or
3706 * JB_ERR_MEMORY on out-of-memory error.
3708 *********************************************************************/
3709 static jb_err server_proxy_connection_adder(struct client_state *csp)
3711 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3712 jb_err err = JB_ERR_OK;
3714 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3715 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3716 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3717 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3718 || (csp->flags & CSP_FLAG_CHUNKED)))
3720 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3721 err = enlist(csp->headers, proxy_connection_header);
3726 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3729 /*********************************************************************
3731 * Function : client_connection_header_adder
3733 * Description : Adds a proper "Connection:" header to csp->headers
3734 * unless the header was already present. Called from `sed'.
3737 * 1 : csp = Current client state (buffers, headers, etc...)
3739 * Returns : JB_ERR_OK on success, or
3740 * JB_ERR_MEMORY on out-of-memory error.
3742 *********************************************************************/
3743 static jb_err client_connection_header_adder(struct client_state *csp)
3745 static const char connection_close[] = "Connection: close";
3747 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3748 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3753 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3754 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3755 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3756 && (csp->http->ssl == 0)
3757 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3759 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3762 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3764 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3766 return enlist(csp->headers, connection_close);
3770 /*********************************************************************
3772 * Function : server_http
3774 * Description : - Save the HTTP Status into csp->http->status
3775 * - Set CT_TABOO to prevent filtering if the answer
3776 * is a partial range (HTTP status 206)
3777 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3781 * 1 : csp = Current client state (buffers, headers, etc...)
3782 * 2 : header = On input, pointer to header to modify.
3783 * On output, pointer to the modified header, or NULL
3784 * to remove the header. This function frees the
3785 * original string if necessary.
3787 * Returns : JB_ERR_OK on success, or
3788 * JB_ERR_MEMORY on out-of-memory error.
3790 *********************************************************************/
3791 static jb_err server_http(struct client_state *csp, char **header)
3793 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3794 if (csp->http->status == 206)
3796 csp->content_type = CT_TABOO;
3799 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3801 /* XXX: Should we do a real validity check here? */
3802 if (strlen(*header) > 8)
3805 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3810 * XXX: Should we block the request or
3811 * enlist a valid status code line here?
3813 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3814 "Downgrading to HTTP/1.0 impossible.");
3821 /*********************************************************************
3823 * Function : add_cooky_expiry_date
3825 * Description : Adds a cookie expiry date to a string.
3828 * 1 : cookie = On input, pointer to cookie to modify.
3829 * On output, pointer to the modified header.
3830 * The original string is freed.
3831 * 2 : lifetime = Seconds the cookie should be valid
3835 *********************************************************************/
3836 static void add_cookie_expiry_date(char **cookie, time_t lifetime)
3839 struct tm *timeptr = NULL;
3840 time_t expiry_date = time(NULL) + lifetime;
3841 #ifdef HAVE_GMTIME_R
3844 timeptr = gmtime_r(&expiry_date, &gmt);
3845 #elif defined(MUTEX_LOCKS_AVAILABLE)
3846 privoxy_mutex_lock(&gmtime_mutex);
3847 timeptr = gmtime(&expiry_date);
3848 privoxy_mutex_unlock(&gmtime_mutex);
3850 timeptr = gmtime(&expiry_date);
3853 if (NULL == timeptr)
3855 log_error(LOG_LEVEL_FATAL,
3856 "Failed to get the time in add_cooky_expiry_date()");
3858 strftime(tmp, sizeof(tmp), "; expires=%a, %d-%b-%Y %H:%M:%S GMT", timeptr);
3859 if (JB_ERR_OK != string_append(cookie, tmp))
3861 log_error(LOG_LEVEL_FATAL, "Out of memory in add_cooky_expiry()");
3866 /*********************************************************************
3868 * Function : server_set_cookie
3870 * Description : Handle the server "cookie" header properly.
3871 * Crunch, accept or rewrite it to a session cookie.
3872 * Called from `sed'.
3875 * 1 : csp = Current client state (buffers, headers, etc...)
3876 * 2 : header = On input, pointer to header to modify.
3877 * On output, pointer to the modified header, or NULL
3878 * to remove the header. This function frees the
3879 * original string if necessary.
3881 * Returns : JB_ERR_OK on success, or
3882 * JB_ERR_MEMORY on out-of-memory error.
3884 *********************************************************************/
3885 static jb_err server_set_cookie(struct client_state *csp, char **header)
3887 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
3889 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3892 else if ((0 != (csp->action->flags & ACTION_SESSION_COOKIES_ONLY))
3893 || (0 != (csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME)))
3897 long cookie_lifetime = 0;
3900 NO_EXPIRY_DATE_SPECIFIED,
3901 EXPIRY_DATE_ACCEPTABLE,
3902 EXPIRY_DATE_UNACCEPTABLE
3903 } expiry_date_status = NO_EXPIRY_DATE_SPECIFIED;
3905 /* A variable to store the tag we're working on */
3908 /* Skip "Set-Cookie:" (11 characters) in header */
3909 cur_tag = *header + 11;
3911 /* skip whitespace between "Set-Cookie:" and value */
3912 while (*cur_tag && privoxy_isspace(*cur_tag))
3919 if ((csp->action->flags & ACTION_LIMIT_COOKIE_LIFETIME) != 0)
3921 const char *param = csp->action->string[ACTION_STRING_LIMIT_COOKIE_LIFETIME];
3923 cookie_lifetime = strtol(param, NULL, 0);
3924 if (cookie_lifetime < 0)
3926 log_error(LOG_LEVEL_FATAL, "Invalid cookie lifetime limit: %s", param);
3928 cookie_lifetime *= 60U;
3931 /* Loop through each tag in the cookie */
3935 char *next_tag = strchr(cur_tag, ';');
3936 if (next_tag != NULL)
3938 /* Skip the ';' character itself */
3941 /* skip whitespace ";" and start of tag */
3942 while (*next_tag && privoxy_isspace(*next_tag))
3949 /* "Next tag" is the end of the string */
3950 next_tag = cur_tag + strlen(cur_tag);
3954 * Check the expiration date to see
3955 * if the cookie is still valid, if yes,
3956 * rewrite it to a session cookie.
3958 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3960 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3962 if ((expiration_date[0] == '"')
3963 && (expiration_date[1] != '\0'))
3966 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
3967 * that the expiration date isn't supposed to be quoted,
3968 * but some servers do it anyway.
3973 /* Did we detect the date properly? */
3974 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3977 * Nope, treat it as if it was still valid.
3979 * XXX: Should we remove the whole cookie instead?
3981 log_error(LOG_LEVEL_ERROR,
3982 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3983 string_move(cur_tag, next_tag);
3984 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
3989 * Yes. Check if the cookie is still valid.
3991 * If the cookie is already expired it's probably
3992 * a delete cookie and even if it isn't, the browser
3993 * will discard it anyway.
3997 * XXX: timegm() isn't available on some AmigaOS
3998 * versions and our replacement doesn't work.
4000 * Our options are to either:
4002 * - disable session-cookies-only completely if timegm
4005 * - to simply remove all expired tags, like it has
4006 * been done until Privoxy 3.0.6 and to live with
4007 * the consequence that it can cause login/logout
4008 * problems on servers that don't validate their
4009 * input properly, or
4011 * - to replace it with mktime in which
4012 * case there is a slight chance of valid cookies
4013 * passing as already expired.
4015 * This is the way it's currently done and it's not
4016 * as bad as it sounds. If the missing GMT offset is
4017 * enough to change the result of the expiration check
4018 * the cookie will be only valid for a few hours
4019 * anyway, which in many cases will be shorter
4020 * than a browser session.
4022 if (cookie_time < now)
4024 log_error(LOG_LEVEL_HEADER,
4025 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
4026 /* Just in case some clown sets more then one expiration date */
4028 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4030 else if ((cookie_lifetime != 0) && (cookie_time < (now + cookie_lifetime)))
4032 log_error(LOG_LEVEL_HEADER, "Cookie \'%s\' can pass unmodified. "
4033 "Its lifetime is below the limit.", *header);
4034 /* Just in case some clown sets more then one expiration date */
4036 expiry_date_status = EXPIRY_DATE_ACCEPTABLE;
4041 * Still valid, delete expiration date by copying
4042 * the rest of the string over it.
4044 string_move(cur_tag, next_tag);
4046 /* That changed the header, need to issue a log message */
4047 expiry_date_status = EXPIRY_DATE_UNACCEPTABLE;
4050 * Note that the next tag has now been moved to *cur_tag,
4051 * so we do not need to update the cur_tag pointer.
4059 /* Move on to next cookie tag */
4064 if (expiry_date_status != EXPIRY_DATE_ACCEPTABLE)
4066 assert(NULL != *header);
4067 if (cookie_lifetime != 0)
4069 add_cookie_expiry_date(header, cookie_lifetime);
4070 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to: %s", *header);
4072 else if (expiry_date_status != NO_EXPIRY_DATE_SPECIFIED)
4074 log_error(LOG_LEVEL_HEADER,
4075 "Cookie rewritten to a temporary one: %s", *header);
4084 #ifdef FEATURE_FORCE_LOAD
4085 /*********************************************************************
4087 * Function : strclean
4089 * Description : In-Situ-Eliminate all occurrences of substring in
4093 * 1 : string = string to clean
4094 * 2 : substring = substring to eliminate
4096 * Returns : Number of eliminations
4098 *********************************************************************/
4099 int strclean(char *string, const char *substring)
4105 len = strlen(substring);
4107 while((pos = strstr(string, substring)) != NULL)
4114 while (*p++ != '\0');
4121 #endif /* def FEATURE_FORCE_LOAD */
4124 /*********************************************************************
4126 * Function : parse_header_time
4128 * Description : Parses time formats used in HTTP header strings
4129 * to get the numerical respresentation.
4132 * 1 : header_time = HTTP header time as string.
4133 * 2 : result = storage for header_time in seconds
4135 * Returns : JB_ERR_OK if the time format was recognized, or
4136 * JB_ERR_PARSE otherwise.
4138 *********************************************************************/
4139 static jb_err parse_header_time(const char *header_time, time_t *result)
4143 * Checking for two-digit years first in an
4144 * attempt to work around GNU libc's strptime()
4145 * reporting negative year values when using %Y.
4147 static const char time_formats[][22] = {
4148 /* Tue, 02-Jun-37 20:00:00 */
4149 "%a, %d-%b-%y %H:%M:%S",
4150 /* Tue, 02 Jun 2037 20:00:00 */
4151 "%a, %d %b %Y %H:%M:%S",
4152 /* Tue, 02-Jun-2037 20:00:00 */
4153 "%a, %d-%b-%Y %H:%M:%S",
4154 /* Tuesday, 02-Jun-2037 20:00:00 */
4155 "%A, %d-%b-%Y %H:%M:%S",
4156 /* Tuesday Jun 02 20:00:00 2037 */
4157 "%A %b %d %H:%M:%S %Y"
4161 for (i = 0; i < SZ(time_formats); i++)
4164 * Zero out gmt to prevent time zone offsets.
4165 * Documented to be required for GNU libc.
4167 memset(&gmt, 0, sizeof(gmt));
4169 if (NULL != strptime(header_time, time_formats[i], &gmt))
4171 /* Sanity check for GNU libc. */
4172 if (gmt.tm_year < 0)
4174 log_error(LOG_LEVEL_HEADER,
4175 "Failed to parse '%s' using '%s'. Moving on.",
4176 header_time, time_formats[i]);
4179 *result = timegm(&gmt);
4184 return JB_ERR_PARSE;
4189 /*********************************************************************
4191 * Function : get_destination_from_headers
4193 * Description : Parse the "Host:" header to get the request's destination.
4194 * Only needed if the client's request was forcefully
4195 * redirected into Privoxy.
4197 * Code mainly copied from client_host() which is currently
4198 * run too late for this purpose.
4201 * 1 : headers = List of headers (one of them hopefully being
4202 * the "Host:" header)
4203 * 2 : http = storage for the result (host, port and hostport).
4205 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4206 * JB_ERR_PARSE if the host header couldn't be found,
4207 * JB_ERR_OK otherwise.
4209 *********************************************************************/
4210 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4216 host = get_header_value(headers, "Host:");
4220 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4221 return JB_ERR_PARSE;
4224 p = strdup_or_die(host);
4226 q = strdup_or_die(p);
4228 freez(http->hostport);
4232 q = strchr(http->host, ':');
4235 /* Terminate hostname and evaluate port string */
4237 http->port = atoi(q);
4241 http->port = http->ssl ? 443 : 80;
4244 /* Rebuild request URL */
4246 http->url = strdup(http->ssl ? "https://" : "http://");
4247 string_append(&http->url, http->hostport);
4248 string_append(&http->url, http->path);
4249 if (http->url == NULL)
4251 return JB_ERR_MEMORY;
4254 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4262 /*********************************************************************
4264 * Function : create_forged_referrer
4266 * Description : Helper for client_referrer to forge a referer as
4267 * 'http://hostname[:port]/' to fool stupid
4268 * checks for in-site links
4271 * 1 : header = Pointer to header pointer
4272 * 2 : hostport = Host and optionally port as string
4274 * Returns : JB_ERR_OK in case of success, or
4275 * JB_ERR_MEMORY in case of memory problems.
4277 *********************************************************************/
4278 static jb_err create_forged_referrer(char **header, const char *hostport)
4280 assert(NULL == *header);
4282 *header = strdup("Referer: http://");
4283 string_append(header, hostport);
4284 string_append(header, "/");
4286 if (NULL == *header)
4288 return JB_ERR_MEMORY;
4291 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4298 /*********************************************************************
4300 * Function : create_fake_referrer
4302 * Description : Helper for client_referrer to create a fake referrer
4303 * based on a string supplied by the user.
4306 * 1 : header = Pointer to header pointer
4307 * 2 : hosthost = Referrer to fake
4309 * Returns : JB_ERR_OK in case of success, or
4310 * JB_ERR_MEMORY in case of memory problems.
4312 *********************************************************************/
4313 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4315 assert(NULL == *header);
4317 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4319 log_error(LOG_LEVEL_HEADER,
4320 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4322 *header = strdup("Referer: ");
4323 string_append(header, fake_referrer);
4325 if (NULL == *header)
4327 return JB_ERR_MEMORY;
4330 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4337 /*********************************************************************
4339 * Function : handle_conditional_hide_referrer_parameter
4341 * Description : Helper for client_referrer to crunch or forge
4342 * the referrer header if the host has changed.
4345 * 1 : header = Pointer to header pointer
4346 * 2 : host = The target host (may include the port)
4347 * 3 : parameter_conditional_block = Boolean to signal
4348 * if we're in conditional-block mode. If not set,
4349 * we're in conditional-forge mode.
4351 * Returns : JB_ERR_OK in case of success, or
4352 * JB_ERR_MEMORY in case of memory problems.
4354 *********************************************************************/
4355 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4356 const char *host, const int parameter_conditional_block)
4358 char *referer = strdup_or_die(*header);
4359 const size_t hostlength = strlen(host);
4360 const char *referer_url = NULL;
4362 /* referer begins with 'Referer: http[s]://' */
4363 if ((hostlength+17) < strlen(referer))
4366 * Shorten referer to make sure the referer is blocked
4367 * if www.example.org/www.example.com-shall-see-the-referer/
4368 * links to www.example.com/
4370 referer[hostlength+17] = '\0';
4372 referer_url = strstr(referer, "http://");
4373 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4375 /* Host has changed, Referer is invalid or a https URL. */
4376 if (parameter_conditional_block)
4378 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4385 return create_forged_referrer(header, host);
4395 /*********************************************************************
4397 * Function : create_content_length_header
4399 * Description : Creates a Content-Length header.
4402 * 1 : content_length = The content length to be used in the header.
4403 * 2 : header = Allocated space to safe the header.
4404 * 3 : buffer_length = The length of the allocated space.
4408 *********************************************************************/
4409 static void create_content_length_header(unsigned long long content_length,
4410 char *header, size_t buffer_length)
4412 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4416 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4417 /*********************************************************************
4419 * Function : get_expected_content_length
4421 * Description : Figures out the content length from a list of headers.
4424 * 1 : headers = List of headers
4426 * Returns : Number of bytes to expect
4428 *********************************************************************/
4429 unsigned long long get_expected_content_length(struct list *headers)
4431 const char *content_length_header;
4432 unsigned long long content_length = 0;
4434 content_length_header = get_header_value(headers, "Content-Length:");
4435 if (content_length_header != NULL)
4437 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4439 log_error(LOG_LEVEL_ERROR,
4440 "Failed to get the Content-Length in %s", content_length_header);
4441 /* XXX: The header will be removed later on */
4446 return content_length;