1 const char parsers_rcs[] = "$Id: parsers.c,v 1.69 2006/09/06 16:25:51 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.69 2006/09/06 16:25:51 fabiankeil
44 * Always have parse_header_time return a pointer
45 * that actual makes sense, even though we currently
46 * only need it to detect problems.
48 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
49 * Added config option enable-remote-http-toggle
50 * to specify if Privoxy should recognize special
51 * headers (currently only X-Filter) to change its
52 * behaviour. Disabled by default.
54 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
55 * After filtering de-chunked instances, remove
56 * "Transfer-Encoding" header entirely instead of changing
57 * it to "Transfer-Encoding: identity", which is invalid.
58 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
60 * Don't use localtime in parse_header_time. An empty time struct
61 * is good enough, it gets overwritten by strptime anyway.
63 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
64 * Use gmtime_r if available, fallback to gmtime with mutex
65 * protection for MacOSX and use vanilla gmtime for the rest.
67 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
68 * Changed client_referrer to use the right type (size_t) for
69 * hostlenght and to shorten the temporary referrer string with
70 * '\0' instead of adding a useless line break.
72 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
73 * - Back to timegm() using GnuPG's replacement if necessary.
74 * Using mktime() and localtime() could add a on hour offset if
75 * the randomize factor was big enough to lead to a summer/wintertime
78 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
80 * - Moved randomization code into pick_from_range().
82 * - Changed parse_header_time definition.
83 * time_t isn't guaranteed to be signed and
84 * if it isn't, -1 isn't available as error code.
85 * Changed some variable types in client_if_modified_since()
86 * because of the same reason.
88 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
89 * OS/2 compilation compatibility fixups
91 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
92 * Changed include from strptime.c to strptime.h
94 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
95 * Split filter-headers{} into filter-client-headers{}
96 * and filter-server-headers{}.
97 * Added parse_header_time() to share some code.
98 * Replaced timegm() with mktime().
100 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
101 * Windows service integration
103 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
104 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
106 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
107 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
108 * with what was really the latest development (the v_3_0_branch branch)
110 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
111 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
113 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
114 * Add the ability to check jpeg images for invalid
115 * lengths of comment blocks. Defensive strategy
116 * against the exploit:
117 * Microsoft Security Bulletin MS04-028
118 * Buffer Overrun in JPEG Processing (GDI+) Could
119 * Allow Code Execution (833987)
120 * Enabled with +inspect-jpegs in actions files.
122 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
123 * Excluded text/plain objects from filtering. This fixes a
124 * couple of client-crashing, download corruption and
125 * Privoxy performance issues, whose root cause lies in
126 * web servers labelling content of unknown type as text/plain.
128 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
129 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
131 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
132 * Completing the previous change
134 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
135 * Added temporary workaround for bug in PHP < 4.2.3
137 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
138 * 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.
140 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
141 * Fix typo: supressed -> suppressed
143 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
144 * Improved cookie logging
146 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
147 * Added basic support for OPTIONS and TRACE HTTP methods:
148 * - New parser function client_max_forwards which decrements
149 * the Max-Forwards HTTP header field of OPTIONS and TRACE
150 * requests by one before forwarding
151 * - New parser function client_host which extracts the host
152 * and port information from the HTTP header field if the
153 * request URI was not absolute
154 * - Don't crumble and re-add the Host: header, but only generate
155 * and append if missing
157 * Revision 1.56 2002/05/12 15:34:22 jongfoster
158 * Fixing typo in a comment
160 * Revision 1.55 2002/05/08 16:01:07 oes
161 * Optimized add_to_iob:
162 * - Use realloc instead of malloc(), memcpy(), free()
163 * - Expand to powers of two if possible, to get
164 * O(log n) reallocs instead of O(n).
165 * - Moved check for buffer limit here from chat
166 * - Report failure via returncode
168 * Revision 1.54 2002/04/02 15:03:16 oes
169 * Tiny code cosmetics
171 * Revision 1.53 2002/03/26 22:29:55 swa
172 * we have a new homepage!
174 * Revision 1.52 2002/03/24 13:25:43 swa
175 * name change related issues
177 * Revision 1.51 2002/03/13 00:27:05 jongfoster
180 * Revision 1.50 2002/03/12 01:45:35 oes
181 * More verbose logging
183 * Revision 1.49 2002/03/09 20:03:52 jongfoster
184 * - Making various functions return int rather than size_t.
185 * (Undoing a recent change). Since size_t is unsigned on
186 * Windows, functions like read_socket that return -1 on
187 * error cannot return a size_t.
189 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
190 * crashes, and also frequently caused JB to jump to 100%
191 * CPU and stay there. (Because it thought it had just
192 * read ((unsigned)-1) == 4Gb of data...)
194 * - The signature of write_socket has changed, it now simply
195 * returns success=0/failure=nonzero.
197 * - Trying to get rid of a few warnings --with-debug on
198 * Windows, I've introduced a new type "jb_socket". This is
199 * used for the socket file descriptors. On Windows, this
200 * is SOCKET (a typedef for unsigned). Everywhere else, it's
201 * an int. The error value can't be -1 any more, so it's
202 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
203 * Windows it maps to the #define INVALID_SOCKET.)
205 * - The signature of bind_port has changed.
207 * Revision 1.48 2002/03/07 03:46:53 oes
208 * Fixed compiler warnings etc
210 * Revision 1.47 2002/02/20 23:15:13 jongfoster
211 * Parsing functions now handle out-of-memory gracefully by returning
214 * Revision 1.46 2002/01/17 21:03:47 jongfoster
215 * Moving all our URL and URL pattern parsing code to urlmatch.c.
217 * Revision 1.45 2002/01/09 14:33:03 oes
218 * Added support for localtime_r.
220 * Revision 1.44 2001/12/14 01:22:54 steudten
221 * Remove 'user:pass@' from 'proto://user:pass@host' for the
222 * new added header 'Host: ..'. (See Req ID 491818)
224 * Revision 1.43 2001/11/23 00:26:38 jongfoster
225 * Fixing two really stupid errors in my previous commit
227 * Revision 1.42 2001/11/22 21:59:30 jongfoster
228 * Adding code to handle +no-cookies-keep
230 * Revision 1.41 2001/11/05 23:43:05 steudten
231 * Add time+date to log files.
233 * Revision 1.40 2001/10/26 20:13:09 jongfoster
234 * ctype.h is needed in Windows, too.
236 * Revision 1.39 2001/10/26 17:40:04 oes
237 * Introduced get_header_value()
238 * Removed http->user_agent, csp->referrer and csp->accept_types
239 * Removed client_accept()
241 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
242 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
243 * threads to call select() simultaneously. So, it's time to do a real, live,
244 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
245 * (native). Both versions will work, but using __OS2__ offers multi-threading.
247 * Revision 1.37 2001/10/23 21:36:02 jongfoster
248 * Documenting sed()'s error behaviou (doc change only)
250 * Revision 1.36 2001/10/13 12:51:51 joergs
251 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
252 * force-load), instead crumble Host: and add it (again) in client_host_adder
253 * (in case we get a HTTP/1.0 request without Host: header and forward it to
254 * a HTTP/1.1 server/proxy).
256 * Revision 1.35 2001/10/09 22:39:21 jongfoster
257 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
260 * Revision 1.34 2001/10/07 18:50:55 oes
261 * Added server_content_encoding, renamed server_transfer_encoding
263 * Revision 1.33 2001/10/07 18:04:49 oes
264 * Changed server_http11 to server_http and its pattern to "HTTP".
265 * Additional functionality: it now saves the HTTP status into
266 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
268 * Revision 1.32 2001/10/07 15:43:28 oes
269 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
270 * client_te and client_accept_encoding_adder, triggered by the new
271 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
272 * changed to allow only identity and chunked, and the TE header is
273 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
275 * parse_http_request no longer does anything than parsing. The rewriting
276 * of http->cmd and version mangling are gone. It now also recognizes
277 * the put and delete methods and saves the url in http->url. Removed
280 * renamed content_type and content_length to have the server_ prefix
282 * server_content_type now only works if csp->content_type != CT_TABOO
284 * added server_transfer_encoding, which
285 * - Sets CT_TABOO to prohibit filtering if encoding compresses
286 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
287 * - Change from "chunked" to "identity" if body was chunked
288 * but has been de-chunked for filtering.
290 * added server_content_md5 which crunches any Content-MD5 headers
291 * if the body was modified.
293 * made server_http11 conditional on +downgrade action
295 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
297 * Revision 1.31 2001/10/05 14:25:02 oes
298 * Crumble Keep-Alive from Server
300 * Revision 1.30 2001/09/29 12:56:03 joergs
301 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
303 * Revision 1.29 2001/09/24 21:09:24 jongfoster
304 * Fixing 2 memory leaks that Guy spotted, where the paramater to
305 * enlist() was not being free()d.
307 * Revision 1.28 2001/09/22 16:32:28 jongfoster
308 * Removing unused #includes.
310 * Revision 1.27 2001/09/20 15:45:25 steudten
312 * add casting from size_t to int for printf()
313 * remove local variable shadow s2
315 * Revision 1.26 2001/09/16 17:05:14 jongfoster
316 * Removing unused #include showarg.h
318 * Revision 1.25 2001/09/16 13:21:27 jongfoster
319 * Changes to use new list functions.
321 * Revision 1.24 2001/09/13 23:05:50 jongfoster
322 * Changing the string paramater to the header parsers a "const".
324 * Revision 1.23 2001/09/12 18:08:19 steudten
326 * In parse_http_request() header rewriting miss the host value, so
327 * from http://www.mydomain.com the result was just " / " not
328 * http://www.mydomain.com/ in case we forward.
330 * Revision 1.22 2001/09/10 10:58:53 oes
331 * Silenced compiler warnings
333 * Revision 1.21 2001/07/31 14:46:00 oes
334 * - Persistant connections now suppressed
335 * - sed() no longer appends empty header to csp->headers
337 * Revision 1.20 2001/07/30 22:08:36 jongfoster
338 * Tidying up #defines:
339 * - All feature #defines are now of the form FEATURE_xxx
340 * - Permanently turned off WIN_GUI_EDIT
341 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
343 * Revision 1.19 2001/07/25 17:21:54 oes
344 * client_uagent now saves copy of User-Agent: header value
346 * Revision 1.18 2001/07/13 14:02:46 oes
347 * - Included fix to repair broken HTTP requests that
348 * don't contain a path, not even '/'.
349 * - Removed all #ifdef PCRS
350 * - content_type now always inspected and classified as
351 * text, gif or other.
352 * - formatting / comments
354 * Revision 1.17 2001/06/29 21:45:41 oes
355 * Indentation, CRLF->LF, Tab-> Space
357 * Revision 1.16 2001/06/29 13:32:42 oes
359 * - Adapted free_http_request
360 * - Removed logentry from cancelled commit
362 * Revision 1.15 2001/06/03 19:12:38 oes
363 * deleted const struct interceptors
365 * Revision 1.14 2001/06/01 18:49:17 jongfoster
366 * Replaced "list_share" with "list" - the tiny memory gain was not
367 * worth the extra complexity.
369 * Revision 1.13 2001/05/31 21:30:33 jongfoster
370 * Removed list code - it's now in list.[ch]
371 * Renamed "permission" to "action", and changed many features
372 * to use the actions file rather than the global config.
374 * Revision 1.12 2001/05/31 17:33:13 oes
378 * Revision 1.11 2001/05/29 20:11:19 joergs
379 * '/ * inside comment' warning removed.
381 * Revision 1.10 2001/05/29 09:50:24 jongfoster
382 * Unified blocklist/imagelist/permissionslist.
383 * File format is still under discussion, but the internal changes
386 * Also modified interceptor behaviour:
387 * - We now intercept all URLs beginning with one of the following
388 * prefixes (and *only* these prefixes):
390 * * http://ijbswa.sf.net/config/
391 * * http://ijbswa.sourceforge.net/config/
392 * - New interceptors "home page" - go to http://i.j.b/ to see it.
393 * - Internal changes so that intercepted and fast redirect pages
394 * are not replaced with an image.
395 * - Interceptors now have the option to send a binary page direct
396 * to the client. (i.e. ijb-send-banner uses this)
397 * - Implemented show-url-info interceptor. (Which is why I needed
398 * the above interceptors changes - a typical URL is
399 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
400 * The previous mechanism would not have intercepted that, and
401 * if it had been intercepted then it then it would have replaced
404 * Revision 1.9 2001/05/28 17:26:33 jongfoster
405 * Fixing segfault if last header was crunched.
406 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
407 * can use the cross-platform sprintf() instead.)
409 * Revision 1.8 2001/05/27 22:17:04 oes
411 * - re_process_buffer no longer writes the modified buffer
412 * to the client, which was very ugly. It now returns the
413 * buffer, which it is then written by chat.
415 * - content_length now adjusts the Content-Length: header
416 * for modified documents rather than crunch()ing it.
417 * (Length info in csp->content_length, which is 0 for
418 * unmodified documents)
420 * - For this to work, sed() is called twice when filtering.
422 * Revision 1.7 2001/05/27 13:19:06 oes
423 * Patched Joergs solution for the content-length in.
425 * Revision 1.6 2001/05/26 13:39:32 jongfoster
426 * Only crunches Content-Length header if applying RE filtering.
427 * Without this fix, Microsoft Windows Update wouldn't work.
429 * Revision 1.5 2001/05/26 00:28:36 jongfoster
430 * Automatic reloading of config file.
431 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
432 * Most of the global variables have been moved to a new
433 * struct configuration_spec, accessed through csp->config->globalname
434 * Most of the globals remaining are used by the Win32 GUI.
436 * Revision 1.4 2001/05/22 18:46:04 oes
438 * - Enabled filtering banners by size rather than URL
439 * by adding patterns that replace all standard banner
440 * sizes with the "Junkbuster" gif to the re_filterfile
442 * - Enabled filtering WebBugs by providing a pattern
443 * which kills all 1x1 images
445 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
446 * which is selected by the (nonstandard and therefore
447 * capital) letter 'U' in the option string.
448 * It causes the quantifiers to be ungreedy by default.
449 * Appending a ? turns back to greedy (!).
451 * - Added a new interceptor ijb-send-banner, which
452 * sends back the "Junkbuster" gif. Without imagelist or
453 * MSIE detection support, or if tinygif = 1, or the
454 * URL isn't recognized as an imageurl, a lame HTML
455 * explanation is sent instead.
457 * - Added new feature, which permits blocking remote
458 * script redirects and firing back a local redirect
460 * The feature is conditionally compiled, i.e. it
461 * can be disabled with --disable-fast-redirects,
462 * plus it must be activated by a "fast-redirects"
463 * line in the config file, has its own log level
464 * and of course wants to be displayed by show-proxy-args
465 * Note: Boy, all the #ifdefs in 1001 locations and
466 * all the fumbling with configure.in and acconfig.h
467 * were *way* more work than the feature itself :-(
469 * - Because a generic redirect template was needed for
470 * this, tinygif = 3 now uses the same.
472 * - Moved GIFs, and other static HTTP response templates
477 * - Removed some >400 CRs again (Jon, you really worked
480 * Revision 1.3 2001/05/20 01:21:20 jongfoster
481 * Version 2.9.4 checkin.
482 * - Merged popupfile and cookiefile, and added control over PCRS
483 * filtering, in new "permissionsfile".
484 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
485 * file error you now get a message box (in the Win32 GUI) rather
486 * than the program exiting with no explanation.
487 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
489 * - Removed tabs from "config"
490 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
491 * - Bumped up version number.
493 * Revision 1.2 2001/05/17 23:02:36 oes
494 * - Made referrer option accept 'L' as a substitute for '§'
496 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
497 * Initial import of version 2.9.3 source tree
500 *********************************************************************/
507 #include <sys/types.h>
516 #if !defined(_WIN32) && !defined(__OS2__)
525 /* jcc.h is for mutex semapores only */
526 #endif /* def OSX_DARWIN */
532 #include "jbsockets.h"
533 #include "miscutil.h"
536 #ifndef HAVE_STRPTIME
537 #include "strptime.h"
540 const char parsers_h_rcs[] = PARSERS_H_VERSION;
542 /* Fix a problem with Solaris. There should be no effect on other
544 * Solaris's isspace() is a macro which uses it's argument directly
545 * as an array index. Therefore we need to make sure that high-bit
546 * characters generate +ve values, and ideally we also want to make
547 * the argument match the declared parameter type of "int".
549 * Why did they write a character function that can't take a simple
550 * "char" argument? Doh!
552 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
553 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
556 const struct parsers client_patterns[] = {
557 { "referer:", 8, client_referrer },
558 { "user-agent:", 11, client_uagent },
559 { "ua-", 3, client_ua },
560 { "from:", 5, client_from },
561 { "cookie:", 7, client_send_cookie },
562 { "x-forwarded-for:", 16, client_x_forwarded },
563 { "Accept-Encoding:", 16, client_accept_encoding },
564 { "TE:", 3, client_te },
565 { "Host:", 5, client_host },
566 { "if-modified-since:", 18, client_if_modified_since },
567 { "Keep-Alive:", 11, crumble },
568 { "connection:", 11, crumble },
569 { "proxy-connection:", 17, crumble },
570 { "max-forwards:", 13, client_max_forwards },
571 { "Accept-Language:", 16, client_accept_language },
572 { "if-none-match:", 14, client_if_none_match },
573 { "X-Filter:", 9, client_x_filter },
574 { "*", 0, crunch_client_header },
575 { "*", 0, filter_client_header },
579 const struct parsers server_patterns[] = {
580 { "HTTP", 4, server_http },
581 { "set-cookie:", 11, server_set_cookie },
582 { "connection:", 11, crumble },
583 { "Content-Type:", 13, server_content_type },
584 { "Content-Length:", 15, server_content_length },
585 { "Content-MD5:", 12, server_content_md5 },
586 { "Content-Encoding:", 17, server_content_encoding },
587 { "Transfer-Encoding:", 18, server_transfer_coding },
588 { "Keep-Alive:", 11, crumble },
589 { "content-disposition:", 20, server_content_disposition },
590 { "Last-Modified:", 14, server_last_modified },
591 { "*", 0, crunch_server_header },
592 { "*", 0, filter_server_header },
596 const struct parsers server_patterns_light[] = {
597 { "Content-Length:", 15, server_content_length },
598 { "Transfer-Encoding:", 18, server_transfer_coding },
602 const add_header_func_ptr add_client_headers[] = {
605 client_x_forwarded_adder,
607 /* Temporarily disabled: client_accept_encoding_adder, */
608 connection_close_adder,
613 const add_header_func_ptr add_server_headers[] = {
614 connection_close_adder,
618 /*********************************************************************
620 * Function : flush_socket
622 * Description : Write any pending "buffered" content.
625 * 1 : fd = file descriptor of the socket to read
626 * 2 : csp = Current client state (buffers, headers, etc...)
628 * Returns : On success, the number of bytes written are returned (zero
629 * indicates nothing was written). On error, -1 is returned,
630 * and errno is set appropriately. If count is zero and the
631 * file descriptor refers to a regular file, 0 will be
632 * returned without causing any other effect. For a special
633 * file, the results are not portable.
635 *********************************************************************/
636 int flush_socket(jb_socket fd, struct client_state *csp)
638 struct iob *iob = csp->iob;
639 int len = iob->eod - iob->cur;
646 if (write_socket(fd, iob->cur, (size_t)len))
650 iob->eod = iob->cur = iob->buf;
656 /*********************************************************************
658 * Function : add_to_iob
660 * Description : Add content to the buffered page, expanding the
661 * buffer if necessary.
664 * 1 : csp = Current client state (buffers, headers, etc...)
665 * 2 : buf = holds the content to be added to the page
666 * 3 : n = number of bytes to be added
668 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
669 * or buffer limit reached.
671 *********************************************************************/
672 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
674 struct iob *iob = csp->iob;
675 size_t used, offset, need, want;
678 if (n <= 0) return JB_ERR_OK;
680 used = iob->eod - iob->buf;
681 offset = iob->cur - iob->buf;
685 * If the buffer can't hold the new data, extend it first.
686 * Use the next power of two if possible, else use the actual need.
688 if (need > csp->config->buffer_limit)
690 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
691 return JB_ERR_MEMORY;
694 if (need > iob->size)
696 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
698 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
702 else if (NULL != (p = (char *)realloc(iob->buf, need)))
708 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
709 return JB_ERR_MEMORY;
712 /* Update the iob pointers */
713 iob->cur = p + offset;
718 /* copy the new data into the iob buffer */
719 memcpy(iob->eod, buf, (size_t)n);
721 /* point to the end of the data */
724 /* null terminate == cheap insurance */
732 /*********************************************************************
734 * Function : get_header
736 * Description : This (odd) routine will parse the csp->iob
739 * 1 : csp = Current client state (buffers, headers, etc...)
741 * Returns : Any one of the following:
743 * 1) a pointer to a dynamically allocated string that contains a header line
744 * 2) NULL indicating that the end of the header was reached
745 * 3) "" indicating that the end of the iob was reached before finding
746 * a complete header line.
748 *********************************************************************/
749 char *get_header(struct client_state *csp)
755 if ((iob->cur == NULL)
756 || ((p = strchr(iob->cur, '\n')) == NULL))
758 return(""); /* couldn't find a complete header */
763 ret = strdup(iob->cur);
766 /* FIXME No way to handle error properly */
767 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
772 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
774 /* is this a blank line (i.e. the end of the header) ? */
786 /*********************************************************************
788 * Function : get_header_value
790 * Description : Get the value of a given header from a chained list
791 * of header lines or return NULL if no such header is
792 * present in the list.
795 * 1 : header_list = pointer to list
796 * 2 : header_name = string with name of header to look for.
797 * Trailing colon required, capitalization
800 * Returns : NULL if not found, else value of header
802 *********************************************************************/
803 char *get_header_value(const struct list *header_list, const char *header_name)
805 struct list_entry *cur_entry;
811 length = strlen(header_name);
813 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
817 if (!strncmpic(cur_entry->str, header_name, length))
820 * Found: return pointer to start of value
822 ret = (char *) (cur_entry->str + length);
823 while (*ret && ijb_isspace(*ret)) ret++;
836 /*********************************************************************
840 * Description : add, delete or modify lines in the HTTP header streams.
841 * On entry, it receives a linked list of headers space
842 * that was allocated dynamically (both the list nodes
843 * and the header contents).
845 * As a side effect it frees the space used by the original
849 * 1 : pats = list of patterns to match against headers
850 * 2 : more_headers = list of functions to add more
851 * headers (client or server)
852 * 3 : csp = Current client state (buffers, headers, etc...)
854 * Returns : Single pointer to a fully formed header, or NULL
855 * on out-of-memory error.
857 *********************************************************************/
858 char *sed(const struct parsers pats[],
859 const add_header_func_ptr more_headers[],
860 struct client_state *csp)
862 struct list_entry *p;
863 const struct parsers *v;
864 const add_header_func_ptr *f;
865 jb_err err = JB_ERR_OK;
869 * If filtering is enabled, sed is run twice,
870 * but most of the work needs to be done only once.
872 first_run = (more_headers != NULL ) ? 1 : 0;
874 if (first_run) /* Parse and print */
876 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
878 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
880 /* Header crunch()ed in previous run? -> ignore */
881 if (p->str == NULL) continue;
883 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
885 /* Does the current parser handle this header? */
886 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
888 err = v->parser(csp, (char **)&(p->str));
892 /* place any additional headers on the csp->headers list */
893 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
898 else /* Parse only */
901 * The second run is only needed if the body was modified
902 * and the content-lenght has changed.
904 if (strncmpic(csp->http->cmd, "HEAD", 4))
906 /*XXX: Code duplication*/
907 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
909 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
911 /* Header crunch()ed in previous run? -> ignore */
912 if (p->str == NULL) continue;
914 /* Does the current parser handle this header? */
915 if (strncmpic(p->str, v->str, v->len) == 0)
917 err = v->parser(csp, (char **)&(p->str));
924 if (err != JB_ERR_OK)
929 return list_to_text(csp->headers);
933 /* here begins the family of parser functions that reformat header lines */
935 /*********************************************************************
937 * Function : filter_server_header
939 * Description : Checks if server header filtering is enabled.
940 * If it is, filter_header is called to do the work.
943 * 1 : csp = Current client state (buffers, headers, etc...)
944 * 2 : header = On input, pointer to header to modify.
945 * On output, pointer to the modified header, or NULL
946 * to remove the header. This function frees the
947 * original string if necessary.
949 * Returns : JB_ERR_OK on success and always succeeds
951 *********************************************************************/
952 jb_err filter_server_header(struct client_state *csp, char **header)
954 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
956 filter_header(csp, header);
961 /*********************************************************************
963 * Function : filter_client_header
965 * Description : Checks if client header filtering is enabled.
966 * If it is, filter_header is called to do the work.
969 * 1 : csp = Current client state (buffers, headers, etc...)
970 * 2 : header = On input, pointer to header to modify.
971 * On output, pointer to the modified header, or NULL
972 * to remove the header. This function frees the
973 * original string if necessary.
975 * Returns : JB_ERR_OK on success and always succeeds
977 *********************************************************************/
978 jb_err filter_client_header(struct client_state *csp, char **header)
980 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
982 filter_header(csp, header);
987 /*********************************************************************
989 * Function : filter_header
991 * Description : Executes all text substitutions from all applying
992 * +filter actions on the header.
993 * Most of the code was copied from pcrs_filter_response,
994 * including the rather short variable names
997 * 1 : csp = Current client state (buffers, headers, etc...)
998 * 2 : header = On input, pointer to header to modify.
999 * On output, pointer to the modified header, or NULL
1000 * to remove the header. This function frees the
1001 * original string if necessary.
1003 * Returns : JB_ERR_OK on success and always succeeds
1005 *********************************************************************/
1006 jb_err filter_header(struct client_state *csp, char **header)
1010 size_t size = strlen(*header);
1012 char *newheader = NULL;
1015 struct file_list *fl;
1016 struct re_filterfile_spec *b;
1017 struct list_entry *filtername;
1019 int i, found_filters = 0;
1021 log_error(LOG_LEVEL_RE_FILTER, "Entered filter_headers");
1023 * Need to check the set of re_filterfiles...
1025 for (i = 0; i < MAX_AF_FILES; i++)
1038 if (0 == found_filters)
1040 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1044 for (i = 0; i < MAX_AF_FILES; i++)
1047 if ((NULL == fl) || (NULL == fl->f))
1050 * For all applying +filter actions, look if a filter by that
1051 * name exists and if yes, execute its pcrs_joblist on the
1054 for (b = fl->f; b; b = b->next)
1056 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1057 filtername ; filtername = filtername->next)
1059 if (strcmp(b->name, filtername->str) == 0)
1061 int current_hits = 0;
1063 if ( NULL == b->joblist )
1065 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1069 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1070 *header, size, b->name);
1072 /* Apply all jobs from the joblist */
1073 for (job = b->joblist; NULL != job; job = job->next)
1075 matches = pcrs_execute(job, *header, size, &newheader, &size);
1078 current_hits += matches;
1079 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1081 *header = newheader;
1083 else if ( 0 == matches )
1085 /* Filter doesn't change header */
1091 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1092 *header, b->name, pcrs_strerror(matches));
1093 if( newheader != NULL)
1095 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1100 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1101 hits += current_hits;
1109 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1112 log_error(LOG_LEVEL_RE_FILTER, "Leaving filter headers");
1118 /*********************************************************************
1120 * Function : crumble
1122 * Description : This is called if a header matches a pattern to "crunch"
1125 * 1 : csp = Current client state (buffers, headers, etc...)
1126 * 2 : header = On input, pointer to header to modify.
1127 * On output, pointer to the modified header, or NULL
1128 * to remove the header. This function frees the
1129 * original string if necessary.
1131 * Returns : JB_ERR_OK on success, or
1132 * JB_ERR_MEMORY on out-of-memory error.
1134 *********************************************************************/
1135 jb_err crumble(struct client_state *csp, char **header)
1137 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1142 /*********************************************************************
1144 * Function : crunch_server_header
1146 * Description : Crunch server header if it matches a string supplied by the
1147 * user. Called from `sed'.
1150 * 1 : csp = Current client state (buffers, headers, etc...)
1151 * 2 : header = On input, pointer to header to modify.
1152 * On output, pointer to the modified header, or NULL
1153 * to remove the header. This function frees the
1154 * original string if necessary.
1156 * Returns : JB_ERR_OK on success and always succeeds
1158 *********************************************************************/
1159 jb_err crunch_server_header(struct client_state *csp, char **header)
1161 const char *crunch_pattern;
1162 /*Is there a header to crunch*/
1164 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1166 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1168 /*Is the current header the lucky one?*/
1169 if (strstr(*header, crunch_pattern))
1171 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1178 /*********************************************************************
1180 * Function : server_content_type
1182 * Description : Set the content-type for filterable types (text/.*,
1183 * javascript and image/gif) unless filtering has been
1184 * forbidden (CT_TABOO) while parsing earlier headers.
1185 * NOTE: Since text/plain is commonly used by web servers
1186 * for files whose correct type is unknown, we don't
1187 * set CT_TEXT for it.
1190 * 1 : csp = Current client state (buffers, headers, etc...)
1191 * 2 : header = On input, pointer to header to modify.
1192 * On output, pointer to the modified header, or NULL
1193 * to remove the header. This function frees the
1194 * original string if necessary.
1196 * Returns : JB_ERR_OK on success, or
1197 * JB_ERR_MEMORY on out-of-memory error.
1199 *********************************************************************/
1200 jb_err server_content_type(struct client_state *csp, char **header)
1204 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1206 if (csp->content_type != CT_TABOO)
1208 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1209 || strstr(*header, "xml")
1210 || strstr(*header, "application/x-javascript"))
1211 csp->content_type = CT_TEXT;
1212 else if (strstr(*header, " image/gif"))
1213 csp->content_type = CT_GIF;
1214 else if (strstr(*header, " image/jpeg"))
1215 csp->content_type = CT_JPEG;
1217 csp->content_type = 0;
1220 * Are we enabling text mode by force?
1222 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1225 * Do we really have to?
1227 if (csp->content_type == CT_TEXT)
1229 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1233 csp->content_type = CT_TEXT;
1234 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1238 * Are we messing with the content type?
1240 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1243 * Make sure the user doesn't accidently
1244 * change the content type of binary documents.
1246 if (csp->content_type == CT_TEXT)
1249 *header = strdup("Content-Type: ");
1250 string_append(header, newval);
1254 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1255 return JB_ERR_MEMORY;
1257 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1261 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1262 "Enable force-text-mode if you know what you're doing.", *header);
1269 /*********************************************************************
1271 * Function : server_transfer_coding
1273 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1274 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1275 * - Remove header if body was chunked but has been
1276 * de-chunked for filtering.
1279 * 1 : csp = Current client state (buffers, headers, etc...)
1280 * 2 : header = On input, pointer to header to modify.
1281 * On output, pointer to the modified header, or NULL
1282 * to remove the header. This function frees the
1283 * original string if necessary.
1285 * Returns : JB_ERR_OK on success, or
1286 * JB_ERR_MEMORY on out-of-memory error.
1288 *********************************************************************/
1289 jb_err server_transfer_coding(struct client_state *csp, char **header)
1292 * Turn off pcrs and gif filtering if body compressed
1294 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1296 csp->content_type = CT_TABOO;
1300 * Raise flag if body chunked
1302 if (strstr(*header, "chunked"))
1304 csp->flags |= CSP_FLAG_CHUNKED;
1307 * If the body was modified, it has been de-chunked first
1308 * and the header must be removed.
1310 if (csp->flags & CSP_FLAG_MODIFIED)
1312 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1321 /*********************************************************************
1323 * Function : server_content_encoding
1325 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1328 * 1 : csp = Current client state (buffers, headers, etc...)
1329 * 2 : header = On input, pointer to header to modify.
1330 * On output, pointer to the modified header, or NULL
1331 * to remove the header. This function frees the
1332 * original string if necessary.
1334 * Returns : JB_ERR_OK on success, or
1335 * JB_ERR_MEMORY on out-of-memory error.
1337 *********************************************************************/
1338 jb_err server_content_encoding(struct client_state *csp, char **header)
1341 * Turn off pcrs and gif filtering if body compressed
1343 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1345 csp->content_type = CT_TABOO;
1353 /*********************************************************************
1355 * Function : server_content_length
1357 * Description : Adjust Content-Length header if we modified
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_length(struct client_state *csp, char **header)
1373 if (csp->content_length != 0) /* Content length could have been modified */
1376 * XXX: Shouldn't we check if csp->content_length
1377 * is different than the original value?
1380 *header = (char *) zalloc(100);
1381 if (*header == NULL)
1383 return JB_ERR_MEMORY;
1386 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1388 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1395 /*********************************************************************
1397 * Function : server_content_md5
1399 * Description : Crumble any Content-MD5 headers if the document was
1400 * modified. FIXME: Should we re-compute instead?
1403 * 1 : csp = Current client state (buffers, headers, etc...)
1404 * 2 : header = On input, pointer to header to modify.
1405 * On output, pointer to the modified header, or NULL
1406 * to remove the header. This function frees the
1407 * original string if necessary.
1409 * Returns : JB_ERR_OK on success, or
1410 * JB_ERR_MEMORY on out-of-memory error.
1412 *********************************************************************/
1413 jb_err server_content_md5(struct client_state *csp, char **header)
1415 if (csp->flags & CSP_FLAG_MODIFIED)
1417 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1424 /*********************************************************************
1426 * Function : server_content_disposition
1428 * Description : If enabled, blocks or modifies the "content-disposition" header.
1429 * Called from `sed'.
1432 * 1 : csp = Current client state (buffers, headers, etc...)
1433 * 2 : header = On input, pointer to header to modify.
1434 * On output, pointer to the modified header, or NULL
1435 * to remove the header. This function frees the
1436 * original string if necessary.
1438 * Returns : JB_ERR_OK on success, or
1439 * JB_ERR_MEMORY on out-of-memory error.
1441 *********************************************************************/
1442 jb_err server_content_disposition(struct client_state *csp, char **header)
1447 * Are we messing with the content-disposition header?
1449 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1455 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1457 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1460 * Blocking content-disposition header
1462 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1469 * Replacing content-disposition header
1472 *header = strdup("content-disposition: ");
1473 string_append(header, newval);
1475 if (*header == NULL)
1477 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1481 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1484 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1487 /*********************************************************************
1489 * Function : server_last_modified
1491 * Description : Changes Last-Modified header to the actual date
1492 * to help hide-if-modified-since.
1493 * Called from `sed'.
1496 * 1 : csp = Current client state (buffers, headers, etc...)
1497 * 2 : header = On input, pointer to header to modify.
1498 * On output, pointer to the modified header, or NULL
1499 * to remove the header. This function frees the
1500 * original string if necessary.
1502 * Returns : JB_ERR_OK on success, or
1503 * JB_ERR_MEMORY on out-of-memory error.
1505 *********************************************************************/
1506 jb_err server_last_modified(struct client_state *csp, char **header)
1509 char buf[BUFFER_SIZE];
1512 #ifdef HAVE_GMTIME_R
1515 struct tm *timeptr = NULL;
1516 time_t now, last_modified;
1518 long int days, hours, minutes, seconds;
1521 * Are we messing with the Last-Modified header?
1523 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1529 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1531 if (0 == strcmpic(newval, "block") )
1534 * Blocking Last-Modified header. Useless but why not.
1536 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1540 else if (0 == strcmpic(newval, "reset-to-request-time"))
1543 * Setting Last-Modified Header to now.
1545 get_http_time(0, buf);
1547 *header = strdup("Last-Modified: ");
1548 string_append(header, buf);
1550 if (*header == NULL)
1552 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1556 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1559 else if (0 == strcmpic(newval, "randomize"))
1561 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1563 #ifdef HAVE_GMTIME_R
1564 timeptr = gmtime_r(&now, &gmt);
1566 pthread_mutex_lock(&gmtime_mutex);
1567 timeptr = gmtime(&now);
1568 pthread_mutex_unlock(&gmtime_mutex);
1570 timeptr = gmtime(&now);
1572 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
1574 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1579 rtime = difftime(now, last_modified);
1582 rtime = pick_from_range(rtime);
1583 last_modified += rtime;
1584 #ifdef HAVE_GMTIME_R
1585 timeptr = gmtime_r(&last_modified, &gmt);
1587 pthread_mutex_lock(&gmtime_mutex);
1588 timeptr = gmtime(&last_modified);
1589 pthread_mutex_unlock(&gmtime_mutex);
1591 timeptr = gmtime(&last_modified);
1593 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1595 *header = strdup("Last-Modified: ");
1596 string_append(header, newheader);
1598 if (*header == NULL)
1600 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
1601 return JB_ERR_MEMORY;
1604 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1606 days = rtime / (3600 * 24);
1607 hours = rtime / 3600 % 24;
1608 minutes = rtime / 60 % 60;
1609 seconds = rtime % 60;
1611 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1612 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1613 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1618 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1626 /*********************************************************************
1628 * Function : client_accept_encoding
1630 * Description : Rewrite the client's Accept-Encoding header so that
1631 * if doesn't allow compression, if the action applies.
1632 * Note: For HTTP/1.0 the absence of the header is enough.
1635 * 1 : csp = Current client state (buffers, headers, etc...)
1636 * 2 : header = On input, pointer to header to modify.
1637 * On output, pointer to the modified header, or NULL
1638 * to remove the header. This function frees the
1639 * original string if necessary.
1641 * Returns : JB_ERR_OK on success, or
1642 * JB_ERR_MEMORY on out-of-memory error.
1644 *********************************************************************/
1645 jb_err client_accept_encoding(struct client_state *csp, char **header)
1647 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1649 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1653 /* Temporarily disable the correct behaviour to
1654 * work around a PHP bug.
1656 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1658 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1659 * if (*header == NULL)
1661 * return JB_ERR_MEMORY;
1672 /*********************************************************************
1674 * Function : client_te
1676 * Description : Rewrite the client's TE header so that
1677 * if doesn't allow compression, if the action applies.
1680 * 1 : csp = Current client state (buffers, headers, etc...)
1681 * 2 : header = On input, pointer to header to modify.
1682 * On output, pointer to the modified header, or NULL
1683 * to remove the header. This function frees the
1684 * original string if necessary.
1686 * Returns : JB_ERR_OK on success, or
1687 * JB_ERR_MEMORY on out-of-memory error.
1689 *********************************************************************/
1690 jb_err client_te(struct client_state *csp, char **header)
1692 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1695 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1701 /*********************************************************************
1703 * Function : client_referrer
1705 * Description : Handle the "referer" config setting properly.
1706 * Called from `sed'.
1709 * 1 : csp = Current client state (buffers, headers, etc...)
1710 * 2 : header = On input, pointer to header to modify.
1711 * On output, pointer to the modified header, or NULL
1712 * to remove the header. This function frees the
1713 * original string if necessary.
1715 * Returns : JB_ERR_OK on success, or
1716 * JB_ERR_MEMORY on out-of-memory error.
1718 *********************************************************************/
1719 jb_err client_referrer(struct client_state *csp, char **header)
1726 #ifdef FEATURE_FORCE_LOAD
1727 /* Since the referrer can include the prefix even
1728 * if the request itself is non-forced, we must
1729 * clean it unconditionally
1731 strclean(*header, FORCE_PREFIX);
1732 #endif /* def FEATURE_FORCE_LOAD */
1735 * Are we sending referer?
1737 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1742 newval = csp->action->string[ACTION_STRING_REFERER];
1744 if ((0 != strcmpic(newval, "conditional-block")))
1748 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1753 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1756 else if (0 == strcmpic(newval, "conditional-block"))
1759 * Block referer if host has changed.
1762 if (NULL == (host = strdup(csp->http->hostport)))
1765 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1766 return JB_ERR_MEMORY;
1768 if (NULL == (referer = strdup(*header)))
1772 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1773 return JB_ERR_MEMORY;
1775 hostlenght = strlen(host);
1776 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1778 /*Shorten referer to make sure the referer is blocked
1779 *if www.example.org/www.example.com-shall-see-the-referer/
1780 *links to www.example.com/
1782 referer[hostlenght+17] = '\0';
1784 if ( 0 == strstr(referer, host)) /*Host has changed*/
1786 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1791 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1797 else if (0 != strcmpic(newval, "forge"))
1800 * We have a specific (fixed) referer we want to send.
1802 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1804 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1806 *header = strdup("Referer: ");
1807 string_append(header, newval);
1808 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1810 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1815 * Forge a referer as http://[hostname:port of REQUEST]/
1816 * to fool stupid checks for in-site links
1819 *header = strdup("Referer: http://");
1820 string_append(header, csp->http->hostport);
1821 string_append(header, "/");
1822 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1824 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1828 /*********************************************************************
1830 * Function : client_accept_language
1832 * Description : Handle the "Accept-Language" config setting properly.
1833 * Called from `sed'.
1836 * 1 : csp = Current client state (buffers, headers, etc...)
1837 * 2 : header = On input, pointer to header to modify.
1838 * On output, pointer to the modified header, or NULL
1839 * to remove the header. This function frees the
1840 * original string if necessary.
1842 * Returns : JB_ERR_OK on success, or
1843 * JB_ERR_MEMORY on out-of-memory error.
1845 *********************************************************************/
1846 jb_err client_accept_language(struct client_state *csp, char **header)
1851 * Are we messing with the Accept-Language?
1853 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1855 /*I don't think so*/
1859 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1861 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1864 * Blocking Accept-Language header
1866 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1873 * Replacing Accept-Language header
1876 *header = strdup("Accept-Language: ");
1877 string_append(header, newval);
1879 if (*header == NULL)
1881 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1885 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1888 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1891 /*********************************************************************
1893 * Function : crunch_client_header
1895 * Description : Crunch client header if it matches a string supplied by the
1896 * user. Called from `sed'.
1899 * 1 : csp = Current client state (buffers, headers, etc...)
1900 * 2 : header = On input, pointer to header to modify.
1901 * On output, pointer to the modified header, or NULL
1902 * to remove the header. This function frees the
1903 * original string if necessary.
1905 * Returns : JB_ERR_OK on success and always succeeds
1907 *********************************************************************/
1908 jb_err crunch_client_header(struct client_state *csp, char **header)
1910 const char *crunch_pattern;
1911 /*Is there a header to crunch*/
1913 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1915 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1917 /*Is the current header the lucky one?*/
1918 if (strstr(*header, crunch_pattern))
1920 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1928 /*********************************************************************
1930 * Function : client_uagent
1932 * Description : Handle the "user-agent" config setting properly
1933 * and remember its original value to enable browser
1934 * bug workarounds. Called from `sed'.
1937 * 1 : csp = Current client state (buffers, headers, etc...)
1938 * 2 : header = On input, pointer to header to modify.
1939 * On output, pointer to the modified header, or NULL
1940 * to remove the header. This function frees the
1941 * original string if necessary.
1943 * Returns : JB_ERR_OK on success, or
1944 * JB_ERR_MEMORY on out-of-memory error.
1946 *********************************************************************/
1947 jb_err client_uagent(struct client_state *csp, char **header)
1951 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1956 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1963 *header = strdup("User-Agent: ");
1964 string_append(header, newval);
1966 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
1968 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1971 /*********************************************************************
1973 * Function : client_ua
1975 * Description : Handle "ua-" headers properly. Called from `sed'.
1978 * 1 : csp = Current client state (buffers, headers, etc...)
1979 * 2 : header = On input, pointer to header to modify.
1980 * On output, pointer to the modified header, or NULL
1981 * to remove the header. This function frees the
1982 * original string if necessary.
1984 * Returns : JB_ERR_OK on success, or
1985 * JB_ERR_MEMORY on out-of-memory error.
1987 *********************************************************************/
1988 jb_err client_ua(struct client_state *csp, char **header)
1990 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1992 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2000 /*********************************************************************
2002 * Function : client_from
2004 * Description : Handle the "from" config setting properly.
2005 * Called from `sed'.
2008 * 1 : csp = Current client state (buffers, headers, etc...)
2009 * 2 : header = On input, pointer to header to modify.
2010 * On output, pointer to the modified header, or NULL
2011 * to remove the header. This function frees the
2012 * original string if necessary.
2014 * Returns : JB_ERR_OK on success, or
2015 * JB_ERR_MEMORY on out-of-memory error.
2017 *********************************************************************/
2018 jb_err client_from(struct client_state *csp, char **header)
2022 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2029 newval = csp->action->string[ACTION_STRING_FROM];
2032 * Are we blocking the e-mail address?
2034 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2036 log_error(LOG_LEVEL_HEADER, "crunched From!");
2040 log_error(LOG_LEVEL_HEADER, " modified");
2042 *header = strdup("From: ");
2043 string_append(header, newval);
2045 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2049 /*********************************************************************
2051 * Function : client_send_cookie
2053 * Description : Handle the "cookie" header properly. Called from `sed'.
2054 * If cookie is accepted, add it to the cookie_list,
2055 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2058 * 1 : csp = Current client state (buffers, headers, etc...)
2059 * 2 : header = On input, pointer to header to modify.
2060 * On output, pointer to the modified header, or NULL
2061 * to remove the header. This function frees the
2062 * original string if necessary.
2064 * Returns : JB_ERR_OK on success, or
2065 * JB_ERR_MEMORY on out-of-memory error.
2067 *********************************************************************/
2068 jb_err client_send_cookie(struct client_state *csp, char **header)
2070 jb_err result = JB_ERR_OK;
2072 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2074 /* strlen("cookie: ") == 8 */
2075 result = enlist(csp->cookie_list, *header + 8);
2079 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2083 * Always remove the cookie here. The cookie header
2084 * will be sent at the end of the header.
2092 /*********************************************************************
2094 * Function : client_x_forwarded
2096 * Description : Handle the "x-forwarded-for" config setting properly,
2097 * also used in the add_client_headers list. Called from `sed'.
2100 * 1 : csp = Current client state (buffers, headers, etc...)
2101 * 2 : header = On input, pointer to header to modify.
2102 * On output, pointer to the modified header, or NULL
2103 * to remove the header. This function frees the
2104 * original string if necessary.
2106 * Returns : JB_ERR_OK on success, or
2107 * JB_ERR_MEMORY on out-of-memory error.
2109 *********************************************************************/
2110 jb_err client_x_forwarded(struct client_state *csp, char **header)
2112 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2114 /* Save it so we can re-add it later */
2115 freez(csp->x_forwarded);
2116 csp->x_forwarded = *header;
2119 * Always set *header = NULL, since this information
2120 * will be sent at the end of the header.
2127 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2134 /*********************************************************************
2136 * Function : client_max_forwards
2138 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2139 * from the value of the Max-Forwards header field.
2142 * 1 : csp = Current client state (buffers, headers, etc...)
2143 * 2 : header = On input, pointer to header to modify.
2144 * On output, pointer to the modified header, or NULL
2145 * to remove the header. This function frees the
2146 * original string if necessary.
2148 * Returns : JB_ERR_OK on success, or
2149 * JB_ERR_MEMORY on out-of-memory error.
2151 *********************************************************************/
2152 jb_err client_max_forwards(struct client_state *csp, char **header)
2154 unsigned int max_forwards;
2156 if ((0 == strcmpic(csp->http->gpc, "trace"))
2157 || (0 == strcmpic(csp->http->gpc, "options")))
2159 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2161 if (max_forwards-- >= 1)
2163 sprintf(*header, "Max-Forwards: %u", max_forwards);
2164 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2168 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2177 /*********************************************************************
2179 * Function : client_host
2181 * Description : If the request URI did not contain host and
2182 * port information, parse and evaluate the Host
2185 * Also, kill ill-formed HOST: headers as sent by
2186 * Apple's iTunes software when used with a proxy.
2189 * 1 : csp = Current client state (buffers, headers, etc...)
2190 * 2 : header = On input, pointer to header to modify.
2191 * On output, pointer to the modified header, or NULL
2192 * to remove the header. This function frees the
2193 * original string if necessary.
2195 * Returns : JB_ERR_OK on success, or
2196 * JB_ERR_MEMORY on out-of-memory error.
2198 *********************************************************************/
2199 jb_err client_host(struct client_state *csp, char **header)
2204 * If the header field name is all upper-case, chances are that it's
2205 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2206 * not a problem -- they are regenerated later.
2208 if ((*header)[1] == 'O')
2210 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2215 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2216 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2219 if (NULL == (p = strdup((*header)+6)))
2221 return JB_ERR_MEMORY;
2224 if (NULL == (q = strdup(p)))
2227 return JB_ERR_MEMORY;
2230 freez(csp->http->hostport);
2231 csp->http->hostport = p;
2232 freez(csp->http->host);
2233 csp->http->host = q;
2234 q = strchr(csp->http->host, ':');
2237 /* Terminate hostname and evaluate port string */
2239 csp->http->port = atoi(q);
2243 csp->http->port = csp->http->ssl ? 443 : 80;
2246 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2247 csp->http->hostport, csp->http->host, csp->http->port);
2253 /*********************************************************************
2255 * Function : client_if_modified_since
2257 * Description : Remove or modify the If-Modified-Since header.
2260 * 1 : csp = Current client state (buffers, headers, etc...)
2261 * 2 : header = On input, pointer to header to modify.
2262 * On output, pointer to the modified header, or NULL
2263 * to remove the header. This function frees the
2264 * original string if necessary.
2266 * Returns : JB_ERR_OK on success, or
2267 * JB_ERR_MEMORY on out-of-memory error.
2269 *********************************************************************/
2270 jb_err client_if_modified_since(struct client_state *csp, char **header)
2273 #ifdef HAVE_GMTIME_R
2276 struct tm *timeptr = NULL;
2280 long int hours, minutes, seconds;
2284 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2287 * The client got an error message because of a temporary problem,
2288 * the problem is gone and the client now tries to revalidate our
2289 * error message on the real server. The revalidation would always
2290 * end with the transmission of the whole document and there is
2291 * no need to expose the bogus If-Modified-Since header.
2293 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2296 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2298 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2300 if ((0 == strcmpic(newval, "block")))
2302 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2305 else /* add random value */
2307 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2309 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2314 rtime = strtol(newval, &endptr, 0);
2322 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2323 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2325 rtime = pick_from_range(rtime);
2329 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2333 #ifdef HAVE_GMTIME_R
2334 timeptr = gmtime_r(&tm, &gmt);
2336 pthread_mutex_lock(&gmtime_mutex);
2337 timeptr = gmtime(&tm);
2338 pthread_mutex_unlock(&gmtime_mutex);
2340 timeptr = gmtime(&tm);
2342 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2345 *header = strdup("If-Modified-Since: ");
2346 string_append(header, newheader);
2348 if (*header == NULL)
2350 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2351 return JB_ERR_MEMORY;
2354 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2356 hours = rtime / 3600;
2357 minutes = rtime / 60 % 60;
2358 seconds = rtime % 60;
2360 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2361 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2362 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2371 /*********************************************************************
2373 * Function : client_if_none_match
2375 * Description : Remove the If-None-Match header.
2378 * 1 : csp = Current client state (buffers, headers, etc...)
2379 * 2 : header = On input, pointer to header to modify.
2380 * On output, pointer to the modified header, or NULL
2381 * to remove the header. This function frees the
2382 * original string if necessary.
2384 * Returns : JB_ERR_OK on success, or
2385 * JB_ERR_MEMORY on out-of-memory error.
2387 *********************************************************************/
2388 jb_err client_if_none_match(struct client_state *csp, char **header)
2390 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2392 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2399 /*********************************************************************
2401 * Function : client_x_filter
2403 * Description : Disables filtering if the client set "X-Filter: No".
2404 * Called from `sed'.
2407 * 1 : csp = Current client state (buffers, headers, etc...)
2408 * 2 : header = On input, pointer to header to modify.
2409 * On output, pointer to the modified header, or NULL
2410 * to remove the header. This function frees the
2411 * original string if necessary.
2413 * Returns : JB_ERR_OK on success
2415 *********************************************************************/
2416 jb_err client_x_filter(struct client_state *csp, char **header)
2418 if ( 0 == strcmpic(*header, "X-Filter: No"))
2420 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2422 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
2426 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2428 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to fetch without filtering!");
2432 csp->content_type = CT_TABOO;
2433 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
2435 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2442 /* the following functions add headers directly to the header list */
2444 /*********************************************************************
2446 * Function : client_host_adder
2448 * Description : Adds the Host: header field if it is missing.
2449 * Called from `sed'.
2452 * 1 : csp = Current client state (buffers, headers, etc...)
2454 * Returns : JB_ERR_OK on success, or
2455 * JB_ERR_MEMORY on out-of-memory error.
2457 *********************************************************************/
2458 jb_err client_host_adder(struct client_state *csp)
2463 if ( !csp->http->hostport || !*(csp->http->hostport))
2469 * remove 'user:pass@' from 'proto://user:pass@host'
2471 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2477 p = csp->http->hostport;
2480 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2481 err = enlist_unique_header(csp->headers, "Host", p);
2487 /*********************************************************************
2489 * Function : client_cookie_adder
2491 * Description : Used in the add_client_headers list. Called from `sed'.
2494 * 1 : csp = Current client state (buffers, headers, etc...)
2496 * Returns : JB_ERR_OK on success, or
2497 * JB_ERR_MEMORY on out-of-memory error.
2499 *********************************************************************/
2500 jb_err client_cookie_adder(struct client_state *csp)
2502 struct list_entry *lst;
2504 struct list_entry *list1 = csp->cookie_list->first;
2505 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2506 int first_cookie = 1;
2509 if ((list1 == NULL) && (list2 == NULL))
2515 tmp = strdup("Cookie: ");
2517 for (lst = list1; lst ; lst = lst->next)
2525 string_append(&tmp, "; ");
2527 string_append(&tmp, lst->str);
2530 for (lst = list2; lst ; lst = lst->next)
2538 string_append(&tmp, "; ");
2540 string_join(&tmp, cookie_encode(lst->str));
2545 return JB_ERR_MEMORY;
2548 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2549 err = enlist(csp->headers, tmp);
2555 /*********************************************************************
2557 * Function : client_accept_encoding_adder
2559 * Description : Add an Accept-Encoding header to the client's request
2560 * that disables compression if the action applies, and
2561 * the header is not already there. Called from `sed'.
2562 * Note: For HTTP/1.0, the absence of the header is enough.
2565 * 1 : csp = Current client state (buffers, headers, etc...)
2567 * Returns : JB_ERR_OK on success, or
2568 * JB_ERR_MEMORY on out-of-memory error.
2570 *********************************************************************/
2571 jb_err client_accept_encoding_adder(struct client_state *csp)
2573 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2574 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2576 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2583 /*********************************************************************
2585 * Function : client_xtra_adder
2587 * Description : Used in the add_client_headers list. Called from `sed'.
2590 * 1 : csp = Current client state (buffers, headers, etc...)
2592 * Returns : JB_ERR_OK on success, or
2593 * JB_ERR_MEMORY on out-of-memory error.
2595 *********************************************************************/
2596 jb_err client_xtra_adder(struct client_state *csp)
2598 struct list_entry *lst;
2601 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2602 lst ; lst = lst->next)
2604 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2605 err = enlist(csp->headers, lst->str);
2617 /*********************************************************************
2619 * Function : client_x_forwarded_adder
2621 * Description : Used in the add_client_headers list. Called from `sed'.
2624 * 1 : csp = Current client state (buffers, headers, etc...)
2626 * Returns : JB_ERR_OK on success, or
2627 * JB_ERR_MEMORY on out-of-memory error.
2629 *********************************************************************/
2630 jb_err client_x_forwarded_adder(struct client_state *csp)
2635 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2640 if (csp->x_forwarded)
2642 p = strdup(csp->x_forwarded);
2643 string_append(&p, ", ");
2647 p = strdup("X-Forwarded-For: ");
2649 string_append(&p, csp->ip_addr_str);
2653 return JB_ERR_MEMORY;
2656 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2657 err = enlist(csp->headers, p);
2664 /*********************************************************************
2666 * Function : connection_close_adder
2668 * Description : Adds a "Connection: close" header to csp->headers
2669 * as a temporary fix for the needed but missing HTTP/1.1
2670 * support. Called from `sed'.
2671 * FIXME: This whole function shouldn't be neccessary!
2674 * 1 : csp = Current client state (buffers, headers, etc...)
2676 * Returns : JB_ERR_OK on success, or
2677 * JB_ERR_MEMORY on out-of-memory error.
2679 *********************************************************************/
2680 jb_err connection_close_adder(struct client_state *csp)
2682 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2683 return enlist(csp->headers, "Connection: close");
2687 /*********************************************************************
2689 * Function : server_http
2691 * Description : - Save the HTTP Status into csp->http->status
2692 * - Set CT_TABOO to prevent filtering if the answer
2693 * is a partial range (HTTP status 206)
2694 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2698 * 1 : csp = Current client state (buffers, headers, etc...)
2699 * 2 : header = On input, pointer to header to modify.
2700 * On output, pointer to the modified header, or NULL
2701 * to remove the header. This function frees the
2702 * original string if necessary.
2704 * Returns : JB_ERR_OK on success, or
2705 * JB_ERR_MEMORY on out-of-memory error.
2707 *********************************************************************/
2708 jb_err server_http(struct client_state *csp, char **header)
2710 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2711 if (csp->http->status == 206)
2713 csp->content_type = CT_TABOO;
2716 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2719 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2726 /*********************************************************************
2728 * Function : server_set_cookie
2730 * Description : Handle the server "cookie" header properly.
2731 * Log cookie to the jar file. Then "crunch" it,
2732 * or accept it. Called from `sed'.
2735 * 1 : csp = Current client state (buffers, headers, etc...)
2736 * 2 : header = On input, pointer to header to modify.
2737 * On output, pointer to the modified header, or NULL
2738 * to remove the header. This function frees the
2739 * original string if necessary.
2741 * Returns : JB_ERR_OK on success, or
2742 * JB_ERR_MEMORY on out-of-memory error.
2744 *********************************************************************/
2745 jb_err server_set_cookie(struct client_state *csp, char **header)
2747 #ifdef FEATURE_COOKIE_JAR
2748 if (csp->config->jar)
2751 * Write timestamp into outbuf.
2753 * Complex because not all OSs have tm_gmtoff or
2754 * the %z field in strftime()
2756 char tempbuf[ BUFFER_SIZE ];
2760 #ifdef HAVE_LOCALTIME_R
2761 tm_now = *localtime_r(&now, &tm_now);
2763 pthread_mutex_lock(&localtime_mutex);
2764 tm_now = *localtime (&now);
2765 pthread_mutex_unlock(&localtime_mutex);
2767 tm_now = *localtime (&now);
2769 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2771 /* strlen("set-cookie: ") = 12 */
2772 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2774 #endif /* def FEATURE_COOKIE_JAR */
2776 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2778 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2779 return crumble(csp, header);
2781 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2783 /* Flag whether or not to log a message */
2786 /* A variable to store the tag we're working on */
2789 /* Skip "Set-Cookie:" (11 characters) in header */
2790 cur_tag = *header + 11;
2792 /* skip whitespace between "Set-Cookie:" and value */
2793 while (*cur_tag && ijb_isspace(*cur_tag))
2798 /* Loop through each tag in the cookie */
2802 char *next_tag = strchr(cur_tag, ';');
2803 if (next_tag != NULL)
2805 /* Skip the ';' character itself */
2808 /* skip whitespace ";" and start of tag */
2809 while (*next_tag && ijb_isspace(*next_tag))
2816 /* "Next tag" is the end of the string */
2817 next_tag = cur_tag + strlen(cur_tag);
2820 /* Is this the "Expires" tag? */
2821 if (strncmpic(cur_tag, "expires=", 8) == 0)
2823 /* Delete the tag by copying the rest of the string over it.
2824 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2825 * since the behaviour of strcpy is undefined for overlapping
2828 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2830 /* That changed the header, need to issue a log message */
2833 /* Note that the next tag has now been moved to *cur_tag,
2834 * so we do not need to update the cur_tag pointer.
2839 /* Move on to next cookie tag */
2846 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2854 #ifdef FEATURE_FORCE_LOAD
2855 /*********************************************************************
2857 * Function : strclean
2859 * Description : In-Situ-Eliminate all occurances of substring in
2863 * 1 : string = string to clean
2864 * 2 : substring = substring to eliminate
2866 * Returns : Number of eliminations
2868 *********************************************************************/
2869 int strclean(const char *string, const char *substring)
2871 int hits = 0, len = strlen(substring);
2874 while((pos = strstr(string, substring)) != NULL)
2881 while (*p++ != '\0');
2888 #endif /* def FEATURE_FORCE_LOAD */
2890 /*********************************************************************
2892 * Function : parse_header_time
2894 * Description : Transforms time inside a HTTP header into
2895 * the usual time format.
2898 * 1 : header = header to parse
2899 * 2 : tm = storage for the resulting time in seconds
2901 * Returns : Time struct containing the header time, or
2902 * NULL in case of a parsing problem.
2904 *********************************************************************/
2905 struct tm *parse_header_time(char *header, time_t *tm) {
2909 struct tm * timeptr;
2911 /* Skipping header name */
2912 timestring = strstr(header, ": ");
2913 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)