1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
5 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Copyright : Written by and Copyright (C) 2001-2017 the
8 * Privoxy team. https://www.privoxy.org/
10 * Based on the Internet Junkbuster originally written
11 * by and Copyright (C) 1997 Anonymous Coders and
12 * Junkbusters Corporation. http://www.junkbusters.com
14 * This program is free software; you can redistribute it
15 * and/or modify it under the terms of the GNU General
16 * Public License as published by the Free Software
17 * Foundation; either version 2 of the License, or (at
18 * your option) any later version.
20 * This program is distributed in the hope that it will
21 * be useful, but WITHOUT ANY WARRANTY; without even the
22 * implied warranty of MERCHANTABILITY or FITNESS FOR A
23 * PARTICULAR PURPOSE. See the GNU General Public
24 * License for more details.
26 * The GNU General Public License should be included with
27 * this file. If not, you can view it at
28 * http://www.gnu.org/copyleft/gpl.html
29 * or write to the Free Software Foundation, Inc., 59
30 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 *********************************************************************/
39 #include <sys/types.h>
49 * Convince GNU's libc to provide a strptime prototype.
58 #define GZIP_IDENTIFIER_1 0x1f
59 #define GZIP_IDENTIFIER_2 0x8b
61 #define GZIP_FLAG_CHECKSUM 0x02
62 #define GZIP_FLAG_EXTRA_FIELDS 0x04
63 #define GZIP_FLAG_FILE_NAME 0x08
64 #define GZIP_FLAG_COMMENT 0x10
65 #define GZIP_FLAG_RESERVED_BITS 0xe0
68 #if !defined(_WIN32) && !defined(__OS2__)
74 #ifdef FEATURE_PTHREAD
76 /* jcc.h is for mutex semapores only */
77 #endif /* def FEATURE_PTHREAD */
82 #include "jbsockets.h"
92 static char *get_header_line(struct iob *iob);
93 static jb_err scan_headers(struct client_state *csp);
94 static jb_err header_tagger(struct client_state *csp, char *header);
95 static jb_err parse_header_time(const char *header_time, time_t *result);
96 static jb_err parse_time_header(const char *header, time_t *result);
98 static jb_err crumble (struct client_state *csp, char **header);
99 static jb_err filter_header (struct client_state *csp, char **header);
100 static jb_err client_connection (struct client_state *csp, char **header);
101 static jb_err client_referrer (struct client_state *csp, char **header);
102 static jb_err client_uagent (struct client_state *csp, char **header);
103 static jb_err client_ua (struct client_state *csp, char **header);
104 static jb_err client_from (struct client_state *csp, char **header);
105 static jb_err client_send_cookie (struct client_state *csp, char **header);
106 static jb_err client_x_forwarded (struct client_state *csp, char **header);
107 static jb_err client_accept_encoding (struct client_state *csp, char **header);
108 static jb_err client_te (struct client_state *csp, char **header);
109 static jb_err client_max_forwards (struct client_state *csp, char **header);
110 static jb_err client_host (struct client_state *csp, char **header);
111 static jb_err client_if_modified_since (struct client_state *csp, char **header);
112 static jb_err client_accept_language (struct client_state *csp, char **header);
113 static jb_err client_if_none_match (struct client_state *csp, char **header);
114 static jb_err crunch_client_header (struct client_state *csp, char **header);
115 static jb_err client_x_filter (struct client_state *csp, char **header);
116 static jb_err client_range (struct client_state *csp, char **header);
117 static jb_err client_expect (struct client_state *csp, char **header);
118 static jb_err server_set_cookie (struct client_state *csp, char **header);
119 static jb_err server_connection (struct client_state *csp, char **header);
120 static jb_err server_content_type (struct client_state *csp, char **header);
121 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
122 static jb_err server_content_md5 (struct client_state *csp, char **header);
123 static jb_err server_content_encoding (struct client_state *csp, char **header);
124 static jb_err server_transfer_coding (struct client_state *csp, char **header);
125 static jb_err server_http (struct client_state *csp, char **header);
126 static jb_err crunch_server_header (struct client_state *csp, char **header);
127 static jb_err server_last_modified (struct client_state *csp, char **header);
128 static jb_err server_content_disposition(struct client_state *csp, char **header);
130 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
133 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
134 static jb_err server_save_content_length(struct client_state *csp, char **header);
135 static jb_err server_keep_alive(struct client_state *csp, char **header);
136 static jb_err server_proxy_connection(struct client_state *csp, char **header);
137 static jb_err client_keep_alive(struct client_state *csp, char **header);
138 static jb_err client_save_content_length(struct client_state *csp, char **header);
139 static jb_err client_proxy_connection(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 */
150 static jb_err proxy_authentication(struct client_state *csp, char **header);
152 static jb_err create_forged_referrer(char **header, const char *hostport);
153 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
154 static jb_err handle_conditional_hide_referrer_parameter(char **header,
155 const char *host, const int parameter_conditional_block);
156 static void create_content_length_header(unsigned long long content_length,
157 char *header, size_t buffer_length);
160 * List of functions to run on a list of headers.
164 /** The header prefix to match */
167 /** The length of the prefix to match */
170 /** The function to apply to this line */
171 const parser_func_ptr parser;
174 static const struct parsers client_patterns[] = {
175 { "referer:", 8, client_referrer },
176 { "user-agent:", 11, client_uagent },
177 { "ua-", 3, client_ua },
178 { "from:", 5, client_from },
179 { "cookie:", 7, client_send_cookie },
180 { "x-forwarded-for:", 16, client_x_forwarded },
181 { "Accept-Encoding:", 16, client_accept_encoding },
182 { "TE:", 3, client_te },
183 { "Host:", 5, client_host },
184 { "if-modified-since:", 18, client_if_modified_since },
185 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
186 { "Keep-Alive:", 11, client_keep_alive },
187 { "Content-Length:", 15, client_save_content_length },
188 { "Proxy-Connection:", 17, client_proxy_connection },
190 { "Keep-Alive:", 11, crumble },
191 { "Proxy-Connection:", 17, crumble },
193 { "connection:", 11, client_connection },
194 { "max-forwards:", 13, client_max_forwards },
195 { "Accept-Language:", 16, client_accept_language },
196 { "if-none-match:", 14, client_if_none_match },
197 { "Range:", 6, client_range },
198 { "Request-Range:", 14, client_range },
199 { "If-Range:", 9, client_range },
200 { "X-Filter:", 9, client_x_filter },
201 { "Proxy-Authorization:", 20, proxy_authentication },
203 { "Transfer-Encoding:", 18, client_transfer_encoding },
205 { "Expect:", 7, client_expect },
206 { "*", 0, crunch_client_header },
207 { "*", 0, filter_header },
211 static const struct parsers server_patterns[] = {
212 { "HTTP/", 5, server_http },
213 { "set-cookie:", 11, server_set_cookie },
214 { "connection:", 11, server_connection },
215 { "Content-Type:", 13, server_content_type },
216 { "Content-MD5:", 12, server_content_md5 },
217 { "Content-Encoding:", 17, server_content_encoding },
218 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
219 { "Content-Length:", 15, server_save_content_length },
220 { "Keep-Alive:", 11, server_keep_alive },
221 { "Proxy-Connection:", 17, server_proxy_connection },
223 { "Keep-Alive:", 11, crumble },
224 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
225 { "Transfer-Encoding:", 18, server_transfer_coding },
226 { "content-disposition:", 20, server_content_disposition },
227 { "Last-Modified:", 14, server_last_modified },
228 { "Proxy-Authenticate:", 19, proxy_authentication },
229 { "*", 0, crunch_server_header },
230 { "*", 0, filter_header },
234 static const add_header_func_ptr add_client_headers[] = {
236 client_x_forwarded_for_adder,
238 client_connection_header_adder,
242 static const add_header_func_ptr add_server_headers[] = {
243 server_connection_adder,
244 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
245 server_proxy_connection_adder,
246 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
250 /*********************************************************************
252 * Function : flush_iob
254 * Description : Write any pending "buffered" content.
257 * 1 : fd = file descriptor of the socket to read
258 * 2 : iob = The I/O buffer to flush, usually csp->iob.
259 * 3 : delay = Number of milliseconds to delay the writes
261 * Returns : On success, the number of bytes written are returned (zero
262 * indicates nothing was written). On error, -1 is returned,
263 * and errno is set appropriately. If count is zero and the
264 * file descriptor refers to a regular file, 0 will be
265 * returned without causing any other effect. For a special
266 * file, the results are not portable.
268 *********************************************************************/
269 long flush_iob(jb_socket fd, struct iob *iob, unsigned int delay)
271 long len = iob->eod - iob->cur;
278 if (write_socket_delayed(fd, iob->cur, (size_t)len, delay))
282 iob->eod = iob->cur = iob->buf;
288 /*********************************************************************
290 * Function : add_to_iob
292 * Description : Add content to the buffer, expanding the
293 * buffer if necessary.
296 * 1 : iob = Destination buffer.
297 * 2 : buffer_limit = Limit to which the destination may grow
298 * 3 : src = holds the content to be added
299 * 4 : n = number of bytes to be added
301 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
302 * or buffer limit reached.
304 *********************************************************************/
305 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
307 size_t used, offset, need;
310 if (n <= 0) return JB_ERR_OK;
312 used = (size_t)(iob->eod - iob->buf);
313 offset = (size_t)(iob->cur - iob->buf);
314 need = used + (size_t)n + 1;
317 * If the buffer can't hold the new data, extend it first.
318 * Use the next power of two if possible, else use the actual need.
320 if (need > buffer_limit)
322 log_error(LOG_LEVEL_INFO,
323 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
325 return JB_ERR_MEMORY;
328 if (need > iob->size)
330 size_t want = iob->size ? iob->size : 512;
337 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
341 else if (NULL != (p = (char *)realloc(iob->buf, need)))
347 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
348 return JB_ERR_MEMORY;
351 /* Update the iob pointers */
352 iob->cur = p + offset;
357 /* copy the new data into the iob buffer */
358 memcpy(iob->eod, src, (size_t)n);
360 /* point to the end of the data */
363 /* null terminate == cheap insurance */
371 /*********************************************************************
373 * Function : clear_iob
375 * Description : Frees the memory allocated for an I/O buffer and
376 * resets the structure.
379 * 1 : iob = I/O buffer to clear.
381 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
382 * or buffer limit reached.
384 *********************************************************************/
385 void clear_iob(struct iob *iob)
388 memset(iob, '\0', sizeof(*iob));
393 /*********************************************************************
395 * Function : decompress_iob
397 * Description : Decompress buffered page, expanding the
398 * buffer as necessary. csp->iob->cur
399 * should point to the the beginning of the
400 * compressed data block.
403 * 1 : csp = Current client state (buffers, headers, etc...)
405 * Returns : JB_ERR_OK on success,
406 * JB_ERR_MEMORY if out-of-memory limit reached, and
407 * JB_ERR_COMPRESS if error decompressing buffer.
409 *********************************************************************/
410 jb_err decompress_iob(struct client_state *csp)
412 char *buf; /* new, uncompressed buffer */
413 char *cur; /* Current iob position (to keep the original
414 * iob->cur unmodified if we return early) */
415 size_t bufsize; /* allocated size of the new buffer */
416 size_t old_size; /* Content size before decompression */
417 size_t skip_size; /* Number of bytes at the beginning of the iob
418 that we should NOT decompress. */
419 int status; /* return status of the inflate() call */
420 z_stream zstr; /* used by calls to zlib */
423 assert(csp->iob->cur - csp->iob->buf >= 0);
424 assert(csp->iob->eod - csp->iob->cur >= 0);
426 assert(csp->iob->cur - csp->iob->buf > 0);
427 assert(csp->iob->eod - csp->iob->cur > 0);
430 bufsize = csp->iob->size;
431 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
432 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
436 if (bufsize < (size_t)10)
439 * This is to protect the parsing of gzipped data,
440 * but it should(?) be valid for deflated data also.
442 log_error(LOG_LEVEL_ERROR,
443 "Insufficient data to start decompression. Bytes in buffer: %d",
444 csp->iob->eod - csp->iob->cur);
445 return JB_ERR_COMPRESS;
448 if (csp->content_type & CT_GZIP)
451 * Our task is slightly complicated by the facts that data
452 * compressed by gzip does not include a zlib header, and
453 * that there is no easily accessible interface in zlib to
454 * handle a gzip header. We strip off the gzip header by
455 * hand, and later inform zlib not to expect a header.
459 * Strip off the gzip header. Please see RFC 1952 for more
460 * explanation of the appropriate fields.
462 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
463 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
464 || (*cur++ != Z_DEFLATED))
466 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
467 return JB_ERR_COMPRESS;
472 if (flags & GZIP_FLAG_RESERVED_BITS)
474 /* The gzip header has reserved bits set; bail out. */
475 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
476 return JB_ERR_COMPRESS;
480 * Skip mtime (4 bytes), extra flags (1 byte)
481 * and OS type (1 byte).
485 /* Skip extra fields if necessary. */
486 if (flags & GZIP_FLAG_EXTRA_FIELDS)
489 * Skip a given number of bytes, specified
490 * as a 16-bit little-endian value.
492 * XXX: this code is untested and should probably be removed.
496 skip_bytes += *cur++ << 8;
499 * The number of bytes to skip should be positive
500 * and we'd like to stay in the buffer.
502 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
504 log_error(LOG_LEVEL_ERROR,
505 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
507 return JB_ERR_COMPRESS;
509 log_error(LOG_LEVEL_INFO,
510 "Skipping %d bytes for gzip compression. Does this sound right?",
515 /* Skip the filename if necessary. */
516 if (flags & GZIP_FLAG_FILE_NAME)
518 /* A null-terminated string is supposed to follow. */
519 while (*cur++ && (cur < csp->iob->eod));
522 /* Skip the comment if necessary. */
523 if (flags & GZIP_FLAG_COMMENT)
525 /* A null-terminated string is supposed to follow. */
526 while (*cur++ && (cur < csp->iob->eod));
529 /* Skip the CRC if necessary. */
530 if (flags & GZIP_FLAG_CHECKSUM)
535 if (cur >= csp->iob->eod)
538 * If the current position pointer reached or passed
539 * the buffer end, we were obviously tricked to skip
542 log_error(LOG_LEVEL_ERROR,
543 "Malformed gzip header detected. Aborting decompression.");
544 return JB_ERR_COMPRESS;
548 else if (csp->content_type & CT_DEFLATE)
551 * In theory (that is, according to RFC 1950), deflate-compressed
552 * data should begin with a two-byte zlib header and have an
553 * adler32 checksum at the end. It seems that in practice only
554 * the raw compressed data is sent. Note that this means that
555 * we are not RFC 1950-compliant here, but the advantage is that
556 * this actually works. :)
558 * We add a dummy null byte to tell zlib where the data ends,
559 * and later inform it not to expect a header.
561 * Fortunately, add_to_iob() has thoughtfully null-terminated
562 * the buffer; we can just increment the end pointer to include
569 log_error(LOG_LEVEL_ERROR,
570 "Unable to determine compression format for decompression");
571 return JB_ERR_COMPRESS;
574 /* Set up the fields required by zlib. */
575 zstr.next_in = (Bytef *)cur;
576 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
577 zstr.zalloc = Z_NULL;
579 zstr.opaque = Z_NULL;
582 * Passing -MAX_WBITS to inflateInit2 tells the library
583 * that there is no zlib header.
585 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
587 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
588 return JB_ERR_COMPRESS;
592 * Next, we allocate new storage for the inflated data.
593 * We don't modify the existing iob yet, so in case there
594 * is error in decompression we can recover gracefully.
596 buf = zalloc(bufsize);
599 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
600 return JB_ERR_MEMORY;
603 assert(bufsize >= skip_size);
604 memcpy(buf, csp->iob->buf, skip_size);
605 zstr.avail_out = (uInt)(bufsize - skip_size);
606 zstr.next_out = (Bytef *)buf + skip_size;
608 /* Try to decompress the whole stream in one shot. */
609 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
611 /* We need to allocate more memory for the output buffer. */
613 char *tmpbuf; /* used for realloc'ing the buffer */
614 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
616 if (0 == zstr.avail_in)
619 * If zlib wants more data then there's a problem, because
620 * the complete compressed file should have been buffered.
622 log_error(LOG_LEVEL_ERROR,
623 "Unexpected end of compressed iob. Using what we got so far.");
628 * If we reached the buffer limit and still didn't have enough
629 * memory, just give up. Due to the ceiling enforced by the next
630 * if block we could actually check for equality here, but as it
631 * can be easily mistaken for a bug we don't.
633 if (bufsize >= csp->config->buffer_limit)
635 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
636 return JB_ERR_MEMORY;
639 /* Try doubling the buffer size each time. */
642 /* Don't exceed the buffer limit. */
643 if (bufsize > csp->config->buffer_limit)
645 bufsize = csp->config->buffer_limit;
648 /* Try to allocate the new buffer. */
649 tmpbuf = realloc(buf, bufsize);
652 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
654 return JB_ERR_MEMORY;
658 char *oldnext_out = (char *)zstr.next_out;
661 * Update the fields for inflate() to use the new
662 * buffer, which may be in a location different from
665 zstr.avail_out += (uInt)(bufsize - oldbufsize);
666 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
669 * Compare with an uglier method of calculating these values
670 * that doesn't require the extra oldbufsize variable.
672 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
673 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
679 if (Z_STREAM_ERROR == inflateEnd(&zstr))
681 log_error(LOG_LEVEL_ERROR,
682 "Inconsistent stream state after decompression: %s", zstr.msg);
684 * XXX: Intentionally no return.
686 * According to zlib.h, Z_STREAM_ERROR is returned
687 * "if the stream state was inconsistent".
689 * I assume in this case inflate()'s status
690 * would also be something different than Z_STREAM_END
691 * so this check should be redundant, but lets see.
695 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
698 * We failed to decompress the stream and it's
699 * not simply because of missing data.
701 log_error(LOG_LEVEL_ERROR,
702 "Unexpected error while decompressing to the buffer (iob): %s",
704 return JB_ERR_COMPRESS;
708 * Finally, we can actually update the iob, since the
709 * decompression was successful. First, free the old
712 freez(csp->iob->buf);
714 /* Now, update the iob to use the new buffer. */
716 csp->iob->cur = csp->iob->buf + skip_size;
717 csp->iob->eod = (char *)zstr.next_out;
718 csp->iob->size = bufsize;
721 * Make sure the new uncompressed iob obeys some minimal
722 * consistency conditions.
724 if ((csp->iob->buf <= csp->iob->cur)
725 && (csp->iob->cur <= csp->iob->eod)
726 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
728 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
729 if (new_size > (size_t)0)
731 log_error(LOG_LEVEL_RE_FILTER,
732 "Decompression successful. Old size: %d, new size: %d.",
737 /* zlib thinks this is OK, so lets do the same. */
738 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
743 /* It seems that zlib did something weird. */
744 log_error(LOG_LEVEL_ERROR,
745 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
746 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
747 csp->iob->eod, csp->iob->buf + csp->iob->size);
748 return JB_ERR_COMPRESS;
754 #endif /* defined(FEATURE_ZLIB) */
757 /*********************************************************************
759 * Function : normalize_lws
761 * Description : Reduces unquoted linear whitespace in headers to
762 * a single space in accordance with RFC 7230 3.2.4.
763 * This simplifies parsing and filtering later on.
766 * 1 : header = A header with linear whitespace to reduce.
770 *********************************************************************/
771 static void normalize_lws(char *header)
777 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
781 while (privoxy_isspace(*q))
785 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
791 log_error(LOG_LEVEL_HEADER,
792 "Converting tab to space in '%s'", header);
797 char *end_of_token = strstr(p+1, "\"");
799 if (NULL != end_of_token)
801 /* Don't mess with quoted text. */
806 log_error(LOG_LEVEL_HEADER,
807 "Ignoring single quote in '%s'", header);
813 p = strchr(header, ':');
814 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
817 * There's still space before the colon.
825 /*********************************************************************
827 * Function : get_header
829 * Description : This (odd) routine will parse the csp->iob
830 * to get the next complete header.
833 * 1 : iob = The I/O buffer to parse, usually csp->iob.
835 * Returns : Any one of the following:
837 * 1) a pointer to a dynamically allocated string that contains a header line
838 * 2) NULL indicating that the end of the header was reached
839 * 3) "" indicating that the end of the iob was reached before finding
840 * a complete header line.
842 *********************************************************************/
843 char *get_header(struct iob *iob)
847 header = get_header_line(iob);
849 if ((header == NULL) || (*header == '\0'))
852 * No complete header read yet, tell the client.
857 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
860 * Header spans multiple lines, append the next one.
862 char *continued_header;
864 continued_header = get_header_line(iob);
865 if ((continued_header == NULL) || (*continued_header == '\0'))
868 * No complete header read yet, return what we got.
869 * XXX: Should "unread" header instead.
871 log_error(LOG_LEVEL_INFO,
872 "Failed to read a multi-line header properly: '%s'",
877 if (JB_ERR_OK != string_join(&header, continued_header))
879 log_error(LOG_LEVEL_FATAL,
880 "Out of memory while appending multiple headers.");
884 /* XXX: remove before next stable release. */
885 log_error(LOG_LEVEL_HEADER,
886 "Merged multiple header lines to: '%s'",
891 normalize_lws(header);
898 /*********************************************************************
900 * Function : get_header_line
902 * Description : This (odd) routine will parse the csp->iob
903 * to get the next header line.
906 * 1 : iob = The I/O buffer to parse, usually csp->iob.
908 * Returns : Any one of the following:
910 * 1) a pointer to a dynamically allocated string that contains a header line
911 * 2) NULL indicating that the end of the header was reached
912 * 3) "" indicating that the end of the iob was reached before finding
913 * a complete header line.
915 *********************************************************************/
916 static char *get_header_line(struct iob *iob)
920 if ((iob->cur == NULL)
921 || ((p = strchr(iob->cur, '\n')) == NULL))
923 return(""); /* couldn't find a complete header */
928 ret = strdup(iob->cur);
931 /* FIXME No way to handle error properly */
932 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
938 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
940 /* is this a blank line (i.e. the end of the header) ? */
952 /*********************************************************************
954 * Function : get_header_value
956 * Description : Get the value of a given header from a chained list
957 * of header lines or return NULL if no such header is
958 * present in the list.
961 * 1 : header_list = pointer to list
962 * 2 : header_name = string with name of header to look for.
963 * Trailing colon required, capitalization
966 * Returns : NULL if not found, else value of header
968 *********************************************************************/
969 char *get_header_value(const struct list *header_list, const char *header_name)
971 struct list_entry *cur_entry;
977 length = strlen(header_name);
979 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
983 if (!strncmpic(cur_entry->str, header_name, length))
986 * Found: return pointer to start of value
988 ret = cur_entry->str + length;
989 while (*ret && privoxy_isspace(*ret)) ret++;
1003 /*********************************************************************
1005 * Function : scan_headers
1007 * Description : Scans headers, applies tags and updates action bits.
1010 * 1 : csp = Current client state (buffers, headers, etc...)
1012 * Returns : JB_ERR_OK
1014 *********************************************************************/
1015 static jb_err scan_headers(struct client_state *csp)
1017 struct list_entry *h; /* Header */
1018 jb_err err = JB_ERR_OK;
1020 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1022 /* Header crunch()ed in previous run? -> ignore */
1023 if (h->str == NULL) continue;
1024 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1025 err = header_tagger(csp, h->str);
1032 /*********************************************************************
1034 * Function : enforce_header_order
1036 * Description : Enforces a given header order.
1039 * 1 : headers = List of headers to order.
1040 * 2 : ordered_headers = List of ordered header names.
1044 *********************************************************************/
1045 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1047 struct list_entry *sorted_header;
1048 struct list new_headers[1];
1049 struct list_entry *header;
1051 init_list(new_headers);
1053 /* The request line is always the first "header" */
1055 assert(NULL != headers->first->str);
1056 enlist(new_headers, headers->first->str);
1057 freez(headers->first->str)
1059 /* Enlist the specified headers in the given order */
1061 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1062 sorted_header = sorted_header->next)
1064 const size_t sorted_header_length = strlen(sorted_header->str);
1065 for (header = headers->first; header != NULL; header = header->next)
1067 /* Header enlisted in previous run? -> ignore */
1068 if (header->str == NULL) continue;
1070 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1071 && (header->str[sorted_header_length] == ':'))
1073 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1074 if (JB_ERR_OK != enlist(new_headers, header->str))
1076 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1083 /* Enlist the rest of the headers behind the ordered ones */
1084 for (header = headers->first; header != NULL; header = header->next)
1086 /* Header enlisted in previous run? -> ignore */
1087 if (header->str == NULL) continue;
1089 log_error(LOG_LEVEL_HEADER,
1090 "Enlisting left-over 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);
1098 list_remove_all(headers);
1099 list_duplicate(headers, new_headers);
1100 list_remove_all(new_headers);
1106 /*********************************************************************
1110 * Description : add, delete or modify lines in the HTTP header streams.
1111 * On entry, it receives a linked list of headers space
1112 * that was allocated dynamically (both the list nodes
1113 * and the header contents).
1115 * As a side effect it frees the space used by the original
1119 * 1 : csp = Current client state (buffers, headers, etc...)
1120 * 2 : filter_server_headers = Boolean to switch between
1121 * server and header filtering.
1123 * Returns : JB_ERR_OK in case off success, or
1124 * JB_ERR_MEMORY on some out-of-memory errors, or
1125 * JB_ERR_PARSE in case of fatal parse errors.
1127 *********************************************************************/
1128 jb_err sed(struct client_state *csp, int filter_server_headers)
1130 /* XXX: use more descriptive names. */
1131 struct list_entry *p;
1132 const struct parsers *v;
1133 const add_header_func_ptr *f;
1134 jb_err err = JB_ERR_OK;
1138 if (filter_server_headers)
1140 v = server_patterns;
1141 f = add_server_headers;
1142 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1146 v = client_patterns;
1147 f = add_client_headers;
1148 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1151 while (v->str != NULL)
1153 for (p = csp->headers->first; p != NULL; p = p->next)
1155 /* Header crunch()ed in previous run? -> ignore */
1156 if (p->str == NULL) continue;
1158 /* Does the current parser handle this header? */
1159 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1160 (v->len == CHECK_EVERY_HEADER_REMAINING))
1162 err = v->parser(csp, &(p->str));
1163 if (err != JB_ERR_OK)
1172 /* place additional headers on the csp->headers list */
1173 while ((err == JB_ERR_OK) && (*f))
1179 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1181 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1188 #ifdef FEATURE_HTTPS_INSPECTION
1189 /*********************************************************************
1191 * Function : sed_https
1193 * Description : add, delete or modify lines in the HTTPS client
1194 * header streams. Wrapper around sed().
1197 * 1 : csp = Current client state (buffers, headers, etc...)
1199 * Returns : JB_ERR_OK in case off success, or
1200 * JB_ERR_MEMORY on some out-of-memory errors, or
1201 * JB_ERR_PARSE in case of fatal parse errors.
1203 *********************************************************************/
1204 jb_err sed_https(struct client_state *csp)
1207 struct list headers;
1210 * Temporarly replace csp->headers with csp->https_headers
1211 * to trick sed() into filtering the https headers.
1213 headers.first = csp->headers->first;
1214 headers.last = csp->headers->last;
1215 csp->headers->first = csp->https_headers->first;
1216 csp->headers->last = csp->https_headers->last;
1219 * We want client header filters and taggers
1220 * so temporarly remove the flag.
1222 csp->flags &= ~CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1223 err = sed(csp, FILTER_CLIENT_HEADERS);
1224 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1226 csp->headers->first = headers.first;
1227 csp->headers->last = headers.last;
1231 #endif /* def FEATURE_HTTPS_INSPECTION */
1234 /*********************************************************************
1236 * Function : update_server_headers
1238 * Description : Updates server headers after the body has been modified.
1241 * 1 : csp = Current client state (buffers, headers, etc...)
1243 * Returns : JB_ERR_OK in case off success, or
1244 * JB_ERR_MEMORY on out-of-memory error.
1246 *********************************************************************/
1247 jb_err update_server_headers(struct client_state *csp)
1249 jb_err err = JB_ERR_OK;
1251 static const struct parsers server_patterns_light[] = {
1252 { "Content-Length:", 15, server_adjust_content_length },
1253 { "Transfer-Encoding:", 18, server_transfer_coding },
1255 { "Content-Encoding:", 17, server_adjust_content_encoding },
1256 #endif /* def FEATURE_ZLIB */
1260 if (strncmpic(csp->http->cmd, "HEAD", 4))
1262 const struct parsers *v;
1263 struct list_entry *p;
1265 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1267 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1269 /* Header crunch()ed in previous run? -> ignore */
1270 if (p->str == NULL) continue;
1272 /* Does the current parser handle this header? */
1273 if (strncmpic(p->str, v->str, v->len) == 0)
1275 err = v->parser(csp, (char **)&(p->str));
1281 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1282 if ((JB_ERR_OK == err)
1283 && (csp->flags & CSP_FLAG_MODIFIED)
1284 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1285 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1289 create_content_length_header(csp->content_length, header, sizeof(header));
1290 err = enlist(csp->headers, header);
1291 if (JB_ERR_OK == err)
1293 log_error(LOG_LEVEL_HEADER,
1294 "Content modified with no Content-Length header set. "
1295 "Created: %s.", header);
1296 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1299 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1301 #ifdef FEATURE_COMPRESSION
1302 if ((JB_ERR_OK == err)
1303 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1305 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1306 if (JB_ERR_OK == err)
1308 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1317 /*********************************************************************
1319 * Function : header_tagger
1321 * Description : Executes all text substitutions from applying
1322 * tag actions and saves the result as tag.
1324 * XXX: Shares enough code with filter_header() and
1325 * pcrs_filter_response() to warrant some helper functions.
1328 * 1 : csp = Current client state (buffers, headers, etc...)
1329 * 2 : header = Header that is used as tagger input
1331 * Returns : JB_ERR_OK on success and always succeeds
1333 *********************************************************************/
1334 static jb_err header_tagger(struct client_state *csp, char *header)
1336 enum filter_type wanted_filter_type;
1337 int multi_action_index;
1340 struct re_filterfile_spec *b;
1341 struct list_entry *tag_name;
1343 const size_t header_length = strlen(header);
1345 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1347 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1348 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1352 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1353 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1356 if (list_is_empty(csp->action->multi[multi_action_index])
1357 || filters_available(csp) == FALSE)
1359 /* Return early if no taggers apply or if none are available. */
1363 /* Execute all applying taggers */
1364 for (tag_name = csp->action->multi[multi_action_index]->first;
1365 NULL != tag_name; tag_name = tag_name->next)
1367 char *modified_tag = NULL;
1369 size_t size = header_length;
1372 b = get_filter(csp, tag_name->str, wanted_filter_type);
1378 joblist = b->joblist;
1380 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1382 if (NULL == joblist)
1384 log_error(LOG_LEVEL_RE_FILTER,
1385 "Tagger %s has empty joblist. Nothing to do.", b->name);
1389 /* execute their pcrs_joblist on the header. */
1390 for (job = joblist; NULL != job; job = job->next)
1392 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1396 /* Success, continue with the modified version. */
1405 /* Tagger doesn't match */
1408 /* Regex failure, log it but continue anyway. */
1409 assert(NULL != header);
1410 log_error(LOG_LEVEL_ERROR,
1411 "Problems with tagger \'%s\' and header \'%s\': %s",
1412 b->name, *header, pcrs_strerror(hits));
1414 freez(modified_tag);
1418 if (b->dynamic) pcrs_free_joblist(joblist);
1420 /* If this tagger matched */
1426 * There is no technical limitation which makes
1427 * it impossible to use empty tags, but I assume
1428 * no one would do it intentionally.
1431 log_error(LOG_LEVEL_INFO,
1432 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1436 if (!list_contains_item(csp->tags, tag))
1438 if (JB_ERR_OK != enlist(csp->tags, tag))
1440 log_error(LOG_LEVEL_ERROR,
1441 "Insufficient memory to add tag \'%s\', "
1442 "based on tagger \'%s\' and header \'%s\'",
1443 tag, b->name, *header);
1447 char *action_message;
1449 * update the action bits right away, to make
1450 * tagging based on tags set by earlier taggers
1451 * of the same kind possible.
1453 if (update_action_bits_for_tag(csp, tag))
1455 action_message = "Action bits updated accordingly.";
1459 action_message = "No action bits update necessary.";
1462 log_error(LOG_LEVEL_HEADER,
1463 "Tagger \'%s\' added tag \'%s\'. %s",
1464 b->name, tag, action_message);
1469 /* XXX: Is this log-worthy? */
1470 log_error(LOG_LEVEL_HEADER,
1471 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1481 /* here begins the family of parser functions that reformat header lines */
1483 /*********************************************************************
1485 * Function : filter_header
1487 * Description : Executes all text substitutions from all applying
1488 * +(server|client)-header-filter actions on the header.
1489 * Most of the code was copied from pcrs_filter_response,
1490 * including the rather short variable names
1493 * 1 : csp = Current client state (buffers, headers, etc...)
1494 * 2 : header = On input, pointer to header to modify.
1495 * On output, pointer to the modified header, or NULL
1496 * to remove the header. This function frees the
1497 * original string if necessary.
1499 * Returns : JB_ERR_OK on success and always succeeds
1501 *********************************************************************/
1502 static jb_err filter_header(struct client_state *csp, char **header)
1506 size_t size = strlen(*header);
1508 char *newheader = NULL;
1511 struct re_filterfile_spec *b;
1512 struct list_entry *filtername;
1514 enum filter_type wanted_filter_type;
1515 int multi_action_index;
1517 if (csp->flags & CSP_FLAG_NO_FILTERING)
1522 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1524 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1525 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1529 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1530 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1533 if (list_is_empty(csp->action->multi[multi_action_index])
1534 || filters_available(csp) == FALSE)
1536 /* Return early if no filters apply or if none are available. */
1540 /* Execute all applying header filters */
1541 for (filtername = csp->action->multi[multi_action_index]->first;
1542 filtername != NULL; filtername = filtername->next)
1544 int current_hits = 0;
1547 b = get_filter(csp, filtername->str, wanted_filter_type);
1553 joblist = b->joblist;
1555 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1557 if (NULL == joblist)
1559 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1563 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1564 *header, size, b->name);
1566 /* Apply all jobs from the joblist */
1567 for (job = joblist; NULL != job; job = job->next)
1569 matches = pcrs_execute(job, *header, size, &newheader, &size);
1572 current_hits += matches;
1573 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1575 *header = newheader;
1577 else if (0 == matches)
1579 /* Filter doesn't change header */
1585 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1586 *header, b->name, pcrs_strerror(matches));
1587 if (newheader != NULL)
1589 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1595 if (b->dynamic) pcrs_free_joblist(joblist);
1597 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1598 hits += current_hits;
1602 * Additionally checking for hits is important because if
1603 * the continue hack is triggered, server headers can
1604 * arrive empty to separate multiple heads from each other.
1606 if ((0 == size) && hits)
1608 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1616 /*********************************************************************
1618 * Function : server_connection
1620 * Description : Makes sure a proper "Connection:" header is
1621 * set and signals connection_header_adder to
1625 * 1 : csp = Current client state (buffers, headers, etc...)
1626 * 2 : header = On input, pointer to header to modify.
1627 * On output, pointer to the modified header, or NULL
1628 * to remove the header. This function frees the
1629 * original string if necessary.
1631 * Returns : JB_ERR_OK on success.
1633 *********************************************************************/
1634 static jb_err server_connection(struct client_state *csp, char **header)
1636 if (!strcmpic(*header, "Connection: keep-alive")
1637 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1638 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1642 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1643 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1645 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1648 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1650 log_error(LOG_LEVEL_HEADER,
1651 "Keeping the server header '%s' around.", *header);
1654 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1656 char *old_header = *header;
1658 *header = strdup_or_die("Connection: close");
1659 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1664 /* Signal server_connection_adder() to return early. */
1665 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1671 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1672 /*********************************************************************
1674 * Function : server_keep_alive
1676 * Description : Stores the server's keep alive timeout.
1679 * 1 : csp = Current client state (buffers, headers, etc...)
1680 * 2 : header = On input, pointer to header to modify.
1681 * On output, pointer to the modified header, or NULL
1682 * to remove the header. This function frees the
1683 * original string if necessary.
1685 * Returns : JB_ERR_OK.
1687 *********************************************************************/
1688 static jb_err server_keep_alive(struct client_state *csp, char **header)
1690 unsigned int keep_alive_timeout;
1691 const char *timeout_position = strstr(*header, "timeout=");
1693 if ((NULL == timeout_position)
1694 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1696 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1700 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1702 log_error(LOG_LEVEL_HEADER,
1703 "Reducing keep-alive timeout from %u to %u.",
1704 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1705 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1709 /* XXX: Is this log worthy? */
1710 log_error(LOG_LEVEL_HEADER,
1711 "Server keep-alive timeout is %u. Sticking with %u.",
1712 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1714 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1723 /*********************************************************************
1725 * Function : server_proxy_connection
1727 * Description : Figures out whether or not we should add a
1728 * Proxy-Connection header.
1731 * 1 : csp = Current client state (buffers, headers, etc...)
1732 * 2 : header = On input, pointer to header to modify.
1733 * On output, pointer to the modified header, or NULL
1734 * to remove the header. This function frees the
1735 * original string if necessary.
1737 * Returns : JB_ERR_OK.
1739 *********************************************************************/
1740 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1742 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1747 /*********************************************************************
1749 * Function : proxy_authentication
1751 * Description : Removes headers that are relevant for proxy
1752 * authentication unless forwarding them has
1753 * been explicitly requested.
1756 * 1 : csp = Current client state (buffers, headers, etc...)
1757 * 2 : header = On input, pointer to header to modify.
1758 * On output, pointer to the modified header, or NULL
1759 * to remove the header. This function frees the
1760 * original string if necessary.
1762 * Returns : JB_ERR_OK.
1764 *********************************************************************/
1765 static jb_err proxy_authentication(struct client_state *csp, char **header)
1767 if ((csp->config->feature_flags &
1768 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1769 log_error(LOG_LEVEL_HEADER,
1770 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1777 /*********************************************************************
1779 * Function : client_keep_alive
1781 * Description : Stores the client's keep alive timeout.
1784 * 1 : csp = Current client state (buffers, headers, etc...)
1785 * 2 : header = On input, pointer to header to modify.
1786 * On output, pointer to the modified header, or NULL
1787 * to remove the header. This function frees the
1788 * original string if necessary.
1790 * Returns : JB_ERR_OK.
1792 *********************************************************************/
1793 static jb_err client_keep_alive(struct client_state *csp, char **header)
1795 unsigned int keep_alive_timeout;
1796 char *timeout_position;
1798 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1800 log_error(LOG_LEVEL_HEADER,
1801 "keep-alive support is disabled. Crunching: %s.", *header);
1806 /* Check for parameter-less format "Keep-Alive: 100" */
1807 timeout_position = strstr(*header, ": ");
1808 if ((NULL == timeout_position)
1809 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1811 /* Assume parameter format "Keep-Alive: timeout=100" */
1812 timeout_position = strstr(*header, "timeout=");
1813 if ((NULL == timeout_position)
1814 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1816 log_error(LOG_LEVEL_HEADER,
1817 "Couldn't parse: '%s'. Using default timeout %u",
1818 *header, csp->config->keep_alive_timeout);
1825 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1827 log_error(LOG_LEVEL_HEADER,
1828 "Reducing keep-alive timeout from %u to %u.",
1829 csp->config->keep_alive_timeout, keep_alive_timeout);
1830 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1834 /* XXX: Is this log worthy? */
1835 log_error(LOG_LEVEL_HEADER,
1836 "Client keep-alive timeout is %u. Sticking with %u.",
1837 keep_alive_timeout, csp->config->keep_alive_timeout);
1845 /*********************************************************************
1847 * Function : get_content_length
1849 * Description : Gets the content length specified in a
1850 * Content-Length header.
1853 * 1 : header_value = The Content-Length header value.
1854 * 2 : length = Storage to return the value.
1856 * Returns : JB_ERR_OK on success, or
1857 * JB_ERR_PARSE if no value is recognized.
1859 *********************************************************************/
1860 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1863 #if SIZEOF_LONG_LONG < 8
1864 #error sizeof(unsigned long long) too small
1866 if (1 != sscanf(header_value, "%I64u", length))
1868 if (1 != sscanf(header_value, "%llu", length))
1871 return JB_ERR_PARSE;
1878 /*********************************************************************
1880 * Function : client_save_content_length
1882 * Description : Save the Content-Length sent by the client.
1885 * 1 : csp = Current client state (buffers, headers, etc...)
1886 * 2 : header = On input, pointer to header to modify.
1887 * On output, pointer to the modified header, or NULL
1888 * to remove the header. This function frees the
1889 * original string if necessary.
1891 * Returns : JB_ERR_OK on success, or
1892 * JB_ERR_MEMORY on out-of-memory error.
1894 *********************************************************************/
1895 static jb_err client_save_content_length(struct client_state *csp, char **header)
1897 unsigned long long content_length = 0;
1898 const char *header_value;
1900 assert(*(*header+14) == ':');
1902 header_value = *header + 15;
1903 if (JB_ERR_OK != get_content_length(header_value, &content_length))
1905 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1910 csp->expected_client_content_length = content_length;
1915 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1919 /*********************************************************************
1921 * Function : client_connection
1923 * Description : Makes sure a proper "Connection:" header is
1924 * set and signals connection_header_adder
1928 * 1 : csp = Current client state (buffers, headers, etc...)
1929 * 2 : header = On input, pointer to header to modify.
1930 * On output, pointer to the modified header, or NULL
1931 * to remove the header. This function frees the
1932 * original string if necessary.
1934 * Returns : JB_ERR_OK on success.
1936 *********************************************************************/
1937 static jb_err client_connection(struct client_state *csp, char **header)
1939 static const char connection_close[] = "Connection: close";
1941 if (!strcmpic(*header, connection_close))
1943 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1944 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1945 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1947 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1949 log_error(LOG_LEVEL_HEADER,
1950 "Removing \'%s\' to imply keep-alive.", *header);
1953 * While we imply keep-alive to the server,
1954 * we have to remember that the client didn't.
1956 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1960 char *old_header = *header;
1962 *header = strdup_or_die("Connection: keep-alive");
1963 log_error(LOG_LEVEL_HEADER,
1964 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1970 log_error(LOG_LEVEL_HEADER,
1971 "Keeping the client header '%s' around. "
1972 "The connection will not be kept alive.",
1974 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1977 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1978 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1980 log_error(LOG_LEVEL_HEADER,
1981 "Keeping the client header '%s' around. "
1982 "The server connection will be kept alive if possible.",
1984 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1985 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1989 char *old_header = *header;
1991 *header = strdup_or_die(connection_close);
1992 log_error(LOG_LEVEL_HEADER,
1993 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1997 /* Signal client_connection_header_adder() to return early. */
1998 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2004 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2005 /*********************************************************************
2007 * Function : client_proxy_connection
2009 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
2010 * appropriate and removes the Proxy-Connection
2014 * 1 : csp = Current client state (buffers, headers, etc...)
2015 * 2 : header = On input, pointer to header to modify.
2016 * On output, pointer to the modified header, or NULL
2017 * to remove the header. This function frees the
2018 * original string if necessary.
2020 * Returns : JB_ERR_OK
2022 *********************************************************************/
2023 static jb_err client_proxy_connection(struct client_state *csp, char **header)
2025 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2026 && (csp->http->ssl == 0)
2027 && (NULL == strstr(*header, "close")))
2029 log_error(LOG_LEVEL_HEADER,
2030 "The client connection can be kept alive due to: %s", *header);
2031 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2033 crumble(csp, header);
2037 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2040 /*********************************************************************
2042 * Function : client_transfer_encoding
2044 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2045 * the request body is "chunked"
2047 * XXX: Currently not called through sed() as we
2048 * need the flag earlier on. Should be fixed.
2051 * 1 : csp = Current client state (buffers, headers, etc...)
2052 * 2 : header = On input, pointer to header to modify.
2053 * On output, pointer to the modified header, or NULL
2054 * to remove the header. This function frees the
2055 * original string if necessary.
2057 * Returns : JB_ERR_OK on success, or
2059 *********************************************************************/
2060 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2062 if (strstr(*header, "chunked"))
2064 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2065 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2072 /*********************************************************************
2074 * Function : client_expect
2076 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2077 * if the Expect header value is unsupported.
2079 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2080 * MAY and a RFC 2616 (obsolete) MUST.
2083 * 1 : csp = Current client state (buffers, headers, etc...)
2084 * 2 : header = On input, pointer to header to modify.
2085 * On output, pointer to the modified header, or NULL
2086 * to remove the header. This function frees the
2087 * original string if necessary.
2089 * Returns : JB_ERR_OK on success, or
2091 *********************************************************************/
2092 jb_err client_expect(struct client_state *csp, char **header)
2094 if (0 != strcmpic(*header, "Expect: 100-continue"))
2096 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2097 log_error(LOG_LEVEL_HEADER,
2098 "Unsupported client expectaction: %s", *header);
2106 /*********************************************************************
2108 * Function : crumble
2110 * Description : This is called if a header matches a pattern to "crunch"
2113 * 1 : csp = Current client state (buffers, headers, etc...)
2114 * 2 : header = On input, pointer to header to modify.
2115 * On output, pointer to the modified header, or NULL
2116 * to remove the header. This function frees the
2117 * original string if necessary.
2119 * Returns : JB_ERR_OK on success, or
2120 * JB_ERR_MEMORY on out-of-memory error.
2122 *********************************************************************/
2123 static jb_err crumble(struct client_state *csp, char **header)
2126 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2132 /*********************************************************************
2134 * Function : crunch_server_header
2136 * Description : Crunch server header if it matches a string supplied by the
2137 * user. Called from `sed'.
2140 * 1 : csp = Current client state (buffers, headers, etc...)
2141 * 2 : header = On input, pointer to header to modify.
2142 * On output, pointer to the modified header, or NULL
2143 * to remove the header. This function frees the
2144 * original string if necessary.
2146 * Returns : JB_ERR_OK on success and always succeeds
2148 *********************************************************************/
2149 static jb_err crunch_server_header(struct client_state *csp, char **header)
2151 const char *crunch_pattern;
2153 /* Do we feel like crunching? */
2154 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2156 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2158 /* Is the current header the lucky one? */
2159 if (strstr(*header, crunch_pattern))
2161 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2170 /*********************************************************************
2172 * Function : server_content_type
2174 * Description : Set the content-type for filterable types (text/.*,
2175 * .*xml.*, .*script.* and image/gif) unless filtering has been
2176 * forbidden (CT_TABOO) while parsing earlier headers.
2177 * NOTE: Since text/plain is commonly used by web servers
2178 * for files whose correct type is unknown, we don't
2179 * set CT_TEXT for it.
2182 * 1 : csp = Current client state (buffers, headers, etc...)
2183 * 2 : header = On input, pointer to header to modify.
2184 * On output, pointer to the modified header, or NULL
2185 * to remove the header. This function frees the
2186 * original string if necessary.
2188 * Returns : JB_ERR_OK on success, or
2189 * JB_ERR_MEMORY on out-of-memory error.
2191 *********************************************************************/
2192 static jb_err server_content_type(struct client_state *csp, char **header)
2194 /* Remove header if it isn't the first Content-Type header */
2195 if ((csp->content_type & CT_DECLARED))
2197 if (content_filters_enabled(csp->action))
2200 * Making sure the client interprets the content the same way
2201 * Privoxy did is only relevant if Privoxy modified it.
2203 * Checking for this is "hard" as it's not yet known when
2204 * this function is called, thus go shopping and and just
2205 * check if Privoxy could filter it.
2207 * The main thing is that we don't mess with the headers
2208 * unless the user signalled that it's acceptable.
2210 log_error(LOG_LEVEL_HEADER,
2211 "Multiple Content-Type headers detected. "
2212 "Removing and ignoring: %s",
2220 * Signal that the Content-Type has been set.
2222 csp->content_type |= CT_DECLARED;
2224 if (!(csp->content_type & CT_TABOO))
2227 * XXX: The assumption that text/plain is a sign of
2228 * binary data seems to be somewhat unreasonable nowadays
2229 * and should be dropped after 3.0.8 is out.
2231 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2232 || strstr(*header, "xml")
2233 || strstr(*header, "script"))
2235 csp->content_type |= CT_TEXT;
2237 else if (strstr(*header, "image/gif"))
2239 csp->content_type |= CT_GIF;
2244 * Are we messing with the content type?
2246 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2249 * Make sure the user doesn't accidentally
2250 * change the content type of binary documents.
2252 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2256 *header = strdup_or_die("Content-Type: ");
2258 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2259 if (JB_ERR_OK != err)
2261 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2262 return JB_ERR_MEMORY;
2264 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2268 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2269 "It doesn't look like a content type that should be filtered. "
2270 "Enable force-text-mode if you know what you're doing.", *header);
2278 /*********************************************************************
2280 * Function : server_transfer_coding
2282 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2283 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2284 * - Remove header if body was chunked but has been
2285 * de-chunked for filtering.
2288 * 1 : csp = Current client state (buffers, headers, etc...)
2289 * 2 : header = On input, pointer to header to modify.
2290 * On output, pointer to the modified header, or NULL
2291 * to remove the header. This function frees the
2292 * original string if necessary.
2294 * Returns : JB_ERR_OK on success, or
2295 * JB_ERR_MEMORY on out-of-memory error.
2297 *********************************************************************/
2298 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2301 * Turn off pcrs and gif filtering if body compressed
2303 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2307 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2309 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2310 csp->http->cmd, *header);
2311 #endif /* def FEATURE_ZLIB */
2312 csp->content_type = CT_TABOO;
2316 * Raise flag if body chunked
2318 if (strstr(*header, "chunked"))
2320 csp->flags |= CSP_FLAG_CHUNKED;
2323 * If the body was modified, it has been de-chunked first
2324 * and the header must be removed.
2326 * FIXME: If there is more than one transfer encoding,
2327 * only the "chunked" part should be removed here.
2329 if (csp->flags & CSP_FLAG_MODIFIED)
2331 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2340 /*********************************************************************
2342 * Function : server_content_encoding
2344 * Description : Used to check if the content is compressed, and if
2345 * FEATURE_ZLIB is disabled, filtering is disabled as
2348 * If FEATURE_ZLIB is enabled and the compression type
2349 * supported, the content is marked for decompression.
2351 * XXX: Doesn't properly deal with multiple or with
2352 * unsupported but unknown encodings.
2353 * Is case-sensitive but shouldn't be.
2356 * 1 : csp = Current client state (buffers, headers, etc...)
2357 * 2 : header = On input, pointer to header to modify.
2358 * On output, pointer to the modified header, or NULL
2359 * to remove the header. This function frees the
2360 * original string if necessary.
2362 * Returns : JB_ERR_OK on success, or
2363 * JB_ERR_MEMORY on out-of-memory error.
2365 *********************************************************************/
2366 static jb_err server_content_encoding(struct client_state *csp, char **header)
2369 if (strstr(*header, "sdch"))
2372 * Shared Dictionary Compression over HTTP isn't supported,
2373 * filtering it anyway is pretty much guaranteed to mess up
2376 csp->content_type |= CT_TABOO;
2379 * Log a warning if the user expects the content to be filtered.
2381 if (content_filters_enabled(csp->action))
2383 log_error(LOG_LEVEL_INFO,
2384 "SDCH-compressed content detected, content filtering disabled. "
2385 "Consider suppressing SDCH offers made by the client.");
2388 else if (strstr(*header, "gzip"))
2390 /* Mark for gzip decompression */
2391 csp->content_type |= CT_GZIP;
2393 else if (strstr(*header, "deflate"))
2395 /* Mark for zlib decompression */
2396 csp->content_type |= CT_DEFLATE;
2398 else if (strstr(*header, "compress"))
2401 * We can't decompress this; therefore we can't filter
2404 csp->content_type |= CT_TABOO;
2406 #else /* !defined(FEATURE_ZLIB) */
2408 * XXX: Using a black list here isn't the right approach.
2410 * In case of SDCH, building with zlib support isn't
2413 if (strstr(*header, "gzip") ||
2414 strstr(*header, "compress") ||
2415 strstr(*header, "deflate") ||
2416 strstr(*header, "sdch"))
2419 * Body is compressed, turn off pcrs and gif filtering.
2421 csp->content_type |= CT_TABOO;
2424 * Log a warning if the user expects the content to be filtered.
2426 if (content_filters_enabled(csp->action))
2428 log_error(LOG_LEVEL_INFO,
2429 "Compressed content detected, content filtering disabled. "
2430 "Consider recompiling Privoxy with zlib support or "
2431 "enable the prevent-compression action.");
2434 #endif /* defined(FEATURE_ZLIB) */
2442 /*********************************************************************
2444 * Function : server_adjust_content_encoding
2446 * Description : Remove the Content-Encoding header if the
2447 * decompression was successful and the content
2451 * 1 : csp = Current client state (buffers, headers, etc...)
2452 * 2 : header = On input, pointer to header to modify.
2453 * On output, pointer to the modified header, or NULL
2454 * to remove the header. This function frees the
2455 * original string if necessary.
2457 * Returns : JB_ERR_OK on success, or
2458 * JB_ERR_MEMORY on out-of-memory error.
2460 *********************************************************************/
2461 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2463 if ((csp->flags & CSP_FLAG_MODIFIED)
2464 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2467 * We successfully decompressed the content,
2468 * and have to clean the header now, so the
2469 * client no longer expects compressed data.
2471 * XXX: There is a difference between cleaning
2472 * and removing it completely.
2474 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2481 #endif /* defined(FEATURE_ZLIB) */
2484 /*********************************************************************
2486 * Function : server_adjust_content_length
2488 * Description : Adjust Content-Length header if we modified
2492 * 1 : csp = Current client state (buffers, headers, etc...)
2493 * 2 : header = On input, pointer to header to modify.
2494 * On output, pointer to the modified header, or NULL
2495 * to remove the header. This function frees the
2496 * original string if necessary.
2498 * Returns : JB_ERR_OK on success, or
2499 * JB_ERR_MEMORY on out-of-memory error.
2501 *********************************************************************/
2502 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2504 /* Regenerate header if the content was modified. */
2505 if (csp->flags & CSP_FLAG_MODIFIED)
2507 const size_t header_length = 50;
2509 *header = malloc(header_length);
2510 if (*header == NULL)
2512 return JB_ERR_MEMORY;
2514 create_content_length_header(csp->content_length, *header, header_length);
2515 log_error(LOG_LEVEL_HEADER,
2516 "Adjusted Content-Length to %llu", csp->content_length);
2523 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2524 /*********************************************************************
2526 * Function : server_save_content_length
2528 * Description : Save the Content-Length sent by the server.
2531 * 1 : csp = Current client state (buffers, headers, etc...)
2532 * 2 : header = On input, pointer to header to modify.
2533 * On output, pointer to the modified header, or NULL
2534 * to remove the header. This function frees the
2535 * original string if necessary.
2537 * Returns : JB_ERR_OK on success, or
2538 * JB_ERR_MEMORY on out-of-memory error.
2540 *********************************************************************/
2541 static jb_err server_save_content_length(struct client_state *csp, char **header)
2543 unsigned long long content_length = 0;
2544 const char *header_value;
2546 assert(*(*header+14) == ':');
2548 header_value = *header + 15;
2549 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2551 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2556 csp->expected_content_length = content_length;
2557 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2558 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2563 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2566 /*********************************************************************
2568 * Function : server_content_md5
2570 * Description : Crumble any Content-MD5 headers if the document was
2571 * modified. FIXME: Should we re-compute instead?
2574 * 1 : csp = Current client state (buffers, headers, etc...)
2575 * 2 : header = On input, pointer to header to modify.
2576 * On output, pointer to the modified header, or NULL
2577 * to remove the header. This function frees the
2578 * original string if necessary.
2580 * Returns : JB_ERR_OK on success, or
2581 * JB_ERR_MEMORY on out-of-memory error.
2583 *********************************************************************/
2584 static jb_err server_content_md5(struct client_state *csp, char **header)
2586 if (csp->flags & CSP_FLAG_MODIFIED)
2588 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2596 /*********************************************************************
2598 * Function : server_content_disposition
2600 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2601 * Called from `sed'.
2604 * 1 : csp = Current client state (buffers, headers, etc...)
2605 * 2 : header = On input, pointer to header to modify.
2606 * On output, pointer to the modified header, or NULL
2607 * to remove the header. This function frees the
2608 * original string if necessary.
2610 * Returns : JB_ERR_OK on success, or
2611 * JB_ERR_MEMORY on out-of-memory error.
2613 *********************************************************************/
2614 static jb_err server_content_disposition(struct client_state *csp, char **header)
2619 * Are we messing with the Content-Disposition header?
2621 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2627 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2629 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2632 * Blocking content-disposition header
2634 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2641 * Replacing Content-Disposition header
2644 *header = strdup("Content-Disposition: ");
2645 string_append(header, newval);
2647 if (*header != NULL)
2649 log_error(LOG_LEVEL_HEADER,
2650 "Content-Disposition header crunched and replaced with: %s", *header);
2653 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2657 /*********************************************************************
2659 * Function : server_last_modified
2661 * Description : Changes Last-Modified header to the actual date
2662 * to help hide-if-modified-since.
2663 * Called from `sed'.
2666 * 1 : csp = Current client state (buffers, headers, etc...)
2667 * 2 : header = On input, pointer to header to modify.
2668 * On output, pointer to the modified header, or NULL
2669 * to remove the header. This function frees the
2670 * original string if necessary.
2672 * Returns : JB_ERR_OK on success, or
2673 * JB_ERR_MEMORY on out-of-memory error.
2675 *********************************************************************/
2676 static jb_err server_last_modified(struct client_state *csp, char **header)
2679 time_t last_modified;
2683 * Are we messing with the Last-Modified header?
2685 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2691 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2693 if (0 == strcmpic(newval, "block"))
2696 * Blocking Last-Modified header. Useless but why not.
2698 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2702 else if (0 == strcmpic(newval, "reset-to-request-time"))
2705 * Setting Last-Modified Header to now.
2708 get_http_time(0, buf, sizeof(buf));
2710 *header = strdup("Last-Modified: ");
2711 string_append(header, buf);
2713 if (*header == NULL)
2715 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2719 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2722 else if (0 == strcmpic(newval, "randomize"))
2724 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2726 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2728 log_error(LOG_LEVEL_HEADER,
2729 "Couldn't parse time in %s (crunching!)", *header);
2735 struct tm *timeptr = NULL;
2737 #ifdef HAVE_GMTIME_R
2741 rtime = (long int)difftime(now, last_modified);
2744 long int days, hours, minutes, seconds;
2745 const int negative_delta = (rtime < 0);
2750 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2752 rtime = pick_from_range(rtime);
2757 last_modified += rtime;
2758 #ifdef HAVE_GMTIME_R
2759 timeptr = gmtime_r(&last_modified, &gmt);
2760 #elif defined(MUTEX_LOCKS_AVAILABLE)
2761 privoxy_mutex_lock(&gmtime_mutex);
2762 timeptr = gmtime(&last_modified);
2763 privoxy_mutex_unlock(&gmtime_mutex);
2765 timeptr = gmtime(&last_modified);
2767 if ((NULL == timeptr) || !strftime(newheader,
2768 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2770 log_error(LOG_LEVEL_ERROR,
2771 "Randomizing '%s' failed. Crunching the header without replacement.",
2778 *header = strdup("Last-Modified: ");
2779 string_append(header, newheader);
2781 if (*header == NULL)
2783 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2784 return JB_ERR_MEMORY;
2787 days = rtime / (3600 * 24);
2788 hours = rtime / 3600 % 24;
2789 minutes = rtime / 60 % 60;
2790 seconds = rtime % 60;
2792 log_error(LOG_LEVEL_HEADER,
2793 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2794 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2795 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2799 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2808 /*********************************************************************
2810 * Function : client_accept_encoding
2812 * Description : Rewrite the client's Accept-Encoding header so that
2813 * if doesn't allow compression, if the action applies.
2814 * Note: For HTTP/1.0 the absence of the header is enough.
2817 * 1 : csp = Current client state (buffers, headers, etc...)
2818 * 2 : header = On input, pointer to header to modify.
2819 * On output, pointer to the modified header, or NULL
2820 * to remove the header. This function frees the
2821 * original string if necessary.
2823 * Returns : JB_ERR_OK on success, or
2824 * JB_ERR_MEMORY on out-of-memory error.
2826 *********************************************************************/
2827 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2829 #ifdef FEATURE_COMPRESSION
2830 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2831 && strstr(*header, "deflate"))
2833 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2836 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2838 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2846 /*********************************************************************
2848 * Function : client_te
2850 * Description : Rewrite the client's TE header so that
2851 * if doesn't allow compression, if the action applies.
2854 * 1 : csp = Current client state (buffers, headers, etc...)
2855 * 2 : header = On input, pointer to header to modify.
2856 * On output, pointer to the modified header, or NULL
2857 * to remove the header. This function frees the
2858 * original string if necessary.
2860 * Returns : JB_ERR_OK on success, or
2861 * JB_ERR_MEMORY on out-of-memory error.
2863 *********************************************************************/
2864 static jb_err client_te(struct client_state *csp, char **header)
2866 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2869 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2876 /*********************************************************************
2878 * Function : client_referrer
2880 * Description : Handle the "referer" config setting properly.
2881 * Called from `sed'.
2884 * 1 : csp = Current client state (buffers, headers, etc...)
2885 * 2 : header = On input, pointer to header to modify.
2886 * On output, pointer to the modified header, or NULL
2887 * to remove the header. This function frees the
2888 * original string if necessary.
2890 * Returns : JB_ERR_OK on success, or
2891 * JB_ERR_MEMORY on out-of-memory error.
2893 *********************************************************************/
2894 static jb_err client_referrer(struct client_state *csp, char **header)
2896 const char *parameter;
2897 /* booleans for parameters we have to check multiple times */
2898 int parameter_conditional_block;
2899 int parameter_conditional_forge;
2901 #ifdef FEATURE_FORCE_LOAD
2903 * Since the referrer can include the prefix even
2904 * if the request itself is non-forced, we must
2905 * clean it unconditionally.
2907 * XXX: strclean is too broad
2909 strclean(*header, FORCE_PREFIX);
2910 #endif /* def FEATURE_FORCE_LOAD */
2912 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2914 /* Nothing left to do */
2918 parameter = csp->action->string[ACTION_STRING_REFERER];
2919 assert(parameter != NULL);
2920 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2921 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2923 if (!parameter_conditional_block && !parameter_conditional_forge)
2926 * As conditional-block and conditional-forge are the only
2927 * parameters that rely on the original referrer, we can
2928 * remove it now for all the others.
2933 if (0 == strcmpic(parameter, "block"))
2935 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2938 else if (parameter_conditional_block || parameter_conditional_forge)
2940 return handle_conditional_hide_referrer_parameter(header,
2941 csp->http->hostport, parameter_conditional_block);
2943 else if (0 == strcmpic(parameter, "forge"))
2945 return create_forged_referrer(header, csp->http->hostport);
2949 /* interpret parameter as user-supplied referer to fake */
2950 return create_fake_referrer(header, parameter);
2955 /*********************************************************************
2957 * Function : client_accept_language
2959 * Description : Handle the "Accept-Language" config setting properly.
2960 * Called from `sed'.
2963 * 1 : csp = Current client state (buffers, headers, etc...)
2964 * 2 : header = On input, pointer to header to modify.
2965 * On output, pointer to the modified header, or NULL
2966 * to remove the header. This function frees the
2967 * original string if necessary.
2969 * Returns : JB_ERR_OK on success, or
2970 * JB_ERR_MEMORY on out-of-memory error.
2972 *********************************************************************/
2973 static jb_err client_accept_language(struct client_state *csp, char **header)
2978 * Are we messing with the Accept-Language?
2980 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2982 /*I don't think so*/
2986 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2988 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2991 * Blocking Accept-Language header
2993 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3000 * Replacing Accept-Language header
3003 *header = strdup("Accept-Language: ");
3004 string_append(header, newval);
3006 if (*header == NULL)
3008 log_error(LOG_LEVEL_ERROR,
3009 "Insufficient memory. Accept-Language header crunched without replacement.");
3013 log_error(LOG_LEVEL_HEADER,
3014 "Accept-Language header crunched and replaced with: %s", *header);
3017 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3021 /*********************************************************************
3023 * Function : crunch_client_header
3025 * Description : Crunch client header if it matches a string supplied by the
3026 * user. Called from `sed'.
3029 * 1 : csp = Current client state (buffers, headers, etc...)
3030 * 2 : header = On input, pointer to header to modify.
3031 * On output, pointer to the modified header, or NULL
3032 * to remove the header. This function frees the
3033 * original string if necessary.
3035 * Returns : JB_ERR_OK on success and always succeeds
3037 *********************************************************************/
3038 static jb_err crunch_client_header(struct client_state *csp, char **header)
3040 const char *crunch_pattern;
3042 /* Do we feel like crunching? */
3043 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3045 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3047 /* Is the current header the lucky one? */
3048 if (strstr(*header, crunch_pattern))
3050 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3058 /*********************************************************************
3060 * Function : client_uagent
3062 * Description : Handle the "user-agent" config setting properly
3063 * and remember its original value to enable browser
3064 * bug workarounds. Called from `sed'.
3067 * 1 : csp = Current client state (buffers, headers, etc...)
3068 * 2 : header = On input, pointer to header to modify.
3069 * On output, pointer to the modified header, or NULL
3070 * to remove the header. This function frees the
3071 * original string if necessary.
3073 * Returns : JB_ERR_OK on success, or
3074 * JB_ERR_MEMORY on out-of-memory error.
3076 *********************************************************************/
3077 static jb_err client_uagent(struct client_state *csp, char **header)
3081 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3086 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3093 *header = strdup("User-Agent: ");
3094 string_append(header, newval);
3096 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3098 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3102 /*********************************************************************
3104 * Function : client_ua
3106 * Description : Handle "ua-" headers properly. Called from `sed'.
3109 * 1 : csp = Current client state (buffers, headers, etc...)
3110 * 2 : header = On input, pointer to header to modify.
3111 * On output, pointer to the modified header, or NULL
3112 * to remove the header. This function frees the
3113 * original string if necessary.
3115 * Returns : JB_ERR_OK on success, or
3116 * JB_ERR_MEMORY on out-of-memory error.
3118 *********************************************************************/
3119 static jb_err client_ua(struct client_state *csp, char **header)
3121 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3123 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3131 /*********************************************************************
3133 * Function : client_from
3135 * Description : Handle the "from" config setting properly.
3136 * Called from `sed'.
3139 * 1 : csp = Current client state (buffers, headers, etc...)
3140 * 2 : header = On input, pointer to header to modify.
3141 * On output, pointer to the modified header, or NULL
3142 * to remove the header. This function frees the
3143 * original string if necessary.
3145 * Returns : JB_ERR_OK on success, or
3146 * JB_ERR_MEMORY on out-of-memory error.
3148 *********************************************************************/
3149 static jb_err client_from(struct client_state *csp, char **header)
3153 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3160 newval = csp->action->string[ACTION_STRING_FROM];
3163 * Are we blocking the e-mail address?
3165 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3167 log_error(LOG_LEVEL_HEADER, "crunched From!");
3171 log_error(LOG_LEVEL_HEADER, " modified");
3173 *header = strdup("From: ");
3174 string_append(header, newval);
3176 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3180 /*********************************************************************
3182 * Function : client_send_cookie
3184 * Description : Crunches the "cookie" header if necessary.
3185 * Called from `sed'.
3187 * XXX: Stupid name, doesn't send squat.
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_send_cookie(struct client_state *csp, char **header)
3202 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3204 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3212 /*********************************************************************
3214 * Function : client_x_forwarded
3216 * Description : Handle the "x-forwarded-for" config setting properly,
3217 * also used in the add_client_headers list. Called from `sed'.
3220 * 1 : csp = Current client state (buffers, headers, etc...)
3221 * 2 : header = On input, pointer to header to modify.
3222 * On output, pointer to the modified header, or NULL
3223 * to remove the header. This function frees the
3224 * original string if necessary.
3226 * Returns : JB_ERR_OK on success, or
3227 * JB_ERR_MEMORY on out-of-memory error.
3229 *********************************************************************/
3230 jb_err client_x_forwarded(struct client_state *csp, char **header)
3232 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3234 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3236 if (0 == strcmpic(parameter, "block"))
3239 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3241 else if (0 == strcmpic(parameter, "add"))
3243 string_append(header, ", ");
3244 string_append(header, csp->ip_addr_str);
3246 if (*header == NULL)
3248 return JB_ERR_MEMORY;
3250 log_error(LOG_LEVEL_HEADER,
3251 "Appended client IP address to %s", *header);
3252 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3256 log_error(LOG_LEVEL_FATAL,
3257 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3265 /*********************************************************************
3267 * Function : client_max_forwards
3269 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3270 * from the value of the Max-Forwards header field.
3273 * 1 : csp = Current client state (buffers, headers, etc...)
3274 * 2 : header = On input, pointer to header to modify.
3275 * On output, pointer to the modified header, or NULL
3276 * to remove the header. This function frees the
3277 * original string if necessary.
3279 * Returns : JB_ERR_OK on success, or
3280 * JB_ERR_MEMORY on out-of-memory error.
3282 *********************************************************************/
3283 static jb_err client_max_forwards(struct client_state *csp, char **header)
3287 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3288 (0 == strcmpic(csp->http->gpc, "options")))
3290 assert(*(*header+12) == ':');
3291 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3293 if (max_forwards > 0)
3295 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3296 log_error(LOG_LEVEL_HEADER,
3297 "Max-Forwards value for %s request reduced to %d.",
3298 csp->http->gpc, max_forwards);
3300 else if (max_forwards < 0)
3302 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3308 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3317 /*********************************************************************
3319 * Function : client_host
3321 * Description : If the request URI did not contain host and
3322 * port information, parse and evaluate the Host
3326 * 1 : csp = Current client state (buffers, headers, etc...)
3327 * 2 : header = On input, pointer to header to modify.
3328 * On output, pointer to the modified header, or NULL
3329 * to remove the header. This function frees the
3330 * original string if necessary.
3332 * Returns : JB_ERR_OK on success, or
3333 * JB_ERR_MEMORY on out-of-memory error.
3335 *********************************************************************/
3336 static jb_err client_host(struct client_state *csp, char **header)
3340 if (strlen(*header) < 7)
3342 log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3347 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3348 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3351 p = strdup_or_die((*header)+6);
3353 q = strdup_or_die(p);
3355 freez(csp->http->hostport);
3356 csp->http->hostport = p;
3357 freez(csp->http->host);
3358 csp->http->host = q;
3359 q = strchr(csp->http->host, ':');
3362 /* Terminate hostname and evaluate port string */
3364 csp->http->port = atoi(q);
3368 csp->http->port = csp->http->ssl ? 443 : 80;
3371 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3372 csp->http->hostport, csp->http->host, csp->http->port);
3375 /* Signal client_host_adder() to return right away */
3376 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3382 /*********************************************************************
3384 * Function : client_if_modified_since
3386 * Description : Remove or modify the If-Modified-Since header.
3389 * 1 : csp = Current client state (buffers, headers, etc...)
3390 * 2 : header = On input, pointer to header to modify.
3391 * On output, pointer to the modified header, or NULL
3392 * to remove the header. This function frees the
3393 * original string if necessary.
3395 * Returns : JB_ERR_OK on success, or
3396 * JB_ERR_MEMORY on out-of-memory error.
3398 *********************************************************************/
3399 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3402 #ifdef HAVE_GMTIME_R
3405 struct tm *timeptr = NULL;
3410 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3413 * The client got an error message because of a temporary problem,
3414 * the problem is gone and the client now tries to revalidate our
3415 * error message on the real server. The revalidation would always
3416 * end with the transmission of the whole document and there is
3417 * no need to expose the bogus If-Modified-Since header.
3419 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3422 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3424 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3426 if ((0 == strcmpic(newval, "block")))
3428 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3431 else /* add random value */
3433 if (JB_ERR_OK != parse_time_header(*header, &tm))
3435 log_error(LOG_LEVEL_HEADER,
3436 "Couldn't parse time in %s (crunching!)", *header);
3441 long int hours, minutes, seconds;
3442 long int rtime = strtol(newval, &endptr, 0);
3443 const int negative_range = (rtime < 0);
3447 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3448 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3454 rtime = pick_from_range(rtime);
3458 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3461 tm += rtime * (negative_range ? -1 : 1);
3462 #ifdef HAVE_GMTIME_R
3463 timeptr = gmtime_r(&tm, &gmt);
3464 #elif defined(MUTEX_LOCKS_AVAILABLE)
3465 privoxy_mutex_lock(&gmtime_mutex);
3466 timeptr = gmtime(&tm);
3467 privoxy_mutex_unlock(&gmtime_mutex);
3469 timeptr = gmtime(&tm);
3471 if ((NULL == timeptr) || !strftime(newheader,
3472 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3474 log_error(LOG_LEVEL_ERROR,
3475 "Randomizing '%s' failed. Crunching the header without replacement.",
3482 *header = strdup("If-Modified-Since: ");
3483 string_append(header, newheader);
3485 if (*header == NULL)
3487 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3488 return JB_ERR_MEMORY;
3491 hours = rtime / 3600;
3492 minutes = rtime / 60 % 60;
3493 seconds = rtime % 60;
3495 log_error(LOG_LEVEL_HEADER,
3496 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3497 *header, (negative_range) ? "subtracted" : "added", hours,
3498 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3499 seconds, (seconds == 1) ? ")" : "s)");
3508 /*********************************************************************
3510 * Function : client_if_none_match
3512 * Description : Remove the If-None-Match header.
3515 * 1 : csp = Current client state (buffers, headers, etc...)
3516 * 2 : header = On input, pointer to header to modify.
3517 * On output, pointer to the modified header, or NULL
3518 * to remove the header. This function frees the
3519 * original string if necessary.
3521 * Returns : JB_ERR_OK on success, or
3522 * JB_ERR_MEMORY on out-of-memory error.
3524 *********************************************************************/
3525 static jb_err client_if_none_match(struct client_state *csp, char **header)
3527 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3529 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3537 /*********************************************************************
3539 * Function : client_x_filter
3541 * Description : Disables filtering if the client set "X-Filter: No".
3542 * Called from `sed'.
3545 * 1 : csp = Current client state (buffers, headers, etc...)
3546 * 2 : header = On input, pointer to header to modify.
3547 * On output, pointer to the modified header, or NULL
3548 * to remove the header. This function frees the
3549 * original string if necessary.
3551 * Returns : JB_ERR_OK on success
3553 *********************************************************************/
3554 jb_err client_x_filter(struct client_state *csp, char **header)
3556 if (0 == strcmpic(*header, "X-Filter: No"))
3558 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3560 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3564 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3566 log_error(LOG_LEVEL_HEADER,
3567 "force-text-mode overruled the client's request to fetch without filtering!");
3571 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3572 csp->flags |= CSP_FLAG_NO_FILTERING;
3573 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3575 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3583 /*********************************************************************
3585 * Function : client_range
3587 * Description : Removes Range, Request-Range and If-Range headers if
3588 * content filtering is enabled and the range doesn't
3591 * If the client's version of the document has been
3592 * altered by Privoxy, the server could interpret the
3593 * range differently than the client intended in which
3594 * case the user could end up with corrupted content.
3596 * If the range starts at byte 0 this isn't an issue
3597 * so the header can pass. Partial requests like this
3598 * are used to render preview images for videos without
3599 * downloading the whole video.
3601 * While HTTP doesn't require that range requests are
3602 * honoured and the client could simply abort the download
3603 * after receiving a sufficient amount of data, various
3604 * clients don't handle complete responses to range
3605 * requests gracefully and emit misleading error messages
3609 * 1 : csp = Current client state (buffers, headers, etc...)
3610 * 2 : header = On input, pointer to header to modify.
3611 * On output, pointer to the modified header, or NULL
3612 * to remove the header. This function frees the
3613 * original string if necessary.
3615 * Returns : JB_ERR_OK
3617 *********************************************************************/
3618 static jb_err client_range(struct client_state *csp, char **header)
3620 if (content_filters_enabled(csp->action)
3621 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3623 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3624 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3631 /* the following functions add headers directly to the header list */
3633 /*********************************************************************
3635 * Function : client_host_adder
3637 * Description : Adds the Host: header field if it is missing.
3638 * Called from `sed'.
3641 * 1 : csp = Current client state (buffers, headers, etc...)
3643 * Returns : JB_ERR_OK on success, or
3644 * JB_ERR_MEMORY on out-of-memory error.
3646 *********************************************************************/
3647 static jb_err client_host_adder(struct client_state *csp)
3652 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3654 /* Header already set by the client, nothing to do. */
3658 if (!csp->http->hostport || !*(csp->http->hostport))
3660 log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3661 return JB_ERR_PARSE;
3665 * remove 'user:pass@' from 'proto://user:pass@host'
3667 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3673 p = csp->http->hostport;
3676 /* XXX: Just add it, we already made sure that it will be unique */
3677 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3678 err = enlist_unique_header(csp->headers, "Host", p);
3684 /*********************************************************************
3686 * Function : client_xtra_adder
3688 * Description : Used in the add_client_headers list. Called from `sed'.
3691 * 1 : csp = Current client state (buffers, headers, etc...)
3693 * Returns : JB_ERR_OK on success, or
3694 * JB_ERR_MEMORY on out-of-memory error.
3696 *********************************************************************/
3697 static jb_err client_xtra_adder(struct client_state *csp)
3699 struct list_entry *lst;
3702 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3703 lst ; lst = lst->next)
3705 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3706 err = enlist(csp->headers, lst->str);
3718 /*********************************************************************
3720 * Function : client_x_forwarded_for_adder
3722 * Description : Used in the add_client_headers list. Called from `sed'.
3725 * 1 : csp = Current client state (buffers, headers, etc...)
3727 * Returns : JB_ERR_OK on success, or
3728 * JB_ERR_MEMORY on out-of-memory error.
3730 *********************************************************************/
3731 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3733 char *header = NULL;
3736 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3737 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3738 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3741 * If we aren't adding X-Forwarded-For headers,
3742 * or we already appended an existing X-Forwarded-For
3743 * header, there's nothing left to do here.
3748 header = strdup("X-Forwarded-For: ");
3749 string_append(&header, csp->ip_addr_str);
3753 return JB_ERR_MEMORY;
3756 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3757 err = enlist(csp->headers, header);
3764 /*********************************************************************
3766 * Function : server_connection_adder
3768 * Description : Adds an appropriate "Connection:" header to csp->headers
3769 * unless the header was already present. Called from `sed'.