1 const char parsers_rcs[] = "$Id: parsers.c,v 2.0 2002/06/04 14:34:21 jongfoster Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/src/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://www.privoxy.org/
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 2.0 2002/06/04 14:34:21 jongfoster
44 * Moving source files to src/
46 * Revision 1.56 2002/05/12 15:34:22 jongfoster
47 * Fixing typo in a comment
49 * Revision 1.55 2002/05/08 16:01:07 oes
50 * Optimized add_to_iob:
51 * - Use realloc instead of malloc(), memcpy(), free()
52 * - Expand to powers of two if possible, to get
53 * O(log n) reallocs instead of O(n).
54 * - Moved check for buffer limit here from chat
55 * - Report failure via returncode
57 * Revision 1.54 2002/04/02 15:03:16 oes
60 * Revision 1.53 2002/03/26 22:29:55 swa
61 * we have a new homepage!
63 * Revision 1.52 2002/03/24 13:25:43 swa
64 * name change related issues
66 * Revision 1.51 2002/03/13 00:27:05 jongfoster
69 * Revision 1.50 2002/03/12 01:45:35 oes
70 * More verbose logging
72 * Revision 1.49 2002/03/09 20:03:52 jongfoster
73 * - Making various functions return int rather than size_t.
74 * (Undoing a recent change). Since size_t is unsigned on
75 * Windows, functions like read_socket that return -1 on
76 * error cannot return a size_t.
78 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
79 * crashes, and also frequently caused JB to jump to 100%
80 * CPU and stay there. (Because it thought it had just
81 * read ((unsigned)-1) == 4Gb of data...)
83 * - The signature of write_socket has changed, it now simply
84 * returns success=0/failure=nonzero.
86 * - Trying to get rid of a few warnings --with-debug on
87 * Windows, I've introduced a new type "jb_socket". This is
88 * used for the socket file descriptors. On Windows, this
89 * is SOCKET (a typedef for unsigned). Everywhere else, it's
90 * an int. The error value can't be -1 any more, so it's
91 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
92 * Windows it maps to the #define INVALID_SOCKET.)
94 * - The signature of bind_port has changed.
96 * Revision 1.48 2002/03/07 03:46:53 oes
97 * Fixed compiler warnings etc
99 * Revision 1.47 2002/02/20 23:15:13 jongfoster
100 * Parsing functions now handle out-of-memory gracefully by returning
103 * Revision 1.46 2002/01/17 21:03:47 jongfoster
104 * Moving all our URL and URL pattern parsing code to urlmatch.c.
106 * Revision 1.45 2002/01/09 14:33:03 oes
107 * Added support for localtime_r.
109 * Revision 1.44 2001/12/14 01:22:54 steudten
110 * Remove 'user:pass@' from 'proto://user:pass@host' for the
111 * new added header 'Host: ..'. (See Req ID 491818)
113 * Revision 1.43 2001/11/23 00:26:38 jongfoster
114 * Fixing two really stupid errors in my previous commit
116 * Revision 1.42 2001/11/22 21:59:30 jongfoster
117 * Adding code to handle +no-cookies-keep
119 * Revision 1.41 2001/11/05 23:43:05 steudten
120 * Add time+date to log files.
122 * Revision 1.40 2001/10/26 20:13:09 jongfoster
123 * ctype.h is needed in Windows, too.
125 * Revision 1.39 2001/10/26 17:40:04 oes
126 * Introduced get_header_value()
127 * Removed http->user_agent, csp->referrer and csp->accept_types
128 * Removed client_accept()
130 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
131 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
132 * threads to call select() simultaneously. So, it's time to do a real, live,
133 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
134 * (native). Both versions will work, but using __OS2__ offers multi-threading.
136 * Revision 1.37 2001/10/23 21:36:02 jongfoster
137 * Documenting sed()'s error behaviou (doc change only)
139 * Revision 1.36 2001/10/13 12:51:51 joergs
140 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
141 * force-load), instead crumble Host: and add it (again) in client_host_adder
142 * (in case we get a HTTP/1.0 request without Host: header and forward it to
143 * a HTTP/1.1 server/proxy).
145 * Revision 1.35 2001/10/09 22:39:21 jongfoster
146 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
149 * Revision 1.34 2001/10/07 18:50:55 oes
150 * Added server_content_encoding, renamed server_transfer_encoding
152 * Revision 1.33 2001/10/07 18:04:49 oes
153 * Changed server_http11 to server_http and its pattern to "HTTP".
154 * Additional functionality: it now saves the HTTP status into
155 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
157 * Revision 1.32 2001/10/07 15:43:28 oes
158 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
159 * client_te and client_accept_encoding_adder, triggered by the new
160 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
161 * changed to allow only identity and chunked, and the TE header is
162 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
164 * parse_http_request no longer does anything than parsing. The rewriting
165 * of http->cmd and version mangling are gone. It now also recognizes
166 * the put and delete methods and saves the url in http->url. Removed
169 * renamed content_type and content_length to have the server_ prefix
171 * server_content_type now only works if csp->content_type != CT_TABOO
173 * added server_transfer_encoding, which
174 * - Sets CT_TABOO to prohibit filtering if encoding compresses
175 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
176 * - Change from "chunked" to "identity" if body was chunked
177 * but has been de-chunked for filtering.
179 * added server_content_md5 which crunches any Content-MD5 headers
180 * if the body was modified.
182 * made server_http11 conditional on +downgrade action
184 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
186 * Revision 1.31 2001/10/05 14:25:02 oes
187 * Crumble Keep-Alive from Server
189 * Revision 1.30 2001/09/29 12:56:03 joergs
190 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
192 * Revision 1.29 2001/09/24 21:09:24 jongfoster
193 * Fixing 2 memory leaks that Guy spotted, where the paramater to
194 * enlist() was not being free()d.
196 * Revision 1.28 2001/09/22 16:32:28 jongfoster
197 * Removing unused #includes.
199 * Revision 1.27 2001/09/20 15:45:25 steudten
201 * add casting from size_t to int for printf()
202 * remove local variable shadow s2
204 * Revision 1.26 2001/09/16 17:05:14 jongfoster
205 * Removing unused #include showarg.h
207 * Revision 1.25 2001/09/16 13:21:27 jongfoster
208 * Changes to use new list functions.
210 * Revision 1.24 2001/09/13 23:05:50 jongfoster
211 * Changing the string paramater to the header parsers a "const".
213 * Revision 1.23 2001/09/12 18:08:19 steudten
215 * In parse_http_request() header rewriting miss the host value, so
216 * from http://www.mydomain.com the result was just " / " not
217 * http://www.mydomain.com/ in case we forward.
219 * Revision 1.22 2001/09/10 10:58:53 oes
220 * Silenced compiler warnings
222 * Revision 1.21 2001/07/31 14:46:00 oes
223 * - Persistant connections now suppressed
224 * - sed() no longer appends empty header to csp->headers
226 * Revision 1.20 2001/07/30 22:08:36 jongfoster
227 * Tidying up #defines:
228 * - All feature #defines are now of the form FEATURE_xxx
229 * - Permanently turned off WIN_GUI_EDIT
230 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
232 * Revision 1.19 2001/07/25 17:21:54 oes
233 * client_uagent now saves copy of User-Agent: header value
235 * Revision 1.18 2001/07/13 14:02:46 oes
236 * - Included fix to repair broken HTTP requests that
237 * don't contain a path, not even '/'.
238 * - Removed all #ifdef PCRS
239 * - content_type now always inspected and classified as
240 * text, gif or other.
241 * - formatting / comments
243 * Revision 1.17 2001/06/29 21:45:41 oes
244 * Indentation, CRLF->LF, Tab-> Space
246 * Revision 1.16 2001/06/29 13:32:42 oes
248 * - Adapted free_http_request
249 * - Removed logentry from cancelled commit
251 * Revision 1.15 2001/06/03 19:12:38 oes
252 * deleted const struct interceptors
254 * Revision 1.14 2001/06/01 18:49:17 jongfoster
255 * Replaced "list_share" with "list" - the tiny memory gain was not
256 * worth the extra complexity.
258 * Revision 1.13 2001/05/31 21:30:33 jongfoster
259 * Removed list code - it's now in list.[ch]
260 * Renamed "permission" to "action", and changed many features
261 * to use the actions file rather than the global config.
263 * Revision 1.12 2001/05/31 17:33:13 oes
267 * Revision 1.11 2001/05/29 20:11:19 joergs
268 * '/ * inside comment' warning removed.
270 * Revision 1.10 2001/05/29 09:50:24 jongfoster
271 * Unified blocklist/imagelist/permissionslist.
272 * File format is still under discussion, but the internal changes
275 * Also modified interceptor behaviour:
276 * - We now intercept all URLs beginning with one of the following
277 * prefixes (and *only* these prefixes):
279 * * http://ijbswa.sf.net/config/
280 * * http://ijbswa.sourceforge.net/config/
281 * - New interceptors "home page" - go to http://i.j.b/ to see it.
282 * - Internal changes so that intercepted and fast redirect pages
283 * are not replaced with an image.
284 * - Interceptors now have the option to send a binary page direct
285 * to the client. (i.e. ijb-send-banner uses this)
286 * - Implemented show-url-info interceptor. (Which is why I needed
287 * the above interceptors changes - a typical URL is
288 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
289 * The previous mechanism would not have intercepted that, and
290 * if it had been intercepted then it then it would have replaced
293 * Revision 1.9 2001/05/28 17:26:33 jongfoster
294 * Fixing segfault if last header was crunched.
295 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
296 * can use the cross-platform sprintf() instead.)
298 * Revision 1.8 2001/05/27 22:17:04 oes
300 * - re_process_buffer no longer writes the modified buffer
301 * to the client, which was very ugly. It now returns the
302 * buffer, which it is then written by chat.
304 * - content_length now adjusts the Content-Length: header
305 * for modified documents rather than crunch()ing it.
306 * (Length info in csp->content_length, which is 0 for
307 * unmodified documents)
309 * - For this to work, sed() is called twice when filtering.
311 * Revision 1.7 2001/05/27 13:19:06 oes
312 * Patched Joergs solution for the content-length in.
314 * Revision 1.6 2001/05/26 13:39:32 jongfoster
315 * Only crunches Content-Length header if applying RE filtering.
316 * Without this fix, Microsoft Windows Update wouldn't work.
318 * Revision 1.5 2001/05/26 00:28:36 jongfoster
319 * Automatic reloading of config file.
320 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
321 * Most of the global variables have been moved to a new
322 * struct configuration_spec, accessed through csp->config->globalname
323 * Most of the globals remaining are used by the Win32 GUI.
325 * Revision 1.4 2001/05/22 18:46:04 oes
327 * - Enabled filtering banners by size rather than URL
328 * by adding patterns that replace all standard banner
329 * sizes with the "Junkbuster" gif to the re_filterfile
331 * - Enabled filtering WebBugs by providing a pattern
332 * which kills all 1x1 images
334 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
335 * which is selected by the (nonstandard and therefore
336 * capital) letter 'U' in the option string.
337 * It causes the quantifiers to be ungreedy by default.
338 * Appending a ? turns back to greedy (!).
340 * - Added a new interceptor ijb-send-banner, which
341 * sends back the "Junkbuster" gif. Without imagelist or
342 * MSIE detection support, or if tinygif = 1, or the
343 * URL isn't recognized as an imageurl, a lame HTML
344 * explanation is sent instead.
346 * - Added new feature, which permits blocking remote
347 * script redirects and firing back a local redirect
349 * The feature is conditionally compiled, i.e. it
350 * can be disabled with --disable-fast-redirects,
351 * plus it must be activated by a "fast-redirects"
352 * line in the config file, has its own log level
353 * and of course wants to be displayed by show-proxy-args
354 * Note: Boy, all the #ifdefs in 1001 locations and
355 * all the fumbling with configure.in and acconfig.h
356 * were *way* more work than the feature itself :-(
358 * - Because a generic redirect template was needed for
359 * this, tinygif = 3 now uses the same.
361 * - Moved GIFs, and other static HTTP response templates
366 * - Removed some >400 CRs again (Jon, you really worked
369 * Revision 1.3 2001/05/20 01:21:20 jongfoster
370 * Version 2.9.4 checkin.
371 * - Merged popupfile and cookiefile, and added control over PCRS
372 * filtering, in new "permissionsfile".
373 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
374 * file error you now get a message box (in the Win32 GUI) rather
375 * than the program exiting with no explanation.
376 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
378 * - Removed tabs from "config"
379 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
380 * - Bumped up version number.
382 * Revision 1.2 2001/05/17 23:02:36 oes
383 * - Made referrer option accept 'L' as a substitute for '§'
385 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
386 * Initial import of version 2.9.3 source tree
389 *********************************************************************/
396 #include <sys/types.h>
404 #if !defined(_WIN32) && !defined(__OS2__)
414 #include "jbsockets.h"
415 #include "miscutil.h"
418 const char parsers_h_rcs[] = PARSERS_H_VERSION;
420 /* Fix a problem with Solaris. There should be no effect on other
422 * Solaris's isspace() is a macro which uses it's argument directly
423 * as an array index. Therefore we need to make sure that high-bit
424 * characters generate +ve values, and ideally we also want to make
425 * the argument match the declared parameter type of "int".
427 * Why did they write a character function that can't take a simple
428 * "char" argument? Doh!
430 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
431 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
434 const struct parsers client_patterns[] = {
435 { "referer:", 8, client_referrer },
436 { "user-agent:", 11, client_uagent },
437 { "ua-", 3, client_ua },
438 { "from:", 5, client_from },
439 { "cookie:", 7, client_send_cookie },
440 { "x-forwarded-for:", 16, client_x_forwarded },
441 { "Accept-Encoding:", 16, client_accept_encoding },
442 { "TE:", 3, client_te },
443 { "Host:", 5, crumble },
444 /* { "if-modified-since:", 18, crumble }, */
445 { "Keep-Alive:", 11, crumble },
446 { "connection:", 11, crumble },
447 { "proxy-connection:", 17, crumble },
452 const struct parsers server_patterns[] = {
453 { "HTTP", 4, server_http },
454 { "set-cookie:", 11, server_set_cookie },
455 { "connection:", 11, crumble },
456 { "Content-Type:", 13, server_content_type },
457 { "Content-Length:", 15, server_content_length },
458 { "Content-MD5:", 12, server_content_md5 },
459 { "Content-Encoding:", 17, server_content_encoding },
460 { "Transfer-Encoding:", 18, server_transfer_coding },
461 { "Keep-Alive:", 11, crumble },
466 const add_header_func_ptr add_client_headers[] = {
469 client_x_forwarded_adder,
471 client_accept_encoding_adder,
472 connection_close_adder,
477 const add_header_func_ptr add_server_headers[] = {
478 connection_close_adder,
483 /*********************************************************************
485 * Function : flush_socket
487 * Description : Write any pending "buffered" content.
490 * 1 : fd = file descriptor of the socket to read
491 * 2 : csp = Current client state (buffers, headers, etc...)
493 * Returns : On success, the number of bytes written are returned (zero
494 * indicates nothing was written). On error, -1 is returned,
495 * and errno is set appropriately. If count is zero and the
496 * file descriptor refers to a regular file, 0 will be
497 * returned without causing any other effect. For a special
498 * file, the results are not portable.
500 *********************************************************************/
501 int flush_socket(jb_socket fd, struct client_state *csp)
503 struct iob *iob = csp->iob;
504 int len = iob->eod - iob->cur;
511 if (write_socket(fd, iob->cur, (size_t)len))
515 iob->eod = iob->cur = iob->buf;
521 /*********************************************************************
523 * Function : add_to_iob
525 * Description : Add content to the buffered page, expanding the
526 * buffer if necessary.
529 * 1 : csp = Current client state (buffers, headers, etc...)
530 * 2 : buf = holds the content to be added to the page
531 * 3 : n = number of bytes to be added
533 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
534 * or buffer limit reached.
536 *********************************************************************/
537 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
539 struct iob *iob = csp->iob;
540 size_t used, offset, need, want;
543 if (n <= 0) return JB_ERR_OK;
545 used = iob->eod - iob->buf;
546 offset = iob->cur - iob->buf;
550 * If the buffer can't hold the new data, extend it first.
551 * Use the next power of two if possible, else use the actual need.
553 if (need > csp->config->buffer_limit)
555 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
556 return JB_ERR_MEMORY;
559 if (need > iob->size)
561 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
563 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
567 else if (NULL != (p = (char *)realloc(iob->buf, need)))
573 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
574 return JB_ERR_MEMORY;
577 /* Update the iob pointers */
578 iob->cur = p + offset;
583 /* copy the new data into the iob buffer */
584 memcpy(iob->eod, buf, (size_t)n);
586 /* point to the end of the data */
589 /* null terminate == cheap insurance */
597 /*********************************************************************
599 * Function : get_header
601 * Description : This (odd) routine will parse the csp->iob
604 * 1 : csp = Current client state (buffers, headers, etc...)
606 * Returns : Any one of the following:
608 * 1) a pointer to a dynamically allocated string that contains a header line
609 * 2) NULL indicating that the end of the header was reached
610 * 3) "" indicating that the end of the iob was reached before finding
611 * a complete header line.
613 *********************************************************************/
614 char *get_header(struct client_state *csp)
620 if ((iob->cur == NULL)
621 || ((p = strchr(iob->cur, '\n')) == NULL))
623 return(""); /* couldn't find a complete header */
628 ret = strdup(iob->cur);
631 /* FIXME No way to handle error properly */
632 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
637 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
639 /* is this a blank line (i.e. the end of the header) ? */
651 /*********************************************************************
653 * Function : get_header_value
655 * Description : Get the value of a given header from a chained list
656 * of header lines or return NULL if no such header is
657 * present in the list.
660 * 1 : header_list = pointer to list
661 * 2 : header_name = string with name of header to look for.
662 * Trailing colon required, capitalization
665 * Returns : NULL if not found, else value of header
667 *********************************************************************/
668 char *get_header_value(const struct list *header_list, const char *header_name)
670 struct list_entry *cur_entry;
676 length = strlen(header_name);
678 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
682 if (!strncmpic(cur_entry->str, header_name, length))
685 * Found: return pointer to start of value
687 ret = (char *) (cur_entry->str + length);
688 while (*ret && ijb_isspace(*ret)) ret++;
701 /*********************************************************************
705 * Description : add, delete or modify lines in the HTTP header streams.
706 * On entry, it receives a linked list of headers space
707 * that was allocated dynamically (both the list nodes
708 * and the header contents).
710 * As a side effect it frees the space used by the original
714 * 1 : pats = list of patterns to match against headers
715 * 2 : more_headers = list of functions to add more
716 * headers (client or server)
717 * 3 : csp = Current client state (buffers, headers, etc...)
719 * Returns : Single pointer to a fully formed header, or NULL
720 * on out-of-memory error.
722 *********************************************************************/
723 char *sed(const struct parsers pats[],
724 const add_header_func_ptr more_headers[],
725 struct client_state *csp)
727 struct list_entry *p;
728 const struct parsers *v;
729 const add_header_func_ptr *f;
730 jb_err err = JB_ERR_OK;
732 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
734 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
736 /* Header crunch()ed in previous run? -> ignore */
737 if (p->str == NULL) continue;
739 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
741 if (strncmpic(p->str, v->str, v->len) == 0)
743 err = v->parser(csp, (char **)&(p->str));
748 /* place any additional headers on the csp->headers list */
749 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
754 if (err != JB_ERR_OK)
759 return list_to_text(csp->headers);
763 /* here begins the family of parser functions that reformat header lines */
766 /*********************************************************************
770 * Description : This is called if a header matches a pattern to "crunch"
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 crumble(struct client_state *csp, char **header)
785 log_error(LOG_LEVEL_HEADER, "crunch!");
791 /*********************************************************************
793 * Function : server_content_type
795 * Description : Set the content-type for filterable types (text/.*,
796 * javascript and image/gif) unless filtering has been
797 * forbidden (CT_TABOO) while parsing earlier headers.
800 * 1 : csp = Current client state (buffers, headers, etc...)
801 * 2 : header = On input, pointer to header to modify.
802 * On output, pointer to the modified header, or NULL
803 * to remove the header. This function frees the
804 * original string if necessary.
806 * Returns : JB_ERR_OK on success, or
807 * JB_ERR_MEMORY on out-of-memory error.
809 *********************************************************************/
810 jb_err server_content_type(struct client_state *csp, char **header)
812 if (csp->content_type != CT_TABOO)
814 if (strstr(*header, " text/")
815 || strstr(*header, "application/x-javascript"))
816 csp->content_type = CT_TEXT;
817 else if (strstr(*header, " image/gif"))
818 csp->content_type = CT_GIF;
820 csp->content_type = 0;
827 /*********************************************************************
829 * Function : server_transfer_coding
831 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
832 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
833 * - Change from "chunked" to "identity" if body was chunked
834 * but has been de-chunked for filtering.
837 * 1 : csp = Current client state (buffers, headers, etc...)
838 * 2 : header = On input, pointer to header to modify.
839 * On output, pointer to the modified header, or NULL
840 * to remove the header. This function frees the
841 * original string if necessary.
843 * Returns : JB_ERR_OK on success, or
844 * JB_ERR_MEMORY on out-of-memory error.
846 *********************************************************************/
847 jb_err server_transfer_coding(struct client_state *csp, char **header)
850 * Turn off pcrs and gif filtering if body compressed
852 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
854 csp->content_type = CT_TABOO;
858 * Raise flag if body chunked
860 if (strstr(*header, "chunked"))
862 csp->flags |= CSP_FLAG_CHUNKED;
865 * If the body was modified, it has been
866 * de-chunked first, so adjust the header:
868 if (csp->flags & CSP_FLAG_MODIFIED)
871 *header = strdup("Transfer-Encoding: identity");
872 return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
880 /*********************************************************************
882 * Function : server_content_encoding
884 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
887 * 1 : csp = Current client state (buffers, headers, etc...)
888 * 2 : header = On input, pointer to header to modify.
889 * On output, pointer to the modified header, or NULL
890 * to remove the header. This function frees the
891 * original string if necessary.
893 * Returns : JB_ERR_OK on success, or
894 * JB_ERR_MEMORY on out-of-memory error.
896 *********************************************************************/
897 jb_err server_content_encoding(struct client_state *csp, char **header)
900 * Turn off pcrs and gif filtering if body compressed
902 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
904 csp->content_type = CT_TABOO;
912 /*********************************************************************
914 * Function : server_content_length
916 * Description : Adjust Content-Length header if we modified
920 * 1 : csp = Current client state (buffers, headers, etc...)
921 * 2 : header = On input, pointer to header to modify.
922 * On output, pointer to the modified header, or NULL
923 * to remove the header. This function frees the
924 * original string if necessary.
926 * Returns : JB_ERR_OK on success, or
927 * JB_ERR_MEMORY on out-of-memory error.
929 *********************************************************************/
930 jb_err server_content_length(struct client_state *csp, char **header)
932 if (csp->content_length != 0) /* Content length has been modified */
935 *header = (char *) zalloc(100);
938 return JB_ERR_MEMORY;
941 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
943 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
950 /*********************************************************************
952 * Function : server_content_md5
954 * Description : Crumble any Content-MD5 headers if the document was
955 * modified. FIXME: Should we re-compute instead?
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 server_content_md5(struct client_state *csp, char **header)
970 if (csp->flags & CSP_FLAG_MODIFIED)
972 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
980 /*********************************************************************
982 * Function : client_accept_encoding
984 * Description : Rewrite the client's Accept-Encoding header so that
985 * if doesn't allow compression, if the action applies.
986 * Note: For HTTP/1.0 the absence of the header is enough.
989 * 1 : csp = Current client state (buffers, headers, etc...)
990 * 2 : header = On input, pointer to header to modify.
991 * On output, pointer to the modified header, or NULL
992 * to remove the header. This function frees the
993 * original string if necessary.
995 * Returns : JB_ERR_OK on success, or
996 * JB_ERR_MEMORY on out-of-memory error.
998 *********************************************************************/
999 jb_err client_accept_encoding(struct client_state *csp, char **header)
1001 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1003 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress content");
1006 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1008 *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1009 if (*header == NULL)
1011 return JB_ERR_MEMORY;
1020 /*********************************************************************
1022 * Function : client_te
1024 * Description : Rewrite the client's TE header so that
1025 * if doesn't allow compression, if the action applies.
1028 * 1 : csp = Current client state (buffers, headers, etc...)
1029 * 2 : header = On input, pointer to header to modify.
1030 * On output, pointer to the modified header, or NULL
1031 * to remove the header. This function frees the
1032 * original string if necessary.
1034 * Returns : JB_ERR_OK on success, or
1035 * JB_ERR_MEMORY on out-of-memory error.
1037 *********************************************************************/
1038 jb_err client_te(struct client_state *csp, char **header)
1040 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1043 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress transfer");
1049 /*********************************************************************
1051 * Function : client_referrer
1053 * Description : Handle the "referer" config setting properly.
1054 * Called from `sed'.
1057 * 1 : csp = Current client state (buffers, headers, etc...)
1058 * 2 : header = On input, pointer to header to modify.
1059 * On output, pointer to the modified header, or NULL
1060 * to remove the header. This function frees the
1061 * original string if necessary.
1063 * Returns : JB_ERR_OK on success, or
1064 * JB_ERR_MEMORY on out-of-memory error.
1066 *********************************************************************/
1067 jb_err client_referrer(struct client_state *csp, char **header)
1071 #ifdef FEATURE_FORCE_LOAD
1072 /* Since the referrer can include the prefix even
1073 * even if the request itself is non-forced, we must
1074 * clean it unconditionally
1076 strclean(*header, FORCE_PREFIX);
1077 #endif /* def FEATURE_FORCE_LOAD */
1080 * Are we sending referer?
1082 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1089 newval = csp->action->string[ACTION_STRING_REFERER];
1091 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1096 log_error(LOG_LEVEL_HEADER, "crunch!");
1099 else if (0 == strncmpic(newval, "http://", 7))
1102 * We have a specific (fixed) referer we want to send.
1104 log_error(LOG_LEVEL_HEADER, "modified");
1106 *header = strdup("Referer: ");
1107 string_append(header, newval);
1109 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1114 * Forge a referer as http://[hostname:port of REQUEST]/
1115 * to fool stupid checks for in-site links
1117 if (0 != strcmpic(newval, "forge"))
1120 * Invalid choice - but forge is probably the best default.
1122 log_error(LOG_LEVEL_ERROR, "Bad parameter: +referer{%s}", newval);
1125 *header = strdup("Referer: http://");
1126 string_append(header, csp->http->hostport);
1127 string_append(header, "/");
1128 log_error(LOG_LEVEL_HEADER, "crunch+forge to %s", *header);
1130 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1135 /*********************************************************************
1137 * Function : client_uagent
1139 * Description : Handle the "user-agent" config setting properly
1140 * and remember its original value to enable browser
1141 * bug workarounds. Called from `sed'.
1144 * 1 : csp = Current client state (buffers, headers, etc...)
1145 * 2 : header = On input, pointer to header to modify.
1146 * On output, pointer to the modified header, or NULL
1147 * to remove the header. This function frees the
1148 * original string if necessary.
1150 * Returns : JB_ERR_OK on success, or
1151 * JB_ERR_MEMORY on out-of-memory error.
1153 *********************************************************************/
1154 jb_err client_uagent(struct client_state *csp, char **header)
1158 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1163 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1169 log_error(LOG_LEVEL_HEADER, "modified");
1172 *header = strdup("User-Agent: ");
1173 string_append(header, newval);
1175 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1179 /*********************************************************************
1181 * Function : client_ua
1183 * Description : Handle "ua-" headers properly. Called from `sed'.
1186 * 1 : csp = Current client state (buffers, headers, etc...)
1187 * 2 : header = On input, pointer to header to modify.
1188 * On output, pointer to the modified header, or NULL
1189 * to remove the header. This function frees the
1190 * original string if necessary.
1192 * Returns : JB_ERR_OK on success, or
1193 * JB_ERR_MEMORY on out-of-memory error.
1195 *********************************************************************/
1196 jb_err client_ua(struct client_state *csp, char **header)
1198 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1200 log_error(LOG_LEVEL_HEADER, "crunch!");
1208 /*********************************************************************
1210 * Function : client_from
1212 * Description : Handle the "from" config setting properly.
1213 * Called from `sed'.
1216 * 1 : csp = Current client state (buffers, headers, etc...)
1217 * 2 : header = On input, pointer to header to modify.
1218 * On output, pointer to the modified header, or NULL
1219 * to remove the header. This function frees the
1220 * original string if necessary.
1222 * Returns : JB_ERR_OK on success, or
1223 * JB_ERR_MEMORY on out-of-memory error.
1225 *********************************************************************/
1226 jb_err client_from(struct client_state *csp, char **header)
1230 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1237 newval = csp->action->string[ACTION_STRING_FROM];
1240 * Are we blocking the e-mail address?
1242 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1244 log_error(LOG_LEVEL_HEADER, "crunch!");
1248 log_error(LOG_LEVEL_HEADER, " modified");
1250 *header = strdup("From: ");
1251 string_append(header, newval);
1253 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1257 /*********************************************************************
1259 * Function : client_send_cookie
1261 * Description : Handle the "cookie" header properly. Called from `sed'.
1262 * If cookie is accepted, add it to the cookie_list,
1263 * else we crunch it. Mmmmmmmmmmm ... cookie ......
1266 * 1 : csp = Current client state (buffers, headers, etc...)
1267 * 2 : header = On input, pointer to header to modify.
1268 * On output, pointer to the modified header, or NULL
1269 * to remove the header. This function frees the
1270 * original string if necessary.
1272 * Returns : JB_ERR_OK on success, or
1273 * JB_ERR_MEMORY on out-of-memory error.
1275 *********************************************************************/
1276 jb_err client_send_cookie(struct client_state *csp, char **header)
1278 jb_err result = JB_ERR_OK;
1280 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
1282 /* strlen("cookie: ") == 8 */
1283 result = enlist(csp->cookie_list, *header + 8);
1287 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
1291 * Always remove the cookie here. The cookie header
1292 * will be sent at the end of the header.
1300 /*********************************************************************
1302 * Function : client_x_forwarded
1304 * Description : Handle the "x-forwarded-for" config setting properly,
1305 * also used in the add_client_headers list. Called from `sed'.
1308 * 1 : csp = Current client state (buffers, headers, etc...)
1309 * 2 : header = On input, pointer to header to modify.
1310 * On output, pointer to the modified header, or NULL
1311 * to remove the header. This function frees the
1312 * original string if necessary.
1314 * Returns : JB_ERR_OK on success, or
1315 * JB_ERR_MEMORY on out-of-memory error.
1317 *********************************************************************/
1318 jb_err client_x_forwarded(struct client_state *csp, char **header)
1320 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
1322 /* Save it so we can re-add it later */
1323 freez(csp->x_forwarded);
1324 csp->x_forwarded = *header;
1327 * Always set *header = NULL, since this information
1328 * will be sent at the end of the header.
1335 log_error(LOG_LEVEL_HEADER, " crunch!");
1341 /* the following functions add headers directly to the header list */
1343 /*********************************************************************
1345 * Function : client_host_adder
1347 * Description : (re)adds the host header. Called from `sed'.
1350 * 1 : csp = Current client state (buffers, headers, etc...)
1352 * Returns : JB_ERR_OK on success, or
1353 * JB_ERR_MEMORY on out-of-memory error.
1355 *********************************************************************/
1356 jb_err client_host_adder(struct client_state *csp)
1362 if ( !csp->http->hostport || !*(csp->http->hostport))
1367 p = strdup("Host: ");
1369 ** remove 'user:pass@' from 'proto://user:pass@host'
1371 if ( (pos = strchr( csp->http->hostport, '@')) != NULL )
1373 string_append(&p, pos+1);
1377 string_append(&p, csp->http->hostport);
1382 return JB_ERR_MEMORY;
1385 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1387 err = enlist(csp->headers, p);
1395 /*********************************************************************
1397 * Function : client_cookie_adder
1399 * Description : Used in the add_client_headers list. Called from `sed'.
1402 * 1 : csp = Current client state (buffers, headers, etc...)
1404 * Returns : JB_ERR_OK on success, or
1405 * JB_ERR_MEMORY on out-of-memory error.
1407 *********************************************************************/
1408 jb_err client_cookie_adder(struct client_state *csp)
1410 struct list_entry *lst;
1412 struct list_entry *list1 = csp->cookie_list->first;
1413 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
1414 int first_cookie = 1;
1417 if ((list1 == NULL) && (list2 == NULL))
1423 tmp = strdup("Cookie: ");
1425 for (lst = list1; lst ; lst = lst->next)
1433 string_append(&tmp, "; ");
1435 string_append(&tmp, lst->str);
1438 for (lst = list2; lst ; lst = lst->next)
1446 string_append(&tmp, "; ");
1448 string_join(&tmp, cookie_encode(lst->str));
1453 return JB_ERR_MEMORY;
1456 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
1457 err = enlist(csp->headers, tmp);
1463 /*********************************************************************
1465 * Function : client_accept_encoding_adder
1467 * Description : Add an Accept-Encoding header to the client's request
1468 * that disables compression if the action applies, and
1469 * the header is not already there. Called from `sed'.
1470 * Note: For HTTP/1.0, the absence of the header is enough.
1473 * 1 : csp = Current client state (buffers, headers, etc...)
1475 * Returns : JB_ERR_OK on success, or
1476 * JB_ERR_MEMORY on out-of-memory error.
1478 *********************************************************************/
1479 jb_err client_accept_encoding_adder(struct client_state *csp)
1481 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1482 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
1484 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
1491 /*********************************************************************
1493 * Function : client_xtra_adder
1495 * Description : Used in the add_client_headers list. Called from `sed'.
1498 * 1 : csp = Current client state (buffers, headers, etc...)
1500 * Returns : JB_ERR_OK on success, or
1501 * JB_ERR_MEMORY on out-of-memory error.
1503 *********************************************************************/
1504 jb_err client_xtra_adder(struct client_state *csp)
1506 struct list_entry *lst;
1509 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
1510 lst ; lst = lst->next)
1512 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
1513 err = enlist(csp->headers, lst->str);
1525 /*********************************************************************
1527 * Function : client_x_forwarded_adder
1529 * Description : Used in the add_client_headers list. Called from `sed'.
1532 * 1 : csp = Current client state (buffers, headers, etc...)
1534 * Returns : JB_ERR_OK on success, or
1535 * JB_ERR_MEMORY on out-of-memory error.
1537 *********************************************************************/
1538 jb_err client_x_forwarded_adder(struct client_state *csp)
1543 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
1548 if (csp->x_forwarded)
1550 p = strdup(csp->x_forwarded);
1551 string_append(&p, ", ");
1555 p = strdup("X-Forwarded-For: ");
1557 string_append(&p, csp->ip_addr_str);
1561 return JB_ERR_MEMORY;
1564 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1565 err = enlist(csp->headers, p);
1572 /*********************************************************************
1574 * Function : connection_close_adder
1576 * Description : Adds a "Connection: close" header to csp->headers
1577 * as a temporary fix for the needed but missing HTTP/1.1
1578 * support. Called from `sed'.
1579 * FIXME: This whole function shouldn't be neccessary!
1582 * 1 : csp = Current client state (buffers, headers, etc...)
1584 * Returns : JB_ERR_OK on success, or
1585 * JB_ERR_MEMORY on out-of-memory error.
1587 *********************************************************************/
1588 jb_err connection_close_adder(struct client_state *csp)
1590 return enlist(csp->headers, "Connection: close");
1594 /*********************************************************************
1596 * Function : server_http
1598 * Description : - Save the HTTP Status into csp->http->status
1599 * - Set CT_TABOO to prevent filtering if the answer
1600 * is a partial range (HTTP status 206)
1601 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
1605 * 1 : csp = Current client state (buffers, headers, etc...)
1606 * 2 : header = On input, pointer to header to modify.
1607 * On output, pointer to the modified header, or NULL
1608 * to remove the header. This function frees the
1609 * original string if necessary.
1611 * Returns : JB_ERR_OK on success, or
1612 * JB_ERR_MEMORY on out-of-memory error.
1614 *********************************************************************/
1615 jb_err server_http(struct client_state *csp, char **header)
1617 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
1618 if (csp->http->status == 206)
1620 csp->content_type = CT_TABOO;
1623 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
1626 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
1633 /*********************************************************************
1635 * Function : server_set_cookie
1637 * Description : Handle the server "cookie" header properly.
1638 * Log cookie to the jar file. Then "crunch" it,
1639 * or accept it. Called from `sed'.
1642 * 1 : csp = Current client state (buffers, headers, etc...)
1643 * 2 : header = On input, pointer to header to modify.
1644 * On output, pointer to the modified header, or NULL
1645 * to remove the header. This function frees the
1646 * original string if necessary.
1648 * Returns : JB_ERR_OK on success, or
1649 * JB_ERR_MEMORY on out-of-memory error.
1651 *********************************************************************/
1652 jb_err server_set_cookie(struct client_state *csp, char **header)
1654 #ifdef FEATURE_COOKIE_JAR
1655 if (csp->config->jar)
1658 * Write timestamp into outbuf.
1660 * Complex because not all OSs have tm_gmtoff or
1661 * the %z field in strftime()
1663 char tempbuf[ BUFFER_SIZE ];
1667 #ifdef HAVE_LOCALTIME_R
1668 tm_now = *localtime_r(&now, &tm_now);
1670 tm_now = *localtime (&now);
1672 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
1674 /* strlen("set-cookie: ") = 12 */
1675 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
1677 #endif /* def FEATURE_COOKIE_JAR */
1679 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
1681 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
1682 return crumble(csp, header);
1684 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
1686 /* Flag whether or not to log a message */
1689 /* A variable to store the tag we're working on */
1692 /* Skip "Set-Cookie:" (11 characters) in header */
1693 cur_tag = *header + 11;
1695 /* skip whitespace between "Set-Cookie:" and value */
1696 while (*cur_tag && ijb_isspace(*cur_tag))
1701 /* Loop through each tag in the cookie */
1705 char *next_tag = strchr(cur_tag, ';');
1706 if (next_tag != NULL)
1708 /* Skip the ';' character itself */
1711 /* skip whitespace ";" and start of tag */
1712 while (*next_tag && ijb_isspace(*next_tag))
1719 /* "Next tag" is the end of the string */
1720 next_tag = cur_tag + strlen(cur_tag);
1723 /* Is this the "Expires" tag? */
1724 if (strncmpic(cur_tag, "expires=", 8) == 0)
1726 /* Delete the tag by copying the rest of the string over it.
1727 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
1728 * since the behaviour of strcpy is undefined for overlapping
1731 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
1733 /* That changed the header, need to issue a log message */
1736 /* Note that the next tag has now been moved to *cur_tag,
1737 * so we do not need to update the cur_tag pointer.
1742 /* Move on to next cookie tag */
1749 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
1757 #ifdef FEATURE_FORCE_LOAD
1758 /*********************************************************************
1760 * Function : strclean
1762 * Description : In-Situ-Eliminate all occurances of substring in
1766 * 1 : string = string to clean
1767 * 2 : substring = substring to eliminate
1769 * Returns : Number of eliminations
1771 *********************************************************************/
1772 int strclean(const char *string, const char *substring)
1774 int hits = 0, len = strlen(substring);
1777 while((pos = strstr(string, substring)) != NULL)
1784 while (*p++ != '\0');
1791 #endif /* def FEATURE_FORCE_LOAD */