1 const char parsers_rcs[] = "$Id: parsers.c,v 1.54 2002/04/02 15:03:16 oes Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/parsers.c,v $
6 * Purpose : Declares functions to parse/crunch headers and pages.
7 * Functions declared include:
8 * `add_to_iob', `client_cookie_adder', `client_from',
9 * `client_referrer', `client_send_cookie', `client_ua',
10 * `client_uagent', `client_x_forwarded',
11 * `client_x_forwarded_adder', `client_xtra_adder',
12 * `content_type', `crumble', `destroy_list', `enlist',
13 * `flush_socket', ``get_header', `sed',
14 * and `server_set_cookie'.
16 * Copyright : Written by and Copyright (C) 2001 the SourceForge
17 * 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.54 2002/04/02 15:03:16 oes
46 * Revision 1.53 2002/03/26 22:29:55 swa
47 * we have a new homepage!
49 * Revision 1.52 2002/03/24 13:25:43 swa
50 * name change related issues
52 * Revision 1.51 2002/03/13 00:27:05 jongfoster
55 * Revision 1.50 2002/03/12 01:45:35 oes
56 * More verbose logging
58 * Revision 1.49 2002/03/09 20:03:52 jongfoster
59 * - Making various functions return int rather than size_t.
60 * (Undoing a recent change). Since size_t is unsigned on
61 * Windows, functions like read_socket that return -1 on
62 * error cannot return a size_t.
64 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
65 * crashes, and also frequently caused JB to jump to 100%
66 * CPU and stay there. (Because it thought it had just
67 * read ((unsigned)-1) == 4Gb of data...)
69 * - The signature of write_socket has changed, it now simply
70 * returns success=0/failure=nonzero.
72 * - Trying to get rid of a few warnings --with-debug on
73 * Windows, I've introduced a new type "jb_socket". This is
74 * used for the socket file descriptors. On Windows, this
75 * is SOCKET (a typedef for unsigned). Everywhere else, it's
76 * an int. The error value can't be -1 any more, so it's
77 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
78 * Windows it maps to the #define INVALID_SOCKET.)
80 * - The signature of bind_port has changed.
82 * Revision 1.48 2002/03/07 03:46:53 oes
83 * Fixed compiler warnings etc
85 * Revision 1.47 2002/02/20 23:15:13 jongfoster
86 * Parsing functions now handle out-of-memory gracefully by returning
89 * Revision 1.46 2002/01/17 21:03:47 jongfoster
90 * Moving all our URL and URL pattern parsing code to urlmatch.c.
92 * Revision 1.45 2002/01/09 14:33:03 oes
93 * Added support for localtime_r.
95 * Revision 1.44 2001/12/14 01:22:54 steudten
96 * Remove 'user:pass@' from 'proto://user:pass@host' for the
97 * new added header 'Host: ..'. (See Req ID 491818)
99 * Revision 1.43 2001/11/23 00:26:38 jongfoster
100 * Fixing two really stupid errors in my previous commit
102 * Revision 1.42 2001/11/22 21:59:30 jongfoster
103 * Adding code to handle +no-cookies-keep
105 * Revision 1.41 2001/11/05 23:43:05 steudten
106 * Add time+date to log files.
108 * Revision 1.40 2001/10/26 20:13:09 jongfoster
109 * ctype.h is needed in Windows, too.
111 * Revision 1.39 2001/10/26 17:40:04 oes
112 * Introduced get_header_value()
113 * Removed http->user_agent, csp->referrer and csp->accept_types
114 * Removed client_accept()
116 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
117 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
118 * threads to call select() simultaneously. So, it's time to do a real, live,
119 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
120 * (native). Both versions will work, but using __OS2__ offers multi-threading.
122 * Revision 1.37 2001/10/23 21:36:02 jongfoster
123 * Documenting sed()'s error behaviou (doc change only)
125 * Revision 1.36 2001/10/13 12:51:51 joergs
126 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
127 * force-load), instead crumble Host: and add it (again) in client_host_adder
128 * (in case we get a HTTP/1.0 request without Host: header and forward it to
129 * a HTTP/1.1 server/proxy).
131 * Revision 1.35 2001/10/09 22:39:21 jongfoster
132 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
135 * Revision 1.34 2001/10/07 18:50:55 oes
136 * Added server_content_encoding, renamed server_transfer_encoding
138 * Revision 1.33 2001/10/07 18:04:49 oes
139 * Changed server_http11 to server_http and its pattern to "HTTP".
140 * Additional functionality: it now saves the HTTP status into
141 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
143 * Revision 1.32 2001/10/07 15:43:28 oes
144 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
145 * client_te and client_accept_encoding_adder, triggered by the new
146 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
147 * changed to allow only identity and chunked, and the TE header is
148 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
150 * parse_http_request no longer does anything than parsing. The rewriting
151 * of http->cmd and version mangling are gone. It now also recognizes
152 * the put and delete methods and saves the url in http->url. Removed
155 * renamed content_type and content_length to have the server_ prefix
157 * server_content_type now only works if csp->content_type != CT_TABOO
159 * added server_transfer_encoding, which
160 * - Sets CT_TABOO to prohibit filtering if encoding compresses
161 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
162 * - Change from "chunked" to "identity" if body was chunked
163 * but has been de-chunked for filtering.
165 * added server_content_md5 which crunches any Content-MD5 headers
166 * if the body was modified.
168 * made server_http11 conditional on +downgrade action
170 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
172 * Revision 1.31 2001/10/05 14:25:02 oes
173 * Crumble Keep-Alive from Server
175 * Revision 1.30 2001/09/29 12:56:03 joergs
176 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
178 * Revision 1.29 2001/09/24 21:09:24 jongfoster
179 * Fixing 2 memory leaks that Guy spotted, where the paramater to
180 * enlist() was not being free()d.
182 * Revision 1.28 2001/09/22 16:32:28 jongfoster
183 * Removing unused #includes.
185 * Revision 1.27 2001/09/20 15:45:25 steudten
187 * add casting from size_t to int for printf()
188 * remove local variable shadow s2
190 * Revision 1.26 2001/09/16 17:05:14 jongfoster
191 * Removing unused #include showarg.h
193 * Revision 1.25 2001/09/16 13:21:27 jongfoster
194 * Changes to use new list functions.
196 * Revision 1.24 2001/09/13 23:05:50 jongfoster
197 * Changing the string paramater to the header parsers a "const".
199 * Revision 1.23 2001/09/12 18:08:19 steudten
201 * In parse_http_request() header rewriting miss the host value, so
202 * from http://www.mydomain.com the result was just " / " not
203 * http://www.mydomain.com/ in case we forward.
205 * Revision 1.22 2001/09/10 10:58:53 oes
206 * Silenced compiler warnings
208 * Revision 1.21 2001/07/31 14:46:00 oes
209 * - Persistant connections now suppressed
210 * - sed() no longer appends empty header to csp->headers
212 * Revision 1.20 2001/07/30 22:08:36 jongfoster
213 * Tidying up #defines:
214 * - All feature #defines are now of the form FEATURE_xxx
215 * - Permanently turned off WIN_GUI_EDIT
216 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
218 * Revision 1.19 2001/07/25 17:21:54 oes
219 * client_uagent now saves copy of User-Agent: header value
221 * Revision 1.18 2001/07/13 14:02:46 oes
222 * - Included fix to repair broken HTTP requests that
223 * don't contain a path, not even '/'.
224 * - Removed all #ifdef PCRS
225 * - content_type now always inspected and classified as
226 * text, gif or other.
227 * - formatting / comments
229 * Revision 1.17 2001/06/29 21:45:41 oes
230 * Indentation, CRLF->LF, Tab-> Space
232 * Revision 1.16 2001/06/29 13:32:42 oes
234 * - Adapted free_http_request
235 * - Removed logentry from cancelled commit
237 * Revision 1.15 2001/06/03 19:12:38 oes
238 * deleted const struct interceptors
240 * Revision 1.14 2001/06/01 18:49:17 jongfoster
241 * Replaced "list_share" with "list" - the tiny memory gain was not
242 * worth the extra complexity.
244 * Revision 1.13 2001/05/31 21:30:33 jongfoster
245 * Removed list code - it's now in list.[ch]
246 * Renamed "permission" to "action", and changed many features
247 * to use the actions file rather than the global config.
249 * Revision 1.12 2001/05/31 17:33:13 oes
253 * Revision 1.11 2001/05/29 20:11:19 joergs
254 * '/ * inside comment' warning removed.
256 * Revision 1.10 2001/05/29 09:50:24 jongfoster
257 * Unified blocklist/imagelist/permissionslist.
258 * File format is still under discussion, but the internal changes
261 * Also modified interceptor behaviour:
262 * - We now intercept all URLs beginning with one of the following
263 * prefixes (and *only* these prefixes):
265 * * http://ijbswa.sf.net/config/
266 * * http://ijbswa.sourceforge.net/config/
267 * - New interceptors "home page" - go to http://i.j.b/ to see it.
268 * - Internal changes so that intercepted and fast redirect pages
269 * are not replaced with an image.
270 * - Interceptors now have the option to send a binary page direct
271 * to the client. (i.e. ijb-send-banner uses this)
272 * - Implemented show-url-info interceptor. (Which is why I needed
273 * the above interceptors changes - a typical URL is
274 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
275 * The previous mechanism would not have intercepted that, and
276 * if it had been intercepted then it then it would have replaced
279 * Revision 1.9 2001/05/28 17:26:33 jongfoster
280 * Fixing segfault if last header was crunched.
281 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
282 * can use the cross-platform sprintf() instead.)
284 * Revision 1.8 2001/05/27 22:17:04 oes
286 * - re_process_buffer no longer writes the modified buffer
287 * to the client, which was very ugly. It now returns the
288 * buffer, which it is then written by chat.
290 * - content_length now adjusts the Content-Length: header
291 * for modified documents rather than crunch()ing it.
292 * (Length info in csp->content_length, which is 0 for
293 * unmodified documents)
295 * - For this to work, sed() is called twice when filtering.
297 * Revision 1.7 2001/05/27 13:19:06 oes
298 * Patched Joergs solution for the content-length in.
300 * Revision 1.6 2001/05/26 13:39:32 jongfoster
301 * Only crunches Content-Length header if applying RE filtering.
302 * Without this fix, Microsoft Windows Update wouldn't work.
304 * Revision 1.5 2001/05/26 00:28:36 jongfoster
305 * Automatic reloading of config file.
306 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
307 * Most of the global variables have been moved to a new
308 * struct configuration_spec, accessed through csp->config->globalname
309 * Most of the globals remaining are used by the Win32 GUI.
311 * Revision 1.4 2001/05/22 18:46:04 oes
313 * - Enabled filtering banners by size rather than URL
314 * by adding patterns that replace all standard banner
315 * sizes with the "Junkbuster" gif to the re_filterfile
317 * - Enabled filtering WebBugs by providing a pattern
318 * which kills all 1x1 images
320 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
321 * which is selected by the (nonstandard and therefore
322 * capital) letter 'U' in the option string.
323 * It causes the quantifiers to be ungreedy by default.
324 * Appending a ? turns back to greedy (!).
326 * - Added a new interceptor ijb-send-banner, which
327 * sends back the "Junkbuster" gif. Without imagelist or
328 * MSIE detection support, or if tinygif = 1, or the
329 * URL isn't recognized as an imageurl, a lame HTML
330 * explanation is sent instead.
332 * - Added new feature, which permits blocking remote
333 * script redirects and firing back a local redirect
335 * The feature is conditionally compiled, i.e. it
336 * can be disabled with --disable-fast-redirects,
337 * plus it must be activated by a "fast-redirects"
338 * line in the config file, has its own log level
339 * and of course wants to be displayed by show-proxy-args
340 * Note: Boy, all the #ifdefs in 1001 locations and
341 * all the fumbling with configure.in and acconfig.h
342 * were *way* more work than the feature itself :-(
344 * - Because a generic redirect template was needed for
345 * this, tinygif = 3 now uses the same.
347 * - Moved GIFs, and other static HTTP response templates
352 * - Removed some >400 CRs again (Jon, you really worked
355 * Revision 1.3 2001/05/20 01:21:20 jongfoster
356 * Version 2.9.4 checkin.
357 * - Merged popupfile and cookiefile, and added control over PCRS
358 * filtering, in new "permissionsfile".
359 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
360 * file error you now get a message box (in the Win32 GUI) rather
361 * than the program exiting with no explanation.
362 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
364 * - Removed tabs from "config"
365 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
366 * - Bumped up version number.
368 * Revision 1.2 2001/05/17 23:02:36 oes
369 * - Made referrer option accept 'L' as a substitute for '§'
371 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
372 * Initial import of version 2.9.3 source tree
375 *********************************************************************/
382 #include <sys/types.h>
390 #if !defined(_WIN32) && !defined(__OS2__)
400 #include "jbsockets.h"
401 #include "miscutil.h"
404 const char parsers_h_rcs[] = PARSERS_H_VERSION;
406 /* Fix a problem with Solaris. There should be no effect on other
408 * Solaris's isspace() is a macro which uses it's argument directly
409 * as an array index. Therefore we need to make sure that high-bit
410 * characters generate +ve values, and ideally we also want to make
411 * the argument match the declared parameter type of "int".
413 * Why did they write a character function that can't take a simple
414 * "char" argument? Doh!
416 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
417 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
420 const struct parsers client_patterns[] = {
421 { "referer:", 8, client_referrer },
422 { "user-agent:", 11, client_uagent },
423 { "ua-", 3, client_ua },
424 { "from:", 5, client_from },
425 { "cookie:", 7, client_send_cookie },
426 { "x-forwarded-for:", 16, client_x_forwarded },
427 { "Accept-Encoding:", 16, client_accept_encoding },
428 { "TE:", 3, client_te },
429 { "Host:", 5, crumble },
430 /* { "if-modified-since:", 18, crumble }, */
431 { "Keep-Alive:", 11, crumble },
432 { "connection:", 11, crumble },
433 { "proxy-connection:", 17, crumble },
438 const struct parsers server_patterns[] = {
439 { "HTTP", 4, server_http },
440 { "set-cookie:", 11, server_set_cookie },
441 { "connection:", 11, crumble },
442 { "Content-Type:", 13, server_content_type },
443 { "Content-Length:", 15, server_content_length },
444 { "Content-MD5:", 12, server_content_md5 },
445 { "Content-Encoding:", 17, server_content_encoding },
446 { "Transfer-Encoding:", 18, server_transfer_coding },
447 { "Keep-Alive:", 11, crumble },
452 const add_header_func_ptr add_client_headers[] = {
455 client_x_forwarded_adder,
457 client_accept_encoding_adder,
458 connection_close_adder,
463 const add_header_func_ptr add_server_headers[] = {
464 connection_close_adder,
469 /*********************************************************************
471 * Function : flush_socket
473 * Description : Write any pending "buffered" content.
476 * 1 : fd = file descriptor of the socket to read
477 * 2 : csp = Current client state (buffers, headers, etc...)
479 * Returns : On success, the number of bytes written are returned (zero
480 * indicates nothing was written). On error, -1 is returned,
481 * and errno is set appropriately. If count is zero and the
482 * file descriptor refers to a regular file, 0 will be
483 * returned without causing any other effect. For a special
484 * file, the results are not portable.
486 *********************************************************************/
487 int flush_socket(jb_socket fd, struct client_state *csp)
489 struct iob *iob = csp->iob;
490 int len = iob->eod - iob->cur;
497 if (write_socket(fd, iob->cur, (size_t)len))
501 iob->eod = iob->cur = iob->buf;
507 /*********************************************************************
509 * Function : add_to_iob
511 * Description : Add content to the buffered page, expanding the
512 * buffer if necessary.
515 * 1 : csp = Current client state (buffers, headers, etc...)
516 * 2 : buf = holds the content to be added to the page
517 * 3 : n = number of bytes to be added
519 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
520 * or buffer limit reached.
522 *********************************************************************/
523 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
525 struct iob *iob = csp->iob;
526 size_t used, offset, need, want;
529 if (n <= 0) return JB_ERR_OK;
531 used = iob->eod - iob->buf;
532 offset = iob->cur - iob->buf;
536 * If the buffer can't hold the new data, extend it first.
537 * Use the next power of two if possible, else use the actual need.
539 if (need > csp->config->buffer_limit)
541 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
542 return JB_ERR_MEMORY;
545 if (need > iob->size)
547 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
549 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
553 else if (NULL != (p = (char *)realloc(iob->buf, need)))
559 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
560 return JB_ERR_MEMORY;
563 /* Update the iob pointers */
564 iob->cur = p + offset;
569 /* copy the new data into the iob buffer */
570 memcpy(iob->eod, buf, (size_t)n);
572 /* point to the end of the data */
575 /* null terminate == cheap insurance */
583 /*********************************************************************
585 * Function : get_header
587 * Description : This (odd) routine will parse the csp->iob
590 * 1 : csp = Current client state (buffers, headers, etc...)
592 * Returns : Any one of the following:
594 * 1) a pointer to a dynamically allocated string that contains a header line
595 * 2) NULL indicating that the end of the header was reached
596 * 3) "" indicating that the end of the iob was reached before finding
597 * a complete header line.
599 *********************************************************************/
600 char *get_header(struct client_state *csp)
606 if ((iob->cur == NULL)
607 || ((p = strchr(iob->cur, '\n')) == NULL))
609 return(""); /* couldn't find a complete header */
614 ret = strdup(iob->cur);
617 /* FIXME No way to handle error properly */
618 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
623 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
625 /* is this a blank linke (i.e. the end of the header) ? */
637 /*********************************************************************
639 * Function : get_header_value
641 * Description : Get the value of a given header from a chained list
642 * of header lines or return NULL if no such header is
643 * present in the list.
646 * 1 : header_list = pointer to list
647 * 2 : header_name = string with name of header to look for.
648 * Trailing colon required, capitalization
651 * Returns : NULL if not found, else value of header
653 *********************************************************************/
654 char *get_header_value(const struct list *header_list, const char *header_name)
656 struct list_entry *cur_entry;
662 length = strlen(header_name);
664 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
668 if (!strncmpic(cur_entry->str, header_name, length))
671 * Found: return pointer to start of value
673 ret = (char *) (cur_entry->str + length);
674 while (*ret && ijb_isspace(*ret)) ret++;
687 /*********************************************************************
691 * Description : add, delete or modify lines in the HTTP header streams.
692 * On entry, it receives a linked list of headers space
693 * that was allocated dynamically (both the list nodes
694 * and the header contents).
696 * As a side effect it frees the space used by the original
700 * 1 : pats = list of patterns to match against headers
701 * 2 : more_headers = list of functions to add more
702 * headers (client or server)
703 * 3 : csp = Current client state (buffers, headers, etc...)
705 * Returns : Single pointer to a fully formed header, or NULL
706 * on out-of-memory error.
708 *********************************************************************/
709 char *sed(const struct parsers pats[],
710 const add_header_func_ptr more_headers[],
711 struct client_state *csp)
713 struct list_entry *p;
714 const struct parsers *v;
715 const add_header_func_ptr *f;
716 jb_err err = JB_ERR_OK;
718 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
720 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
722 /* Header crunch()ed in previous run? -> ignore */
723 if (p->str == NULL) continue;
725 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
727 if (strncmpic(p->str, v->str, v->len) == 0)
729 err = v->parser(csp, (char **)&(p->str));
734 /* place any additional headers on the csp->headers list */
735 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
740 if (err != JB_ERR_OK)
745 return list_to_text(csp->headers);
749 /* here begins the family of parser functions that reformat header lines */
752 /*********************************************************************
756 * Description : This is called if a header matches a pattern to "crunch"
759 * 1 : csp = Current client state (buffers, headers, etc...)
760 * 2 : header = On input, pointer to header to modify.
761 * On output, pointer to the modified header, or NULL
762 * to remove the header. This function frees the
763 * original string if necessary.
765 * Returns : JB_ERR_OK on success, or
766 * JB_ERR_MEMORY on out-of-memory error.
768 *********************************************************************/
769 jb_err crumble(struct client_state *csp, char **header)
771 log_error(LOG_LEVEL_HEADER, "crunch!");
777 /*********************************************************************
779 * Function : server_content_type
781 * Description : Set the content-type for filterable types (text/.*,
782 * javascript and image/gif) unless filtering has been
783 * forbidden (CT_TABOO) while parsing earlier headers.
786 * 1 : csp = Current client state (buffers, headers, etc...)
787 * 2 : header = On input, pointer to header to modify.
788 * On output, pointer to the modified header, or NULL
789 * to remove the header. This function frees the
790 * original string if necessary.
792 * Returns : JB_ERR_OK on success, or
793 * JB_ERR_MEMORY on out-of-memory error.
795 *********************************************************************/
796 jb_err server_content_type(struct client_state *csp, char **header)
798 if (csp->content_type != CT_TABOO)
800 if (strstr(*header, " text/")
801 || strstr(*header, "application/x-javascript"))
802 csp->content_type = CT_TEXT;
803 else if (strstr(*header, " image/gif"))
804 csp->content_type = CT_GIF;
806 csp->content_type = 0;
813 /*********************************************************************
815 * Function : server_transfer_coding
817 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
818 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
819 * - Change from "chunked" to "identity" if body was chunked
820 * but has been de-chunked for filtering.
823 * 1 : csp = Current client state (buffers, headers, etc...)
824 * 2 : header = On input, pointer to header to modify.
825 * On output, pointer to the modified header, or NULL
826 * to remove the header. This function frees the
827 * original string if necessary.
829 * Returns : JB_ERR_OK on success, or
830 * JB_ERR_MEMORY on out-of-memory error.
832 *********************************************************************/
833 jb_err server_transfer_coding(struct client_state *csp, char **header)
836 * Turn off pcrs and gif filtering if body compressed
838 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
840 csp->content_type = CT_TABOO;
844 * Raise flag if body chunked
846 if (strstr(*header, "chunked"))
848 csp->flags |= CSP_FLAG_CHUNKED;
851 * If the body was modified, it has been
852 * de-chunked first, so adjust the header:
854 if (csp->flags & CSP_FLAG_MODIFIED)
857 *header = strdup("Transfer-Encoding: identity");
858 return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
866 /*********************************************************************
868 * Function : server_content_encoding
870 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
873 * 1 : csp = Current client state (buffers, headers, etc...)
874 * 2 : header = On input, pointer to header to modify.
875 * On output, pointer to the modified header, or NULL
876 * to remove the header. This function frees the
877 * original string if necessary.
879 * Returns : JB_ERR_OK on success, or
880 * JB_ERR_MEMORY on out-of-memory error.
882 *********************************************************************/
883 jb_err server_content_encoding(struct client_state *csp, char **header)
886 * Turn off pcrs and gif filtering if body compressed
888 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
890 csp->content_type = CT_TABOO;
898 /*********************************************************************
900 * Function : server_content_length
902 * Description : Adjust Content-Length header if we modified
906 * 1 : csp = Current client state (buffers, headers, etc...)
907 * 2 : header = On input, pointer to header to modify.
908 * On output, pointer to the modified header, or NULL
909 * to remove the header. This function frees the
910 * original string if necessary.
912 * Returns : JB_ERR_OK on success, or
913 * JB_ERR_MEMORY on out-of-memory error.
915 *********************************************************************/
916 jb_err server_content_length(struct client_state *csp, char **header)
918 if (csp->content_length != 0) /* Content length has been modified */
921 *header = (char *) zalloc(100);
924 return JB_ERR_MEMORY;
927 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
929 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
936 /*********************************************************************
938 * Function : server_content_md5
940 * Description : Crumble any Content-MD5 headers if the document was
941 * modified. FIXME: Should we re-compute instead?
944 * 1 : csp = Current client state (buffers, headers, etc...)
945 * 2 : header = On input, pointer to header to modify.
946 * On output, pointer to the modified header, or NULL
947 * to remove the header. This function frees the
948 * original string if necessary.
950 * Returns : JB_ERR_OK on success, or
951 * JB_ERR_MEMORY on out-of-memory error.
953 *********************************************************************/
954 jb_err server_content_md5(struct client_state *csp, char **header)
956 if (csp->flags & CSP_FLAG_MODIFIED)
958 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
966 /*********************************************************************
968 * Function : client_accept_encoding
970 * Description : Rewrite the client's Accept-Encoding header so that
971 * if doesn't allow compression, if the action applies.
972 * Note: For HTTP/1.0 the absence of the header is enough.
975 * 1 : csp = Current client state (buffers, headers, etc...)
976 * 2 : header = On input, pointer to header to modify.
977 * On output, pointer to the modified header, or NULL
978 * to remove the header. This function frees the
979 * original string if necessary.
981 * Returns : JB_ERR_OK on success, or
982 * JB_ERR_MEMORY on out-of-memory error.
984 *********************************************************************/
985 jb_err client_accept_encoding(struct client_state *csp, char **header)
987 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
989 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress content");
992 if (!strcmpic(csp->http->ver, "HTTP/1.1"))
994 *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
997 return JB_ERR_MEMORY;
1006 /*********************************************************************
1008 * Function : client_te
1010 * Description : Rewrite the client's TE header so that
1011 * if doesn't allow compression, if the action applies.
1014 * 1 : csp = Current client state (buffers, headers, etc...)
1015 * 2 : header = On input, pointer to header to modify.
1016 * On output, pointer to the modified header, or NULL
1017 * to remove the header. This function frees the
1018 * original string if necessary.
1020 * Returns : JB_ERR_OK on success, or
1021 * JB_ERR_MEMORY on out-of-memory error.
1023 *********************************************************************/
1024 jb_err client_te(struct client_state *csp, char **header)
1026 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1029 log_error(LOG_LEVEL_HEADER, "Supressed offer to compress transfer");
1035 /*********************************************************************
1037 * Function : client_referrer
1039 * Description : Handle the "referer" config setting properly.
1040 * Called from `sed'.
1043 * 1 : csp = Current client state (buffers, headers, etc...)
1044 * 2 : header = On input, pointer to header to modify.
1045 * On output, pointer to the modified header, or NULL
1046 * to remove the header. This function frees the
1047 * original string if necessary.
1049 * Returns : JB_ERR_OK on success, or
1050 * JB_ERR_MEMORY on out-of-memory error.
1052 *********************************************************************/
1053 jb_err client_referrer(struct client_state *csp, char **header)
1057 #ifdef FEATURE_FORCE_LOAD
1058 /* Since the referrer can include the prefix even
1059 * even if the request itself is non-forced, we must
1060 * clean it unconditionally
1062 strclean(*header, FORCE_PREFIX);
1063 #endif /* def FEATURE_FORCE_LOAD */
1066 * Are we sending referer?
1068 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1075 newval = csp->action->string[ACTION_STRING_REFERER];
1077 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1082 log_error(LOG_LEVEL_HEADER, "crunch!");
1085 else if (0 == strncmpic(newval, "http://", 7))
1088 * We have a specific (fixed) referer we want to send.
1090 log_error(LOG_LEVEL_HEADER, "modified");
1092 *header = strdup("Referer: ");
1093 string_append(header, newval);
1095 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1100 * Forge a referer as http://[hostname:port of REQUEST]/
1101 * to fool stupid checks for in-site links
1103 if (0 != strcmpic(newval, "forge"))
1106 * Invalid choice - but forge is probably the best default.
1108 log_error(LOG_LEVEL_ERROR, "Bad parameter: +referer{%s}", newval);
1111 *header = strdup("Referer: http://");
1112 string_append(header, csp->http->hostport);
1113 string_append(header, "/");
1114 log_error(LOG_LEVEL_HEADER, "crunch+forge to %s", *header);
1116 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1121 /*********************************************************************
1123 * Function : client_uagent
1125 * Description : Handle the "user-agent" config setting properly
1126 * and remember its original value to enable browser
1127 * bug workarounds. Called from `sed'.
1130 * 1 : csp = Current client state (buffers, headers, etc...)
1131 * 2 : header = On input, pointer to header to modify.
1132 * On output, pointer to the modified header, or NULL
1133 * to remove the header. This function frees the
1134 * original string if necessary.
1136 * Returns : JB_ERR_OK on success, or
1137 * JB_ERR_MEMORY on out-of-memory error.
1139 *********************************************************************/
1140 jb_err client_uagent(struct client_state *csp, char **header)
1144 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1149 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1155 log_error(LOG_LEVEL_HEADER, "modified");
1158 *header = strdup("User-Agent: ");
1159 string_append(header, newval);
1161 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1165 /*********************************************************************
1167 * Function : client_ua
1169 * Description : Handle "ua-" headers properly. Called from `sed'.
1172 * 1 : csp = Current client state (buffers, headers, etc...)
1173 * 2 : header = On input, pointer to header to modify.
1174 * On output, pointer to the modified header, or NULL
1175 * to remove the header. This function frees the
1176 * original string if necessary.
1178 * Returns : JB_ERR_OK on success, or
1179 * JB_ERR_MEMORY on out-of-memory error.
1181 *********************************************************************/
1182 jb_err client_ua(struct client_state *csp, char **header)
1184 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1186 log_error(LOG_LEVEL_HEADER, "crunch!");
1194 /*********************************************************************
1196 * Function : client_from
1198 * Description : Handle the "from" config setting properly.
1199 * Called from `sed'.
1202 * 1 : csp = Current client state (buffers, headers, etc...)
1203 * 2 : header = On input, pointer to header to modify.
1204 * On output, pointer to the modified header, or NULL
1205 * to remove the header. This function frees the
1206 * original string if necessary.
1208 * Returns : JB_ERR_OK on success, or
1209 * JB_ERR_MEMORY on out-of-memory error.
1211 *********************************************************************/
1212 jb_err client_from(struct client_state *csp, char **header)
1216 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1223 newval = csp->action->string[ACTION_STRING_FROM];
1226 * Are we blocking the e-mail address?
1228 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1230 log_error(LOG_LEVEL_HEADER, "crunch!");
1234 log_error(LOG_LEVEL_HEADER, " modified");
1236 *header = strdup("From: ");
1237 string_append(header, newval);
1239 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1243 /*********************************************************************
1245 * Function : client_send_cookie
1247 * Description : Handle the "cookie" header properly. Called from `sed'.
1248 * If cookie is accepted, add it to the cookie_list,
1249 * else we crunch it. Mmmmmmmmmmm ... cookie ......
1252 * 1 : csp = Current client state (buffers, headers, etc...)
1253 * 2 : header = On input, pointer to header to modify.
1254 * On output, pointer to the modified header, or NULL
1255 * to remove the header. This function frees the
1256 * original string if necessary.
1258 * Returns : JB_ERR_OK on success, or
1259 * JB_ERR_MEMORY on out-of-memory error.
1261 *********************************************************************/
1262 jb_err client_send_cookie(struct client_state *csp, char **header)
1264 jb_err result = JB_ERR_OK;
1266 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
1268 /* strlen("cookie: ") == 8 */
1269 result = enlist(csp->cookie_list, *header + 8);
1273 log_error(LOG_LEVEL_HEADER, " crunch!");
1277 * Always remove the cookie here. The cookie header
1278 * will be sent at the end of the header.
1286 /*********************************************************************
1288 * Function : client_x_forwarded
1290 * Description : Handle the "x-forwarded-for" config setting properly,
1291 * also used in the add_client_headers list. Called from `sed'.
1294 * 1 : csp = Current client state (buffers, headers, etc...)
1295 * 2 : header = On input, pointer to header to modify.
1296 * On output, pointer to the modified header, or NULL
1297 * to remove the header. This function frees the
1298 * original string if necessary.
1300 * Returns : JB_ERR_OK on success, or
1301 * JB_ERR_MEMORY on out-of-memory error.
1303 *********************************************************************/
1304 jb_err client_x_forwarded(struct client_state *csp, char **header)
1306 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
1308 /* Save it so we can re-add it later */
1309 freez(csp->x_forwarded);
1310 csp->x_forwarded = *header;
1313 * Always set *header = NULL, since this information
1314 * will be sent at the end of the header.
1321 log_error(LOG_LEVEL_HEADER, " crunch!");
1327 /* the following functions add headers directly to the header list */
1329 /*********************************************************************
1331 * Function : client_host_adder
1333 * Description : (re)adds the host header. Called from `sed'.
1336 * 1 : csp = Current client state (buffers, headers, etc...)
1338 * Returns : JB_ERR_OK on success, or
1339 * JB_ERR_MEMORY on out-of-memory error.
1341 *********************************************************************/
1342 jb_err client_host_adder(struct client_state *csp)
1348 if ( !csp->http->hostport || !*(csp->http->hostport))
1353 p = strdup("Host: ");
1355 ** remove 'user:pass@' from 'proto://user:pass@host'
1357 if ( (pos = strchr( csp->http->hostport, '@')) != NULL )
1359 string_append(&p, pos+1);
1363 string_append(&p, csp->http->hostport);
1368 return JB_ERR_MEMORY;
1371 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1373 err = enlist(csp->headers, p);
1381 /*********************************************************************
1383 * Function : client_cookie_adder
1385 * Description : Used in the add_client_headers list. Called from `sed'.
1388 * 1 : csp = Current client state (buffers, headers, etc...)
1390 * Returns : JB_ERR_OK on success, or
1391 * JB_ERR_MEMORY on out-of-memory error.
1393 *********************************************************************/
1394 jb_err client_cookie_adder(struct client_state *csp)
1396 struct list_entry *lst;
1398 struct list_entry *list1 = csp->cookie_list->first;
1399 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
1400 int first_cookie = 1;
1403 if ((list1 == NULL) && (list2 == NULL))
1409 tmp = strdup("Cookie: ");
1411 for (lst = list1; lst ; lst = lst->next)
1419 string_append(&tmp, "; ");
1421 string_append(&tmp, lst->str);
1424 for (lst = list2; lst ; lst = lst->next)
1432 string_append(&tmp, "; ");
1434 string_join(&tmp, cookie_encode(lst->str));
1439 return JB_ERR_MEMORY;
1442 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
1443 err = enlist(csp->headers, tmp);
1449 /*********************************************************************
1451 * Function : client_accept_encoding_adder
1453 * Description : Add an Accept-Encoding header to the client's request
1454 * that disables compression if the action applies, and
1455 * the header is not already there. Called from `sed'.
1456 * Note: For HTTP/1.0, the absence of the header is enough.
1459 * 1 : csp = Current client state (buffers, headers, etc...)
1461 * Returns : JB_ERR_OK on success, or
1462 * JB_ERR_MEMORY on out-of-memory error.
1464 *********************************************************************/
1465 jb_err client_accept_encoding_adder(struct client_state *csp)
1467 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1468 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
1470 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
1477 /*********************************************************************
1479 * Function : client_xtra_adder
1481 * Description : Used in the add_client_headers list. Called from `sed'.
1484 * 1 : csp = Current client state (buffers, headers, etc...)
1486 * Returns : JB_ERR_OK on success, or
1487 * JB_ERR_MEMORY on out-of-memory error.
1489 *********************************************************************/
1490 jb_err client_xtra_adder(struct client_state *csp)
1492 struct list_entry *lst;
1495 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
1496 lst ; lst = lst->next)
1498 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
1499 err = enlist(csp->headers, lst->str);
1511 /*********************************************************************
1513 * Function : client_x_forwarded_adder
1515 * Description : Used in the add_client_headers list. Called from `sed'.
1518 * 1 : csp = Current client state (buffers, headers, etc...)
1520 * Returns : JB_ERR_OK on success, or
1521 * JB_ERR_MEMORY on out-of-memory error.
1523 *********************************************************************/
1524 jb_err client_x_forwarded_adder(struct client_state *csp)
1529 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
1534 if (csp->x_forwarded)
1536 p = strdup(csp->x_forwarded);
1537 string_append(&p, ", ");
1541 p = strdup("X-Forwarded-For: ");
1543 string_append(&p, csp->ip_addr_str);
1547 return JB_ERR_MEMORY;
1550 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
1551 err = enlist(csp->headers, p);
1558 /*********************************************************************
1560 * Function : connection_close_adder
1562 * Description : Adds a "Connection: close" header to csp->headers
1563 * as a temporary fix for the needed but missing HTTP/1.1
1564 * support. Called from `sed'.
1565 * FIXME: This whole function shouldn't be neccessary!
1568 * 1 : csp = Current client state (buffers, headers, etc...)
1570 * Returns : JB_ERR_OK on success, or
1571 * JB_ERR_MEMORY on out-of-memory error.
1573 *********************************************************************/
1574 jb_err connection_close_adder(struct client_state *csp)
1576 return enlist(csp->headers, "Connection: close");
1580 /*********************************************************************
1582 * Function : server_http
1584 * Description : - Save the HTTP Status into csp->http->status
1585 * - Set CT_TABOO to prevent filtering if the answer
1586 * is a partial range (HTTP status 206)
1587 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
1591 * 1 : csp = Current client state (buffers, headers, etc...)
1592 * 2 : header = On input, pointer to header to modify.
1593 * On output, pointer to the modified header, or NULL
1594 * to remove the header. This function frees the
1595 * original string if necessary.
1597 * Returns : JB_ERR_OK on success, or
1598 * JB_ERR_MEMORY on out-of-memory error.
1600 *********************************************************************/
1601 jb_err server_http(struct client_state *csp, char **header)
1603 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
1604 if (csp->http->status == 206)
1606 csp->content_type = CT_TABOO;
1609 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
1612 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
1619 /*********************************************************************
1621 * Function : server_set_cookie
1623 * Description : Handle the server "cookie" header properly.
1624 * Log cookie to the jar file. Then "crunch" it,
1625 * or accept it. Called from `sed'.
1628 * 1 : csp = Current client state (buffers, headers, etc...)
1629 * 2 : header = On input, pointer to header to modify.
1630 * On output, pointer to the modified header, or NULL
1631 * to remove the header. This function frees the
1632 * original string if necessary.
1634 * Returns : JB_ERR_OK on success, or
1635 * JB_ERR_MEMORY on out-of-memory error.
1637 *********************************************************************/
1638 jb_err server_set_cookie(struct client_state *csp, char **header)
1640 #ifdef FEATURE_COOKIE_JAR
1641 if (csp->config->jar)
1644 * Write timestamp into outbuf.
1646 * Complex because not all OSs have tm_gmtoff or
1647 * the %z field in strftime()
1649 char tempbuf[ BUFFER_SIZE ];
1653 #ifdef HAVE_LOCALTIME_R
1654 tm_now = *localtime_r(&now, &tm_now);
1656 tm_now = *localtime (&now);
1658 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
1660 /* strlen("set-cookie: ") = 12 */
1661 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
1663 #endif /* def FEATURE_COOKIE_JAR */
1665 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
1667 return crumble(csp, header);
1669 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
1671 /* Flag whether or not to log a message */
1674 /* A variable to store the tag we're working on */
1677 /* Skip "Set-Cookie:" (11 characters) in header */
1678 cur_tag = *header + 11;
1680 /* skip whitespace between "Set-Cookie:" and value */
1681 while (*cur_tag && ijb_isspace(*cur_tag))
1686 /* Loop through each tag in the cookie */
1690 char *next_tag = strchr(cur_tag, ';');
1691 if (next_tag != NULL)
1693 /* Skip the ';' character itself */
1696 /* skip whitespace ";" and start of tag */
1697 while (*next_tag && ijb_isspace(*next_tag))
1704 /* "Next tag" is the end of the string */
1705 next_tag = cur_tag + strlen(cur_tag);
1708 /* Is this the "Expires" tag? */
1709 if (strncmpic(cur_tag, "expires=", 8) == 0)
1711 /* Delete the tag by copying the rest of the string over it.
1712 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
1713 * since the behaviour of strcpy is undefined for overlapping
1716 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
1718 /* That changed the header, need to issue a log message */
1721 /* Note that the next tag has now been moved to *cur_tag,
1722 * so we do not need to update the cur_tag pointer.
1727 /* Move on to next cookie tag */
1734 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
1742 #ifdef FEATURE_FORCE_LOAD
1743 /*********************************************************************
1745 * Function : strclean
1747 * Description : In-Situ-Eliminate all occurances of substring in
1751 * 1 : string = string to clean
1752 * 2 : substring = substring to eliminate
1754 * Returns : Number of eliminations
1756 *********************************************************************/
1757 int strclean(const char *string, const char *substring)
1759 int hits = 0, len = strlen(substring);
1762 while((pos = strstr(string, substring)) != NULL)
1769 while (*p++ != '\0');
1776 #endif /* def FEATURE_FORCE_LOAD */