1 const char parsers_rcs[] = "$Id: parsers.c,v 1.41 2001/11/05 23:43:05 steudten 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.41 2001/11/05 23:43:05 steudten
45 * Add time+date to log files.
47 * Revision 1.40 2001/10/26 20:13:09 jongfoster
48 * ctype.h is needed in Windows, too.
50 * Revision 1.39 2001/10/26 17:40:04 oes
51 * Introduced get_header_value()
52 * Removed http->user_agent, csp->referrer and csp->accept_types
53 * Removed client_accept()
55 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
56 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
57 * threads to call select() simultaneously. So, it's time to do a real, live,
58 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
59 * (native). Both versions will work, but using __OS2__ offers multi-threading.
61 * Revision 1.37 2001/10/23 21:36:02 jongfoster
62 * Documenting sed()'s error behaviou (doc change only)
64 * Revision 1.36 2001/10/13 12:51:51 joergs
65 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
66 * force-load), instead crumble Host: and add it (again) in client_host_adder
67 * (in case we get a HTTP/1.0 request without Host: header and forward it to
68 * a HTTP/1.1 server/proxy).
70 * Revision 1.35 2001/10/09 22:39:21 jongfoster
71 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
74 * Revision 1.34 2001/10/07 18:50:55 oes
75 * Added server_content_encoding, renamed server_transfer_encoding
77 * Revision 1.33 2001/10/07 18:04:49 oes
78 * Changed server_http11 to server_http and its pattern to "HTTP".
79 * Additional functionality: it now saves the HTTP status into
80 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
82 * Revision 1.32 2001/10/07 15:43:28 oes
83 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
84 * client_te and client_accept_encoding_adder, triggered by the new
85 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
86 * changed to allow only identity and chunked, and the TE header is
87 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
89 * parse_http_request no longer does anything than parsing. The rewriting
90 * of http->cmd and version mangling are gone. It now also recognizes
91 * the put and delete methods and saves the url in http->url. Removed
94 * renamed content_type and content_length to have the server_ prefix
96 * server_content_type now only works if csp->content_type != CT_TABOO
98 * added server_transfer_encoding, which
99 * - Sets CT_TABOO to prohibit filtering if encoding compresses
100 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
101 * - Change from "chunked" to "identity" if body was chunked
102 * but has been de-chunked for filtering.
104 * added server_content_md5 which crunches any Content-MD5 headers
105 * if the body was modified.
107 * made server_http11 conditional on +downgrade action
109 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
111 * Revision 1.31 2001/10/05 14:25:02 oes
112 * Crumble Keep-Alive from Server
114 * Revision 1.30 2001/09/29 12:56:03 joergs
115 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
117 * Revision 1.29 2001/09/24 21:09:24 jongfoster
118 * Fixing 2 memory leaks that Guy spotted, where the paramater to
119 * enlist() was not being free()d.
121 * Revision 1.28 2001/09/22 16:32:28 jongfoster
122 * Removing unused #includes.
124 * Revision 1.27 2001/09/20 15:45:25 steudten
126 * add casting from size_t to int for printf()
127 * remove local variable shadow s2
129 * Revision 1.26 2001/09/16 17:05:14 jongfoster
130 * Removing unused #include showarg.h
132 * Revision 1.25 2001/09/16 13:21:27 jongfoster
133 * Changes to use new list functions.
135 * Revision 1.24 2001/09/13 23:05:50 jongfoster
136 * Changing the string paramater to the header parsers a "const".
138 * Revision 1.23 2001/09/12 18:08:19 steudten
140 * In parse_http_request() header rewriting miss the host value, so
141 * from http://www.mydomain.com the result was just " / " not
142 * http://www.mydomain.com/ in case we forward.
144 * Revision 1.22 2001/09/10 10:58:53 oes
145 * Silenced compiler warnings
147 * Revision 1.21 2001/07/31 14:46:00 oes
148 * - Persistant connections now suppressed
149 * - sed() no longer appends empty header to csp->headers
151 * Revision 1.20 2001/07/30 22:08:36 jongfoster
152 * Tidying up #defines:
153 * - All feature #defines are now of the form FEATURE_xxx
154 * - Permanently turned off WIN_GUI_EDIT
155 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
157 * Revision 1.19 2001/07/25 17:21:54 oes
158 * client_uagent now saves copy of User-Agent: header value
160 * Revision 1.18 2001/07/13 14:02:46 oes
161 * - Included fix to repair broken HTTP requests that
162 * don't contain a path, not even '/'.
163 * - Removed all #ifdef PCRS
164 * - content_type now always inspected and classified as
165 * text, gif or other.
166 * - formatting / comments
168 * Revision 1.17 2001/06/29 21:45:41 oes
169 * Indentation, CRLF->LF, Tab-> Space
171 * Revision 1.16 2001/06/29 13:32:42 oes
173 * - Adapted free_http_request
174 * - Removed logentry from cancelled commit
176 * Revision 1.15 2001/06/03 19:12:38 oes
177 * deleted const struct interceptors
179 * Revision 1.14 2001/06/01 18:49:17 jongfoster
180 * Replaced "list_share" with "list" - the tiny memory gain was not
181 * worth the extra complexity.
183 * Revision 1.13 2001/05/31 21:30:33 jongfoster
184 * Removed list code - it's now in list.[ch]
185 * Renamed "permission" to "action", and changed many features
186 * to use the actions file rather than the global config.
188 * Revision 1.12 2001/05/31 17:33:13 oes
192 * Revision 1.11 2001/05/29 20:11:19 joergs
193 * '/ * inside comment' warning removed.
195 * Revision 1.10 2001/05/29 09:50:24 jongfoster
196 * Unified blocklist/imagelist/permissionslist.
197 * File format is still under discussion, but the internal changes
200 * Also modified interceptor behaviour:
201 * - We now intercept all URLs beginning with one of the following
202 * prefixes (and *only* these prefixes):
204 * * http://ijbswa.sf.net/config/
205 * * http://ijbswa.sourceforge.net/config/
206 * - New interceptors "home page" - go to http://i.j.b/ to see it.
207 * - Internal changes so that intercepted and fast redirect pages
208 * are not replaced with an image.
209 * - Interceptors now have the option to send a binary page direct
210 * to the client. (i.e. ijb-send-banner uses this)
211 * - Implemented show-url-info interceptor. (Which is why I needed
212 * the above interceptors changes - a typical URL is
213 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
214 * The previous mechanism would not have intercepted that, and
215 * if it had been intercepted then it then it would have replaced
218 * Revision 1.9 2001/05/28 17:26:33 jongfoster
219 * Fixing segfault if last header was crunched.
220 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
221 * can use the cross-platform sprintf() instead.)
223 * Revision 1.8 2001/05/27 22:17:04 oes
225 * - re_process_buffer no longer writes the modified buffer
226 * to the client, which was very ugly. It now returns the
227 * buffer, which it is then written by chat.
229 * - content_length now adjusts the Content-Length: header
230 * for modified documents rather than crunch()ing it.
231 * (Length info in csp->content_length, which is 0 for
232 * unmodified documents)
234 * - For this to work, sed() is called twice when filtering.
236 * Revision 1.7 2001/05/27 13:19:06 oes
237 * Patched Joergs solution for the content-length in.
239 * Revision 1.6 2001/05/26 13:39:32 jongfoster
240 * Only crunches Content-Length header if applying RE filtering.
241 * Without this fix, Microsoft Windows Update wouldn't work.
243 * Revision 1.5 2001/05/26 00:28:36 jongfoster
244 * Automatic reloading of config file.
245 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
246 * Most of the global variables have been moved to a new
247 * struct configuration_spec, accessed through csp->config->globalname
248 * Most of the globals remaining are used by the Win32 GUI.
250 * Revision 1.4 2001/05/22 18:46:04 oes
252 * - Enabled filtering banners by size rather than URL
253 * by adding patterns that replace all standard banner
254 * sizes with the "Junkbuster" gif to the re_filterfile
256 * - Enabled filtering WebBugs by providing a pattern
257 * which kills all 1x1 images
259 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
260 * which is selected by the (nonstandard and therefore
261 * capital) letter 'U' in the option string.
262 * It causes the quantifiers to be ungreedy by default.
263 * Appending a ? turns back to greedy (!).
265 * - Added a new interceptor ijb-send-banner, which
266 * sends back the "Junkbuster" gif. Without imagelist or
267 * MSIE detection support, or if tinygif = 1, or the
268 * URL isn't recognized as an imageurl, a lame HTML
269 * explanation is sent instead.
271 * - Added new feature, which permits blocking remote
272 * script redirects and firing back a local redirect
274 * The feature is conditionally compiled, i.e. it
275 * can be disabled with --disable-fast-redirects,
276 * plus it must be activated by a "fast-redirects"
277 * line in the config file, has its own log level
278 * and of course wants to be displayed by show-proxy-args
279 * Note: Boy, all the #ifdefs in 1001 locations and
280 * all the fumbling with configure.in and acconfig.h
281 * were *way* more work than the feature itself :-(
283 * - Because a generic redirect template was needed for
284 * this, tinygif = 3 now uses the same.
286 * - Moved GIFs, and other static HTTP response templates
291 * - Removed some >400 CRs again (Jon, you really worked
294 * Revision 1.3 2001/05/20 01:21:20 jongfoster
295 * Version 2.9.4 checkin.
296 * - Merged popupfile and cookiefile, and added control over PCRS
297 * filtering, in new "permissionsfile".
298 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
299 * file error you now get a message box (in the Win32 GUI) rather
300 * than the program exiting with no explanation.
301 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
303 * - Removed tabs from "config"
304 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
305 * - Bumped up version number.
307 * Revision 1.2 2001/05/17 23:02:36 oes
308 * - Made referrer option accept 'L' as a substitute for '§'
310 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
311 * Initial import of version 2.9.3 source tree
314 *********************************************************************/
321 #include <sys/types.h>
329 #if !defined(_WIN32) && !defined(__OS2__)
339 #include "jbsockets.h"
340 #include "miscutil.h"
343 const char parsers_h_rcs[] = PARSERS_H_VERSION;
345 /* Fix a problem with Solaris. There should be no effect on other
347 * Solaris's isspace() is a macro which uses it's argument directly
348 * as an array index. Therefore we need to make sure that high-bit
349 * characters generate +ve values, and ideally we also want to make
350 * the argument match the declared parameter type of "int".
352 * Why did they write a character function that can't take a simple
353 * "char" argument? Doh!
355 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
356 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
359 const struct parsers client_patterns[] = {
360 { "referer:", 8, client_referrer },
361 { "user-agent:", 11, client_uagent },
362 { "ua-", 3, client_ua },
363 { "from:", 5, client_from },
364 { "cookie:", 7, client_send_cookie },
365 { "x-forwarded-for:", 16, client_x_forwarded },
366 { "Accept-Encoding:", 16, client_accept_encoding },
367 { "TE:", 3, client_te },
368 { "Host:", 5, crumble },
369 /* { "if-modified-since:", 18, crumble }, */
370 { "Keep-Alive:", 11, crumble },
371 { "connection:", 11, crumble },
372 { "proxy-connection:", 17, crumble },
377 const struct parsers server_patterns[] = {
378 { "HTTP", 4, server_http },
379 { "set-cookie:", 11, server_set_cookie },
380 { "connection:", 11, crumble },
381 { "Content-Type:", 13, server_content_type },
382 { "Content-Length:", 15, server_content_length },
383 { "Content-MD5:", 12, server_content_md5 },
384 { "Content-Encoding:", 17, server_content_encoding },
385 { "Transfer-Encoding:", 18, server_transfer_coding },
386 { "Keep-Alive:", 11, crumble },
391 void (* const add_client_headers[])(struct client_state *) = {
394 client_x_forwarded_adder,
396 client_accept_encoding_adder,
397 connection_close_adder,
402 void (* const add_server_headers[])(struct client_state *) = {
403 connection_close_adder,
408 /*********************************************************************
410 * Function : flush_socket
412 * Description : Write any pending "buffered" content.
415 * 1 : fd = file descriptor of the socket to read
416 * 2 : csp = Current client state (buffers, headers, etc...)
418 * Returns : On success, the number of bytes written are returned (zero
419 * indicates nothing was written). On error, -1 is returned,
420 * and errno is set appropriately. If count is zero and the
421 * file descriptor refers to a regular file, 0 will be
422 * returned without causing any other effect. For a special
423 * file, the results are not portable.
425 *********************************************************************/
426 int flush_socket(int fd, struct client_state *csp)
428 struct iob *iob = csp->iob;
429 int n = iob->eod - iob->cur;
436 n = write_socket(fd, iob->cur, n);
437 iob->eod = iob->cur = iob->buf;
443 /*********************************************************************
445 * Function : add_to_iob
447 * Description : Add content to the buffered page.
450 * 1 : csp = Current client state (buffers, headers, etc...)
451 * 2 : buf = holds the content to be added to the page
452 * 3 : n = number of bytes to be added
454 * Returns : Number of bytes in the content buffer.
456 *********************************************************************/
457 int add_to_iob(struct client_state *csp, char *buf, int n)
459 struct iob *iob = csp->iob;
463 have = iob->eod - iob->cur;
472 if ((p = (char *)malloc(need + 1)) == NULL)
474 log_error(LOG_LEVEL_ERROR, "malloc() iob failed: %E");
480 /* there is something in the buffer - save it */
481 memcpy(p, iob->cur, have);
483 /* replace the buffer with the new space */
487 /* point to the end of the data */
492 /* the buffer is empty, free it and reinitialize */
497 /* copy the new data into the iob buffer */
500 /* point to the end of the data */
503 /* null terminate == cheap insurance */
506 /* set the pointers to the new values */
515 /*********************************************************************
517 * Function : get_header
519 * Description : This (odd) routine will parse the csp->iob
522 * 1 : csp = Current client state (buffers, headers, etc...)
524 * Returns : Any one of the following:
526 * 1) a pointer to a dynamically allocated string that contains a header line
527 * 2) NULL indicating that the end of the header was reached
528 * 3) "" indicating that the end of the iob was reached before finding
529 * a complete header line.
531 *********************************************************************/
532 char *get_header(struct client_state *csp)
538 if ((iob->cur == NULL)
539 || ((p = strchr(iob->cur, '\n')) == NULL))
541 return(""); /* couldn't find a complete header */
546 ret = strdup(iob->cur);
550 if ((q = strchr(ret, '\r'))) *q = '\0';
552 /* is this a blank linke (i.e. the end of the header) ? */
564 /*********************************************************************
566 * Function : get_header_value
568 * Description : Get the value of a given header from a chained list
569 * of header lines or return NULL if no such header is
570 * present in the list.
573 * 1 : header_list = pointer to list
574 * 2 : header_name = string with name of header to look for.
575 * Trailing colon required, capitalization
578 * Returns : NULL if not found, else value of header
580 *********************************************************************/
581 char *get_header_value(const struct list *header_list, const char *header_name)
583 struct list_entry *cur_entry;
589 length = strlen(header_name);
591 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
595 if (!strncmpic(cur_entry->str, header_name, length))
598 * Found: return pointer to start of value
600 ret = (char *) (cur_entry->str + length);
601 while (*ret && ijb_isspace(*ret)) ret++;
614 /*********************************************************************
618 * Description : add, delete or modify lines in the HTTP header streams.
619 * On entry, it receives a linked list of headers space
620 * that was allocated dynamically (both the list nodes
621 * and the header contents).
623 * As a side effect it frees the space used by the original
627 * 1 : pats = list of patterns to match against headers
628 * 2 : more_headers = list of functions to add more
629 * headers (client or server)
630 * 3 : csp = Current client state (buffers, headers, etc...)
632 * Returns : Single pointer to a fully formed header, or NULL
633 * on out-of-memory error.
635 *********************************************************************/
636 char *sed(const struct parsers pats[], void (* const more_headers[])(struct client_state *), struct client_state *csp)
638 struct list_entry *p;
639 const struct parsers *v;
643 for (v = pats; v->str ; v++)
645 for (p = csp->headers->first; p ; p = p->next)
647 /* Header crunch()ed in previous run? -> ignore */
648 if (p->str == NULL) continue;
650 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
652 if (strncmpic(p->str, v->str, v->len) == 0)
654 hdr = v->parser(v, p->str, csp);
655 freez(p->str); /* FIXME: Yuck! patching a list...*/
661 /* place any additional headers on the csp->headers list */
662 for (f = more_headers; *f ; f++)
667 hdr = list_to_text(csp->headers);
674 /*********************************************************************
676 * Function : free_http_request
678 * Description : Freez a http_request structure
681 * 1 : http = points to a http_request structure to free
685 *********************************************************************/
686 void free_http_request(struct http_request *http)
694 freez(http->hostport);
697 freez(http->host_ip_addr_str);
702 /*********************************************************************
704 * Function : parse_http_request
706 * Description : Parse out the host and port from the URL. Find the
707 * hostname & path, port (if ':'), and/or password (if '@')
710 * 1 : req = URL (or is it URI?) to break down
711 * 2 : http = pointer to the http structure to hold elements
712 * 3 : csp = Current client state (buffers, headers, etc...)
716 *********************************************************************/
717 void parse_http_request(char *req, struct http_request *http, struct client_state *csp)
719 char *buf, *v[10], *url, *p;
722 memset(http, '\0', sizeof(*http));
723 http->cmd = strdup(req);
726 n = ssplit(buf, " \r\n", v, SZ(v), 1, 1);
730 /* this could be a CONNECT request */
731 if (strcmpic(v[0], "connect") == 0)
734 http->gpc = strdup(v[0]);
735 http->hostport = strdup(v[1]);
736 http->ver = strdup(v[2]);
739 /* or it could be any other basic HTTP request type */
740 if ((0 == strcmpic(v[0], "get"))
741 || (0 == strcmpic(v[0], "head"))
742 || (0 == strcmpic(v[0], "post"))
743 || (0 == strcmpic(v[0], "put"))
744 || (0 == strcmpic(v[0], "delete"))
746 /* or a webDAV extension (RFC2518) */
747 || (0 == strcmpic(v[0], "propfind"))
748 || (0 == strcmpic(v[0], "proppatch"))
749 || (0 == strcmpic(v[0], "move"))
750 || (0 == strcmpic(v[0], "copy"))
751 || (0 == strcmpic(v[0], "mkcol"))
752 || (0 == strcmpic(v[0], "lock"))
753 || (0 == strcmpic(v[0], "unlock"))
757 http->gpc = strdup(v[0]);
758 http->url = strdup(v[1]);
759 http->ver = strdup(v[2]);
762 if (strncmpic(url, "http://", 7) == 0)
766 else if (strncmpic(url, "https://", 8) == 0)
777 if ((p = strchr(url, '/')))
779 http->path = strdup(p);
781 http->hostport = strdup(url);
784 * Repair broken HTTP requests that don't contain a path
788 http->path = strdup("/");
789 http->hostport = strdup(url);
798 if (http->hostport == NULL)
800 free_http_request(http);
804 buf = strdup(http->hostport);
807 /* check if url contains password */
808 n = ssplit(buf, "@", v, SZ(v), 1, 1);
811 char * newbuf = NULL;
812 newbuf = strdup(v[1]);
817 n = ssplit(buf, ":", v, SZ(v), 1, 1);
821 http->host = strdup(v[0]);
827 http->host = strdup(v[0]);
828 http->port = atoi(v[1]);
833 if (http->host == NULL)
835 free_http_request(http);
838 if (http->path == NULL)
840 http->path = strdup("/");
846 /* here begins the family of parser functions that reformat header lines */
849 /*********************************************************************
853 * Description : This is called if a header matches a pattern to "crunch"
856 * 1 : v = Pointer to parsers structure, which basically holds
857 * headers (client or server) that we want to "crunch"
858 * 2 : s = header (from sed) to "crunch"
859 * 3 : csp = Current client state (buffers, headers, etc...)
861 * Returns : Always NULL.
863 *********************************************************************/
864 char *crumble(const struct parsers *v, const char *s, struct client_state *csp)
866 log_error(LOG_LEVEL_HEADER, "crunch!");
872 /*********************************************************************
874 * Function : server_content_type
876 * Description : Set the content-type for filterable types (text/.*,
877 * javascript and image/gif) unless filtering has been
878 * forbidden (CT_TABOO) while parsing earlier headers.
882 * 2 : s = header string we are "considering"
883 * 3 : csp = Current client state (buffers, headers, etc...)
885 * Returns : A duplicate string pointer to this header (ie. pass thru)
887 *********************************************************************/
888 char *server_content_type(const struct parsers *v, const char *s, struct client_state *csp)
890 if (csp->content_type != CT_TABOO)
892 if (strstr(s, " text/") || strstr(s, "application/x-javascript"))
893 csp->content_type = CT_TEXT;
894 else if (strstr(s, " image/gif"))
895 csp->content_type = CT_GIF;
897 csp->content_type = 0;
905 /*********************************************************************
907 * Function : server_transfer_coding
909 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
910 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
911 * - Change from "chunked" to "identity" if body was chunked
912 * but has been de-chunked for filtering.
916 * 2 : s = header string we are "considering"
917 * 3 : csp = Current client state (buffers, headers, etc...)
919 * Returns : A duplicate string pointer to this header (ie. pass thru)
921 *********************************************************************/
922 char *server_transfer_coding(const struct parsers *v, const char *s, struct client_state *csp)
925 * Turn off pcrs and gif filtering if body compressed
927 if (strstr(s, "gzip") || strstr(s, "compress") || strstr(s, "deflate"))
929 csp->content_type = CT_TABOO;
933 * Raise flag if body chunked
935 if (strstr(s, "chunked"))
937 csp->flags |= CSP_FLAG_CHUNKED;
940 * If the body was modified, it has been
941 * de-chunked first, so adjust the header:
943 if (csp->flags & CSP_FLAG_MODIFIED)
945 return(strdup("Transfer-Encoding: identity"));
954 /*********************************************************************
956 * Function : server_content_encoding
958 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
962 * 2 : s = header string we are "considering"
963 * 3 : csp = Current client state (buffers, headers, etc...)
965 * Returns : A duplicate string pointer to this header (ie. pass thru)
967 *********************************************************************/
968 char *server_content_encoding(const struct parsers *v, const char *s, struct client_state *csp)
971 * Turn off pcrs and gif filtering if body compressed
973 if (strstr(s, "gzip") || strstr(s, "compress") || strstr(s, "deflate"))
975 csp->content_type = CT_TABOO;
983 /*********************************************************************
985 * Function : server_content_length
987 * Description : Adjust Content-Length header if we modified
992 * 2 : s = header string we are "considering"
993 * 3 : csp = Current client state (buffers, headers, etc...)
995 * Returns : A duplicate string pointer to this header (ie. pass thru)
997 *********************************************************************/
998 char *server_content_length(const struct parsers *v, const char *s, struct client_state *csp)
1000 if (csp->content_length != 0) /* Content length has been modified */
1002 char * s2 = (char *) zalloc(100);
1003 sprintf(s2, "Content-Length: %d", (int) csp->content_length);
1005 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1016 /*********************************************************************
1018 * Function : server_content_md5
1020 * Description : Crumble any Content-MD5 headers if the document was
1021 * modified. FIXME: Should we re-compute instead?
1025 * 2 : s = header string we are "considering"
1026 * 3 : csp = Current client state (buffers, headers, etc...)
1028 * Returns : A duplicate string pointer to this header (ie. pass thru)
1030 *********************************************************************/
1031 char *server_content_md5(const struct parsers *v, const char *s, struct client_state *csp)
1033 if (csp->flags & CSP_FLAG_MODIFIED)
1035 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1046 /*********************************************************************
1048 * Function : client_accept_encoding
1050 * Description : Rewrite the client's Accept-Encoding header so that
1051 * if doesn't allow compression, if the action applies.
1052 * Note: For HTTP/1.0 the absence of the header is enough.
1056 * 2 : s = header string we are "considering"
1057 * 3 : csp = Current client state (buffers, headers, etc...)
1059 * Returns : A copy of the client's original or the modified header.
1061 *********************************************************************/
1062 char *client_accept_encoding(const struct parsers *v, const char *s, struct client_state *csp)
1064 if ((csp->action->flags & ACTION_NO_COMPRESSION) == 0)
1070 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress content");
1072 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1074 return(strdup("Accept-Encoding: identity;q=1.0, *;q=0"));
1085 /*********************************************************************
1087 * Function : client_te
1089 * Description : Rewrite the client's TE header so that
1090 * if doesn't allow compression, if the action applies.
1094 * 2 : s = header string we are "considering"
1095 * 3 : csp = Current client state (buffers, headers, etc...)
1097 * Returns : A copy of the client's original or the modified header.
1099 *********************************************************************/
1100 char *client_te(const struct parsers *v, const char *s, struct client_state *csp)
1102 if ((csp->action->flags & ACTION_NO_COMPRESSION) == 0)
1108 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress transfer");
1114 /*********************************************************************
1116 * Function : client_referrer
1118 * Description : Handle the "referer" config setting properly.
1119 * Called from `sed'.
1123 * 2 : s = header (from sed) to "crunch"
1124 * 3 : csp = Current client state (buffers, headers, etc...)
1126 * Returns : NULL if crunched, or a malloc'ed string with the original
1127 * or modified header
1129 *********************************************************************/
1130 char *client_referrer(const struct parsers *v, const char *s, struct client_state *csp)
1132 const char * newval;
1134 #ifdef FEATURE_FORCE_LOAD
1135 /* Since the referrer can include the prefix even
1136 * even if the request itself is non-forced, we must
1137 * clean it unconditionally
1139 strclean(s, FORCE_PREFIX);
1140 #endif /* def FEATURE_FORCE_LOAD */
1143 * Are we sending referer?
1145 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1150 newval = csp->action->string[ACTION_STRING_REFERER];
1153 * Are we blocking referer?
1155 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1157 log_error(LOG_LEVEL_HEADER, "crunch!");
1162 * Are we forging referer?
1164 if (0 == strcmpic(newval, "forge"))
1167 * Forge a referer as http://[hostname:port of REQUEST]/
1168 * to fool stupid checks for in-site links
1170 log_error(LOG_LEVEL_HEADER, "crunch+forge!");
1171 s2 = strsav(NULL, "Referer: ");
1172 s2 = strsav(s2, "http://");
1173 s2 = strsav(s2, csp->http->hostport);
1174 s2 = strsav(s2, "/");
1179 * Have we got a fixed referer?
1181 if (0 == strncmpic(newval, "http://", 7))
1184 * We have a specific (fixed) referer we want to send.
1188 log_error(LOG_LEVEL_HEADER, "modified");
1190 s3 = strsav( NULL, "Referer: " );
1191 s3 = strsav( s3, newval );
1195 /* Should never get here! */
1196 log_error(LOG_LEVEL_ERROR, "Bad parameter: +referer{%s}", newval);
1199 * Forge is probably the best default.
1201 * Forge a referer as http://[hostname:port of REQUEST]/
1202 * to fool stupid checks for in-site links
1204 log_error(LOG_LEVEL_HEADER, "crunch+forge!");
1205 s2 = strsav(NULL, "Referer: ");
1206 s2 = strsav(s2, "http://");
1207 s2 = strsav(s2, csp->http->hostport);
1208 s2 = strsav(s2, "/");
1213 /*********************************************************************
1215 * Function : client_uagent
1217 * Description : Handle the "user-agent" config setting properly
1218 * and remember its original value to enable browser
1219 * bug workarounds. Called from `sed'.
1223 * 2 : s = header (from sed) to "crunch"
1224 * 3 : csp = Current client state (buffers, headers, etc...)
1226 * Returns : A malloc'ed pointer to the default agent, or
1227 * a malloc'ed string pointer to this header (ie. pass thru).
1229 *********************************************************************/
1230 char *client_uagent(const struct parsers *v, const char *s, struct client_state *csp)
1232 const char * newval;
1235 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1240 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1246 log_error(LOG_LEVEL_HEADER, "modified");
1248 s2 = strsav( NULL, "User-Agent: " );
1249 s2 = strsav( s2, newval );
1255 /*********************************************************************
1257 * Function : client_ua
1259 * Description : Handle "ua-" headers properly. Called from `sed'.
1263 * 2 : s = header (from sed) to "crunch"
1264 * 3 : csp = Current client state (buffers, headers, etc...)
1266 * Returns : NULL if crunched, or a malloc'ed string to original header
1268 *********************************************************************/
1269 char *client_ua(const struct parsers *v, const char *s, struct client_state *csp)
1271 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1277 log_error(LOG_LEVEL_HEADER, "crunch!");
1283 /*********************************************************************
1285 * Function : client_from
1287 * Description : Handle the "from" config setting properly.
1288 * Called from `sed'.
1292 * 2 : s = header (from sed) to "crunch"
1293 * 3 : csp = Current client state (buffers, headers, etc...)
1295 * Returns : NULL if crunched, or a malloc'ed string to
1296 * modified/original header.
1298 *********************************************************************/
1299 char *client_from(const struct parsers *v, const char *s, struct client_state *csp)
1301 const char * newval;
1304 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1309 newval = csp->action->string[ACTION_STRING_FROM];
1312 * Are we blocking referer?
1314 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1316 log_error(LOG_LEVEL_HEADER, "crunch!");
1320 log_error(LOG_LEVEL_HEADER, " modified");
1322 s2 = strsav( NULL, "From: " );
1323 s2 = strsav( s2, newval );
1329 /*********************************************************************
1331 * Function : client_send_cookie
1333 * Description : Handle the "cookie" header properly. Called from `sed'.
1334 * If cookie is accepted, add it to the cookie_list,
1335 * else we crunch it. Mmmmmmmmmmm ... cookie ......
1338 * 1 : v = pattern of cookie `sed' found matching
1339 * 2 : s = header (from sed) to "crunch"
1340 * 3 : csp = Current client state (buffers, headers, etc...)
1342 * Returns : Always NULL.
1344 *********************************************************************/
1345 char *client_send_cookie(const struct parsers *v, const char *s, struct client_state *csp)
1347 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
1349 enlist(csp->cookie_list, s + v->len + 1);
1353 log_error(LOG_LEVEL_HEADER, " crunch!");
1357 * Always return NULL here. The cookie header
1358 * will be sent at the end of the header.
1365 /*********************************************************************
1367 * Function : client_x_forwarded
1369 * Description : Handle the "x-forwarded-for" config setting properly,
1370 * also used in the add_client_headers list. Called from `sed'.
1374 * 2 : s = header (from sed) to "crunch"
1375 * 3 : csp = Current client state (buffers, headers, etc...)
1377 * Returns : Always NULL.
1379 *********************************************************************/
1380 char *client_x_forwarded(const struct parsers *v, const char *s, struct client_state *csp)
1382 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
1384 /* Save it so we can re-add it later */
1385 csp->x_forwarded = strdup(s);
1389 * Always return NULL, since this information
1390 * will be sent at the end of the header.
1397 /* the following functions add headers directly to the header list */
1399 /*********************************************************************
1401 * Function : client_host_adder
1403 * Description : (re)adds the host header. Called from `sed'.
1406 * 1 : csp = Current client state (buffers, headers, etc...)
1410 *********************************************************************/
1411 void client_host_adder(struct client_state *csp)
1415 p = strsav(p, "Host: ");
1416 p = strsav(p, csp->http->hostport);
1418 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1419 enlist(csp->headers, p);
1425 /*********************************************************************
1427 * Function : client_cookie_adder
1429 * Description : Used in the add_client_headers list. Called from `sed'.
1432 * 1 : csp = Current client state (buffers, headers, etc...)
1436 *********************************************************************/
1437 void client_cookie_adder(struct client_state *csp)
1439 struct list_entry *lst;
1443 for (lst = csp->cookie_list->first; lst ; lst = lst->next)
1447 tmp = strsav(tmp, "; ");
1449 tmp = strsav(tmp, lst->str);
1452 for (lst = csp->action->multi[ACTION_MULTI_WAFER]->first; lst ; lst = lst->next)
1456 tmp = strsav(tmp, "; ");
1459 if ((e = cookie_encode(lst->str)))
1461 tmp = strsav(tmp, e);
1470 ret = strdup("Cookie: ");
1471 ret = strsav(ret, tmp);
1472 log_error(LOG_LEVEL_HEADER, "addh: %s", ret);
1473 enlist(csp->headers, ret);
1481 /*********************************************************************
1483 * Function : client_accept_encoding_adder
1485 * Description : Add an Accept-Encoding header to the client's request
1486 * that disables compression if the action applies, and
1487 * the header is not already there. Called from `sed'.
1488 * Note: For HTTP/1.0, the absence of the header is enough.
1491 * 1 : csp = Current client state (buffers, headers, etc...)
1495 *********************************************************************/
1496 void client_accept_encoding_adder(struct client_state *csp)
1498 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1499 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
1501 enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
1507 /*********************************************************************
1509 * Function : client_xtra_adder
1511 * Description : Used in the add_client_headers list. Called from `sed'.
1514 * 1 : csp = Current client state (buffers, headers, etc...)
1518 *********************************************************************/
1519 void client_xtra_adder(struct client_state *csp)
1521 struct list_entry *lst;
1523 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
1524 lst ; lst = lst->next)
1526 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
1527 enlist(csp->headers, lst->str);
1533 /*********************************************************************
1535 * Function : client_x_forwarded_adder
1537 * Description : Used in the add_client_headers list. Called from `sed'.
1540 * 1 : csp = Current client state (buffers, headers, etc...)
1544 *********************************************************************/
1545 void client_x_forwarded_adder(struct client_state *csp)
1549 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
1554 if (csp->x_forwarded)
1556 p = strsav(p, csp->x_forwarded);
1557 p = strsav(p, ", ");
1558 p = strsav(p, csp->ip_addr_str);
1562 p = strsav(p, "X-Forwarded-For: ");
1563 p = strsav(p, csp->ip_addr_str);
1566 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1567 enlist(csp->headers, p);
1573 /*********************************************************************
1575 * Function : connection_close_adder
1577 * Description : Adds a "Connection: close" header to csp->headers
1578 * as a temporary fix for the needed but missing HTTP/1.1
1579 * support. Called from `sed'.
1580 * FIXME: This whole function shouldn't be neccessary!
1583 * 1 : csp = Current client state (buffers, headers, etc...)
1587 *********************************************************************/
1588 void connection_close_adder(struct client_state *csp)
1590 enlist(csp->headers, "Connection: close");
1594 /*********************************************************************
1596 * Function : server_http
1598 * Description : - Save the HTTP Status into csp->http->status
1599 * - Set CT_TABOO to prevent filtering if the answer
1600 * is a partial range (HTTP status 206)
1601 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
1605 * 1 : v = parser pattern that matched this header
1606 * 2 : s = header that matched this pattern
1607 * 3 : csp = Current client state (buffers, headers, etc...)
1609 * Returns : Copy of changed or original answer.
1611 *********************************************************************/
1612 char *server_http(const struct parsers *v, const char *s, struct client_state *csp)
1614 char *ret = strdup(s);
1616 sscanf(ret, "HTTP/%*d.%*d %d", &(csp->http->status));
1617 if (csp->http->status == 206)
1619 csp->content_type = CT_TABOO;
1622 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
1625 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
1632 /*********************************************************************
1634 * Function : server_set_cookie
1636 * Description : Handle the server "cookie" header properly.
1637 * Log cookie to the jar file. Then "crunch" it,
1638 * or accept it. Called from `sed'.
1641 * 1 : v = parser pattern that matched this header
1642 * 2 : s = header that matched this pattern
1643 * 3 : csp = Current client state (buffers, headers, etc...)
1645 * Returns : `crumble' or a newly malloc'ed string.
1647 *********************************************************************/
1648 char *server_set_cookie(const struct parsers *v, const char *s, struct client_state *csp)
1650 #ifdef FEATURE_COOKIE_JAR
1651 if (csp->config->jar)
1654 * Write timestamp into outbuf.
1656 * Complex because not all OSs have tm_gmtoff or
1657 * the %z field in strftime()
1659 char tempbuf[ BUFFER_SIZE ];
1663 tm_now = localtime (&now);
1664 strftime (tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", tm_now);
1666 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, (s + v->len + 1));
1668 #endif /* def FEATURE_COOKIE_JAR */
1670 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
1672 return(crumble(v, s, csp));
1674 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
1676 /* Flag whether or not to log a message */
1679 /* A variable to store the tag we're working on */
1682 /* Make a copy of the header we can write to */
1683 char * result = strdup(s);
1686 /* FIXME: This error handling is incorrect */
1690 /* Skip "Set-Cookie:" (11 characters) in header */
1691 cur_tag = result + 11;
1693 /* skip whitespace between "Set-Cookie:" and value */
1694 while (*cur_tag && ijb_isspace(*cur_tag))
1699 /* Loop through each tag in the cookie */
1703 char * next_tag = strchr(cur_tag, ';');
1704 if (next_tag != NULL)
1706 /* Skip the ';' character itself */
1709 /* skip whitespace ";" and start of tag */
1710 while (*next_tag && ijb_isspace(*next_tag))
1717 /* "Next tag" is the end of the string */
1718 next_tag = cur_tag + strlen(cur_tag);
1721 /* Is this the "Expires" tag? */
1722 if (strncmpic(cur_tag, "expires=", 8) == 0)
1724 /* Delete the tag by copying the rest of the string over it.
1725 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
1726 * since the behaviour of strcpy is undefined for overlapping
1729 memmove(cur_tag, next_tag, strlen(next_tag));
1731 /* That changed the header, need to issue a log message */
1734 /* Note that the next tag has now been moved to *cur_tag,
1735 * so we do not need to update the cur_tag pointer.
1740 /* Move on to next cookie tag */
1745 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
1754 #ifdef FEATURE_FORCE_LOAD
1755 /*********************************************************************
1757 * Function : strclean
1759 * Description : In-Situ-Eliminate all occurances of substring in
1763 * 1 : string = string to clean
1764 * 2 : substring = substring to eliminate
1766 * Returns : Number of eliminations
1768 *********************************************************************/
1769 int strclean(const char *string, const char *substring)
1771 int hits = 0, len = strlen(substring);
1774 while((pos = strstr(string, substring)))
1781 while (*p++ != '\0');
1788 #endif /* def FEATURE_FORCE_LOAD */