1 const char parsers_rcs[] = "$Id: parsers.c,v 1.49 2002/03/09 20:03:52 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', ``get_header', `sed',
14 * and `server_set_cookie'.
16 * Copyright : Written by and Copyright (C) 2001 the SourceForge
17 * IJBSWA team. http://ijbswa.sourceforge.net
19 * Based on the Internet Junkbuster originally written
20 * by and Copyright (C) 1997 Anonymous Coders and
21 * Junkbusters Corporation. http://www.junkbusters.com
23 * This program is free software; you can redistribute it
24 * and/or modify it under the terms of the GNU General
25 * Public License as published by the Free Software
26 * Foundation; either version 2 of the License, or (at
27 * your option) any later version.
29 * This program is distributed in the hope that it will
30 * be useful, but WITHOUT ANY WARRANTY; without even the
31 * implied warranty of MERCHANTABILITY or FITNESS FOR A
32 * PARTICULAR PURPOSE. See the GNU General Public
33 * License for more details.
35 * The GNU General Public License should be included with
36 * this file. If not, you can view it at
37 * http://www.gnu.org/copyleft/gpl.html
38 * or write to the Free Software Foundation, Inc., 59
39 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
43 * Revision 1.49 2002/03/09 20:03:52 jongfoster
44 * - Making various functions return int rather than size_t.
45 * (Undoing a recent change). Since size_t is unsigned on
46 * Windows, functions like read_socket that return -1 on
47 * error cannot return a size_t.
49 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
50 * crashes, and also frequently caused JB to jump to 100%
51 * CPU and stay there. (Because it thought it had just
52 * read ((unsigned)-1) == 4Gb of data...)
54 * - The signature of write_socket has changed, it now simply
55 * returns success=0/failure=nonzero.
57 * - Trying to get rid of a few warnings --with-debug on
58 * Windows, I've introduced a new type "jb_socket". This is
59 * used for the socket file descriptors. On Windows, this
60 * is SOCKET (a typedef for unsigned). Everywhere else, it's
61 * an int. The error value can't be -1 any more, so it's
62 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
63 * Windows it maps to the #define INVALID_SOCKET.)
65 * - The signature of bind_port has changed.
67 * Revision 1.48 2002/03/07 03:46:53 oes
68 * Fixed compiler warnings etc
70 * Revision 1.47 2002/02/20 23:15:13 jongfoster
71 * Parsing functions now handle out-of-memory gracefully by returning
74 * Revision 1.46 2002/01/17 21:03:47 jongfoster
75 * Moving all our URL and URL pattern parsing code to urlmatch.c.
77 * Revision 1.45 2002/01/09 14:33:03 oes
78 * Added support for localtime_r.
80 * Revision 1.44 2001/12/14 01:22:54 steudten
81 * Remove 'user:pass@' from 'proto://user:pass@host' for the
82 * new added header 'Host: ..'. (See Req ID 491818)
84 * Revision 1.43 2001/11/23 00:26:38 jongfoster
85 * Fixing two really stupid errors in my previous commit
87 * Revision 1.42 2001/11/22 21:59:30 jongfoster
88 * Adding code to handle +no-cookies-keep
90 * Revision 1.41 2001/11/05 23:43:05 steudten
91 * Add time+date to log files.
93 * Revision 1.40 2001/10/26 20:13:09 jongfoster
94 * ctype.h is needed in Windows, too.
96 * Revision 1.39 2001/10/26 17:40:04 oes
97 * Introduced get_header_value()
98 * Removed http->user_agent, csp->referrer and csp->accept_types
99 * Removed client_accept()
101 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
102 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
103 * threads to call select() simultaneously. So, it's time to do a real, live,
104 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
105 * (native). Both versions will work, but using __OS2__ offers multi-threading.
107 * Revision 1.37 2001/10/23 21:36:02 jongfoster
108 * Documenting sed()'s error behaviou (doc change only)
110 * Revision 1.36 2001/10/13 12:51:51 joergs
111 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
112 * force-load), instead crumble Host: and add it (again) in client_host_adder
113 * (in case we get a HTTP/1.0 request without Host: header and forward it to
114 * a HTTP/1.1 server/proxy).
116 * Revision 1.35 2001/10/09 22:39:21 jongfoster
117 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
120 * Revision 1.34 2001/10/07 18:50:55 oes
121 * Added server_content_encoding, renamed server_transfer_encoding
123 * Revision 1.33 2001/10/07 18:04:49 oes
124 * Changed server_http11 to server_http and its pattern to "HTTP".
125 * Additional functionality: it now saves the HTTP status into
126 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
128 * Revision 1.32 2001/10/07 15:43:28 oes
129 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
130 * client_te and client_accept_encoding_adder, triggered by the new
131 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
132 * changed to allow only identity and chunked, and the TE header is
133 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
135 * parse_http_request no longer does anything than parsing. The rewriting
136 * of http->cmd and version mangling are gone. It now also recognizes
137 * the put and delete methods and saves the url in http->url. Removed
140 * renamed content_type and content_length to have the server_ prefix
142 * server_content_type now only works if csp->content_type != CT_TABOO
144 * added server_transfer_encoding, which
145 * - Sets CT_TABOO to prohibit filtering if encoding compresses
146 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
147 * - Change from "chunked" to "identity" if body was chunked
148 * but has been de-chunked for filtering.
150 * added server_content_md5 which crunches any Content-MD5 headers
151 * if the body was modified.
153 * made server_http11 conditional on +downgrade action
155 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
157 * Revision 1.31 2001/10/05 14:25:02 oes
158 * Crumble Keep-Alive from Server
160 * Revision 1.30 2001/09/29 12:56:03 joergs
161 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
163 * Revision 1.29 2001/09/24 21:09:24 jongfoster
164 * Fixing 2 memory leaks that Guy spotted, where the paramater to
165 * enlist() was not being free()d.
167 * Revision 1.28 2001/09/22 16:32:28 jongfoster
168 * Removing unused #includes.
170 * Revision 1.27 2001/09/20 15:45:25 steudten
172 * add casting from size_t to int for printf()
173 * remove local variable shadow s2
175 * Revision 1.26 2001/09/16 17:05:14 jongfoster
176 * Removing unused #include showarg.h
178 * Revision 1.25 2001/09/16 13:21:27 jongfoster
179 * Changes to use new list functions.
181 * Revision 1.24 2001/09/13 23:05:50 jongfoster
182 * Changing the string paramater to the header parsers a "const".
184 * Revision 1.23 2001/09/12 18:08:19 steudten
186 * In parse_http_request() header rewriting miss the host value, so
187 * from http://www.mydomain.com the result was just " / " not
188 * http://www.mydomain.com/ in case we forward.
190 * Revision 1.22 2001/09/10 10:58:53 oes
191 * Silenced compiler warnings
193 * Revision 1.21 2001/07/31 14:46:00 oes
194 * - Persistant connections now suppressed
195 * - sed() no longer appends empty header to csp->headers
197 * Revision 1.20 2001/07/30 22:08:36 jongfoster
198 * Tidying up #defines:
199 * - All feature #defines are now of the form FEATURE_xxx
200 * - Permanently turned off WIN_GUI_EDIT
201 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
203 * Revision 1.19 2001/07/25 17:21:54 oes
204 * client_uagent now saves copy of User-Agent: header value
206 * Revision 1.18 2001/07/13 14:02:46 oes
207 * - Included fix to repair broken HTTP requests that
208 * don't contain a path, not even '/'.
209 * - Removed all #ifdef PCRS
210 * - content_type now always inspected and classified as
211 * text, gif or other.
212 * - formatting / comments
214 * Revision 1.17 2001/06/29 21:45:41 oes
215 * Indentation, CRLF->LF, Tab-> Space
217 * Revision 1.16 2001/06/29 13:32:42 oes
219 * - Adapted free_http_request
220 * - Removed logentry from cancelled commit
222 * Revision 1.15 2001/06/03 19:12:38 oes
223 * deleted const struct interceptors
225 * Revision 1.14 2001/06/01 18:49:17 jongfoster
226 * Replaced "list_share" with "list" - the tiny memory gain was not
227 * worth the extra complexity.
229 * Revision 1.13 2001/05/31 21:30:33 jongfoster
230 * Removed list code - it's now in list.[ch]
231 * Renamed "permission" to "action", and changed many features
232 * to use the actions file rather than the global config.
234 * Revision 1.12 2001/05/31 17:33:13 oes
238 * Revision 1.11 2001/05/29 20:11:19 joergs
239 * '/ * inside comment' warning removed.
241 * Revision 1.10 2001/05/29 09:50:24 jongfoster
242 * Unified blocklist/imagelist/permissionslist.
243 * File format is still under discussion, but the internal changes
246 * Also modified interceptor behaviour:
247 * - We now intercept all URLs beginning with one of the following
248 * prefixes (and *only* these prefixes):
250 * * http://ijbswa.sf.net/config/
251 * * http://ijbswa.sourceforge.net/config/
252 * - New interceptors "home page" - go to http://i.j.b/ to see it.
253 * - Internal changes so that intercepted and fast redirect pages
254 * are not replaced with an image.
255 * - Interceptors now have the option to send a binary page direct
256 * to the client. (i.e. ijb-send-banner uses this)
257 * - Implemented show-url-info interceptor. (Which is why I needed
258 * the above interceptors changes - a typical URL is
259 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
260 * The previous mechanism would not have intercepted that, and
261 * if it had been intercepted then it then it would have replaced
264 * Revision 1.9 2001/05/28 17:26:33 jongfoster
265 * Fixing segfault if last header was crunched.
266 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
267 * can use the cross-platform sprintf() instead.)
269 * Revision 1.8 2001/05/27 22:17:04 oes
271 * - re_process_buffer no longer writes the modified buffer
272 * to the client, which was very ugly. It now returns the
273 * buffer, which it is then written by chat.
275 * - content_length now adjusts the Content-Length: header
276 * for modified documents rather than crunch()ing it.
277 * (Length info in csp->content_length, which is 0 for
278 * unmodified documents)
280 * - For this to work, sed() is called twice when filtering.
282 * Revision 1.7 2001/05/27 13:19:06 oes
283 * Patched Joergs solution for the content-length in.
285 * Revision 1.6 2001/05/26 13:39:32 jongfoster
286 * Only crunches Content-Length header if applying RE filtering.
287 * Without this fix, Microsoft Windows Update wouldn't work.
289 * Revision 1.5 2001/05/26 00:28:36 jongfoster
290 * Automatic reloading of config file.
291 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
292 * Most of the global variables have been moved to a new
293 * struct configuration_spec, accessed through csp->config->globalname
294 * Most of the globals remaining are used by the Win32 GUI.
296 * Revision 1.4 2001/05/22 18:46:04 oes
298 * - Enabled filtering banners by size rather than URL
299 * by adding patterns that replace all standard banner
300 * sizes with the "Junkbuster" gif to the re_filterfile
302 * - Enabled filtering WebBugs by providing a pattern
303 * which kills all 1x1 images
305 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
306 * which is selected by the (nonstandard and therefore
307 * capital) letter 'U' in the option string.
308 * It causes the quantifiers to be ungreedy by default.
309 * Appending a ? turns back to greedy (!).
311 * - Added a new interceptor ijb-send-banner, which
312 * sends back the "Junkbuster" gif. Without imagelist or
313 * MSIE detection support, or if tinygif = 1, or the
314 * URL isn't recognized as an imageurl, a lame HTML
315 * explanation is sent instead.
317 * - Added new feature, which permits blocking remote
318 * script redirects and firing back a local redirect
320 * The feature is conditionally compiled, i.e. it
321 * can be disabled with --disable-fast-redirects,
322 * plus it must be activated by a "fast-redirects"
323 * line in the config file, has its own log level
324 * and of course wants to be displayed by show-proxy-args
325 * Note: Boy, all the #ifdefs in 1001 locations and
326 * all the fumbling with configure.in and acconfig.h
327 * were *way* more work than the feature itself :-(
329 * - Because a generic redirect template was needed for
330 * this, tinygif = 3 now uses the same.
332 * - Moved GIFs, and other static HTTP response templates
337 * - Removed some >400 CRs again (Jon, you really worked
340 * Revision 1.3 2001/05/20 01:21:20 jongfoster
341 * Version 2.9.4 checkin.
342 * - Merged popupfile and cookiefile, and added control over PCRS
343 * filtering, in new "permissionsfile".
344 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
345 * file error you now get a message box (in the Win32 GUI) rather
346 * than the program exiting with no explanation.
347 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
349 * - Removed tabs from "config"
350 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
351 * - Bumped up version number.
353 * Revision 1.2 2001/05/17 23:02:36 oes
354 * - Made referrer option accept 'L' as a substitute for '§'
356 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
357 * Initial import of version 2.9.3 source tree
360 *********************************************************************/
367 #include <sys/types.h>
375 #if !defined(_WIN32) && !defined(__OS2__)
385 #include "jbsockets.h"
386 #include "miscutil.h"
389 const char parsers_h_rcs[] = PARSERS_H_VERSION;
391 /* Fix a problem with Solaris. There should be no effect on other
393 * Solaris's isspace() is a macro which uses it's argument directly
394 * as an array index. Therefore we need to make sure that high-bit
395 * characters generate +ve values, and ideally we also want to make
396 * the argument match the declared parameter type of "int".
398 * Why did they write a character function that can't take a simple
399 * "char" argument? Doh!
401 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
402 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
405 const struct parsers client_patterns[] = {
406 { "referer:", 8, client_referrer },
407 { "user-agent:", 11, client_uagent },
408 { "ua-", 3, client_ua },
409 { "from:", 5, client_from },
410 { "cookie:", 7, client_send_cookie },
411 { "x-forwarded-for:", 16, client_x_forwarded },
412 { "Accept-Encoding:", 16, client_accept_encoding },
413 { "TE:", 3, client_te },
414 { "Host:", 5, crumble },
415 /* { "if-modified-since:", 18, crumble }, */
416 { "Keep-Alive:", 11, crumble },
417 { "connection:", 11, crumble },
418 { "proxy-connection:", 17, crumble },
423 const struct parsers server_patterns[] = {
424 { "HTTP", 4, server_http },
425 { "set-cookie:", 11, server_set_cookie },
426 { "connection:", 11, crumble },
427 { "Content-Type:", 13, server_content_type },
428 { "Content-Length:", 15, server_content_length },
429 { "Content-MD5:", 12, server_content_md5 },
430 { "Content-Encoding:", 17, server_content_encoding },
431 { "Transfer-Encoding:", 18, server_transfer_coding },
432 { "Keep-Alive:", 11, crumble },
437 const add_header_func_ptr add_client_headers[] = {
440 client_x_forwarded_adder,
442 client_accept_encoding_adder,
443 connection_close_adder,
448 const add_header_func_ptr add_server_headers[] = {
449 connection_close_adder,
454 /*********************************************************************
456 * Function : flush_socket
458 * Description : Write any pending "buffered" content.
461 * 1 : fd = file descriptor of the socket to read
462 * 2 : csp = Current client state (buffers, headers, etc...)
464 * Returns : On success, the number of bytes written are returned (zero
465 * indicates nothing was written). On error, -1 is returned,
466 * and errno is set appropriately. If count is zero and the
467 * file descriptor refers to a regular file, 0 will be
468 * returned without causing any other effect. For a special
469 * file, the results are not portable.
471 *********************************************************************/
472 int flush_socket(jb_socket fd, struct client_state *csp)
474 struct iob *iob = csp->iob;
475 int len = iob->eod - iob->cur;
482 if (write_socket(fd, iob->cur, len))
486 iob->eod = iob->cur = iob->buf;
492 /*********************************************************************
494 * Function : add_to_iob
496 * Description : Add content to the buffered page.
499 * 1 : csp = Current client state (buffers, headers, etc...)
500 * 2 : buf = holds the content to be added to the page
501 * 3 : n = number of bytes to be added
503 * Returns : Number of bytes in the content buffer.
505 *********************************************************************/
506 size_t add_to_iob(struct client_state *csp, char *buf, size_t n)
508 struct iob *iob = csp->iob;
512 have = iob->eod - iob->cur;
521 if ((p = (char *)malloc(need + 1)) == NULL)
523 log_error(LOG_LEVEL_FATAL, "malloc() iob failed: %E");
528 /* there is something in the buffer - save it */
529 memcpy(p, iob->cur, have);
531 /* replace the buffer with the new space */
535 /* point to the end of the data */
540 /* the buffer is empty, free it and reinitialize */
545 /* copy the new data into the iob buffer */
548 /* point to the end of the data */
551 /* null terminate == cheap insurance */
554 /* set the pointers to the new values */
563 /*********************************************************************
565 * Function : get_header
567 * Description : This (odd) routine will parse the csp->iob
570 * 1 : csp = Current client state (buffers, headers, etc...)
572 * Returns : Any one of the following:
574 * 1) a pointer to a dynamically allocated string that contains a header line
575 * 2) NULL indicating that the end of the header was reached
576 * 3) "" indicating that the end of the iob was reached before finding
577 * a complete header line.
579 *********************************************************************/
580 char *get_header(struct client_state *csp)
586 if ((iob->cur == NULL)
587 || ((p = strchr(iob->cur, '\n')) == NULL))
589 return(""); /* couldn't find a complete header */
594 ret = strdup(iob->cur);
597 /* FIXME No way to handle error properly */
598 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
603 if ((q = strchr(ret, '\r'))) *q = '\0';
605 /* is this a blank linke (i.e. the end of the header) ? */
617 /*********************************************************************
619 * Function : get_header_value
621 * Description : Get the value of a given header from a chained list
622 * of header lines or return NULL if no such header is
623 * present in the list.
626 * 1 : header_list = pointer to list
627 * 2 : header_name = string with name of header to look for.
628 * Trailing colon required, capitalization
631 * Returns : NULL if not found, else value of header
633 *********************************************************************/
634 char *get_header_value(const struct list *header_list, const char *header_name)
636 struct list_entry *cur_entry;
642 length = strlen(header_name);
644 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
648 if (!strncmpic(cur_entry->str, header_name, length))
651 * Found: return pointer to start of value
653 ret = (char *) (cur_entry->str + length);
654 while (*ret && ijb_isspace(*ret)) ret++;
667 /*********************************************************************
671 * Description : add, delete or modify lines in the HTTP header streams.
672 * On entry, it receives a linked list of headers space
673 * that was allocated dynamically (both the list nodes
674 * and the header contents).
676 * As a side effect it frees the space used by the original
680 * 1 : pats = list of patterns to match against headers
681 * 2 : more_headers = list of functions to add more
682 * headers (client or server)
683 * 3 : csp = Current client state (buffers, headers, etc...)
685 * Returns : Single pointer to a fully formed header, or NULL
686 * on out-of-memory error.
688 *********************************************************************/
689 char *sed(const struct parsers pats[],
690 const add_header_func_ptr more_headers[],
691 struct client_state *csp)
693 struct list_entry *p;
694 const struct parsers *v;
695 const add_header_func_ptr *f;
696 jb_err err = JB_ERR_OK;
698 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
700 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
702 /* Header crunch()ed in previous run? -> ignore */
703 if (p->str == NULL) continue;
705 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
707 if (strncmpic(p->str, v->str, v->len) == 0)
709 err = v->parser(csp, (char **)&(p->str));
714 /* place any additional headers on the csp->headers list */
715 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
720 if (err != JB_ERR_OK)
725 return list_to_text(csp->headers);
729 /* here begins the family of parser functions that reformat header lines */
732 /*********************************************************************
736 * Description : This is called if a header matches a pattern to "crunch"
739 * 1 : csp = Current client state (buffers, headers, etc...)
740 * 2 : header = On input, pointer to header to modify.
741 * On output, pointer to the modified header, or NULL
742 * to remove the header. This function frees the
743 * original string if necessary.
745 * Returns : JB_ERR_OK on success, or
746 * JB_ERR_MEMORY on out-of-memory error.
748 *********************************************************************/
749 jb_err crumble(struct client_state *csp, char **header)
751 log_error(LOG_LEVEL_HEADER, "crunch!");
757 /*********************************************************************
759 * Function : server_content_type
761 * Description : Set the content-type for filterable types (text/.*,
762 * javascript and image/gif) unless filtering has been
763 * forbidden (CT_TABOO) while parsing earlier headers.
766 * 1 : csp = Current client state (buffers, headers, etc...)
767 * 2 : header = On input, pointer to header to modify.
768 * On output, pointer to the modified header, or NULL
769 * to remove the header. This function frees the
770 * original string if necessary.
772 * Returns : JB_ERR_OK on success, or
773 * JB_ERR_MEMORY on out-of-memory error.
775 *********************************************************************/
776 jb_err server_content_type(struct client_state *csp, char **header)
778 if (csp->content_type != CT_TABOO)
780 if (strstr(*header, " text/")
781 || strstr(*header, "application/x-javascript"))
782 csp->content_type = CT_TEXT;
783 else if (strstr(*header, " image/gif"))
784 csp->content_type = CT_GIF;
786 csp->content_type = 0;
793 /*********************************************************************
795 * Function : server_transfer_coding
797 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
798 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
799 * - Change from "chunked" to "identity" if body was chunked
800 * but has been de-chunked for filtering.
803 * 1 : csp = Current client state (buffers, headers, etc...)
804 * 2 : header = On input, pointer to header to modify.
805 * On output, pointer to the modified header, or NULL
806 * to remove the header. This function frees the
807 * original string if necessary.
809 * Returns : JB_ERR_OK on success, or
810 * JB_ERR_MEMORY on out-of-memory error.
812 *********************************************************************/
813 jb_err server_transfer_coding(struct client_state *csp, char **header)
816 * Turn off pcrs and gif filtering if body compressed
818 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
820 csp->content_type = CT_TABOO;
824 * Raise flag if body chunked
826 if (strstr(*header, "chunked"))
828 csp->flags |= CSP_FLAG_CHUNKED;
831 * If the body was modified, it has been
832 * de-chunked first, so adjust the header:
834 if (csp->flags & CSP_FLAG_MODIFIED)
837 *header = strdup("Transfer-Encoding: identity");
838 return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
846 /*********************************************************************
848 * Function : server_content_encoding
850 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
853 * 1 : csp = Current client state (buffers, headers, etc...)
854 * 2 : header = On input, pointer to header to modify.
855 * On output, pointer to the modified header, or NULL
856 * to remove the header. This function frees the
857 * original string if necessary.
859 * Returns : JB_ERR_OK on success, or
860 * JB_ERR_MEMORY on out-of-memory error.
862 *********************************************************************/
863 jb_err server_content_encoding(struct client_state *csp, char **header)
866 * Turn off pcrs and gif filtering if body compressed
868 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
870 csp->content_type = CT_TABOO;
878 /*********************************************************************
880 * Function : server_content_length
882 * Description : Adjust Content-Length header if we modified
886 * 1 : csp = Current client state (buffers, headers, etc...)
887 * 2 : header = On input, pointer to header to modify.
888 * On output, pointer to the modified header, or NULL
889 * to remove the header. This function frees the
890 * original string if necessary.
892 * Returns : JB_ERR_OK on success, or
893 * JB_ERR_MEMORY on out-of-memory error.
895 *********************************************************************/
896 jb_err server_content_length(struct client_state *csp, char **header)
898 if (csp->content_length != 0) /* Content length has been modified */
901 *header = (char *) zalloc(100);
904 return JB_ERR_MEMORY;
907 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
909 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
916 /*********************************************************************
918 * Function : server_content_md5
920 * Description : Crumble any Content-MD5 headers if the document was
921 * modified. FIXME: Should we re-compute instead?
924 * 1 : csp = Current client state (buffers, headers, etc...)
925 * 2 : header = On input, pointer to header to modify.
926 * On output, pointer to the modified header, or NULL
927 * to remove the header. This function frees the
928 * original string if necessary.
930 * Returns : JB_ERR_OK on success, or
931 * JB_ERR_MEMORY on out-of-memory error.
933 *********************************************************************/
934 jb_err server_content_md5(struct client_state *csp, char **header)
936 if (csp->flags & CSP_FLAG_MODIFIED)
938 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
946 /*********************************************************************
948 * Function : client_accept_encoding
950 * Description : Rewrite the client's Accept-Encoding header so that
951 * if doesn't allow compression, if the action applies.
952 * Note: For HTTP/1.0 the absence of the header is enough.
955 * 1 : csp = Current client state (buffers, headers, etc...)
956 * 2 : header = On input, pointer to header to modify.
957 * On output, pointer to the modified header, or NULL
958 * to remove the header. This function frees the
959 * original string if necessary.
961 * Returns : JB_ERR_OK on success, or
962 * JB_ERR_MEMORY on out-of-memory error.
964 *********************************************************************/
965 jb_err client_accept_encoding(struct client_state *csp, char **header)
967 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
969 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress content");
972 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
974 *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
977 return JB_ERR_MEMORY;
986 /*********************************************************************
988 * Function : client_te
990 * Description : Rewrite the client's TE header so that
991 * if doesn't allow compression, if the action applies.
994 * 1 : csp = Current client state (buffers, headers, etc...)
995 * 2 : header = On input, pointer to header to modify.
996 * On output, pointer to the modified header, or NULL
997 * to remove the header. This function frees the
998 * original string if necessary.
1000 * Returns : JB_ERR_OK on success, or
1001 * JB_ERR_MEMORY on out-of-memory error.
1003 *********************************************************************/
1004 jb_err client_te(struct client_state *csp, char **header)
1006 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1009 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress transfer");
1015 /*********************************************************************
1017 * Function : client_referrer
1019 * Description : Handle the "referer" config setting properly.
1020 * Called from `sed'.
1023 * 1 : csp = Current client state (buffers, headers, etc...)
1024 * 2 : header = On input, pointer to header to modify.
1025 * On output, pointer to the modified header, or NULL
1026 * to remove the header. This function frees the
1027 * original string if necessary.
1029 * Returns : JB_ERR_OK on success, or
1030 * JB_ERR_MEMORY on out-of-memory error.
1032 *********************************************************************/
1033 jb_err client_referrer(struct client_state *csp, char **header)
1035 const char * newval;
1037 #ifdef FEATURE_FORCE_LOAD
1038 /* Since the referrer can include the prefix even
1039 * even if the request itself is non-forced, we must
1040 * clean it unconditionally
1042 strclean(*header, FORCE_PREFIX);
1043 #endif /* def FEATURE_FORCE_LOAD */
1046 * Are we sending referer?
1048 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1055 newval = csp->action->string[ACTION_STRING_REFERER];
1057 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1062 log_error(LOG_LEVEL_HEADER, "crunch!");
1065 else if (0 == strncmpic(newval, "http://", 7))
1068 * We have a specific (fixed) referer we want to send.
1070 log_error(LOG_LEVEL_HEADER, "modified");
1072 *header = strdup("Referer: ");
1073 string_append(header, newval);
1075 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1080 * Forge a referer as http://[hostname:port of REQUEST]/
1081 * to fool stupid checks for in-site links
1083 if (0 != strcmpic(newval, "forge"))
1086 * Invalid choice - but forge is probably the best default.
1088 log_error(LOG_LEVEL_ERROR, "Bad parameter: +referer{%s}", newval);
1091 *header = strdup("Referer: http://");
1092 string_append(header, csp->http->hostport);
1093 string_append(header, "/");
1094 log_error(LOG_LEVEL_HEADER, "crunch+forge to %s", *header);
1096 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1101 /*********************************************************************
1103 * Function : client_uagent
1105 * Description : Handle the "user-agent" config setting properly
1106 * and remember its original value to enable browser
1107 * bug workarounds. Called from `sed'.
1110 * 1 : csp = Current client state (buffers, headers, etc...)
1111 * 2 : header = On input, pointer to header to modify.
1112 * On output, pointer to the modified header, or NULL
1113 * to remove the header. This function frees the
1114 * original string if necessary.
1116 * Returns : JB_ERR_OK on success, or
1117 * JB_ERR_MEMORY on out-of-memory error.
1119 *********************************************************************/
1120 jb_err client_uagent(struct client_state *csp, char **header)
1122 const char * newval;
1124 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1129 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1135 log_error(LOG_LEVEL_HEADER, "modified");
1138 *header = strdup("User-Agent: ");
1139 string_append(header, newval);
1141 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1145 /*********************************************************************
1147 * Function : client_ua
1149 * Description : Handle "ua-" headers properly. Called from `sed'.
1152 * 1 : csp = Current client state (buffers, headers, etc...)
1153 * 2 : header = On input, pointer to header to modify.
1154 * On output, pointer to the modified header, or NULL
1155 * to remove the header. This function frees the
1156 * original string if necessary.
1158 * Returns : JB_ERR_OK on success, or
1159 * JB_ERR_MEMORY on out-of-memory error.
1161 *********************************************************************/
1162 jb_err client_ua(struct client_state *csp, char **header)
1164 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1166 log_error(LOG_LEVEL_HEADER, "crunch!");
1174 /*********************************************************************
1176 * Function : client_from
1178 * Description : Handle the "from" config setting properly.
1179 * Called from `sed'.
1182 * 1 : csp = Current client state (buffers, headers, etc...)
1183 * 2 : header = On input, pointer to header to modify.
1184 * On output, pointer to the modified header, or NULL
1185 * to remove the header. This function frees the
1186 * original string if necessary.
1188 * Returns : JB_ERR_OK on success, or
1189 * JB_ERR_MEMORY on out-of-memory error.
1191 *********************************************************************/
1192 jb_err client_from(struct client_state *csp, char **header)
1194 const char * newval;
1196 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1203 newval = csp->action->string[ACTION_STRING_FROM];
1206 * Are we blocking the e-mail address?
1208 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1210 log_error(LOG_LEVEL_HEADER, "crunch!");
1214 log_error(LOG_LEVEL_HEADER, " modified");
1216 *header = strdup("From: ");
1217 string_append(header, newval);
1219 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1223 /*********************************************************************
1225 * Function : client_send_cookie
1227 * Description : Handle the "cookie" header properly. Called from `sed'.
1228 * If cookie is accepted, add it to the cookie_list,
1229 * else we crunch it. Mmmmmmmmmmm ... cookie ......
1232 * 1 : csp = Current client state (buffers, headers, etc...)
1233 * 2 : header = On input, pointer to header to modify.
1234 * On output, pointer to the modified header, or NULL
1235 * to remove the header. This function frees the
1236 * original string if necessary.
1238 * Returns : JB_ERR_OK on success, or
1239 * JB_ERR_MEMORY on out-of-memory error.
1241 *********************************************************************/
1242 jb_err client_send_cookie(struct client_state *csp, char **header)
1244 jb_err result = JB_ERR_OK;
1246 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
1248 /* strlen("cookie: ") == 8 */
1249 result = enlist(csp->cookie_list, *header + 8);
1253 log_error(LOG_LEVEL_HEADER, " crunch!");
1257 * Always remove the cookie here. The cookie header
1258 * will be sent at the end of the header.
1266 /*********************************************************************
1268 * Function : client_x_forwarded
1270 * Description : Handle the "x-forwarded-for" config setting properly,
1271 * also used in the add_client_headers list. Called from `sed'.
1274 * 1 : csp = Current client state (buffers, headers, etc...)
1275 * 2 : header = On input, pointer to header to modify.
1276 * On output, pointer to the modified header, or NULL
1277 * to remove the header. This function frees the
1278 * original string if necessary.
1280 * Returns : JB_ERR_OK on success, or
1281 * JB_ERR_MEMORY on out-of-memory error.
1283 *********************************************************************/
1284 jb_err client_x_forwarded(struct client_state *csp, char **header)
1286 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
1288 /* Save it so we can re-add it later */
1289 freez(csp->x_forwarded);
1290 csp->x_forwarded = *header;
1293 * Always set *header = NULL, since this information
1294 * will be sent at the end of the header.
1301 log_error(LOG_LEVEL_HEADER, " crunch!");
1307 /* the following functions add headers directly to the header list */
1309 /*********************************************************************
1311 * Function : client_host_adder
1313 * Description : (re)adds the host header. Called from `sed'.
1316 * 1 : csp = Current client state (buffers, headers, etc...)
1318 * Returns : JB_ERR_OK on success, or
1319 * JB_ERR_MEMORY on out-of-memory error.
1321 *********************************************************************/
1322 jb_err client_host_adder(struct client_state *csp)
1328 if ( !csp->http->hostport || !*(csp->http->hostport))
1333 p = strdup("Host: ");
1335 ** remove 'user:pass@' from 'proto://user:pass@host'
1337 if ( (pos = strchr( csp->http->hostport, '@')) != NULL )
1339 string_append(&p, pos+1);
1343 string_append(&p, csp->http->hostport);
1348 return JB_ERR_MEMORY;
1351 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1353 err = enlist(csp->headers, p);
1361 /*********************************************************************
1363 * Function : client_cookie_adder
1365 * Description : Used in the add_client_headers list. Called from `sed'.
1368 * 1 : csp = Current client state (buffers, headers, etc...)
1370 * Returns : JB_ERR_OK on success, or
1371 * JB_ERR_MEMORY on out-of-memory error.
1373 *********************************************************************/
1374 jb_err client_cookie_adder(struct client_state *csp)
1376 struct list_entry *lst;
1378 struct list_entry *list1 = csp->cookie_list->first;
1379 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
1380 int first_cookie = 1;
1383 if ((list1 == NULL) && (list2 == NULL))
1389 tmp = strdup("Cookie: ");
1391 for (lst = list1; lst ; lst = lst->next)
1399 string_append(&tmp, "; ");
1401 string_append(&tmp, lst->str);
1404 for (lst = list2; lst ; lst = lst->next)
1412 string_append(&tmp, "; ");
1414 string_join(&tmp, cookie_encode(lst->str));
1419 return JB_ERR_MEMORY;
1422 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
1423 err = enlist(csp->headers, tmp);
1429 /*********************************************************************
1431 * Function : client_accept_encoding_adder
1433 * Description : Add an Accept-Encoding header to the client's request
1434 * that disables compression if the action applies, and
1435 * the header is not already there. Called from `sed'.
1436 * Note: For HTTP/1.0, the absence of the header is enough.
1439 * 1 : csp = Current client state (buffers, headers, etc...)
1441 * Returns : JB_ERR_OK on success, or
1442 * JB_ERR_MEMORY on out-of-memory error.
1444 *********************************************************************/
1445 jb_err client_accept_encoding_adder(struct client_state *csp)
1447 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1448 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
1450 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
1457 /*********************************************************************
1459 * Function : client_xtra_adder
1461 * Description : Used in the add_client_headers list. Called from `sed'.
1464 * 1 : csp = Current client state (buffers, headers, etc...)
1466 * Returns : JB_ERR_OK on success, or
1467 * JB_ERR_MEMORY on out-of-memory error.
1469 *********************************************************************/
1470 jb_err client_xtra_adder(struct client_state *csp)
1472 struct list_entry *lst;
1475 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
1476 lst ; lst = lst->next)
1478 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
1479 err = enlist(csp->headers, lst->str);
1491 /*********************************************************************
1493 * Function : client_x_forwarded_adder
1495 * Description : Used in the add_client_headers list. Called from `sed'.
1498 * 1 : csp = Current client state (buffers, headers, etc...)
1500 * Returns : JB_ERR_OK on success, or
1501 * JB_ERR_MEMORY on out-of-memory error.
1503 *********************************************************************/
1504 jb_err client_x_forwarded_adder(struct client_state *csp)
1509 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
1514 if (csp->x_forwarded)
1516 p = strdup(csp->x_forwarded);
1517 string_append(&p, ", ");
1521 p = strdup("X-Forwarded-For: ");
1523 string_append(&p, csp->ip_addr_str);
1527 return JB_ERR_MEMORY;
1530 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1531 err = enlist(csp->headers, p);
1538 /*********************************************************************
1540 * Function : connection_close_adder
1542 * Description : Adds a "Connection: close" header to csp->headers
1543 * as a temporary fix for the needed but missing HTTP/1.1
1544 * support. Called from `sed'.
1545 * FIXME: This whole function shouldn't be neccessary!
1548 * 1 : csp = Current client state (buffers, headers, etc...)
1550 * Returns : JB_ERR_OK on success, or
1551 * JB_ERR_MEMORY on out-of-memory error.
1553 *********************************************************************/
1554 jb_err connection_close_adder(struct client_state *csp)
1556 return enlist(csp->headers, "Connection: close");
1560 /*********************************************************************
1562 * Function : server_http
1564 * Description : - Save the HTTP Status into csp->http->status
1565 * - Set CT_TABOO to prevent filtering if the answer
1566 * is a partial range (HTTP status 206)
1567 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
1571 * 1 : csp = Current client state (buffers, headers, etc...)
1572 * 2 : header = On input, pointer to header to modify.
1573 * On output, pointer to the modified header, or NULL
1574 * to remove the header. This function frees the
1575 * original string if necessary.
1577 * Returns : JB_ERR_OK on success, or
1578 * JB_ERR_MEMORY on out-of-memory error.
1580 *********************************************************************/
1581 jb_err server_http(struct client_state *csp, char **header)
1583 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
1584 if (csp->http->status == 206)
1586 csp->content_type = CT_TABOO;
1589 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
1592 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
1599 /*********************************************************************
1601 * Function : server_set_cookie
1603 * Description : Handle the server "cookie" header properly.
1604 * Log cookie to the jar file. Then "crunch" it,
1605 * or accept it. Called from `sed'.
1608 * 1 : csp = Current client state (buffers, headers, etc...)
1609 * 2 : header = On input, pointer to header to modify.
1610 * On output, pointer to the modified header, or NULL
1611 * to remove the header. This function frees the
1612 * original string if necessary.
1614 * Returns : JB_ERR_OK on success, or
1615 * JB_ERR_MEMORY on out-of-memory error.
1617 *********************************************************************/
1618 jb_err server_set_cookie(struct client_state *csp, char **header)
1620 #ifdef FEATURE_COOKIE_JAR
1621 if (csp->config->jar)
1624 * Write timestamp into outbuf.
1626 * Complex because not all OSs have tm_gmtoff or
1627 * the %z field in strftime()
1629 char tempbuf[ BUFFER_SIZE ];
1633 #ifdef HAVE_LOCALTIME_R
1634 tm_now = *localtime_r(&now, &tm_now);
1636 tm_now = *localtime (&now);
1638 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
1640 /* strlen("set-cookie: ") = 12 */
1641 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
1643 #endif /* def FEATURE_COOKIE_JAR */
1645 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
1647 return crumble(csp, header);
1649 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
1651 /* Flag whether or not to log a message */
1654 /* A variable to store the tag we're working on */
1657 /* Skip "Set-Cookie:" (11 characters) in header */
1658 cur_tag = *header + 11;
1660 /* skip whitespace between "Set-Cookie:" and value */
1661 while (*cur_tag && ijb_isspace(*cur_tag))
1666 /* Loop through each tag in the cookie */
1670 char * next_tag = strchr(cur_tag, ';');
1671 if (next_tag != NULL)
1673 /* Skip the ';' character itself */
1676 /* skip whitespace ";" and start of tag */
1677 while (*next_tag && ijb_isspace(*next_tag))
1684 /* "Next tag" is the end of the string */
1685 next_tag = cur_tag + strlen(cur_tag);
1688 /* Is this the "Expires" tag? */
1689 if (strncmpic(cur_tag, "expires=", 8) == 0)
1691 /* Delete the tag by copying the rest of the string over it.
1692 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
1693 * since the behaviour of strcpy is undefined for overlapping
1696 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
1698 /* That changed the header, need to issue a log message */
1701 /* Note that the next tag has now been moved to *cur_tag,
1702 * so we do not need to update the cur_tag pointer.
1707 /* Move on to next cookie tag */
1714 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
1722 #ifdef FEATURE_FORCE_LOAD
1723 /*********************************************************************
1725 * Function : strclean
1727 * Description : In-Situ-Eliminate all occurances of substring in
1731 * 1 : string = string to clean
1732 * 2 : substring = substring to eliminate
1734 * Returns : Number of eliminations
1736 *********************************************************************/
1737 int strclean(const char *string, const char *substring)
1739 int hits = 0, len = strlen(substring);
1742 while((pos = strstr(string, substring)))
1749 while (*p++ != '\0');
1756 #endif /* def FEATURE_FORCE_LOAD */