1 const char parsers_rcs[] = "$Id: parsers.c,v 1.43 2001/11/23 00:26:38 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.43 2001/11/23 00:26:38 jongfoster
45 * Fixing two really stupid errors in my previous commit
47 * Revision 1.42 2001/11/22 21:59:30 jongfoster
48 * Adding code to handle +no-cookies-keep
50 * Revision 1.41 2001/11/05 23:43:05 steudten
51 * Add time+date to log files.
53 * Revision 1.40 2001/10/26 20:13:09 jongfoster
54 * ctype.h is needed in Windows, too.
56 * Revision 1.39 2001/10/26 17:40:04 oes
57 * Introduced get_header_value()
58 * Removed http->user_agent, csp->referrer and csp->accept_types
59 * Removed client_accept()
61 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
62 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
63 * threads to call select() simultaneously. So, it's time to do a real, live,
64 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
65 * (native). Both versions will work, but using __OS2__ offers multi-threading.
67 * Revision 1.37 2001/10/23 21:36:02 jongfoster
68 * Documenting sed()'s error behaviou (doc change only)
70 * Revision 1.36 2001/10/13 12:51:51 joergs
71 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
72 * force-load), instead crumble Host: and add it (again) in client_host_adder
73 * (in case we get a HTTP/1.0 request without Host: header and forward it to
74 * a HTTP/1.1 server/proxy).
76 * Revision 1.35 2001/10/09 22:39:21 jongfoster
77 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
80 * Revision 1.34 2001/10/07 18:50:55 oes
81 * Added server_content_encoding, renamed server_transfer_encoding
83 * Revision 1.33 2001/10/07 18:04:49 oes
84 * Changed server_http11 to server_http and its pattern to "HTTP".
85 * Additional functionality: it now saves the HTTP status into
86 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
88 * Revision 1.32 2001/10/07 15:43:28 oes
89 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
90 * client_te and client_accept_encoding_adder, triggered by the new
91 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
92 * changed to allow only identity and chunked, and the TE header is
93 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
95 * parse_http_request no longer does anything than parsing. The rewriting
96 * of http->cmd and version mangling are gone. It now also recognizes
97 * the put and delete methods and saves the url in http->url. Removed
100 * renamed content_type and content_length to have the server_ prefix
102 * server_content_type now only works if csp->content_type != CT_TABOO
104 * added server_transfer_encoding, which
105 * - Sets CT_TABOO to prohibit filtering if encoding compresses
106 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
107 * - Change from "chunked" to "identity" if body was chunked
108 * but has been de-chunked for filtering.
110 * added server_content_md5 which crunches any Content-MD5 headers
111 * if the body was modified.
113 * made server_http11 conditional on +downgrade action
115 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
117 * Revision 1.31 2001/10/05 14:25:02 oes
118 * Crumble Keep-Alive from Server
120 * Revision 1.30 2001/09/29 12:56:03 joergs
121 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
123 * Revision 1.29 2001/09/24 21:09:24 jongfoster
124 * Fixing 2 memory leaks that Guy spotted, where the paramater to
125 * enlist() was not being free()d.
127 * Revision 1.28 2001/09/22 16:32:28 jongfoster
128 * Removing unused #includes.
130 * Revision 1.27 2001/09/20 15:45:25 steudten
132 * add casting from size_t to int for printf()
133 * remove local variable shadow s2
135 * Revision 1.26 2001/09/16 17:05:14 jongfoster
136 * Removing unused #include showarg.h
138 * Revision 1.25 2001/09/16 13:21:27 jongfoster
139 * Changes to use new list functions.
141 * Revision 1.24 2001/09/13 23:05:50 jongfoster
142 * Changing the string paramater to the header parsers a "const".
144 * Revision 1.23 2001/09/12 18:08:19 steudten
146 * In parse_http_request() header rewriting miss the host value, so
147 * from http://www.mydomain.com the result was just " / " not
148 * http://www.mydomain.com/ in case we forward.
150 * Revision 1.22 2001/09/10 10:58:53 oes
151 * Silenced compiler warnings
153 * Revision 1.21 2001/07/31 14:46:00 oes
154 * - Persistant connections now suppressed
155 * - sed() no longer appends empty header to csp->headers
157 * Revision 1.20 2001/07/30 22:08:36 jongfoster
158 * Tidying up #defines:
159 * - All feature #defines are now of the form FEATURE_xxx
160 * - Permanently turned off WIN_GUI_EDIT
161 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
163 * Revision 1.19 2001/07/25 17:21:54 oes
164 * client_uagent now saves copy of User-Agent: header value
166 * Revision 1.18 2001/07/13 14:02:46 oes
167 * - Included fix to repair broken HTTP requests that
168 * don't contain a path, not even '/'.
169 * - Removed all #ifdef PCRS
170 * - content_type now always inspected and classified as
171 * text, gif or other.
172 * - formatting / comments
174 * Revision 1.17 2001/06/29 21:45:41 oes
175 * Indentation, CRLF->LF, Tab-> Space
177 * Revision 1.16 2001/06/29 13:32:42 oes
179 * - Adapted free_http_request
180 * - Removed logentry from cancelled commit
182 * Revision 1.15 2001/06/03 19:12:38 oes
183 * deleted const struct interceptors
185 * Revision 1.14 2001/06/01 18:49:17 jongfoster
186 * Replaced "list_share" with "list" - the tiny memory gain was not
187 * worth the extra complexity.
189 * Revision 1.13 2001/05/31 21:30:33 jongfoster
190 * Removed list code - it's now in list.[ch]
191 * Renamed "permission" to "action", and changed many features
192 * to use the actions file rather than the global config.
194 * Revision 1.12 2001/05/31 17:33:13 oes
198 * Revision 1.11 2001/05/29 20:11:19 joergs
199 * '/ * inside comment' warning removed.
201 * Revision 1.10 2001/05/29 09:50:24 jongfoster
202 * Unified blocklist/imagelist/permissionslist.
203 * File format is still under discussion, but the internal changes
206 * Also modified interceptor behaviour:
207 * - We now intercept all URLs beginning with one of the following
208 * prefixes (and *only* these prefixes):
210 * * http://ijbswa.sf.net/config/
211 * * http://ijbswa.sourceforge.net/config/
212 * - New interceptors "home page" - go to http://i.j.b/ to see it.
213 * - Internal changes so that intercepted and fast redirect pages
214 * are not replaced with an image.
215 * - Interceptors now have the option to send a binary page direct
216 * to the client. (i.e. ijb-send-banner uses this)
217 * - Implemented show-url-info interceptor. (Which is why I needed
218 * the above interceptors changes - a typical URL is
219 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
220 * The previous mechanism would not have intercepted that, and
221 * if it had been intercepted then it then it would have replaced
224 * Revision 1.9 2001/05/28 17:26:33 jongfoster
225 * Fixing segfault if last header was crunched.
226 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
227 * can use the cross-platform sprintf() instead.)
229 * Revision 1.8 2001/05/27 22:17:04 oes
231 * - re_process_buffer no longer writes the modified buffer
232 * to the client, which was very ugly. It now returns the
233 * buffer, which it is then written by chat.
235 * - content_length now adjusts the Content-Length: header
236 * for modified documents rather than crunch()ing it.
237 * (Length info in csp->content_length, which is 0 for
238 * unmodified documents)
240 * - For this to work, sed() is called twice when filtering.
242 * Revision 1.7 2001/05/27 13:19:06 oes
243 * Patched Joergs solution for the content-length in.
245 * Revision 1.6 2001/05/26 13:39:32 jongfoster
246 * Only crunches Content-Length header if applying RE filtering.
247 * Without this fix, Microsoft Windows Update wouldn't work.
249 * Revision 1.5 2001/05/26 00:28:36 jongfoster
250 * Automatic reloading of config file.
251 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
252 * Most of the global variables have been moved to a new
253 * struct configuration_spec, accessed through csp->config->globalname
254 * Most of the globals remaining are used by the Win32 GUI.
256 * Revision 1.4 2001/05/22 18:46:04 oes
258 * - Enabled filtering banners by size rather than URL
259 * by adding patterns that replace all standard banner
260 * sizes with the "Junkbuster" gif to the re_filterfile
262 * - Enabled filtering WebBugs by providing a pattern
263 * which kills all 1x1 images
265 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
266 * which is selected by the (nonstandard and therefore
267 * capital) letter 'U' in the option string.
268 * It causes the quantifiers to be ungreedy by default.
269 * Appending a ? turns back to greedy (!).
271 * - Added a new interceptor ijb-send-banner, which
272 * sends back the "Junkbuster" gif. Without imagelist or
273 * MSIE detection support, or if tinygif = 1, or the
274 * URL isn't recognized as an imageurl, a lame HTML
275 * explanation is sent instead.
277 * - Added new feature, which permits blocking remote
278 * script redirects and firing back a local redirect
280 * The feature is conditionally compiled, i.e. it
281 * can be disabled with --disable-fast-redirects,
282 * plus it must be activated by a "fast-redirects"
283 * line in the config file, has its own log level
284 * and of course wants to be displayed by show-proxy-args
285 * Note: Boy, all the #ifdefs in 1001 locations and
286 * all the fumbling with configure.in and acconfig.h
287 * were *way* more work than the feature itself :-(
289 * - Because a generic redirect template was needed for
290 * this, tinygif = 3 now uses the same.
292 * - Moved GIFs, and other static HTTP response templates
297 * - Removed some >400 CRs again (Jon, you really worked
300 * Revision 1.3 2001/05/20 01:21:20 jongfoster
301 * Version 2.9.4 checkin.
302 * - Merged popupfile and cookiefile, and added control over PCRS
303 * filtering, in new "permissionsfile".
304 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
305 * file error you now get a message box (in the Win32 GUI) rather
306 * than the program exiting with no explanation.
307 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
309 * - Removed tabs from "config"
310 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
311 * - Bumped up version number.
313 * Revision 1.2 2001/05/17 23:02:36 oes
314 * - Made referrer option accept 'L' as a substitute for '§'
316 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
317 * Initial import of version 2.9.3 source tree
320 *********************************************************************/
327 #include <sys/types.h>
335 #if !defined(_WIN32) && !defined(__OS2__)
345 #include "jbsockets.h"
346 #include "miscutil.h"
349 const char parsers_h_rcs[] = PARSERS_H_VERSION;
351 /* Fix a problem with Solaris. There should be no effect on other
353 * Solaris's isspace() is a macro which uses it's argument directly
354 * as an array index. Therefore we need to make sure that high-bit
355 * characters generate +ve values, and ideally we also want to make
356 * the argument match the declared parameter type of "int".
358 * Why did they write a character function that can't take a simple
359 * "char" argument? Doh!
361 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
362 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
365 const struct parsers client_patterns[] = {
366 { "referer:", 8, client_referrer },
367 { "user-agent:", 11, client_uagent },
368 { "ua-", 3, client_ua },
369 { "from:", 5, client_from },
370 { "cookie:", 7, client_send_cookie },
371 { "x-forwarded-for:", 16, client_x_forwarded },
372 { "Accept-Encoding:", 16, client_accept_encoding },
373 { "TE:", 3, client_te },
374 { "Host:", 5, crumble },
375 /* { "if-modified-since:", 18, crumble }, */
376 { "Keep-Alive:", 11, crumble },
377 { "connection:", 11, crumble },
378 { "proxy-connection:", 17, crumble },
383 const struct parsers server_patterns[] = {
384 { "HTTP", 4, server_http },
385 { "set-cookie:", 11, server_set_cookie },
386 { "connection:", 11, crumble },
387 { "Content-Type:", 13, server_content_type },
388 { "Content-Length:", 15, server_content_length },
389 { "Content-MD5:", 12, server_content_md5 },
390 { "Content-Encoding:", 17, server_content_encoding },
391 { "Transfer-Encoding:", 18, server_transfer_coding },
392 { "Keep-Alive:", 11, crumble },
397 void (* const add_client_headers[])(struct client_state *) = {
400 client_x_forwarded_adder,
402 client_accept_encoding_adder,
403 connection_close_adder,
408 void (* const add_server_headers[])(struct client_state *) = {
409 connection_close_adder,
414 /*********************************************************************
416 * Function : flush_socket
418 * Description : Write any pending "buffered" content.
421 * 1 : fd = file descriptor of the socket to read
422 * 2 : csp = Current client state (buffers, headers, etc...)
424 * Returns : On success, the number of bytes written are returned (zero
425 * indicates nothing was written). On error, -1 is returned,
426 * and errno is set appropriately. If count is zero and the
427 * file descriptor refers to a regular file, 0 will be
428 * returned without causing any other effect. For a special
429 * file, the results are not portable.
431 *********************************************************************/
432 int flush_socket(int fd, struct client_state *csp)
434 struct iob *iob = csp->iob;
435 int n = iob->eod - iob->cur;
442 n = write_socket(fd, iob->cur, n);
443 iob->eod = iob->cur = iob->buf;
449 /*********************************************************************
451 * Function : add_to_iob
453 * Description : Add content to the buffered page.
456 * 1 : csp = Current client state (buffers, headers, etc...)
457 * 2 : buf = holds the content to be added to the page
458 * 3 : n = number of bytes to be added
460 * Returns : Number of bytes in the content buffer.
462 *********************************************************************/
463 int add_to_iob(struct client_state *csp, char *buf, int n)
465 struct iob *iob = csp->iob;
469 have = iob->eod - iob->cur;
478 if ((p = (char *)malloc(need + 1)) == NULL)
480 log_error(LOG_LEVEL_ERROR, "malloc() iob failed: %E");
486 /* there is something in the buffer - save it */
487 memcpy(p, iob->cur, have);
489 /* replace the buffer with the new space */
493 /* point to the end of the data */
498 /* the buffer is empty, free it and reinitialize */
503 /* copy the new data into the iob buffer */
506 /* point to the end of the data */
509 /* null terminate == cheap insurance */
512 /* set the pointers to the new values */
521 /*********************************************************************
523 * Function : get_header
525 * Description : This (odd) routine will parse the csp->iob
528 * 1 : csp = Current client state (buffers, headers, etc...)
530 * Returns : Any one of the following:
532 * 1) a pointer to a dynamically allocated string that contains a header line
533 * 2) NULL indicating that the end of the header was reached
534 * 3) "" indicating that the end of the iob was reached before finding
535 * a complete header line.
537 *********************************************************************/
538 char *get_header(struct client_state *csp)
544 if ((iob->cur == NULL)
545 || ((p = strchr(iob->cur, '\n')) == NULL))
547 return(""); /* couldn't find a complete header */
552 ret = strdup(iob->cur);
556 if ((q = strchr(ret, '\r'))) *q = '\0';
558 /* is this a blank linke (i.e. the end of the header) ? */
570 /*********************************************************************
572 * Function : get_header_value
574 * Description : Get the value of a given header from a chained list
575 * of header lines or return NULL if no such header is
576 * present in the list.
579 * 1 : header_list = pointer to list
580 * 2 : header_name = string with name of header to look for.
581 * Trailing colon required, capitalization
584 * Returns : NULL if not found, else value of header
586 *********************************************************************/
587 char *get_header_value(const struct list *header_list, const char *header_name)
589 struct list_entry *cur_entry;
595 length = strlen(header_name);
597 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
601 if (!strncmpic(cur_entry->str, header_name, length))
604 * Found: return pointer to start of value
606 ret = (char *) (cur_entry->str + length);
607 while (*ret && ijb_isspace(*ret)) ret++;
620 /*********************************************************************
624 * Description : add, delete or modify lines in the HTTP header streams.
625 * On entry, it receives a linked list of headers space
626 * that was allocated dynamically (both the list nodes
627 * and the header contents).
629 * As a side effect it frees the space used by the original
633 * 1 : pats = list of patterns to match against headers
634 * 2 : more_headers = list of functions to add more
635 * headers (client or server)
636 * 3 : csp = Current client state (buffers, headers, etc...)
638 * Returns : Single pointer to a fully formed header, or NULL
639 * on out-of-memory error.
641 *********************************************************************/
642 char *sed(const struct parsers pats[], void (* const more_headers[])(struct client_state *), struct client_state *csp)
644 struct list_entry *p;
645 const struct parsers *v;
649 for (v = pats; v->str ; v++)
651 for (p = csp->headers->first; p ; p = p->next)
653 /* Header crunch()ed in previous run? -> ignore */
654 if (p->str == NULL) continue;
656 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
658 if (strncmpic(p->str, v->str, v->len) == 0)
660 hdr = v->parser(v, p->str, csp);
661 freez(p->str); /* FIXME: Yuck! patching a list...*/
667 /* place any additional headers on the csp->headers list */
668 for (f = more_headers; *f ; f++)
673 hdr = list_to_text(csp->headers);
680 /*********************************************************************
682 * Function : free_http_request
684 * Description : Freez a http_request structure
687 * 1 : http = points to a http_request structure to free
691 *********************************************************************/
692 void free_http_request(struct http_request *http)
700 freez(http->hostport);
703 freez(http->host_ip_addr_str);
708 /*********************************************************************
710 * Function : parse_http_request
712 * Description : Parse out the host and port from the URL. Find the
713 * hostname & path, port (if ':'), and/or password (if '@')
716 * 1 : req = URL (or is it URI?) to break down
717 * 2 : http = pointer to the http structure to hold elements
718 * 3 : csp = Current client state (buffers, headers, etc...)
722 *********************************************************************/
723 void parse_http_request(char *req, struct http_request *http, struct client_state *csp)
725 char *buf, *v[10], *url, *p;
728 memset(http, '\0', sizeof(*http));
729 http->cmd = strdup(req);
732 n = ssplit(buf, " \r\n", v, SZ(v), 1, 1);
736 /* this could be a CONNECT request */
737 if (strcmpic(v[0], "connect") == 0)
740 http->gpc = strdup(v[0]);
741 http->hostport = strdup(v[1]);
742 http->ver = strdup(v[2]);
745 /* or it could be any other basic HTTP request type */
746 if ((0 == strcmpic(v[0], "get"))
747 || (0 == strcmpic(v[0], "head"))
748 || (0 == strcmpic(v[0], "post"))
749 || (0 == strcmpic(v[0], "put"))
750 || (0 == strcmpic(v[0], "delete"))
752 /* or a webDAV extension (RFC2518) */
753 || (0 == strcmpic(v[0], "propfind"))
754 || (0 == strcmpic(v[0], "proppatch"))
755 || (0 == strcmpic(v[0], "move"))
756 || (0 == strcmpic(v[0], "copy"))
757 || (0 == strcmpic(v[0], "mkcol"))
758 || (0 == strcmpic(v[0], "lock"))
759 || (0 == strcmpic(v[0], "unlock"))
763 http->gpc = strdup(v[0]);
764 http->url = strdup(v[1]);
765 http->ver = strdup(v[2]);
768 if (strncmpic(url, "http://", 7) == 0)
772 else if (strncmpic(url, "https://", 8) == 0)
783 if ((p = strchr(url, '/')))
785 http->path = strdup(p);
787 http->hostport = strdup(url);
790 * Repair broken HTTP requests that don't contain a path
794 http->path = strdup("/");
795 http->hostport = strdup(url);
804 if (http->hostport == NULL)
806 free_http_request(http);
810 buf = strdup(http->hostport);
813 /* check if url contains password */
814 n = ssplit(buf, "@", v, SZ(v), 1, 1);
817 char * newbuf = NULL;
818 newbuf = strdup(v[1]);
823 n = ssplit(buf, ":", v, SZ(v), 1, 1);
827 http->host = strdup(v[0]);
833 http->host = strdup(v[0]);
834 http->port = atoi(v[1]);
839 if (http->host == NULL)
841 free_http_request(http);
844 if (http->path == NULL)
846 http->path = strdup("/");
852 /* here begins the family of parser functions that reformat header lines */
855 /*********************************************************************
859 * Description : This is called if a header matches a pattern to "crunch"
862 * 1 : v = Pointer to parsers structure, which basically holds
863 * headers (client or server) that we want to "crunch"
864 * 2 : s = header (from sed) to "crunch"
865 * 3 : csp = Current client state (buffers, headers, etc...)
867 * Returns : Always NULL.
869 *********************************************************************/
870 char *crumble(const struct parsers *v, const char *s, struct client_state *csp)
872 log_error(LOG_LEVEL_HEADER, "crunch!");
878 /*********************************************************************
880 * Function : server_content_type
882 * Description : Set the content-type for filterable types (text/.*,
883 * javascript and image/gif) unless filtering has been
884 * forbidden (CT_TABOO) while parsing earlier headers.
888 * 2 : s = header string we are "considering"
889 * 3 : csp = Current client state (buffers, headers, etc...)
891 * Returns : A duplicate string pointer to this header (ie. pass thru)
893 *********************************************************************/
894 char *server_content_type(const struct parsers *v, const char *s, struct client_state *csp)
896 if (csp->content_type != CT_TABOO)
898 if (strstr(s, " text/") || strstr(s, "application/x-javascript"))
899 csp->content_type = CT_TEXT;
900 else if (strstr(s, " image/gif"))
901 csp->content_type = CT_GIF;
903 csp->content_type = 0;
911 /*********************************************************************
913 * Function : server_transfer_coding
915 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
916 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
917 * - Change from "chunked" to "identity" if body was chunked
918 * but has been de-chunked for filtering.
922 * 2 : s = header string we are "considering"
923 * 3 : csp = Current client state (buffers, headers, etc...)
925 * Returns : A duplicate string pointer to this header (ie. pass thru)
927 *********************************************************************/
928 char *server_transfer_coding(const struct parsers *v, const char *s, struct client_state *csp)
931 * Turn off pcrs and gif filtering if body compressed
933 if (strstr(s, "gzip") || strstr(s, "compress") || strstr(s, "deflate"))
935 csp->content_type = CT_TABOO;
939 * Raise flag if body chunked
941 if (strstr(s, "chunked"))
943 csp->flags |= CSP_FLAG_CHUNKED;
946 * If the body was modified, it has been
947 * de-chunked first, so adjust the header:
949 if (csp->flags & CSP_FLAG_MODIFIED)
951 return(strdup("Transfer-Encoding: identity"));
960 /*********************************************************************
962 * Function : server_content_encoding
964 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
968 * 2 : s = header string we are "considering"
969 * 3 : csp = Current client state (buffers, headers, etc...)
971 * Returns : A duplicate string pointer to this header (ie. pass thru)
973 *********************************************************************/
974 char *server_content_encoding(const struct parsers *v, const char *s, struct client_state *csp)
977 * Turn off pcrs and gif filtering if body compressed
979 if (strstr(s, "gzip") || strstr(s, "compress") || strstr(s, "deflate"))
981 csp->content_type = CT_TABOO;
989 /*********************************************************************
991 * Function : server_content_length
993 * Description : Adjust Content-Length header if we modified
998 * 2 : s = header string we are "considering"
999 * 3 : csp = Current client state (buffers, headers, etc...)
1001 * Returns : A duplicate string pointer to this header (ie. pass thru)
1003 *********************************************************************/
1004 char *server_content_length(const struct parsers *v, const char *s, struct client_state *csp)
1006 if (csp->content_length != 0) /* Content length has been modified */
1008 char * s2 = (char *) zalloc(100);
1009 sprintf(s2, "Content-Length: %d", (int) csp->content_length);
1011 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1022 /*********************************************************************
1024 * Function : server_content_md5
1026 * Description : Crumble any Content-MD5 headers if the document was
1027 * modified. FIXME: Should we re-compute instead?
1031 * 2 : s = header string we are "considering"
1032 * 3 : csp = Current client state (buffers, headers, etc...)
1034 * Returns : A duplicate string pointer to this header (ie. pass thru)
1036 *********************************************************************/
1037 char *server_content_md5(const struct parsers *v, const char *s, struct client_state *csp)
1039 if (csp->flags & CSP_FLAG_MODIFIED)
1041 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1052 /*********************************************************************
1054 * Function : client_accept_encoding
1056 * Description : Rewrite the client's Accept-Encoding header so that
1057 * if doesn't allow compression, if the action applies.
1058 * Note: For HTTP/1.0 the absence of the header is enough.
1062 * 2 : s = header string we are "considering"
1063 * 3 : csp = Current client state (buffers, headers, etc...)
1065 * Returns : A copy of the client's original or the modified header.
1067 *********************************************************************/
1068 char *client_accept_encoding(const struct parsers *v, const char *s, struct client_state *csp)
1070 if ((csp->action->flags & ACTION_NO_COMPRESSION) == 0)
1076 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress content");
1078 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1080 return(strdup("Accept-Encoding: identity;q=1.0, *;q=0"));
1091 /*********************************************************************
1093 * Function : client_te
1095 * Description : Rewrite the client's TE header so that
1096 * if doesn't allow compression, if the action applies.
1100 * 2 : s = header string we are "considering"
1101 * 3 : csp = Current client state (buffers, headers, etc...)
1103 * Returns : A copy of the client's original or the modified header.
1105 *********************************************************************/
1106 char *client_te(const struct parsers *v, const char *s, struct client_state *csp)
1108 if ((csp->action->flags & ACTION_NO_COMPRESSION) == 0)
1114 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress transfer");
1120 /*********************************************************************
1122 * Function : client_referrer
1124 * Description : Handle the "referer" config setting properly.
1125 * Called from `sed'.
1129 * 2 : s = header (from sed) to "crunch"
1130 * 3 : csp = Current client state (buffers, headers, etc...)
1132 * Returns : NULL if crunched, or a malloc'ed string with the original
1133 * or modified header
1135 *********************************************************************/
1136 char *client_referrer(const struct parsers *v, const char *s, struct client_state *csp)
1138 const char * newval;
1140 #ifdef FEATURE_FORCE_LOAD
1141 /* Since the referrer can include the prefix even
1142 * even if the request itself is non-forced, we must
1143 * clean it unconditionally
1145 strclean(s, FORCE_PREFIX);
1146 #endif /* def FEATURE_FORCE_LOAD */
1149 * Are we sending referer?
1151 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1156 newval = csp->action->string[ACTION_STRING_REFERER];
1159 * Are we blocking referer?
1161 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1163 log_error(LOG_LEVEL_HEADER, "crunch!");
1168 * Are we forging referer?
1170 if (0 == strcmpic(newval, "forge"))
1173 * Forge a referer as http://[hostname:port of REQUEST]/
1174 * to fool stupid checks for in-site links
1176 log_error(LOG_LEVEL_HEADER, "crunch+forge!");
1177 s2 = strsav(NULL, "Referer: ");
1178 s2 = strsav(s2, "http://");
1179 s2 = strsav(s2, csp->http->hostport);
1180 s2 = strsav(s2, "/");
1185 * Have we got a fixed referer?
1187 if (0 == strncmpic(newval, "http://", 7))
1190 * We have a specific (fixed) referer we want to send.
1194 log_error(LOG_LEVEL_HEADER, "modified");
1196 s3 = strsav( NULL, "Referer: " );
1197 s3 = strsav( s3, newval );
1201 /* Should never get here! */
1202 log_error(LOG_LEVEL_ERROR, "Bad parameter: +referer{%s}", newval);
1205 * Forge is probably the best default.
1207 * Forge a referer as http://[hostname:port of REQUEST]/
1208 * to fool stupid checks for in-site links
1210 log_error(LOG_LEVEL_HEADER, "crunch+forge!");
1211 s2 = strsav(NULL, "Referer: ");
1212 s2 = strsav(s2, "http://");
1213 s2 = strsav(s2, csp->http->hostport);
1214 s2 = strsav(s2, "/");
1219 /*********************************************************************
1221 * Function : client_uagent
1223 * Description : Handle the "user-agent" config setting properly
1224 * and remember its original value to enable browser
1225 * bug workarounds. Called from `sed'.
1229 * 2 : s = header (from sed) to "crunch"
1230 * 3 : csp = Current client state (buffers, headers, etc...)
1232 * Returns : A malloc'ed pointer to the default agent, or
1233 * a malloc'ed string pointer to this header (ie. pass thru).
1235 *********************************************************************/
1236 char *client_uagent(const struct parsers *v, const char *s, struct client_state *csp)
1238 const char * newval;
1241 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1246 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1252 log_error(LOG_LEVEL_HEADER, "modified");
1254 s2 = strsav( NULL, "User-Agent: " );
1255 s2 = strsav( s2, newval );
1261 /*********************************************************************
1263 * Function : client_ua
1265 * Description : Handle "ua-" headers properly. Called from `sed'.
1269 * 2 : s = header (from sed) to "crunch"
1270 * 3 : csp = Current client state (buffers, headers, etc...)
1272 * Returns : NULL if crunched, or a malloc'ed string to original header
1274 *********************************************************************/
1275 char *client_ua(const struct parsers *v, const char *s, struct client_state *csp)
1277 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1283 log_error(LOG_LEVEL_HEADER, "crunch!");
1289 /*********************************************************************
1291 * Function : client_from
1293 * Description : Handle the "from" config setting properly.
1294 * Called from `sed'.
1298 * 2 : s = header (from sed) to "crunch"
1299 * 3 : csp = Current client state (buffers, headers, etc...)
1301 * Returns : NULL if crunched, or a malloc'ed string to
1302 * modified/original header.
1304 *********************************************************************/
1305 char *client_from(const struct parsers *v, const char *s, struct client_state *csp)
1307 const char * newval;
1310 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1315 newval = csp->action->string[ACTION_STRING_FROM];
1318 * Are we blocking referer?
1320 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1322 log_error(LOG_LEVEL_HEADER, "crunch!");
1326 log_error(LOG_LEVEL_HEADER, " modified");
1328 s2 = strsav( NULL, "From: " );
1329 s2 = strsav( s2, newval );
1335 /*********************************************************************
1337 * Function : client_send_cookie
1339 * Description : Handle the "cookie" header properly. Called from `sed'.
1340 * If cookie is accepted, add it to the cookie_list,
1341 * else we crunch it. Mmmmmmmmmmm ... cookie ......
1344 * 1 : v = pattern of cookie `sed' found matching
1345 * 2 : s = header (from sed) to "crunch"
1346 * 3 : csp = Current client state (buffers, headers, etc...)
1348 * Returns : Always NULL.
1350 *********************************************************************/
1351 char *client_send_cookie(const struct parsers *v, const char *s, struct client_state *csp)
1353 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
1355 enlist(csp->cookie_list, s + v->len + 1);
1359 log_error(LOG_LEVEL_HEADER, " crunch!");
1363 * Always return NULL here. The cookie header
1364 * will be sent at the end of the header.
1371 /*********************************************************************
1373 * Function : client_x_forwarded
1375 * Description : Handle the "x-forwarded-for" config setting properly,
1376 * also used in the add_client_headers list. Called from `sed'.
1380 * 2 : s = header (from sed) to "crunch"
1381 * 3 : csp = Current client state (buffers, headers, etc...)
1383 * Returns : Always NULL.
1385 *********************************************************************/
1386 char *client_x_forwarded(const struct parsers *v, const char *s, struct client_state *csp)
1388 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
1390 /* Save it so we can re-add it later */
1391 csp->x_forwarded = strdup(s);
1395 * Always return NULL, since this information
1396 * will be sent at the end of the header.
1403 /* the following functions add headers directly to the header list */
1405 /*********************************************************************
1407 * Function : client_host_adder
1409 * Description : (re)adds the host header. Called from `sed'.
1412 * 1 : csp = Current client state (buffers, headers, etc...)
1416 *********************************************************************/
1417 void client_host_adder(struct client_state *csp)
1422 if ( !csp->http->hostport || !*(csp->http->hostport)) return;
1423 p = strsav(p, "Host: ");
1425 ** remove 'user:pass@' from 'proto://user:pass@host'
1427 if ( (pos = strchr( csp->http->hostport, '@')) != NULL )
1429 p = strsav(p, pos+1);
1433 p = strsav(p, csp->http->hostport);
1435 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1436 enlist(csp->headers, p);
1442 /*********************************************************************
1444 * Function : client_cookie_adder
1446 * Description : Used in the add_client_headers list. Called from `sed'.
1449 * 1 : csp = Current client state (buffers, headers, etc...)
1453 *********************************************************************/
1454 void client_cookie_adder(struct client_state *csp)
1456 struct list_entry *lst;
1460 for (lst = csp->cookie_list->first; lst ; lst = lst->next)
1464 tmp = strsav(tmp, "; ");
1466 tmp = strsav(tmp, lst->str);
1469 for (lst = csp->action->multi[ACTION_MULTI_WAFER]->first; lst ; lst = lst->next)
1473 tmp = strsav(tmp, "; ");
1476 if ((e = cookie_encode(lst->str)))
1478 tmp = strsav(tmp, e);
1487 ret = strdup("Cookie: ");
1488 ret = strsav(ret, tmp);
1489 log_error(LOG_LEVEL_HEADER, "addh: %s", ret);
1490 enlist(csp->headers, ret);
1498 /*********************************************************************
1500 * Function : client_accept_encoding_adder
1502 * Description : Add an Accept-Encoding header to the client's request
1503 * that disables compression if the action applies, and
1504 * the header is not already there. Called from `sed'.
1505 * Note: For HTTP/1.0, the absence of the header is enough.
1508 * 1 : csp = Current client state (buffers, headers, etc...)
1512 *********************************************************************/
1513 void client_accept_encoding_adder(struct client_state *csp)
1515 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1516 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
1518 enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
1524 /*********************************************************************
1526 * Function : client_xtra_adder
1528 * Description : Used in the add_client_headers list. Called from `sed'.
1531 * 1 : csp = Current client state (buffers, headers, etc...)
1535 *********************************************************************/
1536 void client_xtra_adder(struct client_state *csp)
1538 struct list_entry *lst;
1540 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
1541 lst ; lst = lst->next)
1543 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
1544 enlist(csp->headers, lst->str);
1550 /*********************************************************************
1552 * Function : client_x_forwarded_adder
1554 * Description : Used in the add_client_headers list. Called from `sed'.
1557 * 1 : csp = Current client state (buffers, headers, etc...)
1561 *********************************************************************/
1562 void client_x_forwarded_adder(struct client_state *csp)
1566 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
1571 if (csp->x_forwarded)
1573 p = strsav(p, csp->x_forwarded);
1574 p = strsav(p, ", ");
1575 p = strsav(p, csp->ip_addr_str);
1579 p = strsav(p, "X-Forwarded-For: ");
1580 p = strsav(p, csp->ip_addr_str);
1583 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1584 enlist(csp->headers, p);
1590 /*********************************************************************
1592 * Function : connection_close_adder
1594 * Description : Adds a "Connection: close" header to csp->headers
1595 * as a temporary fix for the needed but missing HTTP/1.1
1596 * support. Called from `sed'.
1597 * FIXME: This whole function shouldn't be neccessary!
1600 * 1 : csp = Current client state (buffers, headers, etc...)
1604 *********************************************************************/
1605 void connection_close_adder(struct client_state *csp)
1607 enlist(csp->headers, "Connection: close");
1611 /*********************************************************************
1613 * Function : server_http
1615 * Description : - Save the HTTP Status into csp->http->status
1616 * - Set CT_TABOO to prevent filtering if the answer
1617 * is a partial range (HTTP status 206)
1618 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
1622 * 1 : v = parser pattern that matched this header
1623 * 2 : s = header that matched this pattern
1624 * 3 : csp = Current client state (buffers, headers, etc...)
1626 * Returns : Copy of changed or original answer.
1628 *********************************************************************/
1629 char *server_http(const struct parsers *v, const char *s, struct client_state *csp)
1631 char *ret = strdup(s);
1633 sscanf(ret, "HTTP/%*d.%*d %d", &(csp->http->status));
1634 if (csp->http->status == 206)
1636 csp->content_type = CT_TABOO;
1639 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
1642 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
1649 /*********************************************************************
1651 * Function : server_set_cookie
1653 * Description : Handle the server "cookie" header properly.
1654 * Log cookie to the jar file. Then "crunch" it,
1655 * or accept it. Called from `sed'.
1658 * 1 : v = parser pattern that matched this header
1659 * 2 : s = header that matched this pattern
1660 * 3 : csp = Current client state (buffers, headers, etc...)
1662 * Returns : `crumble' or a newly malloc'ed string.
1664 *********************************************************************/
1665 char *server_set_cookie(const struct parsers *v, const char *s, struct client_state *csp)
1667 #ifdef FEATURE_COOKIE_JAR
1668 if (csp->config->jar)
1671 * Write timestamp into outbuf.
1673 * Complex because not all OSs have tm_gmtoff or
1674 * the %z field in strftime()
1676 char tempbuf[ BUFFER_SIZE ];
1680 tm_now = localtime (&now);
1681 strftime (tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", tm_now);
1683 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, (s + v->len + 1));
1685 #endif /* def FEATURE_COOKIE_JAR */
1687 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
1689 return(crumble(v, s, csp));
1691 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
1693 /* Flag whether or not to log a message */
1696 /* A variable to store the tag we're working on */
1699 /* Make a copy of the header we can write to */
1700 char * result = strdup(s);
1703 /* FIXME: This error handling is incorrect */
1707 /* Skip "Set-Cookie:" (11 characters) in header */
1708 cur_tag = result + 11;
1710 /* skip whitespace between "Set-Cookie:" and value */
1711 while (*cur_tag && ijb_isspace(*cur_tag))
1716 /* Loop through each tag in the cookie */
1720 char * next_tag = strchr(cur_tag, ';');
1721 if (next_tag != NULL)
1723 /* Skip the ';' character itself */
1726 /* skip whitespace ";" and start of tag */
1727 while (*next_tag && ijb_isspace(*next_tag))
1734 /* "Next tag" is the end of the string */
1735 next_tag = cur_tag + strlen(cur_tag);
1738 /* Is this the "Expires" tag? */
1739 if (strncmpic(cur_tag, "expires=", 8) == 0)
1741 /* Delete the tag by copying the rest of the string over it.
1742 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
1743 * since the behaviour of strcpy is undefined for overlapping
1746 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
1748 /* That changed the header, need to issue a log message */
1751 /* Note that the next tag has now been moved to *cur_tag,
1752 * so we do not need to update the cur_tag pointer.
1757 /* Move on to next cookie tag */
1764 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
1774 #ifdef FEATURE_FORCE_LOAD
1775 /*********************************************************************
1777 * Function : strclean
1779 * Description : In-Situ-Eliminate all occurances of substring in
1783 * 1 : string = string to clean
1784 * 2 : substring = substring to eliminate
1786 * Returns : Number of eliminations
1788 *********************************************************************/
1789 int strclean(const char *string, const char *substring)
1791 int hits = 0, len = strlen(substring);
1794 while((pos = strstr(string, substring)))
1801 while (*p++ != '\0');
1808 #endif /* def FEATURE_FORCE_LOAD */