1 const char parsers_rcs[] = "$Id: parsers.c,v 1.56 2002/05/12 15:34:22 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://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 1.56 2002/05/12 15:34:22 jongfoster
44 * Fixing typo in a comment
46 * Revision 1.55 2002/05/08 16:01:07 oes
47 * Optimized add_to_iob:
48 * - Use realloc instead of malloc(), memcpy(), free()
49 * - Expand to powers of two if possible, to get
50 * O(log n) reallocs instead of O(n).
51 * - Moved check for buffer limit here from chat
52 * - Report failure via returncode
54 * Revision 1.54 2002/04/02 15:03:16 oes
57 * Revision 1.53 2002/03/26 22:29:55 swa
58 * we have a new homepage!
60 * Revision 1.52 2002/03/24 13:25:43 swa
61 * name change related issues
63 * Revision 1.51 2002/03/13 00:27:05 jongfoster
66 * Revision 1.50 2002/03/12 01:45:35 oes
67 * More verbose logging
69 * Revision 1.49 2002/03/09 20:03:52 jongfoster
70 * - Making various functions return int rather than size_t.
71 * (Undoing a recent change). Since size_t is unsigned on
72 * Windows, functions like read_socket that return -1 on
73 * error cannot return a size_t.
75 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
76 * crashes, and also frequently caused JB to jump to 100%
77 * CPU and stay there. (Because it thought it had just
78 * read ((unsigned)-1) == 4Gb of data...)
80 * - The signature of write_socket has changed, it now simply
81 * returns success=0/failure=nonzero.
83 * - Trying to get rid of a few warnings --with-debug on
84 * Windows, I've introduced a new type "jb_socket". This is
85 * used for the socket file descriptors. On Windows, this
86 * is SOCKET (a typedef for unsigned). Everywhere else, it's
87 * an int. The error value can't be -1 any more, so it's
88 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
89 * Windows it maps to the #define INVALID_SOCKET.)
91 * - The signature of bind_port has changed.
93 * Revision 1.48 2002/03/07 03:46:53 oes
94 * Fixed compiler warnings etc
96 * Revision 1.47 2002/02/20 23:15:13 jongfoster
97 * Parsing functions now handle out-of-memory gracefully by returning
100 * Revision 1.46 2002/01/17 21:03:47 jongfoster
101 * Moving all our URL and URL pattern parsing code to urlmatch.c.
103 * Revision 1.45 2002/01/09 14:33:03 oes
104 * Added support for localtime_r.
106 * Revision 1.44 2001/12/14 01:22:54 steudten
107 * Remove 'user:pass@' from 'proto://user:pass@host' for the
108 * new added header 'Host: ..'. (See Req ID 491818)
110 * Revision 1.43 2001/11/23 00:26:38 jongfoster
111 * Fixing two really stupid errors in my previous commit
113 * Revision 1.42 2001/11/22 21:59:30 jongfoster
114 * Adding code to handle +no-cookies-keep
116 * Revision 1.41 2001/11/05 23:43:05 steudten
117 * Add time+date to log files.
119 * Revision 1.40 2001/10/26 20:13:09 jongfoster
120 * ctype.h is needed in Windows, too.
122 * Revision 1.39 2001/10/26 17:40:04 oes
123 * Introduced get_header_value()
124 * Removed http->user_agent, csp->referrer and csp->accept_types
125 * Removed client_accept()
127 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
128 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
129 * threads to call select() simultaneously. So, it's time to do a real, live,
130 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
131 * (native). Both versions will work, but using __OS2__ offers multi-threading.
133 * Revision 1.37 2001/10/23 21:36:02 jongfoster
134 * Documenting sed()'s error behaviou (doc change only)
136 * Revision 1.36 2001/10/13 12:51:51 joergs
137 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
138 * force-load), instead crumble Host: and add it (again) in client_host_adder
139 * (in case we get a HTTP/1.0 request without Host: header and forward it to
140 * a HTTP/1.1 server/proxy).
142 * Revision 1.35 2001/10/09 22:39:21 jongfoster
143 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
146 * Revision 1.34 2001/10/07 18:50:55 oes
147 * Added server_content_encoding, renamed server_transfer_encoding
149 * Revision 1.33 2001/10/07 18:04:49 oes
150 * Changed server_http11 to server_http and its pattern to "HTTP".
151 * Additional functionality: it now saves the HTTP status into
152 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
154 * Revision 1.32 2001/10/07 15:43:28 oes
155 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
156 * client_te and client_accept_encoding_adder, triggered by the new
157 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
158 * changed to allow only identity and chunked, and the TE header is
159 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
161 * parse_http_request no longer does anything than parsing. The rewriting
162 * of http->cmd and version mangling are gone. It now also recognizes
163 * the put and delete methods and saves the url in http->url. Removed
166 * renamed content_type and content_length to have the server_ prefix
168 * server_content_type now only works if csp->content_type != CT_TABOO
170 * added server_transfer_encoding, which
171 * - Sets CT_TABOO to prohibit filtering if encoding compresses
172 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
173 * - Change from "chunked" to "identity" if body was chunked
174 * but has been de-chunked for filtering.
176 * added server_content_md5 which crunches any Content-MD5 headers
177 * if the body was modified.
179 * made server_http11 conditional on +downgrade action
181 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
183 * Revision 1.31 2001/10/05 14:25:02 oes
184 * Crumble Keep-Alive from Server
186 * Revision 1.30 2001/09/29 12:56:03 joergs
187 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
189 * Revision 1.29 2001/09/24 21:09:24 jongfoster
190 * Fixing 2 memory leaks that Guy spotted, where the paramater to
191 * enlist() was not being free()d.
193 * Revision 1.28 2001/09/22 16:32:28 jongfoster
194 * Removing unused #includes.
196 * Revision 1.27 2001/09/20 15:45:25 steudten
198 * add casting from size_t to int for printf()
199 * remove local variable shadow s2
201 * Revision 1.26 2001/09/16 17:05:14 jongfoster
202 * Removing unused #include showarg.h
204 * Revision 1.25 2001/09/16 13:21:27 jongfoster
205 * Changes to use new list functions.
207 * Revision 1.24 2001/09/13 23:05:50 jongfoster
208 * Changing the string paramater to the header parsers a "const".
210 * Revision 1.23 2001/09/12 18:08:19 steudten
212 * In parse_http_request() header rewriting miss the host value, so
213 * from http://www.mydomain.com the result was just " / " not
214 * http://www.mydomain.com/ in case we forward.
216 * Revision 1.22 2001/09/10 10:58:53 oes
217 * Silenced compiler warnings
219 * Revision 1.21 2001/07/31 14:46:00 oes
220 * - Persistant connections now suppressed
221 * - sed() no longer appends empty header to csp->headers
223 * Revision 1.20 2001/07/30 22:08:36 jongfoster
224 * Tidying up #defines:
225 * - All feature #defines are now of the form FEATURE_xxx
226 * - Permanently turned off WIN_GUI_EDIT
227 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
229 * Revision 1.19 2001/07/25 17:21:54 oes
230 * client_uagent now saves copy of User-Agent: header value
232 * Revision 1.18 2001/07/13 14:02:46 oes
233 * - Included fix to repair broken HTTP requests that
234 * don't contain a path, not even '/'.
235 * - Removed all #ifdef PCRS
236 * - content_type now always inspected and classified as
237 * text, gif or other.
238 * - formatting / comments
240 * Revision 1.17 2001/06/29 21:45:41 oes
241 * Indentation, CRLF->LF, Tab-> Space
243 * Revision 1.16 2001/06/29 13:32:42 oes
245 * - Adapted free_http_request
246 * - Removed logentry from cancelled commit
248 * Revision 1.15 2001/06/03 19:12:38 oes
249 * deleted const struct interceptors
251 * Revision 1.14 2001/06/01 18:49:17 jongfoster
252 * Replaced "list_share" with "list" - the tiny memory gain was not
253 * worth the extra complexity.
255 * Revision 1.13 2001/05/31 21:30:33 jongfoster
256 * Removed list code - it's now in list.[ch]
257 * Renamed "permission" to "action", and changed many features
258 * to use the actions file rather than the global config.
260 * Revision 1.12 2001/05/31 17:33:13 oes
264 * Revision 1.11 2001/05/29 20:11:19 joergs
265 * '/ * inside comment' warning removed.
267 * Revision 1.10 2001/05/29 09:50:24 jongfoster
268 * Unified blocklist/imagelist/permissionslist.
269 * File format is still under discussion, but the internal changes
272 * Also modified interceptor behaviour:
273 * - We now intercept all URLs beginning with one of the following
274 * prefixes (and *only* these prefixes):
276 * * http://ijbswa.sf.net/config/
277 * * http://ijbswa.sourceforge.net/config/
278 * - New interceptors "home page" - go to http://i.j.b/ to see it.
279 * - Internal changes so that intercepted and fast redirect pages
280 * are not replaced with an image.
281 * - Interceptors now have the option to send a binary page direct
282 * to the client. (i.e. ijb-send-banner uses this)
283 * - Implemented show-url-info interceptor. (Which is why I needed
284 * the above interceptors changes - a typical URL is
285 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
286 * The previous mechanism would not have intercepted that, and
287 * if it had been intercepted then it then it would have replaced
290 * Revision 1.9 2001/05/28 17:26:33 jongfoster
291 * Fixing segfault if last header was crunched.
292 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
293 * can use the cross-platform sprintf() instead.)
295 * Revision 1.8 2001/05/27 22:17:04 oes
297 * - re_process_buffer no longer writes the modified buffer
298 * to the client, which was very ugly. It now returns the
299 * buffer, which it is then written by chat.
301 * - content_length now adjusts the Content-Length: header
302 * for modified documents rather than crunch()ing it.
303 * (Length info in csp->content_length, which is 0 for
304 * unmodified documents)
306 * - For this to work, sed() is called twice when filtering.
308 * Revision 1.7 2001/05/27 13:19:06 oes
309 * Patched Joergs solution for the content-length in.
311 * Revision 1.6 2001/05/26 13:39:32 jongfoster
312 * Only crunches Content-Length header if applying RE filtering.
313 * Without this fix, Microsoft Windows Update wouldn't work.
315 * Revision 1.5 2001/05/26 00:28:36 jongfoster
316 * Automatic reloading of config file.
317 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
318 * Most of the global variables have been moved to a new
319 * struct configuration_spec, accessed through csp->config->globalname
320 * Most of the globals remaining are used by the Win32 GUI.
322 * Revision 1.4 2001/05/22 18:46:04 oes
324 * - Enabled filtering banners by size rather than URL
325 * by adding patterns that replace all standard banner
326 * sizes with the "Junkbuster" gif to the re_filterfile
328 * - Enabled filtering WebBugs by providing a pattern
329 * which kills all 1x1 images
331 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
332 * which is selected by the (nonstandard and therefore
333 * capital) letter 'U' in the option string.
334 * It causes the quantifiers to be ungreedy by default.
335 * Appending a ? turns back to greedy (!).
337 * - Added a new interceptor ijb-send-banner, which
338 * sends back the "Junkbuster" gif. Without imagelist or
339 * MSIE detection support, or if tinygif = 1, or the
340 * URL isn't recognized as an imageurl, a lame HTML
341 * explanation is sent instead.
343 * - Added new feature, which permits blocking remote
344 * script redirects and firing back a local redirect
346 * The feature is conditionally compiled, i.e. it
347 * can be disabled with --disable-fast-redirects,
348 * plus it must be activated by a "fast-redirects"
349 * line in the config file, has its own log level
350 * and of course wants to be displayed by show-proxy-args
351 * Note: Boy, all the #ifdefs in 1001 locations and
352 * all the fumbling with configure.in and acconfig.h
353 * were *way* more work than the feature itself :-(
355 * - Because a generic redirect template was needed for
356 * this, tinygif = 3 now uses the same.
358 * - Moved GIFs, and other static HTTP response templates
363 * - Removed some >400 CRs again (Jon, you really worked
366 * Revision 1.3 2001/05/20 01:21:20 jongfoster
367 * Version 2.9.4 checkin.
368 * - Merged popupfile and cookiefile, and added control over PCRS
369 * filtering, in new "permissionsfile".
370 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
371 * file error you now get a message box (in the Win32 GUI) rather
372 * than the program exiting with no explanation.
373 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
375 * - Removed tabs from "config"
376 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
377 * - Bumped up version number.
379 * Revision 1.2 2001/05/17 23:02:36 oes
380 * - Made referrer option accept 'L' as a substitute for '§'
382 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
383 * Initial import of version 2.9.3 source tree
386 *********************************************************************/
393 #include <sys/types.h>
401 #if !defined(_WIN32) && !defined(__OS2__)
411 #include "jbsockets.h"
412 #include "miscutil.h"
415 const char parsers_h_rcs[] = PARSERS_H_VERSION;
417 /* Fix a problem with Solaris. There should be no effect on other
419 * Solaris's isspace() is a macro which uses it's argument directly
420 * as an array index. Therefore we need to make sure that high-bit
421 * characters generate +ve values, and ideally we also want to make
422 * the argument match the declared parameter type of "int".
424 * Why did they write a character function that can't take a simple
425 * "char" argument? Doh!
427 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
428 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
431 const struct parsers client_patterns[] = {
432 { "referer:", 8, client_referrer },
433 { "user-agent:", 11, client_uagent },
434 { "ua-", 3, client_ua },
435 { "from:", 5, client_from },
436 { "cookie:", 7, client_send_cookie },
437 { "x-forwarded-for:", 16, client_x_forwarded },
438 { "Accept-Encoding:", 16, client_accept_encoding },
439 { "TE:", 3, client_te },
440 { "Host:", 5, crumble },
441 /* { "if-modified-since:", 18, crumble }, */
442 { "Keep-Alive:", 11, crumble },
443 { "connection:", 11, crumble },
444 { "proxy-connection:", 17, crumble },
449 const struct parsers server_patterns[] = {
450 { "HTTP", 4, server_http },
451 { "set-cookie:", 11, server_set_cookie },
452 { "connection:", 11, crumble },
453 { "Content-Type:", 13, server_content_type },
454 { "Content-Length:", 15, server_content_length },
455 { "Content-MD5:", 12, server_content_md5 },
456 { "Content-Encoding:", 17, server_content_encoding },
457 { "Transfer-Encoding:", 18, server_transfer_coding },
458 { "Keep-Alive:", 11, crumble },
463 const add_header_func_ptr add_client_headers[] = {
466 client_x_forwarded_adder,
468 client_accept_encoding_adder,
469 connection_close_adder,
474 const add_header_func_ptr add_server_headers[] = {
475 connection_close_adder,
480 /*********************************************************************
482 * Function : flush_socket
484 * Description : Write any pending "buffered" content.
487 * 1 : fd = file descriptor of the socket to read
488 * 2 : csp = Current client state (buffers, headers, etc...)
490 * Returns : On success, the number of bytes written are returned (zero
491 * indicates nothing was written). On error, -1 is returned,
492 * and errno is set appropriately. If count is zero and the
493 * file descriptor refers to a regular file, 0 will be
494 * returned without causing any other effect. For a special
495 * file, the results are not portable.
497 *********************************************************************/
498 int flush_socket(jb_socket fd, struct client_state *csp)
500 struct iob *iob = csp->iob;
501 int len = iob->eod - iob->cur;
508 if (write_socket(fd, iob->cur, (size_t)len))
512 iob->eod = iob->cur = iob->buf;
518 /*********************************************************************
520 * Function : add_to_iob
522 * Description : Add content to the buffered page, expanding the
523 * buffer if necessary.
526 * 1 : csp = Current client state (buffers, headers, etc...)
527 * 2 : buf = holds the content to be added to the page
528 * 3 : n = number of bytes to be added
530 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
531 * or buffer limit reached.
533 *********************************************************************/
534 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
536 struct iob *iob = csp->iob;
537 size_t used, offset, need, want;
540 if (n <= 0) return JB_ERR_OK;
542 used = iob->eod - iob->buf;
543 offset = iob->cur - iob->buf;
547 * If the buffer can't hold the new data, extend it first.
548 * Use the next power of two if possible, else use the actual need.
550 if (need > csp->config->buffer_limit)
552 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
553 return JB_ERR_MEMORY;
556 if (need > iob->size)
558 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
560 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
564 else if (NULL != (p = (char *)realloc(iob->buf, need)))
570 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
571 return JB_ERR_MEMORY;
574 /* Update the iob pointers */
575 iob->cur = p + offset;
580 /* copy the new data into the iob buffer */
581 memcpy(iob->eod, buf, (size_t)n);
583 /* point to the end of the data */
586 /* null terminate == cheap insurance */
594 /*********************************************************************
596 * Function : get_header
598 * Description : This (odd) routine will parse the csp->iob
601 * 1 : csp = Current client state (buffers, headers, etc...)
603 * Returns : Any one of the following:
605 * 1) a pointer to a dynamically allocated string that contains a header line
606 * 2) NULL indicating that the end of the header was reached
607 * 3) "" indicating that the end of the iob was reached before finding
608 * a complete header line.
610 *********************************************************************/
611 char *get_header(struct client_state *csp)
617 if ((iob->cur == NULL)
618 || ((p = strchr(iob->cur, '\n')) == NULL))
620 return(""); /* couldn't find a complete header */
625 ret = strdup(iob->cur);
628 /* FIXME No way to handle error properly */
629 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
634 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
636 /* is this a blank line (i.e. the end of the header) ? */
648 /*********************************************************************
650 * Function : get_header_value
652 * Description : Get the value of a given header from a chained list
653 * of header lines or return NULL if no such header is
654 * present in the list.
657 * 1 : header_list = pointer to list
658 * 2 : header_name = string with name of header to look for.
659 * Trailing colon required, capitalization
662 * Returns : NULL if not found, else value of header
664 *********************************************************************/
665 char *get_header_value(const struct list *header_list, const char *header_name)
667 struct list_entry *cur_entry;
673 length = strlen(header_name);
675 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
679 if (!strncmpic(cur_entry->str, header_name, length))
682 * Found: return pointer to start of value
684 ret = (char *) (cur_entry->str + length);
685 while (*ret && ijb_isspace(*ret)) ret++;
698 /*********************************************************************
702 * Description : add, delete or modify lines in the HTTP header streams.
703 * On entry, it receives a linked list of headers space
704 * that was allocated dynamically (both the list nodes
705 * and the header contents).
707 * As a side effect it frees the space used by the original
711 * 1 : pats = list of patterns to match against headers
712 * 2 : more_headers = list of functions to add more
713 * headers (client or server)
714 * 3 : csp = Current client state (buffers, headers, etc...)
716 * Returns : Single pointer to a fully formed header, or NULL
717 * on out-of-memory error.
719 *********************************************************************/
720 char *sed(const struct parsers pats[],
721 const add_header_func_ptr more_headers[],
722 struct client_state *csp)
724 struct list_entry *p;
725 const struct parsers *v;
726 const add_header_func_ptr *f;
727 jb_err err = JB_ERR_OK;
729 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
731 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
733 /* Header crunch()ed in previous run? -> ignore */
734 if (p->str == NULL) continue;
736 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
738 if (strncmpic(p->str, v->str, v->len) == 0)
740 err = v->parser(csp, (char **)&(p->str));
745 /* place any additional headers on the csp->headers list */
746 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
751 if (err != JB_ERR_OK)
756 return list_to_text(csp->headers);
760 /* here begins the family of parser functions that reformat header lines */
763 /*********************************************************************
767 * Description : This is called if a header matches a pattern to "crunch"
770 * 1 : csp = Current client state (buffers, headers, etc...)
771 * 2 : header = On input, pointer to header to modify.
772 * On output, pointer to the modified header, or NULL
773 * to remove the header. This function frees the
774 * original string if necessary.
776 * Returns : JB_ERR_OK on success, or
777 * JB_ERR_MEMORY on out-of-memory error.
779 *********************************************************************/
780 jb_err crumble(struct client_state *csp, char **header)
782 log_error(LOG_LEVEL_HEADER, "crunch!");
788 /*********************************************************************
790 * Function : server_content_type
792 * Description : Set the content-type for filterable types (text/.*,
793 * javascript and image/gif) unless filtering has been
794 * forbidden (CT_TABOO) while parsing earlier headers.
797 * 1 : csp = Current client state (buffers, headers, etc...)
798 * 2 : header = On input, pointer to header to modify.
799 * On output, pointer to the modified header, or NULL
800 * to remove the header. This function frees the
801 * original string if necessary.
803 * Returns : JB_ERR_OK on success, or
804 * JB_ERR_MEMORY on out-of-memory error.
806 *********************************************************************/
807 jb_err server_content_type(struct client_state *csp, char **header)
809 if (csp->content_type != CT_TABOO)
811 if (strstr(*header, " text/")
812 || strstr(*header, "application/x-javascript"))
813 csp->content_type = CT_TEXT;
814 else if (strstr(*header, " image/gif"))
815 csp->content_type = CT_GIF;
817 csp->content_type = 0;
824 /*********************************************************************
826 * Function : server_transfer_coding
828 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
829 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
830 * - Change from "chunked" to "identity" if body was chunked
831 * but has been de-chunked for filtering.
834 * 1 : csp = Current client state (buffers, headers, etc...)
835 * 2 : header = On input, pointer to header to modify.
836 * On output, pointer to the modified header, or NULL
837 * to remove the header. This function frees the
838 * original string if necessary.
840 * Returns : JB_ERR_OK on success, or
841 * JB_ERR_MEMORY on out-of-memory error.
843 *********************************************************************/
844 jb_err server_transfer_coding(struct client_state *csp, char **header)
847 * Turn off pcrs and gif filtering if body compressed
849 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
851 csp->content_type = CT_TABOO;
855 * Raise flag if body chunked
857 if (strstr(*header, "chunked"))
859 csp->flags |= CSP_FLAG_CHUNKED;
862 * If the body was modified, it has been
863 * de-chunked first, so adjust the header:
865 if (csp->flags & CSP_FLAG_MODIFIED)
868 *header = strdup("Transfer-Encoding: identity");
869 return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
877 /*********************************************************************
879 * Function : server_content_encoding
881 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
884 * 1 : csp = Current client state (buffers, headers, etc...)
885 * 2 : header = On input, pointer to header to modify.
886 * On output, pointer to the modified header, or NULL
887 * to remove the header. This function frees the
888 * original string if necessary.
890 * Returns : JB_ERR_OK on success, or
891 * JB_ERR_MEMORY on out-of-memory error.
893 *********************************************************************/
894 jb_err server_content_encoding(struct client_state *csp, char **header)
897 * Turn off pcrs and gif filtering if body compressed
899 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
901 csp->content_type = CT_TABOO;
909 /*********************************************************************
911 * Function : server_content_length
913 * Description : Adjust Content-Length header if we modified
917 * 1 : csp = Current client state (buffers, headers, etc...)
918 * 2 : header = On input, pointer to header to modify.
919 * On output, pointer to the modified header, or NULL
920 * to remove the header. This function frees the
921 * original string if necessary.
923 * Returns : JB_ERR_OK on success, or
924 * JB_ERR_MEMORY on out-of-memory error.
926 *********************************************************************/
927 jb_err server_content_length(struct client_state *csp, char **header)
929 if (csp->content_length != 0) /* Content length has been modified */
932 *header = (char *) zalloc(100);
935 return JB_ERR_MEMORY;
938 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
940 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
947 /*********************************************************************
949 * Function : server_content_md5
951 * Description : Crumble any Content-MD5 headers if the document was
952 * modified. FIXME: Should we re-compute instead?
955 * 1 : csp = Current client state (buffers, headers, etc...)
956 * 2 : header = On input, pointer to header to modify.
957 * On output, pointer to the modified header, or NULL
958 * to remove the header. This function frees the
959 * original string if necessary.
961 * Returns : JB_ERR_OK on success, or
962 * JB_ERR_MEMORY on out-of-memory error.
964 *********************************************************************/
965 jb_err server_content_md5(struct client_state *csp, char **header)
967 if (csp->flags & CSP_FLAG_MODIFIED)
969 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
977 /*********************************************************************
979 * Function : client_accept_encoding
981 * Description : Rewrite the client's Accept-Encoding header so that
982 * if doesn't allow compression, if the action applies.
983 * Note: For HTTP/1.0 the absence of the header is enough.
986 * 1 : csp = Current client state (buffers, headers, etc...)
987 * 2 : header = On input, pointer to header to modify.
988 * On output, pointer to the modified header, or NULL
989 * to remove the header. This function frees the
990 * original string if necessary.
992 * Returns : JB_ERR_OK on success, or
993 * JB_ERR_MEMORY on out-of-memory error.
995 *********************************************************************/
996 jb_err client_accept_encoding(struct client_state *csp, char **header)
998 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1000 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress content");
1003 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1005 *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1006 if (*header == NULL)
1008 return JB_ERR_MEMORY;
1017 /*********************************************************************
1019 * Function : client_te
1021 * Description : Rewrite the client's TE header so that
1022 * if doesn't allow compression, if the action applies.
1025 * 1 : csp = Current client state (buffers, headers, etc...)
1026 * 2 : header = On input, pointer to header to modify.
1027 * On output, pointer to the modified header, or NULL
1028 * to remove the header. This function frees the
1029 * original string if necessary.
1031 * Returns : JB_ERR_OK on success, or
1032 * JB_ERR_MEMORY on out-of-memory error.
1034 *********************************************************************/
1035 jb_err client_te(struct client_state *csp, char **header)
1037 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1040 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress transfer");
1046 /*********************************************************************
1048 * Function : client_referrer
1050 * Description : Handle the "referer" config setting properly.
1051 * Called from `sed'.
1054 * 1 : csp = Current client state (buffers, headers, etc...)
1055 * 2 : header = On input, pointer to header to modify.
1056 * On output, pointer to the modified header, or NULL
1057 * to remove the header. This function frees the
1058 * original string if necessary.
1060 * Returns : JB_ERR_OK on success, or
1061 * JB_ERR_MEMORY on out-of-memory error.
1063 *********************************************************************/
1064 jb_err client_referrer(struct client_state *csp, char **header)
1068 #ifdef FEATURE_FORCE_LOAD
1069 /* Since the referrer can include the prefix even
1070 * even if the request itself is non-forced, we must
1071 * clean it unconditionally
1073 strclean(*header, FORCE_PREFIX);
1074 #endif /* def FEATURE_FORCE_LOAD */
1077 * Are we sending referer?
1079 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1086 newval = csp->action->string[ACTION_STRING_REFERER];
1088 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1093 log_error(LOG_LEVEL_HEADER, "crunch!");
1096 else if (0 == strncmpic(newval, "http://", 7))
1099 * We have a specific (fixed) referer we want to send.
1101 log_error(LOG_LEVEL_HEADER, "modified");
1103 *header = strdup("Referer: ");
1104 string_append(header, newval);
1106 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1111 * Forge a referer as http://[hostname:port of REQUEST]/
1112 * to fool stupid checks for in-site links
1114 if (0 != strcmpic(newval, "forge"))
1117 * Invalid choice - but forge is probably the best default.
1119 log_error(LOG_LEVEL_ERROR, "Bad parameter: +referer{%s}", newval);
1122 *header = strdup("Referer: http://");
1123 string_append(header, csp->http->hostport);
1124 string_append(header, "/");
1125 log_error(LOG_LEVEL_HEADER, "crunch+forge to %s", *header);
1127 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1132 /*********************************************************************
1134 * Function : client_uagent
1136 * Description : Handle the "user-agent" config setting properly
1137 * and remember its original value to enable browser
1138 * bug workarounds. Called from `sed'.
1141 * 1 : csp = Current client state (buffers, headers, etc...)
1142 * 2 : header = On input, pointer to header to modify.
1143 * On output, pointer to the modified header, or NULL
1144 * to remove the header. This function frees the
1145 * original string if necessary.
1147 * Returns : JB_ERR_OK on success, or
1148 * JB_ERR_MEMORY on out-of-memory error.
1150 *********************************************************************/
1151 jb_err client_uagent(struct client_state *csp, char **header)
1155 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1160 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1166 log_error(LOG_LEVEL_HEADER, "modified");
1169 *header = strdup("User-Agent: ");
1170 string_append(header, newval);
1172 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1176 /*********************************************************************
1178 * Function : client_ua
1180 * Description : Handle "ua-" headers properly. Called from `sed'.
1183 * 1 : csp = Current client state (buffers, headers, etc...)
1184 * 2 : header = On input, pointer to header to modify.
1185 * On output, pointer to the modified header, or NULL
1186 * to remove the header. This function frees the
1187 * original string if necessary.
1189 * Returns : JB_ERR_OK on success, or
1190 * JB_ERR_MEMORY on out-of-memory error.
1192 *********************************************************************/
1193 jb_err client_ua(struct client_state *csp, char **header)
1195 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1197 log_error(LOG_LEVEL_HEADER, "crunch!");
1205 /*********************************************************************
1207 * Function : client_from
1209 * Description : Handle the "from" config setting properly.
1210 * Called from `sed'.
1213 * 1 : csp = Current client state (buffers, headers, etc...)
1214 * 2 : header = On input, pointer to header to modify.
1215 * On output, pointer to the modified header, or NULL
1216 * to remove the header. This function frees the
1217 * original string if necessary.
1219 * Returns : JB_ERR_OK on success, or
1220 * JB_ERR_MEMORY on out-of-memory error.
1222 *********************************************************************/
1223 jb_err client_from(struct client_state *csp, char **header)
1227 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1234 newval = csp->action->string[ACTION_STRING_FROM];
1237 * Are we blocking the e-mail address?
1239 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1241 log_error(LOG_LEVEL_HEADER, "crunch!");
1245 log_error(LOG_LEVEL_HEADER, " modified");
1247 *header = strdup("From: ");
1248 string_append(header, newval);
1250 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1254 /*********************************************************************
1256 * Function : client_send_cookie
1258 * Description : Handle the "cookie" header properly. Called from `sed'.
1259 * If cookie is accepted, add it to the cookie_list,
1260 * else we crunch it. Mmmmmmmmmmm ... cookie ......
1263 * 1 : csp = Current client state (buffers, headers, etc...)
1264 * 2 : header = On input, pointer to header to modify.
1265 * On output, pointer to the modified header, or NULL
1266 * to remove the header. This function frees the
1267 * original string if necessary.
1269 * Returns : JB_ERR_OK on success, or
1270 * JB_ERR_MEMORY on out-of-memory error.
1272 *********************************************************************/
1273 jb_err client_send_cookie(struct client_state *csp, char **header)
1275 jb_err result = JB_ERR_OK;
1277 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
1279 /* strlen("cookie: ") == 8 */
1280 result = enlist(csp->cookie_list, *header + 8);
1284 log_error(LOG_LEVEL_HEADER, " crunch!");
1288 * Always remove the cookie here. The cookie header
1289 * will be sent at the end of the header.
1297 /*********************************************************************
1299 * Function : client_x_forwarded
1301 * Description : Handle the "x-forwarded-for" config setting properly,
1302 * also used in the add_client_headers list. Called from `sed'.
1305 * 1 : csp = Current client state (buffers, headers, etc...)
1306 * 2 : header = On input, pointer to header to modify.
1307 * On output, pointer to the modified header, or NULL
1308 * to remove the header. This function frees the
1309 * original string if necessary.
1311 * Returns : JB_ERR_OK on success, or
1312 * JB_ERR_MEMORY on out-of-memory error.
1314 *********************************************************************/
1315 jb_err client_x_forwarded(struct client_state *csp, char **header)
1317 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
1319 /* Save it so we can re-add it later */
1320 freez(csp->x_forwarded);
1321 csp->x_forwarded = *header;
1324 * Always set *header = NULL, since this information
1325 * will be sent at the end of the header.
1332 log_error(LOG_LEVEL_HEADER, " crunch!");
1338 /* the following functions add headers directly to the header list */
1340 /*********************************************************************
1342 * Function : client_host_adder
1344 * Description : (re)adds the host header. Called from `sed'.
1347 * 1 : csp = Current client state (buffers, headers, etc...)
1349 * Returns : JB_ERR_OK on success, or
1350 * JB_ERR_MEMORY on out-of-memory error.
1352 *********************************************************************/
1353 jb_err client_host_adder(struct client_state *csp)
1359 if ( !csp->http->hostport || !*(csp->http->hostport))
1364 p = strdup("Host: ");
1366 ** remove 'user:pass@' from 'proto://user:pass@host'
1368 if ( (pos = strchr( csp->http->hostport, '@')) != NULL )
1370 string_append(&p, pos+1);
1374 string_append(&p, csp->http->hostport);
1379 return JB_ERR_MEMORY;
1382 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1384 err = enlist(csp->headers, p);
1392 /*********************************************************************
1394 * Function : client_cookie_adder
1396 * Description : Used in the add_client_headers list. Called from `sed'.
1399 * 1 : csp = Current client state (buffers, headers, etc...)
1401 * Returns : JB_ERR_OK on success, or
1402 * JB_ERR_MEMORY on out-of-memory error.
1404 *********************************************************************/
1405 jb_err client_cookie_adder(struct client_state *csp)
1407 struct list_entry *lst;
1409 struct list_entry *list1 = csp->cookie_list->first;
1410 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
1411 int first_cookie = 1;
1414 if ((list1 == NULL) && (list2 == NULL))
1420 tmp = strdup("Cookie: ");
1422 for (lst = list1; lst ; lst = lst->next)
1430 string_append(&tmp, "; ");
1432 string_append(&tmp, lst->str);
1435 for (lst = list2; lst ; lst = lst->next)
1443 string_append(&tmp, "; ");
1445 string_join(&tmp, cookie_encode(lst->str));
1450 return JB_ERR_MEMORY;
1453 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
1454 err = enlist(csp->headers, tmp);
1460 /*********************************************************************
1462 * Function : client_accept_encoding_adder
1464 * Description : Add an Accept-Encoding header to the client's request
1465 * that disables compression if the action applies, and
1466 * the header is not already there. Called from `sed'.
1467 * Note: For HTTP/1.0, the absence of the header is enough.
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_accept_encoding_adder(struct client_state *csp)
1478 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1479 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
1481 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
1488 /*********************************************************************
1490 * Function : client_xtra_adder
1492 * Description : Used in the add_client_headers list. Called from `sed'.
1495 * 1 : csp = Current client state (buffers, headers, etc...)
1497 * Returns : JB_ERR_OK on success, or
1498 * JB_ERR_MEMORY on out-of-memory error.
1500 *********************************************************************/
1501 jb_err client_xtra_adder(struct client_state *csp)
1503 struct list_entry *lst;
1506 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
1507 lst ; lst = lst->next)
1509 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
1510 err = enlist(csp->headers, lst->str);
1522 /*********************************************************************
1524 * Function : client_x_forwarded_adder
1526 * Description : Used in the add_client_headers list. Called from `sed'.
1529 * 1 : csp = Current client state (buffers, headers, etc...)
1531 * Returns : JB_ERR_OK on success, or
1532 * JB_ERR_MEMORY on out-of-memory error.
1534 *********************************************************************/
1535 jb_err client_x_forwarded_adder(struct client_state *csp)
1540 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
1545 if (csp->x_forwarded)
1547 p = strdup(csp->x_forwarded);
1548 string_append(&p, ", ");
1552 p = strdup("X-Forwarded-For: ");
1554 string_append(&p, csp->ip_addr_str);
1558 return JB_ERR_MEMORY;
1561 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1562 err = enlist(csp->headers, p);
1569 /*********************************************************************
1571 * Function : connection_close_adder
1573 * Description : Adds a "Connection: close" header to csp->headers
1574 * as a temporary fix for the needed but missing HTTP/1.1
1575 * support. Called from `sed'.
1576 * FIXME: This whole function shouldn't be neccessary!
1579 * 1 : csp = Current client state (buffers, headers, etc...)
1581 * Returns : JB_ERR_OK on success, or
1582 * JB_ERR_MEMORY on out-of-memory error.
1584 *********************************************************************/
1585 jb_err connection_close_adder(struct client_state *csp)
1587 return enlist(csp->headers, "Connection: close");
1591 /*********************************************************************
1593 * Function : server_http
1595 * Description : - Save the HTTP Status into csp->http->status
1596 * - Set CT_TABOO to prevent filtering if the answer
1597 * is a partial range (HTTP status 206)
1598 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
1602 * 1 : csp = Current client state (buffers, headers, etc...)
1603 * 2 : header = On input, pointer to header to modify.
1604 * On output, pointer to the modified header, or NULL
1605 * to remove the header. This function frees the
1606 * original string if necessary.
1608 * Returns : JB_ERR_OK on success, or
1609 * JB_ERR_MEMORY on out-of-memory error.
1611 *********************************************************************/
1612 jb_err server_http(struct client_state *csp, char **header)
1614 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
1615 if (csp->http->status == 206)
1617 csp->content_type = CT_TABOO;
1620 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
1623 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
1630 /*********************************************************************
1632 * Function : server_set_cookie
1634 * Description : Handle the server "cookie" header properly.
1635 * Log cookie to the jar file. Then "crunch" it,
1636 * or accept it. Called from `sed'.
1639 * 1 : csp = Current client state (buffers, headers, etc...)
1640 * 2 : header = On input, pointer to header to modify.
1641 * On output, pointer to the modified header, or NULL
1642 * to remove the header. This function frees the
1643 * original string if necessary.
1645 * Returns : JB_ERR_OK on success, or
1646 * JB_ERR_MEMORY on out-of-memory error.
1648 *********************************************************************/
1649 jb_err server_set_cookie(struct client_state *csp, char **header)
1651 #ifdef FEATURE_COOKIE_JAR
1652 if (csp->config->jar)
1655 * Write timestamp into outbuf.
1657 * Complex because not all OSs have tm_gmtoff or
1658 * the %z field in strftime()
1660 char tempbuf[ BUFFER_SIZE ];
1664 #ifdef HAVE_LOCALTIME_R
1665 tm_now = *localtime_r(&now, &tm_now);
1667 tm_now = *localtime (&now);
1669 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
1671 /* strlen("set-cookie: ") = 12 */
1672 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
1674 #endif /* def FEATURE_COOKIE_JAR */
1676 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
1678 return crumble(csp, header);
1680 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
1682 /* Flag whether or not to log a message */
1685 /* A variable to store the tag we're working on */
1688 /* Skip "Set-Cookie:" (11 characters) in header */
1689 cur_tag = *header + 11;
1691 /* skip whitespace between "Set-Cookie:" and value */
1692 while (*cur_tag && ijb_isspace(*cur_tag))
1697 /* Loop through each tag in the cookie */
1701 char *next_tag = strchr(cur_tag, ';');
1702 if (next_tag != NULL)
1704 /* Skip the ';' character itself */
1707 /* skip whitespace ";" and start of tag */
1708 while (*next_tag && ijb_isspace(*next_tag))
1715 /* "Next tag" is the end of the string */
1716 next_tag = cur_tag + strlen(cur_tag);
1719 /* Is this the "Expires" tag? */
1720 if (strncmpic(cur_tag, "expires=", 8) == 0)
1722 /* Delete the tag by copying the rest of the string over it.
1723 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
1724 * since the behaviour of strcpy is undefined for overlapping
1727 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
1729 /* That changed the header, need to issue a log message */
1732 /* Note that the next tag has now been moved to *cur_tag,
1733 * so we do not need to update the cur_tag pointer.
1738 /* Move on to next cookie tag */
1745 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
1753 #ifdef FEATURE_FORCE_LOAD
1754 /*********************************************************************
1756 * Function : strclean
1758 * Description : In-Situ-Eliminate all occurances of substring in
1762 * 1 : string = string to clean
1763 * 2 : substring = substring to eliminate
1765 * Returns : Number of eliminations
1767 *********************************************************************/
1768 int strclean(const char *string, const char *substring)
1770 int hits = 0, len = strlen(substring);
1773 while((pos = strstr(string, substring)) != NULL)
1780 while (*p++ != '\0');
1787 #endif /* def FEATURE_FORCE_LOAD */