1 const char parsers_rcs[] = "$Id: parsers.c,v 1.47 2002/02/20 23:15:13 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.47 2002/02/20 23:15:13 jongfoster
44 * Parsing functions now handle out-of-memory gracefully by returning
47 * Revision 1.46 2002/01/17 21:03:47 jongfoster
48 * Moving all our URL and URL pattern parsing code to urlmatch.c.
50 * Revision 1.45 2002/01/09 14:33:03 oes
51 * Added support for localtime_r.
53 * Revision 1.44 2001/12/14 01:22:54 steudten
54 * Remove 'user:pass@' from 'proto://user:pass@host' for the
55 * new added header 'Host: ..'. (See Req ID 491818)
57 * Revision 1.43 2001/11/23 00:26:38 jongfoster
58 * Fixing two really stupid errors in my previous commit
60 * Revision 1.42 2001/11/22 21:59:30 jongfoster
61 * Adding code to handle +no-cookies-keep
63 * Revision 1.41 2001/11/05 23:43:05 steudten
64 * Add time+date to log files.
66 * Revision 1.40 2001/10/26 20:13:09 jongfoster
67 * ctype.h is needed in Windows, too.
69 * Revision 1.39 2001/10/26 17:40:04 oes
70 * Introduced get_header_value()
71 * Removed http->user_agent, csp->referrer and csp->accept_types
72 * Removed client_accept()
74 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
75 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
76 * threads to call select() simultaneously. So, it's time to do a real, live,
77 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
78 * (native). Both versions will work, but using __OS2__ offers multi-threading.
80 * Revision 1.37 2001/10/23 21:36:02 jongfoster
81 * Documenting sed()'s error behaviou (doc change only)
83 * Revision 1.36 2001/10/13 12:51:51 joergs
84 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
85 * force-load), instead crumble Host: and add it (again) in client_host_adder
86 * (in case we get a HTTP/1.0 request without Host: header and forward it to
87 * a HTTP/1.1 server/proxy).
89 * Revision 1.35 2001/10/09 22:39:21 jongfoster
90 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
93 * Revision 1.34 2001/10/07 18:50:55 oes
94 * Added server_content_encoding, renamed server_transfer_encoding
96 * Revision 1.33 2001/10/07 18:04:49 oes
97 * Changed server_http11 to server_http and its pattern to "HTTP".
98 * Additional functionality: it now saves the HTTP status into
99 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
101 * Revision 1.32 2001/10/07 15:43:28 oes
102 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
103 * client_te and client_accept_encoding_adder, triggered by the new
104 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
105 * changed to allow only identity and chunked, and the TE header is
106 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
108 * parse_http_request no longer does anything than parsing. The rewriting
109 * of http->cmd and version mangling are gone. It now also recognizes
110 * the put and delete methods and saves the url in http->url. Removed
113 * renamed content_type and content_length to have the server_ prefix
115 * server_content_type now only works if csp->content_type != CT_TABOO
117 * added server_transfer_encoding, which
118 * - Sets CT_TABOO to prohibit filtering if encoding compresses
119 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
120 * - Change from "chunked" to "identity" if body was chunked
121 * but has been de-chunked for filtering.
123 * added server_content_md5 which crunches any Content-MD5 headers
124 * if the body was modified.
126 * made server_http11 conditional on +downgrade action
128 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
130 * Revision 1.31 2001/10/05 14:25:02 oes
131 * Crumble Keep-Alive from Server
133 * Revision 1.30 2001/09/29 12:56:03 joergs
134 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
136 * Revision 1.29 2001/09/24 21:09:24 jongfoster
137 * Fixing 2 memory leaks that Guy spotted, where the paramater to
138 * enlist() was not being free()d.
140 * Revision 1.28 2001/09/22 16:32:28 jongfoster
141 * Removing unused #includes.
143 * Revision 1.27 2001/09/20 15:45:25 steudten
145 * add casting from size_t to int for printf()
146 * remove local variable shadow s2
148 * Revision 1.26 2001/09/16 17:05:14 jongfoster
149 * Removing unused #include showarg.h
151 * Revision 1.25 2001/09/16 13:21:27 jongfoster
152 * Changes to use new list functions.
154 * Revision 1.24 2001/09/13 23:05:50 jongfoster
155 * Changing the string paramater to the header parsers a "const".
157 * Revision 1.23 2001/09/12 18:08:19 steudten
159 * In parse_http_request() header rewriting miss the host value, so
160 * from http://www.mydomain.com the result was just " / " not
161 * http://www.mydomain.com/ in case we forward.
163 * Revision 1.22 2001/09/10 10:58:53 oes
164 * Silenced compiler warnings
166 * Revision 1.21 2001/07/31 14:46:00 oes
167 * - Persistant connections now suppressed
168 * - sed() no longer appends empty header to csp->headers
170 * Revision 1.20 2001/07/30 22:08:36 jongfoster
171 * Tidying up #defines:
172 * - All feature #defines are now of the form FEATURE_xxx
173 * - Permanently turned off WIN_GUI_EDIT
174 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
176 * Revision 1.19 2001/07/25 17:21:54 oes
177 * client_uagent now saves copy of User-Agent: header value
179 * Revision 1.18 2001/07/13 14:02:46 oes
180 * - Included fix to repair broken HTTP requests that
181 * don't contain a path, not even '/'.
182 * - Removed all #ifdef PCRS
183 * - content_type now always inspected and classified as
184 * text, gif or other.
185 * - formatting / comments
187 * Revision 1.17 2001/06/29 21:45:41 oes
188 * Indentation, CRLF->LF, Tab-> Space
190 * Revision 1.16 2001/06/29 13:32:42 oes
192 * - Adapted free_http_request
193 * - Removed logentry from cancelled commit
195 * Revision 1.15 2001/06/03 19:12:38 oes
196 * deleted const struct interceptors
198 * Revision 1.14 2001/06/01 18:49:17 jongfoster
199 * Replaced "list_share" with "list" - the tiny memory gain was not
200 * worth the extra complexity.
202 * Revision 1.13 2001/05/31 21:30:33 jongfoster
203 * Removed list code - it's now in list.[ch]
204 * Renamed "permission" to "action", and changed many features
205 * to use the actions file rather than the global config.
207 * Revision 1.12 2001/05/31 17:33:13 oes
211 * Revision 1.11 2001/05/29 20:11:19 joergs
212 * '/ * inside comment' warning removed.
214 * Revision 1.10 2001/05/29 09:50:24 jongfoster
215 * Unified blocklist/imagelist/permissionslist.
216 * File format is still under discussion, but the internal changes
219 * Also modified interceptor behaviour:
220 * - We now intercept all URLs beginning with one of the following
221 * prefixes (and *only* these prefixes):
223 * * http://ijbswa.sf.net/config/
224 * * http://ijbswa.sourceforge.net/config/
225 * - New interceptors "home page" - go to http://i.j.b/ to see it.
226 * - Internal changes so that intercepted and fast redirect pages
227 * are not replaced with an image.
228 * - Interceptors now have the option to send a binary page direct
229 * to the client. (i.e. ijb-send-banner uses this)
230 * - Implemented show-url-info interceptor. (Which is why I needed
231 * the above interceptors changes - a typical URL is
232 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
233 * The previous mechanism would not have intercepted that, and
234 * if it had been intercepted then it then it would have replaced
237 * Revision 1.9 2001/05/28 17:26:33 jongfoster
238 * Fixing segfault if last header was crunched.
239 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
240 * can use the cross-platform sprintf() instead.)
242 * Revision 1.8 2001/05/27 22:17:04 oes
244 * - re_process_buffer no longer writes the modified buffer
245 * to the client, which was very ugly. It now returns the
246 * buffer, which it is then written by chat.
248 * - content_length now adjusts the Content-Length: header
249 * for modified documents rather than crunch()ing it.
250 * (Length info in csp->content_length, which is 0 for
251 * unmodified documents)
253 * - For this to work, sed() is called twice when filtering.
255 * Revision 1.7 2001/05/27 13:19:06 oes
256 * Patched Joergs solution for the content-length in.
258 * Revision 1.6 2001/05/26 13:39:32 jongfoster
259 * Only crunches Content-Length header if applying RE filtering.
260 * Without this fix, Microsoft Windows Update wouldn't work.
262 * Revision 1.5 2001/05/26 00:28:36 jongfoster
263 * Automatic reloading of config file.
264 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
265 * Most of the global variables have been moved to a new
266 * struct configuration_spec, accessed through csp->config->globalname
267 * Most of the globals remaining are used by the Win32 GUI.
269 * Revision 1.4 2001/05/22 18:46:04 oes
271 * - Enabled filtering banners by size rather than URL
272 * by adding patterns that replace all standard banner
273 * sizes with the "Junkbuster" gif to the re_filterfile
275 * - Enabled filtering WebBugs by providing a pattern
276 * which kills all 1x1 images
278 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
279 * which is selected by the (nonstandard and therefore
280 * capital) letter 'U' in the option string.
281 * It causes the quantifiers to be ungreedy by default.
282 * Appending a ? turns back to greedy (!).
284 * - Added a new interceptor ijb-send-banner, which
285 * sends back the "Junkbuster" gif. Without imagelist or
286 * MSIE detection support, or if tinygif = 1, or the
287 * URL isn't recognized as an imageurl, a lame HTML
288 * explanation is sent instead.
290 * - Added new feature, which permits blocking remote
291 * script redirects and firing back a local redirect
293 * The feature is conditionally compiled, i.e. it
294 * can be disabled with --disable-fast-redirects,
295 * plus it must be activated by a "fast-redirects"
296 * line in the config file, has its own log level
297 * and of course wants to be displayed by show-proxy-args
298 * Note: Boy, all the #ifdefs in 1001 locations and
299 * all the fumbling with configure.in and acconfig.h
300 * were *way* more work than the feature itself :-(
302 * - Because a generic redirect template was needed for
303 * this, tinygif = 3 now uses the same.
305 * - Moved GIFs, and other static HTTP response templates
310 * - Removed some >400 CRs again (Jon, you really worked
313 * Revision 1.3 2001/05/20 01:21:20 jongfoster
314 * Version 2.9.4 checkin.
315 * - Merged popupfile and cookiefile, and added control over PCRS
316 * filtering, in new "permissionsfile".
317 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
318 * file error you now get a message box (in the Win32 GUI) rather
319 * than the program exiting with no explanation.
320 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
322 * - Removed tabs from "config"
323 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
324 * - Bumped up version number.
326 * Revision 1.2 2001/05/17 23:02:36 oes
327 * - Made referrer option accept 'L' as a substitute for '§'
329 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
330 * Initial import of version 2.9.3 source tree
333 *********************************************************************/
340 #include <sys/types.h>
348 #if !defined(_WIN32) && !defined(__OS2__)
358 #include "jbsockets.h"
359 #include "miscutil.h"
362 const char parsers_h_rcs[] = PARSERS_H_VERSION;
364 /* Fix a problem with Solaris. There should be no effect on other
366 * Solaris's isspace() is a macro which uses it's argument directly
367 * as an array index. Therefore we need to make sure that high-bit
368 * characters generate +ve values, and ideally we also want to make
369 * the argument match the declared parameter type of "int".
371 * Why did they write a character function that can't take a simple
372 * "char" argument? Doh!
374 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
375 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
378 const struct parsers client_patterns[] = {
379 { "referer:", 8, client_referrer },
380 { "user-agent:", 11, client_uagent },
381 { "ua-", 3, client_ua },
382 { "from:", 5, client_from },
383 { "cookie:", 7, client_send_cookie },
384 { "x-forwarded-for:", 16, client_x_forwarded },
385 { "Accept-Encoding:", 16, client_accept_encoding },
386 { "TE:", 3, client_te },
387 { "Host:", 5, crumble },
388 /* { "if-modified-since:", 18, crumble }, */
389 { "Keep-Alive:", 11, crumble },
390 { "connection:", 11, crumble },
391 { "proxy-connection:", 17, crumble },
396 const struct parsers server_patterns[] = {
397 { "HTTP", 4, server_http },
398 { "set-cookie:", 11, server_set_cookie },
399 { "connection:", 11, crumble },
400 { "Content-Type:", 13, server_content_type },
401 { "Content-Length:", 15, server_content_length },
402 { "Content-MD5:", 12, server_content_md5 },
403 { "Content-Encoding:", 17, server_content_encoding },
404 { "Transfer-Encoding:", 18, server_transfer_coding },
405 { "Keep-Alive:", 11, crumble },
410 const add_header_func_ptr add_client_headers[] = {
413 client_x_forwarded_adder,
415 client_accept_encoding_adder,
416 connection_close_adder,
421 const add_header_func_ptr add_server_headers[] = {
422 connection_close_adder,
427 /*********************************************************************
429 * Function : flush_socket
431 * Description : Write any pending "buffered" content.
434 * 1 : fd = file descriptor of the socket to read
435 * 2 : csp = Current client state (buffers, headers, etc...)
437 * Returns : On success, the number of bytes written are returned (zero
438 * indicates nothing was written). On error, -1 is returned,
439 * and errno is set appropriately. If count is zero and the
440 * file descriptor refers to a regular file, 0 will be
441 * returned without causing any other effect. For a special
442 * file, the results are not portable.
444 *********************************************************************/
445 size_t flush_socket(int fd, struct client_state *csp)
447 struct iob *iob = csp->iob;
448 size_t len = iob->eod - iob->cur;
455 len = write_socket(fd, iob->cur, len);
456 iob->eod = iob->cur = iob->buf;
462 /*********************************************************************
464 * Function : add_to_iob
466 * Description : Add content to the buffered page.
469 * 1 : csp = Current client state (buffers, headers, etc...)
470 * 2 : buf = holds the content to be added to the page
471 * 3 : n = number of bytes to be added
473 * Returns : Number of bytes in the content buffer.
475 *********************************************************************/
476 size_t add_to_iob(struct client_state *csp, char *buf, size_t n)
478 struct iob *iob = csp->iob;
482 have = iob->eod - iob->cur;
491 if ((p = (char *)malloc(need + 1)) == NULL)
493 log_error(LOG_LEVEL_FATAL, "malloc() iob failed: %E");
498 /* there is something in the buffer - save it */
499 memcpy(p, iob->cur, have);
501 /* replace the buffer with the new space */
505 /* point to the end of the data */
510 /* the buffer is empty, free it and reinitialize */
515 /* copy the new data into the iob buffer */
518 /* point to the end of the data */
521 /* null terminate == cheap insurance */
524 /* set the pointers to the new values */
533 /*********************************************************************
535 * Function : get_header
537 * Description : This (odd) routine will parse the csp->iob
540 * 1 : csp = Current client state (buffers, headers, etc...)
542 * Returns : Any one of the following:
544 * 1) a pointer to a dynamically allocated string that contains a header line
545 * 2) NULL indicating that the end of the header was reached
546 * 3) "" indicating that the end of the iob was reached before finding
547 * a complete header line.
549 *********************************************************************/
550 char *get_header(struct client_state *csp)
556 if ((iob->cur == NULL)
557 || ((p = strchr(iob->cur, '\n')) == NULL))
559 return(""); /* couldn't find a complete header */
564 ret = strdup(iob->cur);
567 /* FIXME No way to handle error properly */
568 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
573 if ((q = strchr(ret, '\r'))) *q = '\0';
575 /* is this a blank linke (i.e. the end of the header) ? */
587 /*********************************************************************
589 * Function : get_header_value
591 * Description : Get the value of a given header from a chained list
592 * of header lines or return NULL if no such header is
593 * present in the list.
596 * 1 : header_list = pointer to list
597 * 2 : header_name = string with name of header to look for.
598 * Trailing colon required, capitalization
601 * Returns : NULL if not found, else value of header
603 *********************************************************************/
604 char *get_header_value(const struct list *header_list, const char *header_name)
606 struct list_entry *cur_entry;
612 length = strlen(header_name);
614 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
618 if (!strncmpic(cur_entry->str, header_name, length))
621 * Found: return pointer to start of value
623 ret = (char *) (cur_entry->str + length);
624 while (*ret && ijb_isspace(*ret)) ret++;
637 /*********************************************************************
641 * Description : add, delete or modify lines in the HTTP header streams.
642 * On entry, it receives a linked list of headers space
643 * that was allocated dynamically (both the list nodes
644 * and the header contents).
646 * As a side effect it frees the space used by the original
650 * 1 : pats = list of patterns to match against headers
651 * 2 : more_headers = list of functions to add more
652 * headers (client or server)
653 * 3 : csp = Current client state (buffers, headers, etc...)
655 * Returns : Single pointer to a fully formed header, or NULL
656 * on out-of-memory error.
658 *********************************************************************/
659 char *sed(const struct parsers pats[],
660 const add_header_func_ptr more_headers[],
661 struct client_state *csp)
663 struct list_entry *p;
664 const struct parsers *v;
665 const add_header_func_ptr *f;
666 jb_err err = JB_ERR_OK;
668 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
670 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
672 /* Header crunch()ed in previous run? -> ignore */
673 if (p->str == NULL) continue;
675 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
677 if (strncmpic(p->str, v->str, v->len) == 0)
679 err = v->parser(csp, (char **)&(p->str));
684 /* place any additional headers on the csp->headers list */
685 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
690 if (err != JB_ERR_OK)
695 return list_to_text(csp->headers);
699 /* here begins the family of parser functions that reformat header lines */
702 /*********************************************************************
706 * Description : This is called if a header matches a pattern to "crunch"
709 * 1 : csp = Current client state (buffers, headers, etc...)
710 * 2 : header = On input, pointer to header to modify.
711 * On output, pointer to the modified header, or NULL
712 * to remove the header. This function frees the
713 * original string if necessary.
715 * Returns : JB_ERR_OK on success, or
716 * JB_ERR_MEMORY on out-of-memory error.
718 *********************************************************************/
719 jb_err crumble(struct client_state *csp, char **header)
721 log_error(LOG_LEVEL_HEADER, "crunch!");
727 /*********************************************************************
729 * Function : server_content_type
731 * Description : Set the content-type for filterable types (text/.*,
732 * javascript and image/gif) unless filtering has been
733 * forbidden (CT_TABOO) while parsing earlier headers.
736 * 1 : csp = Current client state (buffers, headers, etc...)
737 * 2 : header = On input, pointer to header to modify.
738 * On output, pointer to the modified header, or NULL
739 * to remove the header. This function frees the
740 * original string if necessary.
742 * Returns : JB_ERR_OK on success, or
743 * JB_ERR_MEMORY on out-of-memory error.
745 *********************************************************************/
746 jb_err server_content_type(struct client_state *csp, char **header)
748 if (csp->content_type != CT_TABOO)
750 if (strstr(*header, " text/")
751 || strstr(*header, "application/x-javascript"))
752 csp->content_type = CT_TEXT;
753 else if (strstr(*header, " image/gif"))
754 csp->content_type = CT_GIF;
756 csp->content_type = 0;
763 /*********************************************************************
765 * Function : server_transfer_coding
767 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
768 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
769 * - Change from "chunked" to "identity" if body was chunked
770 * but has been de-chunked for filtering.
773 * 1 : csp = Current client state (buffers, headers, etc...)
774 * 2 : header = On input, pointer to header to modify.
775 * On output, pointer to the modified header, or NULL
776 * to remove the header. This function frees the
777 * original string if necessary.
779 * Returns : JB_ERR_OK on success, or
780 * JB_ERR_MEMORY on out-of-memory error.
782 *********************************************************************/
783 jb_err server_transfer_coding(struct client_state *csp, char **header)
786 * Turn off pcrs and gif filtering if body compressed
788 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
790 csp->content_type = CT_TABOO;
794 * Raise flag if body chunked
796 if (strstr(*header, "chunked"))
798 csp->flags |= CSP_FLAG_CHUNKED;
801 * If the body was modified, it has been
802 * de-chunked first, so adjust the header:
804 if (csp->flags & CSP_FLAG_MODIFIED)
807 *header = strdup("Transfer-Encoding: identity");
808 return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
816 /*********************************************************************
818 * Function : server_content_encoding
820 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
823 * 1 : csp = Current client state (buffers, headers, etc...)
824 * 2 : header = On input, pointer to header to modify.
825 * On output, pointer to the modified header, or NULL
826 * to remove the header. This function frees the
827 * original string if necessary.
829 * Returns : JB_ERR_OK on success, or
830 * JB_ERR_MEMORY on out-of-memory error.
832 *********************************************************************/
833 jb_err server_content_encoding(struct client_state *csp, char **header)
836 * Turn off pcrs and gif filtering if body compressed
838 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
840 csp->content_type = CT_TABOO;
848 /*********************************************************************
850 * Function : server_content_length
852 * Description : Adjust Content-Length header if we modified
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_length(struct client_state *csp, char **header)
868 if (csp->content_length != 0) /* Content length has been modified */
871 *header = (char *) zalloc(100);
874 return JB_ERR_MEMORY;
877 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
879 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
886 /*********************************************************************
888 * Function : server_content_md5
890 * Description : Crumble any Content-MD5 headers if the document was
891 * modified. FIXME: Should we re-compute instead?
894 * 1 : csp = Current client state (buffers, headers, etc...)
895 * 2 : header = On input, pointer to header to modify.
896 * On output, pointer to the modified header, or NULL
897 * to remove the header. This function frees the
898 * original string if necessary.
900 * Returns : JB_ERR_OK on success, or
901 * JB_ERR_MEMORY on out-of-memory error.
903 *********************************************************************/
904 jb_err server_content_md5(struct client_state *csp, char **header)
906 if (csp->flags & CSP_FLAG_MODIFIED)
908 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
916 /*********************************************************************
918 * Function : client_accept_encoding
920 * Description : Rewrite the client's Accept-Encoding header so that
921 * if doesn't allow compression, if the action applies.
922 * Note: For HTTP/1.0 the absence of the header is enough.
925 * 1 : csp = Current client state (buffers, headers, etc...)
926 * 2 : header = On input, pointer to header to modify.
927 * On output, pointer to the modified header, or NULL
928 * to remove the header. This function frees the
929 * original string if necessary.
931 * Returns : JB_ERR_OK on success, or
932 * JB_ERR_MEMORY on out-of-memory error.
934 *********************************************************************/
935 jb_err client_accept_encoding(struct client_state *csp, char **header)
937 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
939 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress content");
942 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
944 *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
947 return JB_ERR_MEMORY;
956 /*********************************************************************
958 * Function : client_te
960 * Description : Rewrite the client's TE header so that
961 * if doesn't allow compression, if the action applies.
964 * 1 : csp = Current client state (buffers, headers, etc...)
965 * 2 : header = On input, pointer to header to modify.
966 * On output, pointer to the modified header, or NULL
967 * to remove the header. This function frees the
968 * original string if necessary.
970 * Returns : JB_ERR_OK on success, or
971 * JB_ERR_MEMORY on out-of-memory error.
973 *********************************************************************/
974 jb_err client_te(struct client_state *csp, char **header)
976 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
979 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress transfer");
985 /*********************************************************************
987 * Function : client_referrer
989 * Description : Handle the "referer" config setting properly.
993 * 1 : csp = Current client state (buffers, headers, etc...)
994 * 2 : header = On input, pointer to header to modify.
995 * On output, pointer to the modified header, or NULL
996 * to remove the header. This function frees the
997 * original string if necessary.
999 * Returns : JB_ERR_OK on success, or
1000 * JB_ERR_MEMORY on out-of-memory error.
1002 *********************************************************************/
1003 jb_err client_referrer(struct client_state *csp, char **header)
1005 const char * newval;
1007 #ifdef FEATURE_FORCE_LOAD
1008 /* Since the referrer can include the prefix even
1009 * even if the request itself is non-forced, we must
1010 * clean it unconditionally
1012 strclean(*header, FORCE_PREFIX);
1013 #endif /* def FEATURE_FORCE_LOAD */
1016 * Are we sending referer?
1018 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1025 newval = csp->action->string[ACTION_STRING_REFERER];
1027 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1032 log_error(LOG_LEVEL_HEADER, "crunch!");
1035 else if (0 == strncmpic(newval, "http://", 7))
1038 * We have a specific (fixed) referer we want to send.
1040 log_error(LOG_LEVEL_HEADER, "modified");
1042 *header = strdup("Referer: ");
1043 string_append(header, newval);
1045 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1050 * Forge a referer as http://[hostname:port of REQUEST]/
1051 * to fool stupid checks for in-site links
1053 if (0 != strcmpic(newval, "forge"))
1056 * Invalid choice - but forge is probably the best default.
1058 log_error(LOG_LEVEL_ERROR, "Bad parameter: +referer{%s}", newval);
1061 log_error(LOG_LEVEL_HEADER, "crunch+forge!");
1062 *header = strdup("Referer: http://");
1063 string_append(header, csp->http->hostport);
1064 string_append(header, "/");
1066 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1071 /*********************************************************************
1073 * Function : client_uagent
1075 * Description : Handle the "user-agent" config setting properly
1076 * and remember its original value to enable browser
1077 * bug workarounds. Called from `sed'.
1080 * 1 : csp = Current client state (buffers, headers, etc...)
1081 * 2 : header = On input, pointer to header to modify.
1082 * On output, pointer to the modified header, or NULL
1083 * to remove the header. This function frees the
1084 * original string if necessary.
1086 * Returns : JB_ERR_OK on success, or
1087 * JB_ERR_MEMORY on out-of-memory error.
1089 *********************************************************************/
1090 jb_err client_uagent(struct client_state *csp, char **header)
1092 const char * newval;
1094 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1099 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1105 log_error(LOG_LEVEL_HEADER, "modified");
1108 *header = strdup("User-Agent: ");
1109 string_append(header, newval);
1111 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1115 /*********************************************************************
1117 * Function : client_ua
1119 * Description : Handle "ua-" headers properly. Called from `sed'.
1122 * 1 : csp = Current client state (buffers, headers, etc...)
1123 * 2 : header = On input, pointer to header to modify.
1124 * On output, pointer to the modified header, or NULL
1125 * to remove the header. This function frees the
1126 * original string if necessary.
1128 * Returns : JB_ERR_OK on success, or
1129 * JB_ERR_MEMORY on out-of-memory error.
1131 *********************************************************************/
1132 jb_err client_ua(struct client_state *csp, char **header)
1134 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1136 log_error(LOG_LEVEL_HEADER, "crunch!");
1144 /*********************************************************************
1146 * Function : client_from
1148 * Description : Handle the "from" config setting properly.
1149 * 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_from(struct client_state *csp, char **header)
1164 const char * newval;
1166 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1173 newval = csp->action->string[ACTION_STRING_FROM];
1176 * Are we blocking the e-mail address?
1178 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1180 log_error(LOG_LEVEL_HEADER, "crunch!");
1184 log_error(LOG_LEVEL_HEADER, " modified");
1186 *header = strdup("From: ");
1187 string_append(header, newval);
1189 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1193 /*********************************************************************
1195 * Function : client_send_cookie
1197 * Description : Handle the "cookie" header properly. Called from `sed'.
1198 * If cookie is accepted, add it to the cookie_list,
1199 * else we crunch it. Mmmmmmmmmmm ... cookie ......
1202 * 1 : csp = Current client state (buffers, headers, etc...)
1203 * 2 : header = On input, pointer to header to modify.
1204 * On output, pointer to the modified header, or NULL
1205 * to remove the header. This function frees the
1206 * original string if necessary.
1208 * Returns : JB_ERR_OK on success, or
1209 * JB_ERR_MEMORY on out-of-memory error.
1211 *********************************************************************/
1212 jb_err client_send_cookie(struct client_state *csp, char **header)
1214 jb_err result = JB_ERR_OK;
1216 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
1218 /* strlen("cookie: ") == 8 */
1219 result = enlist(csp->cookie_list, *header + 8);
1223 log_error(LOG_LEVEL_HEADER, " crunch!");
1227 * Always remove the cookie here. The cookie header
1228 * will be sent at the end of the header.
1236 /*********************************************************************
1238 * Function : client_x_forwarded
1240 * Description : Handle the "x-forwarded-for" config setting properly,
1241 * also used in the add_client_headers list. Called from `sed'.
1244 * 1 : csp = Current client state (buffers, headers, etc...)
1245 * 2 : header = On input, pointer to header to modify.
1246 * On output, pointer to the modified header, or NULL
1247 * to remove the header. This function frees the
1248 * original string if necessary.
1250 * Returns : JB_ERR_OK on success, or
1251 * JB_ERR_MEMORY on out-of-memory error.
1253 *********************************************************************/
1254 jb_err client_x_forwarded(struct client_state *csp, char **header)
1256 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
1258 /* Save it so we can re-add it later */
1259 freez(csp->x_forwarded);
1260 csp->x_forwarded = *header;
1263 * Always set *header = NULL, since this information
1264 * will be sent at the end of the header.
1271 log_error(LOG_LEVEL_HEADER, " crunch!");
1277 /* the following functions add headers directly to the header list */
1279 /*********************************************************************
1281 * Function : client_host_adder
1283 * Description : (re)adds the host header. Called from `sed'.
1286 * 1 : csp = Current client state (buffers, headers, etc...)
1288 * Returns : JB_ERR_OK on success, or
1289 * JB_ERR_MEMORY on out-of-memory error.
1291 *********************************************************************/
1292 jb_err client_host_adder(struct client_state *csp)
1298 if ( !csp->http->hostport || !*(csp->http->hostport))
1303 p = strdup("Host: ");
1305 ** remove 'user:pass@' from 'proto://user:pass@host'
1307 if ( (pos = strchr( csp->http->hostport, '@')) != NULL )
1309 string_append(&p, pos+1);
1313 string_append(&p, csp->http->hostport);
1318 return JB_ERR_MEMORY;
1321 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1323 err = enlist(csp->headers, p);
1331 /*********************************************************************
1333 * Function : client_cookie_adder
1335 * Description : Used in the add_client_headers list. Called from `sed'.
1338 * 1 : csp = Current client state (buffers, headers, etc...)
1340 * Returns : JB_ERR_OK on success, or
1341 * JB_ERR_MEMORY on out-of-memory error.
1343 *********************************************************************/
1344 jb_err client_cookie_adder(struct client_state *csp)
1346 struct list_entry *lst;
1348 struct list_entry *list1 = csp->cookie_list->first;
1349 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
1350 int first_cookie = 1;
1353 if ((list1 == NULL) && (list2 == NULL))
1359 tmp = strdup("Cookie: ");
1361 for (lst = list1; lst ; lst = lst->next)
1369 string_append(&tmp, "; ");
1371 string_append(&tmp, lst->str);
1374 for (lst = list2; lst ; lst = lst->next)
1382 string_append(&tmp, "; ");
1384 string_join(&tmp, cookie_encode(lst->str));
1389 return JB_ERR_MEMORY;
1392 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
1393 err = enlist(csp->headers, tmp);
1399 /*********************************************************************
1401 * Function : client_accept_encoding_adder
1403 * Description : Add an Accept-Encoding header to the client's request
1404 * that disables compression if the action applies, and
1405 * the header is not already there. Called from `sed'.
1406 * Note: For HTTP/1.0, the absence of the header is enough.
1409 * 1 : csp = Current client state (buffers, headers, etc...)
1411 * Returns : JB_ERR_OK on success, or
1412 * JB_ERR_MEMORY on out-of-memory error.
1414 *********************************************************************/
1415 jb_err client_accept_encoding_adder(struct client_state *csp)
1417 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1418 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
1420 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
1427 /*********************************************************************
1429 * Function : client_xtra_adder
1431 * Description : Used in the add_client_headers list. Called from `sed'.
1434 * 1 : csp = Current client state (buffers, headers, etc...)
1436 * Returns : JB_ERR_OK on success, or
1437 * JB_ERR_MEMORY on out-of-memory error.
1439 *********************************************************************/
1440 jb_err client_xtra_adder(struct client_state *csp)
1442 struct list_entry *lst;
1445 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
1446 lst ; lst = lst->next)
1448 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
1449 err = enlist(csp->headers, lst->str);
1461 /*********************************************************************
1463 * Function : client_x_forwarded_adder
1465 * Description : Used in the add_client_headers list. Called from `sed'.
1468 * 1 : csp = Current client state (buffers, headers, etc...)
1470 * Returns : JB_ERR_OK on success, or
1471 * JB_ERR_MEMORY on out-of-memory error.
1473 *********************************************************************/
1474 jb_err client_x_forwarded_adder(struct client_state *csp)
1479 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
1484 if (csp->x_forwarded)
1486 p = strdup(csp->x_forwarded);
1487 string_append(&p, ", ");
1491 p = strdup("X-Forwarded-For: ");
1493 string_append(&p, csp->ip_addr_str);
1497 return JB_ERR_MEMORY;
1500 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1501 err = enlist(csp->headers, p);
1508 /*********************************************************************
1510 * Function : connection_close_adder
1512 * Description : Adds a "Connection: close" header to csp->headers
1513 * as a temporary fix for the needed but missing HTTP/1.1
1514 * support. Called from `sed'.
1515 * FIXME: This whole function shouldn't be neccessary!
1518 * 1 : csp = Current client state (buffers, headers, etc...)
1520 * Returns : JB_ERR_OK on success, or
1521 * JB_ERR_MEMORY on out-of-memory error.
1523 *********************************************************************/
1524 jb_err connection_close_adder(struct client_state *csp)
1526 return enlist(csp->headers, "Connection: close");
1530 /*********************************************************************
1532 * Function : server_http
1534 * Description : - Save the HTTP Status into csp->http->status
1535 * - Set CT_TABOO to prevent filtering if the answer
1536 * is a partial range (HTTP status 206)
1537 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
1541 * 1 : csp = Current client state (buffers, headers, etc...)
1542 * 2 : header = On input, pointer to header to modify.
1543 * On output, pointer to the modified header, or NULL
1544 * to remove the header. This function frees the
1545 * original string if necessary.
1547 * Returns : JB_ERR_OK on success, or
1548 * JB_ERR_MEMORY on out-of-memory error.
1550 *********************************************************************/
1551 jb_err server_http(struct client_state *csp, char **header)
1553 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
1554 if (csp->http->status == 206)
1556 csp->content_type = CT_TABOO;
1559 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
1562 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
1569 /*********************************************************************
1571 * Function : server_set_cookie
1573 * Description : Handle the server "cookie" header properly.
1574 * Log cookie to the jar file. Then "crunch" it,
1575 * or accept it. Called from `sed'.
1578 * 1 : csp = Current client state (buffers, headers, etc...)
1579 * 2 : header = On input, pointer to header to modify.
1580 * On output, pointer to the modified header, or NULL
1581 * to remove the header. This function frees the
1582 * original string if necessary.
1584 * Returns : JB_ERR_OK on success, or
1585 * JB_ERR_MEMORY on out-of-memory error.
1587 *********************************************************************/
1588 jb_err server_set_cookie(struct client_state *csp, char **header)
1590 #ifdef FEATURE_COOKIE_JAR
1591 if (csp->config->jar)
1594 * Write timestamp into outbuf.
1596 * Complex because not all OSs have tm_gmtoff or
1597 * the %z field in strftime()
1599 char tempbuf[ BUFFER_SIZE ];
1603 #ifdef HAVE_LOCALTIME_R
1604 tm_now = *localtime_r(&now, &tm_now);
1606 tm_now = *localtime (&now);
1608 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
1610 /* strlen("set-cookie: ") = 12 */
1611 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
1613 #endif /* def FEATURE_COOKIE_JAR */
1615 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
1617 return crumble(csp, header);
1619 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
1621 /* Flag whether or not to log a message */
1624 /* A variable to store the tag we're working on */
1627 /* Skip "Set-Cookie:" (11 characters) in header */
1628 cur_tag = *header + 11;
1630 /* skip whitespace between "Set-Cookie:" and value */
1631 while (*cur_tag && ijb_isspace(*cur_tag))
1636 /* Loop through each tag in the cookie */
1640 char * next_tag = strchr(cur_tag, ';');
1641 if (next_tag != NULL)
1643 /* Skip the ';' character itself */
1646 /* skip whitespace ";" and start of tag */
1647 while (*next_tag && ijb_isspace(*next_tag))
1654 /* "Next tag" is the end of the string */
1655 next_tag = cur_tag + strlen(cur_tag);
1658 /* Is this the "Expires" tag? */
1659 if (strncmpic(cur_tag, "expires=", 8) == 0)
1661 /* Delete the tag by copying the rest of the string over it.
1662 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
1663 * since the behaviour of strcpy is undefined for overlapping
1666 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
1668 /* That changed the header, need to issue a log message */
1671 /* Note that the next tag has now been moved to *cur_tag,
1672 * so we do not need to update the cur_tag pointer.
1677 /* Move on to next cookie tag */
1684 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
1692 #ifdef FEATURE_FORCE_LOAD
1693 /*********************************************************************
1695 * Function : strclean
1697 * Description : In-Situ-Eliminate all occurances of substring in
1701 * 1 : string = string to clean
1702 * 2 : substring = substring to eliminate
1704 * Returns : Number of eliminations
1706 *********************************************************************/
1707 int strclean(const char *string, const char *substring)
1709 int hits = 0, len = strlen(substring);
1712 while((pos = strstr(string, substring)))
1719 while (*p++ != '\0');
1726 #endif /* def FEATURE_FORCE_LOAD */