1 const char parsers_rcs[] = "$Id: parsers.c,v 1.52 2002/03/24 13:25:43 swa 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',
14 * and `server_set_cookie'.
16 * Copyright : Written by and Copyright (C) 2001 the SourceForge
17 * Privoxy team. http://www.privoxy.org/
19 * Based on the Internet Junkbuster originally written
20 * by and Copyright (C) 1997 Anonymous Coders and
21 * Junkbusters Corporation. http://www.junkbusters.com
23 * This program is free software; you can redistribute it
24 * and/or modify it under the terms of the GNU General
25 * Public License as published by the Free Software
26 * Foundation; either version 2 of the License, or (at
27 * your option) any later version.
29 * This program is distributed in the hope that it will
30 * be useful, but WITHOUT ANY WARRANTY; without even the
31 * implied warranty of MERCHANTABILITY or FITNESS FOR A
32 * PARTICULAR PURPOSE. See the GNU General Public
33 * License for more details.
35 * The GNU General Public License should be included with
36 * this file. If not, you can view it at
37 * http://www.gnu.org/copyleft/gpl.html
38 * or write to the Free Software Foundation, Inc., 59
39 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
43 * Revision 1.52 2002/03/24 13:25:43 swa
44 * name change related issues
46 * Revision 1.51 2002/03/13 00:27:05 jongfoster
49 * Revision 1.50 2002/03/12 01:45:35 oes
50 * More verbose logging
52 * Revision 1.49 2002/03/09 20:03:52 jongfoster
53 * - Making various functions return int rather than size_t.
54 * (Undoing a recent change). Since size_t is unsigned on
55 * Windows, functions like read_socket that return -1 on
56 * error cannot return a size_t.
58 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
59 * crashes, and also frequently caused JB to jump to 100%
60 * CPU and stay there. (Because it thought it had just
61 * read ((unsigned)-1) == 4Gb of data...)
63 * - The signature of write_socket has changed, it now simply
64 * returns success=0/failure=nonzero.
66 * - Trying to get rid of a few warnings --with-debug on
67 * Windows, I've introduced a new type "jb_socket". This is
68 * used for the socket file descriptors. On Windows, this
69 * is SOCKET (a typedef for unsigned). Everywhere else, it's
70 * an int. The error value can't be -1 any more, so it's
71 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
72 * Windows it maps to the #define INVALID_SOCKET.)
74 * - The signature of bind_port has changed.
76 * Revision 1.48 2002/03/07 03:46:53 oes
77 * Fixed compiler warnings etc
79 * Revision 1.47 2002/02/20 23:15:13 jongfoster
80 * Parsing functions now handle out-of-memory gracefully by returning
83 * Revision 1.46 2002/01/17 21:03:47 jongfoster
84 * Moving all our URL and URL pattern parsing code to urlmatch.c.
86 * Revision 1.45 2002/01/09 14:33:03 oes
87 * Added support for localtime_r.
89 * Revision 1.44 2001/12/14 01:22:54 steudten
90 * Remove 'user:pass@' from 'proto://user:pass@host' for the
91 * new added header 'Host: ..'. (See Req ID 491818)
93 * Revision 1.43 2001/11/23 00:26:38 jongfoster
94 * Fixing two really stupid errors in my previous commit
96 * Revision 1.42 2001/11/22 21:59:30 jongfoster
97 * Adding code to handle +no-cookies-keep
99 * Revision 1.41 2001/11/05 23:43:05 steudten
100 * Add time+date to log files.
102 * Revision 1.40 2001/10/26 20:13:09 jongfoster
103 * ctype.h is needed in Windows, too.
105 * Revision 1.39 2001/10/26 17:40:04 oes
106 * Introduced get_header_value()
107 * Removed http->user_agent, csp->referrer and csp->accept_types
108 * Removed client_accept()
110 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
111 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
112 * threads to call select() simultaneously. So, it's time to do a real, live,
113 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
114 * (native). Both versions will work, but using __OS2__ offers multi-threading.
116 * Revision 1.37 2001/10/23 21:36:02 jongfoster
117 * Documenting sed()'s error behaviou (doc change only)
119 * Revision 1.36 2001/10/13 12:51:51 joergs
120 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
121 * force-load), instead crumble Host: and add it (again) in client_host_adder
122 * (in case we get a HTTP/1.0 request without Host: header and forward it to
123 * a HTTP/1.1 server/proxy).
125 * Revision 1.35 2001/10/09 22:39:21 jongfoster
126 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
129 * Revision 1.34 2001/10/07 18:50:55 oes
130 * Added server_content_encoding, renamed server_transfer_encoding
132 * Revision 1.33 2001/10/07 18:04:49 oes
133 * Changed server_http11 to server_http and its pattern to "HTTP".
134 * Additional functionality: it now saves the HTTP status into
135 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
137 * Revision 1.32 2001/10/07 15:43:28 oes
138 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
139 * client_te and client_accept_encoding_adder, triggered by the new
140 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
141 * changed to allow only identity and chunked, and the TE header is
142 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
144 * parse_http_request no longer does anything than parsing. The rewriting
145 * of http->cmd and version mangling are gone. It now also recognizes
146 * the put and delete methods and saves the url in http->url. Removed
149 * renamed content_type and content_length to have the server_ prefix
151 * server_content_type now only works if csp->content_type != CT_TABOO
153 * added server_transfer_encoding, which
154 * - Sets CT_TABOO to prohibit filtering if encoding compresses
155 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
156 * - Change from "chunked" to "identity" if body was chunked
157 * but has been de-chunked for filtering.
159 * added server_content_md5 which crunches any Content-MD5 headers
160 * if the body was modified.
162 * made server_http11 conditional on +downgrade action
164 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
166 * Revision 1.31 2001/10/05 14:25:02 oes
167 * Crumble Keep-Alive from Server
169 * Revision 1.30 2001/09/29 12:56:03 joergs
170 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
172 * Revision 1.29 2001/09/24 21:09:24 jongfoster
173 * Fixing 2 memory leaks that Guy spotted, where the paramater to
174 * enlist() was not being free()d.
176 * Revision 1.28 2001/09/22 16:32:28 jongfoster
177 * Removing unused #includes.
179 * Revision 1.27 2001/09/20 15:45:25 steudten
181 * add casting from size_t to int for printf()
182 * remove local variable shadow s2
184 * Revision 1.26 2001/09/16 17:05:14 jongfoster
185 * Removing unused #include showarg.h
187 * Revision 1.25 2001/09/16 13:21:27 jongfoster
188 * Changes to use new list functions.
190 * Revision 1.24 2001/09/13 23:05:50 jongfoster
191 * Changing the string paramater to the header parsers a "const".
193 * Revision 1.23 2001/09/12 18:08:19 steudten
195 * In parse_http_request() header rewriting miss the host value, so
196 * from http://www.mydomain.com the result was just " / " not
197 * http://www.mydomain.com/ in case we forward.
199 * Revision 1.22 2001/09/10 10:58:53 oes
200 * Silenced compiler warnings
202 * Revision 1.21 2001/07/31 14:46:00 oes
203 * - Persistant connections now suppressed
204 * - sed() no longer appends empty header to csp->headers
206 * Revision 1.20 2001/07/30 22:08:36 jongfoster
207 * Tidying up #defines:
208 * - All feature #defines are now of the form FEATURE_xxx
209 * - Permanently turned off WIN_GUI_EDIT
210 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
212 * Revision 1.19 2001/07/25 17:21:54 oes
213 * client_uagent now saves copy of User-Agent: header value
215 * Revision 1.18 2001/07/13 14:02:46 oes
216 * - Included fix to repair broken HTTP requests that
217 * don't contain a path, not even '/'.
218 * - Removed all #ifdef PCRS
219 * - content_type now always inspected and classified as
220 * text, gif or other.
221 * - formatting / comments
223 * Revision 1.17 2001/06/29 21:45:41 oes
224 * Indentation, CRLF->LF, Tab-> Space
226 * Revision 1.16 2001/06/29 13:32:42 oes
228 * - Adapted free_http_request
229 * - Removed logentry from cancelled commit
231 * Revision 1.15 2001/06/03 19:12:38 oes
232 * deleted const struct interceptors
234 * Revision 1.14 2001/06/01 18:49:17 jongfoster
235 * Replaced "list_share" with "list" - the tiny memory gain was not
236 * worth the extra complexity.
238 * Revision 1.13 2001/05/31 21:30:33 jongfoster
239 * Removed list code - it's now in list.[ch]
240 * Renamed "permission" to "action", and changed many features
241 * to use the actions file rather than the global config.
243 * Revision 1.12 2001/05/31 17:33:13 oes
247 * Revision 1.11 2001/05/29 20:11:19 joergs
248 * '/ * inside comment' warning removed.
250 * Revision 1.10 2001/05/29 09:50:24 jongfoster
251 * Unified blocklist/imagelist/permissionslist.
252 * File format is still under discussion, but the internal changes
255 * Also modified interceptor behaviour:
256 * - We now intercept all URLs beginning with one of the following
257 * prefixes (and *only* these prefixes):
259 * * http://ijbswa.sf.net/config/
260 * * http://ijbswa.sourceforge.net/config/
261 * - New interceptors "home page" - go to http://i.j.b/ to see it.
262 * - Internal changes so that intercepted and fast redirect pages
263 * are not replaced with an image.
264 * - Interceptors now have the option to send a binary page direct
265 * to the client. (i.e. ijb-send-banner uses this)
266 * - Implemented show-url-info interceptor. (Which is why I needed
267 * the above interceptors changes - a typical URL is
268 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
269 * The previous mechanism would not have intercepted that, and
270 * if it had been intercepted then it then it would have replaced
273 * Revision 1.9 2001/05/28 17:26:33 jongfoster
274 * Fixing segfault if last header was crunched.
275 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
276 * can use the cross-platform sprintf() instead.)
278 * Revision 1.8 2001/05/27 22:17:04 oes
280 * - re_process_buffer no longer writes the modified buffer
281 * to the client, which was very ugly. It now returns the
282 * buffer, which it is then written by chat.
284 * - content_length now adjusts the Content-Length: header
285 * for modified documents rather than crunch()ing it.
286 * (Length info in csp->content_length, which is 0 for
287 * unmodified documents)
289 * - For this to work, sed() is called twice when filtering.
291 * Revision 1.7 2001/05/27 13:19:06 oes
292 * Patched Joergs solution for the content-length in.
294 * Revision 1.6 2001/05/26 13:39:32 jongfoster
295 * Only crunches Content-Length header if applying RE filtering.
296 * Without this fix, Microsoft Windows Update wouldn't work.
298 * Revision 1.5 2001/05/26 00:28:36 jongfoster
299 * Automatic reloading of config file.
300 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
301 * Most of the global variables have been moved to a new
302 * struct configuration_spec, accessed through csp->config->globalname
303 * Most of the globals remaining are used by the Win32 GUI.
305 * Revision 1.4 2001/05/22 18:46:04 oes
307 * - Enabled filtering banners by size rather than URL
308 * by adding patterns that replace all standard banner
309 * sizes with the "Junkbuster" gif to the re_filterfile
311 * - Enabled filtering WebBugs by providing a pattern
312 * which kills all 1x1 images
314 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
315 * which is selected by the (nonstandard and therefore
316 * capital) letter 'U' in the option string.
317 * It causes the quantifiers to be ungreedy by default.
318 * Appending a ? turns back to greedy (!).
320 * - Added a new interceptor ijb-send-banner, which
321 * sends back the "Junkbuster" gif. Without imagelist or
322 * MSIE detection support, or if tinygif = 1, or the
323 * URL isn't recognized as an imageurl, a lame HTML
324 * explanation is sent instead.
326 * - Added new feature, which permits blocking remote
327 * script redirects and firing back a local redirect
329 * The feature is conditionally compiled, i.e. it
330 * can be disabled with --disable-fast-redirects,
331 * plus it must be activated by a "fast-redirects"
332 * line in the config file, has its own log level
333 * and of course wants to be displayed by show-proxy-args
334 * Note: Boy, all the #ifdefs in 1001 locations and
335 * all the fumbling with configure.in and acconfig.h
336 * were *way* more work than the feature itself :-(
338 * - Because a generic redirect template was needed for
339 * this, tinygif = 3 now uses the same.
341 * - Moved GIFs, and other static HTTP response templates
346 * - Removed some >400 CRs again (Jon, you really worked
349 * Revision 1.3 2001/05/20 01:21:20 jongfoster
350 * Version 2.9.4 checkin.
351 * - Merged popupfile and cookiefile, and added control over PCRS
352 * filtering, in new "permissionsfile".
353 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
354 * file error you now get a message box (in the Win32 GUI) rather
355 * than the program exiting with no explanation.
356 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
358 * - Removed tabs from "config"
359 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
360 * - Bumped up version number.
362 * Revision 1.2 2001/05/17 23:02:36 oes
363 * - Made referrer option accept 'L' as a substitute for '§'
365 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
366 * Initial import of version 2.9.3 source tree
369 *********************************************************************/
376 #include <sys/types.h>
384 #if !defined(_WIN32) && !defined(__OS2__)
394 #include "jbsockets.h"
395 #include "miscutil.h"
398 const char parsers_h_rcs[] = PARSERS_H_VERSION;
400 /* Fix a problem with Solaris. There should be no effect on other
402 * Solaris's isspace() is a macro which uses it's argument directly
403 * as an array index. Therefore we need to make sure that high-bit
404 * characters generate +ve values, and ideally we also want to make
405 * the argument match the declared parameter type of "int".
407 * Why did they write a character function that can't take a simple
408 * "char" argument? Doh!
410 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
411 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
414 const struct parsers client_patterns[] = {
415 { "referer:", 8, client_referrer },
416 { "user-agent:", 11, client_uagent },
417 { "ua-", 3, client_ua },
418 { "from:", 5, client_from },
419 { "cookie:", 7, client_send_cookie },
420 { "x-forwarded-for:", 16, client_x_forwarded },
421 { "Accept-Encoding:", 16, client_accept_encoding },
422 { "TE:", 3, client_te },
423 { "Host:", 5, crumble },
424 /* { "if-modified-since:", 18, crumble }, */
425 { "Keep-Alive:", 11, crumble },
426 { "connection:", 11, crumble },
427 { "proxy-connection:", 17, crumble },
432 const struct parsers server_patterns[] = {
433 { "HTTP", 4, server_http },
434 { "set-cookie:", 11, server_set_cookie },
435 { "connection:", 11, crumble },
436 { "Content-Type:", 13, server_content_type },
437 { "Content-Length:", 15, server_content_length },
438 { "Content-MD5:", 12, server_content_md5 },
439 { "Content-Encoding:", 17, server_content_encoding },
440 { "Transfer-Encoding:", 18, server_transfer_coding },
441 { "Keep-Alive:", 11, crumble },
446 const add_header_func_ptr add_client_headers[] = {
449 client_x_forwarded_adder,
451 client_accept_encoding_adder,
452 connection_close_adder,
457 const add_header_func_ptr add_server_headers[] = {
458 connection_close_adder,
463 /*********************************************************************
465 * Function : flush_socket
467 * Description : Write any pending "buffered" content.
470 * 1 : fd = file descriptor of the socket to read
471 * 2 : csp = Current client state (buffers, headers, etc...)
473 * Returns : On success, the number of bytes written are returned (zero
474 * indicates nothing was written). On error, -1 is returned,
475 * and errno is set appropriately. If count is zero and the
476 * file descriptor refers to a regular file, 0 will be
477 * returned without causing any other effect. For a special
478 * file, the results are not portable.
480 *********************************************************************/
481 int flush_socket(jb_socket fd, struct client_state *csp)
483 struct iob *iob = csp->iob;
484 int len = iob->eod - iob->cur;
491 if (write_socket(fd, iob->cur, (size_t)len))
495 iob->eod = iob->cur = iob->buf;
501 /*********************************************************************
503 * Function : add_to_iob
505 * Description : Add content to the buffered page.
508 * 1 : csp = Current client state (buffers, headers, etc...)
509 * 2 : buf = holds the content to be added to the page
510 * 3 : n = number of bytes to be added
514 *********************************************************************/
515 void add_to_iob(struct client_state *csp, char *buf, int n)
517 struct iob *iob = csp->iob;
521 have = iob->eod - iob->cur;
530 if ((p = (char *)malloc(need + 1)) == NULL)
532 log_error(LOG_LEVEL_FATAL, "malloc() iob failed: %E");
537 /* there is something in the buffer - save it */
538 memcpy(p, iob->cur, have);
540 /* replace the buffer with the new space */
544 /* point to the end of the data */
549 /* the buffer is empty, free it and reinitialize */
554 /* copy the new data into the iob buffer */
555 memcpy(p, buf, (size_t)n);
557 /* point to the end of the data */
560 /* null terminate == cheap insurance */
563 /* set the pointers to the new values */
572 /*********************************************************************
574 * Function : get_header
576 * Description : This (odd) routine will parse the csp->iob
579 * 1 : csp = Current client state (buffers, headers, etc...)
581 * Returns : Any one of the following:
583 * 1) a pointer to a dynamically allocated string that contains a header line
584 * 2) NULL indicating that the end of the header was reached
585 * 3) "" indicating that the end of the iob was reached before finding
586 * a complete header line.
588 *********************************************************************/
589 char *get_header(struct client_state *csp)
595 if ((iob->cur == NULL)
596 || ((p = strchr(iob->cur, '\n')) == NULL))
598 return(""); /* couldn't find a complete header */
603 ret = strdup(iob->cur);
606 /* FIXME No way to handle error properly */
607 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
612 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
614 /* is this a blank linke (i.e. the end of the header) ? */
626 /*********************************************************************
628 * Function : get_header_value
630 * Description : Get the value of a given header from a chained list
631 * of header lines or return NULL if no such header is
632 * present in the list.
635 * 1 : header_list = pointer to list
636 * 2 : header_name = string with name of header to look for.
637 * Trailing colon required, capitalization
640 * Returns : NULL if not found, else value of header
642 *********************************************************************/
643 char *get_header_value(const struct list *header_list, const char *header_name)
645 struct list_entry *cur_entry;
651 length = strlen(header_name);
653 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
657 if (!strncmpic(cur_entry->str, header_name, length))
660 * Found: return pointer to start of value
662 ret = (char *) (cur_entry->str + length);
663 while (*ret && ijb_isspace(*ret)) ret++;
676 /*********************************************************************
680 * Description : add, delete or modify lines in the HTTP header streams.
681 * On entry, it receives a linked list of headers space
682 * that was allocated dynamically (both the list nodes
683 * and the header contents).
685 * As a side effect it frees the space used by the original
689 * 1 : pats = list of patterns to match against headers
690 * 2 : more_headers = list of functions to add more
691 * headers (client or server)
692 * 3 : csp = Current client state (buffers, headers, etc...)
694 * Returns : Single pointer to a fully formed header, or NULL
695 * on out-of-memory error.
697 *********************************************************************/
698 char *sed(const struct parsers pats[],
699 const add_header_func_ptr more_headers[],
700 struct client_state *csp)
702 struct list_entry *p;
703 const struct parsers *v;
704 const add_header_func_ptr *f;
705 jb_err err = JB_ERR_OK;
707 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
709 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
711 /* Header crunch()ed in previous run? -> ignore */
712 if (p->str == NULL) continue;
714 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
716 if (strncmpic(p->str, v->str, v->len) == 0)
718 err = v->parser(csp, (char **)&(p->str));
723 /* place any additional headers on the csp->headers list */
724 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
729 if (err != JB_ERR_OK)
734 return list_to_text(csp->headers);
738 /* here begins the family of parser functions that reformat header lines */
741 /*********************************************************************
745 * Description : This is called if a header matches a pattern to "crunch"
748 * 1 : csp = Current client state (buffers, headers, etc...)
749 * 2 : header = On input, pointer to header to modify.
750 * On output, pointer to the modified header, or NULL
751 * to remove the header. This function frees the
752 * original string if necessary.
754 * Returns : JB_ERR_OK on success, or
755 * JB_ERR_MEMORY on out-of-memory error.
757 *********************************************************************/
758 jb_err crumble(struct client_state *csp, char **header)
760 log_error(LOG_LEVEL_HEADER, "crunch!");
766 /*********************************************************************
768 * Function : server_content_type
770 * Description : Set the content-type for filterable types (text/.*,
771 * javascript and image/gif) unless filtering has been
772 * forbidden (CT_TABOO) while parsing earlier headers.
775 * 1 : csp = Current client state (buffers, headers, etc...)
776 * 2 : header = On input, pointer to header to modify.
777 * On output, pointer to the modified header, or NULL
778 * to remove the header. This function frees the
779 * original string if necessary.
781 * Returns : JB_ERR_OK on success, or
782 * JB_ERR_MEMORY on out-of-memory error.
784 *********************************************************************/
785 jb_err server_content_type(struct client_state *csp, char **header)
787 if (csp->content_type != CT_TABOO)
789 if (strstr(*header, " text/")
790 || strstr(*header, "application/x-javascript"))
791 csp->content_type = CT_TEXT;
792 else if (strstr(*header, " image/gif"))
793 csp->content_type = CT_GIF;
795 csp->content_type = 0;
802 /*********************************************************************
804 * Function : server_transfer_coding
806 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
807 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
808 * - Change from "chunked" to "identity" if body was chunked
809 * but has been de-chunked for filtering.
812 * 1 : csp = Current client state (buffers, headers, etc...)
813 * 2 : header = On input, pointer to header to modify.
814 * On output, pointer to the modified header, or NULL
815 * to remove the header. This function frees the
816 * original string if necessary.
818 * Returns : JB_ERR_OK on success, or
819 * JB_ERR_MEMORY on out-of-memory error.
821 *********************************************************************/
822 jb_err server_transfer_coding(struct client_state *csp, char **header)
825 * Turn off pcrs and gif filtering if body compressed
827 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
829 csp->content_type = CT_TABOO;
833 * Raise flag if body chunked
835 if (strstr(*header, "chunked"))
837 csp->flags |= CSP_FLAG_CHUNKED;
840 * If the body was modified, it has been
841 * de-chunked first, so adjust the header:
843 if (csp->flags & CSP_FLAG_MODIFIED)
846 *header = strdup("Transfer-Encoding: identity");
847 return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
855 /*********************************************************************
857 * Function : server_content_encoding
859 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
862 * 1 : csp = Current client state (buffers, headers, etc...)
863 * 2 : header = On input, pointer to header to modify.
864 * On output, pointer to the modified header, or NULL
865 * to remove the header. This function frees the
866 * original string if necessary.
868 * Returns : JB_ERR_OK on success, or
869 * JB_ERR_MEMORY on out-of-memory error.
871 *********************************************************************/
872 jb_err server_content_encoding(struct client_state *csp, char **header)
875 * Turn off pcrs and gif filtering if body compressed
877 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
879 csp->content_type = CT_TABOO;
887 /*********************************************************************
889 * Function : server_content_length
891 * Description : Adjust Content-Length header if we modified
895 * 1 : csp = Current client state (buffers, headers, etc...)
896 * 2 : header = On input, pointer to header to modify.
897 * On output, pointer to the modified header, or NULL
898 * to remove the header. This function frees the
899 * original string if necessary.
901 * Returns : JB_ERR_OK on success, or
902 * JB_ERR_MEMORY on out-of-memory error.
904 *********************************************************************/
905 jb_err server_content_length(struct client_state *csp, char **header)
907 if (csp->content_length != 0) /* Content length has been modified */
910 *header = (char *) zalloc(100);
913 return JB_ERR_MEMORY;
916 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
918 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
925 /*********************************************************************
927 * Function : server_content_md5
929 * Description : Crumble any Content-MD5 headers if the document was
930 * modified. FIXME: Should we re-compute instead?
933 * 1 : csp = Current client state (buffers, headers, etc...)
934 * 2 : header = On input, pointer to header to modify.
935 * On output, pointer to the modified header, or NULL
936 * to remove the header. This function frees the
937 * original string if necessary.
939 * Returns : JB_ERR_OK on success, or
940 * JB_ERR_MEMORY on out-of-memory error.
942 *********************************************************************/
943 jb_err server_content_md5(struct client_state *csp, char **header)
945 if (csp->flags & CSP_FLAG_MODIFIED)
947 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
955 /*********************************************************************
957 * Function : client_accept_encoding
959 * Description : Rewrite the client's Accept-Encoding header so that
960 * if doesn't allow compression, if the action applies.
961 * Note: For HTTP/1.0 the absence of the header is enough.
964 * 1 : csp = Current client state (buffers, headers, etc...)
965 * 2 : header = On input, pointer to header to modify.
966 * On output, pointer to the modified header, or NULL
967 * to remove the header. This function frees the
968 * original string if necessary.
970 * Returns : JB_ERR_OK on success, or
971 * JB_ERR_MEMORY on out-of-memory error.
973 *********************************************************************/
974 jb_err client_accept_encoding(struct client_state *csp, char **header)
976 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
978 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress content");
981 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
983 *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
986 return JB_ERR_MEMORY;
995 /*********************************************************************
997 * Function : client_te
999 * Description : Rewrite the client's TE header so that
1000 * if doesn't allow compression, if the action applies.
1003 * 1 : csp = Current client state (buffers, headers, etc...)
1004 * 2 : header = On input, pointer to header to modify.
1005 * On output, pointer to the modified header, or NULL
1006 * to remove the header. This function frees the
1007 * original string if necessary.
1009 * Returns : JB_ERR_OK on success, or
1010 * JB_ERR_MEMORY on out-of-memory error.
1012 *********************************************************************/
1013 jb_err client_te(struct client_state *csp, char **header)
1015 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1018 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress transfer");
1024 /*********************************************************************
1026 * Function : client_referrer
1028 * Description : Handle the "referer" config setting properly.
1029 * Called from `sed'.
1032 * 1 : csp = Current client state (buffers, headers, etc...)
1033 * 2 : header = On input, pointer to header to modify.
1034 * On output, pointer to the modified header, or NULL
1035 * to remove the header. This function frees the
1036 * original string if necessary.
1038 * Returns : JB_ERR_OK on success, or
1039 * JB_ERR_MEMORY on out-of-memory error.
1041 *********************************************************************/
1042 jb_err client_referrer(struct client_state *csp, char **header)
1044 const char * newval;
1046 #ifdef FEATURE_FORCE_LOAD
1047 /* Since the referrer can include the prefix even
1048 * even if the request itself is non-forced, we must
1049 * clean it unconditionally
1051 strclean(*header, FORCE_PREFIX);
1052 #endif /* def FEATURE_FORCE_LOAD */
1055 * Are we sending referer?
1057 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1064 newval = csp->action->string[ACTION_STRING_REFERER];
1066 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1071 log_error(LOG_LEVEL_HEADER, "crunch!");
1074 else if (0 == strncmpic(newval, "http://", 7))
1077 * We have a specific (fixed) referer we want to send.
1079 log_error(LOG_LEVEL_HEADER, "modified");
1081 *header = strdup("Referer: ");
1082 string_append(header, newval);
1084 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1089 * Forge a referer as http://[hostname:port of REQUEST]/
1090 * to fool stupid checks for in-site links
1092 if (0 != strcmpic(newval, "forge"))
1095 * Invalid choice - but forge is probably the best default.
1097 log_error(LOG_LEVEL_ERROR, "Bad parameter: +referer{%s}", newval);
1100 *header = strdup("Referer: http://");
1101 string_append(header, csp->http->hostport);
1102 string_append(header, "/");
1103 log_error(LOG_LEVEL_HEADER, "crunch+forge to %s", *header);
1105 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1110 /*********************************************************************
1112 * Function : client_uagent
1114 * Description : Handle the "user-agent" config setting properly
1115 * and remember its original value to enable browser
1116 * bug workarounds. Called from `sed'.
1119 * 1 : csp = Current client state (buffers, headers, etc...)
1120 * 2 : header = On input, pointer to header to modify.
1121 * On output, pointer to the modified header, or NULL
1122 * to remove the header. This function frees the
1123 * original string if necessary.
1125 * Returns : JB_ERR_OK on success, or
1126 * JB_ERR_MEMORY on out-of-memory error.
1128 *********************************************************************/
1129 jb_err client_uagent(struct client_state *csp, char **header)
1131 const char * newval;
1133 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1138 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1144 log_error(LOG_LEVEL_HEADER, "modified");
1147 *header = strdup("User-Agent: ");
1148 string_append(header, newval);
1150 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1154 /*********************************************************************
1156 * Function : client_ua
1158 * Description : Handle "ua-" headers properly. Called from `sed'.
1161 * 1 : csp = Current client state (buffers, headers, etc...)
1162 * 2 : header = On input, pointer to header to modify.
1163 * On output, pointer to the modified header, or NULL
1164 * to remove the header. This function frees the
1165 * original string if necessary.
1167 * Returns : JB_ERR_OK on success, or
1168 * JB_ERR_MEMORY on out-of-memory error.
1170 *********************************************************************/
1171 jb_err client_ua(struct client_state *csp, char **header)
1173 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1175 log_error(LOG_LEVEL_HEADER, "crunch!");
1183 /*********************************************************************
1185 * Function : client_from
1187 * Description : Handle the "from" config setting properly.
1188 * Called from `sed'.
1191 * 1 : csp = Current client state (buffers, headers, etc...)
1192 * 2 : header = On input, pointer to header to modify.
1193 * On output, pointer to the modified header, or NULL
1194 * to remove the header. This function frees the
1195 * original string if necessary.
1197 * Returns : JB_ERR_OK on success, or
1198 * JB_ERR_MEMORY on out-of-memory error.
1200 *********************************************************************/
1201 jb_err client_from(struct client_state *csp, char **header)
1203 const char * newval;
1205 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1212 newval = csp->action->string[ACTION_STRING_FROM];
1215 * Are we blocking the e-mail address?
1217 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1219 log_error(LOG_LEVEL_HEADER, "crunch!");
1223 log_error(LOG_LEVEL_HEADER, " modified");
1225 *header = strdup("From: ");
1226 string_append(header, newval);
1228 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1232 /*********************************************************************
1234 * Function : client_send_cookie
1236 * Description : Handle the "cookie" header properly. Called from `sed'.
1237 * If cookie is accepted, add it to the cookie_list,
1238 * else we crunch it. Mmmmmmmmmmm ... cookie ......
1241 * 1 : csp = Current client state (buffers, headers, etc...)
1242 * 2 : header = On input, pointer to header to modify.
1243 * On output, pointer to the modified header, or NULL
1244 * to remove the header. This function frees the
1245 * original string if necessary.
1247 * Returns : JB_ERR_OK on success, or
1248 * JB_ERR_MEMORY on out-of-memory error.
1250 *********************************************************************/
1251 jb_err client_send_cookie(struct client_state *csp, char **header)
1253 jb_err result = JB_ERR_OK;
1255 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
1257 /* strlen("cookie: ") == 8 */
1258 result = enlist(csp->cookie_list, *header + 8);
1262 log_error(LOG_LEVEL_HEADER, " crunch!");
1266 * Always remove the cookie here. The cookie header
1267 * will be sent at the end of the header.
1275 /*********************************************************************
1277 * Function : client_x_forwarded
1279 * Description : Handle the "x-forwarded-for" config setting properly,
1280 * also used in the add_client_headers list. Called from `sed'.
1283 * 1 : csp = Current client state (buffers, headers, etc...)
1284 * 2 : header = On input, pointer to header to modify.
1285 * On output, pointer to the modified header, or NULL
1286 * to remove the header. This function frees the
1287 * original string if necessary.
1289 * Returns : JB_ERR_OK on success, or
1290 * JB_ERR_MEMORY on out-of-memory error.
1292 *********************************************************************/
1293 jb_err client_x_forwarded(struct client_state *csp, char **header)
1295 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
1297 /* Save it so we can re-add it later */
1298 freez(csp->x_forwarded);
1299 csp->x_forwarded = *header;
1302 * Always set *header = NULL, since this information
1303 * will be sent at the end of the header.
1310 log_error(LOG_LEVEL_HEADER, " crunch!");
1316 /* the following functions add headers directly to the header list */
1318 /*********************************************************************
1320 * Function : client_host_adder
1322 * Description : (re)adds the host header. Called from `sed'.
1325 * 1 : csp = Current client state (buffers, headers, etc...)
1327 * Returns : JB_ERR_OK on success, or
1328 * JB_ERR_MEMORY on out-of-memory error.
1330 *********************************************************************/
1331 jb_err client_host_adder(struct client_state *csp)
1337 if ( !csp->http->hostport || !*(csp->http->hostport))
1342 p = strdup("Host: ");
1344 ** remove 'user:pass@' from 'proto://user:pass@host'
1346 if ( (pos = strchr( csp->http->hostport, '@')) != NULL )
1348 string_append(&p, pos+1);
1352 string_append(&p, csp->http->hostport);
1357 return JB_ERR_MEMORY;
1360 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1362 err = enlist(csp->headers, p);
1370 /*********************************************************************
1372 * Function : client_cookie_adder
1374 * Description : Used in the add_client_headers list. Called from `sed'.
1377 * 1 : csp = Current client state (buffers, headers, etc...)
1379 * Returns : JB_ERR_OK on success, or
1380 * JB_ERR_MEMORY on out-of-memory error.
1382 *********************************************************************/
1383 jb_err client_cookie_adder(struct client_state *csp)
1385 struct list_entry *lst;
1387 struct list_entry *list1 = csp->cookie_list->first;
1388 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
1389 int first_cookie = 1;
1392 if ((list1 == NULL) && (list2 == NULL))
1398 tmp = strdup("Cookie: ");
1400 for (lst = list1; lst ; lst = lst->next)
1408 string_append(&tmp, "; ");
1410 string_append(&tmp, lst->str);
1413 for (lst = list2; lst ; lst = lst->next)
1421 string_append(&tmp, "; ");
1423 string_join(&tmp, cookie_encode(lst->str));
1428 return JB_ERR_MEMORY;
1431 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
1432 err = enlist(csp->headers, tmp);
1438 /*********************************************************************
1440 * Function : client_accept_encoding_adder
1442 * Description : Add an Accept-Encoding header to the client's request
1443 * that disables compression if the action applies, and
1444 * the header is not already there. Called from `sed'.
1445 * Note: For HTTP/1.0, the absence of the header is enough.
1448 * 1 : csp = Current client state (buffers, headers, etc...)
1450 * Returns : JB_ERR_OK on success, or
1451 * JB_ERR_MEMORY on out-of-memory error.
1453 *********************************************************************/
1454 jb_err client_accept_encoding_adder(struct client_state *csp)
1456 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1457 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
1459 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
1466 /*********************************************************************
1468 * Function : client_xtra_adder
1470 * Description : Used in the add_client_headers list. Called from `sed'.
1473 * 1 : csp = Current client state (buffers, headers, etc...)
1475 * Returns : JB_ERR_OK on success, or
1476 * JB_ERR_MEMORY on out-of-memory error.
1478 *********************************************************************/
1479 jb_err client_xtra_adder(struct client_state *csp)
1481 struct list_entry *lst;
1484 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
1485 lst ; lst = lst->next)
1487 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
1488 err = enlist(csp->headers, lst->str);
1500 /*********************************************************************
1502 * Function : client_x_forwarded_adder
1504 * Description : Used in the add_client_headers list. Called from `sed'.
1507 * 1 : csp = Current client state (buffers, headers, etc...)
1509 * Returns : JB_ERR_OK on success, or
1510 * JB_ERR_MEMORY on out-of-memory error.
1512 *********************************************************************/
1513 jb_err client_x_forwarded_adder(struct client_state *csp)
1518 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
1523 if (csp->x_forwarded)
1525 p = strdup(csp->x_forwarded);
1526 string_append(&p, ", ");
1530 p = strdup("X-Forwarded-For: ");
1532 string_append(&p, csp->ip_addr_str);
1536 return JB_ERR_MEMORY;
1539 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1540 err = enlist(csp->headers, p);
1547 /*********************************************************************
1549 * Function : connection_close_adder
1551 * Description : Adds a "Connection: close" header to csp->headers
1552 * as a temporary fix for the needed but missing HTTP/1.1
1553 * support. Called from `sed'.
1554 * FIXME: This whole function shouldn't be neccessary!
1557 * 1 : csp = Current client state (buffers, headers, etc...)
1559 * Returns : JB_ERR_OK on success, or
1560 * JB_ERR_MEMORY on out-of-memory error.
1562 *********************************************************************/
1563 jb_err connection_close_adder(struct client_state *csp)
1565 return enlist(csp->headers, "Connection: close");
1569 /*********************************************************************
1571 * Function : server_http
1573 * Description : - Save the HTTP Status into csp->http->status
1574 * - Set CT_TABOO to prevent filtering if the answer
1575 * is a partial range (HTTP status 206)
1576 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
1580 * 1 : csp = Current client state (buffers, headers, etc...)
1581 * 2 : header = On input, pointer to header to modify.
1582 * On output, pointer to the modified header, or NULL
1583 * to remove the header. This function frees the
1584 * original string if necessary.
1586 * Returns : JB_ERR_OK on success, or
1587 * JB_ERR_MEMORY on out-of-memory error.
1589 *********************************************************************/
1590 jb_err server_http(struct client_state *csp, char **header)
1592 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
1593 if (csp->http->status == 206)
1595 csp->content_type = CT_TABOO;
1598 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
1601 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
1608 /*********************************************************************
1610 * Function : server_set_cookie
1612 * Description : Handle the server "cookie" header properly.
1613 * Log cookie to the jar file. Then "crunch" it,
1614 * or accept it. Called from `sed'.
1617 * 1 : csp = Current client state (buffers, headers, etc...)
1618 * 2 : header = On input, pointer to header to modify.
1619 * On output, pointer to the modified header, or NULL
1620 * to remove the header. This function frees the
1621 * original string if necessary.
1623 * Returns : JB_ERR_OK on success, or
1624 * JB_ERR_MEMORY on out-of-memory error.
1626 *********************************************************************/
1627 jb_err server_set_cookie(struct client_state *csp, char **header)
1629 #ifdef FEATURE_COOKIE_JAR
1630 if (csp->config->jar)
1633 * Write timestamp into outbuf.
1635 * Complex because not all OSs have tm_gmtoff or
1636 * the %z field in strftime()
1638 char tempbuf[ BUFFER_SIZE ];
1642 #ifdef HAVE_LOCALTIME_R
1643 tm_now = *localtime_r(&now, &tm_now);
1645 tm_now = *localtime (&now);
1647 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
1649 /* strlen("set-cookie: ") = 12 */
1650 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
1652 #endif /* def FEATURE_COOKIE_JAR */
1654 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
1656 return crumble(csp, header);
1658 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
1660 /* Flag whether or not to log a message */
1663 /* A variable to store the tag we're working on */
1666 /* Skip "Set-Cookie:" (11 characters) in header */
1667 cur_tag = *header + 11;
1669 /* skip whitespace between "Set-Cookie:" and value */
1670 while (*cur_tag && ijb_isspace(*cur_tag))
1675 /* Loop through each tag in the cookie */
1679 char * next_tag = strchr(cur_tag, ';');
1680 if (next_tag != NULL)
1682 /* Skip the ';' character itself */
1685 /* skip whitespace ";" and start of tag */
1686 while (*next_tag && ijb_isspace(*next_tag))
1693 /* "Next tag" is the end of the string */
1694 next_tag = cur_tag + strlen(cur_tag);
1697 /* Is this the "Expires" tag? */
1698 if (strncmpic(cur_tag, "expires=", 8) == 0)
1700 /* Delete the tag by copying the rest of the string over it.
1701 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
1702 * since the behaviour of strcpy is undefined for overlapping
1705 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
1707 /* That changed the header, need to issue a log message */
1710 /* Note that the next tag has now been moved to *cur_tag,
1711 * so we do not need to update the cur_tag pointer.
1716 /* Move on to next cookie tag */
1723 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
1731 #ifdef FEATURE_FORCE_LOAD
1732 /*********************************************************************
1734 * Function : strclean
1736 * Description : In-Situ-Eliminate all occurances of substring in
1740 * 1 : string = string to clean
1741 * 2 : substring = substring to eliminate
1743 * Returns : Number of eliminations
1745 *********************************************************************/
1746 int strclean(const char *string, const char *substring)
1748 int hits = 0, len = strlen(substring);
1751 while((pos = strstr(string, substring)) != NULL)
1758 while (*p++ != '\0');
1765 #endif /* def FEATURE_FORCE_LOAD */