1 const char parsers_rcs[] = "$Id: parsers.c,v 1.61 2006/08/14 08:25:19 fabiankeil 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.61 2006/08/14 08:25:19 fabiankeil
44 * Split filter-headers{} into filter-client-headers{}
45 * and filter-server-headers{}.
46 * Added parse_header_time() to share some code.
47 * Replaced timegm() with mktime().
49 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
50 * Windows service integration
52 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
53 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
55 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
56 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
57 * with what was really the latest development (the v_3_0_branch branch)
59 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
60 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
62 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
63 * Add the ability to check jpeg images for invalid
64 * lengths of comment blocks. Defensive strategy
65 * against the exploit:
66 * Microsoft Security Bulletin MS04-028
67 * Buffer Overrun in JPEG Processing (GDI+) Could
68 * Allow Code Execution (833987)
69 * Enabled with +inspect-jpegs in actions files.
71 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
72 * Excluded text/plain objects from filtering. This fixes a
73 * couple of client-crashing, download corruption and
74 * Privoxy performance issues, whose root cause lies in
75 * web servers labelling content of unknown type as text/plain.
77 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
78 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
80 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
81 * Completing the previous change
83 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
84 * Added temporary workaround for bug in PHP < 4.2.3
86 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
87 * Wrapping all *_r functions (the non-_r versions of them) with mutex semaphores for OSX. Hopefully this will take care of all of those pesky crash reports.
89 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
90 * Fix typo: supressed -> suppressed
92 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
93 * Improved cookie logging
95 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
96 * Added basic support for OPTIONS and TRACE HTTP methods:
97 * - New parser function client_max_forwards which decrements
98 * the Max-Forwards HTTP header field of OPTIONS and TRACE
99 * requests by one before forwarding
100 * - New parser function client_host which extracts the host
101 * and port information from the HTTP header field if the
102 * request URI was not absolute
103 * - Don't crumble and re-add the Host: header, but only generate
104 * and append if missing
106 * Revision 1.56 2002/05/12 15:34:22 jongfoster
107 * Fixing typo in a comment
109 * Revision 1.55 2002/05/08 16:01:07 oes
110 * Optimized add_to_iob:
111 * - Use realloc instead of malloc(), memcpy(), free()
112 * - Expand to powers of two if possible, to get
113 * O(log n) reallocs instead of O(n).
114 * - Moved check for buffer limit here from chat
115 * - Report failure via returncode
117 * Revision 1.54 2002/04/02 15:03:16 oes
118 * Tiny code cosmetics
120 * Revision 1.53 2002/03/26 22:29:55 swa
121 * we have a new homepage!
123 * Revision 1.52 2002/03/24 13:25:43 swa
124 * name change related issues
126 * Revision 1.51 2002/03/13 00:27:05 jongfoster
129 * Revision 1.50 2002/03/12 01:45:35 oes
130 * More verbose logging
132 * Revision 1.49 2002/03/09 20:03:52 jongfoster
133 * - Making various functions return int rather than size_t.
134 * (Undoing a recent change). Since size_t is unsigned on
135 * Windows, functions like read_socket that return -1 on
136 * error cannot return a size_t.
138 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
139 * crashes, and also frequently caused JB to jump to 100%
140 * CPU and stay there. (Because it thought it had just
141 * read ((unsigned)-1) == 4Gb of data...)
143 * - The signature of write_socket has changed, it now simply
144 * returns success=0/failure=nonzero.
146 * - Trying to get rid of a few warnings --with-debug on
147 * Windows, I've introduced a new type "jb_socket". This is
148 * used for the socket file descriptors. On Windows, this
149 * is SOCKET (a typedef for unsigned). Everywhere else, it's
150 * an int. The error value can't be -1 any more, so it's
151 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
152 * Windows it maps to the #define INVALID_SOCKET.)
154 * - The signature of bind_port has changed.
156 * Revision 1.48 2002/03/07 03:46:53 oes
157 * Fixed compiler warnings etc
159 * Revision 1.47 2002/02/20 23:15:13 jongfoster
160 * Parsing functions now handle out-of-memory gracefully by returning
163 * Revision 1.46 2002/01/17 21:03:47 jongfoster
164 * Moving all our URL and URL pattern parsing code to urlmatch.c.
166 * Revision 1.45 2002/01/09 14:33:03 oes
167 * Added support for localtime_r.
169 * Revision 1.44 2001/12/14 01:22:54 steudten
170 * Remove 'user:pass@' from 'proto://user:pass@host' for the
171 * new added header 'Host: ..'. (See Req ID 491818)
173 * Revision 1.43 2001/11/23 00:26:38 jongfoster
174 * Fixing two really stupid errors in my previous commit
176 * Revision 1.42 2001/11/22 21:59:30 jongfoster
177 * Adding code to handle +no-cookies-keep
179 * Revision 1.41 2001/11/05 23:43:05 steudten
180 * Add time+date to log files.
182 * Revision 1.40 2001/10/26 20:13:09 jongfoster
183 * ctype.h is needed in Windows, too.
185 * Revision 1.39 2001/10/26 17:40:04 oes
186 * Introduced get_header_value()
187 * Removed http->user_agent, csp->referrer and csp->accept_types
188 * Removed client_accept()
190 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
191 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
192 * threads to call select() simultaneously. So, it's time to do a real, live,
193 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
194 * (native). Both versions will work, but using __OS2__ offers multi-threading.
196 * Revision 1.37 2001/10/23 21:36:02 jongfoster
197 * Documenting sed()'s error behaviou (doc change only)
199 * Revision 1.36 2001/10/13 12:51:51 joergs
200 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
201 * force-load), instead crumble Host: and add it (again) in client_host_adder
202 * (in case we get a HTTP/1.0 request without Host: header and forward it to
203 * a HTTP/1.1 server/proxy).
205 * Revision 1.35 2001/10/09 22:39:21 jongfoster
206 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
209 * Revision 1.34 2001/10/07 18:50:55 oes
210 * Added server_content_encoding, renamed server_transfer_encoding
212 * Revision 1.33 2001/10/07 18:04:49 oes
213 * Changed server_http11 to server_http and its pattern to "HTTP".
214 * Additional functionality: it now saves the HTTP status into
215 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
217 * Revision 1.32 2001/10/07 15:43:28 oes
218 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
219 * client_te and client_accept_encoding_adder, triggered by the new
220 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
221 * changed to allow only identity and chunked, and the TE header is
222 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
224 * parse_http_request no longer does anything than parsing. The rewriting
225 * of http->cmd and version mangling are gone. It now also recognizes
226 * the put and delete methods and saves the url in http->url. Removed
229 * renamed content_type and content_length to have the server_ prefix
231 * server_content_type now only works if csp->content_type != CT_TABOO
233 * added server_transfer_encoding, which
234 * - Sets CT_TABOO to prohibit filtering if encoding compresses
235 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
236 * - Change from "chunked" to "identity" if body was chunked
237 * but has been de-chunked for filtering.
239 * added server_content_md5 which crunches any Content-MD5 headers
240 * if the body was modified.
242 * made server_http11 conditional on +downgrade action
244 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
246 * Revision 1.31 2001/10/05 14:25:02 oes
247 * Crumble Keep-Alive from Server
249 * Revision 1.30 2001/09/29 12:56:03 joergs
250 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
252 * Revision 1.29 2001/09/24 21:09:24 jongfoster
253 * Fixing 2 memory leaks that Guy spotted, where the paramater to
254 * enlist() was not being free()d.
256 * Revision 1.28 2001/09/22 16:32:28 jongfoster
257 * Removing unused #includes.
259 * Revision 1.27 2001/09/20 15:45:25 steudten
261 * add casting from size_t to int for printf()
262 * remove local variable shadow s2
264 * Revision 1.26 2001/09/16 17:05:14 jongfoster
265 * Removing unused #include showarg.h
267 * Revision 1.25 2001/09/16 13:21:27 jongfoster
268 * Changes to use new list functions.
270 * Revision 1.24 2001/09/13 23:05:50 jongfoster
271 * Changing the string paramater to the header parsers a "const".
273 * Revision 1.23 2001/09/12 18:08:19 steudten
275 * In parse_http_request() header rewriting miss the host value, so
276 * from http://www.mydomain.com the result was just " / " not
277 * http://www.mydomain.com/ in case we forward.
279 * Revision 1.22 2001/09/10 10:58:53 oes
280 * Silenced compiler warnings
282 * Revision 1.21 2001/07/31 14:46:00 oes
283 * - Persistant connections now suppressed
284 * - sed() no longer appends empty header to csp->headers
286 * Revision 1.20 2001/07/30 22:08:36 jongfoster
287 * Tidying up #defines:
288 * - All feature #defines are now of the form FEATURE_xxx
289 * - Permanently turned off WIN_GUI_EDIT
290 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
292 * Revision 1.19 2001/07/25 17:21:54 oes
293 * client_uagent now saves copy of User-Agent: header value
295 * Revision 1.18 2001/07/13 14:02:46 oes
296 * - Included fix to repair broken HTTP requests that
297 * don't contain a path, not even '/'.
298 * - Removed all #ifdef PCRS
299 * - content_type now always inspected and classified as
300 * text, gif or other.
301 * - formatting / comments
303 * Revision 1.17 2001/06/29 21:45:41 oes
304 * Indentation, CRLF->LF, Tab-> Space
306 * Revision 1.16 2001/06/29 13:32:42 oes
308 * - Adapted free_http_request
309 * - Removed logentry from cancelled commit
311 * Revision 1.15 2001/06/03 19:12:38 oes
312 * deleted const struct interceptors
314 * Revision 1.14 2001/06/01 18:49:17 jongfoster
315 * Replaced "list_share" with "list" - the tiny memory gain was not
316 * worth the extra complexity.
318 * Revision 1.13 2001/05/31 21:30:33 jongfoster
319 * Removed list code - it's now in list.[ch]
320 * Renamed "permission" to "action", and changed many features
321 * to use the actions file rather than the global config.
323 * Revision 1.12 2001/05/31 17:33:13 oes
327 * Revision 1.11 2001/05/29 20:11:19 joergs
328 * '/ * inside comment' warning removed.
330 * Revision 1.10 2001/05/29 09:50:24 jongfoster
331 * Unified blocklist/imagelist/permissionslist.
332 * File format is still under discussion, but the internal changes
335 * Also modified interceptor behaviour:
336 * - We now intercept all URLs beginning with one of the following
337 * prefixes (and *only* these prefixes):
339 * * http://ijbswa.sf.net/config/
340 * * http://ijbswa.sourceforge.net/config/
341 * - New interceptors "home page" - go to http://i.j.b/ to see it.
342 * - Internal changes so that intercepted and fast redirect pages
343 * are not replaced with an image.
344 * - Interceptors now have the option to send a binary page direct
345 * to the client. (i.e. ijb-send-banner uses this)
346 * - Implemented show-url-info interceptor. (Which is why I needed
347 * the above interceptors changes - a typical URL is
348 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
349 * The previous mechanism would not have intercepted that, and
350 * if it had been intercepted then it then it would have replaced
353 * Revision 1.9 2001/05/28 17:26:33 jongfoster
354 * Fixing segfault if last header was crunched.
355 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
356 * can use the cross-platform sprintf() instead.)
358 * Revision 1.8 2001/05/27 22:17:04 oes
360 * - re_process_buffer no longer writes the modified buffer
361 * to the client, which was very ugly. It now returns the
362 * buffer, which it is then written by chat.
364 * - content_length now adjusts the Content-Length: header
365 * for modified documents rather than crunch()ing it.
366 * (Length info in csp->content_length, which is 0 for
367 * unmodified documents)
369 * - For this to work, sed() is called twice when filtering.
371 * Revision 1.7 2001/05/27 13:19:06 oes
372 * Patched Joergs solution for the content-length in.
374 * Revision 1.6 2001/05/26 13:39:32 jongfoster
375 * Only crunches Content-Length header if applying RE filtering.
376 * Without this fix, Microsoft Windows Update wouldn't work.
378 * Revision 1.5 2001/05/26 00:28:36 jongfoster
379 * Automatic reloading of config file.
380 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
381 * Most of the global variables have been moved to a new
382 * struct configuration_spec, accessed through csp->config->globalname
383 * Most of the globals remaining are used by the Win32 GUI.
385 * Revision 1.4 2001/05/22 18:46:04 oes
387 * - Enabled filtering banners by size rather than URL
388 * by adding patterns that replace all standard banner
389 * sizes with the "Junkbuster" gif to the re_filterfile
391 * - Enabled filtering WebBugs by providing a pattern
392 * which kills all 1x1 images
394 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
395 * which is selected by the (nonstandard and therefore
396 * capital) letter 'U' in the option string.
397 * It causes the quantifiers to be ungreedy by default.
398 * Appending a ? turns back to greedy (!).
400 * - Added a new interceptor ijb-send-banner, which
401 * sends back the "Junkbuster" gif. Without imagelist or
402 * MSIE detection support, or if tinygif = 1, or the
403 * URL isn't recognized as an imageurl, a lame HTML
404 * explanation is sent instead.
406 * - Added new feature, which permits blocking remote
407 * script redirects and firing back a local redirect
409 * The feature is conditionally compiled, i.e. it
410 * can be disabled with --disable-fast-redirects,
411 * plus it must be activated by a "fast-redirects"
412 * line in the config file, has its own log level
413 * and of course wants to be displayed by show-proxy-args
414 * Note: Boy, all the #ifdefs in 1001 locations and
415 * all the fumbling with configure.in and acconfig.h
416 * were *way* more work than the feature itself :-(
418 * - Because a generic redirect template was needed for
419 * this, tinygif = 3 now uses the same.
421 * - Moved GIFs, and other static HTTP response templates
426 * - Removed some >400 CRs again (Jon, you really worked
429 * Revision 1.3 2001/05/20 01:21:20 jongfoster
430 * Version 2.9.4 checkin.
431 * - Merged popupfile and cookiefile, and added control over PCRS
432 * filtering, in new "permissionsfile".
433 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
434 * file error you now get a message box (in the Win32 GUI) rather
435 * than the program exiting with no explanation.
436 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
438 * - Removed tabs from "config"
439 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
440 * - Bumped up version number.
442 * Revision 1.2 2001/05/17 23:02:36 oes
443 * - Made referrer option accept 'L' as a substitute for '§'
445 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
446 * Initial import of version 2.9.3 source tree
449 *********************************************************************/
456 #include <sys/types.h>
465 #if !defined(_WIN32) && !defined(__OS2__)
474 /* jcc.h is for mutex semapores only */
475 #endif /* def OSX_DARWIN */
481 #include "jbsockets.h"
482 #include "miscutil.h"
485 #ifndef HAVE_STRPTIME
486 #include "strptime.h"
489 const char parsers_h_rcs[] = PARSERS_H_VERSION;
491 /* Fix a problem with Solaris. There should be no effect on other
493 * Solaris's isspace() is a macro which uses it's argument directly
494 * as an array index. Therefore we need to make sure that high-bit
495 * characters generate +ve values, and ideally we also want to make
496 * the argument match the declared parameter type of "int".
498 * Why did they write a character function that can't take a simple
499 * "char" argument? Doh!
501 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
502 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
505 const struct parsers client_patterns[] = {
506 { "referer:", 8, client_referrer },
507 { "user-agent:", 11, client_uagent },
508 { "ua-", 3, client_ua },
509 { "from:", 5, client_from },
510 { "cookie:", 7, client_send_cookie },
511 { "x-forwarded-for:", 16, client_x_forwarded },
512 { "Accept-Encoding:", 16, client_accept_encoding },
513 { "TE:", 3, client_te },
514 { "Host:", 5, client_host },
515 { "if-modified-since:", 18, client_if_modified_since },
516 { "Keep-Alive:", 11, crumble },
517 { "connection:", 11, crumble },
518 { "proxy-connection:", 17, crumble },
519 { "max-forwards:", 13, client_max_forwards },
520 { "Accept-Language:", 16, client_accept_language },
521 { "if-none-match:", 14, client_if_none_match },
522 { "X-Filter:", 9, client_x_filter },
523 { "*", 0, crunch_client_header },
524 { "*", 0, filter_client_header },
528 const struct parsers server_patterns[] = {
529 { "HTTP", 4, server_http },
530 { "set-cookie:", 11, server_set_cookie },
531 { "connection:", 11, crumble },
532 { "Content-Type:", 13, server_content_type },
533 { "Content-Length:", 15, server_content_length },
534 { "Content-MD5:", 12, server_content_md5 },
535 { "Content-Encoding:", 17, server_content_encoding },
536 { "Transfer-Encoding:", 18, server_transfer_coding },
537 { "Keep-Alive:", 11, crumble },
538 { "content-disposition:", 20, server_content_disposition },
539 { "Last-Modified:", 14, server_last_modified },
540 { "*", 0, crunch_server_header },
541 { "*", 0, filter_server_header },
545 const struct parsers server_patterns_light[] = {
546 { "Content-Length:", 15, server_content_length },
547 { "Transfer-Encoding:", 18, server_transfer_coding },
551 const add_header_func_ptr add_client_headers[] = {
554 client_x_forwarded_adder,
556 /* Temporarily disabled: client_accept_encoding_adder, */
557 connection_close_adder,
562 const add_header_func_ptr add_server_headers[] = {
563 connection_close_adder,
567 /*********************************************************************
569 * Function : flush_socket
571 * Description : Write any pending "buffered" content.
574 * 1 : fd = file descriptor of the socket to read
575 * 2 : csp = Current client state (buffers, headers, etc...)
577 * Returns : On success, the number of bytes written are returned (zero
578 * indicates nothing was written). On error, -1 is returned,
579 * and errno is set appropriately. If count is zero and the
580 * file descriptor refers to a regular file, 0 will be
581 * returned without causing any other effect. For a special
582 * file, the results are not portable.
584 *********************************************************************/
585 int flush_socket(jb_socket fd, struct client_state *csp)
587 struct iob *iob = csp->iob;
588 int len = iob->eod - iob->cur;
595 if (write_socket(fd, iob->cur, (size_t)len))
599 iob->eod = iob->cur = iob->buf;
605 /*********************************************************************
607 * Function : add_to_iob
609 * Description : Add content to the buffered page, expanding the
610 * buffer if necessary.
613 * 1 : csp = Current client state (buffers, headers, etc...)
614 * 2 : buf = holds the content to be added to the page
615 * 3 : n = number of bytes to be added
617 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
618 * or buffer limit reached.
620 *********************************************************************/
621 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
623 struct iob *iob = csp->iob;
624 size_t used, offset, need, want;
627 if (n <= 0) return JB_ERR_OK;
629 used = iob->eod - iob->buf;
630 offset = iob->cur - iob->buf;
634 * If the buffer can't hold the new data, extend it first.
635 * Use the next power of two if possible, else use the actual need.
637 if (need > csp->config->buffer_limit)
639 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
640 return JB_ERR_MEMORY;
643 if (need > iob->size)
645 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
647 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
651 else if (NULL != (p = (char *)realloc(iob->buf, need)))
657 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
658 return JB_ERR_MEMORY;
661 /* Update the iob pointers */
662 iob->cur = p + offset;
667 /* copy the new data into the iob buffer */
668 memcpy(iob->eod, buf, (size_t)n);
670 /* point to the end of the data */
673 /* null terminate == cheap insurance */
681 /*********************************************************************
683 * Function : get_header
685 * Description : This (odd) routine will parse the csp->iob
688 * 1 : csp = Current client state (buffers, headers, etc...)
690 * Returns : Any one of the following:
692 * 1) a pointer to a dynamically allocated string that contains a header line
693 * 2) NULL indicating that the end of the header was reached
694 * 3) "" indicating that the end of the iob was reached before finding
695 * a complete header line.
697 *********************************************************************/
698 char *get_header(struct client_state *csp)
704 if ((iob->cur == NULL)
705 || ((p = strchr(iob->cur, '\n')) == NULL))
707 return(""); /* couldn't find a complete header */
712 ret = strdup(iob->cur);
715 /* FIXME No way to handle error properly */
716 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
721 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
723 /* is this a blank line (i.e. the end of the header) ? */
735 /*********************************************************************
737 * Function : get_header_value
739 * Description : Get the value of a given header from a chained list
740 * of header lines or return NULL if no such header is
741 * present in the list.
744 * 1 : header_list = pointer to list
745 * 2 : header_name = string with name of header to look for.
746 * Trailing colon required, capitalization
749 * Returns : NULL if not found, else value of header
751 *********************************************************************/
752 char *get_header_value(const struct list *header_list, const char *header_name)
754 struct list_entry *cur_entry;
760 length = strlen(header_name);
762 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
766 if (!strncmpic(cur_entry->str, header_name, length))
769 * Found: return pointer to start of value
771 ret = (char *) (cur_entry->str + length);
772 while (*ret && ijb_isspace(*ret)) ret++;
785 /*********************************************************************
789 * Description : add, delete or modify lines in the HTTP header streams.
790 * On entry, it receives a linked list of headers space
791 * that was allocated dynamically (both the list nodes
792 * and the header contents).
794 * As a side effect it frees the space used by the original
798 * 1 : pats = list of patterns to match against headers
799 * 2 : more_headers = list of functions to add more
800 * headers (client or server)
801 * 3 : csp = Current client state (buffers, headers, etc...)
803 * Returns : Single pointer to a fully formed header, or NULL
804 * on out-of-memory error.
806 *********************************************************************/
807 char *sed(const struct parsers pats[],
808 const add_header_func_ptr more_headers[],
809 struct client_state *csp)
811 struct list_entry *p;
812 const struct parsers *v;
813 const add_header_func_ptr *f;
814 jb_err err = JB_ERR_OK;
818 * If filtering is enabled, sed is run twice,
819 * but most of the work needs to be done only once.
821 first_run = (more_headers != NULL ) ? 1 : 0;
823 if (first_run) /* Parse and print */
825 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
827 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
829 /* Header crunch()ed in previous run? -> ignore */
830 if (p->str == NULL) continue;
832 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
834 /* Does the current parser handle this header? */
835 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
837 err = v->parser(csp, (char **)&(p->str));
841 /* place any additional headers on the csp->headers list */
842 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
847 else /* Parse only */
850 * The second run is only needed if the body was modified
851 * and the content-lenght has changed.
853 if (strncmpic(csp->http->cmd, "HEAD", 4))
855 /*XXX: Code duplication*/
856 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
858 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
860 /* Header crunch()ed in previous run? -> ignore */
861 if (p->str == NULL) continue;
863 /* Does the current parser handle this header? */
864 if (strncmpic(p->str, v->str, v->len) == 0)
866 err = v->parser(csp, (char **)&(p->str));
873 if (err != JB_ERR_OK)
878 return list_to_text(csp->headers);
882 /* here begins the family of parser functions that reformat header lines */
884 /*********************************************************************
886 * Function : filter_server_header
888 * Description : Checks if server header filtering is enabled.
889 * If it is, filter_header is called to do the work.
892 * 1 : csp = Current client state (buffers, headers, etc...)
893 * 2 : header = On input, pointer to header to modify.
894 * On output, pointer to the modified header, or NULL
895 * to remove the header. This function frees the
896 * original string if necessary.
898 * Returns : JB_ERR_OK on success and always succeeds
900 *********************************************************************/
901 jb_err filter_server_header(struct client_state *csp, char **header)
903 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
905 filter_header(csp, header);
910 /*********************************************************************
912 * Function : filter_client_header
914 * Description : Checks if client header filtering is enabled.
915 * If it is, filter_header is called to do the work.
918 * 1 : csp = Current client state (buffers, headers, etc...)
919 * 2 : header = On input, pointer to header to modify.
920 * On output, pointer to the modified header, or NULL
921 * to remove the header. This function frees the
922 * original string if necessary.
924 * Returns : JB_ERR_OK on success and always succeeds
926 *********************************************************************/
927 jb_err filter_client_header(struct client_state *csp, char **header)
929 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
931 filter_header(csp, header);
936 /*********************************************************************
938 * Function : filter_header
940 * Description : Executes all text substitutions from all applying
941 * +filter actions on the header.
942 * Most of the code was copied from pcrs_filter_response,
943 * including the rather short variable names
946 * 1 : csp = Current client state (buffers, headers, etc...)
947 * 2 : header = On input, pointer to header to modify.
948 * On output, pointer to the modified header, or NULL
949 * to remove the header. This function frees the
950 * original string if necessary.
952 * Returns : JB_ERR_OK on success and always succeeds
954 *********************************************************************/
955 jb_err filter_header(struct client_state *csp, char **header)
959 size_t size = strlen(*header);
961 char *newheader = NULL;
964 struct file_list *fl;
965 struct re_filterfile_spec *b;
966 struct list_entry *filtername;
968 int i, found_filters = 0;
971 # define MAX_AF_FILES 1
972 # define INDEX_OR_NOT
974 # define INDEX_OR_NOT [i]
977 log_error(LOG_LEVEL_RE_FILTER, "Entered filter_headers");
979 * Need to check the set of re_filterfiles...
981 for (i = 0; i < MAX_AF_FILES; i++)
983 fl = csp->rlist INDEX_OR_NOT;
994 if (0 == found_filters)
996 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1000 for (i = 0; i < MAX_AF_FILES; i++)
1002 fl = csp->rlist INDEX_OR_NOT;
1003 if ((NULL == fl) || (NULL == fl->f))
1006 * For all applying +filter actions, look if a filter by that
1007 * name exists and if yes, execute it's pcrs_joblist on the
1010 for (b = fl->f; b; b = b->next)
1012 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1013 filtername ; filtername = filtername->next)
1015 if (strcmp(b->name, filtername->str) == 0)
1017 int current_hits = 0;
1019 if ( NULL == b->joblist )
1021 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1025 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1026 *header, size, b->name);
1028 /* Apply all jobs from the joblist */
1029 for (job = b->joblist; NULL != job; job = job->next)
1031 matches = pcrs_execute(job, *header, size, &newheader, &size);
1034 current_hits += matches;
1035 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1037 *header = newheader;
1039 else if ( 0 == matches )
1041 /* Filter doesn't change header */
1047 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1048 *header, b->name, pcrs_strerror(matches));
1049 if( newheader != NULL)
1051 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1056 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1057 hits += current_hits;
1065 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1068 log_error(LOG_LEVEL_RE_FILTER, "Leaving filter headers");
1074 /*********************************************************************
1076 * Function : crumble
1078 * Description : This is called if a header matches a pattern to "crunch"
1081 * 1 : csp = Current client state (buffers, headers, etc...)
1082 * 2 : header = On input, pointer to header to modify.
1083 * On output, pointer to the modified header, or NULL
1084 * to remove the header. This function frees the
1085 * original string if necessary.
1087 * Returns : JB_ERR_OK on success, or
1088 * JB_ERR_MEMORY on out-of-memory error.
1090 *********************************************************************/
1091 jb_err crumble(struct client_state *csp, char **header)
1093 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1098 /*********************************************************************
1100 * Function : crunch_server_header
1102 * Description : Crunch server header if it matches a string supplied by the
1103 * user. Called from `sed'.
1106 * 1 : csp = Current client state (buffers, headers, etc...)
1107 * 2 : header = On input, pointer to header to modify.
1108 * On output, pointer to the modified header, or NULL
1109 * to remove the header. This function frees the
1110 * original string if necessary.
1112 * Returns : JB_ERR_OK on success and always succeeds
1114 *********************************************************************/
1115 jb_err crunch_server_header(struct client_state *csp, char **header)
1117 const char *crunch_pattern;
1118 /*Is there a header to crunch*/
1120 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1122 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1124 /*Is the current header the lucky one?*/
1125 if (strstr(*header, crunch_pattern))
1127 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1134 /*********************************************************************
1136 * Function : server_content_type
1138 * Description : Set the content-type for filterable types (text/.*,
1139 * javascript and image/gif) unless filtering has been
1140 * forbidden (CT_TABOO) while parsing earlier headers.
1141 * NOTE: Since text/plain is commonly used by web servers
1142 * for files whose correct type is unknown, we don't
1143 * set CT_TEXT for it.
1146 * 1 : csp = Current client state (buffers, headers, etc...)
1147 * 2 : header = On input, pointer to header to modify.
1148 * On output, pointer to the modified header, or NULL
1149 * to remove the header. This function frees the
1150 * original string if necessary.
1152 * Returns : JB_ERR_OK on success, or
1153 * JB_ERR_MEMORY on out-of-memory error.
1155 *********************************************************************/
1156 jb_err server_content_type(struct client_state *csp, char **header)
1160 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1162 if (csp->content_type != CT_TABOO)
1164 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1165 || strstr(*header, "xml")
1166 || strstr(*header, "application/x-javascript"))
1167 csp->content_type = CT_TEXT;
1168 else if (strstr(*header, " image/gif"))
1169 csp->content_type = CT_GIF;
1170 else if (strstr(*header, " image/jpeg"))
1171 csp->content_type = CT_JPEG;
1173 csp->content_type = 0;
1176 * Are we enabling text mode by force?
1178 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1181 * Do we really have to?
1183 if (csp->content_type == CT_TEXT)
1185 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1189 csp->content_type = CT_TEXT;
1190 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1194 * Are we messing with the content type?
1196 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1199 * Make sure the user doesn't accidently
1200 * change the content type of binary documents.
1202 if (csp->content_type == CT_TEXT)
1205 *header = strdup("Content-Type: ");
1206 string_append(header, newval);
1210 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1211 return JB_ERR_MEMORY;
1213 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1217 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1218 "Enable force-text-mode if you know what you're doing.", *header);
1225 /*********************************************************************
1227 * Function : server_transfer_coding
1229 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1230 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1231 * - Change from "chunked" to "identity" if body was chunked
1232 * but has been de-chunked for filtering.
1235 * 1 : csp = Current client state (buffers, headers, etc...)
1236 * 2 : header = On input, pointer to header to modify.
1237 * On output, pointer to the modified header, or NULL
1238 * to remove the header. This function frees the
1239 * original string if necessary.
1241 * Returns : JB_ERR_OK on success, or
1242 * JB_ERR_MEMORY on out-of-memory error.
1244 *********************************************************************/
1245 jb_err server_transfer_coding(struct client_state *csp, char **header)
1248 * Turn off pcrs and gif filtering if body compressed
1250 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1252 csp->content_type = CT_TABOO;
1256 * Raise flag if body chunked
1258 if (strstr(*header, "chunked"))
1260 csp->flags |= CSP_FLAG_CHUNKED;
1263 * If the body was modified, it has been
1264 * de-chunked first, so adjust the header:
1266 if (csp->flags & CSP_FLAG_MODIFIED)
1269 *header = strdup("Transfer-Encoding: identity");
1270 log_error(LOG_LEVEL_HEADER, "Set: %s", *header);
1271 return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1279 /*********************************************************************
1281 * Function : server_content_encoding
1283 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1286 * 1 : csp = Current client state (buffers, headers, etc...)
1287 * 2 : header = On input, pointer to header to modify.
1288 * On output, pointer to the modified header, or NULL
1289 * to remove the header. This function frees the
1290 * original string if necessary.
1292 * Returns : JB_ERR_OK on success, or
1293 * JB_ERR_MEMORY on out-of-memory error.
1295 *********************************************************************/
1296 jb_err server_content_encoding(struct client_state *csp, char **header)
1299 * Turn off pcrs and gif filtering if body compressed
1301 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1303 csp->content_type = CT_TABOO;
1311 /*********************************************************************
1313 * Function : server_content_length
1315 * Description : Adjust Content-Length header if we modified
1319 * 1 : csp = Current client state (buffers, headers, etc...)
1320 * 2 : header = On input, pointer to header to modify.
1321 * On output, pointer to the modified header, or NULL
1322 * to remove the header. This function frees the
1323 * original string if necessary.
1325 * Returns : JB_ERR_OK on success, or
1326 * JB_ERR_MEMORY on out-of-memory error.
1328 *********************************************************************/
1329 jb_err server_content_length(struct client_state *csp, char **header)
1331 if (csp->content_length != 0) /* Content length could have been modified */
1334 * XXX: Shouldn't we check if csp->content_length
1335 * is different than the original value?
1338 *header = (char *) zalloc(100);
1339 if (*header == NULL)
1341 return JB_ERR_MEMORY;
1344 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1346 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1353 /*********************************************************************
1355 * Function : server_content_md5
1357 * Description : Crumble any Content-MD5 headers if the document was
1358 * modified. FIXME: Should we re-compute instead?
1361 * 1 : csp = Current client state (buffers, headers, etc...)
1362 * 2 : header = On input, pointer to header to modify.
1363 * On output, pointer to the modified header, or NULL
1364 * to remove the header. This function frees the
1365 * original string if necessary.
1367 * Returns : JB_ERR_OK on success, or
1368 * JB_ERR_MEMORY on out-of-memory error.
1370 *********************************************************************/
1371 jb_err server_content_md5(struct client_state *csp, char **header)
1373 if (csp->flags & CSP_FLAG_MODIFIED)
1375 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1382 /*********************************************************************
1384 * Function : server_content_disposition
1386 * Description : If enabled, blocks or modifies the "content-disposition" header.
1387 * Called from `sed'.
1390 * 1 : csp = Current client state (buffers, headers, etc...)
1391 * 2 : header = On input, pointer to header to modify.
1392 * On output, pointer to the modified header, or NULL
1393 * to remove the header. This function frees the
1394 * original string if necessary.
1396 * Returns : JB_ERR_OK on success, or
1397 * JB_ERR_MEMORY on out-of-memory error.
1399 *********************************************************************/
1400 jb_err server_content_disposition(struct client_state *csp, char **header)
1405 * Are we messing with the content-disposition header?
1407 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1413 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1415 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1418 * Blocking content-disposition header
1420 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1427 * Replacing content-disposition header
1430 *header = strdup("content-disposition: ");
1431 string_append(header, newval);
1433 if (*header == NULL)
1435 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1439 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1442 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1445 /*********************************************************************
1447 * Function : server_last_modified
1449 * Description : Changes Last-Modified header to the actual date
1450 * to help hide-if-modified-since.
1451 * Called from `sed'.
1454 * 1 : csp = Current client state (buffers, headers, etc...)
1455 * 2 : header = On input, pointer to header to modify.
1456 * On output, pointer to the modified header, or NULL
1457 * to remove the header. This function frees the
1458 * original string if necessary.
1460 * Returns : JB_ERR_OK on success, or
1461 * JB_ERR_MEMORY on out-of-memory error.
1463 *********************************************************************/
1464 jb_err server_last_modified(struct client_state *csp, char **header)
1467 char buf[BUFFER_SIZE];
1470 struct tm *timeptr = NULL;
1471 time_t now, last_modified;
1473 long int days, hours, minutes, seconds;
1476 * Are we messing with the Last-Modified header?
1478 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1484 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1486 if (0 == strcmpic(newval, "block") )
1489 * Blocking Last-Modified header. Useless but why not.
1491 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1495 else if (0 == strcmpic(newval, "reset-to-request-time"))
1498 * Setting Last-Modified Header to now.
1500 get_http_time(0, buf);
1502 *header = strdup("Last-Modified: ");
1503 string_append(header, buf);
1505 if (*header == NULL)
1507 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1511 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1514 else if (0 == strcmpic(newval, "randomize"))
1516 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1518 timeptr = gmtime(&now);
1519 if ( (last_modified = parse_header_time(*header, timeptr)) < 0 )
1521 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1526 rtime = difftime(now, last_modified);
1529 #if !defined(_WIN32) && !defined(__OS2__)
1530 rtime = random() % rtime + 1;
1532 rtime = rand() % rtime + 1;
1533 #endif /* (ifndef _WIN32 || __OS2__) */
1534 last_modified += rtime;
1535 timeptr = localtime(&last_modified);
1536 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1538 *header = strdup("Last-Modified: ");
1539 string_append(header, newheader);
1541 if (*header == NULL)
1543 log_error(LOG_LEVEL_ERROR, " Insufficent memory, header crunched without replacement.");
1544 return JB_ERR_MEMORY;
1547 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1549 days = rtime / (3600 * 24);
1550 hours = rtime / 3600 % 24;
1551 minutes = rtime / 60 % 60;
1552 seconds = rtime % 60;
1554 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1555 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1556 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1561 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1569 /*********************************************************************
1571 * Function : client_accept_encoding
1573 * Description : Rewrite the client's Accept-Encoding header so that
1574 * if doesn't allow compression, if the action applies.
1575 * Note: For HTTP/1.0 the absence of the header is enough.
1578 * 1 : csp = Current client state (buffers, headers, etc...)
1579 * 2 : header = On input, pointer to header to modify.
1580 * On output, pointer to the modified header, or NULL
1581 * to remove the header. This function frees the
1582 * original string if necessary.
1584 * Returns : JB_ERR_OK on success, or
1585 * JB_ERR_MEMORY on out-of-memory error.
1587 *********************************************************************/
1588 jb_err client_accept_encoding(struct client_state *csp, char **header)
1590 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1592 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1596 /* Temporarily disable the correct behaviour to
1597 * work around a PHP bug.
1599 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1601 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1602 * if (*header == NULL)
1604 * return JB_ERR_MEMORY;
1615 /*********************************************************************
1617 * Function : client_te
1619 * Description : Rewrite the client's TE header so that
1620 * if doesn't allow compression, if the action applies.
1623 * 1 : csp = Current client state (buffers, headers, etc...)
1624 * 2 : header = On input, pointer to header to modify.
1625 * On output, pointer to the modified header, or NULL
1626 * to remove the header. This function frees the
1627 * original string if necessary.
1629 * Returns : JB_ERR_OK on success, or
1630 * JB_ERR_MEMORY on out-of-memory error.
1632 *********************************************************************/
1633 jb_err client_te(struct client_state *csp, char **header)
1635 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1638 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1644 /*********************************************************************
1646 * Function : client_referrer
1648 * Description : Handle the "referer" config setting properly.
1649 * Called from `sed'.
1652 * 1 : csp = Current client state (buffers, headers, etc...)
1653 * 2 : header = On input, pointer to header to modify.
1654 * On output, pointer to the modified header, or NULL
1655 * to remove the header. This function frees the
1656 * original string if necessary.
1658 * Returns : JB_ERR_OK on success, or
1659 * JB_ERR_MEMORY on out-of-memory error.
1661 *********************************************************************/
1662 jb_err client_referrer(struct client_state *csp, char **header)
1669 #ifdef FEATURE_FORCE_LOAD
1670 /* Since the referrer can include the prefix even
1671 * if the request itself is non-forced, we must
1672 * clean it unconditionally
1674 strclean(*header, FORCE_PREFIX);
1675 #endif /* def FEATURE_FORCE_LOAD */
1678 * Are we sending referer?
1680 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1685 newval = csp->action->string[ACTION_STRING_REFERER];
1687 if ((0 != strcmpic(newval, "conditional-block")))
1691 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1696 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1699 else if (0 == strcmpic(newval, "conditional-block"))
1702 * Block referer if host has changed.
1705 if (NULL == (host = strdup(csp->http->hostport)))
1708 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1709 return JB_ERR_MEMORY;
1711 if (NULL == (referer = strdup(*header)))
1715 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1716 return JB_ERR_MEMORY;
1718 hostlenght = strlen(host);
1719 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1721 /*Shorten referer to make sure the referer is blocked
1722 *if www.example.org/www.example.com-shall-see-the-referer/
1723 *links to www.example.com/
1725 referer[hostlenght+17] = '\n';
1727 if ( 0 == strstr(referer, host)) /*Host has changed*/
1729 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1734 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1740 else if (0 != strcmpic(newval, "forge"))
1743 * We have a specific (fixed) referer we want to send.
1745 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1747 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1749 *header = strdup("Referer: ");
1750 string_append(header, newval);
1751 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1753 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1758 * Forge a referer as http://[hostname:port of REQUEST]/
1759 * to fool stupid checks for in-site links
1762 *header = strdup("Referer: http://");
1763 string_append(header, csp->http->hostport);
1764 string_append(header, "/");
1765 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1767 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1771 /*********************************************************************
1773 * Function : client_accept_language
1775 * Description : Handle the "Accept-Language" config setting properly.
1776 * Called from `sed'.
1779 * 1 : csp = Current client state (buffers, headers, etc...)
1780 * 2 : header = On input, pointer to header to modify.
1781 * On output, pointer to the modified header, or NULL
1782 * to remove the header. This function frees the
1783 * original string if necessary.
1785 * Returns : JB_ERR_OK on success, or
1786 * JB_ERR_MEMORY on out-of-memory error.
1788 *********************************************************************/
1789 jb_err client_accept_language(struct client_state *csp, char **header)
1794 * Are we messing with the Accept-Language?
1796 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1798 /*I don't think so*/
1802 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1804 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1807 * Blocking Accept-Language header
1809 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1816 * Replacing Accept-Language header
1819 *header = strdup("Accept-Language: ");
1820 string_append(header, newval);
1822 if (*header == NULL)
1824 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1828 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1831 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1834 /*********************************************************************
1836 * Function : crunch_client_header
1838 * Description : Crunch client header if it matches a string supplied by the
1839 * user. Called from `sed'.
1842 * 1 : csp = Current client state (buffers, headers, etc...)
1843 * 2 : header = On input, pointer to header to modify.
1844 * On output, pointer to the modified header, or NULL
1845 * to remove the header. This function frees the
1846 * original string if necessary.
1848 * Returns : JB_ERR_OK on success and always succeeds
1850 *********************************************************************/
1851 jb_err crunch_client_header(struct client_state *csp, char **header)
1853 const char *crunch_pattern;
1854 /*Is there a header to crunch*/
1856 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1858 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1860 /*Is the current header the lucky one?*/
1861 if (strstr(*header, crunch_pattern))
1863 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1871 /*********************************************************************
1873 * Function : client_uagent
1875 * Description : Handle the "user-agent" config setting properly
1876 * and remember its original value to enable browser
1877 * bug workarounds. Called from `sed'.
1880 * 1 : csp = Current client state (buffers, headers, etc...)
1881 * 2 : header = On input, pointer to header to modify.
1882 * On output, pointer to the modified header, or NULL
1883 * to remove the header. This function frees the
1884 * original string if necessary.
1886 * Returns : JB_ERR_OK on success, or
1887 * JB_ERR_MEMORY on out-of-memory error.
1889 *********************************************************************/
1890 jb_err client_uagent(struct client_state *csp, char **header)
1894 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1899 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1906 *header = strdup("User-Agent: ");
1907 string_append(header, newval);
1909 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
1911 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1914 /*********************************************************************
1916 * Function : client_ua
1918 * Description : Handle "ua-" headers properly. Called from `sed'.
1921 * 1 : csp = Current client state (buffers, headers, etc...)
1922 * 2 : header = On input, pointer to header to modify.
1923 * On output, pointer to the modified header, or NULL
1924 * to remove the header. This function frees the
1925 * original string if necessary.
1927 * Returns : JB_ERR_OK on success, or
1928 * JB_ERR_MEMORY on out-of-memory error.
1930 *********************************************************************/
1931 jb_err client_ua(struct client_state *csp, char **header)
1933 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1935 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
1943 /*********************************************************************
1945 * Function : client_from
1947 * Description : Handle the "from" config setting properly.
1948 * Called from `sed'.
1951 * 1 : csp = Current client state (buffers, headers, etc...)
1952 * 2 : header = On input, pointer to header to modify.
1953 * On output, pointer to the modified header, or NULL
1954 * to remove the header. This function frees the
1955 * original string if necessary.
1957 * Returns : JB_ERR_OK on success, or
1958 * JB_ERR_MEMORY on out-of-memory error.
1960 *********************************************************************/
1961 jb_err client_from(struct client_state *csp, char **header)
1965 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1972 newval = csp->action->string[ACTION_STRING_FROM];
1975 * Are we blocking the e-mail address?
1977 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1979 log_error(LOG_LEVEL_HEADER, "crunched From!");
1983 log_error(LOG_LEVEL_HEADER, " modified");
1985 *header = strdup("From: ");
1986 string_append(header, newval);
1988 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1992 /*********************************************************************
1994 * Function : client_send_cookie
1996 * Description : Handle the "cookie" header properly. Called from `sed'.
1997 * If cookie is accepted, add it to the cookie_list,
1998 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2001 * 1 : csp = Current client state (buffers, headers, etc...)
2002 * 2 : header = On input, pointer to header to modify.
2003 * On output, pointer to the modified header, or NULL
2004 * to remove the header. This function frees the
2005 * original string if necessary.
2007 * Returns : JB_ERR_OK on success, or
2008 * JB_ERR_MEMORY on out-of-memory error.
2010 *********************************************************************/
2011 jb_err client_send_cookie(struct client_state *csp, char **header)
2013 jb_err result = JB_ERR_OK;
2015 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2017 /* strlen("cookie: ") == 8 */
2018 result = enlist(csp->cookie_list, *header + 8);
2022 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2026 * Always remove the cookie here. The cookie header
2027 * will be sent at the end of the header.
2035 /*********************************************************************
2037 * Function : client_x_forwarded
2039 * Description : Handle the "x-forwarded-for" config setting properly,
2040 * also used in the add_client_headers list. Called from `sed'.
2043 * 1 : csp = Current client state (buffers, headers, etc...)
2044 * 2 : header = On input, pointer to header to modify.
2045 * On output, pointer to the modified header, or NULL
2046 * to remove the header. This function frees the
2047 * original string if necessary.
2049 * Returns : JB_ERR_OK on success, or
2050 * JB_ERR_MEMORY on out-of-memory error.
2052 *********************************************************************/
2053 jb_err client_x_forwarded(struct client_state *csp, char **header)
2055 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2057 /* Save it so we can re-add it later */
2058 freez(csp->x_forwarded);
2059 csp->x_forwarded = *header;
2062 * Always set *header = NULL, since this information
2063 * will be sent at the end of the header.
2070 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2077 /*********************************************************************
2079 * Function : client_max_forwards
2081 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2082 * from the value of the Max-Forwards header field.
2085 * 1 : csp = Current client state (buffers, headers, etc...)
2086 * 2 : header = On input, pointer to header to modify.
2087 * On output, pointer to the modified header, or NULL
2088 * to remove the header. This function frees the
2089 * original string if necessary.
2091 * Returns : JB_ERR_OK on success, or
2092 * JB_ERR_MEMORY on out-of-memory error.
2094 *********************************************************************/
2095 jb_err client_max_forwards(struct client_state *csp, char **header)
2097 unsigned int max_forwards;
2099 if ((0 == strcmpic(csp->http->gpc, "trace"))
2100 || (0 == strcmpic(csp->http->gpc, "options")))
2102 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2104 if (max_forwards-- >= 1)
2106 sprintf(*header, "Max-Forwards: %u", max_forwards);
2107 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2111 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2120 /*********************************************************************
2122 * Function : client_host
2124 * Description : If the request URI did not contain host and
2125 * port information, parse and evaluate the Host
2128 * Also, kill ill-formed HOST: headers as sent by
2129 * Apple's iTunes software when used with a proxy.
2132 * 1 : csp = Current client state (buffers, headers, etc...)
2133 * 2 : header = On input, pointer to header to modify.
2134 * On output, pointer to the modified header, or NULL
2135 * to remove the header. This function frees the
2136 * original string if necessary.
2138 * Returns : JB_ERR_OK on success, or
2139 * JB_ERR_MEMORY on out-of-memory error.
2141 *********************************************************************/
2142 jb_err client_host(struct client_state *csp, char **header)
2147 * If the header field name is all upper-case, chances are that it's
2148 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2149 * not a problem -- they are regenerated later.
2151 if ((*header)[1] == 'O')
2153 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2158 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2159 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2162 if (NULL == (p = strdup((*header)+6)))
2164 return JB_ERR_MEMORY;
2167 if (NULL == (q = strdup(p)))
2170 return JB_ERR_MEMORY;
2173 freez(csp->http->hostport);
2174 csp->http->hostport = p;
2175 freez(csp->http->host);
2176 csp->http->host = q;
2177 q = strchr(csp->http->host, ':');
2180 /* Terminate hostname and evaluate port string */
2182 csp->http->port = atoi(q);
2186 csp->http->port = csp->http->ssl ? 443 : 80;
2189 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2190 csp->http->hostport, csp->http->host, csp->http->port);
2196 /*********************************************************************
2198 * Function : client_if_modified_since
2200 * Description : Remove or modify the If-Modified-Since header.
2203 * 1 : csp = Current client state (buffers, headers, etc...)
2204 * 2 : header = On input, pointer to header to modify.
2205 * On output, pointer to the modified header, or NULL
2206 * to remove the header. This function frees the
2207 * original string if necessary.
2209 * Returns : JB_ERR_OK on success, or
2210 * JB_ERR_MEMORY on out-of-memory error.
2212 *********************************************************************/
2213 jb_err client_if_modified_since(struct client_state *csp, char **header)
2216 struct tm *timeptr = NULL;
2220 time_t hours, minutes, seconds;
2224 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2227 * The client got an error message because of a temporary problem,
2228 * the problem is gone and the client now tries to revalidate our
2229 * error message on the real server. The revalidation would always
2230 * end with the transmission of the whole document and there is
2231 * no need to expose the bogus If-Modified-Since header.
2233 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2236 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2238 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2240 if ((0 == strcmpic(newval, "block")))
2242 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2245 else /* add random value */
2247 if ( (tm = parse_header_time(*header, timeptr)) < 0 )
2249 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2254 rtime = (time_t) strtol(newval, &endptr, 0);
2257 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d hou%s)",
2258 *header, rtime, (rtime == 1 || rtime == -1) ? "r": "rs");
2260 #if !defined(_WIN32) && !defined(__OS2__)
2261 rtime = random() % rtime + 1;
2263 rtime = rand() % rtime + 1;
2264 #endif /* (_WIN32 || __OS2__) */
2265 if(newval[0] == '-')
2272 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2276 timeptr = localtime(&tm);
2277 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2280 *header = strdup("If-Modified-Since: ");
2281 string_append(header, newheader);
2283 if (*header == NULL)
2285 log_error(LOG_LEVEL_HEADER, " Insufficent memory, header crunched without replacement.");
2286 return JB_ERR_MEMORY;
2289 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2296 hours = rtime / 3600 % 24;
2297 minutes = rtime / 60 % 60;
2298 seconds = rtime % 60;
2300 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2301 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2302 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2311 /*********************************************************************
2313 * Function : client_if_none_match
2315 * Description : Remove the If-None-Match header.
2318 * 1 : csp = Current client state (buffers, headers, etc...)
2319 * 2 : header = On input, pointer to header to modify.
2320 * On output, pointer to the modified header, or NULL
2321 * to remove the header. This function frees the
2322 * original string if necessary.
2324 * Returns : JB_ERR_OK on success, or
2325 * JB_ERR_MEMORY on out-of-memory error.
2327 *********************************************************************/
2328 jb_err client_if_none_match(struct client_state *csp, char **header)
2330 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2332 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2339 /*********************************************************************
2341 * Function : client_x_filter
2343 * Description : Disables filtering if the client set "X-Filter: No".
2344 * Called from `sed'.
2347 * 1 : csp = Current client state (buffers, headers, etc...)
2348 * 2 : header = On input, pointer to header to modify.
2349 * On output, pointer to the modified header, or NULL
2350 * to remove the header. This function frees the
2351 * original string if necessary.
2353 * Returns : JB_ERR_OK on success
2355 *********************************************************************/
2356 jb_err client_x_filter(struct client_state *csp, char **header)
2358 if ( 0 == strcmpic(*header, "X-Filter: No"))
2360 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2362 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to disable filtering!");
2366 csp->content_type = CT_TABOO;
2367 log_error(LOG_LEVEL_HEADER, "Disabled filter mode on behalf of the client.");
2369 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2375 /* the following functions add headers directly to the header list */
2377 /*********************************************************************
2379 * Function : client_host_adder
2381 * Description : Adds the Host: header field if it is missing.
2382 * Called from `sed'.
2385 * 1 : csp = Current client state (buffers, headers, etc...)
2387 * Returns : JB_ERR_OK on success, or
2388 * JB_ERR_MEMORY on out-of-memory error.
2390 *********************************************************************/
2391 jb_err client_host_adder(struct client_state *csp)
2396 if ( !csp->http->hostport || !*(csp->http->hostport))
2402 * remove 'user:pass@' from 'proto://user:pass@host'
2404 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2410 p = csp->http->hostport;
2413 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2414 err = enlist_unique_header(csp->headers, "Host", p);
2420 /*********************************************************************
2422 * Function : client_cookie_adder
2424 * Description : Used in the add_client_headers list. Called from `sed'.
2427 * 1 : csp = Current client state (buffers, headers, etc...)
2429 * Returns : JB_ERR_OK on success, or
2430 * JB_ERR_MEMORY on out-of-memory error.
2432 *********************************************************************/
2433 jb_err client_cookie_adder(struct client_state *csp)
2435 struct list_entry *lst;
2437 struct list_entry *list1 = csp->cookie_list->first;
2438 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2439 int first_cookie = 1;
2442 if ((list1 == NULL) && (list2 == NULL))
2448 tmp = strdup("Cookie: ");
2450 for (lst = list1; lst ; lst = lst->next)
2458 string_append(&tmp, "; ");
2460 string_append(&tmp, lst->str);
2463 for (lst = list2; lst ; lst = lst->next)
2471 string_append(&tmp, "; ");
2473 string_join(&tmp, cookie_encode(lst->str));
2478 return JB_ERR_MEMORY;
2481 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2482 err = enlist(csp->headers, tmp);
2488 /*********************************************************************
2490 * Function : client_accept_encoding_adder
2492 * Description : Add an Accept-Encoding header to the client's request
2493 * that disables compression if the action applies, and
2494 * the header is not already there. Called from `sed'.
2495 * Note: For HTTP/1.0, the absence of the header is enough.
2498 * 1 : csp = Current client state (buffers, headers, etc...)
2500 * Returns : JB_ERR_OK on success, or
2501 * JB_ERR_MEMORY on out-of-memory error.
2503 *********************************************************************/
2504 jb_err client_accept_encoding_adder(struct client_state *csp)
2506 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2507 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2509 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2516 /*********************************************************************
2518 * Function : client_xtra_adder
2520 * Description : Used in the add_client_headers list. Called from `sed'.
2523 * 1 : csp = Current client state (buffers, headers, etc...)
2525 * Returns : JB_ERR_OK on success, or
2526 * JB_ERR_MEMORY on out-of-memory error.
2528 *********************************************************************/
2529 jb_err client_xtra_adder(struct client_state *csp)
2531 struct list_entry *lst;
2534 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2535 lst ; lst = lst->next)
2537 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2538 err = enlist(csp->headers, lst->str);
2550 /*********************************************************************
2552 * Function : client_x_forwarded_adder
2554 * Description : Used in the add_client_headers list. Called from `sed'.
2557 * 1 : csp = Current client state (buffers, headers, etc...)
2559 * Returns : JB_ERR_OK on success, or
2560 * JB_ERR_MEMORY on out-of-memory error.
2562 *********************************************************************/
2563 jb_err client_x_forwarded_adder(struct client_state *csp)
2568 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2573 if (csp->x_forwarded)
2575 p = strdup(csp->x_forwarded);
2576 string_append(&p, ", ");
2580 p = strdup("X-Forwarded-For: ");
2582 string_append(&p, csp->ip_addr_str);
2586 return JB_ERR_MEMORY;
2589 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2590 err = enlist(csp->headers, p);
2597 /*********************************************************************
2599 * Function : connection_close_adder
2601 * Description : Adds a "Connection: close" header to csp->headers
2602 * as a temporary fix for the needed but missing HTTP/1.1
2603 * support. Called from `sed'.
2604 * FIXME: This whole function shouldn't be neccessary!
2607 * 1 : csp = Current client state (buffers, headers, etc...)
2609 * Returns : JB_ERR_OK on success, or
2610 * JB_ERR_MEMORY on out-of-memory error.
2612 *********************************************************************/
2613 jb_err connection_close_adder(struct client_state *csp)
2615 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2616 return enlist(csp->headers, "Connection: close");
2620 /*********************************************************************
2622 * Function : server_http
2624 * Description : - Save the HTTP Status into csp->http->status
2625 * - Set CT_TABOO to prevent filtering if the answer
2626 * is a partial range (HTTP status 206)
2627 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2631 * 1 : csp = Current client state (buffers, headers, etc...)
2632 * 2 : header = On input, pointer to header to modify.
2633 * On output, pointer to the modified header, or NULL
2634 * to remove the header. This function frees the
2635 * original string if necessary.
2637 * Returns : JB_ERR_OK on success, or
2638 * JB_ERR_MEMORY on out-of-memory error.
2640 *********************************************************************/
2641 jb_err server_http(struct client_state *csp, char **header)
2643 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2644 if (csp->http->status == 206)
2646 csp->content_type = CT_TABOO;
2649 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2652 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2659 /*********************************************************************
2661 * Function : server_set_cookie
2663 * Description : Handle the server "cookie" header properly.
2664 * Log cookie to the jar file. Then "crunch" it,
2665 * or accept it. Called from `sed'.
2668 * 1 : csp = Current client state (buffers, headers, etc...)
2669 * 2 : header = On input, pointer to header to modify.
2670 * On output, pointer to the modified header, or NULL
2671 * to remove the header. This function frees the
2672 * original string if necessary.
2674 * Returns : JB_ERR_OK on success, or
2675 * JB_ERR_MEMORY on out-of-memory error.
2677 *********************************************************************/
2678 jb_err server_set_cookie(struct client_state *csp, char **header)
2680 #ifdef FEATURE_COOKIE_JAR
2681 if (csp->config->jar)
2684 * Write timestamp into outbuf.
2686 * Complex because not all OSs have tm_gmtoff or
2687 * the %z field in strftime()
2689 char tempbuf[ BUFFER_SIZE ];
2693 #ifdef HAVE_LOCALTIME_R
2694 tm_now = *localtime_r(&now, &tm_now);
2696 pthread_mutex_lock(&localtime_mutex);
2697 tm_now = *localtime (&now);
2698 pthread_mutex_unlock(&localtime_mutex);
2700 tm_now = *localtime (&now);
2702 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2704 /* strlen("set-cookie: ") = 12 */
2705 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2707 #endif /* def FEATURE_COOKIE_JAR */
2709 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2711 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2712 return crumble(csp, header);
2714 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2716 /* Flag whether or not to log a message */
2719 /* A variable to store the tag we're working on */
2722 /* Skip "Set-Cookie:" (11 characters) in header */
2723 cur_tag = *header + 11;
2725 /* skip whitespace between "Set-Cookie:" and value */
2726 while (*cur_tag && ijb_isspace(*cur_tag))
2731 /* Loop through each tag in the cookie */
2735 char *next_tag = strchr(cur_tag, ';');
2736 if (next_tag != NULL)
2738 /* Skip the ';' character itself */
2741 /* skip whitespace ";" and start of tag */
2742 while (*next_tag && ijb_isspace(*next_tag))
2749 /* "Next tag" is the end of the string */
2750 next_tag = cur_tag + strlen(cur_tag);
2753 /* Is this the "Expires" tag? */
2754 if (strncmpic(cur_tag, "expires=", 8) == 0)
2756 /* Delete the tag by copying the rest of the string over it.
2757 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2758 * since the behaviour of strcpy is undefined for overlapping
2761 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2763 /* That changed the header, need to issue a log message */
2766 /* Note that the next tag has now been moved to *cur_tag,
2767 * so we do not need to update the cur_tag pointer.
2772 /* Move on to next cookie tag */
2779 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2787 #ifdef FEATURE_FORCE_LOAD
2788 /*********************************************************************
2790 * Function : strclean
2792 * Description : In-Situ-Eliminate all occurances of substring in
2796 * 1 : string = string to clean
2797 * 2 : substring = substring to eliminate
2799 * Returns : Number of eliminations
2801 *********************************************************************/
2802 int strclean(const char *string, const char *substring)
2804 int hits = 0, len = strlen(substring);
2807 while((pos = strstr(string, substring)) != NULL)
2814 while (*p++ != '\0');
2821 #endif /* def FEATURE_FORCE_LOAD */
2823 /*********************************************************************
2825 * Function : parse_header_time
2827 * Description : Transforms time inside a HTTP header into
2828 * the usual time format.
2831 * 1 : header = header to parse
2832 * 2 : timeptr = storage for the resulting time structure
2834 * Returns : Time in seconds since Unix epoch or -1 for failure.
2836 *********************************************************************/
2837 time_t parse_header_time(char *header, struct tm *timeptr) {
2843 timeptr = localtime(&tm);
2844 /* Skipping header name */
2845 timestring = strstr(header, ": ");
2846 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", timeptr) == NULL)
2850 tm = mktime(timeptr);