1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
5 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Copyright : Written by and Copyright (C) 2001-2020 the
8 * Privoxy team. https://www.privoxy.org/
10 * Based on the Internet Junkbuster originally written
11 * by and Copyright (C) 1997 Anonymous Coders and
12 * Junkbusters Corporation. http://www.junkbusters.com
14 * This program is free software; you can redistribute it
15 * and/or modify it under the terms of the GNU General
16 * Public License as published by the Free Software
17 * Foundation; either version 2 of the License, or (at
18 * your option) any later version.
20 * This program is distributed in the hope that it will
21 * be useful, but WITHOUT ANY WARRANTY; without even the
22 * implied warranty of MERCHANTABILITY or FITNESS FOR A
23 * PARTICULAR PURPOSE. See the GNU General Public
24 * License for more details.
26 * The GNU General Public License should be included with
27 * this file. If not, you can view it at
28 * http://www.gnu.org/copyleft/gpl.html
29 * or write to the Free Software Foundation, Inc., 59
30 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 *********************************************************************/
39 #include <sys/types.h>
49 * Convince GNU's libc to provide a strptime prototype.
58 #define GZIP_IDENTIFIER_1 0x1f
59 #define GZIP_IDENTIFIER_2 0x8b
61 #define GZIP_FLAG_CHECKSUM 0x02
62 #define GZIP_FLAG_EXTRA_FIELDS 0x04
63 #define GZIP_FLAG_FILE_NAME 0x08
64 #define GZIP_FLAG_COMMENT 0x10
65 #define GZIP_FLAG_RESERVED_BITS 0xe0
68 #if !defined(_WIN32) && !defined(__OS2__)
74 #ifdef FEATURE_PTHREAD
76 /* jcc.h is for mutex semapores only */
77 #endif /* def FEATURE_PTHREAD */
82 #include "jbsockets.h"
92 static char *get_header_line(struct iob *iob);
93 static jb_err scan_headers(struct client_state *csp);
94 static jb_err header_tagger(struct client_state *csp, char *header);
95 static jb_err parse_header_time(const char *header_time, time_t *result);
96 static jb_err parse_time_header(const char *header, time_t *result);
98 static jb_err crumble (struct client_state *csp, char **header);
99 static jb_err filter_header (struct client_state *csp, char **header);
100 static jb_err client_connection (struct client_state *csp, char **header);
101 static jb_err client_referrer (struct client_state *csp, char **header);
102 static jb_err client_uagent (struct client_state *csp, char **header);
103 static jb_err client_ua (struct client_state *csp, char **header);
104 static jb_err client_from (struct client_state *csp, char **header);
105 static jb_err client_send_cookie (struct client_state *csp, char **header);
106 static jb_err client_x_forwarded (struct client_state *csp, char **header);
107 static jb_err client_accept_encoding (struct client_state *csp, char **header);
108 static jb_err client_te (struct client_state *csp, char **header);
109 static jb_err client_max_forwards (struct client_state *csp, char **header);
110 static jb_err client_host (struct client_state *csp, char **header);
111 static jb_err client_if_modified_since (struct client_state *csp, char **header);
112 static jb_err client_accept_language (struct client_state *csp, char **header);
113 static jb_err client_if_none_match (struct client_state *csp, char **header);
114 static jb_err crunch_client_header (struct client_state *csp, char **header);
115 static jb_err client_x_filter (struct client_state *csp, char **header);
116 static jb_err client_range (struct client_state *csp, char **header);
117 static jb_err client_expect (struct client_state *csp, char **header);
118 static jb_err server_set_cookie (struct client_state *csp, char **header);
119 static jb_err server_connection (struct client_state *csp, char **header);
120 static jb_err server_content_type (struct client_state *csp, char **header);
121 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
122 static jb_err server_content_md5 (struct client_state *csp, char **header);
123 static jb_err server_content_encoding (struct client_state *csp, char **header);
124 static jb_err server_transfer_coding (struct client_state *csp, char **header);
125 static jb_err server_http (struct client_state *csp, char **header);
126 static jb_err crunch_server_header (struct client_state *csp, char **header);
127 static jb_err server_last_modified (struct client_state *csp, char **header);
128 static jb_err server_content_disposition(struct client_state *csp, char **header);
130 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header);
133 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
134 static jb_err server_save_content_length(struct client_state *csp, char **header);
135 static jb_err server_keep_alive(struct client_state *csp, char **header);
136 static jb_err server_proxy_connection(struct client_state *csp, char **header);
137 static jb_err client_keep_alive(struct client_state *csp, char **header);
138 static jb_err client_save_content_length(struct client_state *csp, char **header);
139 static jb_err client_proxy_connection(struct client_state *csp, char **header);
140 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
142 static jb_err client_host_adder (struct client_state *csp);
143 static jb_err client_xtra_adder (struct client_state *csp);
144 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
145 static jb_err client_connection_header_adder(struct client_state *csp);
146 static jb_err server_connection_adder(struct client_state *csp);
147 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
148 static jb_err server_proxy_connection_adder(struct client_state *csp);
149 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
150 static jb_err proxy_authentication(struct client_state *csp, char **header);
152 static jb_err create_forged_referrer(char **header, const char *hostport);
153 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
154 static jb_err handle_conditional_hide_referrer_parameter(char **header,
155 const char *host, const int parameter_conditional_block);
156 static void create_content_length_header(unsigned long long content_length,
157 char *header, size_t buffer_length);
160 * List of functions to run on a list of headers.
164 /** The header prefix to match */
167 /** The length of the prefix to match */
170 /** The function to apply to this line */
171 const parser_func_ptr parser;
174 static const struct parsers client_patterns[] = {
175 { "referer:", 8, client_referrer },
176 { "user-agent:", 11, client_uagent },
177 { "ua-", 3, client_ua },
178 { "from:", 5, client_from },
179 { "cookie:", 7, client_send_cookie },
180 { "x-forwarded-for:", 16, client_x_forwarded },
181 { "Accept-Encoding:", 16, client_accept_encoding },
182 { "TE:", 3, client_te },
183 { "Host:", 5, client_host },
184 { "if-modified-since:", 18, client_if_modified_since },
185 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
186 { "Keep-Alive:", 11, client_keep_alive },
187 { "Content-Length:", 15, client_save_content_length },
188 { "Proxy-Connection:", 17, client_proxy_connection },
190 { "Keep-Alive:", 11, crumble },
191 { "Proxy-Connection:", 17, crumble },
193 { "connection:", 11, client_connection },
194 { "max-forwards:", 13, client_max_forwards },
195 { "Accept-Language:", 16, client_accept_language },
196 { "if-none-match:", 14, client_if_none_match },
197 { "Range:", 6, client_range },
198 { "Request-Range:", 14, client_range },
199 { "If-Range:", 9, client_range },
200 { "X-Filter:", 9, client_x_filter },
201 { "Proxy-Authorization:", 20, proxy_authentication },
203 { "Transfer-Encoding:", 18, client_transfer_encoding },
205 { "Expect:", 7, client_expect },
206 { "*", 0, crunch_client_header },
207 { "*", 0, filter_header },
211 static const struct parsers server_patterns[] = {
212 { "HTTP/", 5, server_http },
213 { "set-cookie:", 11, server_set_cookie },
214 { "connection:", 11, server_connection },
215 { "Content-Type:", 13, server_content_type },
216 { "Content-MD5:", 12, server_content_md5 },
217 { "Content-Encoding:", 17, server_content_encoding },
218 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
219 { "Content-Length:", 15, server_save_content_length },
220 { "Keep-Alive:", 11, server_keep_alive },
221 { "Proxy-Connection:", 17, server_proxy_connection },
223 { "Keep-Alive:", 11, crumble },
224 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
225 { "Transfer-Encoding:", 18, server_transfer_coding },
226 { "content-disposition:", 20, server_content_disposition },
227 { "Last-Modified:", 14, server_last_modified },
228 { "Proxy-Authenticate:", 19, proxy_authentication },
229 { "*", 0, crunch_server_header },
230 { "*", 0, filter_header },
234 static const add_header_func_ptr add_client_headers[] = {
236 client_x_forwarded_for_adder,
238 client_connection_header_adder,
242 static const add_header_func_ptr add_server_headers[] = {
243 server_connection_adder,
244 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
245 server_proxy_connection_adder,
246 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
250 /*********************************************************************
252 * Function : flush_iob
254 * Description : Write any pending "buffered" content.
257 * 1 : fd = file descriptor of the socket to read
258 * 2 : iob = The I/O buffer to flush, usually csp->iob.
259 * 3 : delay = Number of milliseconds to delay the writes
261 * Returns : On success, the number of bytes written are returned (zero
262 * indicates nothing was written). On error, -1 is returned,
263 * and errno is set appropriately. If count is zero and the
264 * file descriptor refers to a regular file, 0 will be
265 * returned without causing any other effect. For a special
266 * file, the results are not portable.
268 *********************************************************************/
269 long flush_iob(jb_socket fd, struct iob *iob, unsigned int delay)
271 long len = iob->eod - iob->cur;
278 if (write_socket_delayed(fd, iob->cur, (size_t)len, delay))
282 iob->eod = iob->cur = iob->buf;
288 /*********************************************************************
290 * Function : add_to_iob
292 * Description : Add content to the buffer, expanding the
293 * buffer if necessary.
296 * 1 : iob = Destination buffer.
297 * 2 : buffer_limit = Limit to which the destination may grow
298 * 3 : src = holds the content to be added
299 * 4 : n = number of bytes to be added
301 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
302 * or buffer limit reached.
304 *********************************************************************/
305 jb_err add_to_iob(struct iob *iob, const size_t buffer_limit, char *src, long n)
307 size_t used, offset, need;
310 if (n <= 0) return JB_ERR_OK;
312 used = (size_t)(iob->eod - iob->buf);
313 offset = (size_t)(iob->cur - iob->buf);
314 need = used + (size_t)n + 1;
317 * If the buffer can't hold the new data, extend it first.
318 * Use the next power of two if possible, else use the actual need.
320 if (need > buffer_limit)
322 log_error(LOG_LEVEL_INFO,
323 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
325 return JB_ERR_MEMORY;
328 if (need > iob->size)
330 size_t want = iob->size ? iob->size : 512;
337 if (want <= buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
341 else if (NULL != (p = (char *)realloc(iob->buf, need)))
347 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
348 return JB_ERR_MEMORY;
351 /* Update the iob pointers */
352 iob->cur = p + offset;
357 /* copy the new data into the iob buffer */
358 memcpy(iob->eod, src, (size_t)n);
360 /* point to the end of the data */
363 /* null terminate == cheap insurance */
371 /*********************************************************************
373 * Function : clear_iob
375 * Description : Frees the memory allocated for an I/O buffer and
376 * resets the structure.
379 * 1 : iob = I/O buffer to clear.
381 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
382 * or buffer limit reached.
384 *********************************************************************/
385 void clear_iob(struct iob *iob)
388 memset(iob, '\0', sizeof(*iob));
393 /*********************************************************************
395 * Function : decompress_iob
397 * Description : Decompress buffered page, expanding the
398 * buffer as necessary. csp->iob->cur
399 * should point to the the beginning of the
400 * compressed data block.
403 * 1 : csp = Current client state (buffers, headers, etc...)
405 * Returns : JB_ERR_OK on success,
406 * JB_ERR_MEMORY if out-of-memory limit reached, and
407 * JB_ERR_COMPRESS if error decompressing buffer.
409 *********************************************************************/
410 jb_err decompress_iob(struct client_state *csp)
412 char *buf; /* new, uncompressed buffer */
413 char *cur; /* Current iob position (to keep the original
414 * iob->cur unmodified if we return early) */
415 size_t bufsize; /* allocated size of the new buffer */
416 size_t old_size; /* Content size before decompression */
417 size_t skip_size; /* Number of bytes at the beginning of the iob
418 that we should NOT decompress. */
419 int status; /* return status of the inflate() call */
420 z_stream zstr; /* used by calls to zlib */
423 assert(csp->iob->cur - csp->iob->buf >= 0);
424 assert(csp->iob->eod - csp->iob->cur >= 0);
426 assert(csp->iob->cur - csp->iob->buf > 0);
427 assert(csp->iob->eod - csp->iob->cur > 0);
430 bufsize = csp->iob->size;
431 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
432 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
436 if (bufsize < (size_t)10)
439 * This is to protect the parsing of gzipped data,
440 * but it should(?) be valid for deflated data also.
442 log_error(LOG_LEVEL_ERROR,
443 "Insufficient data to start decompression. Bytes in buffer: %d",
444 csp->iob->eod - csp->iob->cur);
445 return JB_ERR_COMPRESS;
448 if (csp->content_type & CT_GZIP)
451 * Our task is slightly complicated by the facts that data
452 * compressed by gzip does not include a zlib header, and
453 * that there is no easily accessible interface in zlib to
454 * handle a gzip header. We strip off the gzip header by
455 * hand, and later inform zlib not to expect a header.
459 * Strip off the gzip header. Please see RFC 1952 for more
460 * explanation of the appropriate fields.
462 if (((*cur++ & 0xff) != GZIP_IDENTIFIER_1)
463 || ((*cur++ & 0xff) != GZIP_IDENTIFIER_2)
464 || (*cur++ != Z_DEFLATED))
466 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
467 return JB_ERR_COMPRESS;
472 if (flags & GZIP_FLAG_RESERVED_BITS)
474 /* The gzip header has reserved bits set; bail out. */
475 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
476 return JB_ERR_COMPRESS;
480 * Skip mtime (4 bytes), extra flags (1 byte)
481 * and OS type (1 byte).
485 /* Skip extra fields if necessary. */
486 if (flags & GZIP_FLAG_EXTRA_FIELDS)
489 * Skip a given number of bytes, specified
490 * as a 16-bit little-endian value.
492 * XXX: this code is untested and should probably be removed.
496 skip_bytes += *cur++ << 8;
499 * The number of bytes to skip should be positive
500 * and we'd like to stay in the buffer.
502 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
504 log_error(LOG_LEVEL_ERROR,
505 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
507 return JB_ERR_COMPRESS;
509 log_error(LOG_LEVEL_INFO,
510 "Skipping %d bytes for gzip compression. Does this sound right?",
515 /* Skip the filename if necessary. */
516 if (flags & GZIP_FLAG_FILE_NAME)
518 /* A null-terminated string is supposed to follow. */
519 while (*cur++ && (cur < csp->iob->eod));
522 /* Skip the comment if necessary. */
523 if (flags & GZIP_FLAG_COMMENT)
525 /* A null-terminated string is supposed to follow. */
526 while (*cur++ && (cur < csp->iob->eod));
529 /* Skip the CRC if necessary. */
530 if (flags & GZIP_FLAG_CHECKSUM)
535 if (cur >= csp->iob->eod)
538 * If the current position pointer reached or passed
539 * the buffer end, we were obviously tricked to skip
542 log_error(LOG_LEVEL_ERROR,
543 "Malformed gzip header detected. Aborting decompression.");
544 return JB_ERR_COMPRESS;
548 else if (csp->content_type & CT_DEFLATE)
551 * In theory (that is, according to RFC 1950), deflate-compressed
552 * data should begin with a two-byte zlib header and have an
553 * adler32 checksum at the end. It seems that in practice only
554 * the raw compressed data is sent. Note that this means that
555 * we are not RFC 1950-compliant here, but the advantage is that
556 * this actually works. :)
558 * We add a dummy null byte to tell zlib where the data ends,
559 * and later inform it not to expect a header.
561 * Fortunately, add_to_iob() has thoughtfully null-terminated
562 * the buffer; we can just increment the end pointer to include
569 log_error(LOG_LEVEL_ERROR,
570 "Unable to determine compression format for decompression");
571 return JB_ERR_COMPRESS;
574 /* Set up the fields required by zlib. */
575 zstr.next_in = (Bytef *)cur;
576 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
577 zstr.zalloc = Z_NULL;
579 zstr.opaque = Z_NULL;
582 * Passing -MAX_WBITS to inflateInit2 tells the library
583 * that there is no zlib header.
585 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
587 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
588 return JB_ERR_COMPRESS;
592 * Next, we allocate new storage for the inflated data.
593 * We don't modify the existing iob yet, so in case there
594 * is error in decompression we can recover gracefully.
596 buf = zalloc(bufsize);
599 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
600 return JB_ERR_MEMORY;
603 assert(bufsize >= skip_size);
604 memcpy(buf, csp->iob->buf, skip_size);
605 zstr.avail_out = (uInt)(bufsize - skip_size);
606 zstr.next_out = (Bytef *)buf + skip_size;
608 /* Try to decompress the whole stream in one shot. */
609 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
611 /* We need to allocate more memory for the output buffer. */
613 char *tmpbuf; /* used for realloc'ing the buffer */
614 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
616 if (0 == zstr.avail_in)
619 * If zlib wants more data then there's a problem, because
620 * the complete compressed file should have been buffered.
622 log_error(LOG_LEVEL_ERROR,
623 "Unexpected end of compressed iob. Using what we got so far.");
628 * If we reached the buffer limit and still didn't have enough
629 * memory, just give up. Due to the ceiling enforced by the next
630 * if block we could actually check for equality here, but as it
631 * can be easily mistaken for a bug we don't.
633 if (bufsize >= csp->config->buffer_limit)
635 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
637 return JB_ERR_MEMORY;
640 /* Try doubling the buffer size each time. */
643 /* Don't exceed the buffer limit. */
644 if (bufsize > csp->config->buffer_limit)
646 bufsize = csp->config->buffer_limit;
649 /* Try to allocate the new buffer. */
650 tmpbuf = realloc(buf, bufsize);
653 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
655 return JB_ERR_MEMORY;
659 char *oldnext_out = (char *)zstr.next_out;
662 * Update the fields for inflate() to use the new
663 * buffer, which may be in a location different from
666 zstr.avail_out += (uInt)(bufsize - oldbufsize);
667 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
670 * Compare with an uglier method of calculating these values
671 * that doesn't require the extra oldbufsize variable.
673 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
674 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
680 if (Z_STREAM_ERROR == inflateEnd(&zstr))
682 log_error(LOG_LEVEL_ERROR,
683 "Inconsistent stream state after decompression: %s", zstr.msg);
685 * XXX: Intentionally no return.
687 * According to zlib.h, Z_STREAM_ERROR is returned
688 * "if the stream state was inconsistent".
690 * I assume in this case inflate()'s status
691 * would also be something different than Z_STREAM_END
692 * so this check should be redundant, but lets see.
696 if ((status != Z_STREAM_END) && (0 != zstr.avail_in))
699 * We failed to decompress the stream and it's
700 * not simply because of missing data.
702 log_error(LOG_LEVEL_ERROR,
703 "Unexpected error while decompressing to the buffer (iob): %s",
705 return JB_ERR_COMPRESS;
709 * Finally, we can actually update the iob, since the
710 * decompression was successful. First, free the old
713 freez(csp->iob->buf);
715 /* Now, update the iob to use the new buffer. */
717 csp->iob->cur = csp->iob->buf + skip_size;
718 csp->iob->eod = (char *)zstr.next_out;
719 csp->iob->size = bufsize;
722 * Make sure the new uncompressed iob obeys some minimal
723 * consistency conditions.
725 if ((csp->iob->buf <= csp->iob->cur)
726 && (csp->iob->cur <= csp->iob->eod)
727 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
729 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
730 if (new_size > (size_t)0)
732 log_error(LOG_LEVEL_RE_FILTER,
733 "Decompression successful. Old size: %d, new size: %d.",
738 /* zlib thinks this is OK, so lets do the same. */
739 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
744 /* It seems that zlib did something weird. */
745 log_error(LOG_LEVEL_ERROR,
746 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
747 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
748 csp->iob->eod, csp->iob->buf + csp->iob->size);
749 return JB_ERR_COMPRESS;
755 #endif /* defined(FEATURE_ZLIB) */
758 /*********************************************************************
760 * Function : normalize_lws
762 * Description : Reduces unquoted linear whitespace in headers to
763 * a single space in accordance with RFC 7230 3.2.4.
764 * This simplifies parsing and filtering later on.
767 * 1 : header = A header with linear whitespace to reduce.
771 *********************************************************************/
772 static void normalize_lws(char *header)
778 if (privoxy_isspace(*p) && privoxy_isspace(*(p+1)))
782 while (privoxy_isspace(*q))
786 log_error(LOG_LEVEL_HEADER, "Reducing whitespace in '%s'", header);
792 log_error(LOG_LEVEL_HEADER,
793 "Converting tab to space in '%s'", header);
798 char *end_of_token = strstr(p+1, "\"");
800 if (NULL != end_of_token)
802 /* Don't mess with quoted text. */
807 log_error(LOG_LEVEL_HEADER,
808 "Ignoring single quote in '%s'", header);
814 p = strchr(header, ':');
815 if ((p != NULL) && (p != header) && privoxy_isspace(*(p-1)))
818 * There's still space before the colon.
826 /*********************************************************************
828 * Function : get_header
830 * Description : This (odd) routine will parse the csp->iob
831 * to get the next complete header.
834 * 1 : iob = The I/O buffer to parse, usually csp->iob.
836 * Returns : Any one of the following:
838 * 1) a pointer to a dynamically allocated string that contains a header line
839 * 2) NULL indicating that the end of the header was reached
840 * 3) "" indicating that the end of the iob was reached before finding
841 * a complete header line.
843 *********************************************************************/
844 char *get_header(struct iob *iob)
848 header = get_header_line(iob);
850 if ((header == NULL) || (*header == '\0'))
853 * No complete header read yet, tell the client.
858 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
861 * Header spans multiple lines, append the next one.
863 char *continued_header;
865 continued_header = get_header_line(iob);
866 if ((continued_header == NULL) || (*continued_header == '\0'))
869 * No complete header read yet, return what we got.
870 * XXX: Should "unread" header instead.
872 log_error(LOG_LEVEL_INFO,
873 "Failed to read a multi-line header properly: '%s'",
878 if (JB_ERR_OK != string_join(&header, continued_header))
880 log_error(LOG_LEVEL_FATAL,
881 "Out of memory while appending multiple headers.");
885 /* XXX: remove before next stable release. */
886 log_error(LOG_LEVEL_HEADER,
887 "Merged multiple header lines to: '%s'",
892 normalize_lws(header);
899 /*********************************************************************
901 * Function : get_header_line
903 * Description : This (odd) routine will parse the csp->iob
904 * to get the next header line.
907 * 1 : iob = The I/O buffer to parse, usually csp->iob.
909 * Returns : Any one of the following:
911 * 1) a pointer to a dynamically allocated string that contains a header line
912 * 2) NULL indicating that the end of the header was reached
913 * 3) "" indicating that the end of the iob was reached before finding
914 * a complete header line.
916 *********************************************************************/
917 static char *get_header_line(struct iob *iob)
921 if ((iob->cur == NULL)
922 || ((p = strchr(iob->cur, '\n')) == NULL))
924 return(""); /* couldn't find a complete header */
929 ret = strdup(iob->cur);
932 /* FIXME No way to handle error properly */
933 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
939 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
941 /* is this a blank line (i.e. the end of the header) ? */
953 /*********************************************************************
955 * Function : get_header_value
957 * Description : Get the value of a given header from a chained list
958 * of header lines or return NULL if no such header is
959 * present in the list.
962 * 1 : header_list = pointer to list
963 * 2 : header_name = string with name of header to look for.
964 * Trailing colon required, capitalization
967 * Returns : NULL if not found, else value of header
969 *********************************************************************/
970 char *get_header_value(const struct list *header_list, const char *header_name)
972 struct list_entry *cur_entry;
978 length = strlen(header_name);
980 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
984 if (!strncmpic(cur_entry->str, header_name, length))
987 * Found: return pointer to start of value
989 ret = cur_entry->str + length;
990 while (*ret && privoxy_isspace(*ret)) ret++;
1004 /*********************************************************************
1006 * Function : scan_headers
1008 * Description : Scans headers, applies tags and updates action bits.
1011 * 1 : csp = Current client state (buffers, headers, etc...)
1013 * Returns : JB_ERR_OK
1015 *********************************************************************/
1016 static jb_err scan_headers(struct client_state *csp)
1018 struct list_entry *h; /* Header */
1019 jb_err err = JB_ERR_OK;
1021 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1023 /* Header crunch()ed in previous run? -> ignore */
1024 if (h->str == NULL) continue;
1025 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1026 err = header_tagger(csp, h->str);
1033 /*********************************************************************
1035 * Function : enforce_header_order
1037 * Description : Enforces a given header order.
1040 * 1 : headers = List of headers to order.
1041 * 2 : ordered_headers = List of ordered header names.
1045 *********************************************************************/
1046 static void enforce_header_order(struct list *headers, const struct list *ordered_headers)
1048 struct list_entry *sorted_header;
1049 struct list new_headers[1];
1050 struct list_entry *header;
1052 init_list(new_headers);
1054 /* The request line is always the first "header" */
1056 assert(NULL != headers->first->str);
1057 enlist(new_headers, headers->first->str);
1058 freez(headers->first->str)
1060 /* Enlist the specified headers in the given order */
1062 for (sorted_header = ordered_headers->first; sorted_header != NULL;
1063 sorted_header = sorted_header->next)
1065 const size_t sorted_header_length = strlen(sorted_header->str);
1066 for (header = headers->first; header != NULL; header = header->next)
1068 /* Header enlisted in previous run? -> ignore */
1069 if (header->str == NULL) continue;
1071 if (0 == strncmpic(sorted_header->str, header->str, sorted_header_length)
1072 && (header->str[sorted_header_length] == ':'))
1074 log_error(LOG_LEVEL_HEADER, "Enlisting sorted header %s", header->str);
1075 if (JB_ERR_OK != enlist(new_headers, header->str))
1077 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1084 /* Enlist the rest of the headers behind the ordered ones */
1085 for (header = headers->first; header != NULL; header = header->next)
1087 /* Header enlisted in previous run? -> ignore */
1088 if (header->str == NULL) continue;
1090 log_error(LOG_LEVEL_HEADER,
1091 "Enlisting left-over header %s", header->str);
1092 if (JB_ERR_OK != enlist(new_headers, header->str))
1094 log_error(LOG_LEVEL_HEADER, "Failed to enlist %s", header->str);
1099 list_remove_all(headers);
1100 list_duplicate(headers, new_headers);
1101 list_remove_all(new_headers);
1107 /*********************************************************************
1111 * Description : add, delete or modify lines in the HTTP header streams.
1112 * On entry, it receives a linked list of headers space
1113 * that was allocated dynamically (both the list nodes
1114 * and the header contents).
1116 * As a side effect it frees the space used by the original
1120 * 1 : csp = Current client state (buffers, headers, etc...)
1121 * 2 : filter_server_headers = Boolean to switch between
1122 * server and header filtering.
1124 * Returns : JB_ERR_OK in case off success, or
1125 * JB_ERR_MEMORY on some out-of-memory errors, or
1126 * JB_ERR_PARSE in case of fatal parse errors.
1128 *********************************************************************/
1129 jb_err sed(struct client_state *csp, int filter_server_headers)
1131 /* XXX: use more descriptive names. */
1132 struct list_entry *p;
1133 const struct parsers *v;
1134 const add_header_func_ptr *f;
1135 jb_err err = JB_ERR_OK;
1139 if (filter_server_headers)
1141 v = server_patterns;
1142 f = add_server_headers;
1143 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_RESPONSE_TAG_PATTERN);
1147 v = client_patterns;
1148 f = add_client_headers;
1149 check_negative_tag_patterns(csp, PATTERN_SPEC_NO_REQUEST_TAG_PATTERN);
1152 while (v->str != NULL)
1154 for (p = csp->headers->first; p != NULL; p = p->next)
1156 /* Header crunch()ed in previous run? -> ignore */
1157 if (p->str == NULL) continue;
1159 /* Does the current parser handle this header? */
1160 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1161 (v->len == CHECK_EVERY_HEADER_REMAINING))
1163 err = v->parser(csp, &(p->str));
1164 if (err != JB_ERR_OK)
1173 /* place additional headers on the csp->headers list */
1174 while ((err == JB_ERR_OK) && (*f))
1180 if (!filter_server_headers && !list_is_empty(csp->config->ordered_client_headers))
1182 enforce_header_order(csp->headers, csp->config->ordered_client_headers);
1189 #ifdef FEATURE_HTTPS_INSPECTION
1190 /*********************************************************************
1192 * Function : sed_https
1194 * Description : add, delete or modify lines in the HTTPS client
1195 * header streams. Wrapper around sed().
1198 * 1 : csp = Current client state (buffers, headers, etc...)
1200 * Returns : JB_ERR_OK in case off success, or
1201 * JB_ERR_MEMORY on some out-of-memory errors, or
1202 * JB_ERR_PARSE in case of fatal parse errors.
1204 *********************************************************************/
1205 jb_err sed_https(struct client_state *csp)
1208 struct list headers;
1211 * Temporarily replace csp->headers with csp->https_headers
1212 * to trick sed() into filtering the https headers.
1214 headers.first = csp->headers->first;
1215 headers.last = csp->headers->last;
1216 csp->headers->first = csp->https_headers->first;
1217 csp->headers->last = csp->https_headers->last;
1220 * Start with fresh tags. Already existing tags may
1221 * be set again. This is necessary to overrule
1222 * URL-based patterns.
1224 destroy_list(csp->tags);
1227 * We want client header filters and taggers
1228 * so temporarily remove the flag.
1230 csp->flags &= ~CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1231 err = sed(csp, FILTER_CLIENT_HEADERS);
1232 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1235 * Update the last header which may have changed
1236 * due to header additions,
1238 csp->https_headers->last = csp->headers->last;
1240 csp->headers->first = headers.first;
1241 csp->headers->last = headers.last;
1245 #endif /* def FEATURE_HTTPS_INSPECTION */
1248 /*********************************************************************
1250 * Function : update_server_headers
1252 * Description : Updates server headers after the body has been modified.
1255 * 1 : csp = Current client state (buffers, headers, etc...)
1257 * Returns : JB_ERR_OK in case off success, or
1258 * JB_ERR_MEMORY on out-of-memory error.
1260 *********************************************************************/
1261 jb_err update_server_headers(struct client_state *csp)
1263 jb_err err = JB_ERR_OK;
1265 static const struct parsers server_patterns_light[] = {
1266 { "Content-Length:", 15, server_adjust_content_length },
1267 { "Transfer-Encoding:", 18, server_transfer_coding },
1269 { "Content-Encoding:", 17, server_adjust_content_encoding },
1270 #endif /* def FEATURE_ZLIB */
1274 if (strncmpic(csp->http->cmd, "HEAD", 4))
1276 const struct parsers *v;
1277 struct list_entry *p;
1279 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1281 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1283 /* Header crunch()ed in previous run? -> ignore */
1284 if (p->str == NULL) continue;
1286 /* Does the current parser handle this header? */
1287 if (strncmpic(p->str, v->str, v->len) == 0)
1289 err = v->parser(csp, (char **)&(p->str));
1295 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1296 if ((JB_ERR_OK == err)
1297 && (csp->flags & CSP_FLAG_MODIFIED)
1298 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
1299 && !(csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET))
1303 create_content_length_header(csp->content_length, header, sizeof(header));
1304 err = enlist(csp->headers, header);
1305 if (JB_ERR_OK == err)
1307 log_error(LOG_LEVEL_HEADER,
1308 "Content modified with no Content-Length header set. "
1309 "Created: %s.", header);
1310 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1313 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1315 #ifdef FEATURE_COMPRESSION
1316 if ((JB_ERR_OK == err)
1317 && (csp->flags & CSP_FLAG_BUFFERED_CONTENT_DEFLATED))
1319 err = enlist_unique_header(csp->headers, "Content-Encoding", "deflate");
1320 if (JB_ERR_OK == err)
1322 log_error(LOG_LEVEL_HEADER, "Added header: Content-Encoding: deflate");
1331 /*********************************************************************
1333 * Function : header_tagger
1335 * Description : Executes all text substitutions from applying
1336 * tag actions and saves the result as tag.
1338 * XXX: Shares enough code with filter_header() and
1339 * pcrs_filter_response() to warrant some helper functions.
1342 * 1 : csp = Current client state (buffers, headers, etc...)
1343 * 2 : header = Header that is used as tagger input
1345 * Returns : JB_ERR_OK on success and always succeeds
1347 *********************************************************************/
1348 static jb_err header_tagger(struct client_state *csp, char *header)
1350 enum filter_type wanted_filter_type;
1351 int multi_action_index;
1354 struct re_filterfile_spec *b;
1355 struct list_entry *tag_name;
1357 const size_t header_length = strlen(header);
1359 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1361 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1362 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1366 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1367 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1370 if (list_is_empty(csp->action->multi[multi_action_index])
1371 || filters_available(csp) == FALSE)
1373 /* Return early if no taggers apply or if none are available. */
1377 /* Execute all applying taggers */
1378 for (tag_name = csp->action->multi[multi_action_index]->first;
1379 NULL != tag_name; tag_name = tag_name->next)
1381 char *modified_tag = NULL;
1383 size_t size = header_length;
1386 b = get_filter(csp, tag_name->str, wanted_filter_type);
1392 joblist = b->joblist;
1394 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1396 if (NULL == joblist)
1398 log_error(LOG_LEVEL_RE_FILTER,
1399 "Tagger %s has empty joblist. Nothing to do.", b->name);
1403 /* execute their pcrs_joblist on the header. */
1404 for (job = joblist; NULL != job; job = job->next)
1406 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1410 /* Success, continue with the modified version. */
1419 /* Tagger doesn't match */
1422 /* Regex failure, log it but continue anyway. */
1423 assert(NULL != header);
1424 log_error(LOG_LEVEL_ERROR,
1425 "Problems with tagger \'%s\' and header \'%s\': %s",
1426 b->name, *header, pcrs_strerror(hits));
1428 freez(modified_tag);
1432 if (b->dynamic) pcrs_free_joblist(joblist);
1434 /* If this tagger matched */
1440 * There is no technical limitation which makes
1441 * it impossible to use empty tags, but I assume
1442 * no one would do it intentionally.
1445 log_error(LOG_LEVEL_INFO,
1446 "Tagger \'%s\' created an empty tag. Ignored.", b->name);
1450 if (!list_contains_item(csp->tags, tag))
1452 if (JB_ERR_OK != enlist(csp->tags, tag))
1454 log_error(LOG_LEVEL_ERROR,
1455 "Insufficient memory to add tag \'%s\', "
1456 "based on tagger \'%s\' and header \'%s\'",
1457 tag, b->name, *header);
1461 char *action_message;
1463 * update the action bits right away, to make
1464 * tagging based on tags set by earlier taggers
1465 * of the same kind possible.
1467 if (update_action_bits_for_tag(csp, tag))
1469 action_message = "Action bits updated accordingly.";
1473 action_message = "No action bits update necessary.";
1476 log_error(LOG_LEVEL_HEADER,
1477 "Tagger \'%s\' added tag \'%s\'. %s",
1478 b->name, tag, action_message);
1483 /* XXX: Is this log-worthy? */
1484 log_error(LOG_LEVEL_HEADER,
1485 "Tagger \'%s\' didn't add tag \'%s\'. Tag already present",
1495 /* here begins the family of parser functions that reformat header lines */
1497 /*********************************************************************
1499 * Function : filter_header
1501 * Description : Executes all text substitutions from all applying
1502 * +(server|client)-header-filter actions on the header.
1503 * Most of the code was copied from pcrs_filter_response,
1504 * including the rather short variable names
1507 * 1 : csp = Current client state (buffers, headers, etc...)
1508 * 2 : header = On input, pointer to header to modify.
1509 * On output, pointer to the modified header, or NULL
1510 * to remove the header. This function frees the
1511 * original string if necessary.
1513 * Returns : JB_ERR_OK on success and always succeeds
1515 *********************************************************************/
1516 static jb_err filter_header(struct client_state *csp, char **header)
1520 size_t size = strlen(*header);
1522 char *newheader = NULL;
1525 struct re_filterfile_spec *b;
1526 struct list_entry *filtername;
1528 enum filter_type wanted_filter_type;
1529 int multi_action_index;
1531 if (csp->flags & CSP_FLAG_NO_FILTERING)
1536 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1538 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1539 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1543 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1544 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1547 if (list_is_empty(csp->action->multi[multi_action_index])
1548 || filters_available(csp) == FALSE)
1550 /* Return early if no filters apply or if none are available. */
1554 /* Execute all applying header filters */
1555 for (filtername = csp->action->multi[multi_action_index]->first;
1556 filtername != NULL; filtername = filtername->next)
1558 int current_hits = 0;
1561 b = get_filter(csp, filtername->str, wanted_filter_type);
1567 joblist = b->joblist;
1569 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1571 if (NULL == joblist)
1573 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1577 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1578 *header, size, b->name);
1580 /* Apply all jobs from the joblist */
1581 for (job = joblist; NULL != job; job = job->next)
1583 matches = pcrs_execute(job, *header, size, &newheader, &size);
1586 current_hits += matches;
1587 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1589 *header = newheader;
1591 else if (0 == matches)
1593 /* Filter doesn't change header */
1599 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1600 *header, b->name, pcrs_strerror(matches));
1601 if (newheader != NULL)
1603 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1609 if (b->dynamic) pcrs_free_joblist(joblist);
1611 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1612 hits += current_hits;
1616 * Additionally checking for hits is important because if
1617 * the continue hack is triggered, server headers can
1618 * arrive empty to separate multiple heads from each other.
1620 if ((0 == size) && hits)
1622 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1630 /*********************************************************************
1632 * Function : server_connection
1634 * Description : Makes sure a proper "Connection:" header is
1635 * set and signals connection_header_adder to
1639 * 1 : csp = Current client state (buffers, headers, etc...)
1640 * 2 : header = On input, pointer to header to modify.
1641 * On output, pointer to the modified header, or NULL
1642 * to remove the header. This function frees the
1643 * original string if necessary.
1645 * Returns : JB_ERR_OK on success.
1647 *********************************************************************/
1648 static jb_err server_connection(struct client_state *csp, char **header)
1650 if (!strcmpic(*header, "Connection: keep-alive")
1651 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1652 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
1656 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1657 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1659 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1662 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1664 log_error(LOG_LEVEL_HEADER,
1665 "Keeping the server header '%s' around.", *header);
1668 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1670 char *old_header = *header;
1672 *header = strdup_or_die("Connection: close");
1673 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1678 /* Signal server_connection_adder() to return early. */
1679 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1685 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1686 /*********************************************************************
1688 * Function : server_keep_alive
1690 * Description : Stores the server's keep alive timeout.
1693 * 1 : csp = Current client state (buffers, headers, etc...)
1694 * 2 : header = On input, pointer to header to modify.
1695 * On output, pointer to the modified header, or NULL
1696 * to remove the header. This function frees the
1697 * original string if necessary.
1699 * Returns : JB_ERR_OK.
1701 *********************************************************************/
1702 static jb_err server_keep_alive(struct client_state *csp, char **header)
1704 unsigned int keep_alive_timeout;
1705 const char *timeout_position = strstr(*header, "timeout=");
1707 if ((NULL == timeout_position)
1708 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1710 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1714 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1716 log_error(LOG_LEVEL_HEADER,
1717 "Reducing keep-alive timeout from %u to %u.",
1718 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1719 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1723 /* XXX: Is this log worthy? */
1724 log_error(LOG_LEVEL_HEADER,
1725 "Server keep-alive timeout is %u. Sticking with %u.",
1726 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1728 csp->flags |= CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET;
1737 /*********************************************************************
1739 * Function : server_proxy_connection
1741 * Description : Figures out whether or not we should add a
1742 * Proxy-Connection header.
1745 * 1 : csp = Current client state (buffers, headers, etc...)
1746 * 2 : header = On input, pointer to header to modify.
1747 * On output, pointer to the modified header, or NULL
1748 * to remove the header. This function frees the
1749 * original string if necessary.
1751 * Returns : JB_ERR_OK.
1753 *********************************************************************/
1754 static jb_err server_proxy_connection(struct client_state *csp, char **header)
1756 csp->flags |= CSP_FLAG_SERVER_PROXY_CONNECTION_HEADER_SET;
1761 /*********************************************************************
1763 * Function : proxy_authentication
1765 * Description : Removes headers that are relevant for proxy
1766 * authentication unless forwarding them has
1767 * been explicitly requested.
1770 * 1 : csp = Current client state (buffers, headers, etc...)
1771 * 2 : header = On input, pointer to header to modify.
1772 * On output, pointer to the modified header, or NULL
1773 * to remove the header. This function frees the
1774 * original string if necessary.
1776 * Returns : JB_ERR_OK.
1778 *********************************************************************/
1779 static jb_err proxy_authentication(struct client_state *csp, char **header)
1781 if ((csp->config->feature_flags &
1782 RUNTIME_FEATURE_FORWARD_PROXY_AUTHENTICATION_HEADERS) == 0) {
1783 log_error(LOG_LEVEL_HEADER,
1784 "Forwarding proxy authentication headers is disabled. Crunching: %s", *header);
1791 /*********************************************************************
1793 * Function : client_keep_alive
1795 * Description : Stores the client's keep alive timeout.
1798 * 1 : csp = Current client state (buffers, headers, etc...)
1799 * 2 : header = On input, pointer to header to modify.
1800 * On output, pointer to the modified header, or NULL
1801 * to remove the header. This function frees the
1802 * original string if necessary.
1804 * Returns : JB_ERR_OK.
1806 *********************************************************************/
1807 static jb_err client_keep_alive(struct client_state *csp, char **header)
1809 unsigned int keep_alive_timeout;
1810 char *timeout_position;
1812 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1814 log_error(LOG_LEVEL_HEADER,
1815 "keep-alive support is disabled. Crunching: %s.", *header);
1820 /* Check for parameter-less format "Keep-Alive: 100" */
1821 timeout_position = strstr(*header, ": ");
1822 if ((NULL == timeout_position)
1823 || (1 != sscanf(timeout_position, ": %u", &keep_alive_timeout)))
1825 /* Assume parameter format "Keep-Alive: timeout=100" */
1826 timeout_position = strstr(*header, "timeout=");
1827 if ((NULL == timeout_position)
1828 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1830 log_error(LOG_LEVEL_HEADER,
1831 "Couldn't parse: '%s'. Using default timeout %u",
1832 *header, csp->config->keep_alive_timeout);
1839 if (keep_alive_timeout < csp->config->keep_alive_timeout)
1841 log_error(LOG_LEVEL_HEADER,
1842 "Reducing keep-alive timeout from %u to %u.",
1843 csp->config->keep_alive_timeout, keep_alive_timeout);
1844 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1848 /* XXX: Is this log worthy? */
1849 log_error(LOG_LEVEL_HEADER,
1850 "Client keep-alive timeout is %u. Sticking with %u.",
1851 keep_alive_timeout, csp->config->keep_alive_timeout);
1859 /*********************************************************************
1861 * Function : get_content_length
1863 * Description : Gets the content length specified in a
1864 * Content-Length header.
1867 * 1 : header_value = The Content-Length header value.
1868 * 2 : length = Storage to return the value.
1870 * Returns : JB_ERR_OK on success, or
1871 * JB_ERR_PARSE if no value is recognized.
1873 *********************************************************************/
1874 static jb_err get_content_length(const char *header_value, unsigned long long *length)
1877 #if SIZEOF_LONG_LONG < 8
1878 #error sizeof(unsigned long long) too small
1880 if (1 != sscanf(header_value, "%I64u", length))
1882 if (1 != sscanf(header_value, "%llu", length))
1885 return JB_ERR_PARSE;
1892 /*********************************************************************
1894 * Function : client_save_content_length
1896 * Description : Save the Content-Length sent by the client.
1899 * 1 : csp = Current client state (buffers, headers, etc...)
1900 * 2 : header = On input, pointer to header to modify.
1901 * On output, pointer to the modified header, or NULL
1902 * to remove the header. This function frees the
1903 * original string if necessary.
1905 * Returns : JB_ERR_OK on success, or
1906 * JB_ERR_MEMORY on out-of-memory error.
1908 *********************************************************************/
1909 static jb_err client_save_content_length(struct client_state *csp, char **header)
1911 unsigned long long content_length = 0;
1912 const char *header_value;
1914 assert(*(*header+14) == ':');
1916 header_value = *header + 15;
1917 if (JB_ERR_OK != get_content_length(header_value, &content_length))
1919 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
1924 csp->expected_client_content_length = content_length;
1929 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1933 /*********************************************************************
1935 * Function : client_connection
1937 * Description : Makes sure a proper "Connection:" header is
1938 * set and signals connection_header_adder
1942 * 1 : csp = Current client state (buffers, headers, etc...)
1943 * 2 : header = On input, pointer to header to modify.
1944 * On output, pointer to the modified header, or NULL
1945 * to remove the header. This function frees the
1946 * original string if necessary.
1948 * Returns : JB_ERR_OK on success.
1950 *********************************************************************/
1951 static jb_err client_connection(struct client_state *csp, char **header)
1953 static const char connection_close[] = "Connection: close";
1955 if (!strcmpic(*header, connection_close))
1957 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1958 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
1959 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1961 if (!strcmpic(csp->http->version, "HTTP/1.1"))
1963 log_error(LOG_LEVEL_HEADER,
1964 "Removing \'%s\' to imply keep-alive.", *header);
1967 * While we imply keep-alive to the server,
1968 * we have to remember that the client didn't.
1970 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1974 char *old_header = *header;
1976 *header = strdup_or_die("Connection: keep-alive");
1977 log_error(LOG_LEVEL_HEADER,
1978 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1984 log_error(LOG_LEVEL_HEADER,
1985 "Keeping the client header '%s' around. "
1986 "The connection will not be kept alive.",
1988 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1991 else if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1992 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1994 log_error(LOG_LEVEL_HEADER,
1995 "Keeping the client header '%s' around. "
1996 "The server connection will be kept alive if possible.",
1998 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1999 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2003 char *old_header = *header;
2005 *header = strdup_or_die(connection_close);
2006 log_error(LOG_LEVEL_HEADER,
2007 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2011 /* Signal client_connection_header_adder() to return early. */
2012 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2018 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2019 /*********************************************************************
2021 * Function : client_proxy_connection
2023 * Description : Sets the CLIENT_CONNECTION_KEEP_ALIVE flag when
2024 * appropriate and removes the Proxy-Connection
2028 * 1 : csp = Current client state (buffers, headers, etc...)
2029 * 2 : header = On input, pointer to header to modify.
2030 * On output, pointer to the modified header, or NULL
2031 * to remove the header. This function frees the
2032 * original string if necessary.
2034 * Returns : JB_ERR_OK
2036 *********************************************************************/
2037 static jb_err client_proxy_connection(struct client_state *csp, char **header)
2039 if (0 == (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2040 && (csp->http->ssl == 0)
2041 && (NULL == strstr(*header, "close")))
2043 log_error(LOG_LEVEL_HEADER,
2044 "The client connection can be kept alive due to: %s", *header);
2045 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2047 crumble(csp, header);
2051 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2054 /*********************************************************************
2056 * Function : client_transfer_encoding
2058 * Description : Raise the CSP_FLAG_CHUNKED_CLIENT_BODY flag if
2059 * the request body is "chunked"
2061 * XXX: Currently not called through sed() as we
2062 * need the flag earlier on. Should be fixed.
2065 * 1 : csp = Current client state (buffers, headers, etc...)
2066 * 2 : header = On input, pointer to header to modify.
2067 * On output, pointer to the modified header, or NULL
2068 * to remove the header. This function frees the
2069 * original string if necessary.
2071 * Returns : JB_ERR_OK on success, or
2073 *********************************************************************/
2074 jb_err client_transfer_encoding(struct client_state *csp, char **header)
2076 if (strstr(*header, "chunked"))
2078 csp->flags |= CSP_FLAG_CHUNKED_CLIENT_BODY;
2079 log_error(LOG_LEVEL_HEADER, "Expecting chunked client body");
2086 /*********************************************************************
2088 * Function : client_expect
2090 * Description : Raise the CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION
2091 * if the Expect header value is unsupported.
2093 * Rejecting unsupported expectations is a RFC 7231 5.1.1
2094 * MAY and a RFC 2616 (obsolete) MUST.
2097 * 1 : csp = Current client state (buffers, headers, etc...)
2098 * 2 : header = On input, pointer to header to modify.
2099 * On output, pointer to the modified header, or NULL
2100 * to remove the header. This function frees the
2101 * original string if necessary.
2103 * Returns : JB_ERR_OK on success, or
2105 *********************************************************************/
2106 jb_err client_expect(struct client_state *csp, char **header)
2108 if (0 != strcmpic(*header, "Expect: 100-continue"))
2110 csp->flags |= CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION;
2111 log_error(LOG_LEVEL_HEADER,
2112 "Unsupported client expectaction: %s", *header);
2120 /*********************************************************************
2122 * Function : crumble
2124 * Description : This is called if a header matches a pattern to "crunch"
2127 * 1 : csp = Current client state (buffers, headers, etc...)
2128 * 2 : header = On input, pointer to header to modify.
2129 * On output, pointer to the modified header, or NULL
2130 * to remove the header. This function frees the
2131 * original string if necessary.
2133 * Returns : JB_ERR_OK on success, or
2134 * JB_ERR_MEMORY on out-of-memory error.
2136 *********************************************************************/
2137 static jb_err crumble(struct client_state *csp, char **header)
2140 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2146 /*********************************************************************
2148 * Function : crunch_server_header
2150 * Description : Crunch server header if it matches a string supplied by the
2151 * user. Called from `sed'.
2154 * 1 : csp = Current client state (buffers, headers, etc...)
2155 * 2 : header = On input, pointer to header to modify.
2156 * On output, pointer to the modified header, or NULL
2157 * to remove the header. This function frees the
2158 * original string if necessary.
2160 * Returns : JB_ERR_OK on success and always succeeds
2162 *********************************************************************/
2163 static jb_err crunch_server_header(struct client_state *csp, char **header)
2165 const char *crunch_pattern;
2167 /* Do we feel like crunching? */
2168 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2170 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2172 /* Is the current header the lucky one? */
2173 if (strstr(*header, crunch_pattern))
2175 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2184 /*********************************************************************
2186 * Function : server_content_type
2188 * Description : Set the content-type for filterable types (text/.*,
2189 * .*xml.*, .*script.* and image/gif) unless filtering has been
2190 * forbidden (CT_TABOO) while parsing earlier headers.
2191 * NOTE: Since text/plain is commonly used by web servers
2192 * for files whose correct type is unknown, we don't
2193 * set CT_TEXT for it.
2196 * 1 : csp = Current client state (buffers, headers, etc...)
2197 * 2 : header = On input, pointer to header to modify.
2198 * On output, pointer to the modified header, or NULL
2199 * to remove the header. This function frees the
2200 * original string if necessary.
2202 * Returns : JB_ERR_OK on success, or
2203 * JB_ERR_MEMORY on out-of-memory error.
2205 *********************************************************************/
2206 static jb_err server_content_type(struct client_state *csp, char **header)
2208 /* Remove header if it isn't the first Content-Type header */
2209 if ((csp->content_type & CT_DECLARED))
2211 if (content_filters_enabled(csp->action))
2214 * Making sure the client interprets the content the same way
2215 * Privoxy did is only relevant if Privoxy modified it.
2217 * Checking for this is "hard" as it's not yet known when
2218 * this function is called, thus go shopping and and just
2219 * check if Privoxy could filter it.
2221 * The main thing is that we don't mess with the headers
2222 * unless the user signalled that it's acceptable.
2224 log_error(LOG_LEVEL_HEADER,
2225 "Multiple Content-Type headers detected. "
2226 "Removing and ignoring: %s",
2234 * Signal that the Content-Type has been set.
2236 csp->content_type |= CT_DECLARED;
2238 if (!(csp->content_type & CT_TABOO))
2241 * XXX: The assumption that text/plain is a sign of
2242 * binary data seems to be somewhat unreasonable nowadays
2243 * and should be dropped after 3.0.8 is out.
2245 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2246 || strstr(*header, "xml")
2247 || strstr(*header, "script"))
2249 csp->content_type |= CT_TEXT;
2251 else if (strstr(*header, "image/gif"))
2253 csp->content_type |= CT_GIF;
2258 * Are we messing with the content type?
2260 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2263 * Make sure the user doesn't accidentally
2264 * change the content type of binary documents.
2266 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2270 *header = strdup_or_die("Content-Type: ");
2272 err = string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2273 if (JB_ERR_OK != err)
2275 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2276 return JB_ERR_MEMORY;
2278 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2282 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2283 "It doesn't look like a content type that should be filtered. "
2284 "Enable force-text-mode if you know what you're doing.", *header);
2292 /*********************************************************************
2294 * Function : server_transfer_coding
2296 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2297 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2298 * - Remove header if body was chunked but has been
2299 * de-chunked for filtering.
2302 * 1 : csp = Current client state (buffers, headers, etc...)
2303 * 2 : header = On input, pointer to header to modify.
2304 * On output, pointer to the modified header, or NULL
2305 * to remove the header. This function frees the
2306 * original string if necessary.
2308 * Returns : JB_ERR_OK on success, or
2309 * JB_ERR_MEMORY on out-of-memory error.
2311 *********************************************************************/
2312 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2315 * Turn off pcrs and gif filtering if body compressed
2317 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2321 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2323 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2324 csp->http->cmd, *header);
2325 #endif /* def FEATURE_ZLIB */
2326 csp->content_type = CT_TABOO;
2330 * Raise flag if body chunked
2332 if (strstr(*header, "chunked"))
2334 csp->flags |= CSP_FLAG_CHUNKED;
2337 * If the body was modified, it has been de-chunked first
2338 * and the header must be removed.
2340 * FIXME: If there is more than one transfer encoding,
2341 * only the "chunked" part should be removed here.
2343 if (csp->flags & CSP_FLAG_MODIFIED)
2345 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2354 /*********************************************************************
2356 * Function : server_content_encoding
2358 * Description : Used to check if the content is compressed, and if
2359 * FEATURE_ZLIB is disabled, filtering is disabled as
2362 * If FEATURE_ZLIB is enabled and the compression type
2363 * supported, the content is marked for decompression.
2365 * XXX: Doesn't properly deal with multiple or with
2366 * unsupported but unknown encodings.
2367 * Is case-sensitive but shouldn't be.
2370 * 1 : csp = Current client state (buffers, headers, etc...)
2371 * 2 : header = On input, pointer to header to modify.
2372 * On output, pointer to the modified header, or NULL
2373 * to remove the header. This function frees the
2374 * original string if necessary.
2376 * Returns : JB_ERR_OK on success, or
2377 * JB_ERR_MEMORY on out-of-memory error.
2379 *********************************************************************/
2380 static jb_err server_content_encoding(struct client_state *csp, char **header)
2383 if (strstr(*header, "sdch"))
2386 * Shared Dictionary Compression over HTTP isn't supported,
2387 * filtering it anyway is pretty much guaranteed to mess up
2390 csp->content_type |= CT_TABOO;
2393 * Log a warning if the user expects the content to be filtered.
2395 if (content_filters_enabled(csp->action))
2397 log_error(LOG_LEVEL_INFO,
2398 "SDCH-compressed content detected, content filtering disabled. "
2399 "Consider suppressing SDCH offers made by the client.");
2402 else if (strstr(*header, "gzip"))
2404 /* Mark for gzip decompression */
2405 csp->content_type |= CT_GZIP;
2407 else if (strstr(*header, "deflate"))
2409 /* Mark for zlib decompression */
2410 csp->content_type |= CT_DEFLATE;
2412 else if (strstr(*header, "compress"))
2415 * We can't decompress this; therefore we can't filter
2418 csp->content_type |= CT_TABOO;
2420 #else /* !defined(FEATURE_ZLIB) */
2422 * XXX: Using a black list here isn't the right approach.
2424 * In case of SDCH, building with zlib support isn't
2427 if (strstr(*header, "gzip") ||
2428 strstr(*header, "compress") ||
2429 strstr(*header, "deflate") ||
2430 strstr(*header, "sdch"))
2433 * Body is compressed, turn off pcrs and gif filtering.
2435 csp->content_type |= CT_TABOO;
2438 * Log a warning if the user expects the content to be filtered.
2440 if (content_filters_enabled(csp->action))
2442 log_error(LOG_LEVEL_INFO,
2443 "Compressed content detected, content filtering disabled. "
2444 "Consider recompiling Privoxy with zlib support or "
2445 "enable the prevent-compression action.");
2448 #endif /* defined(FEATURE_ZLIB) */
2456 /*********************************************************************
2458 * Function : server_adjust_content_encoding
2460 * Description : Remove the Content-Encoding header if the
2461 * decompression was successful and the content
2462 * has been modified.
2465 * 1 : csp = Current client state (buffers, headers, etc...)
2466 * 2 : header = On input, pointer to header to modify.
2467 * On output, pointer to the modified header, or NULL
2468 * to remove the header. This function frees the
2469 * original string if necessary.
2471 * Returns : JB_ERR_OK on success, or
2472 * JB_ERR_MEMORY on out-of-memory error.
2474 *********************************************************************/
2475 static jb_err server_adjust_content_encoding(struct client_state *csp, char **header)
2477 if ((csp->flags & CSP_FLAG_MODIFIED)
2478 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2481 * We successfully decompressed the content,
2482 * and have to clean the header now, so the
2483 * client no longer expects compressed data.
2485 * XXX: There is a difference between cleaning
2486 * and removing it completely.
2488 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2495 #endif /* defined(FEATURE_ZLIB) */
2498 /*********************************************************************
2500 * Function : server_adjust_content_length
2502 * Description : Adjust Content-Length header if we modified
2506 * 1 : csp = Current client state (buffers, headers, etc...)
2507 * 2 : header = On input, pointer to header to modify.
2508 * On output, pointer to the modified header, or NULL
2509 * to remove the header. This function frees the
2510 * original string if necessary.
2512 * Returns : JB_ERR_OK on success, or
2513 * JB_ERR_MEMORY on out-of-memory error.
2515 *********************************************************************/
2516 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2518 /* Regenerate header if the content was modified. */
2519 if (csp->flags & CSP_FLAG_MODIFIED)
2521 const size_t header_length = 50;
2523 *header = malloc(header_length);
2524 if (*header == NULL)
2526 return JB_ERR_MEMORY;
2528 create_content_length_header(csp->content_length, *header, header_length);
2529 log_error(LOG_LEVEL_HEADER,
2530 "Adjusted Content-Length to %llu", csp->content_length);
2537 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2538 /*********************************************************************
2540 * Function : server_save_content_length
2542 * Description : Save the Content-Length sent by the server.
2545 * 1 : csp = Current client state (buffers, headers, etc...)
2546 * 2 : header = On input, pointer to header to modify.
2547 * On output, pointer to the modified header, or NULL
2548 * to remove the header. This function frees the
2549 * original string if necessary.
2551 * Returns : JB_ERR_OK on success, or
2552 * JB_ERR_MEMORY on out-of-memory error.
2554 *********************************************************************/
2555 static jb_err server_save_content_length(struct client_state *csp, char **header)
2557 unsigned long long content_length = 0;
2558 const char *header_value;
2560 assert(*(*header+14) == ':');
2562 header_value = *header + 15;
2563 if (JB_ERR_OK != get_content_length(header_value, &content_length))
2565 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2570 csp->expected_content_length = content_length;
2571 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
2572 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2577 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2580 /*********************************************************************
2582 * Function : server_content_md5
2584 * Description : Crumble any Content-MD5 headers if the document was
2585 * modified. FIXME: Should we re-compute instead?
2588 * 1 : csp = Current client state (buffers, headers, etc...)
2589 * 2 : header = On input, pointer to header to modify.
2590 * On output, pointer to the modified header, or NULL
2591 * to remove the header. This function frees the
2592 * original string if necessary.
2594 * Returns : JB_ERR_OK on success, or
2595 * JB_ERR_MEMORY on out-of-memory error.
2597 *********************************************************************/
2598 static jb_err server_content_md5(struct client_state *csp, char **header)
2600 if (csp->flags & CSP_FLAG_MODIFIED)
2602 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2610 /*********************************************************************
2612 * Function : server_content_disposition
2614 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2615 * Called from `sed'.
2618 * 1 : csp = Current client state (buffers, headers, etc...)
2619 * 2 : header = On input, pointer to header to modify.
2620 * On output, pointer to the modified header, or NULL
2621 * to remove the header. This function frees the
2622 * original string if necessary.
2624 * Returns : JB_ERR_OK on success, or
2625 * JB_ERR_MEMORY on out-of-memory error.
2627 *********************************************************************/
2628 static jb_err server_content_disposition(struct client_state *csp, char **header)
2633 * Are we messing with the Content-Disposition header?
2635 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2641 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2643 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2646 * Blocking content-disposition header
2648 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2655 * Replacing Content-Disposition header
2658 *header = strdup("Content-Disposition: ");
2659 string_append(header, newval);
2661 if (*header != NULL)
2663 log_error(LOG_LEVEL_HEADER,
2664 "Content-Disposition header crunched and replaced with: %s", *header);
2667 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2671 /*********************************************************************
2673 * Function : server_last_modified
2675 * Description : Changes Last-Modified header to the actual date
2676 * to help hide-if-modified-since.
2677 * Called from `sed'.
2680 * 1 : csp = Current client state (buffers, headers, etc...)
2681 * 2 : header = On input, pointer to header to modify.
2682 * On output, pointer to the modified header, or NULL
2683 * to remove the header. This function frees the
2684 * original string if necessary.
2686 * Returns : JB_ERR_OK on success, or
2687 * JB_ERR_MEMORY on out-of-memory error.
2689 *********************************************************************/
2690 static jb_err server_last_modified(struct client_state *csp, char **header)
2693 time_t last_modified;
2697 * Are we messing with the Last-Modified header?
2699 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2705 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2707 if (0 == strcmpic(newval, "block"))
2710 * Blocking Last-Modified header. Useless but why not.
2712 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2716 else if (0 == strcmpic(newval, "reset-to-request-time"))
2719 * Setting Last-Modified Header to now.
2722 get_http_time(0, buf, sizeof(buf));
2724 *header = strdup("Last-Modified: ");
2725 string_append(header, buf);
2727 if (*header == NULL)
2729 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2733 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2736 else if (0 == strcmpic(newval, "randomize"))
2738 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2740 if (JB_ERR_OK != parse_time_header(*header, &last_modified))
2742 log_error(LOG_LEVEL_HEADER,
2743 "Couldn't parse time in %s (crunching!)", *header);
2749 struct tm *timeptr = NULL;
2751 #ifdef HAVE_GMTIME_R
2755 rtime = (long int)difftime(now, last_modified);
2758 long int days, hours, minutes, seconds;
2759 const int negative_delta = (rtime < 0);
2764 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2766 rtime = pick_from_range(rtime);
2771 last_modified += rtime;
2772 #ifdef HAVE_GMTIME_R
2773 timeptr = gmtime_r(&last_modified, &gmt);
2774 #elif defined(MUTEX_LOCKS_AVAILABLE)
2775 privoxy_mutex_lock(&gmtime_mutex);
2776 timeptr = gmtime(&last_modified);
2778 timeptr = gmtime(&last_modified);
2780 if ((NULL == timeptr) || !strftime(newheader,
2781 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
2783 #if !defined(HAVE_GMTIME_R) && defined(MUTEX_LOCKS_AVAILABLE)
2784 privoxy_mutex_unlock(&gmtime_mutex);
2786 log_error(LOG_LEVEL_ERROR,
2787 "Randomizing '%s' failed. Crunching the header without replacement.",
2792 #if !defined(HAVE_GMTIME_R) && defined(MUTEX_LOCKS_AVAILABLE)
2793 privoxy_mutex_unlock(&gmtime_mutex);
2796 *header = strdup("Last-Modified: ");
2797 string_append(header, newheader);
2799 if (*header == NULL)
2801 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2802 return JB_ERR_MEMORY;
2805 days = rtime / (3600 * 24);
2806 hours = rtime / 3600 % 24;
2807 minutes = rtime / 60 % 60;
2808 seconds = rtime % 60;
2810 log_error(LOG_LEVEL_HEADER,
2811 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2812 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2813 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2817 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2826 /*********************************************************************
2828 * Function : client_accept_encoding
2830 * Description : Rewrite the client's Accept-Encoding header so that
2831 * if doesn't allow compression, if the action applies.
2832 * Note: For HTTP/1.0 the absence of the header is enough.
2835 * 1 : csp = Current client state (buffers, headers, etc...)
2836 * 2 : header = On input, pointer to header to modify.
2837 * On output, pointer to the modified header, or NULL
2838 * to remove the header. This function frees the
2839 * original string if necessary.
2841 * Returns : JB_ERR_OK on success, or
2842 * JB_ERR_MEMORY on out-of-memory error.
2844 *********************************************************************/
2845 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2847 #ifdef FEATURE_COMPRESSION
2848 if ((csp->config->feature_flags & RUNTIME_FEATURE_COMPRESSION)
2849 && strstr(*header, "deflate"))
2851 csp->flags |= CSP_FLAG_CLIENT_SUPPORTS_DEFLATE;
2854 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2856 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2864 /*********************************************************************
2866 * Function : client_te
2868 * Description : Rewrite the client's TE header so that
2869 * if doesn't allow compression, if the action applies.
2872 * 1 : csp = Current client state (buffers, headers, etc...)
2873 * 2 : header = On input, pointer to header to modify.
2874 * On output, pointer to the modified header, or NULL
2875 * to remove the header. This function frees the
2876 * original string if necessary.
2878 * Returns : JB_ERR_OK on success, or
2879 * JB_ERR_MEMORY on out-of-memory error.
2881 *********************************************************************/
2882 static jb_err client_te(struct client_state *csp, char **header)
2884 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2887 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2894 /*********************************************************************
2896 * Function : client_referrer
2898 * Description : Handle the "referer" config setting properly.
2899 * Called from `sed'.
2902 * 1 : csp = Current client state (buffers, headers, etc...)
2903 * 2 : header = On input, pointer to header to modify.
2904 * On output, pointer to the modified header, or NULL
2905 * to remove the header. This function frees the
2906 * original string if necessary.
2908 * Returns : JB_ERR_OK on success, or
2909 * JB_ERR_MEMORY on out-of-memory error.
2911 *********************************************************************/
2912 static jb_err client_referrer(struct client_state *csp, char **header)
2914 const char *parameter;
2915 /* booleans for parameters we have to check multiple times */
2916 int parameter_conditional_block;
2917 int parameter_conditional_forge;
2919 #ifdef FEATURE_FORCE_LOAD
2921 * Since the referrer can include the prefix even
2922 * if the request itself is non-forced, we must
2923 * clean it unconditionally.
2925 * XXX: strclean is too broad
2927 strclean(*header, FORCE_PREFIX);
2928 #endif /* def FEATURE_FORCE_LOAD */
2930 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2932 /* Nothing left to do */
2936 parameter = csp->action->string[ACTION_STRING_REFERER];
2937 assert(parameter != NULL);
2938 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2939 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2941 if (!parameter_conditional_block && !parameter_conditional_forge)
2944 * As conditional-block and conditional-forge are the only
2945 * parameters that rely on the original referrer, we can
2946 * remove it now for all the others.
2951 if (0 == strcmpic(parameter, "block"))
2953 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2956 else if (parameter_conditional_block || parameter_conditional_forge)
2958 return handle_conditional_hide_referrer_parameter(header,
2959 csp->http->hostport, parameter_conditional_block);
2961 else if (0 == strcmpic(parameter, "forge"))
2963 return create_forged_referrer(header, csp->http->hostport);
2967 /* interpret parameter as user-supplied referer to fake */
2968 return create_fake_referrer(header, parameter);
2973 /*********************************************************************
2975 * Function : client_accept_language
2977 * Description : Handle the "Accept-Language" config setting properly.
2978 * Called from `sed'.
2981 * 1 : csp = Current client state (buffers, headers, etc...)
2982 * 2 : header = On input, pointer to header to modify.
2983 * On output, pointer to the modified header, or NULL
2984 * to remove the header. This function frees the
2985 * original string if necessary.
2987 * Returns : JB_ERR_OK on success, or
2988 * JB_ERR_MEMORY on out-of-memory error.
2990 *********************************************************************/
2991 static jb_err client_accept_language(struct client_state *csp, char **header)
2996 * Are we messing with the Accept-Language?
2998 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3000 /*I don't think so*/
3004 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3006 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3009 * Blocking Accept-Language header
3011 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3018 * Replacing Accept-Language header
3021 *header = strdup("Accept-Language: ");
3022 string_append(header, newval);
3024 if (*header == NULL)
3026 log_error(LOG_LEVEL_ERROR,
3027 "Insufficient memory. Accept-Language header crunched without replacement.");
3031 log_error(LOG_LEVEL_HEADER,
3032 "Accept-Language header crunched and replaced with: %s", *header);
3035 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3039 /*********************************************************************
3041 * Function : crunch_client_header
3043 * Description : Crunch client header if it matches a string supplied by the
3044 * user. Called from `sed'.
3047 * 1 : csp = Current client state (buffers, headers, etc...)
3048 * 2 : header = On input, pointer to header to modify.
3049 * On output, pointer to the modified header, or NULL
3050 * to remove the header. This function frees the
3051 * original string if necessary.
3053 * Returns : JB_ERR_OK on success and always succeeds
3055 *********************************************************************/
3056 static jb_err crunch_client_header(struct client_state *csp, char **header)
3058 const char *crunch_pattern;
3060 /* Do we feel like crunching? */
3061 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3063 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3065 /* Is the current header the lucky one? */
3066 if (strstr(*header, crunch_pattern))
3068 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3076 /*********************************************************************
3078 * Function : client_uagent
3080 * Description : Handle the "user-agent" config setting properly
3081 * and remember its original value to enable browser
3082 * bug workarounds. Called from `sed'.
3085 * 1 : csp = Current client state (buffers, headers, etc...)
3086 * 2 : header = On input, pointer to header to modify.
3087 * On output, pointer to the modified header, or NULL
3088 * to remove the header. This function frees the
3089 * original string if necessary.
3091 * Returns : JB_ERR_OK on success, or
3092 * JB_ERR_MEMORY on out-of-memory error.
3094 *********************************************************************/
3095 static jb_err client_uagent(struct client_state *csp, char **header)
3099 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3104 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3111 *header = strdup("User-Agent: ");
3112 string_append(header, newval);
3114 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3116 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3120 /*********************************************************************
3122 * Function : client_ua
3124 * Description : Handle "ua-" headers properly. Called from `sed'.
3127 * 1 : csp = Current client state (buffers, headers, etc...)
3128 * 2 : header = On input, pointer to header to modify.
3129 * On output, pointer to the modified header, or NULL
3130 * to remove the header. This function frees the
3131 * original string if necessary.
3133 * Returns : JB_ERR_OK on success, or
3134 * JB_ERR_MEMORY on out-of-memory error.
3136 *********************************************************************/
3137 static jb_err client_ua(struct client_state *csp, char **header)
3139 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3141 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3149 /*********************************************************************
3151 * Function : client_from
3153 * Description : Handle the "from" config setting properly.
3154 * Called from `sed'.
3157 * 1 : csp = Current client state (buffers, headers, etc...)
3158 * 2 : header = On input, pointer to header to modify.
3159 * On output, pointer to the modified header, or NULL
3160 * to remove the header. This function frees the
3161 * original string if necessary.
3163 * Returns : JB_ERR_OK on success, or
3164 * JB_ERR_MEMORY on out-of-memory error.
3166 *********************************************************************/
3167 static jb_err client_from(struct client_state *csp, char **header)
3171 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3178 newval = csp->action->string[ACTION_STRING_FROM];
3181 * Are we blocking the e-mail address?
3183 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
3185 log_error(LOG_LEVEL_HEADER, "crunched From!");
3189 log_error(LOG_LEVEL_HEADER, " modified");
3191 *header = strdup("From: ");
3192 string_append(header, newval);
3194 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3198 /*********************************************************************
3200 * Function : client_send_cookie
3202 * Description : Crunches the "cookie" header if necessary.
3203 * Called from `sed'.
3205 * XXX: Stupid name, doesn't send squat.
3208 * 1 : csp = Current client state (buffers, headers, etc...)
3209 * 2 : header = On input, pointer to header to modify.
3210 * On output, pointer to the modified header, or NULL
3211 * to remove the header. This function frees the
3212 * original string if necessary.
3214 * Returns : JB_ERR_OK on success, or
3215 * JB_ERR_MEMORY on out-of-memory error.
3217 *********************************************************************/
3218 static jb_err client_send_cookie(struct client_state *csp, char **header)
3220 if (csp->action->flags & ACTION_CRUNCH_OUTGOING_COOKIES)
3222 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3230 /*********************************************************************
3232 * Function : client_x_forwarded
3234 * Description : Handle the "x-forwarded-for" config setting properly,
3235 * also used in the add_client_headers list. Called from `sed'.
3238 * 1 : csp = Current client state (buffers, headers, etc...)
3239 * 2 : header = On input, pointer to header to modify.
3240 * On output, pointer to the modified header, or NULL
3241 * to remove the header. This function frees the
3242 * original string if necessary.
3244 * Returns : JB_ERR_OK on success, or
3245 * JB_ERR_MEMORY on out-of-memory error.
3247 *********************************************************************/
3248 jb_err client_x_forwarded(struct client_state *csp, char **header)
3250 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3252 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3254 if (0 == strcmpic(parameter, "block"))
3257 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3259 else if (0 == strcmpic(parameter, "add"))
3261 string_append(header, ", ");
3262 string_append(header, csp->ip_addr_str);
3264 if (*header == NULL)
3266 return JB_ERR_MEMORY;
3268 log_error(LOG_LEVEL_HEADER,
3269 "Appended client IP address to %s", *header);
3270 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3274 log_error(LOG_LEVEL_FATAL,
3275 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3283 /*********************************************************************
3285 * Function : client_max_forwards
3287 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3288 * from the value of the Max-Forwards header field.
3291 * 1 : csp = Current client state (buffers, headers, etc...)
3292 * 2 : header = On input, pointer to header to modify.
3293 * On output, pointer to the modified header, or NULL
3294 * to remove the header. This function frees the
3295 * original string if necessary.
3297 * Returns : JB_ERR_OK on success, or
3298 * JB_ERR_MEMORY on out-of-memory error.
3300 *********************************************************************/
3301 static jb_err client_max_forwards(struct client_state *csp, char **header)
3305 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3306 (0 == strcmpic(csp->http->gpc, "options")))
3308 assert(*(*header+12) == ':');
3309 if (1 == sscanf(*header+12, ": %d", &max_forwards))
3311 if (max_forwards > 0)
3313 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
3314 log_error(LOG_LEVEL_HEADER,
3315 "Max-Forwards value for %s request reduced to %d.",
3316 csp->http->gpc, max_forwards);
3318 else if (max_forwards < 0)
3320 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3326 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3335 /*********************************************************************
3337 * Function : client_host
3339 * Description : If the request URI did not contain host and
3340 * port information, parse and evaluate the Host
3344 * 1 : csp = Current client state (buffers, headers, etc...)
3345 * 2 : header = On input, pointer to header to modify.
3346 * On output, pointer to the modified header, or NULL
3347 * to remove the header. This function frees the
3348 * original string if necessary.
3350 * Returns : JB_ERR_OK on success, or
3351 * JB_ERR_MEMORY on out-of-memory error.
3353 *********************************************************************/
3354 static jb_err client_host(struct client_state *csp, char **header)
3358 if (strlen(*header) < 7)
3360 log_error(LOG_LEVEL_HEADER, "Removing empty Host header");
3365 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3366 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3369 p = strdup_or_die((*header)+6);
3371 q = strdup_or_die(p);
3373 freez(csp->http->hostport);
3374 csp->http->hostport = p;
3375 freez(csp->http->host);
3376 csp->http->host = q;
3377 q = strchr(csp->http->host, ':');
3380 /* Terminate hostname and evaluate port string */
3382 csp->http->port = atoi(q);
3386 csp->http->port = csp->http->ssl ? 443 : 80;
3389 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3390 csp->http->hostport, csp->http->host, csp->http->port);
3393 /* Signal client_host_adder() to return right away */
3394 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3400 /*********************************************************************
3402 * Function : client_if_modified_since
3404 * Description : Remove or modify the If-Modified-Since header.
3407 * 1 : csp = Current client state (buffers, headers, etc...)
3408 * 2 : header = On input, pointer to header to modify.
3409 * On output, pointer to the modified header, or NULL
3410 * to remove the header. This function frees the
3411 * original string if necessary.
3413 * Returns : JB_ERR_OK on success, or
3414 * JB_ERR_MEMORY on out-of-memory error.
3416 *********************************************************************/
3417 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3420 #ifdef HAVE_GMTIME_R
3423 struct tm *timeptr = NULL;
3428 if (0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3431 * The client got an error message because of a temporary problem,
3432 * the problem is gone and the client now tries to revalidate our
3433 * error message on the real server. The revalidation would always
3434 * end with the transmission of the whole document and there is
3435 * no need to expose the bogus If-Modified-Since header.
3437 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3440 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3442 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3444 if ((0 == strcmpic(newval, "block")))
3446 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3449 else /* add random value */
3451 if (JB_ERR_OK != parse_time_header(*header, &tm))
3453 log_error(LOG_LEVEL_HEADER,
3454 "Couldn't parse time in %s (crunching!)", *header);
3459 long int hours, minutes, seconds;
3460 long int rtime = strtol(newval, &endptr, 0);
3461 const int negative_range = (rtime < 0);
3465 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3466 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3472 rtime = pick_from_range(rtime);
3476 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3479 tm += rtime * (negative_range ? -1 : 1);
3480 #ifdef HAVE_GMTIME_R
3481 timeptr = gmtime_r(&tm, &gmt);
3482 #elif defined(MUTEX_LOCKS_AVAILABLE)
3483 privoxy_mutex_lock(&gmtime_mutex);
3484 timeptr = gmtime(&tm);
3486 timeptr = gmtime(&tm);
3488 if ((NULL == timeptr) || !strftime(newheader,
3489 sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr))
3491 #if !defined(HAVE_GMTIME_R) && defined(MUTEX_LOCKS_AVAILABLE)
3492 privoxy_mutex_unlock(&gmtime_mutex);
3494 log_error(LOG_LEVEL_ERROR,
3495 "Randomizing '%s' failed. Crunching the header without replacement.",
3500 #if !defined(HAVE_GMTIME_R) && defined(MUTEX_LOCKS_AVAILABLE)
3501 privoxy_mutex_unlock(&gmtime_mutex);
3504 *header = strdup("If-Modified-Since: ");
3505 string_append(header, newheader);
3507 if (*header == NULL)
3509 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3510 return JB_ERR_MEMORY;
3513 hours = rtime / 3600;
3514 minutes = rtime / 60 % 60;
3515 seconds = rtime % 60;
3517 log_error(LOG_LEVEL_HEADER,
3518 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3519 *header, (negative_range) ? "subtracted" : "added", hours,
3520 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3521 seconds, (seconds == 1) ? ")" : "s)");
3530 /*********************************************************************
3532 * Function : client_if_none_match
3534 * Description : Remove the If-None-Match header.
3537 * 1 : csp = Current client state (buffers, headers, etc...)
3538 * 2 : header = On input, pointer to header to modify.
3539 * On output, pointer to the modified header, or NULL
3540 * to remove the header. This function frees the
3541 * original string if necessary.
3543 * Returns : JB_ERR_OK on success, or
3544 * JB_ERR_MEMORY on out-of-memory error.
3546 *********************************************************************/
3547 static jb_err client_if_none_match(struct client_state *csp, char **header)
3549 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3551 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3559 /*********************************************************************
3561 * Function : client_x_filter
3563 * Description : Disables filtering if the client set "X-Filter: No".
3564 * Called from `sed'.
3567 * 1 : csp = Current client state (buffers, headers, etc...)
3568 * 2 : header = On input, pointer to header to modify.
3569 * On output, pointer to the modified header, or NULL
3570 * to remove the header. This function frees the
3571 * original string if necessary.
3573 * Returns : JB_ERR_OK on success
3575 *********************************************************************/
3576 jb_err client_x_filter(struct client_state *csp, char **header)
3578 if (0 == strcmpic(*header, "X-Filter: No"))
3580 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3582 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3586 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3588 log_error(LOG_LEVEL_HEADER,
3589 "force-text-mode overruled the client's request to fetch without filtering!");
3593 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3594 csp->flags |= CSP_FLAG_NO_FILTERING;
3595 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3597 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3605 /*********************************************************************
3607 * Function : client_range
3609 * Description : Removes Range, Request-Range and If-Range headers if
3610 * content filtering is enabled and the range doesn't
3613 * If the client's version of the document has been
3614 * altered by Privoxy, the server could interpret the
3615 * range differently than the client intended in which
3616 * case the user could end up with corrupted content.
3618 * If the range starts at byte 0 this isn't an issue
3619 * so the header can pass. Partial requests like this
3620 * are used to render preview images for videos without
3621 * downloading the whole video.
3623 * While HTTP doesn't require that range requests are
3624 * honoured and the client could simply abort the download
3625 * after receiving a sufficient amount of data, various
3626 * clients don't handle complete responses to range
3627 * requests gracefully and emit misleading error messages
3631 * 1 : csp = Current client state (buffers, headers, etc...)
3632 * 2 : header = On input, pointer to header to modify.
3633 * On output, pointer to the modified header, or NULL
3634 * to remove the header. This function frees the
3635 * original string if necessary.
3637 * Returns : JB_ERR_OK
3639 *********************************************************************/
3640 static jb_err client_range(struct client_state *csp, char **header)
3642 if (content_filters_enabled(csp->action)
3643 && (0 != strncmpic(strstr(*header, ":"), ": bytes=0-", 10)))
3645 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3646 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3653 /* the following functions add headers directly to the header list */
3655 /*********************************************************************
3657 * Function : client_host_adder
3659 * Description : Adds the Host: header field if it is missing.
3660 * Called from `sed'.
3663 * 1 : csp = Current client state (buffers, headers, etc...)
3665 * Returns : JB_ERR_OK on success, or
3666 * JB_ERR_MEMORY on out-of-memory error.
3668 *********************************************************************/
3669 static jb_err client_host_adder(struct client_state *csp)
3674 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3676 /* Header already set by the client, nothing to do. */
3680 if (!csp->http->hostport || !*(csp->http->hostport))
3682 log_error(LOG_LEVEL_ERROR, "Destination host unknown.");
3683 return JB_ERR_PARSE;
3687 * remove 'user:pass@' from 'proto://user:pass@host'
3689 if ((p = strchr( csp->http->hostport, '@')) != NULL)
3695 p = csp->http->hostport;
3698 /* XXX: Just add it, we already made sure that it will be unique */
3699 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3700 err = enlist_unique_header(csp->headers, "Host", p);
3706 /*********************************************************************
3708 * Function : client_xtra_adder
3710 * Description : Used in the add_client_headers list. Called from `sed'.
3713 * 1 : csp = Current client state (buffers, headers, etc...)
3715 * Returns : JB_ERR_OK on success, or
3716 * JB_ERR_MEMORY on out-of-memory error.
3718 *********************************************************************/
3719 static jb_err client_xtra_adder(struct client_state *csp)
3721 struct list_entry *lst;
3724 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3725 lst ; lst = lst->next)
3727 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3728 err = enlist(csp->headers, lst->str);
3740 /*********************************************************************
3742 * Function : client_x_forwarded_for_adder
3744 * Description : Used in the add_client_headers list. Called from `sed'.
3747 * 1 : csp = Current client state (buffers, headers, etc...)
3749 * Returns : JB_ERR_OK on success, or
3750 * JB_ERR_MEMORY on out-of-memory error.
3752 *********************************************************************/
3753 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3755 char *header = NULL;
3758 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3759 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3760 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3763 * If we aren't adding X-Forwarded-For headers,
3764 * or we already appended an existing X-Forwarded-For
3765 * header, there's nothing left to do here.