1 const char parsers_rcs[] = "$Id: parsers.c,v 1.257 2012/10/21 12:39:27 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
8 * Copyright : Written by and Copyright (C) 2001-2012 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
40 #include <sys/types.h>
50 * Convince GNU's libc to provide a strptime prototype.
59 #define GZIP_IDENTIFIER_1 0x1f
60 #define GZIP_IDENTIFIER_2 0x8b
62 #define GZIP_FLAG_CHECKSUM 0x02
63 #define GZIP_FLAG_EXTRA_FIELDS 0x04
64 #define GZIP_FLAG_FILE_NAME 0x08
65 #define GZIP_FLAG_COMMENT 0x10
66 #define GZIP_FLAG_RESERVED_BITS 0xe0
69 #if !defined(_WIN32) && !defined(__OS2__)
75 #ifdef FEATURE_PTHREAD
77 /* jcc.h is for mutex semapores only */
78 #endif /* def FEATURE_PTHREAD */
83 #include "jbsockets.h"
93 const char parsers_h_rcs[] = PARSERS_H_VERSION;
95 static char *get_header_line(struct iob *iob);
96 static jb_err scan_headers(struct client_state *csp);
97 static jb_err header_tagger(struct client_state *csp, char *header);
98 static jb_err parse_header_time(const char *header_time, time_t *result);
100 static jb_err crumble (struct client_state *csp, char **header);
101 static jb_err filter_header (struct client_state *csp, char **header);
102 static jb_err client_connection (struct client_state *csp, char **header);
103 static jb_err client_referrer (struct client_state *csp, char **header);
104 static jb_err client_uagent (struct client_state *csp, char **header);
105 static jb_err client_ua (struct client_state *csp, char **header);
106 static jb_err client_from (struct client_state *csp, char **header);
107 static jb_err client_send_cookie (struct client_state *csp, char **header);
108 static jb_err client_x_forwarded (struct client_state *csp, char **header);
109 static jb_err client_accept_encoding (struct client_state *csp, char **header);
110 static jb_err client_te (struct client_state *csp, char **header);
111 static jb_err client_max_forwards (struct client_state *csp, char **header);
112 static jb_err client_host (struct client_state *csp, char **header);
113 static jb_err client_if_modified_since (struct client_state *csp, char **header);
114 static jb_err client_accept_language (struct client_state *csp, char **header);
115 static jb_err client_if_none_match (struct client_state *csp, char **header);
116 static jb_err crunch_client_header (struct client_state *csp, char **header);
117 static jb_err client_x_filter (struct client_state *csp, char **header);
118 static jb_err client_range (struct client_state *csp, char **header);
119 static jb_err server_set_cookie (struct client_state *csp, char **header);
120 static jb_err server_connection (struct client_state *csp, char **header);
121 static jb_err server_content_type (struct client_state *csp, char **header);
122 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
123 static jb_err server_content_md5 (struct client_state *csp, char **header);
124 static jb_err server_content_encoding (struct client_state *csp, char **header);
125 static jb_err server_transfer_coding (struct client_state *csp, char **header);
126 static jb_err server_http (struct client_state *csp, char **header);
127 static jb_err crunch_server_header (struct client_state *csp, char **header);
128 static jb_err server_last_modified (struct client_state *csp, char **header);
129 static jb_err server_content_disposition(struct client_state *csp, char **header);
131 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
134 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
135 static jb_err server_save_content_length(struct client_state *csp, char **header);
136 static jb_err server_keep_alive(struct client_state *csp, char **header);
137 static jb_err server_proxy_connection(struct client_state *csp, char **header);
138 static jb_err client_keep_alive(struct client_state *csp, char **header);
139 static jb_err client_save_content_length(struct client_state *csp, char **header);
140 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
142 static jb_err client_host_adder (struct client_state *csp);
143 static jb_err client_xtra_adder (struct client_state *csp);
144 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
145 static jb_err client_connection_header_adder(struct client_state *csp);
146 static jb_err server_connection_adder(struct client_state *csp);
147 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
148 static jb_err server_proxy_connection_adder(struct client_state *csp);
149 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
151 static jb_err create_forged_referrer(char **header, const char *hostport);
152 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
153 static jb_err handle_conditional_hide_referrer_parameter(char **header,
154 const char *host, const int parameter_conditional_block);
155 static void create_content_length_header(unsigned long long content_length,
156 char *header, size_t buffer_length);
159 * List of functions to run on a list of headers.
163 /** The header prefix to match */
166 /** The length of the prefix to match */
169 /** The function to apply to this line */
170 const parser_func_ptr parser;
173 static const struct parsers client_patterns[] = {
174 { "referer:", 8, client_referrer },
175 { "user-agent:", 11, client_uagent },
176 { "ua-", 3, client_ua },
177 { "from:", 5, client_from },
178 { "cookie:", 7, client_send_cookie },
179 { "x-forwarded-for:", 16, client_x_forwarded },
180 { "Accept-Encoding:", 16, client_accept_encoding },
181 { "TE:", 3, client_te },
182 { "Host:", 5, client_host },
183 { "if-modified-since:", 18, client_if_modified_since },
184 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
185 { "Keep-Alive:", 11, client_keep_alive },
186 { "Content-Length:", 15, client_save_content_length },
188 { "Keep-Alive:", 11, crumble },
190 { "connection:", 11, client_connection },
191 { "proxy-connection:", 17, crumble },
192 { "max-forwards:", 13, client_max_forwards },
193 { "Accept-Language:", 16, client_accept_language },
194 { "if-none-match:", 14, client_if_none_match },
195 { "Range:", 6, client_range },
196 { "Request-Range:", 14, client_range },
197 { "If-Range:", 9, client_range },
198 { "X-Filter:", 9, client_x_filter },
199 { "*", 0, crunch_client_header },
200 { "*", 0, filter_header },
204 static const struct parsers server_patterns[] = {
205 { "HTTP/", 5, server_http },
206 { "set-cookie:", 11, server_set_cookie },
207 { "connection:", 11, server_connection },
208 { "Content-Type:", 13, server_content_type },
209 { "Content-MD5:", 12, server_content_md5 },
210 { "Content-Encoding:", 17, server_content_encoding },
211 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
212 { "Content-Length:", 15, server_save_content_length },
213 { "Keep-Alive:", 11, server_keep_alive },
214 { "Proxy-Connection:", 17, server_proxy_connection },
216 { "Keep-Alive:", 11, crumble },
217 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
218 { "Transfer-Encoding:", 18, server_transfer_coding },
219 { "content-disposition:", 20, server_content_disposition },
220 { "Last-Modified:", 14, server_last_modified },
221 { "*", 0, crunch_server_header },
222 { "*", 0, filter_header },
226 static const add_header_func_ptr add_client_headers[] = {
228 client_x_forwarded_for_adder,
230 client_connection_header_adder,
234 static const add_header_func_ptr add_server_headers[] = {
235 server_connection_adder,
236 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
237 server_proxy_connection_adder,
238 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
242 /*********************************************************************
244 * Function : flush_socket
246 * Description : Write any pending "buffered" content.
249 * 1 : fd = file descriptor of the socket to read
250 * 2 : iob = The I/O buffer to flush, usually csp->iob.
252 * Returns : On success, the number of bytes written are returned (zero
253 * indicates nothing was written). On error, -1 is returned,
254 * and errno is set appropriately. If count is zero and the
255 * file descriptor refers to a regular file, 0 will be
256 * returned without causing any other effect. For a special
257 * file, the results are not portable.
259 *********************************************************************/
260 long flush_socket(jb_socket fd, struct iob *iob)
262 long len = iob->eod - iob->cur;
269 if (write_socket(fd, iob->cur, (size_t)len))
273 iob->eod = iob->cur = iob->buf;
279 /*********************************************************************
281 * Function : add_to_iob
283 * Description : Add content to the buffer, expanding the
284 * buffer if necessary.
287 * 1 : iob = Destination buffer.
288 * 2 : buffer_limit = Limit to which the destination may grow
289 * 3 : src = holds the content to be added
290 * 4 : n = number of bytes to be added
292 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
293 * or buffer limit reached.
295 *********************************************************************/
296 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
298 size_t used, offset, need;
301 if (n <= 0) return JB_ERR_OK;
303 used = (size_t)(iob->eod - iob->buf);
304 offset = (size_t)(iob->cur - iob->buf);
305 need = used + (size_t)n + 1;
308 * If the buffer can't hold the new data, extend it first.
309 * Use the next power of two if possible, else use the actual need.
311 if (need > buffer_limit)
313 log_error(LOG_LEVEL_INFO,
314 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
316 return JB_ERR_MEMORY;
319 if (need > iob->size)
321 size_t want = iob->size ? iob->size : 512;
328 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
332 else if (NULL != (p = (char *)realloc(iob->buf, need)))
338 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
339 return JB_ERR_MEMORY;
342 /* Update the iob pointers */
343 iob->cur = p + offset;
348 /* copy the new data into the iob buffer */
349 memcpy(iob->eod, src, (size_t)n);
351 /* point to the end of the data */
354 /* null terminate == cheap insurance */
362 /*********************************************************************
364 * Function : clear_iob
366 * Description : Frees the memory allocated for an I/O buffer and
367 * resets the structure.
370 * 1 : iob = I/O buffer to clear.
372 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
373 * or buffer limit reached.
375 *********************************************************************/
376 void clear_iob(struct iob *iob)
379 memset(iob, '\0', sizeof(*iob));;
384 /*********************************************************************
386 * Function : decompress_iob
388 * Description : Decompress buffered page, expanding the
389 * buffer as necessary. csp->iob->cur
390 * should point to the the beginning of the
391 * compressed data block.
394 * 1 : csp = Current client state (buffers, headers, etc...)
396 * Returns : JB_ERR_OK on success,
397 * JB_ERR_MEMORY if out-of-memory limit reached, and
398 * JB_ERR_COMPRESS if error decompressing buffer.
400 *********************************************************************/
401 jb_err decompress_iob(struct client_state *csp)
403 char *buf; /* new, uncompressed buffer */
404 char *cur; /* Current iob position (to keep the original
405 * iob->cur unmodified if we return early) */
406 size_t bufsize; /* allocated size of the new buffer */
407 size_t old_size; /* Content size before decompression */
408 size_t skip_size; /* Number of bytes at the beginning of the iob
409 that we should NOT decompress. */
410 int status; /* return status of the inflate() call */
411 z_stream zstr; /* used by calls to zlib */
413 assert(csp->iob->cur - csp->iob->buf > 0);
414 assert(csp->iob->eod - csp->iob->cur > 0);
416 bufsize = csp->iob->size;
417 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
418 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
422 if (bufsize < (size_t)10)
425 * This is to protect the parsing of gzipped data,
426 * but it should(?) be valid for deflated data also.
428 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
429 return JB_ERR_COMPRESS;
432 if (csp->content_type & CT_GZIP)
435 * Our task is slightly complicated by the facts that data
436 * compressed by gzip does not include a zlib header, and
437 * that there is no easily accessible interface in zlib to
438 * handle a gzip header. We strip off the gzip header by
439 * hand, and later inform zlib not to expect a header.
443 * Strip off the gzip header. Please see RFC 1952 for more
444 * explanation of the appropriate fields.
446 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
447 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
448 || (*cur++ != Z_DEFLATED))
450 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
451 return JB_ERR_COMPRESS;
456 if (flags & GZIP_FLAG_RESERVED_BITS)
458 /* The gzip header has reserved bits set; bail out. */
459 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
460 return JB_ERR_COMPRESS;
464 * Skip mtime (4 bytes), extra flags (1 byte)
465 * and OS type (1 byte).
469 /* Skip extra fields if necessary. */
470 if (flags & GZIP_FLAG_EXTRA_FIELDS)
473 * Skip a given number of bytes, specified
474 * as a 16-bit little-endian value.
476 * XXX: this code is untested and should probably be removed.
480 skip_bytes += *cur++ << 8;
483 * The number of bytes to skip should be positive
484 * and we'd like to stay in the buffer.
486 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
488 log_error(LOG_LEVEL_ERROR,
489 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
491 return JB_ERR_COMPRESS;
493 log_error(LOG_LEVEL_INFO,
494 "Skipping %d bytes for gzip compression. Does this sound right?",
499 /* Skip the filename if necessary. */
500 if (flags & GZIP_FLAG_FILE_NAME)
502 /* A null-terminated string is supposed to follow. */
503 while (*cur++ && (cur < csp->iob->eod));
506 /* Skip the comment if necessary. */
507 if (flags & GZIP_FLAG_COMMENT)
509 /* A null-terminated string is supposed to follow. */
510 while (*cur++ && (cur < csp->iob->eod));
513 /* Skip the CRC if necessary. */
514 if (flags & GZIP_FLAG_CHECKSUM)
519 if (cur >= csp->iob->eod)
522 * If the current position pointer reached or passed
523 * the buffer end, we were obviously tricked to skip
526 log_error(LOG_LEVEL_ERROR,
527 "Malformed gzip header detected. Aborting decompression.");
528 return JB_ERR_COMPRESS;
532 else if (csp->content_type & CT_DEFLATE)
535 * XXX: The debug level should be lowered
536 * before the next stable release.
538 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
540 * In theory (that is, according to RFC 1950), deflate-compressed
541 * data should begin with a two-byte zlib header and have an
542 * adler32 checksum at the end. It seems that in practice only
543 * the raw compressed data is sent. Note that this means that
544 * we are not RFC 1950-compliant here, but the advantage is that
545 * this actually works. :)
547 * We add a dummy null byte to tell zlib where the data ends,
548 * and later inform it not to expect a header.
550 * Fortunately, add_to_iob() has thoughtfully null-terminated
551 * the buffer; we can just increment the end pointer to include
558 log_error(LOG_LEVEL_ERROR,
559 "Unable to determine compression format for decompression");
560 return JB_ERR_COMPRESS;
563 /* Set up the fields required by zlib. */
564 zstr.next_in = (Bytef *)cur;
565 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
566 zstr.zalloc = Z_NULL;
568 zstr.opaque = Z_NULL;
571 * Passing -MAX_WBITS to inflateInit2 tells the library
572 * that there is no zlib header.
574 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
576 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
577 return JB_ERR_COMPRESS;
581 * Next, we allocate new storage for the inflated data.
582 * We don't modify the existing iob yet, so in case there
583 * is error in decompression we can recover gracefully.
585 buf = zalloc(bufsize);
588 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
589 return JB_ERR_MEMORY;
592 assert(bufsize >= skip_size);
593 memcpy(buf, csp->iob->buf, skip_size);
594 zstr.avail_out = (uInt)(bufsize - skip_size);
595 zstr.next_out = (Bytef *)buf + skip_size;
597 /* Try to decompress the whole stream in one shot. */
598 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
600 /* We need to allocate more memory for the output buffer. */
602 char *tmpbuf; /* used for realloc'ing the buffer */
603 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
605 if (0 == zstr.avail_in)
608 * If zlib wants more data then there's a problem, because
609 * the complete compressed file should have been buffered.
611 log_error(LOG_LEVEL_ERROR,
612 "Unexpected end of compressed iob. Using what we got so far.");
617 * If we reached the buffer limit and still didn't have enough
618 * memory, just give up. Due to the ceiling enforced by the next
619 * if block we could actually check for equality here, but as it
620 * can be easily mistaken for a bug we don't.
622 if (bufsize >= csp->config->buffer_limit)
624 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
625 return JB_ERR_MEMORY;
628 /* Try doubling the buffer size each time. */
631 /* Don't exceed the buffer limit. */
632 if (bufsize > csp->config->buffer_limit)
634 bufsize = csp->config->buffer_limit;
637 /* Try to allocate the new buffer. */
638 tmpbuf = realloc(buf, bufsize);
641 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
643 return JB_ERR_MEMORY;
647 char *oldnext_out = (char *)zstr.next_out;
650 * Update the fields for inflate() to use the new
651 * buffer, which may be in a location different from
654 zstr.avail_out += (uInt)(bufsize - oldbufsize);
655 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
658 * Compare with an uglier method of calculating these values
659 * that doesn't require the extra oldbufsize variable.
661 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
662 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
668 if (Z_STREAM_ERROR == inflateEnd(&zstr))
670 log_error(LOG_LEVEL_ERROR,
671 "Inconsistent stream state after decompression: %s", zstr.msg);
673 * XXX: Intentionally no return.
675 * According to zlib.h, Z_STREAM_ERROR is returned
676 * "if the stream state was inconsistent".
678 * I assume in this case inflate()'s status
679 * would also be something different than Z_STREAM_END
680 * so this check should be redundant, but lets see.
684 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
687 * We failed to decompress the stream and it's
688 * not simply because of missing data.
690 log_error(LOG_LEVEL_ERROR,
691 "Unexpected error while decompressing to the buffer (iob): %s",
693 return JB_ERR_COMPRESS;
697 * Finally, we can actually update the iob, since the
698 * decompression was successful. First, free the old
701 freez(csp->iob->buf);
703 /* Now, update the iob to use the new buffer. */
705 csp->iob->cur = csp->iob->buf + skip_size;
706 csp->iob->eod = (char *)zstr.next_out;
707 csp->iob->size = bufsize;
710 * Make sure the new uncompressed iob obeys some minimal
711 * consistency conditions.
713 if ((csp->iob->buf < csp->iob->cur)
714 && (csp->iob->cur <= csp->iob->eod)
715 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
717 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
718 if (new_size > (size_t)0)
720 log_error(LOG_LEVEL_RE_FILTER,
721 "Decompression successful. Old size: %d, new size: %d.",
726 /* zlib thinks this is OK, so lets do the same. */
727 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
732 /* It seems that zlib did something weird. */
733 log_error(LOG_LEVEL_ERROR,
734 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
735 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
736 csp->iob->eod, csp->iob->buf + csp->iob->size);
737 return JB_ERR_COMPRESS;
743 #endif /* defined(FEATURE_ZLIB) */
746 /*********************************************************************
748 * Function : string_move
750 * Description : memmove wrapper to move the last part of a string
751 * towards the beginning, overwriting the part in
752 * the middle. strlcpy() can't be used here as the
756 * 1 : dst = Destination to overwrite
757 * 2 : src = Source to move.
761 *********************************************************************/
762 static void string_move(char *dst, char *src)
766 /* +1 to copy the terminating nul as well. */
767 memmove(dst, src, strlen(src)+1);
771 /*********************************************************************
773 * Function : normalize_lws
775 * Description : Reduces unquoted linear white space in headers
776 * to a single space in accordance with RFC 2616 2.2.
777 * This simplifies parsing and filtering later on.
779 * XXX: Remove log messages before
780 * the next stable release?
783 * 1 : header = A header with linear white space to reduce.
787 *********************************************************************/
788 static void normalize_lws(char *header)
794 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
798 while (privoxy_isspace(*q))
802 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
808 log_error(LOG_LEVEL_HEADER,
809 "Converting tab to space in '%s'", header);
814 char *end_of_token = strstr(p+1, "\"");
816 if (NULL != end_of_token)
818 /* Don't mess with quoted text. */
823 log_error(LOG_LEVEL_HEADER,
824 "Ignoring single quote in '%s'", header);
830 p = strchr(header, ':');
831 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
834 * There's still space before the colon.
842 /*********************************************************************
844 * Function : get_header
846 * Description : This (odd) routine will parse the csp->iob
847 * to get the next complete header.
850 * 1 : iob = The I/O buffer to parse, usually csp->iob.
852 * Returns : Any one of the following:
854 * 1) a pointer to a dynamically allocated string that contains a header line
855 * 2) NULL indicating that the end of the header was reached
856 * 3) "" indicating that the end of the iob was reached before finding
857 * a complete header line.
859 *********************************************************************/
860 char *get_header(struct iob *iob)
864 header = get_header_line(iob);
866 if ((header == NULL) || (*header == '\0'))
869 * No complete header read yet, tell the client.
874 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
877 * Header spans multiple lines, append the next one.
879 char *continued_header;
881 continued_header = get_header_line(iob);
882 if ((continued_header == NULL) || (*continued_header == '\0'))
885 * No complete header read yet, return what we got.
886 * XXX: Should "unread" header instead.
888 log_error(LOG_LEVEL_INFO,
889 "Failed to read a multi-line header properly: '%s'",
894 if (JB_ERR_OK != string_join(&header, continued_header))
896 log_error(LOG_LEVEL_FATAL,
897 "Out of memory while appending multiple headers.");
901 /* XXX: remove before next stable release. */
902 log_error(LOG_LEVEL_HEADER,
903 "Merged multiple header lines to: '%s'",
908 normalize_lws(header);
915 /*********************************************************************
917 * Function : get_header_line
919 * Description : This (odd) routine will parse the csp->iob
920 * to get the next header line.
923 * 1 : iob = The I/O buffer to parse, usually csp->iob.
925 * Returns : Any one of the following:
927 * 1) a pointer to a dynamically allocated string that contains a header line
928 * 2) NULL indicating that the end of the header was reached
929 * 3) "" indicating that the end of the iob was reached before finding
930 * a complete header line.
932 *********************************************************************/
933 static char *get_header_line(struct iob *iob)
937 if ((iob->cur == NULL)
938 || ((p = strchr(iob->cur, '\n')) == NULL))
940 return(""); /* couldn't find a complete header */
945 ret = strdup(iob->cur);
948 /* FIXME No way to handle error properly */
949 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
955 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
957 /* is this a blank line (i.e. the end of the header) ? */
969 /*********************************************************************
971 * Function : get_header_value
973 * Description : Get the value of a given header from a chained list
974 * of header lines or return NULL if no such header is
975 * present in the list.
978 * 1 : header_list = pointer to list
979 * 2 : header_name = string with name of header to look for.
980 * Trailing colon required, capitalization
983 * Returns : NULL if not found, else value of header
985 *********************************************************************/
986 char *get_header_value(const struct list *header_list, const char *header_name)
988 struct list_entry *cur_entry;
994 length = strlen(header_name);
996 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1000 if (!strncmpic(cur_entry->str, header_name, length))
1003 * Found: return pointer to start of value
1005 ret = cur_entry->str + length;
1006 while (*ret && privoxy_isspace(*ret)) ret++;
1020 /*********************************************************************
1022 * Function : scan_headers
1024 * Description : Scans headers, applies tags and updates action bits.
1027 * 1 : csp = Current client state (buffers, headers, etc...)
1029 * Returns : JB_ERR_OK
1031 *********************************************************************/
1032 static jb_err scan_headers(struct client_state *csp)
1034 struct list_entry *h; /* Header */
1035 jb_err err = JB_ERR_OK;
1037 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1039 /* Header crunch()ed in previous run? -> ignore */
1040 if (h->str == NULL) continue;
1041 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1042 err = header_tagger(csp, h->str);
1049 /*********************************************************************
1051 * Function : enforce_header_order
1053 * Description : Enforces a given header order.
1056 * 1 : headers = List of headers to order.
1057 * 2 : ordered_headers = List of ordered header names.
1061 *********************************************************************/
1062 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1064 struct list_entry *sorted_header;
1065 struct list new_headers[1];
1066 struct list_entry *header;
1068 init_list(new_headers);
1070 /* The request line is always the first "header" */
1072 assert(NULL != headers->first->str);
1073 enlist(new_headers, headers->first->str);
1074 freez(headers->first->str)
1076 /* Enlist the specified headers in the given order */
1078 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1079 sorted_header = sorted_header->next)
1081 const size_t sorted_header_length = strlen(sorted_header->str);
1082 for (header = headers->first; header != NULL; header = header->next)
1084 /* Header enlisted in previous run? -> ignore */
1085 if (header->str == NULL) continue;
1087 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1088 && (header->str[sorted_header_length] == ':'))
1090 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1091 if (JB_ERR_OK != enlist(new_headers, header->str))
1093 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1100 /* Enlist the rest of the headers behind the ordered ones */
1101 for (header = headers->first; header != NULL; header = header->next)
1103 /* Header enlisted in previous run? -> ignore */
1104 if (header->str == NULL) continue;
1106 log_error(LOG_LEVEL_HEADER,
1107 "Enlisting left-over header %s", header->str);
1108 if (JB_ERR_OK != enlist(new_headers, header->str))
1110 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1115 list_remove_all(headers);
1116 list_duplicate(headers, new_headers);
1117 list_remove_all(new_headers);
1122 /*********************************************************************
1126 * Description : add, delete or modify lines in the HTTP header streams.
1127 * On entry, it receives a linked list of headers space
1128 * that was allocated dynamically (both the list nodes
1129 * and the header contents).
1131 * As a side effect it frees the space used by the original
1135 * 1 : csp = Current client state (buffers, headers, etc...)
1136 * 2 : filter_server_headers = Boolean to switch between
1137 * server and header filtering.
1139 * Returns : JB_ERR_OK in case off success, or
1140 * JB_ERR_MEMORY on out-of-memory error.
1142 *********************************************************************/
1143 jb_err sed(struct client_state *csp, int filter_server_headers)
1145 /* XXX: use more descriptive names. */
1146 struct list_entry *p;
1147 const struct parsers *v;
1148 const add_header_func_ptr *f;
1149 jb_err err = JB_ERR_OK;
1151 if (filter_server_headers)
1153 v = server_patterns;
1154 f = add_server_headers;
1158 v = client_patterns;
1159 f = add_client_headers;
1164 while ((err == JB_ERR_OK) && (v->str != NULL))
1166 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1168 /* Header crunch()ed in previous run? -> ignore */
1169 if (p->str == NULL) continue;
1171 /* Does the current parser handle this header? */
1172 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1173 (v->len == CHECK_EVERY_HEADER_REMAINING))
1175 err = v->parser(csp, &(p->str));
1181 /* place additional headers on the csp->headers list */
1182 while ((err == JB_ERR_OK) && (*f))
1188 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1190 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1197 /*********************************************************************
1199 * Function : update_server_headers
1201 * Description : Updates server headers after the body has been modified.
1204 * 1 : csp = Current client state (buffers, headers, etc...)
1206 * Returns : JB_ERR_OK in case off success, or
1207 * JB_ERR_MEMORY on out-of-memory error.
1209 *********************************************************************/
1210 jb_err update_server_headers(struct client_state *csp)
1212 jb_err err = JB_ERR_OK;
1214 static const struct parsers server_patterns_light[] = {
1215 { "Content-Length:", 15, server_adjust_content_length },
1216 { "Transfer-Encoding:", 18, server_transfer_coding },
1218 { "Content-Encoding:", 17, server_adjust_content_encoding },
1219 #endif /* def FEATURE_ZLIB */
1223 if (strncmpic(csp->http->cmd, "HEAD", 4))
1225 const struct parsers *v;
1226 struct list_entry *p;
1228 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1230 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1232 /* Header crunch()ed in previous run? -> ignore */
1233 if (p->str == NULL) continue;
1235 /* Does the current parser handle this header? */
1236 if (strncmpic(p->str, v->str, v->len) == 0)
1238 err = v->parser(csp, (char **)&(p->str));
1244 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1245 if ((JB_ERR_OK == err)
1246 && (csp->flags & CSP_FLAG_MODIFIED)
1247 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1248 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1252 create_content_length_header(csp->content_length, header, sizeof(header));
1253 err = enlist(csp->headers, header);
1254 if (JB_ERR_OK == err)
1256 log_error(LOG_LEVEL_HEADER,
1257 "Content modified with no Content-Length header set. "
1258 "Created: %s.", header);
1261 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1263 #ifdef FEATURE_COMPRESSION
1264 if ((JB_ERR_OK == err)
1265 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1267 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1268 if (JB_ERR_OK == err)
1270 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1279 /*********************************************************************
1281 * Function : header_tagger
1283 * Description : Executes all text substitutions from applying
1284 * tag actions and saves the result as tag.
1286 * XXX: Shares enough code with filter_header() and
1287 * pcrs_filter_response() to warrant some helper functions.
1290 * 1 : csp = Current client state (buffers, headers, etc...)
1291 * 2 : header = Header that is used as tagger input
1293 * Returns : JB_ERR_OK on success and always succeeds
1295 *********************************************************************/
1296 static jb_err header_tagger(struct client_state *csp, char *header)
1298 int wanted_filter_type;
1299 int multi_action_index;
1303 struct file_list *fl;
1304 struct re_filterfile_spec *b;
1305 struct list_entry *tag_name;
1307 const size_t header_length = strlen(header);
1309 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1311 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1312 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1316 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1317 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1320 if (filters_available(csp) == FALSE)
1322 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1323 "tagging enabled, but no taggers available.");
1327 for (i = 0; i < MAX_AF_FILES; i++)
1330 if ((NULL == fl) || (NULL == fl->f))
1333 * Either there are no filter files
1334 * left, or this filter file just
1335 * contains no valid filters.
1337 * Continue to be sure we don't miss
1338 * valid filter files that are chained
1339 * after empty or invalid ones.
1344 /* For all filters, */
1345 for (b = fl->f; b; b = b->next)
1347 if (b->type != wanted_filter_type)
1349 /* skip the ones we don't care about, */
1352 /* leaving only taggers that could apply, of which we use the ones, */
1353 for (tag_name = csp->action->multi[multi_action_index]->first;
1354 NULL != tag_name; tag_name = tag_name->next)
1356 /* that do apply, and */
1357 if (strcmp(b->name, tag_name->str) == 0)
1359 char *modified_tag = NULL;
1361 size_t size = header_length;
1362 pcrs_job *joblist = b->joblist;
1364 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1366 if (NULL == joblist)
1368 log_error(LOG_LEVEL_RE_FILTER,
1369 "Tagger %s has empty joblist. Nothing to do.", b->name);
1373 /* execute their pcrs_joblist on the header. */
1374 for (job = joblist; NULL != job; job = job->next)
1376 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1380 /* Success, continue with the modified version. */
1389 /* Tagger doesn't match */
1392 /* Regex failure, log it but continue anyway. */
1393 assert(NULL != header);
1394 log_error(LOG_LEVEL_ERROR,
1395 "Problems with tagger \'%s\' and header \'%s\': %s",
1396 b->name, *header, pcrs_strerror(hits));
1398 freez(modified_tag);
1402 if (b->dynamic) pcrs_free_joblist(joblist);
1404 /* If this tagger matched */
1410 * There is to technical limitation which makes
1411 * it impossible to use empty tags, but I assume
1412 * no one would do it intentionally.
1415 log_error(LOG_LEVEL_INFO,
1416 "Tagger \'%s\' created an empty tag. Ignored.",
1421 if (!list_contains_item(csp->tags, tag))
1423 if (JB_ERR_OK != enlist(csp->tags, tag))
1425 log_error(LOG_LEVEL_ERROR,
1426 "Insufficient memory to add tag \'%s\', "
1427 "based on tagger \'%s\' and header \'%s\'",
1428 tag, b->name, *header);
1432 char *action_message;
1434 * update the action bits right away, to make
1435 * tagging based on tags set by earlier taggers
1436 * of the same kind possible.
1438 if (update_action_bits_for_tag(csp, tag))
1440 action_message = "Action bits updated accordingly.";
1444 action_message = "No action bits update necessary.";
1447 log_error(LOG_LEVEL_HEADER,
1448 "Tagger \'%s\' added tag \'%s\'. %s",
1449 b->name, tag, action_message);
1454 /* XXX: Is this log-worthy? */
1455 log_error(LOG_LEVEL_HEADER,
1456 "Tagger \'%s\' didn't add tag \'%s\'. "
1457 "Tag already present", b->name, tag);
1460 } /* if the tagger matched */
1461 } /* if the tagger applies */
1462 } /* for every tagger that could apply */
1463 } /* for all filters */
1464 } /* for all filter files */
1469 /* here begins the family of parser functions that reformat header lines */
1471 /*********************************************************************
1473 * Function : filter_header
1475 * Description : Executes all text substitutions from all applying
1476 * +(server|client)-header-filter actions on the header.
1477 * Most of the code was copied from pcrs_filter_response,
1478 * including the rather short variable names
1481 * 1 : csp = Current client state (buffers, headers, etc...)
1482 * 2 : header = On input, pointer to header to modify.
1483 * On output, pointer to the modified header, or NULL
1484 * to remove the header. This function frees the
1485 * original string if necessary.
1487 * Returns : JB_ERR_OK on success and always succeeds
1489 *********************************************************************/
1490 static jb_err filter_header(struct client_state *csp, char **header)
1494 size_t size = strlen(*header);
1496 char *newheader = NULL;
1499 struct file_list *fl;
1500 struct re_filterfile_spec *b;
1501 struct list_entry *filtername;
1504 int wanted_filter_type;
1505 int multi_action_index;
1507 if (csp->flags & CSP_FLAG_NO_FILTERING)
1512 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1514 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1515 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1519 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1520 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1523 if (filters_available(csp) == FALSE)
1525 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1526 "header filtering enabled, but no matching filters available.");
1530 for (i = 0; i < MAX_AF_FILES; i++)
1533 if ((NULL == fl) || (NULL == fl->f))
1536 * Either there are no filter files
1537 * left, or this filter file just
1538 * contains no valid filters.
1540 * Continue to be sure we don't miss
1541 * valid filter files that are chained
1542 * after empty or invalid ones.
1547 * For all applying +filter actions, look if a filter by that
1548 * name exists and if yes, execute its pcrs_joblist on the
1551 for (b = fl->f; b; b = b->next)
1553 if (b->type != wanted_filter_type)
1555 /* Skip other filter types */
1559 for (filtername = csp->action->multi[multi_action_index]->first;
1560 filtername ; filtername = filtername->next)
1562 if (strcmp(b->name, filtername->str) == 0)
1564 int current_hits = 0;
1565 pcrs_job *joblist = b->joblist;
1567 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1569 if (NULL == joblist)
1571 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1575 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1576 *header, size, b->name);
1578 /* Apply all jobs from the joblist */
1579 for (job = joblist; NULL != job; job = job->next)
1581 matches = pcrs_execute(job, *header, size, &newheader, &size);
1584 current_hits += matches;
1585 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1587 *header = newheader;
1589 else if (0 == matches)
1591 /* Filter doesn't change header */
1597 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1598 *header, b->name, pcrs_strerror(matches));
1599 if (newheader != NULL)
1601 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1607 if (b->dynamic) pcrs_free_joblist(joblist);
1609 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1610 hits += current_hits;
1617 * Additionally checking for hits is important because if
1618 * the continue hack is triggered, server headers can
1619 * arrive empty to separate multiple heads from each other.
1621 if ((0 == size) && hits)
1623 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1631 /*********************************************************************
1633 * Function : server_connection
1635 * Description : Makes sure a proper "Connection:" header is
1636 * set and signals connection_header_adder to
1640 * 1 : csp = Current client state (buffers, headers, etc...)
1641 * 2 : header = On input, pointer to header to modify.
1642 * On output, pointer to the modified header, or NULL
1643 * to remove the header. This function frees the
1644 * original string if necessary.
1646 * Returns : JB_ERR_OK on success.
1648 *********************************************************************/
1649 static jb_err server_connection(struct client_state *csp, char **header)
1651 if (!strcmpic(*header, "Connection: keep-alive")
1652 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1653 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1657 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1658 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1660 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1663 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1665 log_error(LOG_LEVEL_HEADER,
1666 "Keeping the server header '%s' around.", *header);
1669 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1671 char *old_header = *header;
1673 *header = strdup_or_die("Connection: close");
1674 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1679 /* Signal server_connection_adder() to return early. */
1680 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1686 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1687 /*********************************************************************
1689 * Function : server_keep_alive
1691 * Description : Stores the server's keep alive timeout.
1694 * 1 : csp = Current client state (buffers, headers, etc...)
1695 * 2 : header = On input, pointer to header to modify.
1696 * On output, pointer to the modified header, or NULL
1697 * to remove the header. This function frees the
1698 * original string if necessary.
1700 * Returns : JB_ERR_OK.
1702 *********************************************************************/
1703 static jb_err server_keep_alive(struct client_state *csp, char **header)
1705 unsigned int keep_alive_timeout;
1706 const char *timeout_position = strstr(*header, "timeout=");
1708 if ((NULL == timeout_position)
1709 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1711 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1715 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1717 log_error(LOG_LEVEL_HEADER,
1718 "Reducing keep-alive timeout from %u to %u.",
1719 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1720 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1724 /* XXX: Is this log worthy? */
1725 log_error(LOG_LEVEL_HEADER,
1726 "Server keep-alive timeout is %u. Sticking with %u.",
1727 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1729 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1736 /*********************************************************************
1738 * Function : server_proxy_connection
1740 * Description : Figures out whether or not we should add a
1741 * Proxy-Connection header.
1744 * 1 : csp = Current client state (buffers, headers, etc...)
1745 * 2 : header = On input, pointer to header to modify.
1746 * On output, pointer to the modified header, or NULL
1747 * to remove the header. This function frees the
1748 * original string if necessary.
1750 * Returns : JB_ERR_OK.
1752 *********************************************************************/
1753 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1755 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1760 /*********************************************************************
1762 * Function : client_keep_alive
1764 * Description : Stores the client's keep alive timeout.
1767 * 1 : csp = Current client state (buffers, headers, etc...)
1768 * 2 : header = On input, pointer to header to modify.
1769 * On output, pointer to the modified header, or NULL
1770 * to remove the header. This function frees the
1771 * original string if necessary.
1773 * Returns : JB_ERR_OK.
1775 *********************************************************************/
1776 static jb_err client_keep_alive(struct client_state *csp, char **header)
1778 unsigned int keep_alive_timeout;
1779 const char *timeout_position = strstr(*header, ": ");
1781 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1783 log_error(LOG_LEVEL_HEADER,
1784 "keep-alive support is disabled. Crunching: %s.", *header);
1789 if ((NULL == timeout_position)
1790 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1792 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1796 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1798 log_error(LOG_LEVEL_HEADER,
1799 "Reducing keep-alive timeout from %u to %u.",
1800 csp->config->keep_alive_timeout, keep_alive_timeout);
1801 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1805 /* XXX: Is this log worthy? */
1806 log_error(LOG_LEVEL_HEADER,
1807 "Client keep-alive timeout is %u. Sticking with %u.",
1808 keep_alive_timeout, csp->config->keep_alive_timeout);
1816 /*********************************************************************
1818 * Function : get_content_length
1820 * Description : Gets the content length specified in a
1821 * Content-Length header.
1824 * 1 : header_value = The Content-Length header value.
1825 * 2 : length = Storage to return the value.
1827 * Returns : JB_ERR_OK on success, or
1828 * JB_ERR_PARSE if no value is recognized.
1830 *********************************************************************/
1831 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1834 assert(sizeof(unsigned long long) > 4);
1835 if (1 != sscanf(header_value, "%I64u", length))
1837 if (1 != sscanf(header_value, "%llu", length))
1840 return JB_ERR_PARSE;
1847 /*********************************************************************
1849 * Function : client_save_content_length
1851 * Description : Save the Content-Length sent by the client.
1854 * 1 : csp = Current client state (buffers, headers, etc...)
1855 * 2 : header = On input, pointer to header to modify.
1856 * On output, pointer to the modified header, or NULL
1857 * to remove the header. This function frees the
1858 * original string if necessary.
1860 * Returns : JB_ERR_OK on success, or
1861 * JB_ERR_MEMORY on out-of-memory error.
1863 *********************************************************************/
1864 static jb_err client_save_content_length(struct client_state *csp, char **header)
1866 unsigned long long content_length = 0;
1867 const char *header_value;
1869 assert(*(*header+14) == ':');
1871 header_value = *header + 15;
1872 if (JB_ERR_OK != get_content_length(header_value, &content_length))
1874 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1879 csp->expected_client_content_length = content_length;
1884 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1888 /*********************************************************************
1890 * Function : client_connection
1892 * Description : Makes sure a proper "Connection:" header is
1893 * set and signals connection_header_adder
1897 * 1 : csp = Current client state (buffers, headers, etc...)
1898 * 2 : header = On input, pointer to header to modify.
1899 * On output, pointer to the modified header, or NULL
1900 * to remove the header. This function frees the
1901 * original string if necessary.
1903 * Returns : JB_ERR_OK on success.
1905 *********************************************************************/
1906 static jb_err client_connection(struct client_state *csp, char **header)
1908 static const char connection_close[] = "Connection: close";
1910 if (!strcmpic(*header, connection_close))
1912 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1913 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1914 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1916 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1918 log_error(LOG_LEVEL_HEADER,
1919 "Removing \'%s\' to imply keep-alive.", *header);
1922 * While we imply keep-alive to the server,
1923 * we have to remember that the client didn't.
1925 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1929 char *old_header = *header;
1931 *header = strdup_or_die("Connection: keep-alive");
1932 log_error(LOG_LEVEL_HEADER,
1933 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1939 log_error(LOG_LEVEL_HEADER,
1940 "Keeping the client header '%s' around. "
1941 "The connection will not be kept alive.",
1943 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1946 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1947 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1949 log_error(LOG_LEVEL_HEADER,
1950 "Keeping the client header '%s' around. "
1951 "The server connection will be kept alive if possible.",
1953 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1954 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1958 char *old_header = *header;
1960 *header = strdup_or_die(connection_close);
1961 log_error(LOG_LEVEL_HEADER,
1962 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1966 /* Signal client_connection_header_adder() to return early. */
1967 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1973 /*********************************************************************
1975 * Function : crumble
1977 * Description : This is called if a header matches a pattern to "crunch"
1980 * 1 : csp = Current client state (buffers, headers, etc...)
1981 * 2 : header = On input, pointer to header to modify.
1982 * On output, pointer to the modified header, or NULL
1983 * to remove the header. This function frees the
1984 * original string if necessary.
1986 * Returns : JB_ERR_OK on success, or
1987 * JB_ERR_MEMORY on out-of-memory error.
1989 *********************************************************************/
1990 static jb_err crumble(struct client_state *csp, char **header)
1993 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1999 /*********************************************************************
2001 * Function : crunch_server_header
2003 * Description : Crunch server header if it matches a string supplied by the
2004 * user. Called from `sed'.
2007 * 1 : csp = Current client state (buffers, headers, etc...)
2008 * 2 : header = On input, pointer to header to modify.
2009 * On output, pointer to the modified header, or NULL
2010 * to remove the header. This function frees the
2011 * original string if necessary.
2013 * Returns : JB_ERR_OK on success and always succeeds
2015 *********************************************************************/
2016 static jb_err crunch_server_header(struct client_state *csp, char **header)
2018 const char *crunch_pattern;
2020 /* Do we feel like crunching? */
2021 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2023 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2025 /* Is the current header the lucky one? */
2026 if (strstr(*header, crunch_pattern))
2028 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2037 /*********************************************************************
2039 * Function : server_content_type
2041 * Description : Set the content-type for filterable types (text/.*,
2042 * .*xml.*, .*script.* and image/gif) unless filtering has been
2043 * forbidden (CT_TABOO) while parsing earlier headers.
2044 * NOTE: Since text/plain is commonly used by web servers
2045 * for files whose correct type is unknown, we don't
2046 * set CT_TEXT for it.
2049 * 1 : csp = Current client state (buffers, headers, etc...)
2050 * 2 : header = On input, pointer to header to modify.
2051 * On output, pointer to the modified header, or NULL
2052 * to remove the header. This function frees the
2053 * original string if necessary.
2055 * Returns : JB_ERR_OK on success, or
2056 * JB_ERR_MEMORY on out-of-memory error.
2058 *********************************************************************/
2059 static jb_err server_content_type(struct client_state *csp, char **header)
2061 /* Remove header if it isn't the first Content-Type header */
2062 if ((csp->content_type & CT_DECLARED))
2065 * Another, slightly slower, way to see if
2066 * we already parsed another Content-Type header.
2068 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2070 log_error(LOG_LEVEL_ERROR,
2071 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2079 * Signal that the Content-Type has been set.
2081 csp->content_type |= CT_DECLARED;
2083 if (!(csp->content_type & CT_TABOO))
2086 * XXX: The assumption that text/plain is a sign of
2087 * binary data seems to be somewhat unreasonable nowadays
2088 * and should be dropped after 3.0.8 is out.
2090 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2091 || strstr(*header, "xml")
2092 || strstr(*header, "script"))
2094 csp->content_type |= CT_TEXT;
2096 else if (strstr(*header, "image/gif"))
2098 csp->content_type |= CT_GIF;
2103 * Are we messing with the content type?
2105 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2108 * Make sure the user doesn't accidentally
2109 * change the content type of binary documents.
2111 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2114 *header = strdup_or_die("Content-Type: ");
2115 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2119 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2120 return JB_ERR_MEMORY;
2122 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2126 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2127 "It doesn't look like a content type that should be filtered. "
2128 "Enable force-text-mode if you know what you're doing.", *header);
2136 /*********************************************************************
2138 * Function : server_transfer_coding
2140 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2141 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2142 * - Remove header if body was chunked but has been
2143 * de-chunked for filtering.
2146 * 1 : csp = Current client state (buffers, headers, etc...)
2147 * 2 : header = On input, pointer to header to modify.
2148 * On output, pointer to the modified header, or NULL
2149 * to remove the header. This function frees the
2150 * original string if necessary.
2152 * Returns : JB_ERR_OK on success, or
2153 * JB_ERR_MEMORY on out-of-memory error.
2155 *********************************************************************/
2156 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2159 * Turn off pcrs and gif filtering if body compressed
2161 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2165 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2167 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2168 csp->http->cmd, *header);
2169 #endif /* def FEATURE_ZLIB */
2170 csp->content_type = CT_TABOO;
2174 * Raise flag if body chunked
2176 if (strstr(*header, "chunked"))
2178 csp->flags |= CSP_FLAG_CHUNKED;
2181 * If the body was modified, it has been de-chunked first
2182 * and the header must be removed.
2184 * FIXME: If there is more than one transfer encoding,
2185 * only the "chunked" part should be removed here.
2187 if (csp->flags & CSP_FLAG_MODIFIED)
2189 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2198 /*********************************************************************
2200 * Function : server_content_encoding
2202 * Description : Used to check if the content is compressed, and if
2203 * FEATURE_ZLIB is disabled, filtering is disabled as
2206 * If FEATURE_ZLIB is enabled and the compression type
2207 * supported, the content is marked for decompression.
2209 * XXX: Doesn't properly deal with multiple or with
2210 * unsupported but unknown encodings.
2211 * Is case-sensitive but shouldn't be.
2214 * 1 : csp = Current client state (buffers, headers, etc...)
2215 * 2 : header = On input, pointer to header to modify.
2216 * On output, pointer to the modified header, or NULL
2217 * to remove the header. This function frees the
2218 * original string if necessary.
2220 * Returns : JB_ERR_OK on success, or
2221 * JB_ERR_MEMORY on out-of-memory error.
2223 *********************************************************************/
2224 static jb_err server_content_encoding(struct client_state *csp, char **header)
2227 if (strstr(*header, "sdch"))
2230 * Shared Dictionary Compression over HTTP isn't supported,
2231 * filtering it anyway is pretty much guaranteed to mess up
2234 csp->content_type |= CT_TABOO;
2237 * Log a warning if the user expects the content to be filtered.
2239 if ((csp->rlist != NULL) &&
2240 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2242 log_error(LOG_LEVEL_INFO,
2243 "SDCH-compressed content detected, content filtering disabled. "
2244 "Consider suppressing SDCH offers made by the client.");
2247 else if (strstr(*header, "gzip"))
2249 /* Mark for gzip decompression */
2250 csp->content_type |= CT_GZIP;
2252 else if (strstr(*header, "deflate"))
2254 /* Mark for zlib decompression */
2255 csp->content_type |= CT_DEFLATE;
2257 else if (strstr(*header, "compress"))
2260 * We can't decompress this; therefore we can't filter
2263 csp->content_type |= CT_TABOO;
2265 #else /* !defined(FEATURE_ZLIB) */
2267 * XXX: Using a black list here isn't the right approach.
2269 * In case of SDCH, building with zlib support isn't
2272 if (strstr(*header, "gzip") ||
2273 strstr(*header, "compress") ||
2274 strstr(*header, "deflate") ||
2275 strstr(*header, "sdch"))
2278 * Body is compressed, turn off pcrs and gif filtering.
2280 csp->content_type |= CT_TABOO;
2283 * Log a warning if the user expects the content to be filtered.
2285 if ((csp->rlist != NULL) &&
2286 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2288 log_error(LOG_LEVEL_INFO,
2289 "Compressed content detected, content filtering disabled. "
2290 "Consider recompiling Privoxy with zlib support or "
2291 "enable the prevent-compression action.");
2294 #endif /* defined(FEATURE_ZLIB) */
2302 /*********************************************************************
2304 * Function : server_adjust_content_encoding
2306 * Description : Remove the Content-Encoding header if the
2307 * decompression was successful and the content
2311 * 1 : csp = Current client state (buffers, headers, etc...)
2312 * 2 : header = On input, pointer to header to modify.
2313 * On output, pointer to the modified header, or NULL
2314 * to remove the header. This function frees the
2315 * original string if necessary.
2317 * Returns : JB_ERR_OK on success, or
2318 * JB_ERR_MEMORY on out-of-memory error.
2320 *********************************************************************/
2321 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2323 if ((csp->flags & CSP_FLAG_MODIFIED)
2324 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2327 * We successfully decompressed the content,
2328 * and have to clean the header now, so the
2329 * client no longer expects compressed data.
2331 * XXX: There is a difference between cleaning
2332 * and removing it completely.
2334 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2341 #endif /* defined(FEATURE_ZLIB) */
2344 /*********************************************************************
2346 * Function : server_adjust_content_length
2348 * Description : Adjust Content-Length header if we modified
2352 * 1 : csp = Current client state (buffers, headers, etc...)
2353 * 2 : header = On input, pointer to header to modify.
2354 * On output, pointer to the modified header, or NULL
2355 * to remove the header. This function frees the
2356 * original string if necessary.
2358 * Returns : JB_ERR_OK on success, or
2359 * JB_ERR_MEMORY on out-of-memory error.
2361 *********************************************************************/
2362 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2364 /* Regenerate header if the content was modified. */
2365 if (csp->flags & CSP_FLAG_MODIFIED)
2367 const size_t header_length = 50;
2369 *header = malloc(header_length);
2370 if (*header == NULL)
2372 return JB_ERR_MEMORY;
2374 create_content_length_header(csp->content_length, *header, header_length);
2375 log_error(LOG_LEVEL_HEADER,
2376 "Adjusted Content-Length to %llu", csp->content_length);
2383 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2384 /*********************************************************************
2386 * Function : server_save_content_length
2388 * Description : Save the Content-Length sent by the server.
2391 * 1 : csp = Current client state (buffers, headers, etc...)
2392 * 2 : header = On input, pointer to header to modify.
2393 * On output, pointer to the modified header, or NULL
2394 * to remove the header. This function frees the
2395 * original string if necessary.
2397 * Returns : JB_ERR_OK on success, or
2398 * JB_ERR_MEMORY on out-of-memory error.
2400 *********************************************************************/
2401 static jb_err server_save_content_length(struct client_state *csp, char **header)
2403 unsigned long long content_length = 0;
2404 const char *header_value;
2406 assert(*(*header+14) == ':');
2408 header_value = *header + 15;
2409 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2411 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2416 csp->expected_content_length = content_length;
2417 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2418 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2423 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2426 /*********************************************************************
2428 * Function : server_content_md5
2430 * Description : Crumble any Content-MD5 headers if the document was
2431 * modified. FIXME: Should we re-compute instead?
2434 * 1 : csp = Current client state (buffers, headers, etc...)
2435 * 2 : header = On input, pointer to header to modify.
2436 * On output, pointer to the modified header, or NULL
2437 * to remove the header. This function frees the
2438 * original string if necessary.
2440 * Returns : JB_ERR_OK on success, or
2441 * JB_ERR_MEMORY on out-of-memory error.
2443 *********************************************************************/
2444 static jb_err server_content_md5(struct client_state *csp, char **header)
2446 if (csp->flags & CSP_FLAG_MODIFIED)
2448 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2456 /*********************************************************************
2458 * Function : server_content_disposition
2460 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2461 * Called from `sed'.
2464 * 1 : csp = Current client state (buffers, headers, etc...)
2465 * 2 : header = On input, pointer to header to modify.
2466 * On output, pointer to the modified header, or NULL
2467 * to remove the header. This function frees the
2468 * original string if necessary.
2470 * Returns : JB_ERR_OK on success, or
2471 * JB_ERR_MEMORY on out-of-memory error.
2473 *********************************************************************/
2474 static jb_err server_content_disposition(struct client_state *csp, char **header)
2479 * Are we messing with the Content-Disposition header?
2481 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2487 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2489 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2492 * Blocking content-disposition header
2494 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2501 * Replacing Content-Disposition header
2504 *header = strdup("Content-Disposition: ");
2505 string_append(header, newval);
2507 if (*header != NULL)
2509 log_error(LOG_LEVEL_HEADER,
2510 "Content-Disposition header crunched and replaced with: %s", *header);
2513 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2517 /*********************************************************************
2519 * Function : server_last_modified
2521 * Description : Changes Last-Modified header to the actual date
2522 * to help hide-if-modified-since.
2523 * Called from `sed'.
2526 * 1 : csp = Current client state (buffers, headers, etc...)
2527 * 2 : header = On input, pointer to header to modify.
2528 * On output, pointer to the modified header, or NULL
2529 * to remove the header. This function frees the
2530 * original string if necessary.
2532 * Returns : JB_ERR_OK on success, or
2533 * JB_ERR_MEMORY on out-of-memory error.
2535 *********************************************************************/
2536 static jb_err server_last_modified(struct client_state *csp, char **header)
2539 time_t last_modified;
2543 * Are we messing with the Last-Modified header?
2545 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2551 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2553 if (0 == strcmpic(newval, "block"))
2556 * Blocking Last-Modified header. Useless but why not.
2558 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2562 else if (0 == strcmpic(newval, "reset-to-request-time"))
2565 * Setting Last-Modified Header to now.
2568 get_http_time(0, buf, sizeof(buf));
2570 *header = strdup("Last-Modified: ");
2571 string_append(header, buf);
2573 if (*header == NULL)
2575 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2579 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2582 else if (0 == strcmpic(newval, "randomize"))
2584 const char *header_time = *header + sizeof("Last-Modified:");
2586 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2588 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2590 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2596 struct tm *timeptr = NULL;
2598 #ifdef HAVE_GMTIME_R
2602 rtime = (long int)difftime(now, last_modified);
2605 long int days, hours, minutes, seconds;
2606 const int negative_delta = (rtime < 0);
2611 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2613 rtime = pick_from_range(rtime);
2618 last_modified += rtime;
2619 #ifdef HAVE_GMTIME_R
2620 timeptr = gmtime_r(&last_modified, &gmt);
2621 #elif defined(MUTEX_LOCKS_AVAILABLE)
2622 privoxy_mutex_lock(&gmtime_mutex);
2623 timeptr = gmtime(&last_modified);
2624 privoxy_mutex_unlock(&gmtime_mutex);
2626 timeptr = gmtime(&last_modified);
2628 if ((NULL == timeptr) || !strftime(newheader,
2629 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2631 log_error(LOG_LEVEL_ERROR,
2632 "Randomizing '%s' failed. Crunching the header without replacement.",
2639 *header = strdup("Last-Modified: ");
2640 string_append(header, newheader);
2642 if (*header == NULL)
2644 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2645 return JB_ERR_MEMORY;
2648 days = rtime / (3600 * 24);
2649 hours = rtime / 3600 % 24;
2650 minutes = rtime / 60 % 60;
2651 seconds = rtime % 60;
2653 log_error(LOG_LEVEL_HEADER,
2654 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2655 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2656 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2660 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2669 /*********************************************************************
2671 * Function : client_accept_encoding
2673 * Description : Rewrite the client's Accept-Encoding header so that
2674 * if doesn't allow compression, if the action applies.
2675 * Note: For HTTP/1.0 the absence of the header is enough.
2678 * 1 : csp = Current client state (buffers, headers, etc...)
2679 * 2 : header = On input, pointer to header to modify.
2680 * On output, pointer to the modified header, or NULL
2681 * to remove the header. This function frees the
2682 * original string if necessary.
2684 * Returns : JB_ERR_OK on success, or
2685 * JB_ERR_MEMORY on out-of-memory error.
2687 *********************************************************************/
2688 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2690 #ifdef FEATURE_COMPRESSION
2691 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2692 && strstr(*header, "deflate"))
2694 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2697 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2699 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2707 /*********************************************************************
2709 * Function : client_te
2711 * Description : Rewrite the client's TE header so that
2712 * if doesn't allow compression, if the action applies.
2715 * 1 : csp = Current client state (buffers, headers, etc...)
2716 * 2 : header = On input, pointer to header to modify.
2717 * On output, pointer to the modified header, or NULL
2718 * to remove the header. This function frees the
2719 * original string if necessary.
2721 * Returns : JB_ERR_OK on success, or
2722 * JB_ERR_MEMORY on out-of-memory error.
2724 *********************************************************************/
2725 static jb_err client_te(struct client_state *csp, char **header)
2727 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2730 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2737 /*********************************************************************
2739 * Function : client_referrer
2741 * Description : Handle the "referer" config setting properly.
2742 * Called from `sed'.
2745 * 1 : csp = Current client state (buffers, headers, etc...)
2746 * 2 : header = On input, pointer to header to modify.
2747 * On output, pointer to the modified header, or NULL
2748 * to remove the header. This function frees the
2749 * original string if necessary.
2751 * Returns : JB_ERR_OK on success, or
2752 * JB_ERR_MEMORY on out-of-memory error.
2754 *********************************************************************/
2755 static jb_err client_referrer(struct client_state *csp, char **header)
2757 const char *parameter;
2758 /* booleans for parameters we have to check multiple times */
2759 int parameter_conditional_block;
2760 int parameter_conditional_forge;
2762 #ifdef FEATURE_FORCE_LOAD
2764 * Since the referrer can include the prefix even
2765 * if the request itself is non-forced, we must
2766 * clean it unconditionally.
2768 * XXX: strclean is too broad
2770 strclean(*header, FORCE_PREFIX);
2771 #endif /* def FEATURE_FORCE_LOAD */
2773 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2775 /* Nothing left to do */
2779 parameter = csp->action->string[ACTION_STRING_REFERER];
2780 assert(parameter != NULL);
2781 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2782 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2784 if (!parameter_conditional_block && !parameter_conditional_forge)
2787 * As conditional-block and conditional-forge are the only
2788 * parameters that rely on the original referrer, we can
2789 * remove it now for all the others.
2794 if (0 == strcmpic(parameter, "block"))
2796 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2799 else if (parameter_conditional_block || parameter_conditional_forge)
2801 return handle_conditional_hide_referrer_parameter(header,
2802 csp->http->hostport, parameter_conditional_block);
2804 else if (0 == strcmpic(parameter, "forge"))
2806 return create_forged_referrer(header, csp->http->hostport);
2810 /* interpret parameter as user-supplied referer to fake */
2811 return create_fake_referrer(header, parameter);
2816 /*********************************************************************
2818 * Function : client_accept_language
2820 * Description : Handle the "Accept-Language" config setting properly.
2821 * Called from `sed'.
2824 * 1 : csp = Current client state (buffers, headers, etc...)
2825 * 2 : header = On input, pointer to header to modify.
2826 * On output, pointer to the modified header, or NULL
2827 * to remove the header. This function frees the
2828 * original string if necessary.
2830 * Returns : JB_ERR_OK on success, or
2831 * JB_ERR_MEMORY on out-of-memory error.
2833 *********************************************************************/
2834 static jb_err client_accept_language(struct client_state *csp, char **header)
2839 * Are we messing with the Accept-Language?
2841 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2843 /*I don't think so*/
2847 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2849 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2852 * Blocking Accept-Language header
2854 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2861 * Replacing Accept-Language header
2864 *header = strdup("Accept-Language: ");
2865 string_append(header, newval);
2867 if (*header == NULL)
2869 log_error(LOG_LEVEL_ERROR,
2870 "Insufficient memory. Accept-Language header crunched without replacement.");
2874 log_error(LOG_LEVEL_HEADER,
2875 "Accept-Language header crunched and replaced with: %s", *header);
2878 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2882 /*********************************************************************
2884 * Function : crunch_client_header
2886 * Description : Crunch client header if it matches a string supplied by the
2887 * user. Called from `sed'.
2890 * 1 : csp = Current client state (buffers, headers, etc...)
2891 * 2 : header = On input, pointer to header to modify.
2892 * On output, pointer to the modified header, or NULL
2893 * to remove the header. This function frees the
2894 * original string if necessary.
2896 * Returns : JB_ERR_OK on success and always succeeds
2898 *********************************************************************/
2899 static jb_err crunch_client_header(struct client_state *csp, char **header)
2901 const char *crunch_pattern;
2903 /* Do we feel like crunching? */
2904 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2906 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2908 /* Is the current header the lucky one? */
2909 if (strstr(*header, crunch_pattern))
2911 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2919 /*********************************************************************
2921 * Function : client_uagent
2923 * Description : Handle the "user-agent" config setting properly
2924 * and remember its original value to enable browser
2925 * bug workarounds. Called from `sed'.
2928 * 1 : csp = Current client state (buffers, headers, etc...)
2929 * 2 : header = On input, pointer to header to modify.
2930 * On output, pointer to the modified header, or NULL
2931 * to remove the header. This function frees the
2932 * original string if necessary.
2934 * Returns : JB_ERR_OK on success, or
2935 * JB_ERR_MEMORY on out-of-memory error.
2937 *********************************************************************/
2938 static jb_err client_uagent(struct client_state *csp, char **header)
2942 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2947 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2954 *header = strdup("User-Agent: ");
2955 string_append(header, newval);
2957 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2959 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2963 /*********************************************************************
2965 * Function : client_ua
2967 * Description : Handle "ua-" headers properly. Called from `sed'.
2970 * 1 : csp = Current client state (buffers, headers, etc...)
2971 * 2 : header = On input, pointer to header to modify.
2972 * On output, pointer to the modified header, or NULL
2973 * to remove the header. This function frees the
2974 * original string if necessary.
2976 * Returns : JB_ERR_OK on success, or
2977 * JB_ERR_MEMORY on out-of-memory error.
2979 *********************************************************************/
2980 static jb_err client_ua(struct client_state *csp, char **header)
2982 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2984 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2992 /*********************************************************************
2994 * Function : client_from
2996 * Description : Handle the "from" config setting properly.
2997 * Called from `sed'.
3000 * 1 : csp = Current client state (buffers, headers, etc...)
3001 * 2 : header = On input, pointer to header to modify.
3002 * On output, pointer to the modified header, or NULL
3003 * to remove the header. This function frees the
3004 * original string if necessary.
3006 * Returns : JB_ERR_OK on success, or
3007 * JB_ERR_MEMORY on out-of-memory error.
3009 *********************************************************************/
3010 static jb_err client_from(struct client_state *csp, char **header)
3014 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3021 newval = csp->action->string[ACTION_STRING_FROM];
3024 * Are we blocking the e-mail address?
3026 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3028 log_error(LOG_LEVEL_HEADER, "crunched From!");
3032 log_error(LOG_LEVEL_HEADER, " modified");
3034 *header = strdup("From: ");
3035 string_append(header, newval);
3037 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3041 /*********************************************************************
3043 * Function : client_send_cookie
3045 * Description : Crunches the "cookie" header if necessary.
3046 * Called from `sed'.
3048 * XXX: Stupid name, doesn't send squat.
3051 * 1 : csp = Current client state (buffers, headers, etc...)
3052 * 2 : header = On input, pointer to header to modify.
3053 * On output, pointer to the modified header, or NULL
3054 * to remove the header. This function frees the
3055 * original string if necessary.
3057 * Returns : JB_ERR_OK on success, or
3058 * JB_ERR_MEMORY on out-of-memory error.
3060 *********************************************************************/
3061 static jb_err client_send_cookie(struct client_state *csp, char **header)
3063 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3065 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3073 /*********************************************************************
3075 * Function : client_x_forwarded
3077 * Description : Handle the "x-forwarded-for" config setting properly,
3078 * also used in the add_client_headers list. Called from `sed'.
3081 * 1 : csp = Current client state (buffers, headers, etc...)
3082 * 2 : header = On input, pointer to header to modify.
3083 * On output, pointer to the modified header, or NULL
3084 * to remove the header. This function frees the
3085 * original string if necessary.
3087 * Returns : JB_ERR_OK on success, or
3088 * JB_ERR_MEMORY on out-of-memory error.
3090 *********************************************************************/
3091 jb_err client_x_forwarded(struct client_state *csp, char **header)
3093 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3095 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3097 if (0 == strcmpic(parameter, "block"))
3100 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3102 else if (0 == strcmpic(parameter, "add"))
3104 string_append(header, ", ");
3105 string_append(header, csp->ip_addr_str);
3107 if (*header == NULL)
3109 return JB_ERR_MEMORY;
3111 log_error(LOG_LEVEL_HEADER,
3112 "Appended client IP address to %s", *header);
3113 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3117 log_error(LOG_LEVEL_FATAL,
3118 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3126 /*********************************************************************
3128 * Function : client_max_forwards
3130 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3131 * from the value of the Max-Forwards header field.
3134 * 1 : csp = Current client state (buffers, headers, etc...)
3135 * 2 : header = On input, pointer to header to modify.
3136 * On output, pointer to the modified header, or NULL
3137 * to remove the header. This function frees the
3138 * original string if necessary.
3140 * Returns : JB_ERR_OK on success, or
3141 * JB_ERR_MEMORY on out-of-memory error.
3143 *********************************************************************/
3144 static jb_err client_max_forwards(struct client_state *csp, char **header)
3148 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3149 (0 == strcmpic(csp->http->gpc, "options")))
3151 assert(*(*header+12) == ':');
3152 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3154 if (max_forwards > 0)
3156 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3157 log_error(LOG_LEVEL_HEADER,
3158 "Max-Forwards value for %s request reduced to %d.",
3159 csp->http->gpc, max_forwards);
3161 else if (max_forwards < 0)
3163 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3169 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3178 /*********************************************************************
3180 * Function : client_host
3182 * Description : If the request URI did not contain host and
3183 * port information, parse and evaluate the Host
3186 * Also, kill ill-formed HOST: headers as sent by
3187 * Apple's iTunes software when used with a proxy.
3190 * 1 : csp = Current client state (buffers, headers, etc...)
3191 * 2 : header = On input, pointer to header to modify.
3192 * On output, pointer to the modified header, or NULL
3193 * to remove the header. This function frees the
3194 * original string if necessary.
3196 * Returns : JB_ERR_OK on success, or
3197 * JB_ERR_MEMORY on out-of-memory error.
3199 *********************************************************************/
3200 static jb_err client_host(struct client_state *csp, char **header)
3205 * If the header field name is all upper-case, chances are that it's
3206 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3207 * not a problem -- they are regenerated later.
3209 if ((*header)[1] == 'O')
3211 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3216 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3217 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3220 p = strdup_or_die((*header)+6);
3222 q = strdup_or_die(p);
3224 freez(csp->http->hostport);
3225 csp->http->hostport = p;
3226 freez(csp->http->host);
3227 csp->http->host = q;
3228 q = strchr(csp->http->host, ':');
3231 /* Terminate hostname and evaluate port string */
3233 csp->http->port = atoi(q);
3237 csp->http->port = csp->http->ssl ? 443 : 80;
3240 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3241 csp->http->hostport, csp->http->host, csp->http->port);
3244 /* Signal client_host_adder() to return right away */
3245 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3251 /*********************************************************************
3253 * Function : client_if_modified_since
3255 * Description : Remove or modify the If-Modified-Since header.
3258 * 1 : csp = Current client state (buffers, headers, etc...)
3259 * 2 : header = On input, pointer to header to modify.
3260 * On output, pointer to the modified header, or NULL
3261 * to remove the header. This function frees the
3262 * original string if necessary.
3264 * Returns : JB_ERR_OK on success, or
3265 * JB_ERR_MEMORY on out-of-memory error.
3267 *********************************************************************/
3268 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3271 #ifdef HAVE_GMTIME_R
3274 struct tm *timeptr = NULL;
3279 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3282 * The client got an error message because of a temporary problem,
3283 * the problem is gone and the client now tries to revalidate our
3284 * error message on the real server. The revalidation would always
3285 * end with the transmission of the whole document and there is
3286 * no need to expose the bogus If-Modified-Since header.
3288 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3291 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3293 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3295 if ((0 == strcmpic(newval, "block")))
3297 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3300 else /* add random value */
3302 const char *header_time = *header + sizeof("If-Modified-Since:");
3304 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3306 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3311 long int hours, minutes, seconds;
3312 long int rtime = strtol(newval, &endptr, 0);
3313 const int negative_range = (rtime < 0);
3317 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3318 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3324 rtime = pick_from_range(rtime);
3328 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3331 tm += rtime * (negative_range ? -1 : 1);
3332 #ifdef HAVE_GMTIME_R
3333 timeptr = gmtime_r(&tm, &gmt);
3334 #elif defined(MUTEX_LOCKS_AVAILABLE)
3335 privoxy_mutex_lock(&gmtime_mutex);
3336 timeptr = gmtime(&tm);
3337 privoxy_mutex_unlock(&gmtime_mutex);
3339 timeptr = gmtime(&tm);
3341 if ((NULL == timeptr) || !strftime(newheader,
3342 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3344 log_error(LOG_LEVEL_ERROR,
3345 "Randomizing '%s' failed. Crunching the header without replacement.",
3352 *header = strdup("If-Modified-Since: ");
3353 string_append(header, newheader);
3355 if (*header == NULL)
3357 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3358 return JB_ERR_MEMORY;
3361 hours = rtime / 3600;
3362 minutes = rtime / 60 % 60;
3363 seconds = rtime % 60;
3365 log_error(LOG_LEVEL_HEADER,
3366 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3367 *header, (negative_range) ? "subtracted" : "added", hours,
3368 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3369 seconds, (seconds == 1) ? ")" : "s)");
3378 /*********************************************************************
3380 * Function : client_if_none_match
3382 * Description : Remove the If-None-Match header.
3385 * 1 : csp = Current client state (buffers, headers, etc...)
3386 * 2 : header = On input, pointer to header to modify.
3387 * On output, pointer to the modified header, or NULL
3388 * to remove the header. This function frees the
3389 * original string if necessary.
3391 * Returns : JB_ERR_OK on success, or
3392 * JB_ERR_MEMORY on out-of-memory error.
3394 *********************************************************************/
3395 static jb_err client_if_none_match(struct client_state *csp, char **header)
3397 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3399 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3407 /*********************************************************************
3409 * Function : client_x_filter
3411 * Description : Disables filtering if the client set "X-Filter: No".
3412 * Called from `sed'.
3415 * 1 : csp = Current client state (buffers, headers, etc...)
3416 * 2 : header = On input, pointer to header to modify.
3417 * On output, pointer to the modified header, or NULL
3418 * to remove the header. This function frees the
3419 * original string if necessary.
3421 * Returns : JB_ERR_OK on success
3423 *********************************************************************/
3424 jb_err client_x_filter(struct client_state *csp, char **header)
3426 if (0 == strcmpic(*header, "X-Filter: No"))
3428 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3430 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3434 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3436 log_error(LOG_LEVEL_HEADER,
3437 "force-text-mode overruled the client's request to fetch without filtering!");
3441 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3442 csp->flags |= CSP_FLAG_NO_FILTERING;
3443 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3445 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3453 /*********************************************************************
3455 * Function : client_range
3457 * Description : Removes Range, Request-Range and If-Range headers if
3458 * content filtering is enabled and the range doesn't
3461 * If the client's version of the document has been
3462 * altered by Privoxy, the server could interpret the
3463 * range differently than the client intended in which
3464 * case the user could end up with corrupted content.
3466 * If the range starts at byte 0 this isn't an issue
3467 * so the header can pass. Partial requests like this
3468 * are used to render preview images for videos without
3469 * downloading the whole video.
3471 * While HTTP doesn't require that range requests are
3472 * honoured and the client could simply abort the download
3473 * after receiving a sufficient amount of data, various
3474 * clients don't handle complete responses to range
3475 * requests gracefully and emit misleading error messages
3479 * 1 : csp = Current client state (buffers, headers, etc...)
3480 * 2 : header = On input, pointer to header to modify.
3481 * On output, pointer to the modified header, or NULL
3482 * to remove the header. This function frees the
3483 * original string if necessary.
3485 * Returns : JB_ERR_OK
3487 *********************************************************************/
3488 static jb_err client_range(struct client_state *csp, char **header)
3490 if (content_filters_enabled(csp->action)
3491 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3493 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3494 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3501 /* the following functions add headers directly to the header list */
3503 /*********************************************************************
3505 * Function : client_host_adder
3507 * Description : Adds the Host: header field if it is missing.
3508 * Called from `sed'.
3511 * 1 : csp = Current client state (buffers, headers, etc...)
3513 * Returns : JB_ERR_OK on success, or
3514 * JB_ERR_MEMORY on out-of-memory error.
3516 *********************************************************************/
3517 static jb_err client_host_adder(struct client_state *csp)
3522 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3524 /* Header already set by the client, nothing to do. */
3528 if (!csp->http->hostport || !*(csp->http->hostport))
3530 /* XXX: When does this happen and why is it OK? */
3531 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3536 * remove 'user:pass@' from 'proto://user:pass@host'
3538 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3544 p = csp->http->hostport;
3547 /* XXX: Just add it, we already made sure that it will be unique */
3548 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3549 err = enlist_unique_header(csp->headers, "Host", p);
3555 /*********************************************************************
3557 * Function : client_xtra_adder
3559 * Description : Used in the add_client_headers list. Called from `sed'.
3562 * 1 : csp = Current client state (buffers, headers, etc...)
3564 * Returns : JB_ERR_OK on success, or
3565 * JB_ERR_MEMORY on out-of-memory error.
3567 *********************************************************************/
3568 static jb_err client_xtra_adder(struct client_state *csp)
3570 struct list_entry *lst;
3573 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3574 lst ; lst = lst->next)
3576 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3577 err = enlist(csp->headers, lst->str);
3589 /*********************************************************************
3591 * Function : client_x_forwarded_for_adder
3593 * Description : Used in the add_client_headers list. Called from `sed'.
3596 * 1 : csp = Current client state (buffers, headers, etc...)
3598 * Returns : JB_ERR_OK on success, or
3599 * JB_ERR_MEMORY on out-of-memory error.
3601 *********************************************************************/
3602 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3604 char *header = NULL;
3607 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3608 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3609 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3612 * If we aren't adding X-Forwarded-For headers,
3613 * or we already appended an existing X-Forwarded-For
3614 * header, there's nothing left to do here.
3619 header = strdup("X-Forwarded-For: ");
3620 string_append(&header, csp->ip_addr_str);
3624 return JB_ERR_MEMORY;
3627 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3628 err = enlist(csp->headers, header);
3635 /*********************************************************************
3637 * Function : server_connection_adder
3639 * Description : Adds an appropriate "Connection:" header to csp->headers
3640 * unless the header was already present. Called from `sed'.
3643 * 1 : csp = Current client state (buffers, headers, etc...)
3645 * Returns : JB_ERR_OK on success, or
3646 * JB_ERR_MEMORY on out-of-memory error.
3648 *********************************************************************/
3649 static jb_err server_connection_adder(struct client_state *csp)
3651 const unsigned int flags = csp->flags;
3652 const char *response_status_line = csp->headers->first->str;
3653 static const char connection_close[] = "Connection: close";
3655 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3656 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3662 * XXX: if we downgraded the response, this check will fail.
3664 if ((csp->config->feature_flags &
3665 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3666 && (NULL != response_status_line)
3667 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3668 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3669 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3673 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3674 "without Connection header implies keep-alive.");
3675 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3679 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3681 return enlist(csp->headers, connection_close);
3685 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3686 /*********************************************************************
3688 * Function : server_proxy_connection_adder
3690 * Description : Adds a "Proxy-Connection: keep-alive" header to
3691 * csp->headers when appropriate.
3694 * 1 : csp = Current client state (buffers, headers, etc...)
3696 * Returns : JB_ERR_OK on success, or
3697 * JB_ERR_MEMORY on out-of-memory error.
3699 *********************************************************************/
3700 static jb_err server_proxy_connection_adder(struct client_state *csp)
3702 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3703 jb_err err = JB_ERR_OK;
3705 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3706 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3707 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET))
3709 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3710 err = enlist(csp->headers, proxy_connection_header);
3715 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3718 /*********************************************************************
3720 * Function : client_connection_header_adder
3722 * Description : Adds a proper "Connection:" header to csp->headers
3723 * unless the header was already present. Called from `sed'.
3726 * 1 : csp = Current client state (buffers, headers, etc...)
3728 * Returns : JB_ERR_OK on success, or
3729 * JB_ERR_MEMORY on out-of-memory error.
3731 *********************************************************************/
3732 static jb_err client_connection_header_adder(struct client_state *csp)
3734 static const char connection_close[] = "Connection: close";
3736 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3737 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3742 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3743 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3744 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3745 && (csp->http->ssl == 0)
3746 && !strcmpic(csp->http->ver, "HTTP/1.1"))
3748 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3751 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3753 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3755 return enlist(csp->headers, connection_close);
3759 /*********************************************************************
3761 * Function : server_http
3763 * Description : - Save the HTTP Status into csp->http->status
3764 * - Set CT_TABOO to prevent filtering if the answer
3765 * is a partial range (HTTP status 206)
3766 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3770 * 1 : csp = Current client state (buffers, headers, etc...)
3771 * 2 : header = On input, pointer to header to modify.
3772 * On output, pointer to the modified header, or NULL
3773 * to remove the header. This function frees the
3774 * original string if necessary.
3776 * Returns : JB_ERR_OK on success, or
3777 * JB_ERR_MEMORY on out-of-memory error.
3779 *********************************************************************/
3780 static jb_err server_http(struct client_state *csp, char **header)
3782 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3783 if (csp->http->status == 206)
3785 csp->content_type = CT_TABOO;
3788 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3790 /* XXX: Should we do a real validity check here? */
3791 if (strlen(*header) > 8)
3794 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3799 * XXX: Should we block the request or
3800 * enlist a valid status code line here?
3802 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3803 "Downgrading to HTTP/1.0 impossible.");
3811 /*********************************************************************
3813 * Function : server_set_cookie
3815 * Description : Handle the server "cookie" header properly.
3816 * Crunch, accept or rewrite it to a session cookie.
3817 * Called from `sed'.
3819 * TODO: Allow the user to specify a new expiration
3820 * time to cause the cookie to expire even before the
3821 * browser is closed.
3824 * 1 : csp = Current client state (buffers, headers, etc...)
3825 * 2 : header = On input, pointer to header to modify.
3826 * On output, pointer to the modified header, or NULL
3827 * to remove the header. This function frees the
3828 * original string if necessary.
3830 * Returns : JB_ERR_OK on success, or
3831 * JB_ERR_MEMORY on out-of-memory error.
3833 *********************************************************************/
3834 static jb_err server_set_cookie(struct client_state *csp, char **header)
3841 if ((csp->action->flags & ACTION_CRUNCH_INCOMING_COOKIES) != 0)
3843 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3846 else if ((csp->action->flags & ACTION_SESSION_COOKIES_ONLY) != 0)
3848 /* Flag whether or not to log a message */
3851 /* A variable to store the tag we're working on */
3854 /* Skip "Set-Cookie:" (11 characters) in header */
3855 cur_tag = *header + 11;
3857 /* skip whitespace between "Set-Cookie:" and value */
3858 while (*cur_tag && privoxy_isspace(*cur_tag))
3863 /* Loop through each tag in the cookie */
3867 char *next_tag = strchr(cur_tag, ';');
3868 if (next_tag != NULL)
3870 /* Skip the ';' character itself */
3873 /* skip whitespace ";" and start of tag */
3874 while (*next_tag && privoxy_isspace(*next_tag))
3881 /* "Next tag" is the end of the string */
3882 next_tag = cur_tag + strlen(cur_tag);
3886 * Check the expiration date to see
3887 * if the cookie is still valid, if yes,
3888 * rewrite it to a session cookie.
3890 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3892 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3894 if ((expiration_date[0] == '"')
3895 && (expiration_date[1] != '\0'))
3898 * Skip quotation mark. RFC 2109 10.1.2 seems to hint
3899 * that the expiration date isn't supposed to be quoted,
3900 * but some servers do it anyway.
3905 /* Did we detect the date properly? */
3906 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3909 * Nope, treat it as if it was still valid.
3911 * XXX: Should we remove the whole cookie instead?
3913 log_error(LOG_LEVEL_ERROR,
3914 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3915 string_move(cur_tag, next_tag);
3921 * Yes. Check if the cookie is still valid.
3923 * If the cookie is already expired it's probably
3924 * a delete cookie and even if it isn't, the browser
3925 * will discard it anyway.
3929 * XXX: timegm() isn't available on some AmigaOS
3930 * versions and our replacement doesn't work.
3932 * Our options are to either:
3934 * - disable session-cookies-only completely if timegm
3937 * - to simply remove all expired tags, like it has
3938 * been done until Privoxy 3.0.6 and to live with
3939 * the consequence that it can cause login/logout
3940 * problems on servers that don't validate their
3941 * input properly, or
3943 * - to replace it with mktime in which
3944 * case there is a slight chance of valid cookies
3945 * passing as already expired.
3947 * This is the way it's currently done and it's not
3948 * as bad as it sounds. If the missing GMT offset is
3949 * enough to change the result of the expiration check
3950 * the cookie will be only valid for a few hours
3951 * anyway, which in many cases will be shorter
3952 * than a browser session.
3954 if (cookie_time - now < 0)
3956 log_error(LOG_LEVEL_HEADER,
3957 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3958 /* Just in case some clown sets more then one expiration date */
3964 * Still valid, delete expiration date by copying
3965 * the rest of the string over it.
3967 string_move(cur_tag, next_tag);
3969 /* That changed the header, need to issue a log message */
3973 * Note that the next tag has now been moved to *cur_tag,
3974 * so we do not need to update the cur_tag pointer.
3982 /* Move on to next cookie tag */
3989 assert(NULL != *header);
3990 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3999 #ifdef FEATURE_FORCE_LOAD
4000 /*********************************************************************
4002 * Function : strclean
4004 * Description : In-Situ-Eliminate all occurrences of substring in
4008 * 1 : string = string to clean
4009 * 2 : substring = substring to eliminate
4011 * Returns : Number of eliminations
4013 *********************************************************************/
4014 int strclean(char *string, const char *substring)
4020 len = strlen(substring);
4022 while((pos = strstr(string, substring)) != NULL)
4029 while (*p++ != '\0');
4036 #endif /* def FEATURE_FORCE_LOAD */
4039 /*********************************************************************
4041 * Function : parse_header_time
4043 * Description : Parses time formats used in HTTP header strings
4044 * to get the numerical respresentation.
4047 * 1 : header_time = HTTP header time as string.
4048 * 2 : result = storage for header_time in seconds
4050 * Returns : JB_ERR_OK if the time format was recognized, or
4051 * JB_ERR_PARSE otherwise.
4053 *********************************************************************/
4054 static jb_err parse_header_time(const char *header_time, time_t *result)
4058 * Checking for two-digit years first in an
4059 * attempt to work around GNU libc's strptime()
4060 * reporting negative year values when using %Y.
4062 static const char * const time_formats[] = {
4063 /* Tue, 02-Jun-37 20:00:00 */
4064 "%a, %d-%b-%y %H:%M:%S",
4065 /* Tue, 02 Jun 2037 20:00:00 */
4066 "%a, %d %b %Y %H:%M:%S",
4067 /* Tue, 02-Jun-2037 20:00:00 */
4068 "%a, %d-%b-%Y %H:%M:%S",
4069 /* Tuesday, 02-Jun-2037 20:00:00 */
4070 "%A, %d-%b-%Y %H:%M:%S",
4071 /* Tuesday Jun 02 20:00:00 2037 */
4072 "%A %b %d %H:%M:%S %Y"
4076 for (i = 0; i < SZ(time_formats); i++)
4079 * Zero out gmt to prevent time zone offsets.
4080 * Documented to be required for GNU libc.
4082 memset(&gmt, 0, sizeof(gmt));
4084 if (NULL != strptime(header_time, time_formats[i], &gmt))
4086 /* Sanity check for GNU libc. */
4087 if (gmt.tm_year < 0)
4089 log_error(LOG_LEVEL_HEADER,
4090 "Failed to parse '%s' using '%s'. Moving on.",
4091 header_time, time_formats[i]);
4094 *result = timegm(&gmt);
4099 return JB_ERR_PARSE;
4104 /*********************************************************************
4106 * Function : get_destination_from_headers
4108 * Description : Parse the "Host:" header to get the request's destination.
4109 * Only needed if the client's request was forcefully
4110 * redirected into Privoxy.
4112 * Code mainly copied from client_host() which is currently
4113 * run too late for this purpose.
4116 * 1 : headers = List of headers (one of them hopefully being
4117 * the "Host:" header)
4118 * 2 : http = storage for the result (host, port and hostport).
4120 * Returns : JB_ERR_MEMORY (or terminates) in case of memory problems,
4121 * JB_ERR_PARSE if the host header couldn't be found,
4122 * JB_ERR_OK otherwise.
4124 *********************************************************************/
4125 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4131 host = get_header_value(headers, "Host:");
4135 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4136 return JB_ERR_PARSE;
4139 p = strdup_or_die(host);
4141 q = strdup_or_die(p);
4143 freez(http->hostport);
4147 q = strchr(http->host, ':');
4150 /* Terminate hostname and evaluate port string */
4152 http->port = atoi(q);
4156 http->port = http->ssl ? 443 : 80;
4159 /* Rebuild request URL */
4161 http->url = strdup(http->ssl ? "https://" : "http://");
4162 string_append(&http->url, http->hostport);
4163 string_append(&http->url, http->path);
4164 if (http->url == NULL)
4166 return JB_ERR_MEMORY;
4169 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4177 /*********************************************************************
4179 * Function : create_forged_referrer
4181 * Description : Helper for client_referrer to forge a referer as
4182 * 'http://hostname[:port]/' to fool stupid
4183 * checks for in-site links
4186 * 1 : header = Pointer to header pointer
4187 * 2 : hostport = Host and optionally port as string
4189 * Returns : JB_ERR_OK in case of success, or
4190 * JB_ERR_MEMORY in case of memory problems.
4192 *********************************************************************/
4193 static jb_err create_forged_referrer(char **header, const char *hostport)
4195 assert(NULL == *header);
4197 *header = strdup("Referer: http://");
4198 string_append(header, hostport);
4199 string_append(header, "/");
4201 if (NULL == *header)
4203 return JB_ERR_MEMORY;
4206 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4213 /*********************************************************************
4215 * Function : create_fake_referrer
4217 * Description : Helper for client_referrer to create a fake referrer
4218 * based on a string supplied by the user.
4221 * 1 : header = Pointer to header pointer
4222 * 2 : hosthost = Referrer to fake
4224 * Returns : JB_ERR_OK in case of success, or
4225 * JB_ERR_MEMORY in case of memory problems.
4227 *********************************************************************/
4228 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4230 assert(NULL == *header);
4232 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4234 log_error(LOG_LEVEL_HEADER,
4235 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4237 *header = strdup("Referer: ");
4238 string_append(header, fake_referrer);
4240 if (NULL == *header)
4242 return JB_ERR_MEMORY;
4245 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4252 /*********************************************************************
4254 * Function : handle_conditional_hide_referrer_parameter
4256 * Description : Helper for client_referrer to crunch or forge
4257 * the referrer header if the host has changed.
4260 * 1 : header = Pointer to header pointer
4261 * 2 : host = The target host (may include the port)
4262 * 3 : parameter_conditional_block = Boolean to signal
4263 * if we're in conditional-block mode. If not set,
4264 * we're in conditional-forge mode.
4266 * Returns : JB_ERR_OK in case of success, or
4267 * JB_ERR_MEMORY in case of memory problems.
4269 *********************************************************************/
4270 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4271 const char *host, const int parameter_conditional_block)
4273 char *referer = strdup_or_die(*header);
4274 const size_t hostlength = strlen(host);
4275 const char *referer_url = NULL;
4277 /* referer begins with 'Referer: http[s]://' */
4278 if ((hostlength+17) < strlen(referer))
4281 * Shorten referer to make sure the referer is blocked
4282 * if www.example.org/www.example.com-shall-see-the-referer/
4283 * links to www.example.com/
4285 referer[hostlength+17] = '\0';
4287 referer_url = strstr(referer, "http://");
4288 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
4290 /* Host has changed, Referer is invalid or a https URL. */
4291 if (parameter_conditional_block)
4293 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4300 return create_forged_referrer(header, host);
4310 /*********************************************************************
4312 * Function : create_content_length_header
4314 * Description : Creates a Content-Length header.
4317 * 1 : content_length = The content length to be used in the header.
4318 * 2 : header = Allocated space to safe the header.
4319 * 3 : buffer_length = The length of the allocated space.
4323 *********************************************************************/
4324 static void create_content_length_header(unsigned long long content_length,
4325 char *header, size_t buffer_length)
4327 snprintf(header, buffer_length, "Content-Length: %llu", content_length);
4331 /*********************************************************************
4333 * Function : get_expected_content_length
4335 * Description : Figures out the content length from a list of headers.
4338 * 1 : headers = List of headers
4340 * Returns : Number of bytes to expect
4342 *********************************************************************/
4343 unsigned long long get_expected_content_length(struct list *headers)
4345 const char *content_length_header;
4346 unsigned long long content_length = 0;
4348 content_length_header = get_header_value(headers, "Content-Length:");
4349 if (content_length_header != NULL)
4351 if (JB_ERR_OK != get_content_length(content_length_header, &content_length))
4353 log_error(LOG_LEVEL_ERROR,
4354 "Failed to get the Content-Length in %s", content_length_header);
4355 /* XXX: The header will be removed later on */
4360 return content_length;