1 const char parsers_rcs[] = "$Id: parsers.c,v 1.50 2002/03/12 01:45:35 oes 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.50 2002/03/12 01:45:35 oes
44 * More verbose logging
46 * Revision 1.49 2002/03/09 20:03:52 jongfoster
47 * - Making various functions return int rather than size_t.
48 * (Undoing a recent change). Since size_t is unsigned on
49 * Windows, functions like read_socket that return -1 on
50 * error cannot return a size_t.
52 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
53 * crashes, and also frequently caused JB to jump to 100%
54 * CPU and stay there. (Because it thought it had just
55 * read ((unsigned)-1) == 4Gb of data...)
57 * - The signature of write_socket has changed, it now simply
58 * returns success=0/failure=nonzero.
60 * - Trying to get rid of a few warnings --with-debug on
61 * Windows, I've introduced a new type "jb_socket". This is
62 * used for the socket file descriptors. On Windows, this
63 * is SOCKET (a typedef for unsigned). Everywhere else, it's
64 * an int. The error value can't be -1 any more, so it's
65 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
66 * Windows it maps to the #define INVALID_SOCKET.)
68 * - The signature of bind_port has changed.
70 * Revision 1.48 2002/03/07 03:46:53 oes
71 * Fixed compiler warnings etc
73 * Revision 1.47 2002/02/20 23:15:13 jongfoster
74 * Parsing functions now handle out-of-memory gracefully by returning
77 * Revision 1.46 2002/01/17 21:03:47 jongfoster
78 * Moving all our URL and URL pattern parsing code to urlmatch.c.
80 * Revision 1.45 2002/01/09 14:33:03 oes
81 * Added support for localtime_r.
83 * Revision 1.44 2001/12/14 01:22:54 steudten
84 * Remove 'user:pass@' from 'proto://user:pass@host' for the
85 * new added header 'Host: ..'. (See Req ID 491818)
87 * Revision 1.43 2001/11/23 00:26:38 jongfoster
88 * Fixing two really stupid errors in my previous commit
90 * Revision 1.42 2001/11/22 21:59:30 jongfoster
91 * Adding code to handle +no-cookies-keep
93 * Revision 1.41 2001/11/05 23:43:05 steudten
94 * Add time+date to log files.
96 * Revision 1.40 2001/10/26 20:13:09 jongfoster
97 * ctype.h is needed in Windows, too.
99 * Revision 1.39 2001/10/26 17:40:04 oes
100 * Introduced get_header_value()
101 * Removed http->user_agent, csp->referrer and csp->accept_types
102 * Removed client_accept()
104 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
105 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
106 * threads to call select() simultaneously. So, it's time to do a real, live,
107 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
108 * (native). Both versions will work, but using __OS2__ offers multi-threading.
110 * Revision 1.37 2001/10/23 21:36:02 jongfoster
111 * Documenting sed()'s error behaviou (doc change only)
113 * Revision 1.36 2001/10/13 12:51:51 joergs
114 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
115 * force-load), instead crumble Host: and add it (again) in client_host_adder
116 * (in case we get a HTTP/1.0 request without Host: header and forward it to
117 * a HTTP/1.1 server/proxy).
119 * Revision 1.35 2001/10/09 22:39:21 jongfoster
120 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
123 * Revision 1.34 2001/10/07 18:50:55 oes
124 * Added server_content_encoding, renamed server_transfer_encoding
126 * Revision 1.33 2001/10/07 18:04:49 oes
127 * Changed server_http11 to server_http and its pattern to "HTTP".
128 * Additional functionality: it now saves the HTTP status into
129 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
131 * Revision 1.32 2001/10/07 15:43:28 oes
132 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
133 * client_te and client_accept_encoding_adder, triggered by the new
134 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
135 * changed to allow only identity and chunked, and the TE header is
136 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
138 * parse_http_request no longer does anything than parsing. The rewriting
139 * of http->cmd and version mangling are gone. It now also recognizes
140 * the put and delete methods and saves the url in http->url. Removed
143 * renamed content_type and content_length to have the server_ prefix
145 * server_content_type now only works if csp->content_type != CT_TABOO
147 * added server_transfer_encoding, which
148 * - Sets CT_TABOO to prohibit filtering if encoding compresses
149 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
150 * - Change from "chunked" to "identity" if body was chunked
151 * but has been de-chunked for filtering.
153 * added server_content_md5 which crunches any Content-MD5 headers
154 * if the body was modified.
156 * made server_http11 conditional on +downgrade action
158 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
160 * Revision 1.31 2001/10/05 14:25:02 oes
161 * Crumble Keep-Alive from Server
163 * Revision 1.30 2001/09/29 12:56:03 joergs
164 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
166 * Revision 1.29 2001/09/24 21:09:24 jongfoster
167 * Fixing 2 memory leaks that Guy spotted, where the paramater to
168 * enlist() was not being free()d.
170 * Revision 1.28 2001/09/22 16:32:28 jongfoster
171 * Removing unused #includes.
173 * Revision 1.27 2001/09/20 15:45:25 steudten
175 * add casting from size_t to int for printf()
176 * remove local variable shadow s2
178 * Revision 1.26 2001/09/16 17:05:14 jongfoster
179 * Removing unused #include showarg.h
181 * Revision 1.25 2001/09/16 13:21:27 jongfoster
182 * Changes to use new list functions.
184 * Revision 1.24 2001/09/13 23:05:50 jongfoster
185 * Changing the string paramater to the header parsers a "const".
187 * Revision 1.23 2001/09/12 18:08:19 steudten
189 * In parse_http_request() header rewriting miss the host value, so
190 * from http://www.mydomain.com the result was just " / " not
191 * http://www.mydomain.com/ in case we forward.
193 * Revision 1.22 2001/09/10 10:58:53 oes
194 * Silenced compiler warnings
196 * Revision 1.21 2001/07/31 14:46:00 oes
197 * - Persistant connections now suppressed
198 * - sed() no longer appends empty header to csp->headers
200 * Revision 1.20 2001/07/30 22:08:36 jongfoster
201 * Tidying up #defines:
202 * - All feature #defines are now of the form FEATURE_xxx
203 * - Permanently turned off WIN_GUI_EDIT
204 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
206 * Revision 1.19 2001/07/25 17:21:54 oes
207 * client_uagent now saves copy of User-Agent: header value
209 * Revision 1.18 2001/07/13 14:02:46 oes
210 * - Included fix to repair broken HTTP requests that
211 * don't contain a path, not even '/'.
212 * - Removed all #ifdef PCRS
213 * - content_type now always inspected and classified as
214 * text, gif or other.
215 * - formatting / comments
217 * Revision 1.17 2001/06/29 21:45:41 oes
218 * Indentation, CRLF->LF, Tab-> Space
220 * Revision 1.16 2001/06/29 13:32:42 oes
222 * - Adapted free_http_request
223 * - Removed logentry from cancelled commit
225 * Revision 1.15 2001/06/03 19:12:38 oes
226 * deleted const struct interceptors
228 * Revision 1.14 2001/06/01 18:49:17 jongfoster
229 * Replaced "list_share" with "list" - the tiny memory gain was not
230 * worth the extra complexity.
232 * Revision 1.13 2001/05/31 21:30:33 jongfoster
233 * Removed list code - it's now in list.[ch]
234 * Renamed "permission" to "action", and changed many features
235 * to use the actions file rather than the global config.
237 * Revision 1.12 2001/05/31 17:33:13 oes
241 * Revision 1.11 2001/05/29 20:11:19 joergs
242 * '/ * inside comment' warning removed.
244 * Revision 1.10 2001/05/29 09:50:24 jongfoster
245 * Unified blocklist/imagelist/permissionslist.
246 * File format is still under discussion, but the internal changes
249 * Also modified interceptor behaviour:
250 * - We now intercept all URLs beginning with one of the following
251 * prefixes (and *only* these prefixes):
253 * * http://ijbswa.sf.net/config/
254 * * http://ijbswa.sourceforge.net/config/
255 * - New interceptors "home page" - go to http://i.j.b/ to see it.
256 * - Internal changes so that intercepted and fast redirect pages
257 * are not replaced with an image.
258 * - Interceptors now have the option to send a binary page direct
259 * to the client. (i.e. ijb-send-banner uses this)
260 * - Implemented show-url-info interceptor. (Which is why I needed
261 * the above interceptors changes - a typical URL is
262 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
263 * The previous mechanism would not have intercepted that, and
264 * if it had been intercepted then it then it would have replaced
267 * Revision 1.9 2001/05/28 17:26:33 jongfoster
268 * Fixing segfault if last header was crunched.
269 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
270 * can use the cross-platform sprintf() instead.)
272 * Revision 1.8 2001/05/27 22:17:04 oes
274 * - re_process_buffer no longer writes the modified buffer
275 * to the client, which was very ugly. It now returns the
276 * buffer, which it is then written by chat.
278 * - content_length now adjusts the Content-Length: header
279 * for modified documents rather than crunch()ing it.
280 * (Length info in csp->content_length, which is 0 for
281 * unmodified documents)
283 * - For this to work, sed() is called twice when filtering.
285 * Revision 1.7 2001/05/27 13:19:06 oes
286 * Patched Joergs solution for the content-length in.
288 * Revision 1.6 2001/05/26 13:39:32 jongfoster
289 * Only crunches Content-Length header if applying RE filtering.
290 * Without this fix, Microsoft Windows Update wouldn't work.
292 * Revision 1.5 2001/05/26 00:28:36 jongfoster
293 * Automatic reloading of config file.
294 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
295 * Most of the global variables have been moved to a new
296 * struct configuration_spec, accessed through csp->config->globalname
297 * Most of the globals remaining are used by the Win32 GUI.
299 * Revision 1.4 2001/05/22 18:46:04 oes
301 * - Enabled filtering banners by size rather than URL
302 * by adding patterns that replace all standard banner
303 * sizes with the "Junkbuster" gif to the re_filterfile
305 * - Enabled filtering WebBugs by providing a pattern
306 * which kills all 1x1 images
308 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
309 * which is selected by the (nonstandard and therefore
310 * capital) letter 'U' in the option string.
311 * It causes the quantifiers to be ungreedy by default.
312 * Appending a ? turns back to greedy (!).
314 * - Added a new interceptor ijb-send-banner, which
315 * sends back the "Junkbuster" gif. Without imagelist or
316 * MSIE detection support, or if tinygif = 1, or the
317 * URL isn't recognized as an imageurl, a lame HTML
318 * explanation is sent instead.
320 * - Added new feature, which permits blocking remote
321 * script redirects and firing back a local redirect
323 * The feature is conditionally compiled, i.e. it
324 * can be disabled with --disable-fast-redirects,
325 * plus it must be activated by a "fast-redirects"
326 * line in the config file, has its own log level
327 * and of course wants to be displayed by show-proxy-args
328 * Note: Boy, all the #ifdefs in 1001 locations and
329 * all the fumbling with configure.in and acconfig.h
330 * were *way* more work than the feature itself :-(
332 * - Because a generic redirect template was needed for
333 * this, tinygif = 3 now uses the same.
335 * - Moved GIFs, and other static HTTP response templates
340 * - Removed some >400 CRs again (Jon, you really worked
343 * Revision 1.3 2001/05/20 01:21:20 jongfoster
344 * Version 2.9.4 checkin.
345 * - Merged popupfile and cookiefile, and added control over PCRS
346 * filtering, in new "permissionsfile".
347 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
348 * file error you now get a message box (in the Win32 GUI) rather
349 * than the program exiting with no explanation.
350 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
352 * - Removed tabs from "config"
353 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
354 * - Bumped up version number.
356 * Revision 1.2 2001/05/17 23:02:36 oes
357 * - Made referrer option accept 'L' as a substitute for '§'
359 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
360 * Initial import of version 2.9.3 source tree
363 *********************************************************************/
370 #include <sys/types.h>
378 #if !defined(_WIN32) && !defined(__OS2__)
388 #include "jbsockets.h"
389 #include "miscutil.h"
392 const char parsers_h_rcs[] = PARSERS_H_VERSION;
394 /* Fix a problem with Solaris. There should be no effect on other
396 * Solaris's isspace() is a macro which uses it's argument directly
397 * as an array index. Therefore we need to make sure that high-bit
398 * characters generate +ve values, and ideally we also want to make
399 * the argument match the declared parameter type of "int".
401 * Why did they write a character function that can't take a simple
402 * "char" argument? Doh!
404 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
405 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
408 const struct parsers client_patterns[] = {
409 { "referer:", 8, client_referrer },
410 { "user-agent:", 11, client_uagent },
411 { "ua-", 3, client_ua },
412 { "from:", 5, client_from },
413 { "cookie:", 7, client_send_cookie },
414 { "x-forwarded-for:", 16, client_x_forwarded },
415 { "Accept-Encoding:", 16, client_accept_encoding },
416 { "TE:", 3, client_te },
417 { "Host:", 5, crumble },
418 /* { "if-modified-since:", 18, crumble }, */
419 { "Keep-Alive:", 11, crumble },
420 { "connection:", 11, crumble },
421 { "proxy-connection:", 17, crumble },
426 const struct parsers server_patterns[] = {
427 { "HTTP", 4, server_http },
428 { "set-cookie:", 11, server_set_cookie },
429 { "connection:", 11, crumble },
430 { "Content-Type:", 13, server_content_type },
431 { "Content-Length:", 15, server_content_length },
432 { "Content-MD5:", 12, server_content_md5 },
433 { "Content-Encoding:", 17, server_content_encoding },
434 { "Transfer-Encoding:", 18, server_transfer_coding },
435 { "Keep-Alive:", 11, crumble },
440 const add_header_func_ptr add_client_headers[] = {
443 client_x_forwarded_adder,
445 client_accept_encoding_adder,
446 connection_close_adder,
451 const add_header_func_ptr add_server_headers[] = {
452 connection_close_adder,
457 /*********************************************************************
459 * Function : flush_socket
461 * Description : Write any pending "buffered" content.
464 * 1 : fd = file descriptor of the socket to read
465 * 2 : csp = Current client state (buffers, headers, etc...)
467 * Returns : On success, the number of bytes written are returned (zero
468 * indicates nothing was written). On error, -1 is returned,
469 * and errno is set appropriately. If count is zero and the
470 * file descriptor refers to a regular file, 0 will be
471 * returned without causing any other effect. For a special
472 * file, the results are not portable.
474 *********************************************************************/
475 int flush_socket(jb_socket fd, struct client_state *csp)
477 struct iob *iob = csp->iob;
478 int len = iob->eod - iob->cur;
485 if (write_socket(fd, iob->cur, (size_t)len))
489 iob->eod = iob->cur = iob->buf;
495 /*********************************************************************
497 * Function : add_to_iob
499 * Description : Add content to the buffered page.
502 * 1 : csp = Current client state (buffers, headers, etc...)
503 * 2 : buf = holds the content to be added to the page
504 * 3 : n = number of bytes to be added
508 *********************************************************************/
509 void add_to_iob(struct client_state *csp, char *buf, int n)
511 struct iob *iob = csp->iob;
515 have = iob->eod - iob->cur;
524 if ((p = (char *)malloc(need + 1)) == NULL)
526 log_error(LOG_LEVEL_FATAL, "malloc() iob failed: %E");
531 /* there is something in the buffer - save it */
532 memcpy(p, iob->cur, have);
534 /* replace the buffer with the new space */
538 /* point to the end of the data */
543 /* the buffer is empty, free it and reinitialize */
548 /* copy the new data into the iob buffer */
549 memcpy(p, buf, (size_t)n);
551 /* point to the end of the data */
554 /* null terminate == cheap insurance */
557 /* set the pointers to the new values */
566 /*********************************************************************
568 * Function : get_header
570 * Description : This (odd) routine will parse the csp->iob
573 * 1 : csp = Current client state (buffers, headers, etc...)
575 * Returns : Any one of the following:
577 * 1) a pointer to a dynamically allocated string that contains a header line
578 * 2) NULL indicating that the end of the header was reached
579 * 3) "" indicating that the end of the iob was reached before finding
580 * a complete header line.
582 *********************************************************************/
583 char *get_header(struct client_state *csp)
589 if ((iob->cur == NULL)
590 || ((p = strchr(iob->cur, '\n')) == NULL))
592 return(""); /* couldn't find a complete header */
597 ret = strdup(iob->cur);
600 /* FIXME No way to handle error properly */
601 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
606 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
608 /* is this a blank linke (i.e. the end of the header) ? */
620 /*********************************************************************
622 * Function : get_header_value
624 * Description : Get the value of a given header from a chained list
625 * of header lines or return NULL if no such header is
626 * present in the list.
629 * 1 : header_list = pointer to list
630 * 2 : header_name = string with name of header to look for.
631 * Trailing colon required, capitalization
634 * Returns : NULL if not found, else value of header
636 *********************************************************************/
637 char *get_header_value(const struct list *header_list, const char *header_name)
639 struct list_entry *cur_entry;
645 length = strlen(header_name);
647 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
651 if (!strncmpic(cur_entry->str, header_name, length))
654 * Found: return pointer to start of value
656 ret = (char *) (cur_entry->str + length);
657 while (*ret && ijb_isspace(*ret)) ret++;
670 /*********************************************************************
674 * Description : add, delete or modify lines in the HTTP header streams.
675 * On entry, it receives a linked list of headers space
676 * that was allocated dynamically (both the list nodes
677 * and the header contents).
679 * As a side effect it frees the space used by the original
683 * 1 : pats = list of patterns to match against headers
684 * 2 : more_headers = list of functions to add more
685 * headers (client or server)
686 * 3 : csp = Current client state (buffers, headers, etc...)
688 * Returns : Single pointer to a fully formed header, or NULL
689 * on out-of-memory error.
691 *********************************************************************/
692 char *sed(const struct parsers pats[],
693 const add_header_func_ptr more_headers[],
694 struct client_state *csp)
696 struct list_entry *p;
697 const struct parsers *v;
698 const add_header_func_ptr *f;
699 jb_err err = JB_ERR_OK;
701 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
703 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
705 /* Header crunch()ed in previous run? -> ignore */
706 if (p->str == NULL) continue;
708 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
710 if (strncmpic(p->str, v->str, v->len) == 0)
712 err = v->parser(csp, (char **)&(p->str));
717 /* place any additional headers on the csp->headers list */
718 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
723 if (err != JB_ERR_OK)
728 return list_to_text(csp->headers);
732 /* here begins the family of parser functions that reformat header lines */
735 /*********************************************************************
739 * Description : This is called if a header matches a pattern to "crunch"
742 * 1 : csp = Current client state (buffers, headers, etc...)
743 * 2 : header = On input, pointer to header to modify.
744 * On output, pointer to the modified header, or NULL
745 * to remove the header. This function frees the
746 * original string if necessary.
748 * Returns : JB_ERR_OK on success, or
749 * JB_ERR_MEMORY on out-of-memory error.
751 *********************************************************************/
752 jb_err crumble(struct client_state *csp, char **header)
754 log_error(LOG_LEVEL_HEADER, "crunch!");
760 /*********************************************************************
762 * Function : server_content_type
764 * Description : Set the content-type for filterable types (text/.*,
765 * javascript and image/gif) unless filtering has been
766 * forbidden (CT_TABOO) while parsing earlier headers.
769 * 1 : csp = Current client state (buffers, headers, etc...)
770 * 2 : header = On input, pointer to header to modify.
771 * On output, pointer to the modified header, or NULL
772 * to remove the header. This function frees the
773 * original string if necessary.
775 * Returns : JB_ERR_OK on success, or
776 * JB_ERR_MEMORY on out-of-memory error.
778 *********************************************************************/
779 jb_err server_content_type(struct client_state *csp, char **header)
781 if (csp->content_type != CT_TABOO)
783 if (strstr(*header, " text/")
784 || strstr(*header, "application/x-javascript"))
785 csp->content_type = CT_TEXT;
786 else if (strstr(*header, " image/gif"))
787 csp->content_type = CT_GIF;
789 csp->content_type = 0;
796 /*********************************************************************
798 * Function : server_transfer_coding
800 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
801 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
802 * - Change from "chunked" to "identity" if body was chunked
803 * but has been de-chunked for filtering.
806 * 1 : csp = Current client state (buffers, headers, etc...)
807 * 2 : header = On input, pointer to header to modify.
808 * On output, pointer to the modified header, or NULL
809 * to remove the header. This function frees the
810 * original string if necessary.
812 * Returns : JB_ERR_OK on success, or
813 * JB_ERR_MEMORY on out-of-memory error.
815 *********************************************************************/
816 jb_err server_transfer_coding(struct client_state *csp, char **header)
819 * Turn off pcrs and gif filtering if body compressed
821 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
823 csp->content_type = CT_TABOO;
827 * Raise flag if body chunked
829 if (strstr(*header, "chunked"))
831 csp->flags |= CSP_FLAG_CHUNKED;
834 * If the body was modified, it has been
835 * de-chunked first, so adjust the header:
837 if (csp->flags & CSP_FLAG_MODIFIED)
840 *header = strdup("Transfer-Encoding: identity");
841 return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
849 /*********************************************************************
851 * Function : server_content_encoding
853 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
856 * 1 : csp = Current client state (buffers, headers, etc...)
857 * 2 : header = On input, pointer to header to modify.
858 * On output, pointer to the modified header, or NULL
859 * to remove the header. This function frees the
860 * original string if necessary.
862 * Returns : JB_ERR_OK on success, or
863 * JB_ERR_MEMORY on out-of-memory error.
865 *********************************************************************/
866 jb_err server_content_encoding(struct client_state *csp, char **header)
869 * Turn off pcrs and gif filtering if body compressed
871 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
873 csp->content_type = CT_TABOO;
881 /*********************************************************************
883 * Function : server_content_length
885 * Description : Adjust Content-Length header if we modified
889 * 1 : csp = Current client state (buffers, headers, etc...)
890 * 2 : header = On input, pointer to header to modify.
891 * On output, pointer to the modified header, or NULL
892 * to remove the header. This function frees the
893 * original string if necessary.
895 * Returns : JB_ERR_OK on success, or
896 * JB_ERR_MEMORY on out-of-memory error.
898 *********************************************************************/
899 jb_err server_content_length(struct client_state *csp, char **header)
901 if (csp->content_length != 0) /* Content length has been modified */
904 *header = (char *) zalloc(100);
907 return JB_ERR_MEMORY;
910 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
912 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
919 /*********************************************************************
921 * Function : server_content_md5
923 * Description : Crumble any Content-MD5 headers if the document was
924 * modified. FIXME: Should we re-compute instead?
927 * 1 : csp = Current client state (buffers, headers, etc...)
928 * 2 : header = On input, pointer to header to modify.
929 * On output, pointer to the modified header, or NULL
930 * to remove the header. This function frees the
931 * original string if necessary.
933 * Returns : JB_ERR_OK on success, or
934 * JB_ERR_MEMORY on out-of-memory error.
936 *********************************************************************/
937 jb_err server_content_md5(struct client_state *csp, char **header)
939 if (csp->flags & CSP_FLAG_MODIFIED)
941 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
949 /*********************************************************************
951 * Function : client_accept_encoding
953 * Description : Rewrite the client's Accept-Encoding header so that
954 * if doesn't allow compression, if the action applies.
955 * Note: For HTTP/1.0 the absence of the header is enough.
958 * 1 : csp = Current client state (buffers, headers, etc...)
959 * 2 : header = On input, pointer to header to modify.
960 * On output, pointer to the modified header, or NULL
961 * to remove the header. This function frees the
962 * original string if necessary.
964 * Returns : JB_ERR_OK on success, or
965 * JB_ERR_MEMORY on out-of-memory error.
967 *********************************************************************/
968 jb_err client_accept_encoding(struct client_state *csp, char **header)
970 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
972 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress content");
975 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
977 *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
980 return JB_ERR_MEMORY;
989 /*********************************************************************
991 * Function : client_te
993 * Description : Rewrite the client's TE header so that
994 * if doesn't allow compression, if the action applies.
997 * 1 : csp = Current client state (buffers, headers, etc...)
998 * 2 : header = On input, pointer to header to modify.
999 * On output, pointer to the modified header, or NULL
1000 * to remove the header. This function frees the
1001 * original string if necessary.
1003 * Returns : JB_ERR_OK on success, or
1004 * JB_ERR_MEMORY on out-of-memory error.
1006 *********************************************************************/
1007 jb_err client_te(struct client_state *csp, char **header)
1009 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1012 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress transfer");
1018 /*********************************************************************
1020 * Function : client_referrer
1022 * Description : Handle the "referer" config setting properly.
1023 * Called from `sed'.
1026 * 1 : csp = Current client state (buffers, headers, etc...)
1027 * 2 : header = On input, pointer to header to modify.
1028 * On output, pointer to the modified header, or NULL
1029 * to remove the header. This function frees the
1030 * original string if necessary.
1032 * Returns : JB_ERR_OK on success, or
1033 * JB_ERR_MEMORY on out-of-memory error.
1035 *********************************************************************/
1036 jb_err client_referrer(struct client_state *csp, char **header)
1038 const char * newval;
1040 #ifdef FEATURE_FORCE_LOAD
1041 /* Since the referrer can include the prefix even
1042 * even if the request itself is non-forced, we must
1043 * clean it unconditionally
1045 strclean(*header, FORCE_PREFIX);
1046 #endif /* def FEATURE_FORCE_LOAD */
1049 * Are we sending referer?
1051 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1058 newval = csp->action->string[ACTION_STRING_REFERER];
1060 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1065 log_error(LOG_LEVEL_HEADER, "crunch!");
1068 else if (0 == strncmpic(newval, "http://", 7))
1071 * We have a specific (fixed) referer we want to send.
1073 log_error(LOG_LEVEL_HEADER, "modified");
1075 *header = strdup("Referer: ");
1076 string_append(header, newval);
1078 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1083 * Forge a referer as http://[hostname:port of REQUEST]/
1084 * to fool stupid checks for in-site links
1086 if (0 != strcmpic(newval, "forge"))
1089 * Invalid choice - but forge is probably the best default.
1091 log_error(LOG_LEVEL_ERROR, "Bad parameter: +referer{%s}", newval);
1094 *header = strdup("Referer: http://");
1095 string_append(header, csp->http->hostport);
1096 string_append(header, "/");
1097 log_error(LOG_LEVEL_HEADER, "crunch+forge to %s", *header);
1099 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1104 /*********************************************************************
1106 * Function : client_uagent
1108 * Description : Handle the "user-agent" config setting properly
1109 * and remember its original value to enable browser
1110 * bug workarounds. Called from `sed'.
1113 * 1 : csp = Current client state (buffers, headers, etc...)
1114 * 2 : header = On input, pointer to header to modify.
1115 * On output, pointer to the modified header, or NULL
1116 * to remove the header. This function frees the
1117 * original string if necessary.
1119 * Returns : JB_ERR_OK on success, or
1120 * JB_ERR_MEMORY on out-of-memory error.
1122 *********************************************************************/
1123 jb_err client_uagent(struct client_state *csp, char **header)
1125 const char * newval;
1127 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1132 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1138 log_error(LOG_LEVEL_HEADER, "modified");
1141 *header = strdup("User-Agent: ");
1142 string_append(header, newval);
1144 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1148 /*********************************************************************
1150 * Function : client_ua
1152 * Description : Handle "ua-" headers properly. Called from `sed'.
1155 * 1 : csp = Current client state (buffers, headers, etc...)
1156 * 2 : header = On input, pointer to header to modify.
1157 * On output, pointer to the modified header, or NULL
1158 * to remove the header. This function frees the
1159 * original string if necessary.
1161 * Returns : JB_ERR_OK on success, or
1162 * JB_ERR_MEMORY on out-of-memory error.
1164 *********************************************************************/
1165 jb_err client_ua(struct client_state *csp, char **header)
1167 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1169 log_error(LOG_LEVEL_HEADER, "crunch!");
1177 /*********************************************************************
1179 * Function : client_from
1181 * Description : Handle the "from" config setting properly.
1182 * Called from `sed'.
1185 * 1 : csp = Current client state (buffers, headers, etc...)
1186 * 2 : header = On input, pointer to header to modify.
1187 * On output, pointer to the modified header, or NULL
1188 * to remove the header. This function frees the
1189 * original string if necessary.
1191 * Returns : JB_ERR_OK on success, or
1192 * JB_ERR_MEMORY on out-of-memory error.
1194 *********************************************************************/
1195 jb_err client_from(struct client_state *csp, char **header)
1197 const char * newval;
1199 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1206 newval = csp->action->string[ACTION_STRING_FROM];
1209 * Are we blocking the e-mail address?
1211 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1213 log_error(LOG_LEVEL_HEADER, "crunch!");
1217 log_error(LOG_LEVEL_HEADER, " modified");
1219 *header = strdup("From: ");
1220 string_append(header, newval);
1222 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1226 /*********************************************************************
1228 * Function : client_send_cookie
1230 * Description : Handle the "cookie" header properly. Called from `sed'.
1231 * If cookie is accepted, add it to the cookie_list,
1232 * else we crunch it. Mmmmmmmmmmm ... cookie ......
1235 * 1 : csp = Current client state (buffers, headers, etc...)
1236 * 2 : header = On input, pointer to header to modify.
1237 * On output, pointer to the modified header, or NULL
1238 * to remove the header. This function frees the
1239 * original string if necessary.
1241 * Returns : JB_ERR_OK on success, or
1242 * JB_ERR_MEMORY on out-of-memory error.
1244 *********************************************************************/
1245 jb_err client_send_cookie(struct client_state *csp, char **header)
1247 jb_err result = JB_ERR_OK;
1249 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
1251 /* strlen("cookie: ") == 8 */
1252 result = enlist(csp->cookie_list, *header + 8);
1256 log_error(LOG_LEVEL_HEADER, " crunch!");
1260 * Always remove the cookie here. The cookie header
1261 * will be sent at the end of the header.
1269 /*********************************************************************
1271 * Function : client_x_forwarded
1273 * Description : Handle the "x-forwarded-for" config setting properly,
1274 * also used in the add_client_headers list. Called from `sed'.
1277 * 1 : csp = Current client state (buffers, headers, etc...)
1278 * 2 : header = On input, pointer to header to modify.
1279 * On output, pointer to the modified header, or NULL
1280 * to remove the header. This function frees the
1281 * original string if necessary.
1283 * Returns : JB_ERR_OK on success, or
1284 * JB_ERR_MEMORY on out-of-memory error.
1286 *********************************************************************/
1287 jb_err client_x_forwarded(struct client_state *csp, char **header)
1289 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
1291 /* Save it so we can re-add it later */
1292 freez(csp->x_forwarded);
1293 csp->x_forwarded = *header;
1296 * Always set *header = NULL, since this information
1297 * will be sent at the end of the header.
1304 log_error(LOG_LEVEL_HEADER, " crunch!");
1310 /* the following functions add headers directly to the header list */
1312 /*********************************************************************
1314 * Function : client_host_adder
1316 * Description : (re)adds the host header. Called from `sed'.
1319 * 1 : csp = Current client state (buffers, headers, etc...)
1321 * Returns : JB_ERR_OK on success, or
1322 * JB_ERR_MEMORY on out-of-memory error.
1324 *********************************************************************/
1325 jb_err client_host_adder(struct client_state *csp)
1331 if ( !csp->http->hostport || !*(csp->http->hostport))
1336 p = strdup("Host: ");
1338 ** remove 'user:pass@' from 'proto://user:pass@host'
1340 if ( (pos = strchr( csp->http->hostport, '@')) != NULL )
1342 string_append(&p, pos+1);
1346 string_append(&p, csp->http->hostport);
1351 return JB_ERR_MEMORY;
1354 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1356 err = enlist(csp->headers, p);
1364 /*********************************************************************
1366 * Function : client_cookie_adder
1368 * Description : Used in the add_client_headers list. Called from `sed'.
1371 * 1 : csp = Current client state (buffers, headers, etc...)
1373 * Returns : JB_ERR_OK on success, or
1374 * JB_ERR_MEMORY on out-of-memory error.
1376 *********************************************************************/
1377 jb_err client_cookie_adder(struct client_state *csp)
1379 struct list_entry *lst;
1381 struct list_entry *list1 = csp->cookie_list->first;
1382 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
1383 int first_cookie = 1;
1386 if ((list1 == NULL) && (list2 == NULL))
1392 tmp = strdup("Cookie: ");
1394 for (lst = list1; lst ; lst = lst->next)
1402 string_append(&tmp, "; ");
1404 string_append(&tmp, lst->str);
1407 for (lst = list2; lst ; lst = lst->next)
1415 string_append(&tmp, "; ");
1417 string_join(&tmp, cookie_encode(lst->str));
1422 return JB_ERR_MEMORY;
1425 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
1426 err = enlist(csp->headers, tmp);
1432 /*********************************************************************
1434 * Function : client_accept_encoding_adder
1436 * Description : Add an Accept-Encoding header to the client's request
1437 * that disables compression if the action applies, and
1438 * the header is not already there. Called from `sed'.
1439 * Note: For HTTP/1.0, the absence of the header is enough.
1442 * 1 : csp = Current client state (buffers, headers, etc...)
1444 * Returns : JB_ERR_OK on success, or
1445 * JB_ERR_MEMORY on out-of-memory error.
1447 *********************************************************************/
1448 jb_err client_accept_encoding_adder(struct client_state *csp)
1450 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1451 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
1453 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
1460 /*********************************************************************
1462 * Function : client_xtra_adder
1464 * Description : Used in the add_client_headers list. Called from `sed'.
1467 * 1 : csp = Current client state (buffers, headers, etc...)
1469 * Returns : JB_ERR_OK on success, or
1470 * JB_ERR_MEMORY on out-of-memory error.
1472 *********************************************************************/
1473 jb_err client_xtra_adder(struct client_state *csp)
1475 struct list_entry *lst;
1478 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
1479 lst ; lst = lst->next)
1481 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
1482 err = enlist(csp->headers, lst->str);
1494 /*********************************************************************
1496 * Function : client_x_forwarded_adder
1498 * Description : Used in the add_client_headers list. Called from `sed'.
1501 * 1 : csp = Current client state (buffers, headers, etc...)
1503 * Returns : JB_ERR_OK on success, or
1504 * JB_ERR_MEMORY on out-of-memory error.
1506 *********************************************************************/
1507 jb_err client_x_forwarded_adder(struct client_state *csp)
1512 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
1517 if (csp->x_forwarded)
1519 p = strdup(csp->x_forwarded);
1520 string_append(&p, ", ");
1524 p = strdup("X-Forwarded-For: ");
1526 string_append(&p, csp->ip_addr_str);
1530 return JB_ERR_MEMORY;
1533 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1534 err = enlist(csp->headers, p);
1541 /*********************************************************************
1543 * Function : connection_close_adder
1545 * Description : Adds a "Connection: close" header to csp->headers
1546 * as a temporary fix for the needed but missing HTTP/1.1
1547 * support. Called from `sed'.
1548 * FIXME: This whole function shouldn't be neccessary!
1551 * 1 : csp = Current client state (buffers, headers, etc...)
1553 * Returns : JB_ERR_OK on success, or
1554 * JB_ERR_MEMORY on out-of-memory error.
1556 *********************************************************************/
1557 jb_err connection_close_adder(struct client_state *csp)
1559 return enlist(csp->headers, "Connection: close");
1563 /*********************************************************************
1565 * Function : server_http
1567 * Description : - Save the HTTP Status into csp->http->status
1568 * - Set CT_TABOO to prevent filtering if the answer
1569 * is a partial range (HTTP status 206)
1570 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
1574 * 1 : csp = Current client state (buffers, headers, etc...)
1575 * 2 : header = On input, pointer to header to modify.
1576 * On output, pointer to the modified header, or NULL
1577 * to remove the header. This function frees the
1578 * original string if necessary.
1580 * Returns : JB_ERR_OK on success, or
1581 * JB_ERR_MEMORY on out-of-memory error.
1583 *********************************************************************/
1584 jb_err server_http(struct client_state *csp, char **header)
1586 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
1587 if (csp->http->status == 206)
1589 csp->content_type = CT_TABOO;
1592 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
1595 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
1602 /*********************************************************************
1604 * Function : server_set_cookie
1606 * Description : Handle the server "cookie" header properly.
1607 * Log cookie to the jar file. Then "crunch" it,
1608 * or accept it. Called from `sed'.
1611 * 1 : csp = Current client state (buffers, headers, etc...)
1612 * 2 : header = On input, pointer to header to modify.
1613 * On output, pointer to the modified header, or NULL
1614 * to remove the header. This function frees the
1615 * original string if necessary.
1617 * Returns : JB_ERR_OK on success, or
1618 * JB_ERR_MEMORY on out-of-memory error.
1620 *********************************************************************/
1621 jb_err server_set_cookie(struct client_state *csp, char **header)
1623 #ifdef FEATURE_COOKIE_JAR
1624 if (csp->config->jar)
1627 * Write timestamp into outbuf.
1629 * Complex because not all OSs have tm_gmtoff or
1630 * the %z field in strftime()
1632 char tempbuf[ BUFFER_SIZE ];
1636 #ifdef HAVE_LOCALTIME_R
1637 tm_now = *localtime_r(&now, &tm_now);
1639 tm_now = *localtime (&now);
1641 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
1643 /* strlen("set-cookie: ") = 12 */
1644 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
1646 #endif /* def FEATURE_COOKIE_JAR */
1648 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
1650 return crumble(csp, header);
1652 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
1654 /* Flag whether or not to log a message */
1657 /* A variable to store the tag we're working on */
1660 /* Skip "Set-Cookie:" (11 characters) in header */
1661 cur_tag = *header + 11;
1663 /* skip whitespace between "Set-Cookie:" and value */
1664 while (*cur_tag && ijb_isspace(*cur_tag))
1669 /* Loop through each tag in the cookie */
1673 char * next_tag = strchr(cur_tag, ';');
1674 if (next_tag != NULL)
1676 /* Skip the ';' character itself */
1679 /* skip whitespace ";" and start of tag */
1680 while (*next_tag && ijb_isspace(*next_tag))
1687 /* "Next tag" is the end of the string */
1688 next_tag = cur_tag + strlen(cur_tag);
1691 /* Is this the "Expires" tag? */
1692 if (strncmpic(cur_tag, "expires=", 8) == 0)
1694 /* Delete the tag by copying the rest of the string over it.
1695 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
1696 * since the behaviour of strcpy is undefined for overlapping
1699 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
1701 /* That changed the header, need to issue a log message */
1704 /* Note that the next tag has now been moved to *cur_tag,
1705 * so we do not need to update the cur_tag pointer.
1710 /* Move on to next cookie tag */
1717 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
1725 #ifdef FEATURE_FORCE_LOAD
1726 /*********************************************************************
1728 * Function : strclean
1730 * Description : In-Situ-Eliminate all occurances of substring in
1734 * 1 : string = string to clean
1735 * 2 : substring = substring to eliminate
1737 * Returns : Number of eliminations
1739 *********************************************************************/
1740 int strclean(const char *string, const char *substring)
1742 int hits = 0, len = strlen(substring);
1745 while((pos = strstr(string, substring)) != NULL)
1752 while (*p++ != '\0');
1759 #endif /* def FEATURE_FORCE_LOAD */