1 const char parsers_rcs[] = "$Id: parsers.c,v 1.245 2012/04/06 15:17:10 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
8 * Copyright : Written by and Copyright (C) 2001-2012 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
40 #include <sys/types.h>
50 * Convince GNU's libc to provide a strptime prototype.
59 #define GZIP_IDENTIFIER_1 0x1f
60 #define GZIP_IDENTIFIER_2 0x8b
62 #define GZIP_FLAG_CHECKSUM 0x02
63 #define GZIP_FLAG_EXTRA_FIELDS 0x04
64 #define GZIP_FLAG_FILE_NAME 0x08
65 #define GZIP_FLAG_COMMENT 0x10
66 #define GZIP_FLAG_RESERVED_BITS 0xe0
69 #if !defined(_WIN32) && !defined(__OS2__)
75 #ifdef FEATURE_PTHREAD
77 /* jcc.h is for mutex semapores only */
78 #endif /* def FEATURE_PTHREAD */
83 #include "jbsockets.h"
93 const char parsers_h_rcs[] = PARSERS_H_VERSION;
95 static char *get_header_line(struct iob *iob);
96 static jb_err scan_headers(struct client_state *csp);
97 static jb_err header_tagger(struct client_state *csp, char *header);
98 static jb_err parse_header_time(const char *header_time, time_t *result);
100 static jb_err crumble (struct client_state *csp, char **header);
101 static jb_err filter_header (struct client_state *csp, char **header);
102 static jb_err client_connection (struct client_state *csp, char **header);
103 static jb_err client_referrer (struct client_state *csp, char **header);
104 static jb_err client_uagent (struct client_state *csp, char **header);
105 static jb_err client_ua (struct client_state *csp, char **header);
106 static jb_err client_from (struct client_state *csp, char **header);
107 static jb_err client_send_cookie (struct client_state *csp, char **header);
108 static jb_err client_x_forwarded (struct client_state *csp, char **header);
109 static jb_err client_accept_encoding (struct client_state *csp, char **header);
110 static jb_err client_te (struct client_state *csp, char **header);
111 static jb_err client_max_forwards (struct client_state *csp, char **header);
112 static jb_err client_host (struct client_state *csp, char **header);
113 static jb_err client_if_modified_since (struct client_state *csp, char **header);
114 static jb_err client_accept_language (struct client_state *csp, char **header);
115 static jb_err client_if_none_match (struct client_state *csp, char **header);
116 static jb_err crunch_client_header (struct client_state *csp, char **header);
117 static jb_err client_x_filter (struct client_state *csp, char **header);
118 static jb_err client_range (struct client_state *csp, char **header);
119 static jb_err server_set_cookie (struct client_state *csp, char **header);
120 static jb_err server_connection (struct client_state *csp, char **header);
121 static jb_err server_content_type (struct client_state *csp, char **header);
122 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
123 static jb_err server_content_md5 (struct client_state *csp, char **header);
124 static jb_err server_content_encoding (struct client_state *csp, char **header);
125 static jb_err server_transfer_coding (struct client_state *csp, char **header);
126 static jb_err server_http (struct client_state *csp, char **header);
127 static jb_err crunch_server_header (struct client_state *csp, char **header);
128 static jb_err server_last_modified (struct client_state *csp, char **header);
129 static jb_err server_content_disposition(struct client_state *csp, char **header);
131 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
134 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
135 static jb_err server_save_content_length(struct client_state *csp, char **header);
136 static jb_err server_keep_alive(struct client_state *csp, char **header);
137 static jb_err server_proxy_connection(struct client_state *csp, char **header);
138 static jb_err client_keep_alive(struct client_state *csp, char **header);
139 static jb_err client_save_content_length(struct client_state *csp, char **header);
140 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
142 static jb_err client_host_adder (struct client_state *csp);
143 static jb_err client_xtra_adder (struct client_state *csp);
144 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
145 static jb_err client_connection_header_adder(struct client_state *csp);
146 static jb_err server_connection_adder(struct client_state *csp);
147 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
148 static jb_err server_proxy_connection_adder(struct client_state *csp);
149 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
151 static jb_err create_forged_referrer(char **header, const char *hostport);
152 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
153 static jb_err handle_conditional_hide_referrer_parameter(char **header,
154 const char *host, const int parameter_conditional_block);
155 static void create_content_length_header(unsigned long long content_length,
156 char *header, size_t buffer_length);
159 * List of functions to run on a list of headers.
163 /** The header prefix to match */
166 /** The length of the prefix to match */
169 /** The function to apply to this line */
170 const parser_func_ptr parser;
173 static const struct parsers client_patterns[] = {
174 { "referer:", 8, client_referrer },
175 { "user-agent:", 11, client_uagent },
176 { "ua-", 3, client_ua },
177 { "from:", 5, client_from },
178 { "cookie:", 7, client_send_cookie },
179 { "x-forwarded-for:", 16, client_x_forwarded },
180 { "Accept-Encoding:", 16, client_accept_encoding },
181 { "TE:", 3, client_te },
182 { "Host:", 5, client_host },
183 { "if-modified-since:", 18, client_if_modified_since },
184 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
185 { "Keep-Alive:", 11, client_keep_alive },
186 { "Content-Length:", 15, client_save_content_length },
188 { "Keep-Alive:", 11, crumble },
190 { "connection:", 11, client_connection },
191 { "proxy-connection:", 17, crumble },
192 { "max-forwards:", 13, client_max_forwards },
193 { "Accept-Language:", 16, client_accept_language },
194 { "if-none-match:", 14, client_if_none_match },
195 { "Range:", 6, client_range },
196 { "Request-Range:", 14, client_range },
197 { "If-Range:", 9, client_range },
198 { "X-Filter:", 9, client_x_filter },
199 { "*", 0, crunch_client_header },
200 { "*", 0, filter_header },
204 static const struct parsers server_patterns[] = {
205 { "HTTP/", 5, server_http },
206 { "set-cookie:", 11, server_set_cookie },
207 { "connection:", 11, server_connection },
208 { "Content-Type:", 13, server_content_type },
209 { "Content-MD5:", 12, server_content_md5 },
210 { "Content-Encoding:", 17, server_content_encoding },
211 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
212 { "Content-Length:", 15, server_save_content_length },
213 { "Keep-Alive:", 11, server_keep_alive },
214 { "Proxy-Connection:", 17, server_proxy_connection },
216 { "Keep-Alive:", 11, crumble },
217 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
218 { "Transfer-Encoding:", 18, server_transfer_coding },
219 { "content-disposition:", 20, server_content_disposition },
220 { "Last-Modified:", 14, server_last_modified },
221 { "*", 0, crunch_server_header },
222 { "*", 0, filter_header },
226 static const add_header_func_ptr add_client_headers[] = {
228 client_x_forwarded_for_adder,
230 client_connection_header_adder,
234 static const add_header_func_ptr add_server_headers[] = {
235 server_connection_adder,
236 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
237 server_proxy_connection_adder,
238 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
242 /*********************************************************************
244 * Function : flush_socket
246 * Description : Write any pending "buffered" content.
249 * 1 : fd = file descriptor of the socket to read
250 * 2 : iob = The I/O buffer to flush, usually csp->iob.
252 * Returns : On success, the number of bytes written are returned (zero
253 * indicates nothing was written). On error, -1 is returned,
254 * and errno is set appropriately. If count is zero and the
255 * file descriptor refers to a regular file, 0 will be
256 * returned without causing any other effect. For a special
257 * file, the results are not portable.
259 *********************************************************************/
260 long flush_socket(jb_socket fd, struct iob *iob)
262 long len = iob->eod - iob->cur;
269 if (write_socket(fd, iob->cur, (size_t)len))
273 iob->eod = iob->cur = iob->buf;
279 /*********************************************************************
281 * Function : add_to_iob
283 * Description : Add content to the buffered page, expanding the
284 * buffer if necessary.
287 * 1 : csp = Current client state (buffers, headers, etc...)
288 * 2 : buf = holds the content to be added to the page
289 * 3 : n = number of bytes to be added
291 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
292 * or buffer limit reached.
294 *********************************************************************/
295 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
297 struct iob *iob = csp->iob;
298 size_t used, offset, need;
301 if (n <= 0) return JB_ERR_OK;
303 used = (size_t)(iob->eod - iob->buf);
304 offset = (size_t)(iob->cur - iob->buf);
305 need = used + (size_t)n + 1;
308 * If the buffer can't hold the new data, extend it first.
309 * Use the next power of two if possible, else use the actual need.
311 if (need > csp->config->buffer_limit)
313 log_error(LOG_LEVEL_INFO,
314 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
315 need, csp->config->buffer_limit);
316 return JB_ERR_MEMORY;
319 if (need > iob->size)
321 size_t want = csp->iob->size ? csp->iob->size : 512;
328 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
332 else if (NULL != (p = (char *)realloc(iob->buf, need)))
338 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
339 return JB_ERR_MEMORY;
342 /* Update the iob pointers */
343 iob->cur = p + offset;
348 /* copy the new data into the iob buffer */
349 memcpy(iob->eod, buf, (size_t)n);
351 /* point to the end of the data */
354 /* null terminate == cheap insurance */
363 /*********************************************************************
365 * Function : decompress_iob
367 * Description : Decompress buffered page, expanding the
368 * buffer as necessary. csp->iob->cur
369 * should point to the the beginning of the
370 * compressed data block.
373 * 1 : csp = Current client state (buffers, headers, etc...)
375 * Returns : JB_ERR_OK on success,
376 * JB_ERR_MEMORY if out-of-memory limit reached, and
377 * JB_ERR_COMPRESS if error decompressing buffer.
379 *********************************************************************/
380 jb_err decompress_iob(struct client_state *csp)
382 char *buf; /* new, uncompressed buffer */
383 char *cur; /* Current iob position (to keep the original
384 * iob->cur unmodified if we return early) */
385 size_t bufsize; /* allocated size of the new buffer */
386 size_t old_size; /* Content size before decompression */
387 size_t skip_size; /* Number of bytes at the beginning of the iob
388 that we should NOT decompress. */
389 int status; /* return status of the inflate() call */
390 z_stream zstr; /* used by calls to zlib */
392 assert(csp->iob->cur - csp->iob->buf > 0);
393 assert(csp->iob->eod - csp->iob->cur > 0);
395 bufsize = csp->iob->size;
396 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
397 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
401 if (bufsize < (size_t)10)
404 * This is to protect the parsing of gzipped data,
405 * but it should(?) be valid for deflated data also.
407 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
408 return JB_ERR_COMPRESS;
411 if (csp->content_type & CT_GZIP)
414 * Our task is slightly complicated by the facts that data
415 * compressed by gzip does not include a zlib header, and
416 * that there is no easily accessible interface in zlib to
417 * handle a gzip header. We strip off the gzip header by
418 * hand, and later inform zlib not to expect a header.
422 * Strip off the gzip header. Please see RFC 1952 for more
423 * explanation of the appropriate fields.
425 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
426 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
427 || (*cur++ != Z_DEFLATED))
429 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
430 return JB_ERR_COMPRESS;
435 if (flags & GZIP_FLAG_RESERVED_BITS)
437 /* The gzip header has reserved bits set; bail out. */
438 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
439 return JB_ERR_COMPRESS;
443 * Skip mtime (4 bytes), extra flags (1 byte)
444 * and OS type (1 byte).
448 /* Skip extra fields if necessary. */
449 if (flags & GZIP_FLAG_EXTRA_FIELDS)
452 * Skip a given number of bytes, specified
453 * as a 16-bit little-endian value.
455 * XXX: this code is untested and should probably be removed.
459 skip_bytes += *cur++ << 8;
462 * The number of bytes to skip should be positive
463 * and we'd like to stay in the buffer.
465 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
467 log_error(LOG_LEVEL_ERROR,
468 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
470 return JB_ERR_COMPRESS;
472 log_error(LOG_LEVEL_INFO,
473 "Skipping %d bytes for gzip compression. Does this sound right?",
478 /* Skip the filename if necessary. */
479 if (flags & GZIP_FLAG_FILE_NAME)
481 /* A null-terminated string is supposed to follow. */
482 while (*cur++ && (cur < csp->iob->eod));
485 /* Skip the comment if necessary. */
486 if (flags & GZIP_FLAG_COMMENT)
488 /* A null-terminated string is supposed to follow. */
489 while (*cur++ && (cur < csp->iob->eod));
492 /* Skip the CRC if necessary. */
493 if (flags & GZIP_FLAG_CHECKSUM)
498 if (cur >= csp->iob->eod)
501 * If the current position pointer reached or passed
502 * the buffer end, we were obviously tricked to skip
505 log_error(LOG_LEVEL_ERROR,
506 "Malformed gzip header detected. Aborting decompression.");
507 return JB_ERR_COMPRESS;
511 else if (csp->content_type & CT_DEFLATE)
514 * XXX: The debug level should be lowered
515 * before the next stable release.
517 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
519 * In theory (that is, according to RFC 1950), deflate-compressed
520 * data should begin with a two-byte zlib header and have an
521 * adler32 checksum at the end. It seems that in practice only
522 * the raw compressed data is sent. Note that this means that
523 * we are not RFC 1950-compliant here, but the advantage is that
524 * this actually works. :)
526 * We add a dummy null byte to tell zlib where the data ends,
527 * and later inform it not to expect a header.
529 * Fortunately, add_to_iob() has thoughtfully null-terminated
530 * the buffer; we can just increment the end pointer to include
537 log_error(LOG_LEVEL_ERROR,
538 "Unable to determine compression format for decompression");
539 return JB_ERR_COMPRESS;
542 /* Set up the fields required by zlib. */
543 zstr.next_in = (Bytef *)cur;
544 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
545 zstr.zalloc = Z_NULL;
547 zstr.opaque = Z_NULL;
550 * Passing -MAX_WBITS to inflateInit2 tells the library
551 * that there is no zlib header.
553 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
555 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
556 return JB_ERR_COMPRESS;
560 * Next, we allocate new storage for the inflated data.
561 * We don't modify the existing iob yet, so in case there
562 * is error in decompression we can recover gracefully.
564 buf = zalloc(bufsize);
567 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
568 return JB_ERR_MEMORY;
571 assert(bufsize >= skip_size);
572 memcpy(buf, csp->iob->buf, skip_size);
573 zstr.avail_out = (uInt)(bufsize - skip_size);
574 zstr.next_out = (Bytef *)buf + skip_size;
576 /* Try to decompress the whole stream in one shot. */
577 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
579 /* We need to allocate more memory for the output buffer. */
581 char *tmpbuf; /* used for realloc'ing the buffer */
582 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
584 if (0 == zstr.avail_in)
587 * If zlib wants more data then there's a problem, because
588 * the complete compressed file should have been buffered.
590 log_error(LOG_LEVEL_ERROR,
591 "Unexpected end of compressed iob. Using what we got so far.");
596 * If we reached the buffer limit and still didn't have enough
597 * memory, just give up. Due to the ceiling enforced by the next
598 * if block we could actually check for equality here, but as it
599 * can be easily mistaken for a bug we don't.
601 if (bufsize >= csp->config->buffer_limit)
603 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
604 return JB_ERR_MEMORY;
607 /* Try doubling the buffer size each time. */
610 /* Don't exceed the buffer limit. */
611 if (bufsize > csp->config->buffer_limit)
613 bufsize = csp->config->buffer_limit;
616 /* Try to allocate the new buffer. */
617 tmpbuf = realloc(buf, bufsize);
620 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
622 return JB_ERR_MEMORY;
626 char *oldnext_out = (char *)zstr.next_out;
629 * Update the fields for inflate() to use the new
630 * buffer, which may be in a location different from
633 zstr.avail_out += (uInt)(bufsize - oldbufsize);
634 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
637 * Compare with an uglier method of calculating these values
638 * that doesn't require the extra oldbufsize variable.
640 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
641 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
647 if (Z_STREAM_ERROR == inflateEnd(&zstr))
649 log_error(LOG_LEVEL_ERROR,
650 "Inconsistent stream state after decompression: %s", zstr.msg);
652 * XXX: Intentionally no return.
654 * According to zlib.h, Z_STREAM_ERROR is returned
655 * "if the stream state was inconsistent".
657 * I assume in this case inflate()'s status
658 * would also be something different than Z_STREAM_END
659 * so this check should be redundant, but lets see.
663 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
666 * We failed to decompress the stream and it's
667 * not simply because of missing data.
669 log_error(LOG_LEVEL_ERROR,
670 "Unexpected error while decompressing to the buffer (iob): %s",
672 return JB_ERR_COMPRESS;
676 * Finally, we can actually update the iob, since the
677 * decompression was successful. First, free the old
680 freez(csp->iob->buf);
682 /* Now, update the iob to use the new buffer. */
684 csp->iob->cur = csp->iob->buf + skip_size;
685 csp->iob->eod = (char *)zstr.next_out;
686 csp->iob->size = bufsize;
689 * Make sure the new uncompressed iob obeys some minimal
690 * consistency conditions.
692 if ((csp->iob->buf < csp->iob->cur)
693 && (csp->iob->cur <= csp->iob->eod)
694 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
696 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
697 if (new_size > (size_t)0)
699 log_error(LOG_LEVEL_RE_FILTER,
700 "Decompression successful. Old size: %d, new size: %d.",
705 /* zlib thinks this is OK, so lets do the same. */
706 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
711 /* It seems that zlib did something weird. */
712 log_error(LOG_LEVEL_ERROR,
713 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
714 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
715 csp->iob->eod, csp->iob->buf + csp->iob->size);
716 return JB_ERR_COMPRESS;
722 #endif /* defined(FEATURE_ZLIB) */
725 /*********************************************************************
727 * Function : string_move
729 * Description : memmove wrapper to move the last part of a string
730 * towards the beginning, overwriting the part in
731 * the middle. strlcpy() can't be used here as the
735 * 1 : dst = Destination to overwrite
736 * 2 : src = Source to move.
740 *********************************************************************/
741 static void string_move(char *dst, char *src)
745 /* +1 to copy the terminating nul as well. */
746 memmove(dst, src, strlen(src)+1);
750 /*********************************************************************
752 * Function : normalize_lws
754 * Description : Reduces unquoted linear white space in headers
755 * to a single space in accordance with RFC 2616 2.2.
756 * This simplifies parsing and filtering later on.
758 * XXX: Remove log messages before
759 * the next stable release?
762 * 1 : header = A header with linear white space to reduce.
766 *********************************************************************/
767 static void normalize_lws(char *header)
773 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
777 while (privoxy_isspace(*q))
781 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
787 log_error(LOG_LEVEL_HEADER,
788 "Converting tab to space in '%s'", header);
793 char *end_of_token = strstr(p+1, "\"");
795 if (NULL != end_of_token)
797 /* Don't mess with quoted text. */
802 log_error(LOG_LEVEL_HEADER,
803 "Ignoring single quote in '%s'", header);
809 p = strchr(header, ':');
810 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
813 * There's still space before the colon.
821 /*********************************************************************
823 * Function : get_header
825 * Description : This (odd) routine will parse the csp->iob
826 * to get the next complete header.
829 * 1 : iob = The I/O buffer to parse, usually csp->iob.
831 * Returns : Any one of the following:
833 * 1) a pointer to a dynamically allocated string that contains a header line
834 * 2) NULL indicating that the end of the header was reached
835 * 3) "" indicating that the end of the iob was reached before finding
836 * a complete header line.
838 *********************************************************************/
839 char *get_header(struct iob *iob)
843 header = get_header_line(iob);
845 if ((header == NULL) || (*header == '\0'))
848 * No complete header read yet, tell the client.
853 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
856 * Header spans multiple lines, append the next one.
858 char *continued_header;
860 continued_header = get_header_line(iob);
861 if ((continued_header == NULL) || (*continued_header == '\0'))
864 * No complete header read yet, return what we got.
865 * XXX: Should "unread" header instead.
867 log_error(LOG_LEVEL_INFO,
868 "Failed to read a multi-line header properly: '%s'",
873 if (JB_ERR_OK != string_join(&header, continued_header))
875 log_error(LOG_LEVEL_FATAL,
876 "Out of memory while appending multiple headers.");
880 /* XXX: remove before next stable release. */
881 log_error(LOG_LEVEL_HEADER,
882 "Merged multiple header lines to: '%s'",
887 normalize_lws(header);
894 /*********************************************************************
896 * Function : get_header_line
898 * Description : This (odd) routine will parse the csp->iob
899 * to get the next header line.
902 * 1 : iob = The I/O buffer to parse, usually csp->iob.
904 * Returns : Any one of the following:
906 * 1) a pointer to a dynamically allocated string that contains a header line
907 * 2) NULL indicating that the end of the header was reached
908 * 3) "" indicating that the end of the iob was reached before finding
909 * a complete header line.
911 *********************************************************************/
912 static char *get_header_line(struct iob *iob)
916 if ((iob->cur == NULL)
917 || ((p = strchr(iob->cur, '\n')) == NULL))
919 return(""); /* couldn't find a complete header */
924 ret = strdup(iob->cur);
927 /* FIXME No way to handle error properly */
928 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
934 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
936 /* is this a blank line (i.e. the end of the header) ? */
948 /*********************************************************************
950 * Function : get_header_value
952 * Description : Get the value of a given header from a chained list
953 * of header lines or return NULL if no such header is
954 * present in the list.
957 * 1 : header_list = pointer to list
958 * 2 : header_name = string with name of header to look for.
959 * Trailing colon required, capitalization
962 * Returns : NULL if not found, else value of header
964 *********************************************************************/
965 char *get_header_value(const struct list *header_list, const char *header_name)
967 struct list_entry *cur_entry;
973 length = strlen(header_name);
975 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
979 if (!strncmpic(cur_entry->str, header_name, length))
982 * Found: return pointer to start of value
984 ret = cur_entry->str + length;
985 while (*ret && privoxy_isspace(*ret)) ret++;
999 /*********************************************************************
1001 * Function : scan_headers
1003 * Description : Scans headers, applies tags and updates action bits.
1006 * 1 : csp = Current client state (buffers, headers, etc...)
1008 * Returns : JB_ERR_OK
1010 *********************************************************************/
1011 static jb_err scan_headers(struct client_state *csp)
1013 struct list_entry *h; /* Header */
1014 jb_err err = JB_ERR_OK;
1016 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1018 /* Header crunch()ed in previous run? -> ignore */
1019 if (h->str == NULL) continue;
1020 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1021 err = header_tagger(csp, h->str);
1028 /*********************************************************************
1032 * Description : add, delete or modify lines in the HTTP header streams.
1033 * On entry, it receives a linked list of headers space
1034 * that was allocated dynamically (both the list nodes
1035 * and the header contents).
1037 * As a side effect it frees the space used by the original
1041 * 1 : csp = Current client state (buffers, headers, etc...)
1042 * 2 : filter_server_headers = Boolean to switch between
1043 * server and header filtering.
1045 * Returns : JB_ERR_OK in case off success, or
1046 * JB_ERR_MEMORY on out-of-memory error.
1048 *********************************************************************/
1049 jb_err sed(struct client_state *csp, int filter_server_headers)
1051 /* XXX: use more descriptive names. */
1052 struct list_entry *p;
1053 const struct parsers *v;
1054 const add_header_func_ptr *f;
1055 jb_err err = JB_ERR_OK;
1057 if (filter_server_headers)
1059 v = server_patterns;
1060 f = add_server_headers;
1064 v = client_patterns;
1065 f = add_client_headers;
1070 while ((err == JB_ERR_OK) && (v->str != NULL))
1072 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1074 /* Header crunch()ed in previous run? -> ignore */
1075 if (p->str == NULL) continue;
1077 /* Does the current parser handle this header? */
1078 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1079 (v->len == CHECK_EVERY_HEADER_REMAINING))
1081 err = v->parser(csp, &(p->str));
1087 /* place additional headers on the csp->headers list */
1088 while ((err == JB_ERR_OK) && (*f))
1098 /*********************************************************************
1100 * Function : update_server_headers
1102 * Description : Updates server headers after the body has been modified.
1105 * 1 : csp = Current client state (buffers, headers, etc...)
1107 * Returns : JB_ERR_OK in case off success, or
1108 * JB_ERR_MEMORY on out-of-memory error.
1110 *********************************************************************/
1111 jb_err update_server_headers(struct client_state *csp)
1113 jb_err err = JB_ERR_OK;
1115 static const struct parsers server_patterns_light[] = {
1116 { "Content-Length:", 15, server_adjust_content_length },
1117 { "Transfer-Encoding:", 18, server_transfer_coding },
1119 { "Content-Encoding:", 17, server_adjust_content_encoding },
1120 #endif /* def FEATURE_ZLIB */
1124 if (strncmpic(csp->http->cmd, "HEAD", 4))
1126 const struct parsers *v;
1127 struct list_entry *p;
1129 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1131 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1133 /* Header crunch()ed in previous run? -> ignore */
1134 if (p->str == NULL) continue;
1136 /* Does the current parser handle this header? */
1137 if (strncmpic(p->str, v->str, v->len) == 0)
1139 err = v->parser(csp, (char **)&(p->str));
1145 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1146 if ((JB_ERR_OK == err)
1147 && (csp->flags & CSP_FLAG_MODIFIED)
1148 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1149 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1153 create_content_length_header(csp->content_length, header, sizeof(header));
1154 err = enlist(csp->headers, header);
1155 if (JB_ERR_OK == err)
1157 log_error(LOG_LEVEL_HEADER,
1158 "Content modified with no Content-Length header set. "
1159 "Created: %s.", header);
1162 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1164 #ifdef FEATURE_COMPRESSION
1165 if ((JB_ERR_OK == err)
1166 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1168 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1169 if (JB_ERR_OK == err)
1171 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1180 /*********************************************************************
1182 * Function : header_tagger
1184 * Description : Executes all text substitutions from applying
1185 * tag actions and saves the result as tag.
1187 * XXX: Shares enough code with filter_header() and
1188 * pcrs_filter_response() to warrant some helper functions.
1191 * 1 : csp = Current client state (buffers, headers, etc...)
1192 * 2 : header = Header that is used as tagger input
1194 * Returns : JB_ERR_OK on success and always succeeds
1196 *********************************************************************/
1197 static jb_err header_tagger(struct client_state *csp, char *header)
1199 int wanted_filter_type;
1200 int multi_action_index;
1204 struct file_list *fl;
1205 struct re_filterfile_spec *b;
1206 struct list_entry *tag_name;
1208 const size_t header_length = strlen(header);
1210 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1212 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1213 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1217 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1218 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1221 if (filters_available(csp) == FALSE)
1223 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1224 "tagging enabled, but no taggers available.");
1228 for (i = 0; i < MAX_AF_FILES; i++)
1231 if ((NULL == fl) || (NULL == fl->f))
1234 * Either there are no filter files
1235 * left, or this filter file just
1236 * contains no valid filters.
1238 * Continue to be sure we don't miss
1239 * valid filter files that are chained
1240 * after empty or invalid ones.
1245 /* For all filters, */
1246 for (b = fl->f; b; b = b->next)
1248 if (b->type != wanted_filter_type)
1250 /* skip the ones we don't care about, */
1253 /* leaving only taggers that could apply, of which we use the ones, */
1254 for (tag_name = csp->action->multi[multi_action_index]->first;
1255 NULL != tag_name; tag_name = tag_name->next)
1257 /* that do apply, and */
1258 if (strcmp(b->name, tag_name->str) == 0)
1260 char *modified_tag = NULL;
1262 size_t size = header_length;
1263 pcrs_job *joblist = b->joblist;
1265 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1267 if (NULL == joblist)
1269 log_error(LOG_LEVEL_RE_FILTER,
1270 "Tagger %s has empty joblist. Nothing to do.", b->name);
1274 /* execute their pcrs_joblist on the header. */
1275 for (job = joblist; NULL != job; job = job->next)
1277 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1281 /* Success, continue with the modified version. */
1290 /* Tagger doesn't match */
1293 /* Regex failure, log it but continue anyway. */
1294 assert(NULL != header);
1295 log_error(LOG_LEVEL_ERROR,
1296 "Problems with tagger \'%s\' and header \'%s\': %s",
1297 b->name, *header, pcrs_strerror(hits));
1299 freez(modified_tag);
1303 if (b->dynamic) pcrs_free_joblist(joblist);
1305 /* If this tagger matched */
1311 * There is to technical limitation which makes
1312 * it impossible to use empty tags, but I assume
1313 * no one would do it intentionally.
1316 log_error(LOG_LEVEL_INFO,
1317 "Tagger \'%s\' created an empty tag. Ignored.",
1322 if (!list_contains_item(csp->tags, tag))
1324 if (JB_ERR_OK != enlist(csp->tags, tag))
1326 log_error(LOG_LEVEL_ERROR,
1327 "Insufficient memory to add tag \'%s\', "
1328 "based on tagger \'%s\' and header \'%s\'",
1329 tag, b->name, *header);
1333 char *action_message;
1335 * update the action bits right away, to make
1336 * tagging based on tags set by earlier taggers
1337 * of the same kind possible.
1339 if (update_action_bits_for_tag(csp, tag))
1341 action_message = "Action bits updated accordingly.";
1345 action_message = "No action bits update necessary.";
1348 log_error(LOG_LEVEL_HEADER,
1349 "Tagger \'%s\' added tag \'%s\'. %s",
1350 b->name, tag, action_message);
1355 /* XXX: Is this log-worthy? */
1356 log_error(LOG_LEVEL_HEADER,
1357 "Tagger \'%s\' didn't add tag \'%s\'. "
1358 "Tag already present", b->name, tag);
1361 } /* if the tagger matched */
1362 } /* if the tagger applies */
1363 } /* for every tagger that could apply */
1364 } /* for all filters */
1365 } /* for all filter files */
1370 /* here begins the family of parser functions that reformat header lines */
1372 /*********************************************************************
1374 * Function : filter_header
1376 * Description : Executes all text substitutions from all applying
1377 * +(server|client)-header-filter actions on the header.
1378 * Most of the code was copied from pcrs_filter_response,
1379 * including the rather short variable names
1382 * 1 : csp = Current client state (buffers, headers, etc...)
1383 * 2 : header = On input, pointer to header to modify.
1384 * On output, pointer to the modified header, or NULL
1385 * to remove the header. This function frees the
1386 * original string if necessary.
1388 * Returns : JB_ERR_OK on success and always succeeds
1390 *********************************************************************/
1391 static jb_err filter_header(struct client_state *csp, char **header)
1395 size_t size = strlen(*header);
1397 char *newheader = NULL;
1400 struct file_list *fl;
1401 struct re_filterfile_spec *b;
1402 struct list_entry *filtername;
1405 int wanted_filter_type;
1406 int multi_action_index;
1408 if (csp->flags & CSP_FLAG_NO_FILTERING)
1413 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1415 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1416 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1420 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1421 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1424 if (filters_available(csp) == FALSE)
1426 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1427 "header filtering enabled, but no matching filters available.");
1431 for (i = 0; i < MAX_AF_FILES; i++)
1434 if ((NULL == fl) || (NULL == fl->f))
1437 * Either there are no filter files
1438 * left, or this filter file just
1439 * contains no valid filters.
1441 * Continue to be sure we don't miss
1442 * valid filter files that are chained
1443 * after empty or invalid ones.
1448 * For all applying +filter actions, look if a filter by that
1449 * name exists and if yes, execute its pcrs_joblist on the
1452 for (b = fl->f; b; b = b->next)
1454 if (b->type != wanted_filter_type)
1456 /* Skip other filter types */
1460 for (filtername = csp->action->multi[multi_action_index]->first;
1461 filtername ; filtername = filtername->next)
1463 if (strcmp(b->name, filtername->str) == 0)
1465 int current_hits = 0;
1466 pcrs_job *joblist = b->joblist;
1468 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1470 if (NULL == joblist)
1472 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1476 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1477 *header, size, b->name);
1479 /* Apply all jobs from the joblist */
1480 for (job = joblist; NULL != job; job = job->next)
1482 matches = pcrs_execute(job, *header, size, &newheader, &size);
1485 current_hits += matches;
1486 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1488 *header = newheader;
1490 else if (0 == matches)
1492 /* Filter doesn't change header */
1498 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1499 *header, b->name, pcrs_strerror(matches));
1500 if (newheader != NULL)
1502 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1508 if (b->dynamic) pcrs_free_joblist(joblist);
1510 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1511 hits += current_hits;
1518 * Additionally checking for hits is important because if
1519 * the continue hack is triggered, server headers can
1520 * arrive empty to separate multiple heads from each other.
1522 if ((0 == size) && hits)
1524 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1532 /*********************************************************************
1534 * Function : server_connection
1536 * Description : Makes sure a proper "Connection:" header is
1537 * set and signals connection_header_adder to
1541 * 1 : csp = Current client state (buffers, headers, etc...)
1542 * 2 : header = On input, pointer to header to modify.
1543 * On output, pointer to the modified header, or NULL
1544 * to remove the header. This function frees the
1545 * original string if necessary.
1547 * Returns : JB_ERR_OK on success.
1549 *********************************************************************/
1550 static jb_err server_connection(struct client_state *csp, char **header)
1552 if (!strcmpic(*header, "Connection: keep-alive")
1553 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1554 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1558 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1559 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1561 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1564 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1566 log_error(LOG_LEVEL_HEADER,
1567 "Keeping the server header '%s' around.", *header);
1570 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1572 char *old_header = *header;
1574 *header = strdup_or_die("Connection: close");
1575 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1580 /* Signal server_connection_adder() to return early. */
1581 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1587 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1588 /*********************************************************************
1590 * Function : server_keep_alive
1592 * Description : Stores the server's keep alive timeout.
1595 * 1 : csp = Current client state (buffers, headers, etc...)
1596 * 2 : header = On input, pointer to header to modify.
1597 * On output, pointer to the modified header, or NULL
1598 * to remove the header. This function frees the
1599 * original string if necessary.
1601 * Returns : JB_ERR_OK.
1603 *********************************************************************/
1604 static jb_err server_keep_alive(struct client_state *csp, char **header)
1606 unsigned int keep_alive_timeout;
1607 const char *timeout_position = strstr(*header, "timeout=");
1609 if ((NULL == timeout_position)
1610 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1612 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1616 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1618 log_error(LOG_LEVEL_HEADER,
1619 "Reducing keep-alive timeout from %u to %u.",
1620 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1621 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1625 /* XXX: Is this log worthy? */
1626 log_error(LOG_LEVEL_HEADER,
1627 "Server keep-alive timeout is %u. Sticking with %u.",
1628 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1630 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1637 /*********************************************************************
1639 * Function : server_proxy_connection
1641 * Description : Figures out whether or not we should add a
1642 * Proxy-Connection header.
1645 * 1 : csp = Current client state (buffers, headers, etc...)
1646 * 2 : header = On input, pointer to header to modify.
1647 * On output, pointer to the modified header, or NULL
1648 * to remove the header. This function frees the
1649 * original string if necessary.
1651 * Returns : JB_ERR_OK.
1653 *********************************************************************/
1654 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1656 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1661 /*********************************************************************
1663 * Function : client_keep_alive
1665 * Description : Stores the client's keep alive timeout.
1668 * 1 : csp = Current client state (buffers, headers, etc...)
1669 * 2 : header = On input, pointer to header to modify.
1670 * On output, pointer to the modified header, or NULL
1671 * to remove the header. This function frees the
1672 * original string if necessary.
1674 * Returns : JB_ERR_OK.
1676 *********************************************************************/
1677 static jb_err client_keep_alive(struct client_state *csp, char **header)
1679 unsigned int keep_alive_timeout;
1680 const char *timeout_position = strstr(*header, ": ");
1682 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1684 log_error(LOG_LEVEL_HEADER,
1685 "keep-alive support is disabled. Crunching: %s.", *header);
1690 if ((NULL == timeout_position)
1691 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1693 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1697 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1699 log_error(LOG_LEVEL_HEADER,
1700 "Reducing keep-alive timeout from %u to %u.",
1701 csp->config->keep_alive_timeout, keep_alive_timeout);
1702 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1706 /* XXX: Is this log worthy? */
1707 log_error(LOG_LEVEL_HEADER,
1708 "Client keep-alive timeout is %u. Sticking with %u.",
1709 keep_alive_timeout, csp->config->keep_alive_timeout);
1717 /*********************************************************************
1719 * Function : get_content_length
1721 * Description : Gets the content length specified in a
1722 * Content-Length header.
1725 * 1 : header = The Content-Length header.
1726 * 2 : length = Storage to return the value.
1728 * Returns : JB_ERR_OK on success, or
1729 * JB_ERR_PARSE if no value is recognized.
1731 *********************************************************************/
1732 static jb_err get_content_length(const char *header, unsigned long long *length)
1734 assert(header[14] == ':');
1737 assert(sizeof(unsigned long long) > 4);
1738 if (1 != sscanf(header+14, ": %I64u", length))
1740 if (1 != sscanf(header+14, ": %llu", length))
1743 return JB_ERR_PARSE;
1750 /*********************************************************************
1752 * Function : client_save_content_length
1754 * Description : Save the Content-Length sent by the client.
1757 * 1 : csp = Current client state (buffers, headers, etc...)
1758 * 2 : header = On input, pointer to header to modify.
1759 * On output, pointer to the modified header, or NULL
1760 * to remove the header. This function frees the
1761 * original string if necessary.
1763 * Returns : JB_ERR_OK on success, or
1764 * JB_ERR_MEMORY on out-of-memory error.
1766 *********************************************************************/
1767 static jb_err client_save_content_length(struct client_state *csp, char **header)
1769 unsigned long long content_length = 0;
1771 assert(*(*header+14) == ':');
1773 if (JB_ERR_OK != get_content_length(*header, &content_length))
1775 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1780 csp->expected_client_content_length = content_length;
1785 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1789 /*********************************************************************
1791 * Function : client_connection
1793 * Description : Makes sure a proper "Connection:" header is
1794 * set and signals connection_header_adder
1798 * 1 : csp = Current client state (buffers, headers, etc...)
1799 * 2 : header = On input, pointer to header to modify.
1800 * On output, pointer to the modified header, or NULL
1801 * to remove the header. This function frees the
1802 * original string if necessary.
1804 * Returns : JB_ERR_OK on success.
1806 *********************************************************************/
1807 static jb_err client_connection(struct client_state *csp, char **header)
1809 static const char connection_close[] = "Connection: close";
1811 if (!strcmpic(*header, connection_close))
1813 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1814 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1816 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1818 log_error(LOG_LEVEL_HEADER,
1819 "Removing \'%s\' to imply keep-alive.", *header);
1822 * While we imply keep-alive to the server,
1823 * we have to remember that the client didn't.
1825 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1829 char *old_header = *header;
1831 *header = strdup_or_die("Connection: keep-alive");
1832 log_error(LOG_LEVEL_HEADER,
1833 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1839 log_error(LOG_LEVEL_HEADER,
1840 "Keeping the client header '%s' around. "
1841 "The connection will not be kept alive.",
1843 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1846 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1848 log_error(LOG_LEVEL_HEADER,
1849 "Keeping the client header '%s' around. "
1850 "The server connection will be kept alive if possible.",
1852 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1853 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1857 char *old_header = *header;
1859 *header = strdup_or_die(connection_close);
1860 log_error(LOG_LEVEL_HEADER,
1861 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1865 /* Signal client_connection_adder() to return early. */
1866 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1872 /*********************************************************************
1874 * Function : crumble
1876 * Description : This is called if a header matches a pattern to "crunch"
1879 * 1 : csp = Current client state (buffers, headers, etc...)
1880 * 2 : header = On input, pointer to header to modify.
1881 * On output, pointer to the modified header, or NULL
1882 * to remove the header. This function frees the
1883 * original string if necessary.
1885 * Returns : JB_ERR_OK on success, or
1886 * JB_ERR_MEMORY on out-of-memory error.
1888 *********************************************************************/
1889 static jb_err crumble(struct client_state *csp, char **header)
1892 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1898 /*********************************************************************
1900 * Function : crunch_server_header
1902 * Description : Crunch server header if it matches a string supplied by the
1903 * user. Called from `sed'.
1906 * 1 : csp = Current client state (buffers, headers, etc...)
1907 * 2 : header = On input, pointer to header to modify.
1908 * On output, pointer to the modified header, or NULL
1909 * to remove the header. This function frees the
1910 * original string if necessary.
1912 * Returns : JB_ERR_OK on success and always succeeds
1914 *********************************************************************/
1915 static jb_err crunch_server_header(struct client_state *csp, char **header)
1917 const char *crunch_pattern;
1919 /* Do we feel like crunching? */
1920 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1922 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1924 /* Is the current header the lucky one? */
1925 if (strstr(*header, crunch_pattern))
1927 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1936 /*********************************************************************
1938 * Function : server_content_type
1940 * Description : Set the content-type for filterable types (text/.*,
1941 * .*xml.*, .*script.* and image/gif) unless filtering has been
1942 * forbidden (CT_TABOO) while parsing earlier headers.
1943 * NOTE: Since text/plain is commonly used by web servers
1944 * for files whose correct type is unknown, we don't
1945 * set CT_TEXT for it.
1948 * 1 : csp = Current client state (buffers, headers, etc...)
1949 * 2 : header = On input, pointer to header to modify.
1950 * On output, pointer to the modified header, or NULL
1951 * to remove the header. This function frees the
1952 * original string if necessary.
1954 * Returns : JB_ERR_OK on success, or
1955 * JB_ERR_MEMORY on out-of-memory error.
1957 *********************************************************************/
1958 static jb_err server_content_type(struct client_state *csp, char **header)
1960 /* Remove header if it isn't the first Content-Type header */
1961 if ((csp->content_type & CT_DECLARED))
1964 * Another, slightly slower, way to see if
1965 * we already parsed another Content-Type header.
1967 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1969 log_error(LOG_LEVEL_ERROR,
1970 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1978 * Signal that the Content-Type has been set.
1980 csp->content_type |= CT_DECLARED;
1982 if (!(csp->content_type & CT_TABOO))
1985 * XXX: The assumption that text/plain is a sign of
1986 * binary data seems to be somewhat unreasonable nowadays
1987 * and should be dropped after 3.0.8 is out.
1989 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
1990 || strstr(*header, "xml")
1991 || strstr(*header, "script"))
1993 csp->content_type |= CT_TEXT;
1995 else if (strstr(*header, "image/gif"))
1997 csp->content_type |= CT_GIF;
2002 * Are we messing with the content type?
2004 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2007 * Make sure the user doesn't accidentally
2008 * change the content type of binary documents.
2010 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2013 *header = strdup_or_die("Content-Type: ");
2014 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2018 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2019 return JB_ERR_MEMORY;
2021 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2025 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2026 "It doesn't look like a content type that should be filtered. "
2027 "Enable force-text-mode if you know what you're doing.", *header);
2035 /*********************************************************************
2037 * Function : server_transfer_coding
2039 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2040 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2041 * - Remove header if body was chunked but has been
2042 * de-chunked for filtering.
2045 * 1 : csp = Current client state (buffers, headers, etc...)
2046 * 2 : header = On input, pointer to header to modify.
2047 * On output, pointer to the modified header, or NULL
2048 * to remove the header. This function frees the
2049 * original string if necessary.
2051 * Returns : JB_ERR_OK on success, or
2052 * JB_ERR_MEMORY on out-of-memory error.
2054 *********************************************************************/
2055 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2058 * Turn off pcrs and gif filtering if body compressed
2060 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2064 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2066 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2067 csp->http->cmd, *header);
2068 #endif /* def FEATURE_ZLIB */
2069 csp->content_type = CT_TABOO;
2073 * Raise flag if body chunked
2075 if (strstr(*header, "chunked"))
2077 csp->flags |= CSP_FLAG_CHUNKED;
2080 * If the body was modified, it has been de-chunked first
2081 * and the header must be removed.
2083 * FIXME: If there is more than one transfer encoding,
2084 * only the "chunked" part should be removed here.
2086 if (csp->flags & CSP_FLAG_MODIFIED)
2088 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2097 /*********************************************************************
2099 * Function : server_content_encoding
2101 * Description : Used to check if the content is compressed, and if
2102 * FEATURE_ZLIB is disabled, filtering is disabled as
2105 * If FEATURE_ZLIB is enabled and the compression type
2106 * supported, the content is marked for decompression.
2108 * XXX: Doesn't properly deal with multiple or with
2109 * unsupported but unknown encodings.
2110 * Is case-sensitive but shouldn't be.
2113 * 1 : csp = Current client state (buffers, headers, etc...)
2114 * 2 : header = On input, pointer to header to modify.
2115 * On output, pointer to the modified header, or NULL
2116 * to remove the header. This function frees the
2117 * original string if necessary.
2119 * Returns : JB_ERR_OK on success, or
2120 * JB_ERR_MEMORY on out-of-memory error.
2122 *********************************************************************/
2123 static jb_err server_content_encoding(struct client_state *csp, char **header)
2126 if (strstr(*header, "sdch"))
2129 * Shared Dictionary Compression over HTTP isn't supported,
2130 * filtering it anyway is pretty much guaranteed to mess up
2133 csp->content_type |= CT_TABOO;
2136 * Log a warning if the user expects the content to be filtered.
2138 if ((csp->rlist != NULL) &&
2139 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2141 log_error(LOG_LEVEL_INFO,
2142 "SDCH-compressed content detected, content filtering disabled. "
2143 "Consider suppressing SDCH offers made by the client.");
2146 else if (strstr(*header, "gzip"))
2148 /* Mark for gzip decompression */
2149 csp->content_type |= CT_GZIP;
2151 else if (strstr(*header, "deflate"))
2153 /* Mark for zlib decompression */
2154 csp->content_type |= CT_DEFLATE;
2156 else if (strstr(*header, "compress"))
2159 * We can't decompress this; therefore we can't filter
2162 csp->content_type |= CT_TABOO;
2164 #else /* !defined(FEATURE_ZLIB) */
2166 * XXX: Using a black list here isn't the right approach.
2168 * In case of SDCH, building with zlib support isn't
2171 if (strstr(*header, "gzip") ||
2172 strstr(*header, "compress") ||
2173 strstr(*header, "deflate") ||
2174 strstr(*header, "sdch"))
2177 * Body is compressed, turn off pcrs and gif filtering.
2179 csp->content_type |= CT_TABOO;
2182 * Log a warning if the user expects the content to be filtered.
2184 if ((csp->rlist != NULL) &&
2185 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2187 log_error(LOG_LEVEL_INFO,
2188 "Compressed content detected, content filtering disabled. "
2189 "Consider recompiling Privoxy with zlib support or "
2190 "enable the prevent-compression action.");
2193 #endif /* defined(FEATURE_ZLIB) */
2201 /*********************************************************************
2203 * Function : server_adjust_content_encoding
2205 * Description : Remove the Content-Encoding header if the
2206 * decompression was successful and the content
2210 * 1 : csp = Current client state (buffers, headers, etc...)
2211 * 2 : header = On input, pointer to header to modify.
2212 * On output, pointer to the modified header, or NULL
2213 * to remove the header. This function frees the
2214 * original string if necessary.
2216 * Returns : JB_ERR_OK on success, or
2217 * JB_ERR_MEMORY on out-of-memory error.
2219 *********************************************************************/
2220 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2222 if ((csp->flags & CSP_FLAG_MODIFIED)
2223 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2226 * We successfully decompressed the content,
2227 * and have to clean the header now, so the
2228 * client no longer expects compressed data.
2230 * XXX: There is a difference between cleaning
2231 * and removing it completely.
2233 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2240 #endif /* defined(FEATURE_ZLIB) */
2243 /*********************************************************************
2245 * Function : server_adjust_content_length
2247 * Description : Adjust Content-Length header if we modified
2251 * 1 : csp = Current client state (buffers, headers, etc...)
2252 * 2 : header = On input, pointer to header to modify.
2253 * On output, pointer to the modified header, or NULL
2254 * to remove the header. This function frees the
2255 * original string if necessary.
2257 * Returns : JB_ERR_OK on success, or
2258 * JB_ERR_MEMORY on out-of-memory error.
2260 *********************************************************************/
2261 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2263 /* Regenerate header if the content was modified. */
2264 if (csp->flags & CSP_FLAG_MODIFIED)
2266 const size_t header_length = 50;
2268 *header = malloc(header_length);
2269 if (*header == NULL)
2271 return JB_ERR_MEMORY;
2273 create_content_length_header(csp->content_length, *header, header_length);
2274 log_error(LOG_LEVEL_HEADER,
2275 "Adjusted Content-Length to %llu", csp->content_length);
2282 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2283 /*********************************************************************
2285 * Function : server_save_content_length
2287 * Description : Save the Content-Length sent by the server.
2290 * 1 : csp = Current client state (buffers, headers, etc...)
2291 * 2 : header = On input, pointer to header to modify.
2292 * On output, pointer to the modified header, or NULL
2293 * to remove the header. This function frees the
2294 * original string if necessary.
2296 * Returns : JB_ERR_OK on success, or
2297 * JB_ERR_MEMORY on out-of-memory error.
2299 *********************************************************************/
2300 static jb_err server_save_content_length(struct client_state *csp, char **header)
2302 unsigned long long content_length = 0;
2304 assert(*(*header+14) == ':');
2306 if (JB_ERR_OK != get_content_length(*header, &content_length))
2308 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2313 csp->expected_content_length = content_length;
2314 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2315 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2320 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2323 /*********************************************************************
2325 * Function : server_content_md5
2327 * Description : Crumble any Content-MD5 headers if the document was
2328 * modified. FIXME: Should we re-compute instead?
2331 * 1 : csp = Current client state (buffers, headers, etc...)
2332 * 2 : header = On input, pointer to header to modify.
2333 * On output, pointer to the modified header, or NULL
2334 * to remove the header. This function frees the
2335 * original string if necessary.
2337 * Returns : JB_ERR_OK on success, or
2338 * JB_ERR_MEMORY on out-of-memory error.
2340 *********************************************************************/
2341 static jb_err server_content_md5(struct client_state *csp, char **header)
2343 if (csp->flags & CSP_FLAG_MODIFIED)
2345 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2353 /*********************************************************************
2355 * Function : server_content_disposition
2357 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2358 * Called from `sed'.
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_content_disposition(struct client_state *csp, char **header)
2376 * Are we messing with the Content-Disposition header?
2378 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2384 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2386 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2389 * Blocking content-disposition header
2391 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2398 * Replacing Content-Disposition header
2401 *header = strdup("Content-Disposition: ");
2402 string_append(header, newval);
2404 if (*header != NULL)
2406 log_error(LOG_LEVEL_HEADER,
2407 "Content-Disposition header crunched and replaced with: %s", *header);
2410 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2414 /*********************************************************************
2416 * Function : server_last_modified
2418 * Description : Changes Last-Modified header to the actual date
2419 * to help hide-if-modified-since.
2420 * Called from `sed'.
2423 * 1 : csp = Current client state (buffers, headers, etc...)
2424 * 2 : header = On input, pointer to header to modify.
2425 * On output, pointer to the modified header, or NULL
2426 * to remove the header. This function frees the
2427 * original string if necessary.
2429 * Returns : JB_ERR_OK on success, or
2430 * JB_ERR_MEMORY on out-of-memory error.
2432 *********************************************************************/
2433 static jb_err server_last_modified(struct client_state *csp, char **header)
2436 time_t last_modified;
2440 * Are we messing with the Last-Modified header?
2442 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2448 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2450 if (0 == strcmpic(newval, "block"))
2453 * Blocking Last-Modified header. Useless but why not.
2455 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2459 else if (0 == strcmpic(newval, "reset-to-request-time"))
2462 * Setting Last-Modified Header to now.
2465 get_http_time(0, buf, sizeof(buf));
2467 *header = strdup("Last-Modified: ");
2468 string_append(header, buf);
2470 if (*header == NULL)
2472 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2476 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2479 else if (0 == strcmpic(newval, "randomize"))
2481 const char *header_time = *header + sizeof("Last-Modified:");
2483 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2485 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2487 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2493 struct tm *timeptr = NULL;
2495 #ifdef HAVE_GMTIME_R
2499 rtime = (long int)difftime(now, last_modified);
2502 long int days, hours, minutes, seconds;
2503 const int negative_delta = (rtime < 0);
2508 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2510 rtime = pick_from_range(rtime);
2515 last_modified += rtime;
2516 #ifdef HAVE_GMTIME_R
2517 timeptr = gmtime_r(&last_modified, &gmt);
2518 #elif defined(MUTEX_LOCKS_AVAILABLE)
2519 privoxy_mutex_lock(&gmtime_mutex);
2520 timeptr = gmtime(&last_modified);
2521 privoxy_mutex_unlock(&gmtime_mutex);
2523 timeptr = gmtime(&last_modified);
2525 if ((NULL == timeptr) || !strftime(newheader,
2526 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2528 log_error(LOG_LEVEL_ERROR,
2529 "Randomizing '%s' failed. Crunching the header without replacement.",
2536 *header = strdup("Last-Modified: ");
2537 string_append(header, newheader);
2539 if (*header == NULL)
2541 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2542 return JB_ERR_MEMORY;
2545 days = rtime / (3600 * 24);
2546 hours = rtime / 3600 % 24;
2547 minutes = rtime / 60 % 60;
2548 seconds = rtime % 60;
2550 log_error(LOG_LEVEL_HEADER,
2551 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2552 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2553 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2557 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2566 /*********************************************************************
2568 * Function : client_accept_encoding
2570 * Description : Rewrite the client's Accept-Encoding header so that
2571 * if doesn't allow compression, if the action applies.
2572 * Note: For HTTP/1.0 the absence of the header is enough.
2575 * 1 : csp = Current client state (buffers, headers, etc...)
2576 * 2 : header = On input, pointer to header to modify.
2577 * On output, pointer to the modified header, or NULL
2578 * to remove the header. This function frees the
2579 * original string if necessary.
2581 * Returns : JB_ERR_OK on success, or
2582 * JB_ERR_MEMORY on out-of-memory error.
2584 *********************************************************************/
2585 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2587 #ifdef FEATURE_COMPRESSION
2588 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2589 && strstr(*header, "deflate"))
2591 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2594 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2596 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2604 /*********************************************************************
2606 * Function : client_te
2608 * Description : Rewrite the client's TE header so that
2609 * if doesn't allow compression, if the action applies.
2612 * 1 : csp = Current client state (buffers, headers, etc...)
2613 * 2 : header = On input, pointer to header to modify.
2614 * On output, pointer to the modified header, or NULL
2615 * to remove the header. This function frees the
2616 * original string if necessary.
2618 * Returns : JB_ERR_OK on success, or
2619 * JB_ERR_MEMORY on out-of-memory error.
2621 *********************************************************************/
2622 static jb_err client_te(struct client_state *csp, char **header)
2624 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2627 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2634 /*********************************************************************
2636 * Function : client_referrer
2638 * Description : Handle the "referer" config setting properly.
2639 * Called from `sed'.
2642 * 1 : csp = Current client state (buffers, headers, etc...)
2643 * 2 : header = On input, pointer to header to modify.
2644 * On output, pointer to the modified header, or NULL
2645 * to remove the header. This function frees the
2646 * original string if necessary.
2648 * Returns : JB_ERR_OK on success, or
2649 * JB_ERR_MEMORY on out-of-memory error.
2651 *********************************************************************/
2652 static jb_err client_referrer(struct client_state *csp, char **header)
2654 const char *parameter;
2655 /* booleans for parameters we have to check multiple times */
2656 int parameter_conditional_block;
2657 int parameter_conditional_forge;
2659 #ifdef FEATURE_FORCE_LOAD
2661 * Since the referrer can include the prefix even
2662 * if the request itself is non-forced, we must
2663 * clean it unconditionally.
2665 * XXX: strclean is too broad
2667 strclean(*header, FORCE_PREFIX);
2668 #endif /* def FEATURE_FORCE_LOAD */
2670 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2672 /* Nothing left to do */
2676 parameter = csp->action->string[ACTION_STRING_REFERER];
2677 assert(parameter != NULL);
2678 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2679 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2681 if (!parameter_conditional_block && !parameter_conditional_forge)
2684 * As conditional-block and conditional-forge are the only
2685 * parameters that rely on the original referrer, we can
2686 * remove it now for all the others.
2691 if (0 == strcmpic(parameter, "block"))
2693 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2696 else if (parameter_conditional_block || parameter_conditional_forge)
2698 return handle_conditional_hide_referrer_parameter(header,
2699 csp->http->hostport, parameter_conditional_block);
2701 else if (0 == strcmpic(parameter, "forge"))
2703 return create_forged_referrer(header, csp->http->hostport);
2707 /* interpret parameter as user-supplied referer to fake */
2708 return create_fake_referrer(header, parameter);
2713 /*********************************************************************
2715 * Function : client_accept_language
2717 * Description : Handle the "Accept-Language" config setting properly.
2718 * Called from `sed'.
2721 * 1 : csp = Current client state (buffers, headers, etc...)
2722 * 2 : header = On input, pointer to header to modify.
2723 * On output, pointer to the modified header, or NULL
2724 * to remove the header. This function frees the
2725 * original string if necessary.
2727 * Returns : JB_ERR_OK on success, or
2728 * JB_ERR_MEMORY on out-of-memory error.
2730 *********************************************************************/
2731 static jb_err client_accept_language(struct client_state *csp, char **header)
2736 * Are we messing with the Accept-Language?
2738 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2740 /*I don't think so*/
2744 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2746 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2749 * Blocking Accept-Language header
2751 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2758 * Replacing Accept-Language header
2761 *header = strdup("Accept-Language: ");
2762 string_append(header, newval);
2764 if (*header == NULL)
2766 log_error(LOG_LEVEL_ERROR,
2767 "Insufficient memory. Accept-Language header crunched without replacement.");
2771 log_error(LOG_LEVEL_HEADER,
2772 "Accept-Language header crunched and replaced with: %s", *header);
2775 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2779 /*********************************************************************
2781 * Function : crunch_client_header
2783 * Description : Crunch client header if it matches a string supplied by the
2784 * user. Called from `sed'.
2787 * 1 : csp = Current client state (buffers, headers, etc...)
2788 * 2 : header = On input, pointer to header to modify.
2789 * On output, pointer to the modified header, or NULL
2790 * to remove the header. This function frees the
2791 * original string if necessary.
2793 * Returns : JB_ERR_OK on success and always succeeds
2795 *********************************************************************/
2796 static jb_err crunch_client_header(struct client_state *csp, char **header)
2798 const char *crunch_pattern;
2800 /* Do we feel like crunching? */
2801 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2803 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2805 /* Is the current header the lucky one? */
2806 if (strstr(*header, crunch_pattern))
2808 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2816 /*********************************************************************
2818 * Function : client_uagent
2820 * Description : Handle the "user-agent" config setting properly
2821 * and remember its original value to enable browser
2822 * bug workarounds. Called from `sed'.
2825 * 1 : csp = Current client state (buffers, headers, etc...)
2826 * 2 : header = On input, pointer to header to modify.
2827 * On output, pointer to the modified header, or NULL
2828 * to remove the header. This function frees the
2829 * original string if necessary.
2831 * Returns : JB_ERR_OK on success, or
2832 * JB_ERR_MEMORY on out-of-memory error.
2834 *********************************************************************/
2835 static jb_err client_uagent(struct client_state *csp, char **header)
2839 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2844 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2851 *header = strdup("User-Agent: ");
2852 string_append(header, newval);
2854 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2856 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2860 /*********************************************************************
2862 * Function : client_ua
2864 * Description : Handle "ua-" headers properly. Called from `sed'.
2867 * 1 : csp = Current client state (buffers, headers, etc...)
2868 * 2 : header = On input, pointer to header to modify.
2869 * On output, pointer to the modified header, or NULL
2870 * to remove the header. This function frees the
2871 * original string if necessary.
2873 * Returns : JB_ERR_OK on success, or
2874 * JB_ERR_MEMORY on out-of-memory error.
2876 *********************************************************************/
2877 static jb_err client_ua(struct client_state *csp, char **header)
2879 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2881 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2889 /*********************************************************************
2891 * Function : client_from
2893 * Description : Handle the "from" config setting properly.
2894 * Called from `sed'.
2897 * 1 : csp = Current client state (buffers, headers, etc...)
2898 * 2 : header = On input, pointer to header to modify.
2899 * On output, pointer to the modified header, or NULL
2900 * to remove the header. This function frees the
2901 * original string if necessary.
2903 * Returns : JB_ERR_OK on success, or
2904 * JB_ERR_MEMORY on out-of-memory error.
2906 *********************************************************************/
2907 static jb_err client_from(struct client_state *csp, char **header)
2911 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2918 newval = csp->action->string[ACTION_STRING_FROM];
2921 * Are we blocking the e-mail address?
2923 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2925 log_error(LOG_LEVEL_HEADER, "crunched From!");
2929 log_error(LOG_LEVEL_HEADER, " modified");
2931 *header = strdup("From: ");
2932 string_append(header, newval);
2934 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2938 /*********************************************************************
2940 * Function : client_send_cookie
2942 * Description : Crunches the "cookie" header if necessary.
2943 * Called from `sed'.
2945 * XXX: Stupid name, doesn't send squat.
2948 * 1 : csp = Current client state (buffers, headers, etc...)
2949 * 2 : header = On input, pointer to header to modify.
2950 * On output, pointer to the modified header, or NULL
2951 * to remove the header. This function frees the
2952 * original string if necessary.
2954 * Returns : JB_ERR_OK on success, or
2955 * JB_ERR_MEMORY on out-of-memory error.
2957 *********************************************************************/
2958 static jb_err client_send_cookie(struct client_state *csp, char **header)
2960 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2962 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2970 /*********************************************************************
2972 * Function : client_x_forwarded
2974 * Description : Handle the "x-forwarded-for" config setting properly,
2975 * also used in the add_client_headers list. Called from `sed'.
2978 * 1 : csp = Current client state (buffers, headers, etc...)
2979 * 2 : header = On input, pointer to header to modify.
2980 * On output, pointer to the modified header, or NULL
2981 * to remove the header. This function frees the
2982 * original string if necessary.
2984 * Returns : JB_ERR_OK on success, or
2985 * JB_ERR_MEMORY on out-of-memory error.
2987 *********************************************************************/
2988 jb_err client_x_forwarded(struct client_state *csp, char **header)
2990 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
2992 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
2994 if (0 == strcmpic(parameter, "block"))
2997 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2999 else if (0 == strcmpic(parameter, "add"))
3001 string_append(header, ", ");
3002 string_append(header, csp->ip_addr_str);
3004 if (*header == NULL)
3006 return JB_ERR_MEMORY;
3008 log_error(LOG_LEVEL_HEADER,
3009 "Appended client IP address to %s", *header);
3010 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3014 log_error(LOG_LEVEL_FATAL,
3015 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3023 /*********************************************************************
3025 * Function : client_max_forwards
3027 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3028 * from the value of the Max-Forwards header field.
3031 * 1 : csp = Current client state (buffers, headers, etc...)
3032 * 2 : header = On input, pointer to header to modify.
3033 * On output, pointer to the modified header, or NULL
3034 * to remove the header. This function frees the
3035 * original string if necessary.
3037 * Returns : JB_ERR_OK on success, or
3038 * JB_ERR_MEMORY on out-of-memory error.
3040 *********************************************************************/
3041 static jb_err client_max_forwards(struct client_state *csp, char **header)
3045 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3046 (0 == strcmpic(csp->http->gpc, "options")))
3048 assert(*(*header+12) == ':');
3049 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3051 if (max_forwards > 0)
3053 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3054 log_error(LOG_LEVEL_HEADER,
3055 "Max-Forwards value for %s request reduced to %d.",
3056 csp->http->gpc, max_forwards);
3058 else if (max_forwards < 0)
3060 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3066 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3075 /*********************************************************************
3077 * Function : client_host
3079 * Description : If the request URI did not contain host and
3080 * port information, parse and evaluate the Host
3083 * Also, kill ill-formed HOST: headers as sent by
3084 * Apple's iTunes software when used with a proxy.
3087 * 1 : csp = Current client state (buffers, headers, etc...)
3088 * 2 : header = On input, pointer to header to modify.
3089 * On output, pointer to the modified header, or NULL
3090 * to remove the header. This function frees the
3091 * original string if necessary.
3093 * Returns : JB_ERR_OK on success, or
3094 * JB_ERR_MEMORY on out-of-memory error.
3096 *********************************************************************/
3097 static jb_err client_host(struct client_state *csp, char **header)
3102 * If the header field name is all upper-case, chances are that it's
3103 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3104 * not a problem -- they are regenerated later.
3106 if ((*header)[1] == 'O')
3108 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3113 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3114 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3117 p = strdup_or_die((*header)+6);
3119 q = strdup_or_die(p);
3121 freez(csp->http->hostport);
3122 csp->http->hostport = p;
3123 freez(csp->http->host);
3124 csp->http->host = q;
3125 q = strchr(csp->http->host, ':');
3128 /* Terminate hostname and evaluate port string */
3130 csp->http->port = atoi(q);
3134 csp->http->port = csp->http->ssl ? 443 : 80;
3137 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3138 csp->http->hostport, csp->http->host, csp->http->port);
3141 /* Signal client_host_adder() to return right away */
3142 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3148 /*********************************************************************
3150 * Function : client_if_modified_since
3152 * Description : Remove or modify the If-Modified-Since header.
3155 * 1 : csp = Current client state (buffers, headers, etc...)
3156 * 2 : header = On input, pointer to header to modify.
3157 * On output, pointer to the modified header, or NULL
3158 * to remove the header. This function frees the
3159 * original string if necessary.
3161 * Returns : JB_ERR_OK on success, or
3162 * JB_ERR_MEMORY on out-of-memory error.
3164 *********************************************************************/
3165 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3168 #ifdef HAVE_GMTIME_R
3171 struct tm *timeptr = NULL;
3176 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3179 * The client got an error message because of a temporary problem,
3180 * the problem is gone and the client now tries to revalidate our
3181 * error message on the real server. The revalidation would always
3182 * end with the transmission of the whole document and there is
3183 * no need to expose the bogus If-Modified-Since header.
3185 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3188 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3190 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3192 if ((0 == strcmpic(newval, "block")))
3194 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3197 else /* add random value */
3199 const char *header_time = *header + sizeof("If-Modified-Since:");
3201 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3203 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3208 long int hours, minutes, seconds;
3209 long int rtime = strtol(newval, &endptr, 0);
3210 const int negative_range = (rtime < 0);
3214 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3215 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3221 rtime = pick_from_range(rtime);
3225 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3228 tm += rtime * (negative_range ? -1 : 1);
3229 #ifdef HAVE_GMTIME_R
3230 timeptr = gmtime_r(&tm, &gmt);
3231 #elif defined(MUTEX_LOCKS_AVAILABLE)
3232 privoxy_mutex_lock(&gmtime_mutex);
3233 timeptr = gmtime(&tm);
3234 privoxy_mutex_unlock(&gmtime_mutex);
3236 timeptr = gmtime(&tm);
3238 if ((NULL == timeptr) || !strftime(newheader,
3239 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3241 log_error(LOG_LEVEL_ERROR,
3242 "Randomizing '%s' failed. Crunching the header without replacement.",
3249 *header = strdup("If-Modified-Since: ");
3250 string_append(header, newheader);
3252 if (*header == NULL)
3254 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3255 return JB_ERR_MEMORY;
3258 hours = rtime / 3600;
3259 minutes = rtime / 60 % 60;
3260 seconds = rtime % 60;
3262 log_error(LOG_LEVEL_HEADER,
3263 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3264 *header, (negative_range) ? "subtracted" : "added", hours,
3265 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3266 seconds, (seconds == 1) ? ")" : "s)");
3275 /*********************************************************************
3277 * Function : client_if_none_match
3279 * Description : Remove the If-None-Match header.
3282 * 1 : csp = Current client state (buffers, headers, etc...)
3283 * 2 : header = On input, pointer to header to modify.
3284 * On output, pointer to the modified header, or NULL
3285 * to remove the header. This function frees the
3286 * original string if necessary.
3288 * Returns : JB_ERR_OK on success, or
3289 * JB_ERR_MEMORY on out-of-memory error.
3291 *********************************************************************/
3292 static jb_err client_if_none_match(struct client_state *csp, char **header)
3294 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3296 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3304 /*********************************************************************
3306 * Function : client_x_filter
3308 * Description : Disables filtering if the client set "X-Filter: No".
3309 * Called from `sed'.
3312 * 1 : csp = Current client state (buffers, headers, etc...)
3313 * 2 : header = On input, pointer to header to modify.
3314 * On output, pointer to the modified header, or NULL
3315 * to remove the header. This function frees the
3316 * original string if necessary.
3318 * Returns : JB_ERR_OK on success
3320 *********************************************************************/
3321 jb_err client_x_filter(struct client_state *csp, char **header)
3323 if (0 == strcmpic(*header, "X-Filter: No"))
3325 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3327 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3331 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3333 log_error(LOG_LEVEL_HEADER,
3334 "force-text-mode overruled the client's request to fetch without filtering!");
3338 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3339 csp->flags |= CSP_FLAG_NO_FILTERING;
3340 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3342 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3350 /*********************************************************************
3352 * Function : client_range
3354 * Description : Removes Range, Request-Range and If-Range headers if
3355 * content filtering is enabled and the range doesn't
3358 * If the client's version of the document has been
3359 * altered by Privoxy, the server could interpret the
3360 * range differently than the client intended in which
3361 * case the user could end up with corrupted content.
3363 * If the range starts at byte 0 this isn't an issue
3364 * so the header can pass. Partial requests like this
3365 * are used to render preview images for videos without
3366 * downloading the whole video.
3368 * While HTTP doesn't require that range requests are
3369 * honoured and the client could simply abort the download
3370 * after receiving a sufficient amount of data, various
3371 * clients don't handle complete responses to range
3372 * requests gracefully and emit misleading error messages
3376 * 1 : csp = Current client state (buffers, headers, etc...)
3377 * 2 : header = On input, pointer to header to modify.
3378 * On output, pointer to the modified header, or NULL
3379 * to remove the header. This function frees the
3380 * original string if necessary.
3382 * Returns : JB_ERR_OK
3384 *********************************************************************/
3385 static jb_err client_range(struct client_state *csp, char **header)
3387 if (content_filters_enabled(csp->action)
3388 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3390 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3391 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3398 /* the following functions add headers directly to the header list */
3400 /*********************************************************************
3402 * Function : client_host_adder
3404 * Description : Adds the Host: header field if it is missing.
3405 * Called from `sed'.
3408 * 1 : csp = Current client state (buffers, headers, etc...)
3410 * Returns : JB_ERR_OK on success, or
3411 * JB_ERR_MEMORY on out-of-memory error.
3413 *********************************************************************/
3414 static jb_err client_host_adder(struct client_state *csp)
3419 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3421 /* Header already set by the client, nothing to do. */
3425 if (!csp->http->hostport || !*(csp->http->hostport))
3427 /* XXX: When does this happen and why is it OK? */
3428 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3433 * remove 'user:pass@' from 'proto://user:pass@host'
3435 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3441 p = csp->http->hostport;
3444 /* XXX: Just add it, we already made sure that it will be unique */
3445 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3446 err = enlist_unique_header(csp->headers, "Host", p);
3452 /*********************************************************************
3454 * Function : client_xtra_adder
3456 * Description : Used in the add_client_headers list. Called from `sed'.
3459 * 1 : csp = Current client state (buffers, headers, etc...)
3461 * Returns : JB_ERR_OK on success, or
3462 * JB_ERR_MEMORY on out-of-memory error.
3464 *********************************************************************/
3465 static jb_err client_xtra_adder(struct client_state *csp)
3467 struct list_entry *lst;
3470 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3471 lst ; lst = lst->next)
3473 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3474 err = enlist(csp->headers, lst->str);
3486 /*********************************************************************
3488 * Function : client_x_forwarded_for_adder
3490 * Description : Used in the add_client_headers list. Called from `sed'.
3493 * 1 : csp = Current client state (buffers, headers, etc...)
3495 * Returns : JB_ERR_OK on success, or
3496 * JB_ERR_MEMORY on out-of-memory error.
3498 *********************************************************************/
3499 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3501 char *header = NULL;
3504 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3505 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3506 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3509 * If we aren't adding X-Forwarded-For headers,
3510 * or we already appended an existing X-Forwarded-For
3511 * header, there's nothing left to do here.
3516 header = strdup("X-Forwarded-For: ");
3517 string_append(&header, csp->ip_addr_str);
3521 return JB_ERR_MEMORY;
3524 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3525 err = enlist(csp->headers, header);
3532 /*********************************************************************
3534 * Function : server_connection_adder
3536 * Description : Adds an appropriate "Connection:" header to csp->headers
3537 * unless the header was already present. Called from `sed'.
3540 * 1 : csp = Current client state (buffers, headers, etc...)
3542 * Returns : JB_ERR_OK on success, or
3543 * JB_ERR_MEMORY on out-of-memory error.
3545 *********************************************************************/
3546 static jb_err server_connection_adder(struct client_state *csp)
3548 const unsigned int flags = csp->flags;
3549 const char *response_status_line = csp->headers->first->str;
3550 static const char connection_close[] = "Connection: close";
3552 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3553 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3559 * XXX: if we downgraded the response, this check will fail.
3561 if ((csp->config->feature_flags &
3562 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3563 && (NULL != response_status_line)
3564 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3565 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3566 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3570 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3571 "without Connection header implies keep-alive.");
3572 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3576 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3578 return enlist(csp->headers, connection_close);
3582 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3583 /*********************************************************************
3585 * Function : server_proxy_connection_adder
3587 * Description : Adds a "Proxy-Connection: keep-alive" header to
3588 * csp->headers if the client asked for keep-alive.
3589 * XXX: We should reuse existent ones.
3592 * 1 : csp = Current client state (buffers, headers, etc...)
3594 * Returns : JB_ERR_OK on success, or
3595 * JB_ERR_MEMORY on out-of-memory error.
3597 *********************************************************************/
3598 static jb_err server_proxy_connection_adder(struct client_state *csp)
3600 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3601 jb_err err = JB_ERR_OK;
3603 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3604 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3605 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET))
3607 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3608 err = enlist(csp->headers, proxy_connection_header);
3613 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3616 /*********************************************************************
3618 * Function : client_connection_header_adder
3620 * Description : Adds a proper "Connection:" header to csp->headers
3621 * unless the header was already present. Called from `sed'.
3624 * 1 : csp = Current client state (buffers, headers, etc...)
3626 * Returns : JB_ERR_OK on success, or
3627 * JB_ERR_MEMORY on out-of-memory error.
3629 *********************************************************************/
3630 static jb_err client_connection_header_adder(struct client_state *csp)
3632 static const char connection_close[] = "Connection: close";
3634 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3635 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3640 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3641 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3642 && (csp->http->ssl == 0)
3643 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3645 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3648 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3650 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3652 return enlist(csp->headers, connection_close);
3656 /*********************************************************************
3658 * Function : server_http
3660 * Description : - Save the HTTP Status into csp->http->status
3661 * - Set CT_TABOO to prevent filtering if the answer
3662 * is a partial range (HTTP status 206)
3663 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3667 * 1 : csp = Current client state (buffers, headers, etc...)
3668 * 2 : header = On input, pointer to header to modify.
3669 * On output, pointer to the modified header, or NULL
3670 * to remove the header. This function frees the
3671 * original string if necessary.
3673 * Returns : JB_ERR_OK on success, or
3674 * JB_ERR_MEMORY on out-of-memory error.
3676 *********************************************************************/
3677 static jb_err server_http(struct client_state *csp, char **header)
3679 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3680 if (csp->http->status == 206)
3682 csp->content_type = CT_TABOO;
3685 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3687 /* XXX: Should we do a real validity check here? */
3688 if (strlen(*header) > 8)
3691 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3696 * XXX: Should we block the request or
3697 * enlist a valid status code line here?
3699 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3700 "Downgrading to HTTP/1.0 impossible.");
3708 /*********************************************************************
3710 * Function : server_set_cookie
3712 * Description : Handle the server "cookie" header properly.
3713 * Crunch, accept or rewrite it to a session cookie.
3714 * Called from `sed'.
3716 * TODO: Allow the user to specify a new expiration
3717 * time to cause the cookie to expire even before the
3718 * browser is closed.
3721 * 1 : csp = Current client state (buffers, headers, etc...)
3722 * 2 : header = On input, pointer to header to modify.
3723 * On output, pointer to the modified header, or NULL
3724 * to remove the header. This function frees the
3725 * original string if necessary.
3727 * Returns : JB_ERR_OK on success, or
3728 * JB_ERR_MEMORY on out-of-memory error.
3730 *********************************************************************/
3731 static jb_err server_set_cookie(struct client_state *csp, char **header)
3738 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3740 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3743 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3745 /* Flag whether or not to log a message */
3748 /* A variable to store the tag we're working on */
3751 /* Skip "Set-Cookie:" (11 characters) in header */
3752 cur_tag = *header + 11;
3754 /* skip whitespace between "Set-Cookie:" and value */
3755 while (*cur_tag && privoxy_isspace(*cur_tag))
3760 /* Loop through each tag in the cookie */
3764 char *next_tag = strchr(cur_tag, ';');
3765 if (next_tag != NULL)
3767 /* Skip the ';' character itself */
3770 /* skip whitespace ";" and start of tag */
3771 while (*next_tag && privoxy_isspace(*next_tag))
3778 /* "Next tag" is the end of the string */
3779 next_tag = cur_tag + strlen(cur_tag);
3783 * Check the expiration date to see
3784 * if the cookie is still valid, if yes,
3785 * rewrite it to a session cookie.
3787 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3789 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3791 if ((expiration_date[0] == '"')
3792 && (expiration_date[1] != '\0'))
3795 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
3796 * that the expiration date isn't supposed to be quoted,
3797 * but some servers do it anyway.
3802 /* Did we detect the date properly? */
3803 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3806 * Nope, treat it as if it was still valid.
3808 * XXX: Should we remove the whole cookie instead?
3810 log_error(LOG_LEVEL_ERROR,
3811 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3812 string_move(cur_tag, next_tag);
3818 * Yes. Check if the cookie is still valid.
3820 * If the cookie is already expired it's probably
3821 * a delete cookie and even if it isn't, the browser
3822 * will discard it anyway.
3826 * XXX: timegm() isn't available on some AmigaOS
3827 * versions and our replacement doesn't work.
3829 * Our options are to either:
3831 * - disable session-cookies-only completely if timegm
3834 * - to simply remove all expired tags, like it has
3835 * been done until Privoxy 3.0.6 and to live with
3836 * the consequence that it can cause login/logout
3837 * problems on servers that don't validate their
3838 * input properly, or
3840 * - to replace it with mktime in which
3841 * case there is a slight chance of valid cookies
3842 * passing as already expired.
3844 * This is the way it's currently done and it's not
3845 * as bad as it sounds. If the missing GMT offset is
3846 * enough to change the result of the expiration check
3847 * the cookie will be only valid for a few hours
3848 * anyway, which in many cases will be shorter
3849 * than a browser session.
3851 if (cookie_time - now < 0)
3853 log_error(LOG_LEVEL_HEADER,
3854 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3855 /* Just in case some clown sets more then one expiration date */
3861 * Still valid, delete expiration date by copying
3862 * the rest of the string over it.
3864 string_move(cur_tag, next_tag);
3866 /* That changed the header, need to issue a log message */
3870 * Note that the next tag has now been moved to *cur_tag,
3871 * so we do not need to update the cur_tag pointer.
3879 /* Move on to next cookie tag */
3886 assert(NULL != *header);
3887 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3896 #ifdef FEATURE_FORCE_LOAD
3897 /*********************************************************************
3899 * Function : strclean
3901 * Description : In-Situ-Eliminate all occurrences of substring in
3905 * 1 : string = string to clean
3906 * 2 : substring = substring to eliminate
3908 * Returns : Number of eliminations
3910 *********************************************************************/
3911 int strclean(char *string, const char *substring)
3917 len = strlen(substring);
3919 while((pos = strstr(string, substring)) != NULL)
3926 while (*p++ != '\0');
3933 #endif /* def FEATURE_FORCE_LOAD */
3936 /*********************************************************************
3938 * Function : parse_header_time
3940 * Description : Parses time formats used in HTTP header strings
3941 * to get the numerical respresentation.
3944 * 1 : header_time = HTTP header time as string.
3945 * 2 : result = storage for header_time in seconds
3947 * Returns : JB_ERR_OK if the time format was recognized, or
3948 * JB_ERR_PARSE otherwise.
3950 *********************************************************************/
3951 static jb_err parse_header_time(const char *header_time, time_t *result)
3955 * Checking for two-digit years first in an
3956 * attempt to work around GNU libc's strptime()
3957 * reporting negative year values when using %Y.
3959 static const char * const time_formats[] = {
3960 /* Tue, 02-Jun-37 20:00:00 */
3961 "%a, %d-%b-%y %H:%M:%S",
3962 /* Tue, 02 Jun 2037 20:00:00 */
3963 "%a, %d %b %Y %H:%M:%S",
3964 /* Tue, 02-Jun-2037 20:00:00 */
3965 "%a, %d-%b-%Y %H:%M:%S",
3966 /* Tuesday, 02-Jun-2037 20:00:00 */
3967 "%A, %d-%b-%Y %H:%M:%S",
3968 /* Tuesday Jun 02 20:00:00 2037 */
3969 "%A %b %d %H:%M:%S %Y"
3973 for (i = 0; i < SZ(time_formats); i++)
3976 * Zero out gmt to prevent time zone offsets.
3977 * Documented to be required for GNU libc.
3979 memset(&gmt, 0, sizeof(gmt));
3981 if (NULL != strptime(header_time, time_formats[i], &gmt))
3983 /* Sanity check for GNU libc. */
3984 if (gmt.tm_year < 0)
3986 log_error(LOG_LEVEL_HEADER,
3987 "Failed to parse '%s' using '%s'. Moving on.",
3988 header_time, time_formats[i]);
3991 *result = timegm(&gmt);
3996 return JB_ERR_PARSE;
4001 /*********************************************************************
4003 * Function : get_destination_from_headers
4005 * Description : Parse the "Host:" header to get the request's destination.
4006 * Only needed if the client's request was forcefully
4007 * redirected into Privoxy.
4009 * Code mainly copied from client_host() which is currently
4010 * run too late for this purpose.
4013 * 1 : headers = List of headers (one of them hopefully being
4014 * the "Host:" header)
4015 * 2 : http = storage for the result (host, port and hostport).
4017 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4018 * JB_ERR_PARSE if the host header couldn't be found,
4019 * JB_ERR_OK otherwise.
4021 *********************************************************************/
4022 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4028 host = get_header_value(headers, "Host:");
4032 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4033 return JB_ERR_PARSE;
4036 p = strdup_or_die(host);
4038 q = strdup_or_die(p);
4040 freez(http->hostport);
4044 q = strchr(http->host, ':');
4047 /* Terminate hostname and evaluate port string */
4049 http->port = atoi(q);
4053 http->port = http->ssl ? 443 : 80;
4056 /* Rebuild request URL */
4058 http->url = strdup(http->ssl ? "https://" : "http://");
4059 string_append(&http->url, http->hostport);
4060 string_append(&http->url, http->path);
4061 if (http->url == NULL)
4063 return JB_ERR_MEMORY;
4066 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4074 /*********************************************************************
4076 * Function : create_forged_referrer
4078 * Description : Helper for client_referrer to forge a referer as
4079 * 'http://hostname[:port]/' to fool stupid
4080 * checks for in-site links
4083 * 1 : header = Pointer to header pointer
4084 * 2 : hostport = Host and optionally port as string
4086 * Returns : JB_ERR_OK in case of success, or
4087 * JB_ERR_MEMORY in case of memory problems.
4089 *********************************************************************/
4090 static jb_err create_forged_referrer(char **header, const char *hostport)
4092 assert(NULL == *header);
4094 *header = strdup("Referer: http://");
4095 string_append(header, hostport);
4096 string_append(header, "/");
4098 if (NULL == *header)
4100 return JB_ERR_MEMORY;
4103 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4110 /*********************************************************************
4112 * Function : create_fake_referrer
4114 * Description : Helper for client_referrer to create a fake referrer
4115 * based on a string supplied by the user.
4118 * 1 : header = Pointer to header pointer
4119 * 2 : hosthost = Referrer to fake
4121 * Returns : JB_ERR_OK in case of success, or
4122 * JB_ERR_MEMORY in case of memory problems.
4124 *********************************************************************/
4125 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4127 assert(NULL == *header);
4129 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4131 log_error(LOG_LEVEL_HEADER,
4132 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4134 *header = strdup("Referer: ");
4135 string_append(header, fake_referrer);
4137 if (NULL == *header)
4139 return JB_ERR_MEMORY;
4142 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4149 /*********************************************************************
4151 * Function : handle_conditional_hide_referrer_parameter
4153 * Description : Helper for client_referrer to crunch or forge
4154 * the referrer header if the host has changed.
4157 * 1 : header = Pointer to header pointer
4158 * 2 : host = The target host (may include the port)
4159 * 3 : parameter_conditional_block = Boolean to signal
4160 * if we're in conditional-block mode. If not set,
4161 * we're in conditional-forge mode.
4163 * Returns : JB_ERR_OK in case of success, or
4164 * JB_ERR_MEMORY in case of memory problems.
4166 *********************************************************************/
4167 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4168 const char *host, const int parameter_conditional_block)
4170 char *referer = strdup_or_die(*header);
4171 const size_t hostlength = strlen(host);
4172 const char *referer_url = NULL;
4174 /* referer begins with 'Referer: http[s]://' */
4175 if ((hostlength+17) < strlen(referer))
4178 * Shorten referer to make sure the referer is blocked
4179 * if www.example.org/www.example.com-shall-see-the-referer/
4180 * links to www.example.com/
4182 referer[hostlength+17] = '\0';
4184 referer_url = strstr(referer, "http://");
4185 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4187 /* Host has changed, Referer is invalid or a https URL. */
4188 if (parameter_conditional_block)
4190 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4197 return create_forged_referrer(header, host);
4207 /*********************************************************************
4209 * Function : create_content_length_header
4211 * Description : Creates a Content-Length header.
4214 * 1 : content_length = The content length to be used in the header.
4215 * 2 : header = Allocated space to safe the header.
4216 * 3 : buffer_length = The length of the allocated space.
4220 *********************************************************************/
4221 static void create_content_length_header(unsigned long long content_length,
4222 char *header, size_t buffer_length)
4224 snprintf(header, buffer_length, "Content-Length: %llu", content_length);