1 const char parsers_rcs[] = "$Id: parsers.c,v 1.51 2002/03/13 00:27:05 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 * Privoxy 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.51 2002/03/13 00:27:05 jongfoster
46 * Revision 1.50 2002/03/12 01:45:35 oes
47 * More verbose logging
49 * Revision 1.49 2002/03/09 20:03:52 jongfoster
50 * - Making various functions return int rather than size_t.
51 * (Undoing a recent change). Since size_t is unsigned on
52 * Windows, functions like read_socket that return -1 on
53 * error cannot return a size_t.
55 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
56 * crashes, and also frequently caused JB to jump to 100%
57 * CPU and stay there. (Because it thought it had just
58 * read ((unsigned)-1) == 4Gb of data...)
60 * - The signature of write_socket has changed, it now simply
61 * returns success=0/failure=nonzero.
63 * - Trying to get rid of a few warnings --with-debug on
64 * Windows, I've introduced a new type "jb_socket". This is
65 * used for the socket file descriptors. On Windows, this
66 * is SOCKET (a typedef for unsigned). Everywhere else, it's
67 * an int. The error value can't be -1 any more, so it's
68 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
69 * Windows it maps to the #define INVALID_SOCKET.)
71 * - The signature of bind_port has changed.
73 * Revision 1.48 2002/03/07 03:46:53 oes
74 * Fixed compiler warnings etc
76 * Revision 1.47 2002/02/20 23:15:13 jongfoster
77 * Parsing functions now handle out-of-memory gracefully by returning
80 * Revision 1.46 2002/01/17 21:03:47 jongfoster
81 * Moving all our URL and URL pattern parsing code to urlmatch.c.
83 * Revision 1.45 2002/01/09 14:33:03 oes
84 * Added support for localtime_r.
86 * Revision 1.44 2001/12/14 01:22:54 steudten
87 * Remove 'user:pass@' from 'proto://user:pass@host' for the
88 * new added header 'Host: ..'. (See Req ID 491818)
90 * Revision 1.43 2001/11/23 00:26:38 jongfoster
91 * Fixing two really stupid errors in my previous commit
93 * Revision 1.42 2001/11/22 21:59:30 jongfoster
94 * Adding code to handle +no-cookies-keep
96 * Revision 1.41 2001/11/05 23:43:05 steudten
97 * Add time+date to log files.
99 * Revision 1.40 2001/10/26 20:13:09 jongfoster
100 * ctype.h is needed in Windows, too.
102 * Revision 1.39 2001/10/26 17:40:04 oes
103 * Introduced get_header_value()
104 * Removed http->user_agent, csp->referrer and csp->accept_types
105 * Removed client_accept()
107 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
108 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
109 * threads to call select() simultaneously. So, it's time to do a real, live,
110 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
111 * (native). Both versions will work, but using __OS2__ offers multi-threading.
113 * Revision 1.37 2001/10/23 21:36:02 jongfoster
114 * Documenting sed()'s error behaviou (doc change only)
116 * Revision 1.36 2001/10/13 12:51:51 joergs
117 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
118 * force-load), instead crumble Host: and add it (again) in client_host_adder
119 * (in case we get a HTTP/1.0 request without Host: header and forward it to
120 * a HTTP/1.1 server/proxy).
122 * Revision 1.35 2001/10/09 22:39:21 jongfoster
123 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
126 * Revision 1.34 2001/10/07 18:50:55 oes
127 * Added server_content_encoding, renamed server_transfer_encoding
129 * Revision 1.33 2001/10/07 18:04:49 oes
130 * Changed server_http11 to server_http and its pattern to "HTTP".
131 * Additional functionality: it now saves the HTTP status into
132 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
134 * Revision 1.32 2001/10/07 15:43:28 oes
135 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
136 * client_te and client_accept_encoding_adder, triggered by the new
137 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
138 * changed to allow only identity and chunked, and the TE header is
139 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
141 * parse_http_request no longer does anything than parsing. The rewriting
142 * of http->cmd and version mangling are gone. It now also recognizes
143 * the put and delete methods and saves the url in http->url. Removed
146 * renamed content_type and content_length to have the server_ prefix
148 * server_content_type now only works if csp->content_type != CT_TABOO
150 * added server_transfer_encoding, which
151 * - Sets CT_TABOO to prohibit filtering if encoding compresses
152 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
153 * - Change from "chunked" to "identity" if body was chunked
154 * but has been de-chunked for filtering.
156 * added server_content_md5 which crunches any Content-MD5 headers
157 * if the body was modified.
159 * made server_http11 conditional on +downgrade action
161 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
163 * Revision 1.31 2001/10/05 14:25:02 oes
164 * Crumble Keep-Alive from Server
166 * Revision 1.30 2001/09/29 12:56:03 joergs
167 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
169 * Revision 1.29 2001/09/24 21:09:24 jongfoster
170 * Fixing 2 memory leaks that Guy spotted, where the paramater to
171 * enlist() was not being free()d.
173 * Revision 1.28 2001/09/22 16:32:28 jongfoster
174 * Removing unused #includes.
176 * Revision 1.27 2001/09/20 15:45:25 steudten
178 * add casting from size_t to int for printf()
179 * remove local variable shadow s2
181 * Revision 1.26 2001/09/16 17:05:14 jongfoster
182 * Removing unused #include showarg.h
184 * Revision 1.25 2001/09/16 13:21:27 jongfoster
185 * Changes to use new list functions.
187 * Revision 1.24 2001/09/13 23:05:50 jongfoster
188 * Changing the string paramater to the header parsers a "const".
190 * Revision 1.23 2001/09/12 18:08:19 steudten
192 * In parse_http_request() header rewriting miss the host value, so
193 * from http://www.mydomain.com the result was just " / " not
194 * http://www.mydomain.com/ in case we forward.
196 * Revision 1.22 2001/09/10 10:58:53 oes
197 * Silenced compiler warnings
199 * Revision 1.21 2001/07/31 14:46:00 oes
200 * - Persistant connections now suppressed
201 * - sed() no longer appends empty header to csp->headers
203 * Revision 1.20 2001/07/30 22:08:36 jongfoster
204 * Tidying up #defines:
205 * - All feature #defines are now of the form FEATURE_xxx
206 * - Permanently turned off WIN_GUI_EDIT
207 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
209 * Revision 1.19 2001/07/25 17:21:54 oes
210 * client_uagent now saves copy of User-Agent: header value
212 * Revision 1.18 2001/07/13 14:02:46 oes
213 * - Included fix to repair broken HTTP requests that
214 * don't contain a path, not even '/'.
215 * - Removed all #ifdef PCRS
216 * - content_type now always inspected and classified as
217 * text, gif or other.
218 * - formatting / comments
220 * Revision 1.17 2001/06/29 21:45:41 oes
221 * Indentation, CRLF->LF, Tab-> Space
223 * Revision 1.16 2001/06/29 13:32:42 oes
225 * - Adapted free_http_request
226 * - Removed logentry from cancelled commit
228 * Revision 1.15 2001/06/03 19:12:38 oes
229 * deleted const struct interceptors
231 * Revision 1.14 2001/06/01 18:49:17 jongfoster
232 * Replaced "list_share" with "list" - the tiny memory gain was not
233 * worth the extra complexity.
235 * Revision 1.13 2001/05/31 21:30:33 jongfoster
236 * Removed list code - it's now in list.[ch]
237 * Renamed "permission" to "action", and changed many features
238 * to use the actions file rather than the global config.
240 * Revision 1.12 2001/05/31 17:33:13 oes
244 * Revision 1.11 2001/05/29 20:11:19 joergs
245 * '/ * inside comment' warning removed.
247 * Revision 1.10 2001/05/29 09:50:24 jongfoster
248 * Unified blocklist/imagelist/permissionslist.
249 * File format is still under discussion, but the internal changes
252 * Also modified interceptor behaviour:
253 * - We now intercept all URLs beginning with one of the following
254 * prefixes (and *only* these prefixes):
256 * * http://ijbswa.sf.net/config/
257 * * http://ijbswa.sourceforge.net/config/
258 * - New interceptors "home page" - go to http://i.j.b/ to see it.
259 * - Internal changes so that intercepted and fast redirect pages
260 * are not replaced with an image.
261 * - Interceptors now have the option to send a binary page direct
262 * to the client. (i.e. ijb-send-banner uses this)
263 * - Implemented show-url-info interceptor. (Which is why I needed
264 * the above interceptors changes - a typical URL is
265 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
266 * The previous mechanism would not have intercepted that, and
267 * if it had been intercepted then it then it would have replaced
270 * Revision 1.9 2001/05/28 17:26:33 jongfoster
271 * Fixing segfault if last header was crunched.
272 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
273 * can use the cross-platform sprintf() instead.)
275 * Revision 1.8 2001/05/27 22:17:04 oes
277 * - re_process_buffer no longer writes the modified buffer
278 * to the client, which was very ugly. It now returns the
279 * buffer, which it is then written by chat.
281 * - content_length now adjusts the Content-Length: header
282 * for modified documents rather than crunch()ing it.
283 * (Length info in csp->content_length, which is 0 for
284 * unmodified documents)
286 * - For this to work, sed() is called twice when filtering.
288 * Revision 1.7 2001/05/27 13:19:06 oes
289 * Patched Joergs solution for the content-length in.
291 * Revision 1.6 2001/05/26 13:39:32 jongfoster
292 * Only crunches Content-Length header if applying RE filtering.
293 * Without this fix, Microsoft Windows Update wouldn't work.
295 * Revision 1.5 2001/05/26 00:28:36 jongfoster
296 * Automatic reloading of config file.
297 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
298 * Most of the global variables have been moved to a new
299 * struct configuration_spec, accessed through csp->config->globalname
300 * Most of the globals remaining are used by the Win32 GUI.
302 * Revision 1.4 2001/05/22 18:46:04 oes
304 * - Enabled filtering banners by size rather than URL
305 * by adding patterns that replace all standard banner
306 * sizes with the "Junkbuster" gif to the re_filterfile
308 * - Enabled filtering WebBugs by providing a pattern
309 * which kills all 1x1 images
311 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
312 * which is selected by the (nonstandard and therefore
313 * capital) letter 'U' in the option string.
314 * It causes the quantifiers to be ungreedy by default.
315 * Appending a ? turns back to greedy (!).
317 * - Added a new interceptor ijb-send-banner, which
318 * sends back the "Junkbuster" gif. Without imagelist or
319 * MSIE detection support, or if tinygif = 1, or the
320 * URL isn't recognized as an imageurl, a lame HTML
321 * explanation is sent instead.
323 * - Added new feature, which permits blocking remote
324 * script redirects and firing back a local redirect
326 * The feature is conditionally compiled, i.e. it
327 * can be disabled with --disable-fast-redirects,
328 * plus it must be activated by a "fast-redirects"
329 * line in the config file, has its own log level
330 * and of course wants to be displayed by show-proxy-args
331 * Note: Boy, all the #ifdefs in 1001 locations and
332 * all the fumbling with configure.in and acconfig.h
333 * were *way* more work than the feature itself :-(
335 * - Because a generic redirect template was needed for
336 * this, tinygif = 3 now uses the same.
338 * - Moved GIFs, and other static HTTP response templates
343 * - Removed some >400 CRs again (Jon, you really worked
346 * Revision 1.3 2001/05/20 01:21:20 jongfoster
347 * Version 2.9.4 checkin.
348 * - Merged popupfile and cookiefile, and added control over PCRS
349 * filtering, in new "permissionsfile".
350 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
351 * file error you now get a message box (in the Win32 GUI) rather
352 * than the program exiting with no explanation.
353 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
355 * - Removed tabs from "config"
356 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
357 * - Bumped up version number.
359 * Revision 1.2 2001/05/17 23:02:36 oes
360 * - Made referrer option accept 'L' as a substitute for '§'
362 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
363 * Initial import of version 2.9.3 source tree
366 *********************************************************************/
373 #include <sys/types.h>
381 #if !defined(_WIN32) && !defined(__OS2__)
391 #include "jbsockets.h"
392 #include "miscutil.h"
395 const char parsers_h_rcs[] = PARSERS_H_VERSION;
397 /* Fix a problem with Solaris. There should be no effect on other
399 * Solaris's isspace() is a macro which uses it's argument directly
400 * as an array index. Therefore we need to make sure that high-bit
401 * characters generate +ve values, and ideally we also want to make
402 * the argument match the declared parameter type of "int".
404 * Why did they write a character function that can't take a simple
405 * "char" argument? Doh!
407 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
408 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
411 const struct parsers client_patterns[] = {
412 { "referer:", 8, client_referrer },
413 { "user-agent:", 11, client_uagent },
414 { "ua-", 3, client_ua },
415 { "from:", 5, client_from },
416 { "cookie:", 7, client_send_cookie },
417 { "x-forwarded-for:", 16, client_x_forwarded },
418 { "Accept-Encoding:", 16, client_accept_encoding },
419 { "TE:", 3, client_te },
420 { "Host:", 5, crumble },
421 /* { "if-modified-since:", 18, crumble }, */
422 { "Keep-Alive:", 11, crumble },
423 { "connection:", 11, crumble },
424 { "proxy-connection:", 17, crumble },
429 const struct parsers server_patterns[] = {
430 { "HTTP", 4, server_http },
431 { "set-cookie:", 11, server_set_cookie },
432 { "connection:", 11, crumble },
433 { "Content-Type:", 13, server_content_type },
434 { "Content-Length:", 15, server_content_length },
435 { "Content-MD5:", 12, server_content_md5 },
436 { "Content-Encoding:", 17, server_content_encoding },
437 { "Transfer-Encoding:", 18, server_transfer_coding },
438 { "Keep-Alive:", 11, crumble },
443 const add_header_func_ptr add_client_headers[] = {
446 client_x_forwarded_adder,
448 client_accept_encoding_adder,
449 connection_close_adder,
454 const add_header_func_ptr add_server_headers[] = {
455 connection_close_adder,
460 /*********************************************************************
462 * Function : flush_socket
464 * Description : Write any pending "buffered" content.
467 * 1 : fd = file descriptor of the socket to read
468 * 2 : csp = Current client state (buffers, headers, etc...)
470 * Returns : On success, the number of bytes written are returned (zero
471 * indicates nothing was written). On error, -1 is returned,
472 * and errno is set appropriately. If count is zero and the
473 * file descriptor refers to a regular file, 0 will be
474 * returned without causing any other effect. For a special
475 * file, the results are not portable.
477 *********************************************************************/
478 int flush_socket(jb_socket fd, struct client_state *csp)
480 struct iob *iob = csp->iob;
481 int len = iob->eod - iob->cur;
488 if (write_socket(fd, iob->cur, (size_t)len))
492 iob->eod = iob->cur = iob->buf;
498 /*********************************************************************
500 * Function : add_to_iob
502 * Description : Add content to the buffered page.
505 * 1 : csp = Current client state (buffers, headers, etc...)
506 * 2 : buf = holds the content to be added to the page
507 * 3 : n = number of bytes to be added
511 *********************************************************************/
512 void add_to_iob(struct client_state *csp, char *buf, int n)
514 struct iob *iob = csp->iob;
518 have = iob->eod - iob->cur;
527 if ((p = (char *)malloc(need + 1)) == NULL)
529 log_error(LOG_LEVEL_FATAL, "malloc() iob failed: %E");
534 /* there is something in the buffer - save it */
535 memcpy(p, iob->cur, have);
537 /* replace the buffer with the new space */
541 /* point to the end of the data */
546 /* the buffer is empty, free it and reinitialize */
551 /* copy the new data into the iob buffer */
552 memcpy(p, buf, (size_t)n);
554 /* point to the end of the data */
557 /* null terminate == cheap insurance */
560 /* set the pointers to the new values */
569 /*********************************************************************
571 * Function : get_header
573 * Description : This (odd) routine will parse the csp->iob
576 * 1 : csp = Current client state (buffers, headers, etc...)
578 * Returns : Any one of the following:
580 * 1) a pointer to a dynamically allocated string that contains a header line
581 * 2) NULL indicating that the end of the header was reached
582 * 3) "" indicating that the end of the iob was reached before finding
583 * a complete header line.
585 *********************************************************************/
586 char *get_header(struct client_state *csp)
592 if ((iob->cur == NULL)
593 || ((p = strchr(iob->cur, '\n')) == NULL))
595 return(""); /* couldn't find a complete header */
600 ret = strdup(iob->cur);
603 /* FIXME No way to handle error properly */
604 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
609 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
611 /* is this a blank linke (i.e. the end of the header) ? */
623 /*********************************************************************
625 * Function : get_header_value
627 * Description : Get the value of a given header from a chained list
628 * of header lines or return NULL if no such header is
629 * present in the list.
632 * 1 : header_list = pointer to list
633 * 2 : header_name = string with name of header to look for.
634 * Trailing colon required, capitalization
637 * Returns : NULL if not found, else value of header
639 *********************************************************************/
640 char *get_header_value(const struct list *header_list, const char *header_name)
642 struct list_entry *cur_entry;
648 length = strlen(header_name);
650 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
654 if (!strncmpic(cur_entry->str, header_name, length))
657 * Found: return pointer to start of value
659 ret = (char *) (cur_entry->str + length);
660 while (*ret && ijb_isspace(*ret)) ret++;
673 /*********************************************************************
677 * Description : add, delete or modify lines in the HTTP header streams.
678 * On entry, it receives a linked list of headers space
679 * that was allocated dynamically (both the list nodes
680 * and the header contents).
682 * As a side effect it frees the space used by the original
686 * 1 : pats = list of patterns to match against headers
687 * 2 : more_headers = list of functions to add more
688 * headers (client or server)
689 * 3 : csp = Current client state (buffers, headers, etc...)
691 * Returns : Single pointer to a fully formed header, or NULL
692 * on out-of-memory error.
694 *********************************************************************/
695 char *sed(const struct parsers pats[],
696 const add_header_func_ptr more_headers[],
697 struct client_state *csp)
699 struct list_entry *p;
700 const struct parsers *v;
701 const add_header_func_ptr *f;
702 jb_err err = JB_ERR_OK;
704 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
706 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
708 /* Header crunch()ed in previous run? -> ignore */
709 if (p->str == NULL) continue;
711 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
713 if (strncmpic(p->str, v->str, v->len) == 0)
715 err = v->parser(csp, (char **)&(p->str));
720 /* place any additional headers on the csp->headers list */
721 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
726 if (err != JB_ERR_OK)
731 return list_to_text(csp->headers);
735 /* here begins the family of parser functions that reformat header lines */
738 /*********************************************************************
742 * Description : This is called if a header matches a pattern to "crunch"
745 * 1 : csp = Current client state (buffers, headers, etc...)
746 * 2 : header = On input, pointer to header to modify.
747 * On output, pointer to the modified header, or NULL
748 * to remove the header. This function frees the
749 * original string if necessary.
751 * Returns : JB_ERR_OK on success, or
752 * JB_ERR_MEMORY on out-of-memory error.
754 *********************************************************************/
755 jb_err crumble(struct client_state *csp, char **header)
757 log_error(LOG_LEVEL_HEADER, "crunch!");
763 /*********************************************************************
765 * Function : server_content_type
767 * Description : Set the content-type for filterable types (text/.*,
768 * javascript and image/gif) unless filtering has been
769 * forbidden (CT_TABOO) while parsing earlier headers.
772 * 1 : csp = Current client state (buffers, headers, etc...)
773 * 2 : header = On input, pointer to header to modify.
774 * On output, pointer to the modified header, or NULL
775 * to remove the header. This function frees the
776 * original string if necessary.
778 * Returns : JB_ERR_OK on success, or
779 * JB_ERR_MEMORY on out-of-memory error.
781 *********************************************************************/
782 jb_err server_content_type(struct client_state *csp, char **header)
784 if (csp->content_type != CT_TABOO)
786 if (strstr(*header, " text/")
787 || strstr(*header, "application/x-javascript"))
788 csp->content_type = CT_TEXT;
789 else if (strstr(*header, " image/gif"))
790 csp->content_type = CT_GIF;
792 csp->content_type = 0;
799 /*********************************************************************
801 * Function : server_transfer_coding
803 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
804 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
805 * - Change from "chunked" to "identity" if body was chunked
806 * but has been de-chunked for filtering.
809 * 1 : csp = Current client state (buffers, headers, etc...)
810 * 2 : header = On input, pointer to header to modify.
811 * On output, pointer to the modified header, or NULL
812 * to remove the header. This function frees the
813 * original string if necessary.
815 * Returns : JB_ERR_OK on success, or
816 * JB_ERR_MEMORY on out-of-memory error.
818 *********************************************************************/
819 jb_err server_transfer_coding(struct client_state *csp, char **header)
822 * Turn off pcrs and gif filtering if body compressed
824 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
826 csp->content_type = CT_TABOO;
830 * Raise flag if body chunked
832 if (strstr(*header, "chunked"))
834 csp->flags |= CSP_FLAG_CHUNKED;
837 * If the body was modified, it has been
838 * de-chunked first, so adjust the header:
840 if (csp->flags & CSP_FLAG_MODIFIED)
843 *header = strdup("Transfer-Encoding: identity");
844 return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
852 /*********************************************************************
854 * Function : server_content_encoding
856 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
859 * 1 : csp = Current client state (buffers, headers, etc...)
860 * 2 : header = On input, pointer to header to modify.
861 * On output, pointer to the modified header, or NULL
862 * to remove the header. This function frees the
863 * original string if necessary.
865 * Returns : JB_ERR_OK on success, or
866 * JB_ERR_MEMORY on out-of-memory error.
868 *********************************************************************/
869 jb_err server_content_encoding(struct client_state *csp, char **header)
872 * Turn off pcrs and gif filtering if body compressed
874 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
876 csp->content_type = CT_TABOO;
884 /*********************************************************************
886 * Function : server_content_length
888 * Description : Adjust Content-Length header if we modified
892 * 1 : csp = Current client state (buffers, headers, etc...)
893 * 2 : header = On input, pointer to header to modify.
894 * On output, pointer to the modified header, or NULL
895 * to remove the header. This function frees the
896 * original string if necessary.
898 * Returns : JB_ERR_OK on success, or
899 * JB_ERR_MEMORY on out-of-memory error.
901 *********************************************************************/
902 jb_err server_content_length(struct client_state *csp, char **header)
904 if (csp->content_length != 0) /* Content length has been modified */
907 *header = (char *) zalloc(100);
910 return JB_ERR_MEMORY;
913 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
915 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
922 /*********************************************************************
924 * Function : server_content_md5
926 * Description : Crumble any Content-MD5 headers if the document was
927 * modified. FIXME: Should we re-compute instead?
930 * 1 : csp = Current client state (buffers, headers, etc...)
931 * 2 : header = On input, pointer to header to modify.
932 * On output, pointer to the modified header, or NULL
933 * to remove the header. This function frees the
934 * original string if necessary.
936 * Returns : JB_ERR_OK on success, or
937 * JB_ERR_MEMORY on out-of-memory error.
939 *********************************************************************/
940 jb_err server_content_md5(struct client_state *csp, char **header)
942 if (csp->flags & CSP_FLAG_MODIFIED)
944 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
952 /*********************************************************************
954 * Function : client_accept_encoding
956 * Description : Rewrite the client's Accept-Encoding header so that
957 * if doesn't allow compression, if the action applies.
958 * Note: For HTTP/1.0 the absence of the header is enough.
961 * 1 : csp = Current client state (buffers, headers, etc...)
962 * 2 : header = On input, pointer to header to modify.
963 * On output, pointer to the modified header, or NULL
964 * to remove the header. This function frees the
965 * original string if necessary.
967 * Returns : JB_ERR_OK on success, or
968 * JB_ERR_MEMORY on out-of-memory error.
970 *********************************************************************/
971 jb_err client_accept_encoding(struct client_state *csp, char **header)
973 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
975 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress content");
978 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
980 *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
983 return JB_ERR_MEMORY;
992 /*********************************************************************
994 * Function : client_te
996 * Description : Rewrite the client's TE header so that
997 * if doesn't allow compression, if the action applies.
1000 * 1 : csp = Current client state (buffers, headers, etc...)
1001 * 2 : header = On input, pointer to header to modify.
1002 * On output, pointer to the modified header, or NULL
1003 * to remove the header. This function frees the
1004 * original string if necessary.
1006 * Returns : JB_ERR_OK on success, or
1007 * JB_ERR_MEMORY on out-of-memory error.
1009 *********************************************************************/
1010 jb_err client_te(struct client_state *csp, char **header)
1012 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1015 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress transfer");
1021 /*********************************************************************
1023 * Function : client_referrer
1025 * Description : Handle the "referer" config setting properly.
1026 * Called from `sed'.
1029 * 1 : csp = Current client state (buffers, headers, etc...)
1030 * 2 : header = On input, pointer to header to modify.
1031 * On output, pointer to the modified header, or NULL
1032 * to remove the header. This function frees the
1033 * original string if necessary.
1035 * Returns : JB_ERR_OK on success, or
1036 * JB_ERR_MEMORY on out-of-memory error.
1038 *********************************************************************/
1039 jb_err client_referrer(struct client_state *csp, char **header)
1041 const char * newval;
1043 #ifdef FEATURE_FORCE_LOAD
1044 /* Since the referrer can include the prefix even
1045 * even if the request itself is non-forced, we must
1046 * clean it unconditionally
1048 strclean(*header, FORCE_PREFIX);
1049 #endif /* def FEATURE_FORCE_LOAD */
1052 * Are we sending referer?
1054 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1061 newval = csp->action->string[ACTION_STRING_REFERER];
1063 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1068 log_error(LOG_LEVEL_HEADER, "crunch!");
1071 else if (0 == strncmpic(newval, "http://", 7))
1074 * We have a specific (fixed) referer we want to send.
1076 log_error(LOG_LEVEL_HEADER, "modified");
1078 *header = strdup("Referer: ");
1079 string_append(header, newval);
1081 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1086 * Forge a referer as http://[hostname:port of REQUEST]/
1087 * to fool stupid checks for in-site links
1089 if (0 != strcmpic(newval, "forge"))
1092 * Invalid choice - but forge is probably the best default.
1094 log_error(LOG_LEVEL_ERROR, "Bad parameter: +referer{%s}", newval);
1097 *header = strdup("Referer: http://");
1098 string_append(header, csp->http->hostport);
1099 string_append(header, "/");
1100 log_error(LOG_LEVEL_HEADER, "crunch+forge to %s", *header);
1102 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1107 /*********************************************************************
1109 * Function : client_uagent
1111 * Description : Handle the "user-agent" config setting properly
1112 * and remember its original value to enable browser
1113 * bug workarounds. Called from `sed'.
1116 * 1 : csp = Current client state (buffers, headers, etc...)
1117 * 2 : header = On input, pointer to header to modify.
1118 * On output, pointer to the modified header, or NULL
1119 * to remove the header. This function frees the
1120 * original string if necessary.
1122 * Returns : JB_ERR_OK on success, or
1123 * JB_ERR_MEMORY on out-of-memory error.
1125 *********************************************************************/
1126 jb_err client_uagent(struct client_state *csp, char **header)
1128 const char * newval;
1130 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1135 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1141 log_error(LOG_LEVEL_HEADER, "modified");
1144 *header = strdup("User-Agent: ");
1145 string_append(header, newval);
1147 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1151 /*********************************************************************
1153 * Function : client_ua
1155 * Description : Handle "ua-" headers properly. Called from `sed'.
1158 * 1 : csp = Current client state (buffers, headers, etc...)
1159 * 2 : header = On input, pointer to header to modify.
1160 * On output, pointer to the modified header, or NULL
1161 * to remove the header. This function frees the
1162 * original string if necessary.
1164 * Returns : JB_ERR_OK on success, or
1165 * JB_ERR_MEMORY on out-of-memory error.
1167 *********************************************************************/
1168 jb_err client_ua(struct client_state *csp, char **header)
1170 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1172 log_error(LOG_LEVEL_HEADER, "crunch!");
1180 /*********************************************************************
1182 * Function : client_from
1184 * Description : Handle the "from" config setting properly.
1185 * Called from `sed'.
1188 * 1 : csp = Current client state (buffers, headers, etc...)
1189 * 2 : header = On input, pointer to header to modify.
1190 * On output, pointer to the modified header, or NULL
1191 * to remove the header. This function frees the
1192 * original string if necessary.
1194 * Returns : JB_ERR_OK on success, or
1195 * JB_ERR_MEMORY on out-of-memory error.
1197 *********************************************************************/
1198 jb_err client_from(struct client_state *csp, char **header)
1200 const char * newval;
1202 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1209 newval = csp->action->string[ACTION_STRING_FROM];
1212 * Are we blocking the e-mail address?
1214 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1216 log_error(LOG_LEVEL_HEADER, "crunch!");
1220 log_error(LOG_LEVEL_HEADER, " modified");
1222 *header = strdup("From: ");
1223 string_append(header, newval);
1225 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1229 /*********************************************************************
1231 * Function : client_send_cookie
1233 * Description : Handle the "cookie" header properly. Called from `sed'.
1234 * If cookie is accepted, add it to the cookie_list,
1235 * else we crunch it. Mmmmmmmmmmm ... cookie ......
1238 * 1 : csp = Current client state (buffers, headers, etc...)
1239 * 2 : header = On input, pointer to header to modify.
1240 * On output, pointer to the modified header, or NULL
1241 * to remove the header. This function frees the
1242 * original string if necessary.
1244 * Returns : JB_ERR_OK on success, or
1245 * JB_ERR_MEMORY on out-of-memory error.
1247 *********************************************************************/
1248 jb_err client_send_cookie(struct client_state *csp, char **header)
1250 jb_err result = JB_ERR_OK;
1252 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
1254 /* strlen("cookie: ") == 8 */
1255 result = enlist(csp->cookie_list, *header + 8);
1259 log_error(LOG_LEVEL_HEADER, " crunch!");
1263 * Always remove the cookie here. The cookie header
1264 * will be sent at the end of the header.
1272 /*********************************************************************
1274 * Function : client_x_forwarded
1276 * Description : Handle the "x-forwarded-for" config setting properly,
1277 * also used in the add_client_headers list. Called from `sed'.
1280 * 1 : csp = Current client state (buffers, headers, etc...)
1281 * 2 : header = On input, pointer to header to modify.
1282 * On output, pointer to the modified header, or NULL
1283 * to remove the header. This function frees the
1284 * original string if necessary.
1286 * Returns : JB_ERR_OK on success, or
1287 * JB_ERR_MEMORY on out-of-memory error.
1289 *********************************************************************/
1290 jb_err client_x_forwarded(struct client_state *csp, char **header)
1292 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
1294 /* Save it so we can re-add it later */
1295 freez(csp->x_forwarded);
1296 csp->x_forwarded = *header;
1299 * Always set *header = NULL, since this information
1300 * will be sent at the end of the header.
1307 log_error(LOG_LEVEL_HEADER, " crunch!");
1313 /* the following functions add headers directly to the header list */
1315 /*********************************************************************
1317 * Function : client_host_adder
1319 * Description : (re)adds the host header. Called from `sed'.
1322 * 1 : csp = Current client state (buffers, headers, etc...)
1324 * Returns : JB_ERR_OK on success, or
1325 * JB_ERR_MEMORY on out-of-memory error.
1327 *********************************************************************/
1328 jb_err client_host_adder(struct client_state *csp)
1334 if ( !csp->http->hostport || !*(csp->http->hostport))
1339 p = strdup("Host: ");
1341 ** remove 'user:pass@' from 'proto://user:pass@host'
1343 if ( (pos = strchr( csp->http->hostport, '@')) != NULL )
1345 string_append(&p, pos+1);
1349 string_append(&p, csp->http->hostport);
1354 return JB_ERR_MEMORY;
1357 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1359 err = enlist(csp->headers, p);
1367 /*********************************************************************
1369 * Function : client_cookie_adder
1371 * Description : Used in the add_client_headers list. Called from `sed'.
1374 * 1 : csp = Current client state (buffers, headers, etc...)
1376 * Returns : JB_ERR_OK on success, or
1377 * JB_ERR_MEMORY on out-of-memory error.
1379 *********************************************************************/
1380 jb_err client_cookie_adder(struct client_state *csp)
1382 struct list_entry *lst;
1384 struct list_entry *list1 = csp->cookie_list->first;
1385 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
1386 int first_cookie = 1;
1389 if ((list1 == NULL) && (list2 == NULL))
1395 tmp = strdup("Cookie: ");
1397 for (lst = list1; lst ; lst = lst->next)
1405 string_append(&tmp, "; ");
1407 string_append(&tmp, lst->str);
1410 for (lst = list2; lst ; lst = lst->next)
1418 string_append(&tmp, "; ");
1420 string_join(&tmp, cookie_encode(lst->str));
1425 return JB_ERR_MEMORY;
1428 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
1429 err = enlist(csp->headers, tmp);
1435 /*********************************************************************
1437 * Function : client_accept_encoding_adder
1439 * Description : Add an Accept-Encoding header to the client's request
1440 * that disables compression if the action applies, and
1441 * the header is not already there. Called from `sed'.
1442 * Note: For HTTP/1.0, the absence of the header is enough.
1445 * 1 : csp = Current client state (buffers, headers, etc...)
1447 * Returns : JB_ERR_OK on success, or
1448 * JB_ERR_MEMORY on out-of-memory error.
1450 *********************************************************************/
1451 jb_err client_accept_encoding_adder(struct client_state *csp)
1453 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1454 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
1456 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
1463 /*********************************************************************
1465 * Function : client_xtra_adder
1467 * Description : Used in the add_client_headers list. Called from `sed'.
1470 * 1 : csp = Current client state (buffers, headers, etc...)
1472 * Returns : JB_ERR_OK on success, or
1473 * JB_ERR_MEMORY on out-of-memory error.
1475 *********************************************************************/
1476 jb_err client_xtra_adder(struct client_state *csp)
1478 struct list_entry *lst;
1481 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
1482 lst ; lst = lst->next)
1484 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
1485 err = enlist(csp->headers, lst->str);
1497 /*********************************************************************
1499 * Function : client_x_forwarded_adder
1501 * Description : Used in the add_client_headers list. Called from `sed'.
1504 * 1 : csp = Current client state (buffers, headers, etc...)
1506 * Returns : JB_ERR_OK on success, or
1507 * JB_ERR_MEMORY on out-of-memory error.
1509 *********************************************************************/
1510 jb_err client_x_forwarded_adder(struct client_state *csp)
1515 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
1520 if (csp->x_forwarded)
1522 p = strdup(csp->x_forwarded);
1523 string_append(&p, ", ");
1527 p = strdup("X-Forwarded-For: ");
1529 string_append(&p, csp->ip_addr_str);
1533 return JB_ERR_MEMORY;
1536 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1537 err = enlist(csp->headers, p);
1544 /*********************************************************************
1546 * Function : connection_close_adder
1548 * Description : Adds a "Connection: close" header to csp->headers
1549 * as a temporary fix for the needed but missing HTTP/1.1
1550 * support. Called from `sed'.
1551 * FIXME: This whole function shouldn't be neccessary!
1554 * 1 : csp = Current client state (buffers, headers, etc...)
1556 * Returns : JB_ERR_OK on success, or
1557 * JB_ERR_MEMORY on out-of-memory error.
1559 *********************************************************************/
1560 jb_err connection_close_adder(struct client_state *csp)
1562 return enlist(csp->headers, "Connection: close");
1566 /*********************************************************************
1568 * Function : server_http
1570 * Description : - Save the HTTP Status into csp->http->status
1571 * - Set CT_TABOO to prevent filtering if the answer
1572 * is a partial range (HTTP status 206)
1573 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
1577 * 1 : csp = Current client state (buffers, headers, etc...)
1578 * 2 : header = On input, pointer to header to modify.
1579 * On output, pointer to the modified header, or NULL
1580 * to remove the header. This function frees the
1581 * original string if necessary.
1583 * Returns : JB_ERR_OK on success, or
1584 * JB_ERR_MEMORY on out-of-memory error.
1586 *********************************************************************/
1587 jb_err server_http(struct client_state *csp, char **header)
1589 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
1590 if (csp->http->status == 206)
1592 csp->content_type = CT_TABOO;
1595 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
1598 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
1605 /*********************************************************************
1607 * Function : server_set_cookie
1609 * Description : Handle the server "cookie" header properly.
1610 * Log cookie to the jar file. Then "crunch" it,
1611 * or accept it. Called from `sed'.
1614 * 1 : csp = Current client state (buffers, headers, etc...)
1615 * 2 : header = On input, pointer to header to modify.
1616 * On output, pointer to the modified header, or NULL
1617 * to remove the header. This function frees the
1618 * original string if necessary.
1620 * Returns : JB_ERR_OK on success, or
1621 * JB_ERR_MEMORY on out-of-memory error.
1623 *********************************************************************/
1624 jb_err server_set_cookie(struct client_state *csp, char **header)
1626 #ifdef FEATURE_COOKIE_JAR
1627 if (csp->config->jar)
1630 * Write timestamp into outbuf.
1632 * Complex because not all OSs have tm_gmtoff or
1633 * the %z field in strftime()
1635 char tempbuf[ BUFFER_SIZE ];
1639 #ifdef HAVE_LOCALTIME_R
1640 tm_now = *localtime_r(&now, &tm_now);
1642 tm_now = *localtime (&now);
1644 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
1646 /* strlen("set-cookie: ") = 12 */
1647 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
1649 #endif /* def FEATURE_COOKIE_JAR */
1651 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
1653 return crumble(csp, header);
1655 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
1657 /* Flag whether or not to log a message */
1660 /* A variable to store the tag we're working on */
1663 /* Skip "Set-Cookie:" (11 characters) in header */
1664 cur_tag = *header + 11;
1666 /* skip whitespace between "Set-Cookie:" and value */
1667 while (*cur_tag && ijb_isspace(*cur_tag))
1672 /* Loop through each tag in the cookie */
1676 char * next_tag = strchr(cur_tag, ';');
1677 if (next_tag != NULL)
1679 /* Skip the ';' character itself */
1682 /* skip whitespace ";" and start of tag */
1683 while (*next_tag && ijb_isspace(*next_tag))
1690 /* "Next tag" is the end of the string */
1691 next_tag = cur_tag + strlen(cur_tag);
1694 /* Is this the "Expires" tag? */
1695 if (strncmpic(cur_tag, "expires=", 8) == 0)
1697 /* Delete the tag by copying the rest of the string over it.
1698 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
1699 * since the behaviour of strcpy is undefined for overlapping
1702 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
1704 /* That changed the header, need to issue a log message */
1707 /* Note that the next tag has now been moved to *cur_tag,
1708 * so we do not need to update the cur_tag pointer.
1713 /* Move on to next cookie tag */
1720 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
1728 #ifdef FEATURE_FORCE_LOAD
1729 /*********************************************************************
1731 * Function : strclean
1733 * Description : In-Situ-Eliminate all occurances of substring in
1737 * 1 : string = string to clean
1738 * 2 : substring = substring to eliminate
1740 * Returns : Number of eliminations
1742 *********************************************************************/
1743 int strclean(const char *string, const char *substring)
1745 int hits = 0, len = strlen(substring);
1748 while((pos = strstr(string, substring)) != NULL)
1755 while (*p++ != '\0');
1762 #endif /* def FEATURE_FORCE_LOAD */