1 const char parsers_rcs[] = "$Id: parsers.c,v 1.283 2014/02/10 14:42:18 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
8 * Copyright : Written by and Copyright (C) 2001-2012 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
40 #include <sys/types.h>
50 * Convince GNU's libc to provide a strptime prototype.
59 #define GZIP_IDENTIFIER_1 0x1f
60 #define GZIP_IDENTIFIER_2 0x8b
62 #define GZIP_FLAG_CHECKSUM 0x02
63 #define GZIP_FLAG_EXTRA_FIELDS 0x04
64 #define GZIP_FLAG_FILE_NAME 0x08
65 #define GZIP_FLAG_COMMENT 0x10
66 #define GZIP_FLAG_RESERVED_BITS 0xe0
69 #if !defined(_WIN32) && !defined(__OS2__)
75 #ifdef FEATURE_PTHREAD
77 /* jcc.h is for mutex semapores only */
78 #endif /* def FEATURE_PTHREAD */
83 #include "jbsockets.h"
93 const char parsers_h_rcs[] = PARSERS_H_VERSION;
95 static char *get_header_line(struct iob *iob);
96 static jb_err scan_headers(struct client_state *csp);
97 static jb_err header_tagger(struct client_state *csp, char *header);
98 static jb_err parse_header_time(const char *header_time, time_t *result);
100 static jb_err crumble (struct client_state *csp, char **header);
101 static jb_err filter_header (struct client_state *csp, char **header);
102 static jb_err client_connection (struct client_state *csp, char **header);
103 static jb_err client_referrer (struct client_state *csp, char **header);
104 static jb_err client_uagent (struct client_state *csp, char **header);
105 static jb_err client_ua (struct client_state *csp, char **header);
106 static jb_err client_from (struct client_state *csp, char **header);
107 static jb_err client_send_cookie (struct client_state *csp, char **header);
108 static jb_err client_x_forwarded (struct client_state *csp, char **header);
109 static jb_err client_accept_encoding (struct client_state *csp, char **header);
110 static jb_err client_te (struct client_state *csp, char **header);
111 static jb_err client_max_forwards (struct client_state *csp, char **header);
112 static jb_err client_host (struct client_state *csp, char **header);
113 static jb_err client_if_modified_since (struct client_state *csp, char **header);
114 static jb_err client_accept_language (struct client_state *csp, char **header);
115 static jb_err client_if_none_match (struct client_state *csp, char **header);
116 static jb_err crunch_client_header (struct client_state *csp, char **header);
117 static jb_err client_x_filter (struct client_state *csp, char **header);
118 static jb_err client_range (struct client_state *csp, char **header);
119 static jb_err server_set_cookie (struct client_state *csp, char **header);
120 static jb_err server_connection (struct client_state *csp, char **header);
121 static jb_err server_content_type (struct client_state *csp, char **header);
122 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
123 static jb_err server_content_md5 (struct client_state *csp, char **header);
124 static jb_err server_content_encoding (struct client_state *csp, char **header);
125 static jb_err server_transfer_coding (struct client_state *csp, char **header);
126 static jb_err server_http (struct client_state *csp, char **header);
127 static jb_err crunch_server_header (struct client_state *csp, char **header);
128 static jb_err server_last_modified (struct client_state *csp, char **header);
129 static jb_err server_content_disposition(struct client_state *csp, char **header);
131 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
134 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
135 static jb_err server_save_content_length(struct client_state *csp, char **header);
136 static jb_err server_keep_alive(struct client_state *csp, char **header);
137 static jb_err server_proxy_connection(struct client_state *csp, char **header);
138 static jb_err client_keep_alive(struct client_state *csp, char **header);
139 static jb_err client_save_content_length(struct client_state *csp, char **header);
140 static jb_err client_proxy_connection(struct client_state *csp, char **header);
141 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
143 static jb_err client_host_adder (struct client_state *csp);
144 static jb_err client_xtra_adder (struct client_state *csp);
145 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
146 static jb_err client_connection_header_adder(struct client_state *csp);
147 static jb_err server_connection_adder(struct client_state *csp);
148 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
149 static jb_err server_proxy_connection_adder(struct client_state *csp);
150 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
151 static jb_err proxy_authentication(struct client_state *csp, char **header);
153 static jb_err create_forged_referrer(char **header, const char *hostport);
154 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
155 static jb_err handle_conditional_hide_referrer_parameter(char **header,
156 const char *host, const int parameter_conditional_block);
157 static void create_content_length_header(unsigned long long content_length,
158 char *header, size_t buffer_length);
161 * List of functions to run on a list of headers.
165 /** The header prefix to match */
168 /** The length of the prefix to match */
171 /** The function to apply to this line */
172 const parser_func_ptr parser;
175 static const struct parsers client_patterns[] = {
176 { "referer:", 8, client_referrer },
177 { "user-agent:", 11, client_uagent },
178 { "ua-", 3, client_ua },
179 { "from:", 5, client_from },
180 { "cookie:", 7, client_send_cookie },
181 { "x-forwarded-for:", 16, client_x_forwarded },
182 { "Accept-Encoding:", 16, client_accept_encoding },
183 { "TE:", 3, client_te },
184 { "Host:", 5, client_host },
185 { "if-modified-since:", 18, client_if_modified_since },
186 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
187 { "Keep-Alive:", 11, client_keep_alive },
188 { "Content-Length:", 15, client_save_content_length },
189 { "Proxy-Connection:", 17, client_proxy_connection },
191 { "Keep-Alive:", 11, crumble },
192 { "Proxy-Connection:", 17, crumble },
194 { "connection:", 11, client_connection },
195 { "max-forwards:", 13, client_max_forwards },
196 { "Accept-Language:", 16, client_accept_language },
197 { "if-none-match:", 14, client_if_none_match },
198 { "Range:", 6, client_range },
199 { "Request-Range:", 14, client_range },
200 { "If-Range:", 9, client_range },
201 { "X-Filter:", 9, client_x_filter },
202 { "Proxy-Authorization:", 20, proxy_authentication },
204 { "Transfer-Encoding:", 18, client_transfer_encoding },
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_socket
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.
260 * Returns : On success, the number of bytes written are returned (zero
261 * indicates nothing was written). On error, -1 is returned,
262 * and errno is set appropriately. If count is zero and the
263 * file descriptor refers to a regular file, 0 will be
264 * returned without causing any other effect. For a special
265 * file, the results are not portable.
267 *********************************************************************/
268 long flush_socket(jb_socket fd, struct iob *iob)
270 long len = iob->eod - iob->cur;
277 if (write_socket(fd, iob->cur, (size_t)len))
281 iob->eod = iob->cur = iob->buf;
287 /*********************************************************************
289 * Function : add_to_iob
291 * Description : Add content to the buffer, expanding the
292 * buffer if necessary.
295 * 1 : iob = Destination buffer.
296 * 2 : buffer_limit = Limit to which the destination may grow
297 * 3 : src = holds the content to be added
298 * 4 : n = number of bytes to be added
300 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
301 * or buffer limit reached.
303 *********************************************************************/
304 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
306 size_t used, offset, need;
309 if (n <= 0) return JB_ERR_OK;
311 used = (size_t)(iob->eod - iob->buf);
312 offset = (size_t)(iob->cur - iob->buf);
313 need = used + (size_t)n + 1;
316 * If the buffer can't hold the new data, extend it first.
317 * Use the next power of two if possible, else use the actual need.
319 if (need > buffer_limit)
321 log_error(LOG_LEVEL_INFO,
322 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
324 return JB_ERR_MEMORY;
327 if (need > iob->size)
329 size_t want = iob->size ? iob->size : 512;
336 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
340 else if (NULL != (p = (char *)realloc(iob->buf, need)))
346 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
347 return JB_ERR_MEMORY;
350 /* Update the iob pointers */
351 iob->cur = p + offset;
356 /* copy the new data into the iob buffer */
357 memcpy(iob->eod, src, (size_t)n);
359 /* point to the end of the data */
362 /* null terminate == cheap insurance */
370 /*********************************************************************
372 * Function : clear_iob
374 * Description : Frees the memory allocated for an I/O buffer and
375 * resets the structure.
378 * 1 : iob = I/O buffer to clear.
380 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
381 * or buffer limit reached.
383 *********************************************************************/
384 void clear_iob(struct iob *iob)
387 memset(iob, '\0', sizeof(*iob));;
392 /*********************************************************************
394 * Function : decompress_iob
396 * Description : Decompress buffered page, expanding the
397 * buffer as necessary. csp->iob->cur
398 * should point to the the beginning of the
399 * compressed data block.
402 * 1 : csp = Current client state (buffers, headers, etc...)
404 * Returns : JB_ERR_OK on success,
405 * JB_ERR_MEMORY if out-of-memory limit reached, and
406 * JB_ERR_COMPRESS if error decompressing buffer.
408 *********************************************************************/
409 jb_err decompress_iob(struct client_state *csp)
411 char *buf; /* new, uncompressed buffer */
412 char *cur; /* Current iob position (to keep the original
413 * iob->cur unmodified if we return early) */
414 size_t bufsize; /* allocated size of the new buffer */
415 size_t old_size; /* Content size before decompression */
416 size_t skip_size; /* Number of bytes at the beginning of the iob
417 that we should NOT decompress. */
418 int status; /* return status of the inflate() call */
419 z_stream zstr; /* used by calls to zlib */
421 assert(csp->iob->cur - csp->iob->buf > 0);
422 assert(csp->iob->eod - csp->iob->cur > 0);
424 bufsize = csp->iob->size;
425 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
426 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
430 if (bufsize < (size_t)10)
433 * This is to protect the parsing of gzipped data,
434 * but it should(?) be valid for deflated data also.
436 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
437 return JB_ERR_COMPRESS;
440 if (csp->content_type & CT_GZIP)
443 * Our task is slightly complicated by the facts that data
444 * compressed by gzip does not include a zlib header, and
445 * that there is no easily accessible interface in zlib to
446 * handle a gzip header. We strip off the gzip header by
447 * hand, and later inform zlib not to expect a header.
451 * Strip off the gzip header. Please see RFC 1952 for more
452 * explanation of the appropriate fields.
454 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
455 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
456 || (*cur++ != Z_DEFLATED))
458 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
459 return JB_ERR_COMPRESS;
464 if (flags & GZIP_FLAG_RESERVED_BITS)
466 /* The gzip header has reserved bits set; bail out. */
467 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
468 return JB_ERR_COMPRESS;
472 * Skip mtime (4 bytes), extra flags (1 byte)
473 * and OS type (1 byte).
477 /* Skip extra fields if necessary. */
478 if (flags & GZIP_FLAG_EXTRA_FIELDS)
481 * Skip a given number of bytes, specified
482 * as a 16-bit little-endian value.
484 * XXX: this code is untested and should probably be removed.
488 skip_bytes += *cur++ << 8;
491 * The number of bytes to skip should be positive
492 * and we'd like to stay in the buffer.
494 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
496 log_error(LOG_LEVEL_ERROR,
497 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
499 return JB_ERR_COMPRESS;
501 log_error(LOG_LEVEL_INFO,
502 "Skipping %d bytes for gzip compression. Does this sound right?",
507 /* Skip the filename if necessary. */
508 if (flags & GZIP_FLAG_FILE_NAME)
510 /* A null-terminated string is supposed to follow. */
511 while (*cur++ && (cur < csp->iob->eod));
514 /* Skip the comment if necessary. */
515 if (flags & GZIP_FLAG_COMMENT)
517 /* A null-terminated string is supposed to follow. */
518 while (*cur++ && (cur < csp->iob->eod));
521 /* Skip the CRC if necessary. */
522 if (flags & GZIP_FLAG_CHECKSUM)
527 if (cur >= csp->iob->eod)
530 * If the current position pointer reached or passed
531 * the buffer end, we were obviously tricked to skip
534 log_error(LOG_LEVEL_ERROR,
535 "Malformed gzip header detected. Aborting decompression.");
536 return JB_ERR_COMPRESS;
540 else if (csp->content_type & CT_DEFLATE)
543 * In theory (that is, according to RFC 1950), deflate-compressed
544 * data should begin with a two-byte zlib header and have an
545 * adler32 checksum at the end. It seems that in practice only
546 * the raw compressed data is sent. Note that this means that
547 * we are not RFC 1950-compliant here, but the advantage is that
548 * this actually works. :)
550 * We add a dummy null byte to tell zlib where the data ends,
551 * and later inform it not to expect a header.
553 * Fortunately, add_to_iob() has thoughtfully null-terminated
554 * the buffer; we can just increment the end pointer to include
561 log_error(LOG_LEVEL_ERROR,
562 "Unable to determine compression format for decompression");
563 return JB_ERR_COMPRESS;
566 /* Set up the fields required by zlib. */
567 zstr.next_in = (Bytef *)cur;
568 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
569 zstr.zalloc = Z_NULL;
571 zstr.opaque = Z_NULL;
574 * Passing -MAX_WBITS to inflateInit2 tells the library
575 * that there is no zlib header.
577 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
579 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
580 return JB_ERR_COMPRESS;
584 * Next, we allocate new storage for the inflated data.
585 * We don't modify the existing iob yet, so in case there
586 * is error in decompression we can recover gracefully.
588 buf = zalloc(bufsize);
591 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
592 return JB_ERR_MEMORY;
595 assert(bufsize >= skip_size);
596 memcpy(buf, csp->iob->buf, skip_size);
597 zstr.avail_out = (uInt)(bufsize - skip_size);
598 zstr.next_out = (Bytef *)buf + skip_size;
600 /* Try to decompress the whole stream in one shot. */
601 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
603 /* We need to allocate more memory for the output buffer. */
605 char *tmpbuf; /* used for realloc'ing the buffer */
606 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
608 if (0 == zstr.avail_in)
611 * If zlib wants more data then there's a problem, because
612 * the complete compressed file should have been buffered.
614 log_error(LOG_LEVEL_ERROR,
615 "Unexpected end of compressed iob. Using what we got so far.");
620 * If we reached the buffer limit and still didn't have enough
621 * memory, just give up. Due to the ceiling enforced by the next
622 * if block we could actually check for equality here, but as it
623 * can be easily mistaken for a bug we don't.
625 if (bufsize >= csp->config->buffer_limit)
627 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
628 return JB_ERR_MEMORY;
631 /* Try doubling the buffer size each time. */
634 /* Don't exceed the buffer limit. */
635 if (bufsize > csp->config->buffer_limit)
637 bufsize = csp->config->buffer_limit;
640 /* Try to allocate the new buffer. */
641 tmpbuf = realloc(buf, bufsize);
644 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
646 return JB_ERR_MEMORY;
650 char *oldnext_out = (char *)zstr.next_out;
653 * Update the fields for inflate() to use the new
654 * buffer, which may be in a location different from
657 zstr.avail_out += (uInt)(bufsize - oldbufsize);
658 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
661 * Compare with an uglier method of calculating these values
662 * that doesn't require the extra oldbufsize variable.
664 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
665 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
671 if (Z_STREAM_ERROR == inflateEnd(&zstr))
673 log_error(LOG_LEVEL_ERROR,
674 "Inconsistent stream state after decompression: %s", zstr.msg);
676 * XXX: Intentionally no return.
678 * According to zlib.h, Z_STREAM_ERROR is returned
679 * "if the stream state was inconsistent".
681 * I assume in this case inflate()'s status
682 * would also be something different than Z_STREAM_END
683 * so this check should be redundant, but lets see.
687 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
690 * We failed to decompress the stream and it's
691 * not simply because of missing data.
693 log_error(LOG_LEVEL_ERROR,
694 "Unexpected error while decompressing to the buffer (iob): %s",
696 return JB_ERR_COMPRESS;
700 * Finally, we can actually update the iob, since the
701 * decompression was successful. First, free the old
704 freez(csp->iob->buf);
706 /* Now, update the iob to use the new buffer. */
708 csp->iob->cur = csp->iob->buf + skip_size;
709 csp->iob->eod = (char *)zstr.next_out;
710 csp->iob->size = bufsize;
713 * Make sure the new uncompressed iob obeys some minimal
714 * consistency conditions.
716 if ((csp->iob->buf < csp->iob->cur)
717 && (csp->iob->cur <= csp->iob->eod)
718 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
720 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
721 if (new_size > (size_t)0)
723 log_error(LOG_LEVEL_RE_FILTER,
724 "Decompression successful. Old size: %d, new size: %d.",
729 /* zlib thinks this is OK, so lets do the same. */
730 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
735 /* It seems that zlib did something weird. */
736 log_error(LOG_LEVEL_ERROR,
737 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
738 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
739 csp->iob->eod, csp->iob->buf + csp->iob->size);
740 return JB_ERR_COMPRESS;
746 #endif /* defined(FEATURE_ZLIB) */
749 /*********************************************************************
751 * Function : normalize_lws
753 * Description : Reduces unquoted linear white space in headers
754 * to a single space in accordance with RFC 2616 2.2.
755 * This simplifies parsing and filtering later on.
757 * XXX: Remove log messages before
758 * the next stable release?
761 * 1 : header = A header with linear white space to reduce.
765 *********************************************************************/
766 static void normalize_lws(char *header)
772 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
776 while (privoxy_isspace(*q))
780 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
786 log_error(LOG_LEVEL_HEADER,
787 "Converting tab to space in '%s'", header);
792 char *end_of_token = strstr(p+1, "\"");
794 if (NULL != end_of_token)
796 /* Don't mess with quoted text. */
801 log_error(LOG_LEVEL_HEADER,
802 "Ignoring single quote in '%s'", header);
808 p = strchr(header, ':');
809 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
812 * There's still space before the colon.
820 /*********************************************************************
822 * Function : get_header
824 * Description : This (odd) routine will parse the csp->iob
825 * to get the next complete header.
828 * 1 : iob = The I/O buffer to parse, usually csp->iob.
830 * Returns : Any one of the following:
832 * 1) a pointer to a dynamically allocated string that contains a header line
833 * 2) NULL indicating that the end of the header was reached
834 * 3) "" indicating that the end of the iob was reached before finding
835 * a complete header line.
837 *********************************************************************/
838 char *get_header(struct iob *iob)
842 header = get_header_line(iob);
844 if ((header == NULL) || (*header == '\0'))
847 * No complete header read yet, tell the client.
852 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
855 * Header spans multiple lines, append the next one.
857 char *continued_header;
859 continued_header = get_header_line(iob);
860 if ((continued_header == NULL) || (*continued_header == '\0'))
863 * No complete header read yet, return what we got.
864 * XXX: Should "unread" header instead.
866 log_error(LOG_LEVEL_INFO,
867 "Failed to read a multi-line header properly: '%s'",
872 if (JB_ERR_OK != string_join(&header, continued_header))
874 log_error(LOG_LEVEL_FATAL,
875 "Out of memory while appending multiple headers.");
879 /* XXX: remove before next stable release. */
880 log_error(LOG_LEVEL_HEADER,
881 "Merged multiple header lines to: '%s'",
886 normalize_lws(header);
893 /*********************************************************************
895 * Function : get_header_line
897 * Description : This (odd) routine will parse the csp->iob
898 * to get the next header line.
901 * 1 : iob = The I/O buffer to parse, usually csp->iob.
903 * Returns : Any one of the following:
905 * 1) a pointer to a dynamically allocated string that contains a header line
906 * 2) NULL indicating that the end of the header was reached
907 * 3) "" indicating that the end of the iob was reached before finding
908 * a complete header line.
910 *********************************************************************/
911 static char *get_header_line(struct iob *iob)
915 if ((iob->cur == NULL)
916 || ((p = strchr(iob->cur, '\n')) == NULL))
918 return(""); /* couldn't find a complete header */
923 ret = strdup(iob->cur);
926 /* FIXME No way to handle error properly */
927 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
933 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
935 /* is this a blank line (i.e. the end of the header) ? */
947 /*********************************************************************
949 * Function : get_header_value
951 * Description : Get the value of a given header from a chained list
952 * of header lines or return NULL if no such header is
953 * present in the list.
956 * 1 : header_list = pointer to list
957 * 2 : header_name = string with name of header to look for.
958 * Trailing colon required, capitalization
961 * Returns : NULL if not found, else value of header
963 *********************************************************************/
964 char *get_header_value(const struct list *header_list, const char *header_name)
966 struct list_entry *cur_entry;
972 length = strlen(header_name);
974 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
978 if (!strncmpic(cur_entry->str, header_name, length))
981 * Found: return pointer to start of value
983 ret = cur_entry->str + length;
984 while (*ret && privoxy_isspace(*ret)) ret++;
998 /*********************************************************************
1000 * Function : scan_headers
1002 * Description : Scans headers, applies tags and updates action bits.
1005 * 1 : csp = Current client state (buffers, headers, etc...)
1007 * Returns : JB_ERR_OK
1009 *********************************************************************/
1010 static jb_err scan_headers(struct client_state *csp)
1012 struct list_entry *h; /* Header */
1013 jb_err err = JB_ERR_OK;
1015 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1017 /* Header crunch()ed in previous run? -> ignore */
1018 if (h->str == NULL) continue;
1019 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1020 err = header_tagger(csp, h->str);
1027 /*********************************************************************
1029 * Function : enforce_header_order
1031 * Description : Enforces a given header order.
1034 * 1 : headers = List of headers to order.
1035 * 2 : ordered_headers = List of ordered header names.
1039 *********************************************************************/
1040 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1042 struct list_entry *sorted_header;
1043 struct list new_headers[1];
1044 struct list_entry *header;
1046 init_list(new_headers);
1048 /* The request line is always the first "header" */
1050 assert(NULL != headers->first->str);
1051 enlist(new_headers, headers->first->str);
1052 freez(headers->first->str)
1054 /* Enlist the specified headers in the given order */
1056 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1057 sorted_header = sorted_header->next)
1059 const size_t sorted_header_length = strlen(sorted_header->str);
1060 for (header = headers->first; header != NULL; header = header->next)
1062 /* Header enlisted in previous run? -> ignore */
1063 if (header->str == NULL) continue;
1065 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1066 && (header->str[sorted_header_length] == ':'))
1068 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1069 if (JB_ERR_OK != enlist(new_headers, header->str))
1071 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1078 /* Enlist the rest of the headers behind the ordered ones */
1079 for (header = headers->first; header != NULL; header = header->next)
1081 /* Header enlisted in previous run? -> ignore */
1082 if (header->str == NULL) continue;
1084 log_error(LOG_LEVEL_HEADER,
1085 "Enlisting left-over header %s", header->str);
1086 if (JB_ERR_OK != enlist(new_headers, header->str))
1088 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1093 list_remove_all(headers);
1094 list_duplicate(headers, new_headers);
1095 list_remove_all(new_headers);
1101 /*********************************************************************
1105 * Description : add, delete or modify lines in the HTTP header streams.
1106 * On entry, it receives a linked list of headers space
1107 * that was allocated dynamically (both the list nodes
1108 * and the header contents).
1110 * As a side effect it frees the space used by the original
1114 * 1 : csp = Current client state (buffers, headers, etc...)
1115 * 2 : filter_server_headers = Boolean to switch between
1116 * server and header filtering.
1118 * Returns : JB_ERR_OK in case off success, or
1119 * JB_ERR_MEMORY on out-of-memory error.
1121 *********************************************************************/
1122 jb_err sed(struct client_state *csp, int filter_server_headers)
1124 /* XXX: use more descriptive names. */
1125 struct list_entry *p;
1126 const struct parsers *v;
1127 const add_header_func_ptr *f;
1128 jb_err err = JB_ERR_OK;
1132 if (filter_server_headers)
1134 v = server_patterns;
1135 f = add_server_headers;
1136 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1140 v = client_patterns;
1141 f = add_client_headers;
1142 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1145 while ((err == JB_ERR_OK) && (v->str != NULL))
1147 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1149 /* Header crunch()ed in previous run? -> ignore */
1150 if (p->str == NULL) continue;
1152 /* Does the current parser handle this header? */
1153 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1154 (v->len == CHECK_EVERY_HEADER_REMAINING))
1156 err = v->parser(csp, &(p->str));
1162 /* place additional headers on the csp->headers list */
1163 while ((err == JB_ERR_OK) && (*f))
1169 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1171 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1178 /*********************************************************************
1180 * Function : update_server_headers
1182 * Description : Updates server headers after the body has been modified.
1185 * 1 : csp = Current client state (buffers, headers, etc...)
1187 * Returns : JB_ERR_OK in case off success, or
1188 * JB_ERR_MEMORY on out-of-memory error.
1190 *********************************************************************/
1191 jb_err update_server_headers(struct client_state *csp)
1193 jb_err err = JB_ERR_OK;
1195 static const struct parsers server_patterns_light[] = {
1196 { "Content-Length:", 15, server_adjust_content_length },
1197 { "Transfer-Encoding:", 18, server_transfer_coding },
1199 { "Content-Encoding:", 17, server_adjust_content_encoding },
1200 #endif /* def FEATURE_ZLIB */
1204 if (strncmpic(csp->http->cmd, "HEAD", 4))
1206 const struct parsers *v;
1207 struct list_entry *p;
1209 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1211 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1213 /* Header crunch()ed in previous run? -> ignore */
1214 if (p->str == NULL) continue;
1216 /* Does the current parser handle this header? */
1217 if (strncmpic(p->str, v->str, v->len) == 0)
1219 err = v->parser(csp, (char **)&(p->str));
1225 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1226 if ((JB_ERR_OK == err)
1227 && (csp->flags & CSP_FLAG_MODIFIED)
1228 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1229 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1233 create_content_length_header(csp->content_length, header, sizeof(header));
1234 err = enlist(csp->headers, header);
1235 if (JB_ERR_OK == err)
1237 log_error(LOG_LEVEL_HEADER,
1238 "Content modified with no Content-Length header set. "
1239 "Created: %s.", header);
1240 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1243 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1245 #ifdef FEATURE_COMPRESSION
1246 if ((JB_ERR_OK == err)
1247 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1249 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1250 if (JB_ERR_OK == err)
1252 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1261 /*********************************************************************
1263 * Function : header_tagger
1265 * Description : Executes all text substitutions from applying
1266 * tag actions and saves the result as tag.
1268 * XXX: Shares enough code with filter_header() and
1269 * pcrs_filter_response() to warrant some helper functions.
1272 * 1 : csp = Current client state (buffers, headers, etc...)
1273 * 2 : header = Header that is used as tagger input
1275 * Returns : JB_ERR_OK on success and always succeeds
1277 *********************************************************************/
1278 static jb_err header_tagger(struct client_state *csp, char *header)
1280 int wanted_filter_type;
1281 int multi_action_index;
1284 struct re_filterfile_spec *b;
1285 struct list_entry *tag_name;
1287 const size_t header_length = strlen(header);
1289 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1291 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1292 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1296 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1297 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1300 if (list_is_empty(csp->action->multi[multi_action_index])
1301 || filters_available(csp) == FALSE)
1303 /* Return early if no taggers apply or if none are available. */
1307 /* Execute all applying taggers */
1308 for (tag_name = csp->action->multi[multi_action_index]->first;
1309 NULL != tag_name; tag_name = tag_name->next)
1311 char *modified_tag = NULL;
1313 size_t size = header_length;
1316 b = get_filter(csp, tag_name->str, wanted_filter_type);
1322 joblist = b->joblist;
1324 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1326 if (NULL == joblist)
1328 log_error(LOG_LEVEL_RE_FILTER,
1329 "Tagger %s has empty joblist. Nothing to do.", b->name);
1333 /* execute their pcrs_joblist on the header. */
1334 for (job = joblist; NULL != job; job = job->next)
1336 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1340 /* Success, continue with the modified version. */
1349 /* Tagger doesn't match */
1352 /* Regex failure, log it but continue anyway. */
1353 assert(NULL != header);
1354 log_error(LOG_LEVEL_ERROR,
1355 "Problems with tagger \'%s\' and header \'%s\': %s",
1356 b->name, *header, pcrs_strerror(hits));
1358 freez(modified_tag);
1362 if (b->dynamic) pcrs_free_joblist(joblist);
1364 /* If this tagger matched */
1370 * There is no technical limitation which makes
1371 * it impossible to use empty tags, but I assume
1372 * no one would do it intentionally.
1375 log_error(LOG_LEVEL_INFO,
1376 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1380 if (!list_contains_item(csp->tags, tag))
1382 if (JB_ERR_OK != enlist(csp->tags, tag))
1384 log_error(LOG_LEVEL_ERROR,
1385 "Insufficient memory to add tag \'%s\', "
1386 "based on tagger \'%s\' and header \'%s\'",
1387 tag, b->name, *header);
1391 char *action_message;
1393 * update the action bits right away, to make
1394 * tagging based on tags set by earlier taggers
1395 * of the same kind possible.
1397 if (update_action_bits_for_tag(csp, tag))
1399 action_message = "Action bits updated accordingly.";
1403 action_message = "No action bits update necessary.";
1406 log_error(LOG_LEVEL_HEADER,
1407 "Tagger \'%s\' added tag \'%s\'. %s",
1408 b->name, tag, action_message);
1413 /* XXX: Is this log-worthy? */
1414 log_error(LOG_LEVEL_HEADER,
1415 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1425 /* here begins the family of parser functions that reformat header lines */
1427 /*********************************************************************
1429 * Function : filter_header
1431 * Description : Executes all text substitutions from all applying
1432 * +(server|client)-header-filter actions on the header.
1433 * Most of the code was copied from pcrs_filter_response,
1434 * including the rather short variable names
1437 * 1 : csp = Current client state (buffers, headers, etc...)
1438 * 2 : header = On input, pointer to header to modify.
1439 * On output, pointer to the modified header, or NULL
1440 * to remove the header. This function frees the
1441 * original string if necessary.
1443 * Returns : JB_ERR_OK on success and always succeeds
1445 *********************************************************************/
1446 static jb_err filter_header(struct client_state *csp, char **header)
1450 size_t size = strlen(*header);
1452 char *newheader = NULL;
1455 struct re_filterfile_spec *b;
1456 struct list_entry *filtername;
1458 int wanted_filter_type;
1459 int multi_action_index;
1461 if (csp->flags & CSP_FLAG_NO_FILTERING)
1466 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1468 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1469 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1473 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1474 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1477 if (list_is_empty(csp->action->multi[multi_action_index])
1478 || filters_available(csp) == FALSE)
1480 /* Return early if no filters apply or if none are available. */
1484 /* Execute all applying header filters */
1485 for (filtername = csp->action->multi[multi_action_index]->first;
1486 filtername != NULL; filtername = filtername->next)
1488 int current_hits = 0;
1491 b = get_filter(csp, filtername->str, wanted_filter_type);
1497 joblist = b->joblist;
1499 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1501 if (NULL == joblist)
1503 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1507 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1508 *header, size, b->name);
1510 /* Apply all jobs from the joblist */
1511 for (job = joblist; NULL != job; job = job->next)
1513 matches = pcrs_execute(job, *header, size, &newheader, &size);
1516 current_hits += matches;
1517 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1519 *header = newheader;
1521 else if (0 == matches)
1523 /* Filter doesn't change header */
1529 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1530 *header, b->name, pcrs_strerror(matches));
1531 if (newheader != NULL)
1533 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1539 if (b->dynamic) pcrs_free_joblist(joblist);
1541 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1542 hits += current_hits;
1546 * Additionally checking for hits is important because if
1547 * the continue hack is triggered, server headers can
1548 * arrive empty to separate multiple heads from each other.
1550 if ((0 == size) && hits)
1552 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1560 /*********************************************************************
1562 * Function : server_connection
1564 * Description : Makes sure a proper "Connection:" header is
1565 * set and signals connection_header_adder to
1569 * 1 : csp = Current client state (buffers, headers, etc...)
1570 * 2 : header = On input, pointer to header to modify.
1571 * On output, pointer to the modified header, or NULL
1572 * to remove the header. This function frees the
1573 * original string if necessary.
1575 * Returns : JB_ERR_OK on success.
1577 *********************************************************************/
1578 static jb_err server_connection(struct client_state *csp, char **header)
1580 if (!strcmpic(*header, "Connection: keep-alive")
1581 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1582 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1586 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1587 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1589 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1592 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1594 log_error(LOG_LEVEL_HEADER,
1595 "Keeping the server header '%s' around.", *header);
1598 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1600 char *old_header = *header;
1602 *header = strdup_or_die("Connection: close");
1603 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1608 /* Signal server_connection_adder() to return early. */
1609 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1615 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1616 /*********************************************************************
1618 * Function : server_keep_alive
1620 * Description : Stores the server's keep alive timeout.
1623 * 1 : csp = Current client state (buffers, headers, etc...)
1624 * 2 : header = On input, pointer to header to modify.
1625 * On output, pointer to the modified header, or NULL
1626 * to remove the header. This function frees the
1627 * original string if necessary.
1629 * Returns : JB_ERR_OK.
1631 *********************************************************************/
1632 static jb_err server_keep_alive(struct client_state *csp, char **header)
1634 unsigned int keep_alive_timeout;
1635 const char *timeout_position = strstr(*header, "timeout=");
1637 if ((NULL == timeout_position)
1638 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1640 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1644 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1646 log_error(LOG_LEVEL_HEADER,
1647 "Reducing keep-alive timeout from %u to %u.",
1648 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1649 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1653 /* XXX: Is this log worthy? */
1654 log_error(LOG_LEVEL_HEADER,
1655 "Server keep-alive timeout is %u. Sticking with %u.",
1656 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1658 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1665 /*********************************************************************
1667 * Function : server_proxy_connection
1669 * Description : Figures out whether or not we should add a
1670 * Proxy-Connection header.
1673 * 1 : csp = Current client state (buffers, headers, etc...)
1674 * 2 : header = On input, pointer to header to modify.
1675 * On output, pointer to the modified header, or NULL
1676 * to remove the header. This function frees the
1677 * original string if necessary.
1679 * Returns : JB_ERR_OK.
1681 *********************************************************************/
1682 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1684 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1689 /*********************************************************************
1691 * Function : proxy_authentication
1693 * Description : Removes headers that are relevant for proxy
1694 * authentication unless forwarding them has
1695 * been explicitly requested.
1698 * 1 : csp = Current client state (buffers, headers, etc...)
1699 * 2 : header = On input, pointer to header to modify.
1700 * On output, pointer to the modified header, or NULL
1701 * to remove the header. This function frees the
1702 * original string if necessary.
1704 * Returns : JB_ERR_OK.
1706 *********************************************************************/
1707 static jb_err proxy_authentication(struct client_state *csp, char **header)
1709 if ((csp->config->feature_flags &
1710 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1711 log_error(LOG_LEVEL_HEADER,
1712 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1719 /*********************************************************************
1721 * Function : client_keep_alive
1723 * Description : Stores the client's keep alive timeout.
1726 * 1 : csp = Current client state (buffers, headers, etc...)
1727 * 2 : header = On input, pointer to header to modify.
1728 * On output, pointer to the modified header, or NULL
1729 * to remove the header. This function frees the
1730 * original string if necessary.
1732 * Returns : JB_ERR_OK.
1734 *********************************************************************/
1735 static jb_err client_keep_alive(struct client_state *csp, char **header)
1737 unsigned int keep_alive_timeout;
1738 char *timeout_position;
1740 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1742 log_error(LOG_LEVEL_HEADER,
1743 "keep-alive support is disabled. Crunching: %s.", *header);
1748 /* Check for parameter-less format "Keep-Alive: 100" */
1749 timeout_position = strstr(*header, ": ");
1750 if ((NULL == timeout_position)
1751 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1753 /* Assume parameter format "Keep-Alive: timeout=100" */
1754 timeout_position = strstr(*header, "timeout=");
1755 if ((NULL == timeout_position)
1756 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1758 log_error(LOG_LEVEL_HEADER,
1759 "Couldn't parse: '%s'. Using default timeout %u",
1760 *header, csp->config->keep_alive_timeout);
1767 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1769 log_error(LOG_LEVEL_HEADER,
1770 "Reducing keep-alive timeout from %u to %u.",
1771 csp->config->keep_alive_timeout, keep_alive_timeout);
1772 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1776 /* XXX: Is this log worthy? */
1777 log_error(LOG_LEVEL_HEADER,
1778 "Client keep-alive timeout is %u. Sticking with %u.",
1779 keep_alive_timeout, csp->config->keep_alive_timeout);
1787 /*********************************************************************
1789 * Function : get_content_length
1791 * Description : Gets the content length specified in a
1792 * Content-Length header.
1795 * 1 : header_value = The Content-Length header value.
1796 * 2 : length = Storage to return the value.
1798 * Returns : JB_ERR_OK on success, or
1799 * JB_ERR_PARSE if no value is recognized.
1801 *********************************************************************/
1802 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1805 assert(sizeof(unsigned long long) > 4);
1806 if (1 != sscanf(header_value, "%I64u", length))
1808 if (1 != sscanf(header_value, "%llu", length))
1811 return JB_ERR_PARSE;
1818 /*********************************************************************
1820 * Function : client_save_content_length
1822 * Description : Save the Content-Length sent by the client.
1825 * 1 : csp = Current client state (buffers, headers, etc...)
1826 * 2 : header = On input, pointer to header to modify.
1827 * On output, pointer to the modified header, or NULL
1828 * to remove the header. This function frees the
1829 * original string if necessary.
1831 * Returns : JB_ERR_OK on success, or
1832 * JB_ERR_MEMORY on out-of-memory error.
1834 *********************************************************************/
1835 static jb_err client_save_content_length(struct client_state *csp, char **header)
1837 unsigned long long content_length = 0;
1838 const char *header_value;
1840 assert(*(*header+14) == ':');
1842 header_value = *header + 15;
1843 if (JB_ERR_OK != get_content_length(header_value, &content_length))
1845 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1850 csp->expected_client_content_length = content_length;
1855 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1859 /*********************************************************************
1861 * Function : client_connection
1863 * Description : Makes sure a proper "Connection:" header is
1864 * set and signals connection_header_adder
1868 * 1 : csp = Current client state (buffers, headers, etc...)
1869 * 2 : header = On input, pointer to header to modify.
1870 * On output, pointer to the modified header, or NULL
1871 * to remove the header. This function frees the
1872 * original string if necessary.
1874 * Returns : JB_ERR_OK on success.
1876 *********************************************************************/
1877 static jb_err client_connection(struct client_state *csp, char **header)
1879 static const char connection_close[] = "Connection: close";
1881 if (!strcmpic(*header, connection_close))
1883 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1884 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1885 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1887 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1889 log_error(LOG_LEVEL_HEADER,
1890 "Removing \'%s\' to imply keep-alive.", *header);
1893 * While we imply keep-alive to the server,
1894 * we have to remember that the client didn't.
1896 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1900 char *old_header = *header;
1902 *header = strdup_or_die("Connection: keep-alive");
1903 log_error(LOG_LEVEL_HEADER,
1904 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1910 log_error(LOG_LEVEL_HEADER,
1911 "Keeping the client header '%s' around. "
1912 "The connection will not be kept alive.",
1914 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1917 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1918 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1920 log_error(LOG_LEVEL_HEADER,
1921 "Keeping the client header '%s' around. "
1922 "The server connection will be kept alive if possible.",
1924 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1925 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1929 char *old_header = *header;
1931 *header = strdup_or_die(connection_close);
1932 log_error(LOG_LEVEL_HEADER,
1933 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1937 /* Signal client_connection_header_adder() to return early. */
1938 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1944 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1945 /*********************************************************************
1947 * Function : client_proxy_connection
1949 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
1950 * appropriate and removes the Proxy-Connection
1954 * 1 : csp = Current client state (buffers, headers, etc...)
1955 * 2 : header = On input, pointer to header to modify.
1956 * On output, pointer to the modified header, or NULL
1957 * to remove the header. This function frees the
1958 * original string if necessary.
1960 * Returns : JB_ERR_OK
1962 *********************************************************************/
1963 static jb_err client_proxy_connection(struct client_state *csp, char **header)
1965 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1966 && (csp->http->ssl == 0)
1967 && (NULL == strstr(*header, "close")))
1969 log_error(LOG_LEVEL_HEADER,
1970 "The client connection can be kept alive due to: %s", *header);
1971 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1973 crumble(csp, header);
1977 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1980 /*********************************************************************
1982 * Function : client_transfer_encoding
1984 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
1985 * the request body is "chunked"
1987 * XXX: Currently not called through sed() as we
1988 * need the flag earlier on. Should be fixed.
1991 * 1 : csp = Current client state (buffers, headers, etc...)
1992 * 2 : header = On input, pointer to header to modify.
1993 * On output, pointer to the modified header, or NULL
1994 * to remove the header. This function frees the
1995 * original string if necessary.
1997 * Returns : JB_ERR_OK on success, or
1999 *********************************************************************/
2000 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2002 if (strstr(*header, "chunked"))
2004 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2005 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2012 /*********************************************************************
2014 * Function : crumble
2016 * Description : This is called if a header matches a pattern to "crunch"
2019 * 1 : csp = Current client state (buffers, headers, etc...)
2020 * 2 : header = On input, pointer to header to modify.
2021 * On output, pointer to the modified header, or NULL
2022 * to remove the header. This function frees the
2023 * original string if necessary.
2025 * Returns : JB_ERR_OK on success, or
2026 * JB_ERR_MEMORY on out-of-memory error.
2028 *********************************************************************/
2029 static jb_err crumble(struct client_state *csp, char **header)
2032 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2038 /*********************************************************************
2040 * Function : crunch_server_header
2042 * Description : Crunch server header if it matches a string supplied by the
2043 * user. Called from `sed'.
2046 * 1 : csp = Current client state (buffers, headers, etc...)
2047 * 2 : header = On input, pointer to header to modify.
2048 * On output, pointer to the modified header, or NULL
2049 * to remove the header. This function frees the
2050 * original string if necessary.
2052 * Returns : JB_ERR_OK on success and always succeeds
2054 *********************************************************************/
2055 static jb_err crunch_server_header(struct client_state *csp, char **header)
2057 const char *crunch_pattern;
2059 /* Do we feel like crunching? */
2060 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2062 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2064 /* Is the current header the lucky one? */
2065 if (strstr(*header, crunch_pattern))
2067 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2076 /*********************************************************************
2078 * Function : server_content_type
2080 * Description : Set the content-type for filterable types (text/.*,
2081 * .*xml.*, .*script.* and image/gif) unless filtering has been
2082 * forbidden (CT_TABOO) while parsing earlier headers.
2083 * NOTE: Since text/plain is commonly used by web servers
2084 * for files whose correct type is unknown, we don't
2085 * set CT_TEXT for it.
2088 * 1 : csp = Current client state (buffers, headers, etc...)
2089 * 2 : header = On input, pointer to header to modify.
2090 * On output, pointer to the modified header, or NULL
2091 * to remove the header. This function frees the
2092 * original string if necessary.
2094 * Returns : JB_ERR_OK on success, or
2095 * JB_ERR_MEMORY on out-of-memory error.
2097 *********************************************************************/
2098 static jb_err server_content_type(struct client_state *csp, char **header)
2100 /* Remove header if it isn't the first Content-Type header */
2101 if ((csp->content_type & CT_DECLARED))
2103 if (content_filters_enabled(csp->action))
2106 * Making sure the client interprets the content the same way
2107 * Privoxy did is only relevant if Privoxy modified it.
2109 * Checking for this is "hard" as it's not yet known when
2110 * this function is called, thus go shopping and and just
2111 * check if Privoxy could filter it.
2113 * The main thing is that we don't mess with the headers
2114 * unless the user signalled that it's acceptable.
2116 log_error(LOG_LEVEL_HEADER,
2117 "Multiple Content-Type headers detected. "
2118 "Removing and ignoring: %s",
2126 * Signal that the Content-Type has been set.
2128 csp->content_type |= CT_DECLARED;
2130 if (!(csp->content_type & CT_TABOO))
2133 * XXX: The assumption that text/plain is a sign of
2134 * binary data seems to be somewhat unreasonable nowadays
2135 * and should be dropped after 3.0.8 is out.
2137 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2138 || strstr(*header, "xml")
2139 || strstr(*header, "script"))
2141 csp->content_type |= CT_TEXT;
2143 else if (strstr(*header, "image/gif"))
2145 csp->content_type |= CT_GIF;
2150 * Are we messing with the content type?
2152 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2155 * Make sure the user doesn't accidentally
2156 * change the content type of binary documents.
2158 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2161 *header = strdup_or_die("Content-Type: ");
2162 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2166 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2167 return JB_ERR_MEMORY;
2169 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2173 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2174 "It doesn't look like a content type that should be filtered. "
2175 "Enable force-text-mode if you know what you're doing.", *header);
2183 /*********************************************************************
2185 * Function : server_transfer_coding
2187 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2188 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2189 * - Remove header if body was chunked but has been
2190 * de-chunked for filtering.
2193 * 1 : csp = Current client state (buffers, headers, etc...)
2194 * 2 : header = On input, pointer to header to modify.
2195 * On output, pointer to the modified header, or NULL
2196 * to remove the header. This function frees the
2197 * original string if necessary.
2199 * Returns : JB_ERR_OK on success, or
2200 * JB_ERR_MEMORY on out-of-memory error.
2202 *********************************************************************/
2203 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2206 * Turn off pcrs and gif filtering if body compressed
2208 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2212 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2214 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2215 csp->http->cmd, *header);
2216 #endif /* def FEATURE_ZLIB */
2217 csp->content_type = CT_TABOO;
2221 * Raise flag if body chunked
2223 if (strstr(*header, "chunked"))
2225 csp->flags |= CSP_FLAG_CHUNKED;
2228 * If the body was modified, it has been de-chunked first
2229 * and the header must be removed.
2231 * FIXME: If there is more than one transfer encoding,
2232 * only the "chunked" part should be removed here.
2234 if (csp->flags & CSP_FLAG_MODIFIED)
2236 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2245 /*********************************************************************
2247 * Function : server_content_encoding
2249 * Description : Used to check if the content is compressed, and if
2250 * FEATURE_ZLIB is disabled, filtering is disabled as
2253 * If FEATURE_ZLIB is enabled and the compression type
2254 * supported, the content is marked for decompression.
2256 * XXX: Doesn't properly deal with multiple or with
2257 * unsupported but unknown encodings.
2258 * Is case-sensitive but shouldn't be.
2261 * 1 : csp = Current client state (buffers, headers, etc...)
2262 * 2 : header = On input, pointer to header to modify.
2263 * On output, pointer to the modified header, or NULL
2264 * to remove the header. This function frees the
2265 * original string if necessary.
2267 * Returns : JB_ERR_OK on success, or
2268 * JB_ERR_MEMORY on out-of-memory error.
2270 *********************************************************************/
2271 static jb_err server_content_encoding(struct client_state *csp, char **header)
2274 if (strstr(*header, "sdch"))
2277 * Shared Dictionary Compression over HTTP isn't supported,
2278 * filtering it anyway is pretty much guaranteed to mess up
2281 csp->content_type |= CT_TABOO;
2284 * Log a warning if the user expects the content to be filtered.
2286 if ((csp->rlist != NULL) &&
2287 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2289 log_error(LOG_LEVEL_INFO,
2290 "SDCH-compressed content detected, content filtering disabled. "
2291 "Consider suppressing SDCH offers made by the client.");
2294 else if (strstr(*header, "gzip"))
2296 /* Mark for gzip decompression */
2297 csp->content_type |= CT_GZIP;
2299 else if (strstr(*header, "deflate"))
2301 /* Mark for zlib decompression */
2302 csp->content_type |= CT_DEFLATE;
2304 else if (strstr(*header, "compress"))
2307 * We can't decompress this; therefore we can't filter
2310 csp->content_type |= CT_TABOO;
2312 #else /* !defined(FEATURE_ZLIB) */
2314 * XXX: Using a black list here isn't the right approach.
2316 * In case of SDCH, building with zlib support isn't
2319 if (strstr(*header, "gzip") ||
2320 strstr(*header, "compress") ||
2321 strstr(*header, "deflate") ||
2322 strstr(*header, "sdch"))
2325 * Body is compressed, turn off pcrs and gif filtering.
2327 csp->content_type |= CT_TABOO;
2330 * Log a warning if the user expects the content to be filtered.
2332 if ((csp->rlist != NULL) &&
2333 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2335 log_error(LOG_LEVEL_INFO,
2336 "Compressed content detected, content filtering disabled. "
2337 "Consider recompiling Privoxy with zlib support or "
2338 "enable the prevent-compression action.");
2341 #endif /* defined(FEATURE_ZLIB) */
2349 /*********************************************************************
2351 * Function : server_adjust_content_encoding
2353 * Description : Remove the Content-Encoding header if the
2354 * decompression was successful and the content
2358 * 1 : csp = Current client state (buffers, headers, etc...)
2359 * 2 : header = On input, pointer to header to modify.
2360 * On output, pointer to the modified header, or NULL
2361 * to remove the header. This function frees the
2362 * original string if necessary.
2364 * Returns : JB_ERR_OK on success, or
2365 * JB_ERR_MEMORY on out-of-memory error.
2367 *********************************************************************/
2368 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2370 if ((csp->flags & CSP_FLAG_MODIFIED)
2371 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2374 * We successfully decompressed the content,
2375 * and have to clean the header now, so the
2376 * client no longer expects compressed data.
2378 * XXX: There is a difference between cleaning
2379 * and removing it completely.
2381 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2388 #endif /* defined(FEATURE_ZLIB) */
2391 /*********************************************************************
2393 * Function : server_adjust_content_length
2395 * Description : Adjust Content-Length header if we modified
2399 * 1 : csp = Current client state (buffers, headers, etc...)
2400 * 2 : header = On input, pointer to header to modify.
2401 * On output, pointer to the modified header, or NULL
2402 * to remove the header. This function frees the
2403 * original string if necessary.
2405 * Returns : JB_ERR_OK on success, or
2406 * JB_ERR_MEMORY on out-of-memory error.
2408 *********************************************************************/
2409 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2411 /* Regenerate header if the content was modified. */
2412 if (csp->flags & CSP_FLAG_MODIFIED)
2414 const size_t header_length = 50;
2416 *header = malloc(header_length);
2417 if (*header == NULL)
2419 return JB_ERR_MEMORY;
2421 create_content_length_header(csp->content_length, *header, header_length);
2422 log_error(LOG_LEVEL_HEADER,
2423 "Adjusted Content-Length to %llu", csp->content_length);
2430 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2431 /*********************************************************************
2433 * Function : server_save_content_length
2435 * Description : Save the Content-Length sent by the server.
2438 * 1 : csp = Current client state (buffers, headers, etc...)
2439 * 2 : header = On input, pointer to header to modify.
2440 * On output, pointer to the modified header, or NULL
2441 * to remove the header. This function frees the
2442 * original string if necessary.
2444 * Returns : JB_ERR_OK on success, or
2445 * JB_ERR_MEMORY on out-of-memory error.
2447 *********************************************************************/
2448 static jb_err server_save_content_length(struct client_state *csp, char **header)
2450 unsigned long long content_length = 0;
2451 const char *header_value;
2453 assert(*(*header+14) == ':');
2455 header_value = *header + 15;
2456 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2458 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2463 csp->expected_content_length = content_length;
2464 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2465 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2470 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2473 /*********************************************************************
2475 * Function : server_content_md5
2477 * Description : Crumble any Content-MD5 headers if the document was
2478 * modified. FIXME: Should we re-compute instead?
2481 * 1 : csp = Current client state (buffers, headers, etc...)
2482 * 2 : header = On input, pointer to header to modify.
2483 * On output, pointer to the modified header, or NULL
2484 * to remove the header. This function frees the
2485 * original string if necessary.
2487 * Returns : JB_ERR_OK on success, or
2488 * JB_ERR_MEMORY on out-of-memory error.
2490 *********************************************************************/
2491 static jb_err server_content_md5(struct client_state *csp, char **header)
2493 if (csp->flags & CSP_FLAG_MODIFIED)
2495 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2503 /*********************************************************************
2505 * Function : server_content_disposition
2507 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2508 * Called from `sed'.
2511 * 1 : csp = Current client state (buffers, headers, etc...)
2512 * 2 : header = On input, pointer to header to modify.
2513 * On output, pointer to the modified header, or NULL
2514 * to remove the header. This function frees the
2515 * original string if necessary.
2517 * Returns : JB_ERR_OK on success, or
2518 * JB_ERR_MEMORY on out-of-memory error.
2520 *********************************************************************/
2521 static jb_err server_content_disposition(struct client_state *csp, char **header)
2526 * Are we messing with the Content-Disposition header?
2528 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2534 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2536 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2539 * Blocking content-disposition header
2541 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2548 * Replacing Content-Disposition header
2551 *header = strdup("Content-Disposition: ");
2552 string_append(header, newval);
2554 if (*header != NULL)
2556 log_error(LOG_LEVEL_HEADER,
2557 "Content-Disposition header crunched and replaced with: %s", *header);
2560 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2564 /*********************************************************************
2566 * Function : server_last_modified
2568 * Description : Changes Last-Modified header to the actual date
2569 * to help hide-if-modified-since.
2570 * Called from `sed'.
2573 * 1 : csp = Current client state (buffers, headers, etc...)
2574 * 2 : header = On input, pointer to header to modify.
2575 * On output, pointer to the modified header, or NULL
2576 * to remove the header. This function frees the
2577 * original string if necessary.
2579 * Returns : JB_ERR_OK on success, or
2580 * JB_ERR_MEMORY on out-of-memory error.
2582 *********************************************************************/
2583 static jb_err server_last_modified(struct client_state *csp, char **header)
2586 time_t last_modified;
2590 * Are we messing with the Last-Modified header?
2592 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2598 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2600 if (0 == strcmpic(newval, "block"))
2603 * Blocking Last-Modified header. Useless but why not.
2605 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2609 else if (0 == strcmpic(newval, "reset-to-request-time"))
2612 * Setting Last-Modified Header to now.
2615 get_http_time(0, buf, sizeof(buf));
2617 *header = strdup("Last-Modified: ");
2618 string_append(header, buf);
2620 if (*header == NULL)
2622 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2626 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2629 else if (0 == strcmpic(newval, "randomize"))
2631 const char *header_time = *header + sizeof("Last-Modified:");
2633 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2635 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2637 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2643 struct tm *timeptr = NULL;
2645 #ifdef HAVE_GMTIME_R
2649 rtime = (long int)difftime(now, last_modified);
2652 long int days, hours, minutes, seconds;
2653 const int negative_delta = (rtime < 0);
2658 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2660 rtime = pick_from_range(rtime);
2665 last_modified += rtime;
2666 #ifdef HAVE_GMTIME_R
2667 timeptr = gmtime_r(&last_modified, &gmt);
2668 #elif defined(MUTEX_LOCKS_AVAILABLE)
2669 privoxy_mutex_lock(&gmtime_mutex);
2670 timeptr = gmtime(&last_modified);
2671 privoxy_mutex_unlock(&gmtime_mutex);
2673 timeptr = gmtime(&last_modified);
2675 if ((NULL == timeptr) || !strftime(newheader,
2676 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2678 log_error(LOG_LEVEL_ERROR,
2679 "Randomizing '%s' failed. Crunching the header without replacement.",
2686 *header = strdup("Last-Modified: ");
2687 string_append(header, newheader);
2689 if (*header == NULL)
2691 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2692 return JB_ERR_MEMORY;
2695 days = rtime / (3600 * 24);
2696 hours = rtime / 3600 % 24;
2697 minutes = rtime / 60 % 60;
2698 seconds = rtime % 60;
2700 log_error(LOG_LEVEL_HEADER,
2701 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2702 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2703 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2707 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2716 /*********************************************************************
2718 * Function : client_accept_encoding
2720 * Description : Rewrite the client's Accept-Encoding header so that
2721 * if doesn't allow compression, if the action applies.
2722 * Note: For HTTP/1.0 the absence of the header is enough.
2725 * 1 : csp = Current client state (buffers, headers, etc...)
2726 * 2 : header = On input, pointer to header to modify.
2727 * On output, pointer to the modified header, or NULL
2728 * to remove the header. This function frees the
2729 * original string if necessary.
2731 * Returns : JB_ERR_OK on success, or
2732 * JB_ERR_MEMORY on out-of-memory error.
2734 *********************************************************************/
2735 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2737 #ifdef FEATURE_COMPRESSION
2738 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2739 && strstr(*header, "deflate"))
2741 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2744 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2746 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2754 /*********************************************************************
2756 * Function : client_te
2758 * Description : Rewrite the client's TE header so that
2759 * if doesn't allow compression, if the action applies.
2762 * 1 : csp = Current client state (buffers, headers, etc...)
2763 * 2 : header = On input, pointer to header to modify.
2764 * On output, pointer to the modified header, or NULL
2765 * to remove the header. This function frees the
2766 * original string if necessary.
2768 * Returns : JB_ERR_OK on success, or
2769 * JB_ERR_MEMORY on out-of-memory error.
2771 *********************************************************************/
2772 static jb_err client_te(struct client_state *csp, char **header)
2774 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2777 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2784 /*********************************************************************
2786 * Function : client_referrer
2788 * Description : Handle the "referer" config setting properly.
2789 * Called from `sed'.
2792 * 1 : csp = Current client state (buffers, headers, etc...)
2793 * 2 : header = On input, pointer to header to modify.
2794 * On output, pointer to the modified header, or NULL
2795 * to remove the header. This function frees the
2796 * original string if necessary.
2798 * Returns : JB_ERR_OK on success, or
2799 * JB_ERR_MEMORY on out-of-memory error.
2801 *********************************************************************/
2802 static jb_err client_referrer(struct client_state *csp, char **header)
2804 const char *parameter;
2805 /* booleans for parameters we have to check multiple times */
2806 int parameter_conditional_block;
2807 int parameter_conditional_forge;
2809 #ifdef FEATURE_FORCE_LOAD
2811 * Since the referrer can include the prefix even
2812 * if the request itself is non-forced, we must
2813 * clean it unconditionally.
2815 * XXX: strclean is too broad
2817 strclean(*header, FORCE_PREFIX);
2818 #endif /* def FEATURE_FORCE_LOAD */
2820 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2822 /* Nothing left to do */
2826 parameter = csp->action->string[ACTION_STRING_REFERER];
2827 assert(parameter != NULL);
2828 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2829 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2831 if (!parameter_conditional_block && !parameter_conditional_forge)
2834 * As conditional-block and conditional-forge are the only
2835 * parameters that rely on the original referrer, we can
2836 * remove it now for all the others.
2841 if (0 == strcmpic(parameter, "block"))
2843 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2846 else if (parameter_conditional_block || parameter_conditional_forge)
2848 return handle_conditional_hide_referrer_parameter(header,
2849 csp->http->hostport, parameter_conditional_block);
2851 else if (0 == strcmpic(parameter, "forge"))
2853 return create_forged_referrer(header, csp->http->hostport);
2857 /* interpret parameter as user-supplied referer to fake */
2858 return create_fake_referrer(header, parameter);
2863 /*********************************************************************
2865 * Function : client_accept_language
2867 * Description : Handle the "Accept-Language" config setting properly.
2868 * Called from `sed'.
2871 * 1 : csp = Current client state (buffers, headers, etc...)
2872 * 2 : header = On input, pointer to header to modify.
2873 * On output, pointer to the modified header, or NULL
2874 * to remove the header. This function frees the
2875 * original string if necessary.
2877 * Returns : JB_ERR_OK on success, or
2878 * JB_ERR_MEMORY on out-of-memory error.
2880 *********************************************************************/
2881 static jb_err client_accept_language(struct client_state *csp, char **header)
2886 * Are we messing with the Accept-Language?
2888 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2890 /*I don't think so*/
2894 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2896 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2899 * Blocking Accept-Language header
2901 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2908 * Replacing Accept-Language header
2911 *header = strdup("Accept-Language: ");
2912 string_append(header, newval);
2914 if (*header == NULL)
2916 log_error(LOG_LEVEL_ERROR,
2917 "Insufficient memory. Accept-Language header crunched without replacement.");
2921 log_error(LOG_LEVEL_HEADER,
2922 "Accept-Language header crunched and replaced with: %s", *header);
2925 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2929 /*********************************************************************
2931 * Function : crunch_client_header
2933 * Description : Crunch client header if it matches a string supplied by the
2934 * user. Called from `sed'.
2937 * 1 : csp = Current client state (buffers, headers, etc...)
2938 * 2 : header = On input, pointer to header to modify.
2939 * On output, pointer to the modified header, or NULL
2940 * to remove the header. This function frees the
2941 * original string if necessary.
2943 * Returns : JB_ERR_OK on success and always succeeds
2945 *********************************************************************/
2946 static jb_err crunch_client_header(struct client_state *csp, char **header)
2948 const char *crunch_pattern;
2950 /* Do we feel like crunching? */
2951 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2953 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2955 /* Is the current header the lucky one? */
2956 if (strstr(*header, crunch_pattern))
2958 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2966 /*********************************************************************
2968 * Function : client_uagent
2970 * Description : Handle the "user-agent" config setting properly
2971 * and remember its original value to enable browser
2972 * bug workarounds. Called from `sed'.
2975 * 1 : csp = Current client state (buffers, headers, etc...)
2976 * 2 : header = On input, pointer to header to modify.
2977 * On output, pointer to the modified header, or NULL
2978 * to remove the header. This function frees the
2979 * original string if necessary.
2981 * Returns : JB_ERR_OK on success, or
2982 * JB_ERR_MEMORY on out-of-memory error.
2984 *********************************************************************/
2985 static jb_err client_uagent(struct client_state *csp, char **header)
2989 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2994 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3001 *header = strdup("User-Agent: ");
3002 string_append(header, newval);
3004 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3006 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3010 /*********************************************************************
3012 * Function : client_ua
3014 * Description : Handle "ua-" headers properly. Called from `sed'.
3017 * 1 : csp = Current client state (buffers, headers, etc...)
3018 * 2 : header = On input, pointer to header to modify.
3019 * On output, pointer to the modified header, or NULL
3020 * to remove the header. This function frees the
3021 * original string if necessary.
3023 * Returns : JB_ERR_OK on success, or
3024 * JB_ERR_MEMORY on out-of-memory error.
3026 *********************************************************************/
3027 static jb_err client_ua(struct client_state *csp, char **header)
3029 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3031 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3039 /*********************************************************************
3041 * Function : client_from
3043 * Description : Handle the "from" config setting properly.
3044 * Called from `sed'.
3047 * 1 : csp = Current client state (buffers, headers, etc...)
3048 * 2 : header = On input, pointer to header to modify.
3049 * On output, pointer to the modified header, or NULL
3050 * to remove the header. This function frees the
3051 * original string if necessary.
3053 * Returns : JB_ERR_OK on success, or
3054 * JB_ERR_MEMORY on out-of-memory error.
3056 *********************************************************************/
3057 static jb_err client_from(struct client_state *csp, char **header)
3061 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3068 newval = csp->action->string[ACTION_STRING_FROM];
3071 * Are we blocking the e-mail address?
3073 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3075 log_error(LOG_LEVEL_HEADER, "crunched From!");
3079 log_error(LOG_LEVEL_HEADER, " modified");
3081 *header = strdup("From: ");
3082 string_append(header, newval);
3084 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3088 /*********************************************************************
3090 * Function : client_send_cookie
3092 * Description : Crunches the "cookie" header if necessary.
3093 * Called from `sed'.
3095 * XXX: Stupid name, doesn't send squat.
3098 * 1 : csp = Current client state (buffers, headers, etc...)
3099 * 2 : header = On input, pointer to header to modify.
3100 * On output, pointer to the modified header, or NULL
3101 * to remove the header. This function frees the
3102 * original string if necessary.
3104 * Returns : JB_ERR_OK on success, or
3105 * JB_ERR_MEMORY on out-of-memory error.
3107 *********************************************************************/
3108 static jb_err client_send_cookie(struct client_state *csp, char **header)
3110 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3112 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3120 /*********************************************************************
3122 * Function : client_x_forwarded
3124 * Description : Handle the "x-forwarded-for" config setting properly,
3125 * also used in the add_client_headers list. Called from `sed'.
3128 * 1 : csp = Current client state (buffers, headers, etc...)
3129 * 2 : header = On input, pointer to header to modify.
3130 * On output, pointer to the modified header, or NULL
3131 * to remove the header. This function frees the
3132 * original string if necessary.
3134 * Returns : JB_ERR_OK on success, or
3135 * JB_ERR_MEMORY on out-of-memory error.
3137 *********************************************************************/
3138 jb_err client_x_forwarded(struct client_state *csp, char **header)
3140 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3142 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3144 if (0 == strcmpic(parameter, "block"))
3147 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3149 else if (0 == strcmpic(parameter, "add"))
3151 string_append(header, ", ");
3152 string_append(header, csp->ip_addr_str);
3154 if (*header == NULL)
3156 return JB_ERR_MEMORY;
3158 log_error(LOG_LEVEL_HEADER,
3159 "Appended client IP address to %s", *header);
3160 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3164 log_error(LOG_LEVEL_FATAL,
3165 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3173 /*********************************************************************
3175 * Function : client_max_forwards
3177 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3178 * from the value of the Max-Forwards header field.
3181 * 1 : csp = Current client state (buffers, headers, etc...)
3182 * 2 : header = On input, pointer to header to modify.
3183 * On output, pointer to the modified header, or NULL
3184 * to remove the header. This function frees the
3185 * original string if necessary.
3187 * Returns : JB_ERR_OK on success, or
3188 * JB_ERR_MEMORY on out-of-memory error.
3190 *********************************************************************/
3191 static jb_err client_max_forwards(struct client_state *csp, char **header)
3195 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3196 (0 == strcmpic(csp->http->gpc, "options")))
3198 assert(*(*header+12) == ':');
3199 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3201 if (max_forwards > 0)
3203 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3204 log_error(LOG_LEVEL_HEADER,
3205 "Max-Forwards value for %s request reduced to %d.",
3206 csp->http->gpc, max_forwards);
3208 else if (max_forwards < 0)
3210 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3216 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3225 /*********************************************************************
3227 * Function : client_host
3229 * Description : If the request URI did not contain host and
3230 * port information, parse and evaluate the Host
3234 * 1 : csp = Current client state (buffers, headers, etc...)
3235 * 2 : header = On input, pointer to header to modify.
3236 * On output, pointer to the modified header, or NULL
3237 * to remove the header. This function frees the
3238 * original string if necessary.
3240 * Returns : JB_ERR_OK on success, or
3241 * JB_ERR_MEMORY on out-of-memory error.
3243 *********************************************************************/
3244 static jb_err client_host(struct client_state *csp, char **header)
3248 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3249 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3252 p = strdup_or_die((*header)+6);
3254 q = strdup_or_die(p);
3256 freez(csp->http->hostport);
3257 csp->http->hostport = p;
3258 freez(csp->http->host);
3259 csp->http->host = q;
3260 q = strchr(csp->http->host, ':');
3263 /* Terminate hostname and evaluate port string */
3265 csp->http->port = atoi(q);
3269 csp->http->port = csp->http->ssl ? 443 : 80;
3272 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3273 csp->http->hostport, csp->http->host, csp->http->port);
3276 /* Signal client_host_adder() to return right away */
3277 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3283 /*********************************************************************
3285 * Function : client_if_modified_since
3287 * Description : Remove or modify the If-Modified-Since header.
3290 * 1 : csp = Current client state (buffers, headers, etc...)
3291 * 2 : header = On input, pointer to header to modify.
3292 * On output, pointer to the modified header, or NULL
3293 * to remove the header. This function frees the
3294 * original string if necessary.
3296 * Returns : JB_ERR_OK on success, or
3297 * JB_ERR_MEMORY on out-of-memory error.
3299 *********************************************************************/
3300 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3303 #ifdef HAVE_GMTIME_R
3306 struct tm *timeptr = NULL;
3311 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3314 * The client got an error message because of a temporary problem,
3315 * the problem is gone and the client now tries to revalidate our
3316 * error message on the real server. The revalidation would always
3317 * end with the transmission of the whole document and there is
3318 * no need to expose the bogus If-Modified-Since header.
3320 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3323 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3325 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3327 if ((0 == strcmpic(newval, "block")))
3329 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3332 else /* add random value */
3334 const char *header_time = *header + sizeof("If-Modified-Since:");
3336 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3338 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3343 long int hours, minutes, seconds;
3344 long int rtime = strtol(newval, &endptr, 0);
3345 const int negative_range = (rtime < 0);
3349 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3350 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3356 rtime = pick_from_range(rtime);
3360 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3363 tm += rtime * (negative_range ? -1 : 1);
3364 #ifdef HAVE_GMTIME_R
3365 timeptr = gmtime_r(&tm, &gmt);
3366 #elif defined(MUTEX_LOCKS_AVAILABLE)
3367 privoxy_mutex_lock(&gmtime_mutex);
3368 timeptr = gmtime(&tm);
3369 privoxy_mutex_unlock(&gmtime_mutex);
3371 timeptr = gmtime(&tm);
3373 if ((NULL == timeptr) || !strftime(newheader,
3374 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3376 log_error(LOG_LEVEL_ERROR,
3377 "Randomizing '%s' failed. Crunching the header without replacement.",
3384 *header = strdup("If-Modified-Since: ");
3385 string_append(header, newheader);
3387 if (*header == NULL)
3389 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3390 return JB_ERR_MEMORY;
3393 hours = rtime / 3600;
3394 minutes = rtime / 60 % 60;
3395 seconds = rtime % 60;
3397 log_error(LOG_LEVEL_HEADER,
3398 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3399 *header, (negative_range) ? "subtracted" : "added", hours,
3400 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3401 seconds, (seconds == 1) ? ")" : "s)");
3410 /*********************************************************************
3412 * Function : client_if_none_match
3414 * Description : Remove the If-None-Match header.
3417 * 1 : csp = Current client state (buffers, headers, etc...)
3418 * 2 : header = On input, pointer to header to modify.
3419 * On output, pointer to the modified header, or NULL
3420 * to remove the header. This function frees the
3421 * original string if necessary.
3423 * Returns : JB_ERR_OK on success, or
3424 * JB_ERR_MEMORY on out-of-memory error.
3426 *********************************************************************/
3427 static jb_err client_if_none_match(struct client_state *csp, char **header)
3429 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3431 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3439 /*********************************************************************
3441 * Function : client_x_filter
3443 * Description : Disables filtering if the client set "X-Filter: No".
3444 * Called from `sed'.
3447 * 1 : csp = Current client state (buffers, headers, etc...)
3448 * 2 : header = On input, pointer to header to modify.
3449 * On output, pointer to the modified header, or NULL
3450 * to remove the header. This function frees the
3451 * original string if necessary.
3453 * Returns : JB_ERR_OK on success
3455 *********************************************************************/
3456 jb_err client_x_filter(struct client_state *csp, char **header)
3458 if (0 == strcmpic(*header, "X-Filter: No"))
3460 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3462 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3466 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3468 log_error(LOG_LEVEL_HEADER,
3469 "force-text-mode overruled the client's request to fetch without filtering!");
3473 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3474 csp->flags |= CSP_FLAG_NO_FILTERING;
3475 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3477 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3485 /*********************************************************************
3487 * Function : client_range
3489 * Description : Removes Range, Request-Range and If-Range headers if
3490 * content filtering is enabled and the range doesn't
3493 * If the client's version of the document has been
3494 * altered by Privoxy, the server could interpret the
3495 * range differently than the client intended in which
3496 * case the user could end up with corrupted content.
3498 * If the range starts at byte 0 this isn't an issue
3499 * so the header can pass. Partial requests like this
3500 * are used to render preview images for videos without
3501 * downloading the whole video.
3503 * While HTTP doesn't require that range requests are
3504 * honoured and the client could simply abort the download
3505 * after receiving a sufficient amount of data, various
3506 * clients don't handle complete responses to range
3507 * requests gracefully and emit misleading error messages
3511 * 1 : csp = Current client state (buffers, headers, etc...)
3512 * 2 : header = On input, pointer to header to modify.
3513 * On output, pointer to the modified header, or NULL
3514 * to remove the header. This function frees the
3515 * original string if necessary.
3517 * Returns : JB_ERR_OK
3519 *********************************************************************/
3520 static jb_err client_range(struct client_state *csp, char **header)
3522 if (content_filters_enabled(csp->action)
3523 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3525 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3526 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3533 /* the following functions add headers directly to the header list */
3535 /*********************************************************************
3537 * Function : client_host_adder
3539 * Description : Adds the Host: header field if it is missing.
3540 * Called from `sed'.
3543 * 1 : csp = Current client state (buffers, headers, etc...)
3545 * Returns : JB_ERR_OK on success, or
3546 * JB_ERR_MEMORY on out-of-memory error.
3548 *********************************************************************/
3549 static jb_err client_host_adder(struct client_state *csp)
3554 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3556 /* Header already set by the client, nothing to do. */
3560 if (!csp->http->hostport || !*(csp->http->hostport))
3562 /* XXX: When does this happen and why is it OK? */
3563 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3568 * remove 'user:pass@' from 'proto://user:pass@host'
3570 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3576 p = csp->http->hostport;
3579 /* XXX: Just add it, we already made sure that it will be unique */
3580 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3581 err = enlist_unique_header(csp->headers, "Host", p);
3587 /*********************************************************************
3589 * Function : client_xtra_adder
3591 * Description : Used in the add_client_headers list. Called from `sed'.
3594 * 1 : csp = Current client state (buffers, headers, etc...)
3596 * Returns : JB_ERR_OK on success, or
3597 * JB_ERR_MEMORY on out-of-memory error.
3599 *********************************************************************/
3600 static jb_err client_xtra_adder(struct client_state *csp)
3602 struct list_entry *lst;
3605 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3606 lst ; lst = lst->next)
3608 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3609 err = enlist(csp->headers, lst->str);
3621 /*********************************************************************
3623 * Function : client_x_forwarded_for_adder
3625 * Description : Used in the add_client_headers list. Called from `sed'.
3628 * 1 : csp = Current client state (buffers, headers, etc...)
3630 * Returns : JB_ERR_OK on success, or
3631 * JB_ERR_MEMORY on out-of-memory error.
3633 *********************************************************************/
3634 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3636 char *header = NULL;
3639 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3640 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3641 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3644 * If we aren't adding X-Forwarded-For headers,
3645 * or we already appended an existing X-Forwarded-For
3646 * header, there's nothing left to do here.
3651 header = strdup("X-Forwarded-For: ");
3652 string_append(&header, csp->ip_addr_str);
3656 return JB_ERR_MEMORY;
3659 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3660 err = enlist(csp->headers, header);
3667 /*********************************************************************
3669 * Function : server_connection_adder
3671 * Description : Adds an appropriate "Connection:" header to csp->headers
3672 * unless the header was already present. Called from `sed'.
3675 * 1 : csp = Current client state (buffers, headers, etc...)
3677 * Returns : JB_ERR_OK on success, or
3678 * JB_ERR_MEMORY on out-of-memory error.
3680 *********************************************************************/
3681 static jb_err server_connection_adder(struct client_state *csp)
3683 const unsigned int flags = csp->flags;
3684 const char *response_status_line = csp->headers->first->str;
3685 static const char connection_close[] = "Connection: close";
3687 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3688 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3694 * XXX: if we downgraded the response, this check will fail.
3696 if ((csp->config->feature_flags &
3697 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3698 && (NULL != response_status_line)
3699 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3700 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3701 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3705 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3706 "without Connection header implies keep-alive.");
3707 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3711 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3713 return enlist(csp->headers, connection_close);
3717 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3718 /*********************************************************************
3720 * Function : server_proxy_connection_adder
3722 * Description : Adds a "Proxy-Connection: keep-alive" header to
3723 * csp->headers when appropriate.
3726 * 1 : csp = Current client state (buffers, headers, etc...)
3728 * Returns : JB_ERR_OK on success, or
3729 * JB_ERR_MEMORY on out-of-memory error.
3731 *********************************************************************/
3732 static jb_err server_proxy_connection_adder(struct client_state *csp)
3734 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3735 jb_err err = JB_ERR_OK;
3737 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3738 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3739 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3740 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3741 || (csp->flags & CSP_FLAG_CHUNKED)))
3743 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3744 err = enlist(csp->headers, proxy_connection_header);
3749 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3752 /*********************************************************************
3754 * Function : client_connection_header_adder
3756 * Description : Adds a proper "Connection:" header to csp->headers
3757 * unless the header was already present. Called from `sed'.
3760 * 1 : csp = Current client state (buffers, headers, etc...)
3762 * Returns : JB_ERR_OK on success, or
3763 * JB_ERR_MEMORY on out-of-memory error.
3765 *********************************************************************/
3766 static jb_err client_connection_header_adder(struct client_state *csp)
3768 static const char connection_close[] = "Connection: close";