1 const char parsers_rcs[] = "$Id: parsers.c,v 1.40 2001/10/26 20:13:09 jongfoster 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', `free_http_request', `get_header',
14 * `list_to_text', `parse_http_request', `sed',
15 * and `server_set_cookie'.
17 * Copyright : Written by and Copyright (C) 2001 the SourceForge
18 * IJBSWA team. http://ijbswa.sourceforge.net
20 * Based on the Internet Junkbuster originally written
21 * by and Copyright (C) 1997 Anonymous Coders and
22 * Junkbusters Corporation. http://www.junkbusters.com
24 * This program is free software; you can redistribute it
25 * and/or modify it under the terms of the GNU General
26 * Public License as published by the Free Software
27 * Foundation; either version 2 of the License, or (at
28 * your option) any later version.
30 * This program is distributed in the hope that it will
31 * be useful, but WITHOUT ANY WARRANTY; without even the
32 * implied warranty of MERCHANTABILITY or FITNESS FOR A
33 * PARTICULAR PURPOSE. See the GNU General Public
34 * License for more details.
36 * The GNU General Public License should be included with
37 * this file. If not, you can view it at
38 * http://www.gnu.org/copyleft/gpl.html
39 * or write to the Free Software Foundation, Inc., 59
40 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
44 * Revision 1.40 2001/10/26 20:13:09 jongfoster
45 * ctype.h is needed in Windows, too.
47 * Revision 1.39 2001/10/26 17:40:04 oes
48 * Introduced get_header_value()
49 * Removed http->user_agent, csp->referrer and csp->accept_types
50 * Removed client_accept()
52 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
53 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
54 * threads to call select() simultaneously. So, it's time to do a real, live,
55 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
56 * (native). Both versions will work, but using __OS2__ offers multi-threading.
58 * Revision 1.37 2001/10/23 21:36:02 jongfoster
59 * Documenting sed()'s error behaviou (doc change only)
61 * Revision 1.36 2001/10/13 12:51:51 joergs
62 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
63 * force-load), instead crumble Host: and add it (again) in client_host_adder
64 * (in case we get a HTTP/1.0 request without Host: header and forward it to
65 * a HTTP/1.1 server/proxy).
67 * Revision 1.35 2001/10/09 22:39:21 jongfoster
68 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
71 * Revision 1.34 2001/10/07 18:50:55 oes
72 * Added server_content_encoding, renamed server_transfer_encoding
74 * Revision 1.33 2001/10/07 18:04:49 oes
75 * Changed server_http11 to server_http and its pattern to "HTTP".
76 * Additional functionality: it now saves the HTTP status into
77 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
79 * Revision 1.32 2001/10/07 15:43:28 oes
80 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
81 * client_te and client_accept_encoding_adder, triggered by the new
82 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
83 * changed to allow only identity and chunked, and the TE header is
84 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
86 * parse_http_request no longer does anything than parsing. The rewriting
87 * of http->cmd and version mangling are gone. It now also recognizes
88 * the put and delete methods and saves the url in http->url. Removed
91 * renamed content_type and content_length to have the server_ prefix
93 * server_content_type now only works if csp->content_type != CT_TABOO
95 * added server_transfer_encoding, which
96 * - Sets CT_TABOO to prohibit filtering if encoding compresses
97 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
98 * - Change from "chunked" to "identity" if body was chunked
99 * but has been de-chunked for filtering.
101 * added server_content_md5 which crunches any Content-MD5 headers
102 * if the body was modified.
104 * made server_http11 conditional on +downgrade action
106 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
108 * Revision 1.31 2001/10/05 14:25:02 oes
109 * Crumble Keep-Alive from Server
111 * Revision 1.30 2001/09/29 12:56:03 joergs
112 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
114 * Revision 1.29 2001/09/24 21:09:24 jongfoster
115 * Fixing 2 memory leaks that Guy spotted, where the paramater to
116 * enlist() was not being free()d.
118 * Revision 1.28 2001/09/22 16:32:28 jongfoster
119 * Removing unused #includes.
121 * Revision 1.27 2001/09/20 15:45:25 steudten
123 * add casting from size_t to int for printf()
124 * remove local variable shadow s2
126 * Revision 1.26 2001/09/16 17:05:14 jongfoster
127 * Removing unused #include showarg.h
129 * Revision 1.25 2001/09/16 13:21:27 jongfoster
130 * Changes to use new list functions.
132 * Revision 1.24 2001/09/13 23:05:50 jongfoster
133 * Changing the string paramater to the header parsers a "const".
135 * Revision 1.23 2001/09/12 18:08:19 steudten
137 * In parse_http_request() header rewriting miss the host value, so
138 * from http://www.mydomain.com the result was just " / " not
139 * http://www.mydomain.com/ in case we forward.
141 * Revision 1.22 2001/09/10 10:58:53 oes
142 * Silenced compiler warnings
144 * Revision 1.21 2001/07/31 14:46:00 oes
145 * - Persistant connections now suppressed
146 * - sed() no longer appends empty header to csp->headers
148 * Revision 1.20 2001/07/30 22:08:36 jongfoster
149 * Tidying up #defines:
150 * - All feature #defines are now of the form FEATURE_xxx
151 * - Permanently turned off WIN_GUI_EDIT
152 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
154 * Revision 1.19 2001/07/25 17:21:54 oes
155 * client_uagent now saves copy of User-Agent: header value
157 * Revision 1.18 2001/07/13 14:02:46 oes
158 * - Included fix to repair broken HTTP requests that
159 * don't contain a path, not even '/'.
160 * - Removed all #ifdef PCRS
161 * - content_type now always inspected and classified as
162 * text, gif or other.
163 * - formatting / comments
165 * Revision 1.17 2001/06/29 21:45:41 oes
166 * Indentation, CRLF->LF, Tab-> Space
168 * Revision 1.16 2001/06/29 13:32:42 oes
170 * - Adapted free_http_request
171 * - Removed logentry from cancelled commit
173 * Revision 1.15 2001/06/03 19:12:38 oes
174 * deleted const struct interceptors
176 * Revision 1.14 2001/06/01 18:49:17 jongfoster
177 * Replaced "list_share" with "list" - the tiny memory gain was not
178 * worth the extra complexity.
180 * Revision 1.13 2001/05/31 21:30:33 jongfoster
181 * Removed list code - it's now in list.[ch]
182 * Renamed "permission" to "action", and changed many features
183 * to use the actions file rather than the global config.
185 * Revision 1.12 2001/05/31 17:33:13 oes
189 * Revision 1.11 2001/05/29 20:11:19 joergs
190 * '/ * inside comment' warning removed.
192 * Revision 1.10 2001/05/29 09:50:24 jongfoster
193 * Unified blocklist/imagelist/permissionslist.
194 * File format is still under discussion, but the internal changes
197 * Also modified interceptor behaviour:
198 * - We now intercept all URLs beginning with one of the following
199 * prefixes (and *only* these prefixes):
201 * * http://ijbswa.sf.net/config/
202 * * http://ijbswa.sourceforge.net/config/
203 * - New interceptors "home page" - go to http://i.j.b/ to see it.
204 * - Internal changes so that intercepted and fast redirect pages
205 * are not replaced with an image.
206 * - Interceptors now have the option to send a binary page direct
207 * to the client. (i.e. ijb-send-banner uses this)
208 * - Implemented show-url-info interceptor. (Which is why I needed
209 * the above interceptors changes - a typical URL is
210 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
211 * The previous mechanism would not have intercepted that, and
212 * if it had been intercepted then it then it would have replaced
215 * Revision 1.9 2001/05/28 17:26:33 jongfoster
216 * Fixing segfault if last header was crunched.
217 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
218 * can use the cross-platform sprintf() instead.)
220 * Revision 1.8 2001/05/27 22:17:04 oes
222 * - re_process_buffer no longer writes the modified buffer
223 * to the client, which was very ugly. It now returns the
224 * buffer, which it is then written by chat.
226 * - content_length now adjusts the Content-Length: header
227 * for modified documents rather than crunch()ing it.
228 * (Length info in csp->content_length, which is 0 for
229 * unmodified documents)
231 * - For this to work, sed() is called twice when filtering.
233 * Revision 1.7 2001/05/27 13:19:06 oes
234 * Patched Joergs solution for the content-length in.
236 * Revision 1.6 2001/05/26 13:39:32 jongfoster
237 * Only crunches Content-Length header if applying RE filtering.
238 * Without this fix, Microsoft Windows Update wouldn't work.
240 * Revision 1.5 2001/05/26 00:28:36 jongfoster
241 * Automatic reloading of config file.
242 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
243 * Most of the global variables have been moved to a new
244 * struct configuration_spec, accessed through csp->config->globalname
245 * Most of the globals remaining are used by the Win32 GUI.
247 * Revision 1.4 2001/05/22 18:46:04 oes
249 * - Enabled filtering banners by size rather than URL
250 * by adding patterns that replace all standard banner
251 * sizes with the "Junkbuster" gif to the re_filterfile
253 * - Enabled filtering WebBugs by providing a pattern
254 * which kills all 1x1 images
256 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
257 * which is selected by the (nonstandard and therefore
258 * capital) letter 'U' in the option string.
259 * It causes the quantifiers to be ungreedy by default.
260 * Appending a ? turns back to greedy (!).
262 * - Added a new interceptor ijb-send-banner, which
263 * sends back the "Junkbuster" gif. Without imagelist or
264 * MSIE detection support, or if tinygif = 1, or the
265 * URL isn't recognized as an imageurl, a lame HTML
266 * explanation is sent instead.
268 * - Added new feature, which permits blocking remote
269 * script redirects and firing back a local redirect
271 * The feature is conditionally compiled, i.e. it
272 * can be disabled with --disable-fast-redirects,
273 * plus it must be activated by a "fast-redirects"
274 * line in the config file, has its own log level
275 * and of course wants to be displayed by show-proxy-args
276 * Note: Boy, all the #ifdefs in 1001 locations and
277 * all the fumbling with configure.in and acconfig.h
278 * were *way* more work than the feature itself :-(
280 * - Because a generic redirect template was needed for
281 * this, tinygif = 3 now uses the same.
283 * - Moved GIFs, and other static HTTP response templates
288 * - Removed some >400 CRs again (Jon, you really worked
291 * Revision 1.3 2001/05/20 01:21:20 jongfoster
292 * Version 2.9.4 checkin.
293 * - Merged popupfile and cookiefile, and added control over PCRS
294 * filtering, in new "permissionsfile".
295 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
296 * file error you now get a message box (in the Win32 GUI) rather
297 * than the program exiting with no explanation.
298 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
300 * - Removed tabs from "config"
301 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
302 * - Bumped up version number.
304 * Revision 1.2 2001/05/17 23:02:36 oes
305 * - Made referrer option accept 'L' as a substitute for '§'
307 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
308 * Initial import of version 2.9.3 source tree
311 *********************************************************************/
318 #include <sys/types.h>
326 #if !defined(_WIN32) && !defined(__OS2__)
336 #include "jbsockets.h"
337 #include "miscutil.h"
340 const char parsers_h_rcs[] = PARSERS_H_VERSION;
342 /* Fix a problem with Solaris. There should be no effect on other
344 * Solaris's isspace() is a macro which uses it's argument directly
345 * as an array index. Therefore we need to make sure that high-bit
346 * characters generate +ve values, and ideally we also want to make
347 * the argument match the declared parameter type of "int".
349 * Why did they write a character function that can't take a simple
350 * "char" argument? Doh!
352 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
353 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
356 const struct parsers client_patterns[] = {
357 { "referer:", 8, client_referrer },
358 { "user-agent:", 11, client_uagent },
359 { "ua-", 3, client_ua },
360 { "from:", 5, client_from },
361 { "cookie:", 7, client_send_cookie },
362 { "x-forwarded-for:", 16, client_x_forwarded },
363 { "Accept-Encoding:", 16, client_accept_encoding },
364 { "TE:", 3, client_te },
365 { "Host:", 5, crumble },
366 /* { "if-modified-since:", 18, crumble }, */
367 { "Keep-Alive:", 11, crumble },
368 { "connection:", 11, crumble },
369 { "proxy-connection:", 17, crumble },
374 const struct parsers server_patterns[] = {
375 { "HTTP", 4, server_http },
376 { "set-cookie:", 11, server_set_cookie },
377 { "connection:", 11, crumble },
378 { "Content-Type:", 13, server_content_type },
379 { "Content-Length:", 15, server_content_length },
380 { "Content-MD5:", 12, server_content_md5 },
381 { "Content-Encoding:", 17, server_content_encoding },
382 { "Transfer-Encoding:", 18, server_transfer_coding },
383 { "Keep-Alive:", 11, crumble },
388 void (* const add_client_headers[])(struct client_state *) = {
391 client_x_forwarded_adder,
393 client_accept_encoding_adder,
394 connection_close_adder,
399 void (* const add_server_headers[])(struct client_state *) = {
400 connection_close_adder,
405 /*********************************************************************
407 * Function : flush_socket
409 * Description : Write any pending "buffered" content.
412 * 1 : fd = file descriptor of the socket to read
413 * 2 : csp = Current client state (buffers, headers, etc...)
415 * Returns : On success, the number of bytes written are returned (zero
416 * indicates nothing was written). On error, -1 is returned,
417 * and errno is set appropriately. If count is zero and the
418 * file descriptor refers to a regular file, 0 will be
419 * returned without causing any other effect. For a special
420 * file, the results are not portable.
422 *********************************************************************/
423 int flush_socket(int fd, struct client_state *csp)
425 struct iob *iob = csp->iob;
426 int n = iob->eod - iob->cur;
433 n = write_socket(fd, iob->cur, n);
434 iob->eod = iob->cur = iob->buf;
440 /*********************************************************************
442 * Function : add_to_iob
444 * Description : Add content to the buffered page.
447 * 1 : csp = Current client state (buffers, headers, etc...)
448 * 2 : buf = holds the content to be added to the page
449 * 3 : n = number of bytes to be added
451 * Returns : Number of bytes in the content buffer.
453 *********************************************************************/
454 int add_to_iob(struct client_state *csp, char *buf, int n)
456 struct iob *iob = csp->iob;
460 have = iob->eod - iob->cur;
469 if ((p = (char *)malloc(need + 1)) == NULL)
471 log_error(LOG_LEVEL_ERROR, "malloc() iob failed: %E");
477 /* there is something in the buffer - save it */
478 memcpy(p, iob->cur, have);
480 /* replace the buffer with the new space */
484 /* point to the end of the data */
489 /* the buffer is empty, free it and reinitialize */
494 /* copy the new data into the iob buffer */
497 /* point to the end of the data */
500 /* null terminate == cheap insurance */
503 /* set the pointers to the new values */
512 /*********************************************************************
514 * Function : get_header
516 * Description : This (odd) routine will parse the csp->iob
519 * 1 : csp = Current client state (buffers, headers, etc...)
521 * Returns : Any one of the following:
523 * 1) a pointer to a dynamically allocated string that contains a header line
524 * 2) NULL indicating that the end of the header was reached
525 * 3) "" indicating that the end of the iob was reached before finding
526 * a complete header line.
528 *********************************************************************/
529 char *get_header(struct client_state *csp)
535 if ((iob->cur == NULL)
536 || ((p = strchr(iob->cur, '\n')) == NULL))
538 return(""); /* couldn't find a complete header */
543 ret = strdup(iob->cur);
547 if ((q = strchr(ret, '\r'))) *q = '\0';
549 /* is this a blank linke (i.e. the end of the header) ? */
561 /*********************************************************************
563 * Function : get_header_value
565 * Description : Get the value of a given header from a chained list
566 * of header lines or return NULL if no such header is
567 * present in the list.
570 * 1 : header_list = pointer to list
571 * 2 : header_name = string with name of header to look for.
572 * Trailing colon required, capitalization
575 * Returns : NULL if not found, else value of header
577 *********************************************************************/
578 char *get_header_value(const struct list *header_list, const char *header_name)
580 struct list_entry *cur_entry;
586 length = strlen(header_name);
588 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
592 if (!strncmpic(cur_entry->str, header_name, length))
595 * Found: return pointer to start of value
597 ret = (char *) (cur_entry->str + length);
598 while (*ret && ijb_isspace(*ret)) ret++;
611 /*********************************************************************
615 * Description : add, delete or modify lines in the HTTP header streams.
616 * On entry, it receives a linked list of headers space
617 * that was allocated dynamically (both the list nodes
618 * and the header contents).
620 * As a side effect it frees the space used by the original
624 * 1 : pats = list of patterns to match against headers
625 * 2 : more_headers = list of functions to add more
626 * headers (client or server)
627 * 3 : csp = Current client state (buffers, headers, etc...)
629 * Returns : Single pointer to a fully formed header, or NULL
630 * on out-of-memory error.
632 *********************************************************************/
633 char *sed(const struct parsers pats[], void (* const more_headers[])(struct client_state *), struct client_state *csp)
635 struct list_entry *p;
636 const struct parsers *v;
640 for (v = pats; v->str ; v++)
642 for (p = csp->headers->first; p ; p = p->next)
644 /* Header crunch()ed in previous run? -> ignore */
645 if (p->str == NULL) continue;
647 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
649 if (strncmpic(p->str, v->str, v->len) == 0)
651 hdr = v->parser(v, p->str, csp);
652 freez(p->str); /* FIXME: Yuck! patching a list...*/
658 /* place any additional headers on the csp->headers list */
659 for (f = more_headers; *f ; f++)
664 hdr = list_to_text(csp->headers);
671 /*********************************************************************
673 * Function : free_http_request
675 * Description : Freez a http_request structure
678 * 1 : http = points to a http_request structure to free
682 *********************************************************************/
683 void free_http_request(struct http_request *http)
691 freez(http->hostport);
694 freez(http->host_ip_addr_str);
699 /*********************************************************************
701 * Function : parse_http_request
703 * Description : Parse out the host and port from the URL. Find the
704 * hostname & path, port (if ':'), and/or password (if '@')
707 * 1 : req = URL (or is it URI?) to break down
708 * 2 : http = pointer to the http structure to hold elements
709 * 3 : csp = Current client state (buffers, headers, etc...)
713 *********************************************************************/
714 void parse_http_request(char *req, struct http_request *http, struct client_state *csp)
716 char *buf, *v[10], *url, *p;
719 memset(http, '\0', sizeof(*http));
720 http->cmd = strdup(req);
723 n = ssplit(buf, " \r\n", v, SZ(v), 1, 1);
727 /* this could be a CONNECT request */
728 if (strcmpic(v[0], "connect") == 0)
731 http->gpc = strdup(v[0]);
732 http->hostport = strdup(v[1]);
733 http->ver = strdup(v[2]);
736 /* or it could be any other basic HTTP request type */
737 if ((0 == strcmpic(v[0], "get"))
738 || (0 == strcmpic(v[0], "head"))
739 || (0 == strcmpic(v[0], "post"))
740 || (0 == strcmpic(v[0], "put"))
741 || (0 == strcmpic(v[0], "delete"))
743 /* or a webDAV extension (RFC2518) */
744 || (0 == strcmpic(v[0], "propfind"))
745 || (0 == strcmpic(v[0], "proppatch"))
746 || (0 == strcmpic(v[0], "move"))
747 || (0 == strcmpic(v[0], "copy"))
748 || (0 == strcmpic(v[0], "mkcol"))
749 || (0 == strcmpic(v[0], "lock"))
750 || (0 == strcmpic(v[0], "unlock"))
754 http->gpc = strdup(v[0]);
755 http->url = strdup(v[1]);
756 http->ver = strdup(v[2]);
759 if (strncmpic(url, "http://", 7) == 0)
763 else if (strncmpic(url, "https://", 8) == 0)
774 if ((p = strchr(url, '/')))
776 http->path = strdup(p);
778 http->hostport = strdup(url);
781 * Repair broken HTTP requests that don't contain a path
785 http->path = strdup("/");
786 http->hostport = strdup(url);
795 if (http->hostport == NULL)
797 free_http_request(http);
801 buf = strdup(http->hostport);
804 /* check if url contains password */
805 n = ssplit(buf, "@", v, SZ(v), 1, 1);
808 char * newbuf = NULL;
809 newbuf = strdup(v[1]);
814 n = ssplit(buf, ":", v, SZ(v), 1, 1);
818 http->host = strdup(v[0]);
824 http->host = strdup(v[0]);
825 http->port = atoi(v[1]);
830 if (http->host == NULL)
832 free_http_request(http);
835 if (http->path == NULL)
837 http->path = strdup("/");
843 /* here begins the family of parser functions that reformat header lines */
846 /*********************************************************************
850 * Description : This is called if a header matches a pattern to "crunch"
853 * 1 : v = Pointer to parsers structure, which basically holds
854 * headers (client or server) that we want to "crunch"
855 * 2 : s = header (from sed) to "crunch"
856 * 3 : csp = Current client state (buffers, headers, etc...)
858 * Returns : Always NULL.
860 *********************************************************************/
861 char *crumble(const struct parsers *v, const char *s, struct client_state *csp)
863 log_error(LOG_LEVEL_HEADER, "crunch!");
869 /*********************************************************************
871 * Function : server_content_type
873 * Description : Set the content-type for filterable types (text/.*,
874 * javascript and image/gif) unless filtering has been
875 * forbidden (CT_TABOO) while parsing earlier headers.
879 * 2 : s = header string we are "considering"
880 * 3 : csp = Current client state (buffers, headers, etc...)
882 * Returns : A duplicate string pointer to this header (ie. pass thru)
884 *********************************************************************/
885 char *server_content_type(const struct parsers *v, const char *s, struct client_state *csp)
887 if (csp->content_type != CT_TABOO)
889 if (strstr(s, " text/") || strstr(s, "application/x-javascript"))
890 csp->content_type = CT_TEXT;
891 else if (strstr(s, " image/gif"))
892 csp->content_type = CT_GIF;
894 csp->content_type = 0;
902 /*********************************************************************
904 * Function : server_transfer_coding
906 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
907 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
908 * - Change from "chunked" to "identity" if body was chunked
909 * but has been de-chunked for filtering.
913 * 2 : s = header string we are "considering"
914 * 3 : csp = Current client state (buffers, headers, etc...)
916 * Returns : A duplicate string pointer to this header (ie. pass thru)
918 *********************************************************************/
919 char *server_transfer_coding(const struct parsers *v, const char *s, struct client_state *csp)
922 * Turn off pcrs and gif filtering if body compressed
924 if (strstr(s, "gzip") || strstr(s, "compress") || strstr(s, "deflate"))
926 csp->content_type = CT_TABOO;
930 * Raise flag if body chunked
932 if (strstr(s, "chunked"))
934 csp->flags |= CSP_FLAG_CHUNKED;
937 * If the body was modified, it has been
938 * de-chunked first, so adjust the header:
940 if (csp->flags & CSP_FLAG_MODIFIED)
942 return(strdup("Transfer-Encoding: identity"));
951 /*********************************************************************
953 * Function : server_content_encoding
955 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
959 * 2 : s = header string we are "considering"
960 * 3 : csp = Current client state (buffers, headers, etc...)
962 * Returns : A duplicate string pointer to this header (ie. pass thru)
964 *********************************************************************/
965 char *server_content_encoding(const struct parsers *v, const char *s, struct client_state *csp)
968 * Turn off pcrs and gif filtering if body compressed
970 if (strstr(s, "gzip") || strstr(s, "compress") || strstr(s, "deflate"))
972 csp->content_type = CT_TABOO;
980 /*********************************************************************
982 * Function : server_content_length
984 * Description : Adjust Content-Length header if we modified
989 * 2 : s = header string we are "considering"
990 * 3 : csp = Current client state (buffers, headers, etc...)
992 * Returns : A duplicate string pointer to this header (ie. pass thru)
994 *********************************************************************/
995 char *server_content_length(const struct parsers *v, const char *s, struct client_state *csp)
997 if (csp->content_length != 0) /* Content length has been modified */
999 char * s2 = (char *) zalloc(100);
1000 sprintf(s2, "Content-Length: %d", (int) csp->content_length);
1002 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1013 /*********************************************************************
1015 * Function : server_content_md5
1017 * Description : Crumble any Content-MD5 headers if the document was
1018 * modified. FIXME: Should we re-compute instead?
1022 * 2 : s = header string we are "considering"
1023 * 3 : csp = Current client state (buffers, headers, etc...)
1025 * Returns : A duplicate string pointer to this header (ie. pass thru)
1027 *********************************************************************/
1028 char *server_content_md5(const struct parsers *v, const char *s, struct client_state *csp)
1030 if (csp->flags & CSP_FLAG_MODIFIED)
1032 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1043 /*********************************************************************
1045 * Function : client_accept_encoding
1047 * Description : Rewrite the client's Accept-Encoding header so that
1048 * if doesn't allow compression, if the action applies.
1049 * Note: For HTTP/1.0 the absence of the header is enough.
1053 * 2 : s = header string we are "considering"
1054 * 3 : csp = Current client state (buffers, headers, etc...)
1056 * Returns : A copy of the client's original or the modified header.
1058 *********************************************************************/
1059 char *client_accept_encoding(const struct parsers *v, const char *s, struct client_state *csp)
1061 if ((csp->action->flags & ACTION_NO_COMPRESSION) == 0)
1067 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress content");
1069 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1071 return(strdup("Accept-Encoding: identity;q=1.0, *;q=0"));
1082 /*********************************************************************
1084 * Function : client_te
1086 * Description : Rewrite the client's TE header so that
1087 * if doesn't allow compression, if the action applies.
1091 * 2 : s = header string we are "considering"
1092 * 3 : csp = Current client state (buffers, headers, etc...)
1094 * Returns : A copy of the client's original or the modified header.
1096 *********************************************************************/
1097 char *client_te(const struct parsers *v, const char *s, struct client_state *csp)
1099 if ((csp->action->flags & ACTION_NO_COMPRESSION) == 0)
1105 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress transfer");
1111 /*********************************************************************
1113 * Function : client_referrer
1115 * Description : Handle the "referer" config setting properly.
1116 * Called from `sed'.
1120 * 2 : s = header (from sed) to "crunch"
1121 * 3 : csp = Current client state (buffers, headers, etc...)
1123 * Returns : NULL if crunched, or a malloc'ed string with the original
1124 * or modified header
1126 *********************************************************************/
1127 char *client_referrer(const struct parsers *v, const char *s, struct client_state *csp)
1129 const char * newval;
1131 #ifdef FEATURE_FORCE_LOAD
1132 /* Since the referrer can include the prefix even
1133 * even if the request itself is non-forced, we must
1134 * clean it unconditionally
1136 strclean(s, FORCE_PREFIX);
1137 #endif /* def FEATURE_FORCE_LOAD */
1140 * Are we sending referer?
1142 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1147 newval = csp->action->string[ACTION_STRING_REFERER];
1150 * Are we blocking referer?
1152 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1154 log_error(LOG_LEVEL_HEADER, "crunch!");
1159 * Are we forging referer?
1161 if (0 == strcmpic(newval, "forge"))
1164 * Forge a referer as http://[hostname:port of REQUEST]/
1165 * to fool stupid checks for in-site links
1167 log_error(LOG_LEVEL_HEADER, "crunch+forge!");
1168 s2 = strsav(NULL, "Referer: ");
1169 s2 = strsav(s2, "http://");
1170 s2 = strsav(s2, csp->http->hostport);
1171 s2 = strsav(s2, "/");
1176 * Have we got a fixed referer?
1178 if (0 == strncmpic(newval, "http://", 7))
1181 * We have a specific (fixed) referer we want to send.
1185 log_error(LOG_LEVEL_HEADER, "modified");
1187 s3 = strsav( NULL, "Referer: " );
1188 s3 = strsav( s3, newval );
1192 /* Should never get here! */
1193 log_error(LOG_LEVEL_ERROR, "Bad parameter: +referer{%s}", newval);
1196 * Forge is probably the best default.
1198 * Forge a referer as http://[hostname:port of REQUEST]/
1199 * to fool stupid checks for in-site links
1201 log_error(LOG_LEVEL_HEADER, "crunch+forge!");
1202 s2 = strsav(NULL, "Referer: ");
1203 s2 = strsav(s2, "http://");
1204 s2 = strsav(s2, csp->http->hostport);
1205 s2 = strsav(s2, "/");
1210 /*********************************************************************
1212 * Function : client_uagent
1214 * Description : Handle the "user-agent" config setting properly
1215 * and remember its original value to enable browser
1216 * bug workarounds. Called from `sed'.
1220 * 2 : s = header (from sed) to "crunch"
1221 * 3 : csp = Current client state (buffers, headers, etc...)
1223 * Returns : A malloc'ed pointer to the default agent, or
1224 * a malloc'ed string pointer to this header (ie. pass thru).
1226 *********************************************************************/
1227 char *client_uagent(const struct parsers *v, const char *s, struct client_state *csp)
1229 const char * newval;
1232 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1237 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1243 log_error(LOG_LEVEL_HEADER, "modified");
1245 s2 = strsav( NULL, "User-Agent: " );
1246 s2 = strsav( s2, newval );
1252 /*********************************************************************
1254 * Function : client_ua
1256 * Description : Handle "ua-" headers properly. Called from `sed'.
1260 * 2 : s = header (from sed) to "crunch"
1261 * 3 : csp = Current client state (buffers, headers, etc...)
1263 * Returns : NULL if crunched, or a malloc'ed string to original header
1265 *********************************************************************/
1266 char *client_ua(const struct parsers *v, const char *s, struct client_state *csp)
1268 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1274 log_error(LOG_LEVEL_HEADER, "crunch!");
1280 /*********************************************************************
1282 * Function : client_from
1284 * Description : Handle the "from" config setting properly.
1285 * Called from `sed'.
1289 * 2 : s = header (from sed) to "crunch"
1290 * 3 : csp = Current client state (buffers, headers, etc...)
1292 * Returns : NULL if crunched, or a malloc'ed string to
1293 * modified/original header.
1295 *********************************************************************/
1296 char *client_from(const struct parsers *v, const char *s, struct client_state *csp)
1298 const char * newval;
1301 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1306 newval = csp->action->string[ACTION_STRING_FROM];
1309 * Are we blocking referer?
1311 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1313 log_error(LOG_LEVEL_HEADER, "crunch!");
1317 log_error(LOG_LEVEL_HEADER, " modified");
1319 s2 = strsav( NULL, "From: " );
1320 s2 = strsav( s2, newval );
1326 /*********************************************************************
1328 * Function : client_send_cookie
1330 * Description : Handle the "cookie" header properly. Called from `sed'.
1331 * If cookie is accepted, add it to the cookie_list,
1332 * else we crunch it. Mmmmmmmmmmm ... cookie ......
1335 * 1 : v = pattern of cookie `sed' found matching
1336 * 2 : s = header (from sed) to "crunch"
1337 * 3 : csp = Current client state (buffers, headers, etc...)
1339 * Returns : Always NULL.
1341 *********************************************************************/
1342 char *client_send_cookie(const struct parsers *v, const char *s, struct client_state *csp)
1344 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
1346 enlist(csp->cookie_list, s + v->len + 1);
1350 log_error(LOG_LEVEL_HEADER, " crunch!");
1354 * Always return NULL here. The cookie header
1355 * will be sent at the end of the header.
1362 /*********************************************************************
1364 * Function : client_x_forwarded
1366 * Description : Handle the "x-forwarded-for" config setting properly,
1367 * also used in the add_client_headers list. Called from `sed'.
1371 * 2 : s = header (from sed) to "crunch"
1372 * 3 : csp = Current client state (buffers, headers, etc...)
1374 * Returns : Always NULL.
1376 *********************************************************************/
1377 char *client_x_forwarded(const struct parsers *v, const char *s, struct client_state *csp)
1379 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
1381 /* Save it so we can re-add it later */
1382 csp->x_forwarded = strdup(s);
1386 * Always return NULL, since this information
1387 * will be sent at the end of the header.
1394 /* the following functions add headers directly to the header list */
1396 /*********************************************************************
1398 * Function : client_host_adder
1400 * Description : (re)adds the host header. Called from `sed'.
1403 * 1 : csp = Current client state (buffers, headers, etc...)
1407 *********************************************************************/
1408 void client_host_adder(struct client_state *csp)
1412 p = strsav(p, "Host: ");
1413 p = strsav(p, csp->http->hostport);
1415 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1416 enlist(csp->headers, p);
1422 /*********************************************************************
1424 * Function : client_cookie_adder
1426 * Description : Used in the add_client_headers list. Called from `sed'.
1429 * 1 : csp = Current client state (buffers, headers, etc...)
1433 *********************************************************************/
1434 void client_cookie_adder(struct client_state *csp)
1436 struct list_entry *lst;
1440 for (lst = csp->cookie_list->first; lst ; lst = lst->next)
1444 tmp = strsav(tmp, "; ");
1446 tmp = strsav(tmp, lst->str);
1449 for (lst = csp->action->multi[ACTION_MULTI_WAFER]->first; lst ; lst = lst->next)
1453 tmp = strsav(tmp, "; ");
1456 if ((e = cookie_encode(lst->str)))
1458 tmp = strsav(tmp, e);
1467 ret = strdup("Cookie: ");
1468 ret = strsav(ret, tmp);
1469 log_error(LOG_LEVEL_HEADER, "addh: %s", ret);
1470 enlist(csp->headers, ret);
1478 /*********************************************************************
1480 * Function : client_accept_encoding_adder
1482 * Description : Add an Accept-Encoding header to the client's request
1483 * that disables compression if the action applies, and
1484 * the header is not already there. Called from `sed'.
1485 * Note: For HTTP/1.0, the absence of the header is enough.
1488 * 1 : csp = Current client state (buffers, headers, etc...)
1492 *********************************************************************/
1493 void client_accept_encoding_adder(struct client_state *csp)
1495 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1496 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
1498 enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
1504 /*********************************************************************
1506 * Function : client_xtra_adder
1508 * Description : Used in the add_client_headers list. Called from `sed'.
1511 * 1 : csp = Current client state (buffers, headers, etc...)
1515 *********************************************************************/
1516 void client_xtra_adder(struct client_state *csp)
1518 struct list_entry *lst;
1520 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
1521 lst ; lst = lst->next)
1523 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
1524 enlist(csp->headers, lst->str);
1530 /*********************************************************************
1532 * Function : client_x_forwarded_adder
1534 * Description : Used in the add_client_headers list. Called from `sed'.
1537 * 1 : csp = Current client state (buffers, headers, etc...)
1541 *********************************************************************/
1542 void client_x_forwarded_adder(struct client_state *csp)
1546 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
1551 if (csp->x_forwarded)
1553 p = strsav(p, csp->x_forwarded);
1554 p = strsav(p, ", ");
1555 p = strsav(p, csp->ip_addr_str);
1559 p = strsav(p, "X-Forwarded-For: ");
1560 p = strsav(p, csp->ip_addr_str);
1563 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1564 enlist(csp->headers, p);
1570 /*********************************************************************
1572 * Function : connection_close_adder
1574 * Description : Adds a "Connection: close" header to csp->headers
1575 * as a temporary fix for the needed but missing HTTP/1.1
1576 * support. Called from `sed'.
1577 * FIXME: This whole function shouldn't be neccessary!
1580 * 1 : csp = Current client state (buffers, headers, etc...)
1584 *********************************************************************/
1585 void connection_close_adder(struct client_state *csp)
1587 enlist(csp->headers, "Connection: close");
1591 /*********************************************************************
1593 * Function : server_http
1595 * Description : - Save the HTTP Status into csp->http->status
1596 * - Set CT_TABOO to prevent filtering if the answer
1597 * is a partial range (HTTP status 206)
1598 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
1602 * 1 : v = parser pattern that matched this header
1603 * 2 : s = header that matched this pattern
1604 * 3 : csp = Current client state (buffers, headers, etc...)
1606 * Returns : Copy of changed or original answer.
1608 *********************************************************************/
1609 char *server_http(const struct parsers *v, const char *s, struct client_state *csp)
1611 char *ret = strdup(s);
1613 sscanf(ret, "HTTP/%*d.%*d %d", &(csp->http->status));
1614 if (csp->http->status == 206)
1616 csp->content_type = CT_TABOO;
1619 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
1622 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
1629 /*********************************************************************
1631 * Function : server_set_cookie
1633 * Description : Handle the server "cookie" header properly.
1634 * Log cookie to the jar file. Then "crunch" it,
1635 * or accept it. Called from `sed'.
1638 * 1 : v = parser pattern that matched this header
1639 * 2 : s = header that matched this pattern
1640 * 3 : csp = Current client state (buffers, headers, etc...)
1642 * Returns : `crumble' or a newly malloc'ed string.
1644 *********************************************************************/
1645 char *server_set_cookie(const struct parsers *v, const char *s, struct client_state *csp)
1647 #ifdef FEATURE_COOKIE_JAR
1650 * Write timestamp into outbuf.
1652 * Complex because not all OSs have tm_gmtoff or
1653 * the %z field in strftime()
1655 char tempbuf[ BUFFER_SIZE ];
1659 tm_now = localtime (&now);
1660 strftime (tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", tm_now);
1662 if (csp->config->jar)
1664 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, (s + v->len + 1));
1666 #endif /* def FEATURE_COOKIE_JAR */
1668 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
1670 return(crumble(v, s, csp));
1678 #ifdef FEATURE_FORCE_LOAD
1679 /*********************************************************************
1681 * Function : strclean
1683 * Description : In-Situ-Eliminate all occurances of substring in
1687 * 1 : string = string to clean
1688 * 2 : substring = substring to eliminate
1690 * Returns : Number of eliminations
1692 *********************************************************************/
1693 int strclean(const char *string, const char *substring)
1695 int hits = 0, len = strlen(substring);
1698 while((pos = strstr(string, substring)))
1705 while (*p++ != '\0');
1712 #endif /* def FEATURE_FORCE_LOAD */