1 const char parsers_rcs[] = "$Id: parsers.c,v 1.263 2012/11/11 12:38:42 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
8 * Copyright : Written by and Copyright (C) 2001-2012 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
40 #include <sys/types.h>
50 * Convince GNU's libc to provide a strptime prototype.
59 #define GZIP_IDENTIFIER_1 0x1f
60 #define GZIP_IDENTIFIER_2 0x8b
62 #define GZIP_FLAG_CHECKSUM 0x02
63 #define GZIP_FLAG_EXTRA_FIELDS 0x04
64 #define GZIP_FLAG_FILE_NAME 0x08
65 #define GZIP_FLAG_COMMENT 0x10
66 #define GZIP_FLAG_RESERVED_BITS 0xe0
69 #if !defined(_WIN32) && !defined(__OS2__)
75 #ifdef FEATURE_PTHREAD
77 /* jcc.h is for mutex semapores only */
78 #endif /* def FEATURE_PTHREAD */
83 #include "jbsockets.h"
93 const char parsers_h_rcs[] = PARSERS_H_VERSION;
95 static char *get_header_line(struct iob *iob);
96 static jb_err scan_headers(struct client_state *csp);
97 static jb_err header_tagger(struct client_state *csp, char *header);
98 static jb_err parse_header_time(const char *header_time, time_t *result);
100 static jb_err crumble (struct client_state *csp, char **header);
101 static jb_err filter_header (struct client_state *csp, char **header);
102 static jb_err client_connection (struct client_state *csp, char **header);
103 static jb_err client_referrer (struct client_state *csp, char **header);
104 static jb_err client_uagent (struct client_state *csp, char **header);
105 static jb_err client_ua (struct client_state *csp, char **header);
106 static jb_err client_from (struct client_state *csp, char **header);
107 static jb_err client_send_cookie (struct client_state *csp, char **header);
108 static jb_err client_x_forwarded (struct client_state *csp, char **header);
109 static jb_err client_accept_encoding (struct client_state *csp, char **header);
110 static jb_err client_te (struct client_state *csp, char **header);
111 static jb_err client_max_forwards (struct client_state *csp, char **header);
112 static jb_err client_host (struct client_state *csp, char **header);
113 static jb_err client_if_modified_since (struct client_state *csp, char **header);
114 static jb_err client_accept_language (struct client_state *csp, char **header);
115 static jb_err client_if_none_match (struct client_state *csp, char **header);
116 static jb_err crunch_client_header (struct client_state *csp, char **header);
117 static jb_err client_x_filter (struct client_state *csp, char **header);
118 static jb_err client_range (struct client_state *csp, char **header);
119 static jb_err server_set_cookie (struct client_state *csp, char **header);
120 static jb_err server_connection (struct client_state *csp, char **header);
121 static jb_err server_content_type (struct client_state *csp, char **header);
122 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
123 static jb_err server_content_md5 (struct client_state *csp, char **header);
124 static jb_err server_content_encoding (struct client_state *csp, char **header);
125 static jb_err server_transfer_coding (struct client_state *csp, char **header);
126 static jb_err server_http (struct client_state *csp, char **header);
127 static jb_err crunch_server_header (struct client_state *csp, char **header);
128 static jb_err server_last_modified (struct client_state *csp, char **header);
129 static jb_err server_content_disposition(struct client_state *csp, char **header);
131 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
134 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
135 static jb_err server_save_content_length(struct client_state *csp, char **header);
136 static jb_err server_keep_alive(struct client_state *csp, char **header);
137 static jb_err server_proxy_connection(struct client_state *csp, char **header);
138 static jb_err client_keep_alive(struct client_state *csp, char **header);
139 static jb_err client_save_content_length(struct client_state *csp, char **header);
140 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
142 static jb_err client_host_adder (struct client_state *csp);
143 static jb_err client_xtra_adder (struct client_state *csp);
144 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
145 static jb_err client_connection_header_adder(struct client_state *csp);
146 static jb_err server_connection_adder(struct client_state *csp);
147 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
148 static jb_err server_proxy_connection_adder(struct client_state *csp);
149 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
151 static jb_err create_forged_referrer(char **header, const char *hostport);
152 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
153 static jb_err handle_conditional_hide_referrer_parameter(char **header,
154 const char *host, const int parameter_conditional_block);
155 static void create_content_length_header(unsigned long long content_length,
156 char *header, size_t buffer_length);
159 * List of functions to run on a list of headers.
163 /** The header prefix to match */
166 /** The length of the prefix to match */
169 /** The function to apply to this line */
170 const parser_func_ptr parser;
173 static const struct parsers client_patterns[] = {
174 { "referer:", 8, client_referrer },
175 { "user-agent:", 11, client_uagent },
176 { "ua-", 3, client_ua },
177 { "from:", 5, client_from },
178 { "cookie:", 7, client_send_cookie },
179 { "x-forwarded-for:", 16, client_x_forwarded },
180 { "Accept-Encoding:", 16, client_accept_encoding },
181 { "TE:", 3, client_te },
182 { "Host:", 5, client_host },
183 { "if-modified-since:", 18, client_if_modified_since },
184 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
185 { "Keep-Alive:", 11, client_keep_alive },
186 { "Content-Length:", 15, client_save_content_length },
188 { "Keep-Alive:", 11, crumble },
190 { "connection:", 11, client_connection },
191 { "proxy-connection:", 17, crumble },
192 { "max-forwards:", 13, client_max_forwards },
193 { "Accept-Language:", 16, client_accept_language },
194 { "if-none-match:", 14, client_if_none_match },
195 { "Range:", 6, client_range },
196 { "Request-Range:", 14, client_range },
197 { "If-Range:", 9, client_range },
198 { "X-Filter:", 9, client_x_filter },
199 { "*", 0, crunch_client_header },
200 { "*", 0, filter_header },
204 static const struct parsers server_patterns[] = {
205 { "HTTP/", 5, server_http },
206 { "set-cookie:", 11, server_set_cookie },
207 { "connection:", 11, server_connection },
208 { "Content-Type:", 13, server_content_type },
209 { "Content-MD5:", 12, server_content_md5 },
210 { "Content-Encoding:", 17, server_content_encoding },
211 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
212 { "Content-Length:", 15, server_save_content_length },
213 { "Keep-Alive:", 11, server_keep_alive },
214 { "Proxy-Connection:", 17, server_proxy_connection },
216 { "Keep-Alive:", 11, crumble },
217 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
218 { "Transfer-Encoding:", 18, server_transfer_coding },
219 { "content-disposition:", 20, server_content_disposition },
220 { "Last-Modified:", 14, server_last_modified },
221 { "*", 0, crunch_server_header },
222 { "*", 0, filter_header },
226 static const add_header_func_ptr add_client_headers[] = {
228 client_x_forwarded_for_adder,
230 client_connection_header_adder,
234 static const add_header_func_ptr add_server_headers[] = {
235 server_connection_adder,
236 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
237 server_proxy_connection_adder,
238 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
242 /*********************************************************************
244 * Function : flush_socket
246 * Description : Write any pending "buffered" content.
249 * 1 : fd = file descriptor of the socket to read
250 * 2 : iob = The I/O buffer to flush, usually csp->iob.
252 * Returns : On success, the number of bytes written are returned (zero
253 * indicates nothing was written). On error, -1 is returned,
254 * and errno is set appropriately. If count is zero and the
255 * file descriptor refers to a regular file, 0 will be
256 * returned without causing any other effect. For a special
257 * file, the results are not portable.
259 *********************************************************************/
260 long flush_socket(jb_socket fd, struct iob *iob)
262 long len = iob->eod - iob->cur;
269 if (write_socket(fd, iob->cur, (size_t)len))
273 iob->eod = iob->cur = iob->buf;
279 /*********************************************************************
281 * Function : add_to_iob
283 * Description : Add content to the buffer, expanding the
284 * buffer if necessary.
287 * 1 : iob = Destination buffer.
288 * 2 : buffer_limit = Limit to which the destination may grow
289 * 3 : src = holds the content to be added
290 * 4 : n = number of bytes to be added
292 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
293 * or buffer limit reached.
295 *********************************************************************/
296 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
298 size_t used, offset, need;
301 if (n <= 0) return JB_ERR_OK;
303 used = (size_t)(iob->eod - iob->buf);
304 offset = (size_t)(iob->cur - iob->buf);
305 need = used + (size_t)n + 1;
308 * If the buffer can't hold the new data, extend it first.
309 * Use the next power of two if possible, else use the actual need.
311 if (need > buffer_limit)
313 log_error(LOG_LEVEL_INFO,
314 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
316 return JB_ERR_MEMORY;
319 if (need > iob->size)
321 size_t want = iob->size ? iob->size : 512;
328 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
332 else if (NULL != (p = (char *)realloc(iob->buf, need)))
338 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
339 return JB_ERR_MEMORY;
342 /* Update the iob pointers */
343 iob->cur = p + offset;
348 /* copy the new data into the iob buffer */
349 memcpy(iob->eod, src, (size_t)n);
351 /* point to the end of the data */
354 /* null terminate == cheap insurance */
362 /*********************************************************************
364 * Function : clear_iob
366 * Description : Frees the memory allocated for an I/O buffer and
367 * resets the structure.
370 * 1 : iob = I/O buffer to clear.
372 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
373 * or buffer limit reached.
375 *********************************************************************/
376 void clear_iob(struct iob *iob)
379 memset(iob, '\0', sizeof(*iob));;
384 /*********************************************************************
386 * Function : decompress_iob
388 * Description : Decompress buffered page, expanding the
389 * buffer as necessary. csp->iob->cur
390 * should point to the the beginning of the
391 * compressed data block.
394 * 1 : csp = Current client state (buffers, headers, etc...)
396 * Returns : JB_ERR_OK on success,
397 * JB_ERR_MEMORY if out-of-memory limit reached, and
398 * JB_ERR_COMPRESS if error decompressing buffer.
400 *********************************************************************/
401 jb_err decompress_iob(struct client_state *csp)
403 char *buf; /* new, uncompressed buffer */
404 char *cur; /* Current iob position (to keep the original
405 * iob->cur unmodified if we return early) */
406 size_t bufsize; /* allocated size of the new buffer */
407 size_t old_size; /* Content size before decompression */
408 size_t skip_size; /* Number of bytes at the beginning of the iob
409 that we should NOT decompress. */
410 int status; /* return status of the inflate() call */
411 z_stream zstr; /* used by calls to zlib */
413 assert(csp->iob->cur - csp->iob->buf > 0);
414 assert(csp->iob->eod - csp->iob->cur > 0);
416 bufsize = csp->iob->size;
417 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
418 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
422 if (bufsize < (size_t)10)
425 * This is to protect the parsing of gzipped data,
426 * but it should(?) be valid for deflated data also.
428 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
429 return JB_ERR_COMPRESS;
432 if (csp->content_type & CT_GZIP)
435 * Our task is slightly complicated by the facts that data
436 * compressed by gzip does not include a zlib header, and
437 * that there is no easily accessible interface in zlib to
438 * handle a gzip header. We strip off the gzip header by
439 * hand, and later inform zlib not to expect a header.
443 * Strip off the gzip header. Please see RFC 1952 for more
444 * explanation of the appropriate fields.
446 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
447 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
448 || (*cur++ != Z_DEFLATED))
450 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
451 return JB_ERR_COMPRESS;
456 if (flags & GZIP_FLAG_RESERVED_BITS)
458 /* The gzip header has reserved bits set; bail out. */
459 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
460 return JB_ERR_COMPRESS;
464 * Skip mtime (4 bytes), extra flags (1 byte)
465 * and OS type (1 byte).
469 /* Skip extra fields if necessary. */
470 if (flags & GZIP_FLAG_EXTRA_FIELDS)
473 * Skip a given number of bytes, specified
474 * as a 16-bit little-endian value.
476 * XXX: this code is untested and should probably be removed.
480 skip_bytes += *cur++ << 8;
483 * The number of bytes to skip should be positive
484 * and we'd like to stay in the buffer.
486 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
488 log_error(LOG_LEVEL_ERROR,
489 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
491 return JB_ERR_COMPRESS;
493 log_error(LOG_LEVEL_INFO,
494 "Skipping %d bytes for gzip compression. Does this sound right?",
499 /* Skip the filename if necessary. */
500 if (flags & GZIP_FLAG_FILE_NAME)
502 /* A null-terminated string is supposed to follow. */
503 while (*cur++ && (cur < csp->iob->eod));
506 /* Skip the comment if necessary. */
507 if (flags & GZIP_FLAG_COMMENT)
509 /* A null-terminated string is supposed to follow. */
510 while (*cur++ && (cur < csp->iob->eod));
513 /* Skip the CRC if necessary. */
514 if (flags & GZIP_FLAG_CHECKSUM)
519 if (cur >= csp->iob->eod)
522 * If the current position pointer reached or passed
523 * the buffer end, we were obviously tricked to skip
526 log_error(LOG_LEVEL_ERROR,
527 "Malformed gzip header detected. Aborting decompression.");
528 return JB_ERR_COMPRESS;
532 else if (csp->content_type & CT_DEFLATE)
535 * In theory (that is, according to RFC 1950), deflate-compressed
536 * data should begin with a two-byte zlib header and have an
537 * adler32 checksum at the end. It seems that in practice only
538 * the raw compressed data is sent. Note that this means that
539 * we are not RFC 1950-compliant here, but the advantage is that
540 * this actually works. :)
542 * We add a dummy null byte to tell zlib where the data ends,
543 * and later inform it not to expect a header.
545 * Fortunately, add_to_iob() has thoughtfully null-terminated
546 * the buffer; we can just increment the end pointer to include
553 log_error(LOG_LEVEL_ERROR,
554 "Unable to determine compression format for decompression");
555 return JB_ERR_COMPRESS;
558 /* Set up the fields required by zlib. */
559 zstr.next_in = (Bytef *)cur;
560 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
561 zstr.zalloc = Z_NULL;
563 zstr.opaque = Z_NULL;
566 * Passing -MAX_WBITS to inflateInit2 tells the library
567 * that there is no zlib header.
569 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
571 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
572 return JB_ERR_COMPRESS;
576 * Next, we allocate new storage for the inflated data.
577 * We don't modify the existing iob yet, so in case there
578 * is error in decompression we can recover gracefully.
580 buf = zalloc(bufsize);
583 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
584 return JB_ERR_MEMORY;
587 assert(bufsize >= skip_size);
588 memcpy(buf, csp->iob->buf, skip_size);
589 zstr.avail_out = (uInt)(bufsize - skip_size);
590 zstr.next_out = (Bytef *)buf + skip_size;
592 /* Try to decompress the whole stream in one shot. */
593 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
595 /* We need to allocate more memory for the output buffer. */
597 char *tmpbuf; /* used for realloc'ing the buffer */
598 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
600 if (0 == zstr.avail_in)
603 * If zlib wants more data then there's a problem, because
604 * the complete compressed file should have been buffered.
606 log_error(LOG_LEVEL_ERROR,
607 "Unexpected end of compressed iob. Using what we got so far.");
612 * If we reached the buffer limit and still didn't have enough
613 * memory, just give up. Due to the ceiling enforced by the next
614 * if block we could actually check for equality here, but as it
615 * can be easily mistaken for a bug we don't.
617 if (bufsize >= csp->config->buffer_limit)
619 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
620 return JB_ERR_MEMORY;
623 /* Try doubling the buffer size each time. */
626 /* Don't exceed the buffer limit. */
627 if (bufsize > csp->config->buffer_limit)
629 bufsize = csp->config->buffer_limit;
632 /* Try to allocate the new buffer. */
633 tmpbuf = realloc(buf, bufsize);
636 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
638 return JB_ERR_MEMORY;
642 char *oldnext_out = (char *)zstr.next_out;
645 * Update the fields for inflate() to use the new
646 * buffer, which may be in a location different from
649 zstr.avail_out += (uInt)(bufsize - oldbufsize);
650 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
653 * Compare with an uglier method of calculating these values
654 * that doesn't require the extra oldbufsize variable.
656 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
657 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
663 if (Z_STREAM_ERROR == inflateEnd(&zstr))
665 log_error(LOG_LEVEL_ERROR,
666 "Inconsistent stream state after decompression: %s", zstr.msg);
668 * XXX: Intentionally no return.
670 * According to zlib.h, Z_STREAM_ERROR is returned
671 * "if the stream state was inconsistent".
673 * I assume in this case inflate()'s status
674 * would also be something different than Z_STREAM_END
675 * so this check should be redundant, but lets see.
679 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
682 * We failed to decompress the stream and it's
683 * not simply because of missing data.
685 log_error(LOG_LEVEL_ERROR,
686 "Unexpected error while decompressing to the buffer (iob): %s",
688 return JB_ERR_COMPRESS;
692 * Finally, we can actually update the iob, since the
693 * decompression was successful. First, free the old
696 freez(csp->iob->buf);
698 /* Now, update the iob to use the new buffer. */
700 csp->iob->cur = csp->iob->buf + skip_size;
701 csp->iob->eod = (char *)zstr.next_out;
702 csp->iob->size = bufsize;
705 * Make sure the new uncompressed iob obeys some minimal
706 * consistency conditions.
708 if ((csp->iob->buf < csp->iob->cur)
709 && (csp->iob->cur <= csp->iob->eod)
710 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
712 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
713 if (new_size > (size_t)0)
715 log_error(LOG_LEVEL_RE_FILTER,
716 "Decompression successful. Old size: %d, new size: %d.",
721 /* zlib thinks this is OK, so lets do the same. */
722 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
727 /* It seems that zlib did something weird. */
728 log_error(LOG_LEVEL_ERROR,
729 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
730 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
731 csp->iob->eod, csp->iob->buf + csp->iob->size);
732 return JB_ERR_COMPRESS;
738 #endif /* defined(FEATURE_ZLIB) */
741 /*********************************************************************
743 * Function : string_move
745 * Description : memmove wrapper to move the last part of a string
746 * towards the beginning, overwriting the part in
747 * the middle. strlcpy() can't be used here as the
751 * 1 : dst = Destination to overwrite
752 * 2 : src = Source to move.
756 *********************************************************************/
757 static void string_move(char *dst, char *src)
761 /* +1 to copy the terminating nul as well. */
762 memmove(dst, src, strlen(src)+1);
766 /*********************************************************************
768 * Function : normalize_lws
770 * Description : Reduces unquoted linear white space in headers
771 * to a single space in accordance with RFC 2616 2.2.
772 * This simplifies parsing and filtering later on.
774 * XXX: Remove log messages before
775 * the next stable release?
778 * 1 : header = A header with linear white space to reduce.
782 *********************************************************************/
783 static void normalize_lws(char *header)
789 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
793 while (privoxy_isspace(*q))
797 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
803 log_error(LOG_LEVEL_HEADER,
804 "Converting tab to space in '%s'", header);
809 char *end_of_token = strstr(p+1, "\"");
811 if (NULL != end_of_token)
813 /* Don't mess with quoted text. */
818 log_error(LOG_LEVEL_HEADER,
819 "Ignoring single quote in '%s'", header);
825 p = strchr(header, ':');
826 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
829 * There's still space before the colon.
837 /*********************************************************************
839 * Function : get_header
841 * Description : This (odd) routine will parse the csp->iob
842 * to get the next complete header.
845 * 1 : iob = The I/O buffer to parse, usually csp->iob.
847 * Returns : Any one of the following:
849 * 1) a pointer to a dynamically allocated string that contains a header line
850 * 2) NULL indicating that the end of the header was reached
851 * 3) "" indicating that the end of the iob was reached before finding
852 * a complete header line.
854 *********************************************************************/
855 char *get_header(struct iob *iob)
859 header = get_header_line(iob);
861 if ((header == NULL) || (*header == '\0'))
864 * No complete header read yet, tell the client.
869 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
872 * Header spans multiple lines, append the next one.
874 char *continued_header;
876 continued_header = get_header_line(iob);
877 if ((continued_header == NULL) || (*continued_header == '\0'))
880 * No complete header read yet, return what we got.
881 * XXX: Should "unread" header instead.
883 log_error(LOG_LEVEL_INFO,
884 "Failed to read a multi-line header properly: '%s'",
889 if (JB_ERR_OK != string_join(&header, continued_header))
891 log_error(LOG_LEVEL_FATAL,
892 "Out of memory while appending multiple headers.");
896 /* XXX: remove before next stable release. */
897 log_error(LOG_LEVEL_HEADER,
898 "Merged multiple header lines to: '%s'",
903 normalize_lws(header);
910 /*********************************************************************
912 * Function : get_header_line
914 * Description : This (odd) routine will parse the csp->iob
915 * to get the next header line.
918 * 1 : iob = The I/O buffer to parse, usually csp->iob.
920 * Returns : Any one of the following:
922 * 1) a pointer to a dynamically allocated string that contains a header line
923 * 2) NULL indicating that the end of the header was reached
924 * 3) "" indicating that the end of the iob was reached before finding
925 * a complete header line.
927 *********************************************************************/
928 static char *get_header_line(struct iob *iob)
932 if ((iob->cur == NULL)
933 || ((p = strchr(iob->cur, '\n')) == NULL))
935 return(""); /* couldn't find a complete header */
940 ret = strdup(iob->cur);
943 /* FIXME No way to handle error properly */
944 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
950 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
952 /* is this a blank line (i.e. the end of the header) ? */
964 /*********************************************************************
966 * Function : get_header_value
968 * Description : Get the value of a given header from a chained list
969 * of header lines or return NULL if no such header is
970 * present in the list.
973 * 1 : header_list = pointer to list
974 * 2 : header_name = string with name of header to look for.
975 * Trailing colon required, capitalization
978 * Returns : NULL if not found, else value of header
980 *********************************************************************/
981 char *get_header_value(const struct list *header_list, const char *header_name)
983 struct list_entry *cur_entry;
989 length = strlen(header_name);
991 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
995 if (!strncmpic(cur_entry->str, header_name, length))
998 * Found: return pointer to start of value
1000 ret = cur_entry->str + length;
1001 while (*ret && privoxy_isspace(*ret)) ret++;
1015 /*********************************************************************
1017 * Function : scan_headers
1019 * Description : Scans headers, applies tags and updates action bits.
1022 * 1 : csp = Current client state (buffers, headers, etc...)
1024 * Returns : JB_ERR_OK
1026 *********************************************************************/
1027 static jb_err scan_headers(struct client_state *csp)
1029 struct list_entry *h; /* Header */
1030 jb_err err = JB_ERR_OK;
1032 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1034 /* Header crunch()ed in previous run? -> ignore */
1035 if (h->str == NULL) continue;
1036 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1037 err = header_tagger(csp, h->str);
1044 /*********************************************************************
1046 * Function : enforce_header_order
1048 * Description : Enforces a given header order.
1051 * 1 : headers = List of headers to order.
1052 * 2 : ordered_headers = List of ordered header names.
1056 *********************************************************************/
1057 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1059 struct list_entry *sorted_header;
1060 struct list new_headers[1];
1061 struct list_entry *header;
1063 init_list(new_headers);
1065 /* The request line is always the first "header" */
1067 assert(NULL != headers->first->str);
1068 enlist(new_headers, headers->first->str);
1069 freez(headers->first->str)
1071 /* Enlist the specified headers in the given order */
1073 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1074 sorted_header = sorted_header->next)
1076 const size_t sorted_header_length = strlen(sorted_header->str);
1077 for (header = headers->first; header != NULL; header = header->next)
1079 /* Header enlisted in previous run? -> ignore */
1080 if (header->str == NULL) continue;
1082 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1083 && (header->str[sorted_header_length] == ':'))
1085 log_error(LOG_LEVEL_HEADER, "Enlisting sorted 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);
1095 /* Enlist the rest of the headers behind the ordered ones */
1096 for (header = headers->first; header != NULL; header = header->next)
1098 /* Header enlisted in previous run? -> ignore */
1099 if (header->str == NULL) continue;
1101 log_error(LOG_LEVEL_HEADER,
1102 "Enlisting left-over header %s", header->str);
1103 if (JB_ERR_OK != enlist(new_headers, header->str))
1105 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1110 list_remove_all(headers);
1111 list_duplicate(headers, new_headers);
1112 list_remove_all(new_headers);
1117 /*********************************************************************
1121 * Description : add, delete or modify lines in the HTTP header streams.
1122 * On entry, it receives a linked list of headers space
1123 * that was allocated dynamically (both the list nodes
1124 * and the header contents).
1126 * As a side effect it frees the space used by the original
1130 * 1 : csp = Current client state (buffers, headers, etc...)
1131 * 2 : filter_server_headers = Boolean to switch between
1132 * server and header filtering.
1134 * Returns : JB_ERR_OK in case off success, or
1135 * JB_ERR_MEMORY on out-of-memory error.
1137 *********************************************************************/
1138 jb_err sed(struct client_state *csp, int filter_server_headers)
1140 /* XXX: use more descriptive names. */
1141 struct list_entry *p;
1142 const struct parsers *v;
1143 const add_header_func_ptr *f;
1144 jb_err err = JB_ERR_OK;
1146 if (filter_server_headers)
1148 v = server_patterns;
1149 f = add_server_headers;
1153 v = client_patterns;
1154 f = add_client_headers;
1159 while ((err == JB_ERR_OK) && (v->str != NULL))
1161 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1163 /* Header crunch()ed in previous run? -> ignore */
1164 if (p->str == NULL) continue;
1166 /* Does the current parser handle this header? */
1167 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1168 (v->len == CHECK_EVERY_HEADER_REMAINING))
1170 err = v->parser(csp, &(p->str));
1176 /* place additional headers on the csp->headers list */
1177 while ((err == JB_ERR_OK) && (*f))
1183 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1185 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1192 /*********************************************************************
1194 * Function : update_server_headers
1196 * Description : Updates server headers after the body has been modified.
1199 * 1 : csp = Current client state (buffers, headers, etc...)
1201 * Returns : JB_ERR_OK in case off success, or
1202 * JB_ERR_MEMORY on out-of-memory error.
1204 *********************************************************************/
1205 jb_err update_server_headers(struct client_state *csp)
1207 jb_err err = JB_ERR_OK;
1209 static const struct parsers server_patterns_light[] = {
1210 { "Content-Length:", 15, server_adjust_content_length },
1211 { "Transfer-Encoding:", 18, server_transfer_coding },
1213 { "Content-Encoding:", 17, server_adjust_content_encoding },
1214 #endif /* def FEATURE_ZLIB */
1218 if (strncmpic(csp->http->cmd, "HEAD", 4))
1220 const struct parsers *v;
1221 struct list_entry *p;
1223 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1225 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1227 /* Header crunch()ed in previous run? -> ignore */
1228 if (p->str == NULL) continue;
1230 /* Does the current parser handle this header? */
1231 if (strncmpic(p->str, v->str, v->len) == 0)
1233 err = v->parser(csp, (char **)&(p->str));
1239 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1240 if ((JB_ERR_OK == err)
1241 && (csp->flags & CSP_FLAG_MODIFIED)
1242 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1243 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1247 create_content_length_header(csp->content_length, header, sizeof(header));
1248 err = enlist(csp->headers, header);
1249 if (JB_ERR_OK == err)
1251 log_error(LOG_LEVEL_HEADER,
1252 "Content modified with no Content-Length header set. "
1253 "Created: %s.", header);
1256 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1258 #ifdef FEATURE_COMPRESSION
1259 if ((JB_ERR_OK == err)
1260 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1262 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1263 if (JB_ERR_OK == err)
1265 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1274 /*********************************************************************
1276 * Function : header_tagger
1278 * Description : Executes all text substitutions from applying
1279 * tag actions and saves the result as tag.
1281 * XXX: Shares enough code with filter_header() and
1282 * pcrs_filter_response() to warrant some helper functions.
1285 * 1 : csp = Current client state (buffers, headers, etc...)
1286 * 2 : header = Header that is used as tagger input
1288 * Returns : JB_ERR_OK on success and always succeeds
1290 *********************************************************************/
1291 static jb_err header_tagger(struct client_state *csp, char *header)
1293 int wanted_filter_type;
1294 int multi_action_index;
1298 struct file_list *fl;
1299 struct re_filterfile_spec *b;
1300 struct list_entry *tag_name;
1302 const size_t header_length = strlen(header);
1304 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1306 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1307 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1311 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1312 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1315 if (filters_available(csp) == FALSE)
1317 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1318 "tagging enabled, but no taggers available.");
1322 for (i = 0; i < MAX_AF_FILES; i++)
1325 if ((NULL == fl) || (NULL == fl->f))
1328 * Either there are no filter files
1329 * left, or this filter file just
1330 * contains no valid filters.
1332 * Continue to be sure we don't miss
1333 * valid filter files that are chained
1334 * after empty or invalid ones.
1339 /* For all filters, */
1340 for (b = fl->f; b; b = b->next)
1342 if (b->type != wanted_filter_type)
1344 /* skip the ones we don't care about, */
1347 /* leaving only taggers that could apply, of which we use the ones, */
1348 for (tag_name = csp->action->multi[multi_action_index]->first;
1349 NULL != tag_name; tag_name = tag_name->next)
1351 /* that do apply, and */
1352 if (strcmp(b->name, tag_name->str) == 0)
1354 char *modified_tag = NULL;
1356 size_t size = header_length;
1357 pcrs_job *joblist = b->joblist;
1359 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1361 if (NULL == joblist)
1363 log_error(LOG_LEVEL_RE_FILTER,
1364 "Tagger %s has empty joblist. Nothing to do.", b->name);
1368 /* execute their pcrs_joblist on the header. */
1369 for (job = joblist; NULL != job; job = job->next)
1371 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1375 /* Success, continue with the modified version. */
1384 /* Tagger doesn't match */
1387 /* Regex failure, log it but continue anyway. */
1388 assert(NULL != header);
1389 log_error(LOG_LEVEL_ERROR,
1390 "Problems with tagger \'%s\' and header \'%s\': %s",
1391 b->name, *header, pcrs_strerror(hits));
1393 freez(modified_tag);
1397 if (b->dynamic) pcrs_free_joblist(joblist);
1399 /* If this tagger matched */
1405 * There is to technical limitation which makes
1406 * it impossible to use empty tags, but I assume
1407 * no one would do it intentionally.
1410 log_error(LOG_LEVEL_INFO,
1411 "Tagger \'%s\' created an empty tag. Ignored.",
1416 if (!list_contains_item(csp->tags, tag))
1418 if (JB_ERR_OK != enlist(csp->tags, tag))
1420 log_error(LOG_LEVEL_ERROR,
1421 "Insufficient memory to add tag \'%s\', "
1422 "based on tagger \'%s\' and header \'%s\'",
1423 tag, b->name, *header);
1427 char *action_message;
1429 * update the action bits right away, to make
1430 * tagging based on tags set by earlier taggers
1431 * of the same kind possible.
1433 if (update_action_bits_for_tag(csp, tag))
1435 action_message = "Action bits updated accordingly.";
1439 action_message = "No action bits update necessary.";
1442 log_error(LOG_LEVEL_HEADER,
1443 "Tagger \'%s\' added tag \'%s\'. %s",
1444 b->name, tag, action_message);
1449 /* XXX: Is this log-worthy? */
1450 log_error(LOG_LEVEL_HEADER,
1451 "Tagger \'%s\' didn't add tag \'%s\'. "
1452 "Tag already present", b->name, tag);
1455 } /* if the tagger matched */
1456 } /* if the tagger applies */
1457 } /* for every tagger that could apply */
1458 } /* for all filters */
1459 } /* for all filter files */
1464 /* here begins the family of parser functions that reformat header lines */
1466 /*********************************************************************
1468 * Function : filter_header
1470 * Description : Executes all text substitutions from all applying
1471 * +(server|client)-header-filter actions on the header.
1472 * Most of the code was copied from pcrs_filter_response,
1473 * including the rather short variable names
1476 * 1 : csp = Current client state (buffers, headers, etc...)
1477 * 2 : header = On input, pointer to header to modify.
1478 * On output, pointer to the modified header, or NULL
1479 * to remove the header. This function frees the
1480 * original string if necessary.
1482 * Returns : JB_ERR_OK on success and always succeeds
1484 *********************************************************************/
1485 static jb_err filter_header(struct client_state *csp, char **header)
1489 size_t size = strlen(*header);
1491 char *newheader = NULL;
1494 struct file_list *fl;
1495 struct re_filterfile_spec *b;
1496 struct list_entry *filtername;
1499 int wanted_filter_type;
1500 int multi_action_index;
1502 if (csp->flags & CSP_FLAG_NO_FILTERING)
1507 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1509 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1510 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1514 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1515 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1518 if (filters_available(csp) == FALSE)
1520 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1521 "header filtering enabled, but no matching filters available.");
1525 for (i = 0; i < MAX_AF_FILES; i++)
1528 if ((NULL == fl) || (NULL == fl->f))
1531 * Either there are no filter files
1532 * left, or this filter file just
1533 * contains no valid filters.
1535 * Continue to be sure we don't miss
1536 * valid filter files that are chained
1537 * after empty or invalid ones.
1542 * For all applying +filter actions, look if a filter by that
1543 * name exists and if yes, execute its pcrs_joblist on the
1546 for (b = fl->f; b; b = b->next)
1548 if (b->type != wanted_filter_type)
1550 /* Skip other filter types */
1554 for (filtername = csp->action->multi[multi_action_index]->first;
1555 filtername ; filtername = filtername->next)
1557 if (strcmp(b->name, filtername->str) == 0)
1559 int current_hits = 0;
1560 pcrs_job *joblist = b->joblist;
1562 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1564 if (NULL == joblist)
1566 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1570 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1571 *header, size, b->name);
1573 /* Apply all jobs from the joblist */
1574 for (job = joblist; NULL != job; job = job->next)
1576 matches = pcrs_execute(job, *header, size, &newheader, &size);
1579 current_hits += matches;
1580 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1582 *header = newheader;
1584 else if (0 == matches)
1586 /* Filter doesn't change header */
1592 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1593 *header, b->name, pcrs_strerror(matches));
1594 if (newheader != NULL)
1596 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1602 if (b->dynamic) pcrs_free_joblist(joblist);
1604 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1605 hits += current_hits;
1612 * Additionally checking for hits is important because if
1613 * the continue hack is triggered, server headers can
1614 * arrive empty to separate multiple heads from each other.
1616 if ((0 == size) && hits)
1618 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1626 /*********************************************************************
1628 * Function : server_connection
1630 * Description : Makes sure a proper "Connection:" header is
1631 * set and signals connection_header_adder to
1635 * 1 : csp = Current client state (buffers, headers, etc...)
1636 * 2 : header = On input, pointer to header to modify.
1637 * On output, pointer to the modified header, or NULL
1638 * to remove the header. This function frees the
1639 * original string if necessary.
1641 * Returns : JB_ERR_OK on success.
1643 *********************************************************************/
1644 static jb_err server_connection(struct client_state *csp, char **header)
1646 if (!strcmpic(*header, "Connection: keep-alive")
1647 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1648 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1652 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1653 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1655 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1658 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1660 log_error(LOG_LEVEL_HEADER,
1661 "Keeping the server header '%s' around.", *header);
1664 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1666 char *old_header = *header;
1668 *header = strdup_or_die("Connection: close");
1669 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1674 /* Signal server_connection_adder() to return early. */
1675 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1681 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1682 /*********************************************************************
1684 * Function : server_keep_alive
1686 * Description : Stores the server's keep alive timeout.
1689 * 1 : csp = Current client state (buffers, headers, etc...)
1690 * 2 : header = On input, pointer to header to modify.
1691 * On output, pointer to the modified header, or NULL
1692 * to remove the header. This function frees the
1693 * original string if necessary.
1695 * Returns : JB_ERR_OK.
1697 *********************************************************************/
1698 static jb_err server_keep_alive(struct client_state *csp, char **header)
1700 unsigned int keep_alive_timeout;
1701 const char *timeout_position = strstr(*header, "timeout=");
1703 if ((NULL == timeout_position)
1704 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1706 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1710 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1712 log_error(LOG_LEVEL_HEADER,
1713 "Reducing keep-alive timeout from %u to %u.",
1714 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1715 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1719 /* XXX: Is this log worthy? */
1720 log_error(LOG_LEVEL_HEADER,
1721 "Server keep-alive timeout is %u. Sticking with %u.",
1722 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1724 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1731 /*********************************************************************
1733 * Function : server_proxy_connection
1735 * Description : Figures out whether or not we should add a
1736 * Proxy-Connection header.
1739 * 1 : csp = Current client state (buffers, headers, etc...)
1740 * 2 : header = On input, pointer to header to modify.
1741 * On output, pointer to the modified header, or NULL
1742 * to remove the header. This function frees the
1743 * original string if necessary.
1745 * Returns : JB_ERR_OK.
1747 *********************************************************************/
1748 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1750 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1755 /*********************************************************************
1757 * Function : client_keep_alive
1759 * Description : Stores the client's keep alive timeout.
1762 * 1 : csp = Current client state (buffers, headers, etc...)
1763 * 2 : header = On input, pointer to header to modify.
1764 * On output, pointer to the modified header, or NULL
1765 * to remove the header. This function frees the
1766 * original string if necessary.
1768 * Returns : JB_ERR_OK.
1770 *********************************************************************/
1771 static jb_err client_keep_alive(struct client_state *csp, char **header)
1773 unsigned int keep_alive_timeout;
1774 const char *timeout_position = strstr(*header, ": ");
1776 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1778 log_error(LOG_LEVEL_HEADER,
1779 "keep-alive support is disabled. Crunching: %s.", *header);
1784 if ((NULL == timeout_position)
1785 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1787 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1791 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1793 log_error(LOG_LEVEL_HEADER,
1794 "Reducing keep-alive timeout from %u to %u.",
1795 csp->config->keep_alive_timeout, keep_alive_timeout);
1796 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1800 /* XXX: Is this log worthy? */
1801 log_error(LOG_LEVEL_HEADER,
1802 "Client keep-alive timeout is %u. Sticking with %u.",
1803 keep_alive_timeout, csp->config->keep_alive_timeout);
1811 /*********************************************************************
1813 * Function : get_content_length
1815 * Description : Gets the content length specified in a
1816 * Content-Length header.
1819 * 1 : header_value = The Content-Length header value.
1820 * 2 : length = Storage to return the value.
1822 * Returns : JB_ERR_OK on success, or
1823 * JB_ERR_PARSE if no value is recognized.
1825 *********************************************************************/
1826 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1829 assert(sizeof(unsigned long long) > 4);
1830 if (1 != sscanf(header_value, "%I64u", length))
1832 if (1 != sscanf(header_value, "%llu", length))
1835 return JB_ERR_PARSE;
1842 /*********************************************************************
1844 * Function : client_save_content_length
1846 * Description : Save the Content-Length sent by the client.
1849 * 1 : csp = Current client state (buffers, headers, etc...)
1850 * 2 : header = On input, pointer to header to modify.
1851 * On output, pointer to the modified header, or NULL
1852 * to remove the header. This function frees the
1853 * original string if necessary.
1855 * Returns : JB_ERR_OK on success, or
1856 * JB_ERR_MEMORY on out-of-memory error.
1858 *********************************************************************/
1859 static jb_err client_save_content_length(struct client_state *csp, char **header)
1861 unsigned long long content_length = 0;
1862 const char *header_value;
1864 assert(*(*header+14) == ':');
1866 header_value = *header + 15;
1867 if (JB_ERR_OK != get_content_length(header_value, &content_length))
1869 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1874 csp->expected_client_content_length = content_length;
1879 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1883 /*********************************************************************
1885 * Function : client_connection
1887 * Description : Makes sure a proper "Connection:" header is
1888 * set and signals connection_header_adder
1892 * 1 : csp = Current client state (buffers, headers, etc...)
1893 * 2 : header = On input, pointer to header to modify.
1894 * On output, pointer to the modified header, or NULL
1895 * to remove the header. This function frees the
1896 * original string if necessary.
1898 * Returns : JB_ERR_OK on success.
1900 *********************************************************************/
1901 static jb_err client_connection(struct client_state *csp, char **header)
1903 static const char connection_close[] = "Connection: close";
1905 if (!strcmpic(*header, connection_close))
1907 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1908 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1909 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1911 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1913 log_error(LOG_LEVEL_HEADER,
1914 "Removing \'%s\' to imply keep-alive.", *header);
1917 * While we imply keep-alive to the server,
1918 * we have to remember that the client didn't.
1920 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1924 char *old_header = *header;
1926 *header = strdup_or_die("Connection: keep-alive");
1927 log_error(LOG_LEVEL_HEADER,
1928 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1934 log_error(LOG_LEVEL_HEADER,
1935 "Keeping the client header '%s' around. "
1936 "The connection will not be kept alive.",
1938 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1941 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1942 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1944 log_error(LOG_LEVEL_HEADER,
1945 "Keeping the client header '%s' around. "
1946 "The server connection will be kept alive if possible.",
1948 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1949 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1953 char *old_header = *header;
1955 *header = strdup_or_die(connection_close);
1956 log_error(LOG_LEVEL_HEADER,
1957 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1961 /* Signal client_connection_header_adder() to return early. */
1962 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1968 /*********************************************************************
1970 * Function : crumble
1972 * Description : This is called if a header matches a pattern to "crunch"
1975 * 1 : csp = Current client state (buffers, headers, etc...)
1976 * 2 : header = On input, pointer to header to modify.
1977 * On output, pointer to the modified header, or NULL
1978 * to remove the header. This function frees the
1979 * original string if necessary.
1981 * Returns : JB_ERR_OK on success, or
1982 * JB_ERR_MEMORY on out-of-memory error.
1984 *********************************************************************/
1985 static jb_err crumble(struct client_state *csp, char **header)
1988 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1994 /*********************************************************************
1996 * Function : crunch_server_header
1998 * Description : Crunch server header if it matches a string supplied by the
1999 * user. Called from `sed'.
2002 * 1 : csp = Current client state (buffers, headers, etc...)
2003 * 2 : header = On input, pointer to header to modify.
2004 * On output, pointer to the modified header, or NULL
2005 * to remove the header. This function frees the
2006 * original string if necessary.
2008 * Returns : JB_ERR_OK on success and always succeeds
2010 *********************************************************************/
2011 static jb_err crunch_server_header(struct client_state *csp, char **header)
2013 const char *crunch_pattern;
2015 /* Do we feel like crunching? */
2016 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2018 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2020 /* Is the current header the lucky one? */
2021 if (strstr(*header, crunch_pattern))
2023 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2032 /*********************************************************************
2034 * Function : server_content_type
2036 * Description : Set the content-type for filterable types (text/.*,
2037 * .*xml.*, .*script.* and image/gif) unless filtering has been
2038 * forbidden (CT_TABOO) while parsing earlier headers.
2039 * NOTE: Since text/plain is commonly used by web servers
2040 * for files whose correct type is unknown, we don't
2041 * set CT_TEXT for it.
2044 * 1 : csp = Current client state (buffers, headers, etc...)
2045 * 2 : header = On input, pointer to header to modify.
2046 * On output, pointer to the modified header, or NULL
2047 * to remove the header. This function frees the
2048 * original string if necessary.
2050 * Returns : JB_ERR_OK on success, or
2051 * JB_ERR_MEMORY on out-of-memory error.
2053 *********************************************************************/
2054 static jb_err server_content_type(struct client_state *csp, char **header)
2056 /* Remove header if it isn't the first Content-Type header */
2057 if ((csp->content_type & CT_DECLARED))
2060 * Another, slightly slower, way to see if
2061 * we already parsed another Content-Type header.
2063 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2065 log_error(LOG_LEVEL_ERROR,
2066 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2074 * Signal that the Content-Type has been set.
2076 csp->content_type |= CT_DECLARED;
2078 if (!(csp->content_type & CT_TABOO))
2081 * XXX: The assumption that text/plain is a sign of
2082 * binary data seems to be somewhat unreasonable nowadays
2083 * and should be dropped after 3.0.8 is out.
2085 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2086 || strstr(*header, "xml")
2087 || strstr(*header, "script"))
2089 csp->content_type |= CT_TEXT;
2091 else if (strstr(*header, "image/gif"))
2093 csp->content_type |= CT_GIF;
2098 * Are we messing with the content type?
2100 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2103 * Make sure the user doesn't accidentally
2104 * change the content type of binary documents.
2106 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2109 *header = strdup_or_die("Content-Type: ");
2110 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2114 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2115 return JB_ERR_MEMORY;
2117 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2121 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2122 "It doesn't look like a content type that should be filtered. "
2123 "Enable force-text-mode if you know what you're doing.", *header);
2131 /*********************************************************************
2133 * Function : server_transfer_coding
2135 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2136 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2137 * - Remove header if body was chunked but has been
2138 * de-chunked for filtering.
2141 * 1 : csp = Current client state (buffers, headers, etc...)
2142 * 2 : header = On input, pointer to header to modify.
2143 * On output, pointer to the modified header, or NULL
2144 * to remove the header. This function frees the
2145 * original string if necessary.
2147 * Returns : JB_ERR_OK on success, or
2148 * JB_ERR_MEMORY on out-of-memory error.
2150 *********************************************************************/
2151 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2154 * Turn off pcrs and gif filtering if body compressed
2156 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2160 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2162 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2163 csp->http->cmd, *header);
2164 #endif /* def FEATURE_ZLIB */
2165 csp->content_type = CT_TABOO;
2169 * Raise flag if body chunked
2171 if (strstr(*header, "chunked"))
2173 csp->flags |= CSP_FLAG_CHUNKED;
2176 * If the body was modified, it has been de-chunked first
2177 * and the header must be removed.
2179 * FIXME: If there is more than one transfer encoding,
2180 * only the "chunked" part should be removed here.
2182 if (csp->flags & CSP_FLAG_MODIFIED)
2184 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2193 /*********************************************************************
2195 * Function : server_content_encoding
2197 * Description : Used to check if the content is compressed, and if
2198 * FEATURE_ZLIB is disabled, filtering is disabled as
2201 * If FEATURE_ZLIB is enabled and the compression type
2202 * supported, the content is marked for decompression.
2204 * XXX: Doesn't properly deal with multiple or with
2205 * unsupported but unknown encodings.
2206 * Is case-sensitive but shouldn't be.
2209 * 1 : csp = Current client state (buffers, headers, etc...)
2210 * 2 : header = On input, pointer to header to modify.
2211 * On output, pointer to the modified header, or NULL
2212 * to remove the header. This function frees the
2213 * original string if necessary.
2215 * Returns : JB_ERR_OK on success, or
2216 * JB_ERR_MEMORY on out-of-memory error.
2218 *********************************************************************/
2219 static jb_err server_content_encoding(struct client_state *csp, char **header)
2222 if (strstr(*header, "sdch"))
2225 * Shared Dictionary Compression over HTTP isn't supported,
2226 * filtering it anyway is pretty much guaranteed to mess up
2229 csp->content_type |= CT_TABOO;
2232 * Log a warning if the user expects the content to be filtered.
2234 if ((csp->rlist != NULL) &&
2235 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2237 log_error(LOG_LEVEL_INFO,
2238 "SDCH-compressed content detected, content filtering disabled. "
2239 "Consider suppressing SDCH offers made by the client.");
2242 else if (strstr(*header, "gzip"))
2244 /* Mark for gzip decompression */
2245 csp->content_type |= CT_GZIP;
2247 else if (strstr(*header, "deflate"))
2249 /* Mark for zlib decompression */
2250 csp->content_type |= CT_DEFLATE;
2252 else if (strstr(*header, "compress"))
2255 * We can't decompress this; therefore we can't filter
2258 csp->content_type |= CT_TABOO;
2260 #else /* !defined(FEATURE_ZLIB) */
2262 * XXX: Using a black list here isn't the right approach.
2264 * In case of SDCH, building with zlib support isn't
2267 if (strstr(*header, "gzip") ||
2268 strstr(*header, "compress") ||
2269 strstr(*header, "deflate") ||
2270 strstr(*header, "sdch"))
2273 * Body is compressed, turn off pcrs and gif filtering.
2275 csp->content_type |= CT_TABOO;
2278 * Log a warning if the user expects the content to be filtered.
2280 if ((csp->rlist != NULL) &&
2281 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2283 log_error(LOG_LEVEL_INFO,
2284 "Compressed content detected, content filtering disabled. "
2285 "Consider recompiling Privoxy with zlib support or "
2286 "enable the prevent-compression action.");
2289 #endif /* defined(FEATURE_ZLIB) */
2297 /*********************************************************************
2299 * Function : server_adjust_content_encoding
2301 * Description : Remove the Content-Encoding header if the
2302 * decompression was successful and the content
2306 * 1 : csp = Current client state (buffers, headers, etc...)
2307 * 2 : header = On input, pointer to header to modify.
2308 * On output, pointer to the modified header, or NULL
2309 * to remove the header. This function frees the
2310 * original string if necessary.
2312 * Returns : JB_ERR_OK on success, or
2313 * JB_ERR_MEMORY on out-of-memory error.
2315 *********************************************************************/
2316 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2318 if ((csp->flags & CSP_FLAG_MODIFIED)
2319 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2322 * We successfully decompressed the content,
2323 * and have to clean the header now, so the
2324 * client no longer expects compressed data.
2326 * XXX: There is a difference between cleaning
2327 * and removing it completely.
2329 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2336 #endif /* defined(FEATURE_ZLIB) */
2339 /*********************************************************************
2341 * Function : server_adjust_content_length
2343 * Description : Adjust Content-Length header if we modified
2347 * 1 : csp = Current client state (buffers, headers, etc...)
2348 * 2 : header = On input, pointer to header to modify.
2349 * On output, pointer to the modified header, or NULL
2350 * to remove the header. This function frees the
2351 * original string if necessary.
2353 * Returns : JB_ERR_OK on success, or
2354 * JB_ERR_MEMORY on out-of-memory error.
2356 *********************************************************************/
2357 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2359 /* Regenerate header if the content was modified. */
2360 if (csp->flags & CSP_FLAG_MODIFIED)
2362 const size_t header_length = 50;
2364 *header = malloc(header_length);
2365 if (*header == NULL)
2367 return JB_ERR_MEMORY;
2369 create_content_length_header(csp->content_length, *header, header_length);
2370 log_error(LOG_LEVEL_HEADER,
2371 "Adjusted Content-Length to %llu", csp->content_length);
2378 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2379 /*********************************************************************
2381 * Function : server_save_content_length
2383 * Description : Save the Content-Length sent by the server.
2386 * 1 : csp = Current client state (buffers, headers, etc...)
2387 * 2 : header = On input, pointer to header to modify.
2388 * On output, pointer to the modified header, or NULL
2389 * to remove the header. This function frees the
2390 * original string if necessary.
2392 * Returns : JB_ERR_OK on success, or
2393 * JB_ERR_MEMORY on out-of-memory error.
2395 *********************************************************************/
2396 static jb_err server_save_content_length(struct client_state *csp, char **header)
2398 unsigned long long content_length = 0;
2399 const char *header_value;
2401 assert(*(*header+14) == ':');
2403 header_value = *header + 15;
2404 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2406 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2411 csp->expected_content_length = content_length;
2412 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2413 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2418 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2421 /*********************************************************************
2423 * Function : server_content_md5
2425 * Description : Crumble any Content-MD5 headers if the document was
2426 * modified. FIXME: Should we re-compute instead?
2429 * 1 : csp = Current client state (buffers, headers, etc...)
2430 * 2 : header = On input, pointer to header to modify.
2431 * On output, pointer to the modified header, or NULL
2432 * to remove the header. This function frees the
2433 * original string if necessary.
2435 * Returns : JB_ERR_OK on success, or
2436 * JB_ERR_MEMORY on out-of-memory error.
2438 *********************************************************************/
2439 static jb_err server_content_md5(struct client_state *csp, char **header)
2441 if (csp->flags & CSP_FLAG_MODIFIED)
2443 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2451 /*********************************************************************
2453 * Function : server_content_disposition
2455 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2456 * Called from `sed'.
2459 * 1 : csp = Current client state (buffers, headers, etc...)
2460 * 2 : header = On input, pointer to header to modify.
2461 * On output, pointer to the modified header, or NULL
2462 * to remove the header. This function frees the
2463 * original string if necessary.
2465 * Returns : JB_ERR_OK on success, or
2466 * JB_ERR_MEMORY on out-of-memory error.
2468 *********************************************************************/
2469 static jb_err server_content_disposition(struct client_state *csp, char **header)
2474 * Are we messing with the Content-Disposition header?
2476 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2482 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2484 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2487 * Blocking content-disposition header
2489 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2496 * Replacing Content-Disposition header
2499 *header = strdup("Content-Disposition: ");
2500 string_append(header, newval);
2502 if (*header != NULL)
2504 log_error(LOG_LEVEL_HEADER,
2505 "Content-Disposition header crunched and replaced with: %s", *header);
2508 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2512 /*********************************************************************
2514 * Function : server_last_modified
2516 * Description : Changes Last-Modified header to the actual date
2517 * to help hide-if-modified-since.
2518 * Called from `sed'.
2521 * 1 : csp = Current client state (buffers, headers, etc...)
2522 * 2 : header = On input, pointer to header to modify.
2523 * On output, pointer to the modified header, or NULL
2524 * to remove the header. This function frees the
2525 * original string if necessary.
2527 * Returns : JB_ERR_OK on success, or
2528 * JB_ERR_MEMORY on out-of-memory error.
2530 *********************************************************************/
2531 static jb_err server_last_modified(struct client_state *csp, char **header)
2534 time_t last_modified;
2538 * Are we messing with the Last-Modified header?
2540 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2546 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2548 if (0 == strcmpic(newval, "block"))
2551 * Blocking Last-Modified header. Useless but why not.
2553 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2557 else if (0 == strcmpic(newval, "reset-to-request-time"))
2560 * Setting Last-Modified Header to now.
2563 get_http_time(0, buf, sizeof(buf));
2565 *header = strdup("Last-Modified: ");
2566 string_append(header, buf);
2568 if (*header == NULL)
2570 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2574 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2577 else if (0 == strcmpic(newval, "randomize"))
2579 const char *header_time = *header + sizeof("Last-Modified:");
2581 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2583 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2585 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2591 struct tm *timeptr = NULL;
2593 #ifdef HAVE_GMTIME_R
2597 rtime = (long int)difftime(now, last_modified);
2600 long int days, hours, minutes, seconds;
2601 const int negative_delta = (rtime < 0);
2606 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2608 rtime = pick_from_range(rtime);
2613 last_modified += rtime;
2614 #ifdef HAVE_GMTIME_R
2615 timeptr = gmtime_r(&last_modified, &gmt);
2616 #elif defined(MUTEX_LOCKS_AVAILABLE)
2617 privoxy_mutex_lock(&gmtime_mutex);
2618 timeptr = gmtime(&last_modified);
2619 privoxy_mutex_unlock(&gmtime_mutex);
2621 timeptr = gmtime(&last_modified);
2623 if ((NULL == timeptr) || !strftime(newheader,
2624 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2626 log_error(LOG_LEVEL_ERROR,
2627 "Randomizing '%s' failed. Crunching the header without replacement.",
2634 *header = strdup("Last-Modified: ");
2635 string_append(header, newheader);
2637 if (*header == NULL)
2639 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2640 return JB_ERR_MEMORY;
2643 days = rtime / (3600 * 24);
2644 hours = rtime / 3600 % 24;
2645 minutes = rtime / 60 % 60;
2646 seconds = rtime % 60;
2648 log_error(LOG_LEVEL_HEADER,
2649 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2650 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2651 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2655 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2664 /*********************************************************************
2666 * Function : client_accept_encoding
2668 * Description : Rewrite the client's Accept-Encoding header so that
2669 * if doesn't allow compression, if the action applies.
2670 * Note: For HTTP/1.0 the absence of the header is enough.
2673 * 1 : csp = Current client state (buffers, headers, etc...)
2674 * 2 : header = On input, pointer to header to modify.
2675 * On output, pointer to the modified header, or NULL
2676 * to remove the header. This function frees the
2677 * original string if necessary.
2679 * Returns : JB_ERR_OK on success, or
2680 * JB_ERR_MEMORY on out-of-memory error.
2682 *********************************************************************/
2683 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2685 #ifdef FEATURE_COMPRESSION
2686 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2687 && strstr(*header, "deflate"))
2689 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2692 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2694 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2702 /*********************************************************************
2704 * Function : client_te
2706 * Description : Rewrite the client's TE header so that
2707 * if doesn't allow compression, if the action applies.
2710 * 1 : csp = Current client state (buffers, headers, etc...)
2711 * 2 : header = On input, pointer to header to modify.
2712 * On output, pointer to the modified header, or NULL
2713 * to remove the header. This function frees the
2714 * original string if necessary.
2716 * Returns : JB_ERR_OK on success, or
2717 * JB_ERR_MEMORY on out-of-memory error.
2719 *********************************************************************/
2720 static jb_err client_te(struct client_state *csp, char **header)
2722 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2725 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2732 /*********************************************************************
2734 * Function : client_referrer
2736 * Description : Handle the "referer" config setting properly.
2737 * Called from `sed'.
2740 * 1 : csp = Current client state (buffers, headers, etc...)
2741 * 2 : header = On input, pointer to header to modify.
2742 * On output, pointer to the modified header, or NULL
2743 * to remove the header. This function frees the
2744 * original string if necessary.
2746 * Returns : JB_ERR_OK on success, or
2747 * JB_ERR_MEMORY on out-of-memory error.
2749 *********************************************************************/
2750 static jb_err client_referrer(struct client_state *csp, char **header)
2752 const char *parameter;
2753 /* booleans for parameters we have to check multiple times */
2754 int parameter_conditional_block;
2755 int parameter_conditional_forge;
2757 #ifdef FEATURE_FORCE_LOAD
2759 * Since the referrer can include the prefix even
2760 * if the request itself is non-forced, we must
2761 * clean it unconditionally.
2763 * XXX: strclean is too broad
2765 strclean(*header, FORCE_PREFIX);
2766 #endif /* def FEATURE_FORCE_LOAD */
2768 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2770 /* Nothing left to do */
2774 parameter = csp->action->string[ACTION_STRING_REFERER];
2775 assert(parameter != NULL);
2776 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2777 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2779 if (!parameter_conditional_block && !parameter_conditional_forge)
2782 * As conditional-block and conditional-forge are the only
2783 * parameters that rely on the original referrer, we can
2784 * remove it now for all the others.
2789 if (0 == strcmpic(parameter, "block"))
2791 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2794 else if (parameter_conditional_block || parameter_conditional_forge)
2796 return handle_conditional_hide_referrer_parameter(header,
2797 csp->http->hostport, parameter_conditional_block);
2799 else if (0 == strcmpic(parameter, "forge"))
2801 return create_forged_referrer(header, csp->http->hostport);
2805 /* interpret parameter as user-supplied referer to fake */
2806 return create_fake_referrer(header, parameter);
2811 /*********************************************************************
2813 * Function : client_accept_language
2815 * Description : Handle the "Accept-Language" config setting properly.
2816 * Called from `sed'.
2819 * 1 : csp = Current client state (buffers, headers, etc...)
2820 * 2 : header = On input, pointer to header to modify.
2821 * On output, pointer to the modified header, or NULL
2822 * to remove the header. This function frees the
2823 * original string if necessary.
2825 * Returns : JB_ERR_OK on success, or
2826 * JB_ERR_MEMORY on out-of-memory error.
2828 *********************************************************************/
2829 static jb_err client_accept_language(struct client_state *csp, char **header)
2834 * Are we messing with the Accept-Language?
2836 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2838 /*I don't think so*/
2842 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2844 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2847 * Blocking Accept-Language header
2849 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2856 * Replacing Accept-Language header
2859 *header = strdup("Accept-Language: ");
2860 string_append(header, newval);
2862 if (*header == NULL)
2864 log_error(LOG_LEVEL_ERROR,
2865 "Insufficient memory. Accept-Language header crunched without replacement.");
2869 log_error(LOG_LEVEL_HEADER,
2870 "Accept-Language header crunched and replaced with: %s", *header);
2873 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2877 /*********************************************************************
2879 * Function : crunch_client_header
2881 * Description : Crunch client header if it matches a string supplied by the
2882 * user. Called from `sed'.
2885 * 1 : csp = Current client state (buffers, headers, etc...)
2886 * 2 : header = On input, pointer to header to modify.
2887 * On output, pointer to the modified header, or NULL
2888 * to remove the header. This function frees the
2889 * original string if necessary.
2891 * Returns : JB_ERR_OK on success and always succeeds
2893 *********************************************************************/
2894 static jb_err crunch_client_header(struct client_state *csp, char **header)
2896 const char *crunch_pattern;
2898 /* Do we feel like crunching? */
2899 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2901 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2903 /* Is the current header the lucky one? */
2904 if (strstr(*header, crunch_pattern))
2906 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2914 /*********************************************************************
2916 * Function : client_uagent
2918 * Description : Handle the "user-agent" config setting properly
2919 * and remember its original value to enable browser
2920 * bug workarounds. Called from `sed'.
2923 * 1 : csp = Current client state (buffers, headers, etc...)
2924 * 2 : header = On input, pointer to header to modify.
2925 * On output, pointer to the modified header, or NULL
2926 * to remove the header. This function frees the
2927 * original string if necessary.
2929 * Returns : JB_ERR_OK on success, or
2930 * JB_ERR_MEMORY on out-of-memory error.
2932 *********************************************************************/
2933 static jb_err client_uagent(struct client_state *csp, char **header)
2937 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2942 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2949 *header = strdup("User-Agent: ");
2950 string_append(header, newval);
2952 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2954 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2958 /*********************************************************************
2960 * Function : client_ua
2962 * Description : Handle "ua-" headers properly. Called from `sed'.
2965 * 1 : csp = Current client state (buffers, headers, etc...)
2966 * 2 : header = On input, pointer to header to modify.
2967 * On output, pointer to the modified header, or NULL
2968 * to remove the header. This function frees the
2969 * original string if necessary.
2971 * Returns : JB_ERR_OK on success, or
2972 * JB_ERR_MEMORY on out-of-memory error.
2974 *********************************************************************/
2975 static jb_err client_ua(struct client_state *csp, char **header)
2977 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2979 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2987 /*********************************************************************
2989 * Function : client_from
2991 * Description : Handle the "from" config setting properly.
2992 * Called from `sed'.
2995 * 1 : csp = Current client state (buffers, headers, etc...)
2996 * 2 : header = On input, pointer to header to modify.
2997 * On output, pointer to the modified header, or NULL
2998 * to remove the header. This function frees the
2999 * original string if necessary.
3001 * Returns : JB_ERR_OK on success, or
3002 * JB_ERR_MEMORY on out-of-memory error.
3004 *********************************************************************/
3005 static jb_err client_from(struct client_state *csp, char **header)
3009 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3016 newval = csp->action->string[ACTION_STRING_FROM];
3019 * Are we blocking the e-mail address?
3021 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3023 log_error(LOG_LEVEL_HEADER, "crunched From!");
3027 log_error(LOG_LEVEL_HEADER, " modified");
3029 *header = strdup("From: ");
3030 string_append(header, newval);
3032 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3036 /*********************************************************************
3038 * Function : client_send_cookie
3040 * Description : Crunches the "cookie" header if necessary.
3041 * Called from `sed'.
3043 * XXX: Stupid name, doesn't send squat.
3046 * 1 : csp = Current client state (buffers, headers, etc...)
3047 * 2 : header = On input, pointer to header to modify.
3048 * On output, pointer to the modified header, or NULL
3049 * to remove the header. This function frees the
3050 * original string if necessary.
3052 * Returns : JB_ERR_OK on success, or
3053 * JB_ERR_MEMORY on out-of-memory error.
3055 *********************************************************************/
3056 static jb_err client_send_cookie(struct client_state *csp, char **header)
3058 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3060 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3068 /*********************************************************************
3070 * Function : client_x_forwarded
3072 * Description : Handle the "x-forwarded-for" config setting properly,
3073 * also used in the add_client_headers list. Called from `sed'.
3076 * 1 : csp = Current client state (buffers, headers, etc...)
3077 * 2 : header = On input, pointer to header to modify.
3078 * On output, pointer to the modified header, or NULL
3079 * to remove the header. This function frees the
3080 * original string if necessary.
3082 * Returns : JB_ERR_OK on success, or
3083 * JB_ERR_MEMORY on out-of-memory error.
3085 *********************************************************************/
3086 jb_err client_x_forwarded(struct client_state *csp, char **header)
3088 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3090 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3092 if (0 == strcmpic(parameter, "block"))
3095 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3097 else if (0 == strcmpic(parameter, "add"))
3099 string_append(header, ", ");
3100 string_append(header, csp->ip_addr_str);
3102 if (*header == NULL)
3104 return JB_ERR_MEMORY;
3106 log_error(LOG_LEVEL_HEADER,
3107 "Appended client IP address to %s", *header);
3108 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3112 log_error(LOG_LEVEL_FATAL,
3113 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3121 /*********************************************************************
3123 * Function : client_max_forwards
3125 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3126 * from the value of the Max-Forwards header field.
3129 * 1 : csp = Current client state (buffers, headers, etc...)
3130 * 2 : header = On input, pointer to header to modify.
3131 * On output, pointer to the modified header, or NULL
3132 * to remove the header. This function frees the
3133 * original string if necessary.
3135 * Returns : JB_ERR_OK on success, or
3136 * JB_ERR_MEMORY on out-of-memory error.
3138 *********************************************************************/
3139 static jb_err client_max_forwards(struct client_state *csp, char **header)
3143 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3144 (0 == strcmpic(csp->http->gpc, "options")))
3146 assert(*(*header+12) == ':');
3147 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3149 if (max_forwards > 0)
3151 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3152 log_error(LOG_LEVEL_HEADER,
3153 "Max-Forwards value for %s request reduced to %d.",
3154 csp->http->gpc, max_forwards);
3156 else if (max_forwards < 0)
3158 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3164 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3173 /*********************************************************************
3175 * Function : client_host
3177 * Description : If the request URI did not contain host and
3178 * port information, parse and evaluate the Host
3181 * Also, kill ill-formed HOST: headers as sent by
3182 * Apple's iTunes software when used with a proxy.
3185 * 1 : csp = Current client state (buffers, headers, etc...)
3186 * 2 : header = On input, pointer to header to modify.
3187 * On output, pointer to the modified header, or NULL
3188 * to remove the header. This function frees the
3189 * original string if necessary.
3191 * Returns : JB_ERR_OK on success, or
3192 * JB_ERR_MEMORY on out-of-memory error.
3194 *********************************************************************/
3195 static jb_err client_host(struct client_state *csp, char **header)
3200 * If the header field name is all upper-case, chances are that it's
3201 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3202 * not a problem -- they are regenerated later.
3204 if ((*header)[1] == 'O')
3206 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3211 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3212 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3215 p = strdup_or_die((*header)+6);
3217 q = strdup_or_die(p);
3219 freez(csp->http->hostport);
3220 csp->http->hostport = p;
3221 freez(csp->http->host);
3222 csp->http->host = q;
3223 q = strchr(csp->http->host, ':');
3226 /* Terminate hostname and evaluate port string */
3228 csp->http->port = atoi(q);
3232 csp->http->port = csp->http->ssl ? 443 : 80;
3235 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3236 csp->http->hostport, csp->http->host, csp->http->port);
3239 /* Signal client_host_adder() to return right away */
3240 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3246 /*********************************************************************
3248 * Function : client_if_modified_since
3250 * Description : Remove or modify the If-Modified-Since header.
3253 * 1 : csp = Current client state (buffers, headers, etc...)
3254 * 2 : header = On input, pointer to header to modify.
3255 * On output, pointer to the modified header, or NULL
3256 * to remove the header. This function frees the
3257 * original string if necessary.
3259 * Returns : JB_ERR_OK on success, or
3260 * JB_ERR_MEMORY on out-of-memory error.
3262 *********************************************************************/
3263 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3266 #ifdef HAVE_GMTIME_R
3269 struct tm *timeptr = NULL;
3274 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3277 * The client got an error message because of a temporary problem,
3278 * the problem is gone and the client now tries to revalidate our
3279 * error message on the real server. The revalidation would always
3280 * end with the transmission of the whole document and there is
3281 * no need to expose the bogus If-Modified-Since header.
3283 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3286 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3288 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3290 if ((0 == strcmpic(newval, "block")))
3292 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3295 else /* add random value */
3297 const char *header_time = *header + sizeof("If-Modified-Since:");
3299 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3301 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3306 long int hours, minutes, seconds;
3307 long int rtime = strtol(newval, &endptr, 0);
3308 const int negative_range = (rtime < 0);
3312 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3313 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3319 rtime = pick_from_range(rtime);
3323 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3326 tm += rtime * (negative_range ? -1 : 1);
3327 #ifdef HAVE_GMTIME_R
3328 timeptr = gmtime_r(&tm, &gmt);
3329 #elif defined(MUTEX_LOCKS_AVAILABLE)
3330 privoxy_mutex_lock(&gmtime_mutex);
3331 timeptr = gmtime(&tm);
3332 privoxy_mutex_unlock(&gmtime_mutex);
3334 timeptr = gmtime(&tm);
3336 if ((NULL == timeptr) || !strftime(newheader,
3337 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3339 log_error(LOG_LEVEL_ERROR,
3340 "Randomizing '%s' failed. Crunching the header without replacement.",
3347 *header = strdup("If-Modified-Since: ");
3348 string_append(header, newheader);
3350 if (*header == NULL)
3352 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3353 return JB_ERR_MEMORY;
3356 hours = rtime / 3600;
3357 minutes = rtime / 60 % 60;
3358 seconds = rtime % 60;
3360 log_error(LOG_LEVEL_HEADER,
3361 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3362 *header, (negative_range) ? "subtracted" : "added", hours,
3363 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3364 seconds, (seconds == 1) ? ")" : "s)");
3373 /*********************************************************************
3375 * Function : client_if_none_match
3377 * Description : Remove the If-None-Match header.
3380 * 1 : csp = Current client state (buffers, headers, etc...)
3381 * 2 : header = On input, pointer to header to modify.
3382 * On output, pointer to the modified header, or NULL
3383 * to remove the header. This function frees the
3384 * original string if necessary.
3386 * Returns : JB_ERR_OK on success, or
3387 * JB_ERR_MEMORY on out-of-memory error.
3389 *********************************************************************/
3390 static jb_err client_if_none_match(struct client_state *csp, char **header)
3392 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3394 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3402 /*********************************************************************
3404 * Function : client_x_filter
3406 * Description : Disables filtering if the client set "X-Filter: No".
3407 * Called from `sed'.
3410 * 1 : csp = Current client state (buffers, headers, etc...)
3411 * 2 : header = On input, pointer to header to modify.
3412 * On output, pointer to the modified header, or NULL
3413 * to remove the header. This function frees the
3414 * original string if necessary.
3416 * Returns : JB_ERR_OK on success
3418 *********************************************************************/
3419 jb_err client_x_filter(struct client_state *csp, char **header)
3421 if (0 == strcmpic(*header, "X-Filter: No"))
3423 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3425 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3429 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3431 log_error(LOG_LEVEL_HEADER,
3432 "force-text-mode overruled the client's request to fetch without filtering!");
3436 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3437 csp->flags |= CSP_FLAG_NO_FILTERING;
3438 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3440 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3448 /*********************************************************************
3450 * Function : client_range
3452 * Description : Removes Range, Request-Range and If-Range headers if
3453 * content filtering is enabled and the range doesn't
3456 * If the client's version of the document has been
3457 * altered by Privoxy, the server could interpret the
3458 * range differently than the client intended in which
3459 * case the user could end up with corrupted content.
3461 * If the range starts at byte 0 this isn't an issue
3462 * so the header can pass. Partial requests like this
3463 * are used to render preview images for videos without
3464 * downloading the whole video.
3466 * While HTTP doesn't require that range requests are
3467 * honoured and the client could simply abort the download
3468 * after receiving a sufficient amount of data, various
3469 * clients don't handle complete responses to range
3470 * requests gracefully and emit misleading error messages
3474 * 1 : csp = Current client state (buffers, headers, etc...)
3475 * 2 : header = On input, pointer to header to modify.
3476 * On output, pointer to the modified header, or NULL
3477 * to remove the header. This function frees the
3478 * original string if necessary.
3480 * Returns : JB_ERR_OK
3482 *********************************************************************/
3483 static jb_err client_range(struct client_state *csp, char **header)
3485 if (content_filters_enabled(csp->action)
3486 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3488 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3489 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3496 /* the following functions add headers directly to the header list */
3498 /*********************************************************************
3500 * Function : client_host_adder
3502 * Description : Adds the Host: header field if it is missing.
3503 * Called from `sed'.
3506 * 1 : csp = Current client state (buffers, headers, etc...)
3508 * Returns : JB_ERR_OK on success, or
3509 * JB_ERR_MEMORY on out-of-memory error.
3511 *********************************************************************/
3512 static jb_err client_host_adder(struct client_state *csp)
3517 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3519 /* Header already set by the client, nothing to do. */
3523 if (!csp->http->hostport || !*(csp->http->hostport))
3525 /* XXX: When does this happen and why is it OK? */
3526 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3531 * remove 'user:pass@' from 'proto://user:pass@host'
3533 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3539 p = csp->http->hostport;
3542 /* XXX: Just add it, we already made sure that it will be unique */
3543 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3544 err = enlist_unique_header(csp->headers, "Host", p);
3550 /*********************************************************************
3552 * Function : client_xtra_adder
3554 * Description : Used in the add_client_headers list. Called from `sed'.
3557 * 1 : csp = Current client state (buffers, headers, etc...)
3559 * Returns : JB_ERR_OK on success, or
3560 * JB_ERR_MEMORY on out-of-memory error.
3562 *********************************************************************/
3563 static jb_err client_xtra_adder(struct client_state *csp)
3565 struct list_entry *lst;
3568 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3569 lst ; lst = lst->next)
3571 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3572 err = enlist(csp->headers, lst->str);
3584 /*********************************************************************
3586 * Function : client_x_forwarded_for_adder
3588 * Description : Used in the add_client_headers list. Called from `sed'.
3591 * 1 : csp = Current client state (buffers, headers, etc...)
3593 * Returns : JB_ERR_OK on success, or
3594 * JB_ERR_MEMORY on out-of-memory error.
3596 *********************************************************************/
3597 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3599 char *header = NULL;
3602 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3603 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3604 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3607 * If we aren't adding X-Forwarded-For headers,
3608 * or we already appended an existing X-Forwarded-For
3609 * header, there's nothing left to do here.
3614 header = strdup("X-Forwarded-For: ");
3615 string_append(&header, csp->ip_addr_str);
3619 return JB_ERR_MEMORY;
3622 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3623 err = enlist(csp->headers, header);
3630 /*********************************************************************
3632 * Function : server_connection_adder
3634 * Description : Adds an appropriate "Connection:" header to csp->headers
3635 * unless the header was already present. Called from `sed'.
3638 * 1 : csp = Current client state (buffers, headers, etc...)
3640 * Returns : JB_ERR_OK on success, or
3641 * JB_ERR_MEMORY on out-of-memory error.
3643 *********************************************************************/
3644 static jb_err server_connection_adder(struct client_state *csp)
3646 const unsigned int flags = csp->flags;
3647 const char *response_status_line = csp->headers->first->str;
3648 static const char connection_close[] = "Connection: close";
3650 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3651 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3657 * XXX: if we downgraded the response, this check will fail.
3659 if ((csp->config->feature_flags &
3660 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3661 && (NULL != response_status_line)
3662 && !strncmpic(response_status_line, "HTTP/1.1", 8)
3663 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3664 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3668 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3669 "without Connection header implies keep-alive.");
3670 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3674 log_error(LOG_LEVEL_HEADER, "Adding: %s", connection_close);
3676 return enlist(csp->headers, connection_close);
3680 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3681 /*********************************************************************
3683 * Function : server_proxy_connection_adder
3685 * Description : Adds a "Proxy-Connection: keep-alive" header to
3686 * csp->headers when appropriate.
3689 * 1 : csp = Current client state (buffers, headers, etc...)
3691 * Returns : JB_ERR_OK on success, or
3692 * JB_ERR_MEMORY on out-of-memory error.
3694 *********************************************************************/
3695 static jb_err server_proxy_connection_adder(struct client_state *csp)
3697 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3698 jb_err err = JB_ERR_OK;
3700 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3701 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3702 && !(csp->flags & CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET)
3703 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3704 || (csp->flags & CSP_FLAG_CHUNKED)))
3706 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3707 err = enlist(csp->headers, proxy_connection_header);
3712 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3715 /*********************************************************************
3717 * Function : client_connection_header_adder
3719 * Description : Adds a proper "Connection:" header to csp->headers
3720 * unless the header was already present. Called from `sed'.
3723 * 1 : csp = Current client state (buffers, headers, etc...)
3725 * Returns : JB_ERR_OK on success, or
3726 * JB_ERR_MEMORY on out-of-memory error.
3728 *********************************************************************/
3729 static jb_err client_connection_header_adder(struct client_state *csp)
3731 static const char connection_close[] = "Connection: close";
3733 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3734 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3739 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3740 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3741 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3742 && (csp->http->ssl == 0)
3743 && !strcmpic(csp->http->ver,