1 const char parsers_rcs[] = "$Id: parsers.c,v 1.170 2009/06/01 15:14:40 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2009 the
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
45 *********************************************************************/
52 #include <sys/types.h>
62 * Convince GNU's libc to provide a strptime prototype.
72 #if !defined(_WIN32) && !defined(__OS2__)
78 #ifdef FEATURE_PTHREAD
80 /* jcc.h is for mutex semapores only */
81 #endif /* def FEATURE_PTHREAD */
86 #include "jbsockets.h"
96 const char parsers_h_rcs[] = PARSERS_H_VERSION;
98 /* Fix a problem with Solaris. There should be no effect on other
100 * Solaris's isspace() is a macro which uses its argument directly
101 * as an array index. Therefore we need to make sure that high-bit
102 * characters generate +ve values, and ideally we also want to make
103 * the argument match the declared parameter type of "int".
105 * Why did they write a character function that can't take a simple
106 * "char" argument? Doh!
108 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
109 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
111 static char *get_header_line(struct iob *iob);
112 static jb_err scan_headers(struct client_state *csp);
113 static jb_err header_tagger(struct client_state *csp, char *header);
114 static jb_err parse_header_time(const char *header_time, time_t *result);
116 static jb_err crumble (struct client_state *csp, char **header);
117 static jb_err filter_header (struct client_state *csp, char **header);
118 static jb_err client_connection (struct client_state *csp, char **header);
119 static jb_err client_referrer (struct client_state *csp, char **header);
120 static jb_err client_uagent (struct client_state *csp, char **header);
121 static jb_err client_ua (struct client_state *csp, char **header);
122 static jb_err client_from (struct client_state *csp, char **header);
123 static jb_err client_send_cookie (struct client_state *csp, char **header);
124 static jb_err client_x_forwarded (struct client_state *csp, char **header);
125 static jb_err client_accept_encoding (struct client_state *csp, char **header);
126 static jb_err client_te (struct client_state *csp, char **header);
127 static jb_err client_max_forwards (struct client_state *csp, char **header);
128 static jb_err client_host (struct client_state *csp, char **header);
129 static jb_err client_if_modified_since (struct client_state *csp, char **header);
130 static jb_err client_accept_language (struct client_state *csp, char **header);
131 static jb_err client_if_none_match (struct client_state *csp, char **header);
132 static jb_err crunch_client_header (struct client_state *csp, char **header);
133 static jb_err client_x_filter (struct client_state *csp, char **header);
134 static jb_err client_range (struct client_state *csp, char **header);
135 static jb_err server_set_cookie (struct client_state *csp, char **header);
136 static jb_err server_connection (struct client_state *csp, char **header);
137 static jb_err server_content_type (struct client_state *csp, char **header);
138 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
139 static jb_err server_content_md5 (struct client_state *csp, char **header);
140 static jb_err server_content_encoding (struct client_state *csp, char **header);
141 static jb_err server_transfer_coding (struct client_state *csp, char **header);
142 static jb_err server_http (struct client_state *csp, char **header);
143 static jb_err crunch_server_header (struct client_state *csp, char **header);
144 static jb_err server_last_modified (struct client_state *csp, char **header);
145 static jb_err server_content_disposition(struct client_state *csp, char **header);
147 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
148 static jb_err server_save_content_length(struct client_state *csp, char **header);
149 static jb_err server_keep_alive(struct client_state *csp, char **header);
150 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
152 static jb_err client_host_adder (struct client_state *csp);
153 static jb_err client_xtra_adder (struct client_state *csp);
154 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
155 static jb_err client_connection_header_adder(struct client_state *csp);
156 static jb_err server_connection_adder(struct client_state *csp);
157 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
158 static jb_err server_proxy_connection_adder(struct client_state *csp);
159 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
161 static jb_err create_forged_referrer(char **header, const char *hostport);
162 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
163 static jb_err handle_conditional_hide_referrer_parameter(char **header,
164 const char *host, const int parameter_conditional_block);
165 static const char *get_appropiate_connection_header(const struct client_state *csp);
168 * List of functions to run on a list of headers.
172 /** The header prefix to match */
175 /** The length of the prefix to match */
178 /** The function to apply to this line */
179 const parser_func_ptr parser;
182 static const struct parsers client_patterns[] = {
183 { "referer:", 8, client_referrer },
184 { "user-agent:", 11, client_uagent },
185 { "ua-", 3, client_ua },
186 { "from:", 5, client_from },
187 { "cookie:", 7, client_send_cookie },
188 { "x-forwarded-for:", 16, client_x_forwarded },
189 { "Accept-Encoding:", 16, client_accept_encoding },
190 { "TE:", 3, client_te },
191 { "Host:", 5, client_host },
192 { "if-modified-since:", 18, client_if_modified_since },
193 #ifndef FEATURE_CONNECTION_KEEP_ALIVE
194 { "Keep-Alive:", 11, crumble },
196 { "connection:", 11, client_connection },
197 { "proxy-connection:", 17, crumble },
198 { "max-forwards:", 13, client_max_forwards },
199 { "Accept-Language:", 16, client_accept_language },
200 { "if-none-match:", 14, client_if_none_match },
201 { "Range:", 6, client_range },
202 { "Request-Range:", 14, client_range },
203 { "If-Range:", 9, client_range },
204 { "X-Filter:", 9, client_x_filter },
205 { "*", 0, crunch_client_header },
206 { "*", 0, filter_header },
210 static const struct parsers server_patterns[] = {
211 { "HTTP/", 5, server_http },
212 { "set-cookie:", 11, server_set_cookie },
213 { "connection:", 11, server_connection },
214 { "Content-Type:", 13, server_content_type },
215 { "Content-MD5:", 12, server_content_md5 },
216 { "Content-Encoding:", 17, server_content_encoding },
217 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
218 { "Content-Length:", 15, server_save_content_length },
219 { "Keep-Alive:", 11, server_keep_alive },
221 { "Keep-Alive:", 11, crumble },
222 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
223 { "Transfer-Encoding:", 18, server_transfer_coding },
224 { "content-disposition:", 20, server_content_disposition },
225 { "Last-Modified:", 14, server_last_modified },
226 { "*", 0, crunch_server_header },
227 { "*", 0, filter_header },
231 static const add_header_func_ptr add_client_headers[] = {
233 client_x_forwarded_for_adder,
235 /* Temporarily disabled: client_accept_encoding_adder, */
236 client_connection_header_adder,
240 static const add_header_func_ptr add_server_headers[] = {
241 server_connection_adder,
242 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
243 server_proxy_connection_adder,
244 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
248 /*********************************************************************
250 * Function : flush_socket
252 * Description : Write any pending "buffered" content.
255 * 1 : fd = file descriptor of the socket to read
256 * 2 : iob = The I/O buffer to flush, usually csp->iob.
258 * Returns : On success, the number of bytes written are returned (zero
259 * indicates nothing was written). On error, -1 is returned,
260 * and errno is set appropriately. If count is zero and the
261 * file descriptor refers to a regular file, 0 will be
262 * returned without causing any other effect. For a special
263 * file, the results are not portable.
265 *********************************************************************/
266 long flush_socket(jb_socket fd, struct iob *iob)
268 long len = iob->eod - iob->cur;
275 if (write_socket(fd, iob->cur, (size_t)len))
279 iob->eod = iob->cur = iob->buf;
285 /*********************************************************************
287 * Function : add_to_iob
289 * Description : Add content to the buffered page, expanding the
290 * buffer if necessary.
293 * 1 : csp = Current client state (buffers, headers, etc...)
294 * 2 : buf = holds the content to be added to the page
295 * 3 : n = number of bytes to be added
297 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
298 * or buffer limit reached.
300 *********************************************************************/
301 jb_err add_to_iob(struct client_state *csp, char *buf, long n)
303 struct iob *iob = csp->iob;
304 size_t used, offset, need, want;
307 if (n <= 0) return JB_ERR_OK;
309 used = (size_t)(iob->eod - iob->buf);
310 offset = (size_t)(iob->cur - iob->buf);
311 need = used + (size_t)n + 1;
314 * If the buffer can't hold the new data, extend it first.
315 * Use the next power of two if possible, else use the actual need.
317 if (need > csp->config->buffer_limit)
319 log_error(LOG_LEVEL_INFO,
320 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
321 need, csp->config->buffer_limit);
322 return JB_ERR_MEMORY;
325 if (need > iob->size)
327 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
329 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
333 else if (NULL != (p = (char *)realloc(iob->buf, need)))
339 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
340 return JB_ERR_MEMORY;
343 /* Update the iob pointers */
344 iob->cur = p + offset;
349 /* copy the new data into the iob buffer */
350 memcpy(iob->eod, buf, (size_t)n);
352 /* point to the end of the data */
355 /* null terminate == cheap insurance */
364 /*********************************************************************
366 * Function : decompress_iob
368 * Description : Decompress buffered page, expanding the
369 * buffer as necessary. csp->iob->cur
370 * should point to the the beginning of the
371 * compressed data block.
374 * 1 : csp = Current client state (buffers, headers, etc...)
376 * Returns : JB_ERR_OK on success,
377 * JB_ERR_MEMORY if out-of-memory limit reached, and
378 * JB_ERR_COMPRESS if error decompressing buffer.
380 *********************************************************************/
381 jb_err decompress_iob(struct client_state *csp)
383 char *buf; /* new, uncompressed buffer */
384 char *cur; /* Current iob position (to keep the original
385 * iob->cur unmodified if we return early) */
386 size_t bufsize; /* allocated size of the new buffer */
387 size_t old_size; /* Content size before decompression */
388 size_t skip_size; /* Number of bytes at the beginning of the iob
389 that we should NOT decompress. */
390 int status; /* return status of the inflate() call */
391 z_stream zstr; /* used by calls to zlib */
393 assert(csp->iob->cur - csp->iob->buf > 0);
394 assert(csp->iob->eod - csp->iob->cur > 0);
396 bufsize = csp->iob->size;
397 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
398 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
402 if (bufsize < (size_t)10)
405 * This is to protect the parsing of gzipped data,
406 * but it should(?) be valid for deflated data also.
408 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
409 return JB_ERR_COMPRESS;
412 if (csp->content_type & CT_GZIP)
415 * Our task is slightly complicated by the facts that data
416 * compressed by gzip does not include a zlib header, and
417 * that there is no easily accessible interface in zlib to
418 * handle a gzip header. We strip off the gzip header by
419 * hand, and later inform zlib not to expect a header.
423 * Strip off the gzip header. Please see RFC 1952 for more
424 * explanation of the appropriate fields.
426 if ((*cur++ != (char)0x1f)
427 || (*cur++ != (char)0x8b)
428 || (*cur++ != Z_DEFLATED))
430 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
431 return JB_ERR_COMPRESS;
437 * XXX: These magic numbers should be replaced
438 * with macros to give a better idea what they do.
442 /* The gzip header has reserved bits set; bail out. */
443 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
444 return JB_ERR_COMPRESS;
448 /* Skip extra fields if necessary. */
452 * Skip a given number of bytes, specified
453 * as a 16-bit little-endian value.
455 * XXX: this code is untested and should probably be removed.
459 skip_bytes += *cur++ << 8;
462 * The number of bytes to skip should be positive
463 * and we'd like to stay in the buffer.
465 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
467 log_error(LOG_LEVEL_ERROR,
468 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
470 return JB_ERR_COMPRESS;
472 log_error(LOG_LEVEL_INFO,
473 "Skipping %d bytes for gzip compression. Does this sound right?",
478 /* Skip the filename if necessary. */
481 /* A null-terminated string is supposed to follow. */
482 while (*cur++ && (cur < csp->iob->eod));
486 /* Skip the comment if necessary. */
489 /* A null-terminated string is supposed to follow. */
490 while (*cur++ && (cur < csp->iob->eod));
493 /* Skip the CRC if necessary. */
499 if (cur >= csp->iob->eod)
502 * If the current position pointer reached or passed
503 * the buffer end, we were obviously tricked to skip
506 log_error(LOG_LEVEL_ERROR,
507 "Malformed gzip header detected. Aborting decompression.");
508 return JB_ERR_COMPRESS;
512 else if (csp->content_type & CT_DEFLATE)
515 * XXX: The debug level should be lowered
516 * before the next stable release.
518 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
520 * In theory (that is, according to RFC 1950), deflate-compressed
521 * data should begin with a two-byte zlib header and have an
522 * adler32 checksum at the end. It seems that in practice only
523 * the raw compressed data is sent. Note that this means that
524 * we are not RFC 1950-compliant here, but the advantage is that
525 * this actually works. :)
527 * We add a dummy null byte to tell zlib where the data ends,
528 * and later inform it not to expect a header.
530 * Fortunately, add_to_iob() has thoughtfully null-terminated
531 * the buffer; we can just increment the end pointer to include
538 log_error(LOG_LEVEL_ERROR,
539 "Unable to determine compression format for decompression");
540 return JB_ERR_COMPRESS;
543 /* Set up the fields required by zlib. */
544 zstr.next_in = (Bytef *)cur;
545 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
546 zstr.zalloc = Z_NULL;
548 zstr.opaque = Z_NULL;
551 * Passing -MAX_WBITS to inflateInit2 tells the library
552 * that there is no zlib header.
554 if (inflateInit2(&zstr, -MAX_WBITS) != Z_OK)
556 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
557 return JB_ERR_COMPRESS;
561 * Next, we allocate new storage for the inflated data.
562 * We don't modify the existing iob yet, so in case there
563 * is error in decompression we can recover gracefully.
565 buf = zalloc(bufsize);
568 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
569 return JB_ERR_MEMORY;
572 assert(bufsize >= skip_size);
573 memcpy(buf, csp->iob->buf, skip_size);
574 zstr.avail_out = bufsize - skip_size;
575 zstr.next_out = (Bytef *)buf + skip_size;
577 /* Try to decompress the whole stream in one shot. */
578 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
580 /* We need to allocate more memory for the output buffer. */
582 char *tmpbuf; /* used for realloc'ing the buffer */
583 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
586 * If zlib wants more data then there's a problem, because
587 * the complete compressed file should have been buffered.
589 if (0 == zstr.avail_in)
591 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
592 return JB_ERR_COMPRESS;
596 * If we tried the limit and still didn't have enough
597 * memory, just give up.
599 if (bufsize == csp->config->buffer_limit)
601 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
602 return JB_ERR_MEMORY;
605 /* Try doubling the buffer size each time. */
608 /* Don't exceed the buffer limit. */
609 if (bufsize > csp->config->buffer_limit)
611 bufsize = csp->config->buffer_limit;
614 /* Try to allocate the new buffer. */
615 tmpbuf = realloc(buf, bufsize);
618 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
620 return JB_ERR_MEMORY;
624 char *oldnext_out = (char *)zstr.next_out;
627 * Update the fields for inflate() to use the new
628 * buffer, which may be in a location different from
631 zstr.avail_out += bufsize - oldbufsize;
632 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
635 * Compare with an uglier method of calculating these values
636 * that doesn't require the extra oldbufsize variable.
638 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
639 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
640 assert(zstr.avail_out > 0U);
646 if (Z_STREAM_ERROR == inflateEnd(&zstr))
648 log_error(LOG_LEVEL_ERROR,
649 "Inconsistent stream state after decompression: %s", zstr.msg);
651 * XXX: Intentionally no return.
653 * According to zlib.h, Z_STREAM_ERROR is returned
654 * "if the stream state was inconsistent".
656 * I assume in this case inflate()'s status
657 * would also be something different than Z_STREAM_END
658 * so this check should be redundant, but lets see.
662 if (status != Z_STREAM_END)
664 /* We failed to decompress the stream. */
665 log_error(LOG_LEVEL_ERROR,
666 "Error in decompressing to the buffer (iob): %s", zstr.msg);
667 return JB_ERR_COMPRESS;
671 * Finally, we can actually update the iob, since the
672 * decompression was successful. First, free the old
675 freez(csp->iob->buf);
677 /* Now, update the iob to use the new buffer. */
679 csp->iob->cur = csp->iob->buf + skip_size;
680 csp->iob->eod = (char *)zstr.next_out;
681 csp->iob->size = bufsize;
684 * Make sure the new uncompressed iob obeys some minimal
685 * consistency conditions.
687 if ((csp->iob->buf < csp->iob->cur)
688 && (csp->iob->cur <= csp->iob->eod)
689 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
691 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
692 if (new_size > (size_t)0)
694 log_error(LOG_LEVEL_RE_FILTER,
695 "Decompression successful. Old size: %d, new size: %d.",
700 /* zlib thinks this is OK, so lets do the same. */
701 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
706 /* It seems that zlib did something weird. */
707 log_error(LOG_LEVEL_ERROR,
708 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
709 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
710 csp->iob->eod, csp->iob->buf + csp->iob->size);
711 return JB_ERR_COMPRESS;
717 #endif /* defined(FEATURE_ZLIB) */
720 /*********************************************************************
722 * Function : string_move
724 * Description : memmove wrapper to move the last part of a string
725 * towards the beginning, overwriting the part in
726 * the middle. strlcpy() can't be used here as the
730 * 1 : dst = Destination to overwrite
731 * 2 : src = Source to move.
735 *********************************************************************/
736 static void string_move(char *dst, char *src)
740 /* +1 to copy the terminating nul as well. */
741 memmove(dst, src, strlen(src)+1);
745 /*********************************************************************
747 * Function : normalize_lws
749 * Description : Reduces unquoted linear white space in headers
750 * to a single space in accordance with RFC 2616 2.2.
751 * This simplifies parsing and filtering later on.
753 * XXX: Remove log messages before
754 * the next stable release?
757 * 1 : header = A header with linear white space to reduce.
761 *********************************************************************/
762 static void normalize_lws(char *header)
768 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
772 while (ijb_isspace(*q))
776 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
782 log_error(LOG_LEVEL_HEADER,
783 "Converting tab to space in '%s'", header);
788 char *end_of_token = strstr(p+1, "\"");
790 if (NULL != end_of_token)
792 /* Don't mess with quoted text. */
797 log_error(LOG_LEVEL_HEADER,
798 "Ignoring single quote in '%s'", header);
804 p = strchr(header, ':');
805 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
808 * There's still space before the colon.
816 /*********************************************************************
818 * Function : get_header
820 * Description : This (odd) routine will parse the csp->iob
821 * to get the next complete header.
824 * 1 : iob = The I/O buffer to parse, usually csp->iob.
826 * Returns : Any one of the following:
828 * 1) a pointer to a dynamically allocated string that contains a header line
829 * 2) NULL indicating that the end of the header was reached
830 * 3) "" indicating that the end of the iob was reached before finding
831 * a complete header line.
833 *********************************************************************/
834 char *get_header(struct iob *iob)
838 header = get_header_line(iob);
840 if ((header == NULL) || (*header == '\0'))
843 * No complete header read yet, tell the client.
848 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
851 * Header spans multiple lines, append the next one.
853 char *continued_header;
855 continued_header = get_header_line(iob);
856 if ((continued_header == NULL) || (*continued_header == '\0'))
859 * No complete header read yet, return what we got.
860 * XXX: Should "unread" header instead.
862 log_error(LOG_LEVEL_INFO,
863 "Failed to read a multi-line header properly: '%s'",
868 if (JB_ERR_OK != string_join(&header, continued_header))
870 log_error(LOG_LEVEL_FATAL,
871 "Out of memory while appending multiple headers.");
875 /* XXX: remove before next stable release. */
876 log_error(LOG_LEVEL_HEADER,
877 "Merged multiple header lines to: '%s'",
882 normalize_lws(header);
889 /*********************************************************************
891 * Function : get_header_line
893 * Description : This (odd) routine will parse the csp->iob
894 * to get the next header line.
897 * 1 : iob = The I/O buffer to parse, usually csp->iob.
899 * Returns : Any one of the following:
901 * 1) a pointer to a dynamically allocated string that contains a header line
902 * 2) NULL indicating that the end of the header was reached
903 * 3) "" indicating that the end of the iob was reached before finding
904 * a complete header line.
906 *********************************************************************/
907 static char *get_header_line(struct iob *iob)
911 if ((iob->cur == NULL)
912 || ((p = strchr(iob->cur, '\n')) == NULL))
914 return(""); /* couldn't find a complete header */
919 ret = strdup(iob->cur);
922 /* FIXME No way to handle error properly */
923 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
929 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
931 /* is this a blank line (i.e. the end of the header) ? */
943 /*********************************************************************
945 * Function : get_header_value
947 * Description : Get the value of a given header from a chained list
948 * of header lines or return NULL if no such header is
949 * present in the list.
952 * 1 : header_list = pointer to list
953 * 2 : header_name = string with name of header to look for.
954 * Trailing colon required, capitalization
957 * Returns : NULL if not found, else value of header
959 *********************************************************************/
960 char *get_header_value(const struct list *header_list, const char *header_name)
962 struct list_entry *cur_entry;
968 length = strlen(header_name);
970 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
974 if (!strncmpic(cur_entry->str, header_name, length))
977 * Found: return pointer to start of value
979 ret = cur_entry->str + length;
980 while (*ret && ijb_isspace(*ret)) ret++;
994 /*********************************************************************
996 * Function : scan_headers
998 * Description : Scans headers, applies tags and updates action bits.
1001 * 1 : csp = Current client state (buffers, headers, etc...)
1003 * Returns : JB_ERR_OK
1005 *********************************************************************/
1006 static jb_err scan_headers(struct client_state *csp)
1008 struct list_entry *h; /* Header */
1009 jb_err err = JB_ERR_OK;
1011 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1013 /* Header crunch()ed in previous run? -> ignore */
1014 if (h->str == NULL) continue;
1015 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1016 err = header_tagger(csp, h->str);
1023 /*********************************************************************
1027 * Description : add, delete or modify lines in the HTTP header streams.
1028 * On entry, it receives a linked list of headers space
1029 * that was allocated dynamically (both the list nodes
1030 * and the header contents).
1032 * As a side effect it frees the space used by the original
1036 * 1 : csp = Current client state (buffers, headers, etc...)
1037 * 2 : filter_server_headers = Boolean to switch between
1038 * server and header filtering.
1040 * Returns : JB_ERR_OK in case off success, or
1041 * JB_ERR_MEMORY on out-of-memory error.
1043 *********************************************************************/
1044 jb_err sed(struct client_state *csp, int filter_server_headers)
1046 /* XXX: use more descriptive names. */
1047 struct list_entry *p;
1048 const struct parsers *v;
1049 const add_header_func_ptr *f;
1050 jb_err err = JB_ERR_OK;
1052 if (filter_server_headers)
1054 v = server_patterns;
1055 f = add_server_headers;
1059 v = client_patterns;
1060 f = add_client_headers;
1065 while ((err == JB_ERR_OK) && (v->str != NULL))
1067 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1069 /* Header crunch()ed in previous run? -> ignore */
1070 if (p->str == NULL) continue;
1072 /* Does the current parser handle this header? */
1073 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1074 (v->len == CHECK_EVERY_HEADER_REMAINING))
1076 err = v->parser(csp, &(p->str));
1082 /* place additional headers on the csp->headers list */
1083 while ((err == JB_ERR_OK) && (*f))
1093 /*********************************************************************
1095 * Function : update_server_headers
1097 * Description : Updates server headers after the body has been modified.
1100 * 1 : csp = Current client state (buffers, headers, etc...)
1102 * Returns : JB_ERR_OK in case off success, or
1103 * JB_ERR_MEMORY on out-of-memory error.
1105 *********************************************************************/
1106 jb_err update_server_headers(struct client_state *csp)
1108 jb_err err = JB_ERR_OK;
1110 static const struct parsers server_patterns_light[] = {
1111 { "Content-Length:", 15, server_adjust_content_length },
1112 { "Transfer-Encoding:", 18, server_transfer_coding },
1114 { "Content-Encoding:", 17, server_content_encoding },
1115 #endif /* def FEATURE_ZLIB */
1119 if (strncmpic(csp->http->cmd, "HEAD", 4))
1121 const struct parsers *v;
1122 struct list_entry *p;
1124 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1126 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1128 /* Header crunch()ed in previous run? -> ignore */
1129 if (p->str == NULL) continue;
1131 /* Does the current parser handle this header? */
1132 if (strncmpic(p->str, v->str, v->len) == 0)
1134 err = v->parser(csp, (char **)&(p->str));
1144 /*********************************************************************
1146 * Function : header_tagger
1148 * Description : Executes all text substitutions from applying
1149 * tag actions and saves the result as tag.
1151 * XXX: Shares enough code with filter_header() and
1152 * pcrs_filter_response() to warrant some helper functions.
1155 * 1 : csp = Current client state (buffers, headers, etc...)
1156 * 2 : header = Header that is used as tagger input
1158 * Returns : JB_ERR_OK on success and always succeeds
1160 *********************************************************************/
1161 static jb_err header_tagger(struct client_state *csp, char *header)
1163 int wanted_filter_type;
1164 int multi_action_index;
1168 struct file_list *fl;
1169 struct re_filterfile_spec *b;
1170 struct list_entry *tag_name;
1172 int found_filters = 0;
1173 const size_t header_length = strlen(header);
1175 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1177 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1178 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1182 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1183 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1186 /* Check if there are any filters */
1187 for (i = 0; i < MAX_AF_FILES; i++)
1200 if (0 == found_filters)
1202 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1203 "tagging enabled, but no taggers available.");
1207 for (i = 0; i < MAX_AF_FILES; i++)
1210 if ((NULL == fl) || (NULL == fl->f))
1213 * Either there are no filter files
1214 * left, or this filter file just
1215 * contains no valid filters.
1217 * Continue to be sure we don't miss
1218 * valid filter files that are chained
1219 * after empty or invalid ones.
1224 /* For all filters, */
1225 for (b = fl->f; b; b = b->next)
1227 if (b->type != wanted_filter_type)
1229 /* skip the ones we don't care about, */
1232 /* leaving only taggers that could apply, of which we use the ones, */
1233 for (tag_name = csp->action->multi[multi_action_index]->first;
1234 NULL != tag_name; tag_name = tag_name->next)
1236 /* that do apply, and */
1237 if (strcmp(b->name, tag_name->str) == 0)
1239 char *modified_tag = NULL;
1241 size_t size = header_length;
1242 pcrs_job *joblist = b->joblist;
1244 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1246 if (NULL == joblist)
1248 log_error(LOG_LEVEL_RE_FILTER,
1249 "Tagger %s has empty joblist. Nothing to do.", b->name);
1253 /* execute their pcrs_joblist on the header. */
1254 for (job = joblist; NULL != job; job = job->next)
1256 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1260 /* Success, continue with the modified version. */
1269 /* Tagger doesn't match */
1272 /* Regex failure, log it but continue anyway. */
1273 assert(NULL != header);
1274 log_error(LOG_LEVEL_ERROR,
1275 "Problems with tagger \'%s\' and header \'%s\': %s",
1276 b->name, *header, pcrs_strerror(hits));
1278 freez(modified_tag);
1282 if (b->dynamic) pcrs_free_joblist(joblist);
1284 /* If this tagger matched */
1290 * There is to technical limitation which makes
1291 * it impossible to use empty tags, but I assume
1292 * no one would do it intentionally.
1295 log_error(LOG_LEVEL_INFO,
1296 "Tagger \'%s\' created an empty tag. Ignored.",
1301 if (!list_contains_item(csp->tags, tag))
1303 if (JB_ERR_OK != enlist(csp->tags, tag))
1305 log_error(LOG_LEVEL_ERROR,
1306 "Insufficient memory to add tag \'%s\', "
1307 "based on tagger \'%s\' and header \'%s\'",
1308 tag, b->name, *header);
1312 char *action_message;
1314 * update the action bits right away, to make
1315 * tagging based on tags set by earlier taggers
1316 * of the same kind possible.
1318 if (update_action_bits_for_tag(csp, tag))
1320 action_message = "Action bits updated accordingly.";
1324 action_message = "No action bits update necessary.";
1327 log_error(LOG_LEVEL_HEADER,
1328 "Tagger \'%s\' added tag \'%s\'. %s",
1329 b->name, tag, action_message);
1334 /* XXX: Is this log-worthy? */
1335 log_error(LOG_LEVEL_HEADER,
1336 "Tagger \'%s\' didn't add tag \'%s\'. "
1337 "Tag already present", b->name, tag);
1340 } /* if the tagger matched */
1341 } /* if the tagger applies */
1342 } /* for every tagger that could apply */
1343 } /* for all filters */
1344 } /* for all filter files */
1349 /* here begins the family of parser functions that reformat header lines */
1351 /*********************************************************************
1353 * Function : filter_header
1355 * Description : Executes all text substitutions from all applying
1356 * +(server|client)-header-filter actions on the header.
1357 * Most of the code was copied from pcrs_filter_response,
1358 * including the rather short variable names
1361 * 1 : csp = Current client state (buffers, headers, etc...)
1362 * 2 : header = On input, pointer to header to modify.
1363 * On output, pointer to the modified header, or NULL
1364 * to remove the header. This function frees the
1365 * original string if necessary.
1367 * Returns : JB_ERR_OK on success and always succeeds
1369 *********************************************************************/
1370 static jb_err filter_header(struct client_state *csp, char **header)
1374 size_t size = strlen(*header);
1376 char *newheader = NULL;
1379 struct file_list *fl;
1380 struct re_filterfile_spec *b;
1381 struct list_entry *filtername;
1383 int i, found_filters = 0;
1384 int wanted_filter_type;
1385 int multi_action_index;
1387 if (csp->flags & CSP_FLAG_NO_FILTERING)
1392 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1394 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1395 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1399 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1400 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1404 * Need to check the set of re_filterfiles...
1406 for (i = 0; i < MAX_AF_FILES; i++)
1419 if (0 == found_filters)
1421 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
1422 "header filtering enabled, but no matching filters available.");
1426 for (i = 0; i < MAX_AF_FILES; i++)
1429 if ((NULL == fl) || (NULL == fl->f))
1432 * Either there are no filter files
1433 * left, or this filter file just
1434 * contains no valid filters.
1436 * Continue to be sure we don't miss
1437 * valid filter files that are chained
1438 * after empty or invalid ones.
1443 * For all applying +filter actions, look if a filter by that
1444 * name exists and if yes, execute its pcrs_joblist on the
1447 for (b = fl->f; b; b = b->next)
1449 if (b->type != wanted_filter_type)
1451 /* Skip other filter types */
1455 for (filtername = csp->action->multi[multi_action_index]->first;
1456 filtername ; filtername = filtername->next)
1458 if (strcmp(b->name, filtername->str) == 0)
1460 int current_hits = 0;
1461 pcrs_job *joblist = b->joblist;
1463 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1465 if (NULL == joblist)
1467 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1471 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1472 *header, size, b->name);
1474 /* Apply all jobs from the joblist */
1475 for (job = joblist; NULL != job; job = job->next)
1477 matches = pcrs_execute(job, *header, size, &newheader, &size);
1480 current_hits += matches;
1481 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1483 *header = newheader;
1485 else if ( 0 == matches )
1487 /* Filter doesn't change header */
1493 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1494 *header, b->name, pcrs_strerror(matches));
1495 if (newheader != NULL)
1497 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1503 if (b->dynamic) pcrs_free_joblist(joblist);
1505 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1506 hits += current_hits;
1513 * Additionally checking for hits is important because if
1514 * the continue hack is triggered, server headers can
1515 * arrive empty to separate multiple heads from each other.
1517 if ((0 == size) && hits)
1519 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1527 /*********************************************************************
1529 * Function : server_connection
1531 * Description : Makes sure a proper "Connection:" header is
1532 * set and signals connection_header_adder to
1536 * 1 : csp = Current client state (buffers, headers, etc...)
1537 * 2 : header = On input, pointer to header to modify.
1538 * On output, pointer to the modified header, or NULL
1539 * to remove the header. This function frees the
1540 * original string if necessary.
1542 * Returns : JB_ERR_OK on success, or
1543 * JB_ERR_MEMORY on out-of-memory error.
1545 *********************************************************************/
1546 static jb_err server_connection(struct client_state *csp, char **header)
1548 if (!strcmpic(*header, "Connection: keep-alive"))
1550 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1551 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE))
1553 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
1556 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
1558 log_error(LOG_LEVEL_HEADER,
1559 "Keeping the server header '%s' around.", *header);
1562 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1564 char *old_header = *header;
1566 *header = strdup("Connection: close");
1569 return JB_ERR_MEMORY;
1571 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
1576 /* Signal server_connection_adder() to return early. */
1577 csp->flags |= CSP_FLAG_SERVER_CONNECTION_HEADER_SET;
1583 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1584 /*********************************************************************
1586 * Function : server_keep_alive
1588 * Description : Stores the servers keep alive timeout.
1591 * 1 : csp = Current client state (buffers, headers, etc...)
1592 * 2 : header = On input, pointer to header to modify.
1593 * On output, pointer to the modified header, or NULL
1594 * to remove the header. This function frees the
1595 * original string if necessary.
1597 * Returns : JB_ERR_OK.
1599 *********************************************************************/
1600 static jb_err server_keep_alive(struct client_state *csp, char **header)
1602 unsigned int keep_alive_timeout;
1603 const char *timeout_position = strstr(*header, "timeout=");
1605 if ((NULL == timeout_position)
1606 || (1 != sscanf(timeout_position, "timeout=%u", &keep_alive_timeout)))
1608 log_error(LOG_LEVEL_ERROR, "Couldn't parse: %s", *header);
1612 if (keep_alive_timeout < csp->server_connection.keep_alive_timeout)
1614 log_error(LOG_LEVEL_HEADER,
1615 "Reducing keep-alive timeout from %u to %u.",
1616 csp->server_connection.keep_alive_timeout, keep_alive_timeout);
1617 csp->server_connection.keep_alive_timeout = keep_alive_timeout;
1621 /* XXX: Is this log worthy? */
1622 log_error(LOG_LEVEL_HEADER,
1623 "Server keep-alive timeout is %u. Sticking with %u.",
1624 keep_alive_timeout, csp->server_connection.keep_alive_timeout);
1630 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1634 /*********************************************************************
1636 * Function : client_connection
1638 * Description : Makes sure a proper "Connection:" header is
1639 * set and signals connection_header_adder
1643 * 1 : csp = Current client state (buffers, headers, etc...)
1644 * 2 : header = On input, pointer to header to modify.
1645 * On output, pointer to the modified header, or NULL
1646 * to remove the header. This function frees the
1647 * original string if necessary.
1649 * Returns : JB_ERR_OK on success, or
1650 * JB_ERR_MEMORY on out-of-memory error.
1652 *********************************************************************/
1653 static jb_err client_connection(struct client_state *csp, char **header)
1655 const char *wanted_header = get_appropiate_connection_header(csp);
1657 if (strcmpic(*header, wanted_header))
1659 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1660 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
1662 log_error(LOG_LEVEL_HEADER,
1663 "Keeping the client header '%s' around. "
1664 "The connection will not be kept alive.",
1668 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1670 char *old_header = *header;
1672 *header = strdup(wanted_header);
1675 return JB_ERR_MEMORY;
1677 log_error(LOG_LEVEL_HEADER,
1678 "Replaced: \'%s\' with \'%s\'", old_header, *header);
1682 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1685 log_error(LOG_LEVEL_HEADER,
1686 "Keeping the client header '%s' around. "
1687 "The server connection will be kept alive if possible.",
1689 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1691 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1693 /* Signal client_connection_adder() to return early. */
1694 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
1700 /*********************************************************************
1702 * Function : crumble
1704 * Description : This is called if a header matches a pattern to "crunch"
1707 * 1 : csp = Current client state (buffers, headers, etc...)
1708 * 2 : header = On input, pointer to header to modify.
1709 * On output, pointer to the modified header, or NULL
1710 * to remove the header. This function frees the
1711 * original string if necessary.
1713 * Returns : JB_ERR_OK on success, or
1714 * JB_ERR_MEMORY on out-of-memory error.
1716 *********************************************************************/
1717 static jb_err crumble(struct client_state *csp, char **header)
1720 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1726 /*********************************************************************
1728 * Function : crunch_server_header
1730 * Description : Crunch server header if it matches a string supplied by the
1731 * user. Called from `sed'.
1734 * 1 : csp = Current client state (buffers, headers, etc...)
1735 * 2 : header = On input, pointer to header to modify.
1736 * On output, pointer to the modified header, or NULL
1737 * to remove the header. This function frees the
1738 * original string if necessary.
1740 * Returns : JB_ERR_OK on success and always succeeds
1742 *********************************************************************/
1743 static jb_err crunch_server_header(struct client_state *csp, char **header)
1745 const char *crunch_pattern;
1747 /* Do we feel like crunching? */
1748 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1750 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1752 /* Is the current header the lucky one? */
1753 if (strstr(*header, crunch_pattern))
1755 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1764 /*********************************************************************
1766 * Function : server_content_type
1768 * Description : Set the content-type for filterable types (text/.*,
1769 * .*xml.*, javascript and image/gif) unless filtering has been
1770 * forbidden (CT_TABOO) while parsing earlier headers.
1771 * NOTE: Since text/plain is commonly used by web servers
1772 * for files whose correct type is unknown, we don't
1773 * set CT_TEXT for it.
1776 * 1 : csp = Current client state (buffers, headers, etc...)
1777 * 2 : header = On input, pointer to header to modify.
1778 * On output, pointer to the modified header, or NULL
1779 * to remove the header. This function frees the
1780 * original string if necessary.
1782 * Returns : JB_ERR_OK on success, or
1783 * JB_ERR_MEMORY on out-of-memory error.
1785 *********************************************************************/
1786 static jb_err server_content_type(struct client_state *csp, char **header)
1788 /* Remove header if it isn't the first Content-Type header */
1789 if ((csp->content_type & CT_DECLARED))
1792 * Another, slightly slower, way to see if
1793 * we already parsed another Content-Type header.
1795 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
1797 log_error(LOG_LEVEL_ERROR,
1798 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
1806 * Signal that the Content-Type has been set.
1808 csp->content_type |= CT_DECLARED;
1810 if (!(csp->content_type & CT_TABOO))
1813 * XXX: The assumption that text/plain is a sign of
1814 * binary data seems to be somewhat unreasonable nowadays
1815 * and should be dropped after 3.0.8 is out.
1817 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
1818 || strstr(*header, "xml")
1819 || strstr(*header, "application/x-javascript"))
1821 csp->content_type |= CT_TEXT;
1823 else if (strstr(*header, "image/gif"))
1825 csp->content_type |= CT_GIF;
1830 * Are we messing with the content type?
1832 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1835 * Make sure the user doesn't accidently
1836 * change the content type of binary documents.
1838 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
1841 *header = strdup("Content-Type: ");
1842 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
1846 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
1847 return JB_ERR_MEMORY;
1849 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1853 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
1854 "It doesn't look like a content type that should be filtered. "
1855 "Enable force-text-mode if you know what you're doing.", *header);
1863 /*********************************************************************
1865 * Function : server_transfer_coding
1867 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1868 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1869 * - Remove header if body was chunked but has been
1870 * de-chunked for filtering.
1873 * 1 : csp = Current client state (buffers, headers, etc...)
1874 * 2 : header = On input, pointer to header to modify.
1875 * On output, pointer to the modified header, or NULL
1876 * to remove the header. This function frees the
1877 * original string if necessary.
1879 * Returns : JB_ERR_OK on success, or
1880 * JB_ERR_MEMORY on out-of-memory error.
1882 *********************************************************************/
1883 static jb_err server_transfer_coding(struct client_state *csp, char **header)
1886 * Turn off pcrs and gif filtering if body compressed
1888 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1892 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
1894 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
1895 csp->http->cmd, *header);
1896 #endif /* def FEATURE_ZLIB */
1897 csp->content_type = CT_TABOO;
1901 * Raise flag if body chunked
1903 if (strstr(*header, "chunked"))
1905 csp->flags |= CSP_FLAG_CHUNKED;
1908 * If the body was modified, it has been de-chunked first
1909 * and the header must be removed.
1911 * FIXME: If there is more than one transfer encoding,
1912 * only the "chunked" part should be removed here.
1914 if (csp->flags & CSP_FLAG_MODIFIED)
1916 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1925 /*********************************************************************
1927 * Function : server_content_encoding
1929 * Description : This function is run twice for each request,
1930 * unless FEATURE_ZLIB and filtering are disabled.
1932 * The first run is used to check if the content
1933 * is compressed, if FEATURE_ZLIB is disabled
1934 * filtering is then disabled as well, if FEATURE_ZLIB
1935 * is enabled the content is marked for decompression.
1937 * The second run is used to remove the Content-Encoding
1938 * header if the decompression was successful.
1941 * 1 : csp = Current client state (buffers, headers, etc...)
1942 * 2 : header = On input, pointer to header to modify.
1943 * On output, pointer to the modified header, or NULL
1944 * to remove the header. This function frees the
1945 * original string if necessary.
1947 * Returns : JB_ERR_OK on success, or
1948 * JB_ERR_MEMORY on out-of-memory error.
1950 *********************************************************************/
1951 static jb_err server_content_encoding(struct client_state *csp, char **header)
1954 if ((csp->flags & CSP_FLAG_MODIFIED)
1955 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
1958 * We successfully decompressed the content,
1959 * and have to clean the header now, so the
1960 * client no longer expects compressed data..
1962 * XXX: There is a difference between cleaning
1963 * and removing it completely.
1965 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
1968 else if (strstr(*header, "gzip"))
1970 /* Mark for gzip decompression */
1971 csp->content_type |= CT_GZIP;
1973 else if (strstr(*header, "deflate"))
1975 /* Mark for zlib decompression */
1976 csp->content_type |= CT_DEFLATE;
1978 else if (strstr(*header, "compress"))
1981 * We can't decompress this; therefore we can't filter
1984 csp->content_type |= CT_TABOO;
1986 #else /* !defined(FEATURE_ZLIB) */
1987 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1990 * Body is compressed, turn off pcrs and gif filtering.
1992 csp->content_type |= CT_TABOO;
1995 * Log a warning if the user expects the content to be filtered.
1997 if ((csp->rlist != NULL) &&
1998 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2000 log_error(LOG_LEVEL_INFO,
2001 "Compressed content detected, content filtering disabled. "
2002 "Consider recompiling Privoxy with zlib support or "
2003 "enable the prevent-compression action.");
2006 #endif /* defined(FEATURE_ZLIB) */
2013 /*********************************************************************
2015 * Function : server_adjust_content_length
2017 * Description : Adjust Content-Length header if we modified
2021 * 1 : csp = Current client state (buffers, headers, etc...)
2022 * 2 : header = On input, pointer to header to modify.
2023 * On output, pointer to the modified header, or NULL
2024 * to remove the header. This function frees the
2025 * original string if necessary.
2027 * Returns : JB_ERR_OK on success, or
2028 * JB_ERR_MEMORY on out-of-memory error.
2030 *********************************************************************/
2031 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2033 const size_t max_header_length = 80;
2035 /* Regenerate header if the content was modified. */
2036 if (csp->flags & CSP_FLAG_MODIFIED)
2039 *header = (char *) zalloc(max_header_length);
2040 if (*header == NULL)
2042 return JB_ERR_MEMORY;
2045 snprintf(*header, max_header_length, "Content-Length: %d",
2046 (int)csp->content_length);
2047 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2048 (int)csp->content_length);
2055 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2056 /*********************************************************************
2058 * Function : server_save_content_length
2060 * Description : Save the Content-Length sent by the server.
2063 * 1 : csp = Current client state (buffers, headers, etc...)
2064 * 2 : header = On input, pointer to header to modify.
2065 * On output, pointer to the modified header, or NULL
2066 * to remove the header. This function frees the
2067 * original string if necessary.
2069 * Returns : JB_ERR_OK on success, or
2070 * JB_ERR_MEMORY on out-of-memory error.
2072 *********************************************************************/
2073 static jb_err server_save_content_length(struct client_state *csp, char **header)
2075 unsigned long long content_length = 0;
2077 assert(*(*header+14) == ':');
2079 if (1 != sscanf(*header+14, ": %llu", &content_length))
2081 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2086 csp->expected_content_length = content_length;
2087 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2092 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2095 /*********************************************************************
2097 * Function : server_content_md5
2099 * Description : Crumble any Content-MD5 headers if the document was
2100 * modified. FIXME: Should we re-compute instead?
2103 * 1 : csp = Current client state (buffers, headers, etc...)
2104 * 2 : header = On input, pointer to header to modify.
2105 * On output, pointer to the modified header, or NULL
2106 * to remove the header. This function frees the
2107 * original string if necessary.
2109 * Returns : JB_ERR_OK on success, or
2110 * JB_ERR_MEMORY on out-of-memory error.
2112 *********************************************************************/
2113 static jb_err server_content_md5(struct client_state *csp, char **header)
2115 if (csp->flags & CSP_FLAG_MODIFIED)
2117 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2125 /*********************************************************************
2127 * Function : server_content_disposition
2129 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2130 * Called from `sed'.
2133 * 1 : csp = Current client state (buffers, headers, etc...)
2134 * 2 : header = On input, pointer to header to modify.
2135 * On output, pointer to the modified header, or NULL
2136 * to remove the header. This function frees the
2137 * original string if necessary.
2139 * Returns : JB_ERR_OK on success, or
2140 * JB_ERR_MEMORY on out-of-memory error.
2142 *********************************************************************/
2143 static jb_err server_content_disposition(struct client_state *csp, char **header)
2148 * Are we messing with the Content-Disposition header?
2150 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2156 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2158 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2161 * Blocking content-disposition header
2163 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2170 * Replacing Content-Disposition header
2173 *header = strdup("Content-Disposition: ");
2174 string_append(header, newval);
2176 if (*header != NULL)
2178 log_error(LOG_LEVEL_HEADER,
2179 "Content-Disposition header crunched and replaced with: %s", *header);
2182 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2186 /*********************************************************************
2188 * Function : server_last_modified
2190 * Description : Changes Last-Modified header to the actual date
2191 * to help hide-if-modified-since.
2192 * Called from `sed'.
2195 * 1 : csp = Current client state (buffers, headers, etc...)
2196 * 2 : header = On input, pointer to header to modify.
2197 * On output, pointer to the modified header, or NULL
2198 * to remove the header. This function frees the
2199 * original string if necessary.
2201 * Returns : JB_ERR_OK on success, or
2202 * JB_ERR_MEMORY on out-of-memory error.
2204 *********************************************************************/
2205 static jb_err server_last_modified(struct client_state *csp, char **header)
2208 char buf[BUFFER_SIZE];
2211 #ifdef HAVE_GMTIME_R
2214 struct tm *timeptr = NULL;
2215 time_t now, last_modified;
2216 long int days, hours, minutes, seconds;
2219 * Are we messing with the Last-Modified header?
2221 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2227 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2229 if (0 == strcmpic(newval, "block") )
2232 * Blocking Last-Modified header. Useless but why not.
2234 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2238 else if (0 == strcmpic(newval, "reset-to-request-time"))
2241 * Setting Last-Modified Header to now.
2243 get_http_time(0, buf, sizeof(buf));
2245 *header = strdup("Last-Modified: ");
2246 string_append(header, buf);
2248 if (*header == NULL)
2250 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2254 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2257 else if (0 == strcmpic(newval, "randomize"))
2259 const char *header_time = *header + sizeof("Last-Modified:");
2261 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2263 #ifdef HAVE_GMTIME_R
2264 gmtime_r(&now, &gmt);
2265 #elif defined(MUTEX_LOCKS_AVAILABLE)
2266 privoxy_mutex_lock(&gmtime_mutex);
2268 privoxy_mutex_unlock(&gmtime_mutex);
2272 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2274 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2279 long int rtime = (long int)difftime(now, last_modified);
2282 const int negative_delta = (rtime < 0);
2287 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
2289 rtime = pick_from_range(rtime);
2294 last_modified += rtime;
2295 #ifdef HAVE_GMTIME_R
2296 timeptr = gmtime_r(&last_modified, &gmt);
2297 #elif defined(MUTEX_LOCKS_AVAILABLE)
2298 privoxy_mutex_lock(&gmtime_mutex);
2299 timeptr = gmtime(&last_modified);
2300 privoxy_mutex_unlock(&gmtime_mutex);
2302 timeptr = gmtime(&last_modified);
2304 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2306 *header = strdup("Last-Modified: ");
2307 string_append(header, newheader);
2309 if (*header == NULL)
2311 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
2312 return JB_ERR_MEMORY;
2315 days = rtime / (3600 * 24);
2316 hours = rtime / 3600 % 24;
2317 minutes = rtime / 60 % 60;
2318 seconds = rtime % 60;
2320 log_error(LOG_LEVEL_HEADER,
2321 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2322 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2323 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2327 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2336 /*********************************************************************
2338 * Function : client_accept_encoding
2340 * Description : Rewrite the client's Accept-Encoding header so that
2341 * if doesn't allow compression, if the action applies.
2342 * Note: For HTTP/1.0 the absence of the header is enough.
2345 * 1 : csp = Current client state (buffers, headers, etc...)
2346 * 2 : header = On input, pointer to header to modify.
2347 * On output, pointer to the modified header, or NULL
2348 * to remove the header. This function frees the
2349 * original string if necessary.
2351 * Returns : JB_ERR_OK on success, or
2352 * JB_ERR_MEMORY on out-of-memory error.
2354 *********************************************************************/
2355 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2357 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2359 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2363 /* Temporarily disable the correct behaviour to
2364 * work around a PHP bug.
2366 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2368 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2369 * if (*header == NULL)
2371 * return JB_ERR_MEMORY;
2382 /*********************************************************************
2384 * Function : client_te
2386 * Description : Rewrite the client's TE header so that
2387 * if doesn't allow compression, if the action applies.
2390 * 1 : csp = Current client state (buffers, headers, etc...)
2391 * 2 : header = On input, pointer to header to modify.
2392 * On output, pointer to the modified header, or NULL
2393 * to remove the header. This function frees the
2394 * original string if necessary.
2396 * Returns : JB_ERR_OK on success, or
2397 * JB_ERR_MEMORY on out-of-memory error.
2399 *********************************************************************/
2400 static jb_err client_te(struct client_state *csp, char **header)
2402 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2405 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2412 /*********************************************************************
2414 * Function : client_referrer
2416 * Description : Handle the "referer" config setting properly.
2417 * Called from `sed'.
2420 * 1 : csp = Current client state (buffers, headers, etc...)
2421 * 2 : header = On input, pointer to header to modify.
2422 * On output, pointer to the modified header, or NULL
2423 * to remove the header. This function frees the
2424 * original string if necessary.
2426 * Returns : JB_ERR_OK on success, or
2427 * JB_ERR_MEMORY on out-of-memory error.
2429 *********************************************************************/
2430 static jb_err client_referrer(struct client_state *csp, char **header)
2432 const char *parameter;
2433 /* booleans for parameters we have to check multiple times */
2434 int parameter_conditional_block;
2435 int parameter_conditional_forge;
2437 #ifdef FEATURE_FORCE_LOAD
2439 * Since the referrer can include the prefix even
2440 * if the request itself is non-forced, we must
2441 * clean it unconditionally.
2443 * XXX: strclean is too broad
2445 strclean(*header, FORCE_PREFIX);
2446 #endif /* def FEATURE_FORCE_LOAD */
2448 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2450 /* Nothing left to do */
2454 parameter = csp->action->string[ACTION_STRING_REFERER];
2455 assert(parameter != NULL);
2456 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2457 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2459 if (!parameter_conditional_block && !parameter_conditional_forge)
2462 * As conditional-block and conditional-forge are the only
2463 * parameters that rely on the original referrer, we can
2464 * remove it now for all the others.
2469 if (0 == strcmpic(parameter, "block"))
2471 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2474 else if (parameter_conditional_block || parameter_conditional_forge)
2476 return handle_conditional_hide_referrer_parameter(header,
2477 csp->http->hostport, parameter_conditional_block);
2479 else if (0 == strcmpic(parameter, "forge"))
2481 return create_forged_referrer(header, csp->http->hostport);
2485 /* interpret parameter as user-supplied referer to fake */
2486 return create_fake_referrer(header, parameter);
2491 /*********************************************************************
2493 * Function : client_accept_language
2495 * Description : Handle the "Accept-Language" config setting properly.
2496 * Called from `sed'.
2499 * 1 : csp = Current client state (buffers, headers, etc...)
2500 * 2 : header = On input, pointer to header to modify.
2501 * On output, pointer to the modified header, or NULL
2502 * to remove the header. This function frees the
2503 * original string if necessary.
2505 * Returns : JB_ERR_OK on success, or
2506 * JB_ERR_MEMORY on out-of-memory error.
2508 *********************************************************************/
2509 static jb_err client_accept_language(struct client_state *csp, char **header)
2514 * Are we messing with the Accept-Language?
2516 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2518 /*I don't think so*/
2522 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2524 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2527 * Blocking Accept-Language header
2529 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2536 * Replacing Accept-Language header
2539 *header = strdup("Accept-Language: ");
2540 string_append(header, newval);
2542 if (*header == NULL)
2544 log_error(LOG_LEVEL_ERROR,
2545 "Insufficient memory. Accept-Language header crunched without replacement.");
2549 log_error(LOG_LEVEL_HEADER,
2550 "Accept-Language header crunched and replaced with: %s", *header);
2553 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2557 /*********************************************************************
2559 * Function : crunch_client_header
2561 * Description : Crunch client header if it matches a string supplied by the
2562 * user. Called from `sed'.
2565 * 1 : csp = Current client state (buffers, headers, etc...)
2566 * 2 : header = On input, pointer to header to modify.
2567 * On output, pointer to the modified header, or NULL
2568 * to remove the header. This function frees the
2569 * original string if necessary.
2571 * Returns : JB_ERR_OK on success and always succeeds
2573 *********************************************************************/
2574 static jb_err crunch_client_header(struct client_state *csp, char **header)
2576 const char *crunch_pattern;
2578 /* Do we feel like crunching? */
2579 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2581 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2583 /* Is the current header the lucky one? */
2584 if (strstr(*header, crunch_pattern))
2586 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2594 /*********************************************************************
2596 * Function : client_uagent
2598 * Description : Handle the "user-agent" config setting properly
2599 * and remember its original value to enable browser
2600 * bug workarounds. Called from `sed'.
2603 * 1 : csp = Current client state (buffers, headers, etc...)
2604 * 2 : header = On input, pointer to header to modify.
2605 * On output, pointer to the modified header, or NULL
2606 * to remove the header. This function frees the
2607 * original string if necessary.
2609 * Returns : JB_ERR_OK on success, or
2610 * JB_ERR_MEMORY on out-of-memory error.
2612 *********************************************************************/
2613 static jb_err client_uagent(struct client_state *csp, char **header)
2617 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2622 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2629 *header = strdup("User-Agent: ");
2630 string_append(header, newval);
2632 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2634 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2638 /*********************************************************************
2640 * Function : client_ua
2642 * Description : Handle "ua-" headers properly. Called from `sed'.
2645 * 1 : csp = Current client state (buffers, headers, etc...)
2646 * 2 : header = On input, pointer to header to modify.
2647 * On output, pointer to the modified header, or NULL
2648 * to remove the header. This function frees the
2649 * original string if necessary.
2651 * Returns : JB_ERR_OK on success, or
2652 * JB_ERR_MEMORY on out-of-memory error.
2654 *********************************************************************/
2655 static jb_err client_ua(struct client_state *csp, char **header)
2657 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2659 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2667 /*********************************************************************
2669 * Function : client_from
2671 * Description : Handle the "from" config setting properly.
2672 * Called from `sed'.
2675 * 1 : csp = Current client state (buffers, headers, etc...)
2676 * 2 : header = On input, pointer to header to modify.
2677 * On output, pointer to the modified header, or NULL
2678 * to remove the header. This function frees the
2679 * original string if necessary.
2681 * Returns : JB_ERR_OK on success, or
2682 * JB_ERR_MEMORY on out-of-memory error.
2684 *********************************************************************/
2685 static jb_err client_from(struct client_state *csp, char **header)
2689 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2696 newval = csp->action->string[ACTION_STRING_FROM];
2699 * Are we blocking the e-mail address?
2701 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2703 log_error(LOG_LEVEL_HEADER, "crunched From!");
2707 log_error(LOG_LEVEL_HEADER, " modified");
2709 *header = strdup("From: ");
2710 string_append(header, newval);
2712 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2716 /*********************************************************************
2718 * Function : client_send_cookie
2720 * Description : Crunches the "cookie" header if necessary.
2721 * Called from `sed'.
2723 * XXX: Stupid name, doesn't send squat.
2726 * 1 : csp = Current client state (buffers, headers, etc...)
2727 * 2 : header = On input, pointer to header to modify.
2728 * On output, pointer to the modified header, or NULL
2729 * to remove the header. This function frees the
2730 * original string if necessary.
2732 * Returns : JB_ERR_OK on success, or
2733 * JB_ERR_MEMORY on out-of-memory error.
2735 *********************************************************************/
2736 static jb_err client_send_cookie(struct client_state *csp, char **header)
2738 if (csp->action->flags & ACTION_NO_COOKIE_READ)
2740 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
2748 /*********************************************************************
2750 * Function : client_x_forwarded
2752 * Description : Handle the "x-forwarded-for" config setting properly,
2753 * also used in the add_client_headers list. Called from `sed'.
2756 * 1 : csp = Current client state (buffers, headers, etc...)
2757 * 2 : header = On input, pointer to header to modify.
2758 * On output, pointer to the modified header, or NULL
2759 * to remove the header. This function frees the
2760 * original string if necessary.
2762 * Returns : JB_ERR_OK on success, or
2763 * JB_ERR_MEMORY on out-of-memory error.
2765 *********************************************************************/
2766 jb_err client_x_forwarded(struct client_state *csp, char **header)
2768 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
2770 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
2772 if (0 == strcmpic(parameter, "block"))
2775 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2777 else if (0 == strcmpic(parameter, "add"))
2779 string_append(header, ", ");
2780 string_append(header, csp->ip_addr_str);
2782 if (*header == NULL)
2784 return JB_ERR_MEMORY;
2786 log_error(LOG_LEVEL_HEADER,
2787 "Appended client IP address to %s", *header);
2788 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
2792 log_error(LOG_LEVEL_FATAL,
2793 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
2801 /*********************************************************************
2803 * Function : client_max_forwards
2805 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2806 * from the value of the Max-Forwards header field.
2809 * 1 : csp = Current client state (buffers, headers, etc...)
2810 * 2 : header = On input, pointer to header to modify.
2811 * On output, pointer to the modified header, or NULL
2812 * to remove the header. This function frees the
2813 * original string if necessary.
2815 * Returns : JB_ERR_OK on success, or
2816 * JB_ERR_MEMORY on out-of-memory error.
2818 *********************************************************************/
2819 static jb_err client_max_forwards(struct client_state *csp, char **header)
2823 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
2824 (0 == strcmpic(csp->http->gpc, "options")))
2826 assert(*(*header+12) == ':');
2827 if (1 == sscanf(*header+12, ": %d", &max_forwards))
2829 if (max_forwards > 0)
2831 snprintf(*header, strlen(*header)+1, "Max-Forwards: %d", --max_forwards);
2832 log_error(LOG_LEVEL_HEADER,
2833 "Max-Forwards value for %s request reduced to %d.",
2834 csp->http->gpc, max_forwards);
2836 else if (max_forwards < 0)
2838 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2844 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2853 /*********************************************************************
2855 * Function : client_host
2857 * Description : If the request URI did not contain host and
2858 * port information, parse and evaluate the Host
2861 * Also, kill ill-formed HOST: headers as sent by
2862 * Apple's iTunes software when used with a proxy.
2865 * 1 : csp = Current client state (buffers, headers, etc...)
2866 * 2 : header = On input, pointer to header to modify.
2867 * On output, pointer to the modified header, or NULL
2868 * to remove the header. This function frees the
2869 * original string if necessary.
2871 * Returns : JB_ERR_OK on success, or
2872 * JB_ERR_MEMORY on out-of-memory error.
2874 *********************************************************************/
2875 static jb_err client_host(struct client_state *csp, char **header)
2880 * If the header field name is all upper-case, chances are that it's
2881 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2882 * not a problem -- they are regenerated later.
2884 if ((*header)[1] == 'O')
2886 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2891 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2892 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2895 if (NULL == (p = strdup((*header)+6)))
2897 return JB_ERR_MEMORY;
2900 if (NULL == (q = strdup(p)))
2903 return JB_ERR_MEMORY;
2906 freez(csp->http->hostport);
2907 csp->http->hostport = p;
2908 freez(csp->http->host);
2909 csp->http->host = q;
2910 q = strchr(csp->http->host, ':');
2913 /* Terminate hostname and evaluate port string */
2915 csp->http->port = atoi(q);
2919 csp->http->port = csp->http->ssl ? 443 : 80;
2922 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2923 csp->http->hostport, csp->http->host, csp->http->port);
2926 /* Signal client_host_adder() to return right away */
2927 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
2933 /*********************************************************************
2935 * Function : client_if_modified_since
2937 * Description : Remove or modify the If-Modified-Since header.
2940 * 1 : csp = Current client state (buffers, headers, etc...)
2941 * 2 : header = On input, pointer to header to modify.
2942 * On output, pointer to the modified header, or NULL
2943 * to remove the header. This function frees the
2944 * original string if necessary.
2946 * Returns : JB_ERR_OK on success, or
2947 * JB_ERR_MEMORY on out-of-memory error.
2949 *********************************************************************/
2950 static jb_err client_if_modified_since(struct client_state *csp, char **header)
2953 #ifdef HAVE_GMTIME_R
2956 struct tm *timeptr = NULL;
2959 long int hours, minutes, seconds;
2962 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2965 * The client got an error message because of a temporary problem,
2966 * the problem is gone and the client now tries to revalidate our
2967 * error message on the real server. The revalidation would always
2968 * end with the transmission of the whole document and there is
2969 * no need to expose the bogus If-Modified-Since header.
2971 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2974 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2976 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2978 if ((0 == strcmpic(newval, "block")))
2980 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2983 else /* add random value */
2985 const char *header_time = *header + sizeof("If-Modified-Since:");
2987 if (JB_ERR_OK != parse_header_time(header_time, &tm))
2989 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2994 long int rtime = strtol(newval, &endptr, 0);
2995 const int negative_range = (rtime < 0);
2999 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3000 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3006 rtime = pick_from_range(rtime);
3010 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3013 tm += rtime * (negative_range ? -1 : 1);
3014 #ifdef HAVE_GMTIME_R
3015 timeptr = gmtime_r(&tm, &gmt);
3016 #elif defined(MUTEX_LOCKS_AVAILABLE)
3017 privoxy_mutex_lock(&gmtime_mutex);
3018 timeptr = gmtime(&tm);
3019 privoxy_mutex_unlock(&gmtime_mutex);
3021 timeptr = gmtime(&tm);
3023 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3026 *header = strdup("If-Modified-Since: ");
3027 string_append(header, newheader);
3029 if (*header == NULL)
3031 log_error(LOG_LEVEL_HEADER, "Insufficient memory, header crunched without replacement.");
3032 return JB_ERR_MEMORY;
3035 hours = rtime / 3600;
3036 minutes = rtime / 60 % 60;
3037 seconds = rtime % 60;
3039 log_error(LOG_LEVEL_HEADER,
3040 "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3041 *header, (negative_range) ? "subtracted" : "added", hours,
3042 (hours == 1) ? "r" : "rs", minutes, (minutes == 1) ? "e" : "es",
3043 seconds, (seconds == 1) ? ")" : "s)");
3052 /*********************************************************************
3054 * Function : client_if_none_match
3056 * Description : Remove the If-None-Match header.
3059 * 1 : csp = Current client state (buffers, headers, etc...)
3060 * 2 : header = On input, pointer to header to modify.
3061 * On output, pointer to the modified header, or NULL
3062 * to remove the header. This function frees the
3063 * original string if necessary.
3065 * Returns : JB_ERR_OK on success, or
3066 * JB_ERR_MEMORY on out-of-memory error.
3068 *********************************************************************/
3069 static jb_err client_if_none_match(struct client_state *csp, char **header)
3071 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3073 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3081 /*********************************************************************
3083 * Function : client_x_filter
3085 * Description : Disables filtering if the client set "X-Filter: No".
3086 * Called from `sed'.
3089 * 1 : csp = Current client state (buffers, headers, etc...)
3090 * 2 : header = On input, pointer to header to modify.
3091 * On output, pointer to the modified header, or NULL
3092 * to remove the header. This function frees the
3093 * original string if necessary.
3095 * Returns : JB_ERR_OK on success
3097 *********************************************************************/
3098 jb_err client_x_filter(struct client_state *csp, char **header)
3100 if ( 0 == strcmpic(*header, "X-Filter: No"))
3102 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3104 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3108 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3110 log_error(LOG_LEVEL_HEADER,
3111 "force-text-mode overruled the client's request to fetch without filtering!");
3115 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3116 csp->flags |= CSP_FLAG_NO_FILTERING;
3117 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3119 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3127 /*********************************************************************
3129 * Function : client_range
3131 * Description : Removes Range, Request-Range and If-Range headers if
3132 * content filtering is enabled. If the client's version
3133 * of the document has been altered by Privoxy, the server
3134 * could interpret the range differently than the client
3135 * intended in which case the user could end up with
3136 * corrupted content.
3139 * 1 : csp = Current client state (buffers, headers, etc...)
3140 * 2 : header = On input, pointer to header to modify.
3141 * On output, pointer to the modified header, or NULL
3142 * to remove the header. This function frees the
3143 * original string if necessary.
3145 * Returns : JB_ERR_OK
3147 *********************************************************************/
3148 static jb_err client_range(struct client_state *csp, char **header)
3150 if (content_filters_enabled(csp->action))
3152 log_error(LOG_LEVEL_HEADER, "Content filtering is enabled."
3153 " Crunching: \'%s\' to prevent range-mismatch problems.", *header);
3160 /* the following functions add headers directly to the header list */
3162 /*********************************************************************
3164 * Function : client_host_adder
3166 * Description : Adds the Host: header field if it is missing.
3167 * Called from `sed'.
3170 * 1 : csp = Current client state (buffers, headers, etc...)
3172 * Returns : JB_ERR_OK on success, or
3173 * JB_ERR_MEMORY on out-of-memory error.
3175 *********************************************************************/
3176 static jb_err client_host_adder(struct client_state *csp)
3181 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3183 /* Header already set by the client, nothing to do. */
3187 if ( !csp->http->hostport || !*(csp->http->hostport))
3189 /* XXX: When does this happen and why is it OK? */
3190 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3195 * remove 'user:pass@' from 'proto://user:pass@host'
3197 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3203 p = csp->http->hostport;
3206 /* XXX: Just add it, we already made sure that it will be unique */
3207 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3208 err = enlist_unique_header(csp->headers, "Host", p);
3215 /*********************************************************************
3217 * Function : client_accept_encoding_adder
3219 * Description : Add an Accept-Encoding header to the client's request
3220 * that disables compression if the action applies, and
3221 * the header is not already there. Called from `sed'.
3222 * Note: For HTTP/1.0, the absence of the header is enough.
3225 * 1 : csp = Current client state (buffers, headers, etc...)
3227 * Returns : JB_ERR_OK on success, or
3228 * JB_ERR_MEMORY on out-of-memory error.
3230 *********************************************************************/
3231 static jb_err client_accept_encoding_adder(struct client_state *csp)
3233 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3234 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3236 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3244 /*********************************************************************
3246 * Function : client_xtra_adder
3248 * Description : Used in the add_client_headers list. Called from `sed'.
3251 * 1 : csp = Current client state (buffers, headers, etc...)
3253 * Returns : JB_ERR_OK on success, or
3254 * JB_ERR_MEMORY on out-of-memory error.
3256 *********************************************************************/
3257 static jb_err client_xtra_adder(struct client_state *csp)
3259 struct list_entry *lst;
3262 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3263 lst ; lst = lst->next)
3265 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3266 err = enlist(csp->headers, lst->str);
3278 /*********************************************************************
3280 * Function : client_x_forwarded_for_adder
3282 * Description : Used in the add_client_headers list. Called from `sed'.
3285 * 1 : csp = Current client state (buffers, headers, etc...)
3287 * Returns : JB_ERR_OK on success, or
3288 * JB_ERR_MEMORY on out-of-memory error.
3290 *********************************************************************/
3291 static jb_err client_x_forwarded_for_adder(struct client_state *csp)
3293 char *header = NULL;
3296 if (!((csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR)
3297 && (0 == strcmpic(csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR], "add")))
3298 || (csp->flags & CSP_FLAG_X_FORWARDED_FOR_APPENDED))
3301 * If we aren't adding X-Forwarded-For headers,
3302 * or we already appended an existing X-Forwarded-For
3303 * header, there's nothing left to do here.
3308 header = strdup("X-Forwarded-For: ");
3309 string_append(&header, csp->ip_addr_str);
3313 return JB_ERR_MEMORY;
3316 log_error(LOG_LEVEL_HEADER, "addh: %s", header);
3317 err = enlist(csp->headers, header);
3324 /*********************************************************************
3326 * Function : server_connection_adder
3328 * Description : Adds an appropiate "Connection:" header to csp->headers
3329 * unless the header was already present. Called from `sed'.
3332 * 1 : csp = Current client state (buffers, headers, etc...)
3334 * Returns : JB_ERR_OK on success, or
3335 * JB_ERR_MEMORY on out-of-memory error.
3337 *********************************************************************/
3338 static jb_err server_connection_adder(struct client_state *csp)
3340 const unsigned int flags = csp->flags;
3341 const char *response_status_line = csp->headers->first->str;
3342 const char *wanted_header = get_appropiate_connection_header(csp);
3344 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3345 && (flags & CSP_FLAG_SERVER_CONNECTION_HEADER_SET))
3351 * XXX: if we downgraded the response, this check will fail.
3353 if ((csp->config->feature_flags &
3354 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3355 && (NULL != response_status_line)
3356 && !strncmpic(response_status_line, "HTTP/1.1", 8))
3358 log_error(LOG_LEVEL_HEADER, "A HTTP/1.1 response "
3359 "without Connection header implies keep-alive.");
3360 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
3363 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3365 return enlist(csp->headers, wanted_header);
3369 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3370 /*********************************************************************
3372 * Function : server_proxy_connection_adder
3374 * Description : Adds a "Proxy-Connection: keep-alive" header to
3375 * csp->headers if the client asked for keep-alive.
3376 * XXX: We should reuse existant ones.
3379 * 1 : csp = Current client state (buffers, headers, etc...)
3381 * Returns : JB_ERR_OK on success, or
3382 * JB_ERR_MEMORY on out-of-memory error.
3384 *********************************************************************/
3385 static jb_err server_proxy_connection_adder(struct client_state *csp)
3387 static const char proxy_connection_header[] = "Proxy-Connection: keep-alive";
3388 jb_err err = JB_ERR_OK;
3390 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3392 log_error(LOG_LEVEL_HEADER, "Adding: %s", proxy_connection_header);
3393 err = enlist(csp->headers, proxy_connection_header);
3398 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3401 /*********************************************************************
3403 * Function : client_connection_header_adder
3405 * Description : Adds a proper "Connection:" header to csp->headers
3406 * unless the header was already present. Called from `sed'.
3409 * 1 : csp = Current client state (buffers, headers, etc...)
3411 * Returns : JB_ERR_OK on success, or
3412 * JB_ERR_MEMORY on out-of-memory error.
3414 *********************************************************************/
3415 static jb_err client_connection_header_adder(struct client_state *csp)
3417 const char *wanted_header = get_appropiate_connection_header(csp);
3419 if (!(csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3420 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_HEADER_SET))
3425 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3426 && (csp->http->ssl == 0))
3428 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3431 log_error(LOG_LEVEL_HEADER, "Adding: %s", wanted_header);
3433 return enlist(csp->headers, wanted_header);
3437 /*********************************************************************
3439 * Function : server_http
3441 * Description : - Save the HTTP Status into csp->http->status
3442 * - Set CT_TABOO to prevent filtering if the answer
3443 * is a partial range (HTTP status 206)
3444 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3448 * 1 : csp = Current client state (buffers, headers, etc...)
3449 * 2 : header = On input, pointer to header to modify.
3450 * On output, pointer to the modified header, or NULL
3451 * to remove the header. This function frees the
3452 * original string if necessary.
3454 * Returns : JB_ERR_OK on success, or
3455 * JB_ERR_MEMORY on out-of-memory error.
3457 *********************************************************************/
3458 static jb_err server_http(struct client_state *csp, char **header)
3460 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3461 if (csp->http->status == 206)
3463 csp->content_type = CT_TABOO;
3466 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3468 /* XXX: Should we do a real validity check here? */
3469 if (strlen(*header) > 8)
3472 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3477 * XXX: Should we block the request or
3478 * enlist a valid status code line here?
3480 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3481 "Downgrading to HTTP/1.0 impossible.");
3489 /*********************************************************************
3491 * Function : server_set_cookie
3493 * Description : Handle the server "cookie" header properly.
3494 * Log cookie to the jar file. Then "crunch",
3495 * accept or rewrite it to a session cookie.
3496 * Called from `sed'.
3498 * TODO: Allow the user to specify a new expiration
3499 * time to cause the cookie to expire even before the
3500 * browser is closed.
3503 * 1 : csp = Current client state (buffers, headers, etc...)
3504 * 2 : header = On input, pointer to header to modify.
3505 * On output, pointer to the modified header, or NULL
3506 * to remove the header. This function frees the
3507 * original string if necessary.
3509 * Returns : JB_ERR_OK on success, or
3510 * JB_ERR_MEMORY on out-of-memory error.
3512 *********************************************************************/
3513 static jb_err server_set_cookie(struct client_state *csp, char **header)
3520 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3522 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3525 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3527 /* Flag whether or not to log a message */
3530 /* A variable to store the tag we're working on */
3533 /* Skip "Set-Cookie:" (11 characters) in header */
3534 cur_tag = *header + 11;
3536 /* skip whitespace between "Set-Cookie:" and value */
3537 while (*cur_tag && ijb_isspace(*cur_tag))
3542 /* Loop through each tag in the cookie */
3546 char *next_tag = strchr(cur_tag, ';');
3547 if (next_tag != NULL)
3549 /* Skip the ';' character itself */
3552 /* skip whitespace ";" and start of tag */
3553 while (*next_tag && ijb_isspace(*next_tag))
3560 /* "Next tag" is the end of the string */
3561 next_tag = cur_tag + strlen(cur_tag);
3565 * Check the expiration date to see
3566 * if the cookie is still valid, if yes,
3567 * rewrite it to a session cookie.
3569 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3571 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3573 /* Did we detect the date properly? */
3574 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3577 * Nope, treat it as if it was still valid.
3579 * XXX: Should we remove the whole cookie instead?
3581 log_error(LOG_LEVEL_ERROR,
3582 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3583 string_move(cur_tag, next_tag);
3589 * Yes. Check if the cookie is still valid.
3591 * If the cookie is already expired it's probably
3592 * a delete cookie and even if it isn't, the browser
3593 * will discard it anyway.
3597 * XXX: timegm() isn't available on some AmigaOS
3598 * versions and our replacement doesn't work.
3600 * Our options are to either:
3602 * - disable session-cookies-only completely if timegm
3605 * - to simply remove all expired tags, like it has
3606 * been done until Privoxy 3.0.6 and to live with
3607 * the consequence that it can cause login/logout
3608 * problems on servers that don't validate their
3609 * input properly, or
3611 * - to replace it with mktime in which
3612 * case there is a slight chance of valid cookies
3613 * passing as already expired.
3615 * This is the way it's currently done and it's not
3616 * as bad as it sounds. If the missing GMT offset is
3617 * enough to change the result of the expiration check
3618 * the cookie will be only valid for a few hours
3619 * anyway, which in many cases will be shorter
3620 * than a browser session.
3622 if (cookie_time - now < 0)
3624 log_error(LOG_LEVEL_HEADER,
3625 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3626 /* Just in case some clown sets more then one expiration date */
3632 * Still valid, delete expiration date by copying
3633 * the rest of the string over it.
3635 string_move(cur_tag, next_tag);
3637 /* That changed the header, need to issue a log message */
3641 * Note that the next tag has now been moved to *cur_tag,
3642 * so we do not need to update the cur_tag pointer.
3650 /* Move on to next cookie tag */
3657 assert(NULL != *header);
3658 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3667 #ifdef FEATURE_FORCE_LOAD
3668 /*********************************************************************
3670 * Function : strclean
3672 * Description : In-Situ-Eliminate all occurances of substring in
3676 * 1 : string = string to clean
3677 * 2 : substring = substring to eliminate
3679 * Returns : Number of eliminations
3681 *********************************************************************/
3682 int strclean(char *string, const char *substring)
3688 len = strlen(substring);
3690 while((pos = strstr(string, substring)) != NULL)
3697 while (*p++ != '\0');
3704 #endif /* def FEATURE_FORCE_LOAD */
3707 /*********************************************************************
3709 * Function : parse_header_time
3711 * Description : Parses time formats used in HTTP header strings
3712 * to get the numerical respresentation.
3715 * 1 : header_time = HTTP header time as string.
3716 * 2 : result = storage for header_time in seconds
3718 * Returns : JB_ERR_OK if the time format was recognized, or
3719 * JB_ERR_PARSE otherwise.
3721 *********************************************************************/
3722 static jb_err parse_header_time(const char *header_time, time_t *result)
3727 * Zero out gmt to prevent time zone offsets.
3729 * While this is only necessary on some platforms
3730 * (mingw32 for example), I don't know how to
3731 * detect these automatically and doing it everywhere
3734 memset(&gmt, 0, sizeof(gmt));
3736 /* Tue, 02 Jun 2037 20:00:00 */
3737 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3738 /* Tue, 02-Jun-2037 20:00:00 */
3739 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3740 /* Tue, 02-Jun-37 20:00:00 */
3741 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3742 /* Tuesday, 02-Jun-2037 20:00:00 */
3743 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3744 /* Tuesday Jun 02 20:00:00 2037 */
3745 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3747 return JB_ERR_PARSE;
3750 *result = timegm(&gmt);
3757 /*********************************************************************
3759 * Function : get_destination_from_headers
3761 * Description : Parse the "Host:" header to get the request's destination.
3762 * Only needed if the client's request was forcefully
3763 * redirected into Privoxy.
3765 * Code mainly copied from client_host() which is currently
3766 * run too late for this purpose.
3769 * 1 : headers = List of headers (one of them hopefully being
3770 * the "Host:" header)
3771 * 2 : http = storage for the result (host, port and hostport).
3773 * Returns : JB_ERR_MEMORY in case of memory problems,
3774 * JB_ERR_PARSE if the host header couldn't be found,
3775 * JB_ERR_OK otherwise.
3777 *********************************************************************/
3778 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
3784 host = get_header_value(headers, "Host:");
3788 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
3789 return JB_ERR_PARSE;
3792 if (NULL == (p = strdup((host))))
3794 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3795 return JB_ERR_MEMORY;
3798 if (NULL == (q = strdup(p)))
3801 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
3802 return JB_ERR_MEMORY;
3805 freez(http->hostport);
3809 q = strchr(http->host, ':');
3812 /* Terminate hostname and evaluate port string */
3814 http->port = atoi(q);
3818 http->port = http->ssl ? 443 : 80;
3821 /* Rebuild request URL */
3823 http->url = strdup(http->ssl ? "https://" : "http://");
3824 string_append(&http->url, http->hostport);
3825 string_append(&http->url, http->path);
3826 if (http->url == NULL)
3828 return JB_ERR_MEMORY;
3831 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
3839 /*********************************************************************
3841 * Function : create_forged_referrer
3843 * Description : Helper for client_referrer to forge a referer as
3844 * 'http://[hostname:port/' to fool stupid
3845 * checks for in-site links
3848 * 1 : header = Pointer to header pointer
3849 * 2 : hostport = Host and optionally port as string
3851 * Returns : JB_ERR_OK in case of success, or
3852 * JB_ERR_MEMORY in case of memory problems.
3854 *********************************************************************/
3855 static jb_err create_forged_referrer(char **header, const char *hostport)
3857 assert(NULL == *header);
3859 *header = strdup("Referer: http://");
3860 string_append(header, hostport);
3861 string_append(header, "/");
3863 if (NULL == *header)
3865 return JB_ERR_MEMORY;
3868 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
3875 /*********************************************************************
3877 * Function : create_fake_referrer
3879 * Description : Helper for client_referrer to create a fake referrer
3880 * based on a string supplied by the user.
3883 * 1 : header = Pointer to header pointer
3884 * 2 : hosthost = Referrer to fake
3886 * Returns : JB_ERR_OK in case of success, or
3887 * JB_ERR_MEMORY in case of memory problems.
3889 *********************************************************************/
3890 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
3892 assert(NULL == *header);
3894 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
3896 log_error(LOG_LEVEL_HEADER,
3897 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
3899 *header = strdup("Referer: ");
3900 string_append(header, fake_referrer);
3902 if (NULL == *header)
3904 return JB_ERR_MEMORY;
3907 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
3914 /*********************************************************************
3916 * Function : handle_conditional_hide_referrer_parameter
3918 * Description : Helper for client_referrer to crunch or forge
3919 * the referrer header if the host has changed.
3922 * 1 : header = Pointer to header pointer
3923 * 2 : host = The target host (may include the port)
3924 * 3 : parameter_conditional_block = Boolean to signal
3925 * if we're in conditional-block mode. If not set,
3926 * we're in conditional-forge mode.
3928 * Returns : JB_ERR_OK in case of success, or
3929 * JB_ERR_MEMORY in case of memory problems.
3931 *********************************************************************/
3932 static jb_err handle_conditional_hide_referrer_parameter(char **header,
3933 const char *host, const int parameter_conditional_block)
3935 char *referer = strdup(*header);
3936 const size_t hostlenght = strlen(host);
3937 const char *referer_url = NULL;
3939 if (NULL == referer)
3942 return JB_ERR_MEMORY;
3945 /* referer begins with 'Referer: http[s]://' */
3946 if ((hostlenght+17) < strlen(referer))
3949 * Shorten referer to make sure the referer is blocked
3950 * if www.example.org/www.example.com-shall-see-the-referer/
3951 * links to www.example.com/
3953 referer[hostlenght+17] = '\0';
3955 referer_url = strstr(referer, "http://");
3956 if ((NULL == referer_url) || (NULL == strstr(referer_url, host)))
3958 /* Host has changed, Referer is invalid or a https URL. */
3959 if (parameter_conditional_block)
3961 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
3968 return create_forged_referrer(header, host);
3978 /*********************************************************************
3980 * Function : get_appropiate_connection_header
3982 * Description : Returns an appropiate Connection header
3983 * depending on whether or not we try to keep
3984 * the connection to the server alive.
3987 * 1 : csp = Current client state (buffers, headers, etc...)
3989 * Returns : Pointer to statically allocated header buffer.
3991 *********************************************************************/
3992 static const char *get_appropiate_connection_header(const struct client_state *csp)
3994 static const char connection_keep_alive[] = "Connection: keep-alive";
3995 static const char connection_close[] = "Connection: close";
3997 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3998 && (csp->http->ssl == 0))
4000 return connection_keep_alive;
4002 return connection_close;