1 const char parsers_rcs[] = "$Id: parsers.c,v 1.71 2006/09/21 19:55:17 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.71 2006/09/21 19:55:17 fabiankeil
44 * Fix +hide-if-modified-since{-n}.
46 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
47 * Have hide-if-modified-since interpret the random
48 * range value as minutes instead of hours. Allows
49 * more fine-grained configuration.
51 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
52 * Always have parse_header_time return a pointer
53 * that actual makes sense, even though we currently
54 * only need it to detect problems.
56 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
57 * Added config option enable-remote-http-toggle
58 * to specify if Privoxy should recognize special
59 * headers (currently only X-Filter) to change its
60 * behaviour. Disabled by default.
62 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
63 * After filtering de-chunked instances, remove
64 * "Transfer-Encoding" header entirely instead of changing
65 * it to "Transfer-Encoding: identity", which is invalid.
66 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
68 * Don't use localtime in parse_header_time. An empty time struct
69 * is good enough, it gets overwritten by strptime anyway.
71 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
72 * Use gmtime_r if available, fallback to gmtime with mutex
73 * protection for MacOSX and use vanilla gmtime for the rest.
75 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
76 * Changed client_referrer to use the right type (size_t) for
77 * hostlenght and to shorten the temporary referrer string with
78 * '\0' instead of adding a useless line break.
80 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
81 * - Back to timegm() using GnuPG's replacement if necessary.
82 * Using mktime() and localtime() could add a on hour offset if
83 * the randomize factor was big enough to lead to a summer/wintertime
86 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
88 * - Moved randomization code into pick_from_range().
90 * - Changed parse_header_time definition.
91 * time_t isn't guaranteed to be signed and
92 * if it isn't, -1 isn't available as error code.
93 * Changed some variable types in client_if_modified_since()
94 * because of the same reason.
96 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
97 * OS/2 compilation compatibility fixups
99 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
100 * Changed include from strptime.c to strptime.h
102 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
103 * Split filter-headers{} into filter-client-headers{}
104 * and filter-server-headers{}.
105 * Added parse_header_time() to share some code.
106 * Replaced timegm() with mktime().
108 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
109 * Windows service integration
111 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
112 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
114 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
115 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
116 * with what was really the latest development (the v_3_0_branch branch)
118 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
119 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
121 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
122 * Add the ability to check jpeg images for invalid
123 * lengths of comment blocks. Defensive strategy
124 * against the exploit:
125 * Microsoft Security Bulletin MS04-028
126 * Buffer Overrun in JPEG Processing (GDI+) Could
127 * Allow Code Execution (833987)
128 * Enabled with +inspect-jpegs in actions files.
130 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
131 * Excluded text/plain objects from filtering. This fixes a
132 * couple of client-crashing, download corruption and
133 * Privoxy performance issues, whose root cause lies in
134 * web servers labelling content of unknown type as text/plain.
136 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
137 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
139 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
140 * Completing the previous change
142 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
143 * Added temporary workaround for bug in PHP < 4.2.3
145 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
146 * 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.
148 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
149 * Fix typo: supressed -> suppressed
151 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
152 * Improved cookie logging
154 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
155 * Added basic support for OPTIONS and TRACE HTTP methods:
156 * - New parser function client_max_forwards which decrements
157 * the Max-Forwards HTTP header field of OPTIONS and TRACE
158 * requests by one before forwarding
159 * - New parser function client_host which extracts the host
160 * and port information from the HTTP header field if the
161 * request URI was not absolute
162 * - Don't crumble and re-add the Host: header, but only generate
163 * and append if missing
165 * Revision 1.56 2002/05/12 15:34:22 jongfoster
166 * Fixing typo in a comment
168 * Revision 1.55 2002/05/08 16:01:07 oes
169 * Optimized add_to_iob:
170 * - Use realloc instead of malloc(), memcpy(), free()
171 * - Expand to powers of two if possible, to get
172 * O(log n) reallocs instead of O(n).
173 * - Moved check for buffer limit here from chat
174 * - Report failure via returncode
176 * Revision 1.54 2002/04/02 15:03:16 oes
177 * Tiny code cosmetics
179 * Revision 1.53 2002/03/26 22:29:55 swa
180 * we have a new homepage!
182 * Revision 1.52 2002/03/24 13:25:43 swa
183 * name change related issues
185 * Revision 1.51 2002/03/13 00:27:05 jongfoster
188 * Revision 1.50 2002/03/12 01:45:35 oes
189 * More verbose logging
191 * Revision 1.49 2002/03/09 20:03:52 jongfoster
192 * - Making various functions return int rather than size_t.
193 * (Undoing a recent change). Since size_t is unsigned on
194 * Windows, functions like read_socket that return -1 on
195 * error cannot return a size_t.
197 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
198 * crashes, and also frequently caused JB to jump to 100%
199 * CPU and stay there. (Because it thought it had just
200 * read ((unsigned)-1) == 4Gb of data...)
202 * - The signature of write_socket has changed, it now simply
203 * returns success=0/failure=nonzero.
205 * - Trying to get rid of a few warnings --with-debug on
206 * Windows, I've introduced a new type "jb_socket". This is
207 * used for the socket file descriptors. On Windows, this
208 * is SOCKET (a typedef for unsigned). Everywhere else, it's
209 * an int. The error value can't be -1 any more, so it's
210 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
211 * Windows it maps to the #define INVALID_SOCKET.)
213 * - The signature of bind_port has changed.
215 * Revision 1.48 2002/03/07 03:46:53 oes
216 * Fixed compiler warnings etc
218 * Revision 1.47 2002/02/20 23:15:13 jongfoster
219 * Parsing functions now handle out-of-memory gracefully by returning
222 * Revision 1.46 2002/01/17 21:03:47 jongfoster
223 * Moving all our URL and URL pattern parsing code to urlmatch.c.
225 * Revision 1.45 2002/01/09 14:33:03 oes
226 * Added support for localtime_r.
228 * Revision 1.44 2001/12/14 01:22:54 steudten
229 * Remove 'user:pass@' from 'proto://user:pass@host' for the
230 * new added header 'Host: ..'. (See Req ID 491818)
232 * Revision 1.43 2001/11/23 00:26:38 jongfoster
233 * Fixing two really stupid errors in my previous commit
235 * Revision 1.42 2001/11/22 21:59:30 jongfoster
236 * Adding code to handle +no-cookies-keep
238 * Revision 1.41 2001/11/05 23:43:05 steudten
239 * Add time+date to log files.
241 * Revision 1.40 2001/10/26 20:13:09 jongfoster
242 * ctype.h is needed in Windows, too.
244 * Revision 1.39 2001/10/26 17:40:04 oes
245 * Introduced get_header_value()
246 * Removed http->user_agent, csp->referrer and csp->accept_types
247 * Removed client_accept()
249 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
250 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
251 * threads to call select() simultaneously. So, it's time to do a real, live,
252 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
253 * (native). Both versions will work, but using __OS2__ offers multi-threading.
255 * Revision 1.37 2001/10/23 21:36:02 jongfoster
256 * Documenting sed()'s error behaviou (doc change only)
258 * Revision 1.36 2001/10/13 12:51:51 joergs
259 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
260 * force-load), instead crumble Host: and add it (again) in client_host_adder
261 * (in case we get a HTTP/1.0 request without Host: header and forward it to
262 * a HTTP/1.1 server/proxy).
264 * Revision 1.35 2001/10/09 22:39:21 jongfoster
265 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
268 * Revision 1.34 2001/10/07 18:50:55 oes
269 * Added server_content_encoding, renamed server_transfer_encoding
271 * Revision 1.33 2001/10/07 18:04:49 oes
272 * Changed server_http11 to server_http and its pattern to "HTTP".
273 * Additional functionality: it now saves the HTTP status into
274 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
276 * Revision 1.32 2001/10/07 15:43:28 oes
277 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
278 * client_te and client_accept_encoding_adder, triggered by the new
279 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
280 * changed to allow only identity and chunked, and the TE header is
281 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
283 * parse_http_request no longer does anything than parsing. The rewriting
284 * of http->cmd and version mangling are gone. It now also recognizes
285 * the put and delete methods and saves the url in http->url. Removed
288 * renamed content_type and content_length to have the server_ prefix
290 * server_content_type now only works if csp->content_type != CT_TABOO
292 * added server_transfer_encoding, which
293 * - Sets CT_TABOO to prohibit filtering if encoding compresses
294 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
295 * - Change from "chunked" to "identity" if body was chunked
296 * but has been de-chunked for filtering.
298 * added server_content_md5 which crunches any Content-MD5 headers
299 * if the body was modified.
301 * made server_http11 conditional on +downgrade action
303 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
305 * Revision 1.31 2001/10/05 14:25:02 oes
306 * Crumble Keep-Alive from Server
308 * Revision 1.30 2001/09/29 12:56:03 joergs
309 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
311 * Revision 1.29 2001/09/24 21:09:24 jongfoster
312 * Fixing 2 memory leaks that Guy spotted, where the paramater to
313 * enlist() was not being free()d.
315 * Revision 1.28 2001/09/22 16:32:28 jongfoster
316 * Removing unused #includes.
318 * Revision 1.27 2001/09/20 15:45:25 steudten
320 * add casting from size_t to int for printf()
321 * remove local variable shadow s2
323 * Revision 1.26 2001/09/16 17:05:14 jongfoster
324 * Removing unused #include showarg.h
326 * Revision 1.25 2001/09/16 13:21:27 jongfoster
327 * Changes to use new list functions.
329 * Revision 1.24 2001/09/13 23:05:50 jongfoster
330 * Changing the string paramater to the header parsers a "const".
332 * Revision 1.23 2001/09/12 18:08:19 steudten
334 * In parse_http_request() header rewriting miss the host value, so
335 * from http://www.mydomain.com the result was just " / " not
336 * http://www.mydomain.com/ in case we forward.
338 * Revision 1.22 2001/09/10 10:58:53 oes
339 * Silenced compiler warnings
341 * Revision 1.21 2001/07/31 14:46:00 oes
342 * - Persistant connections now suppressed
343 * - sed() no longer appends empty header to csp->headers
345 * Revision 1.20 2001/07/30 22:08:36 jongfoster
346 * Tidying up #defines:
347 * - All feature #defines are now of the form FEATURE_xxx
348 * - Permanently turned off WIN_GUI_EDIT
349 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
351 * Revision 1.19 2001/07/25 17:21:54 oes
352 * client_uagent now saves copy of User-Agent: header value
354 * Revision 1.18 2001/07/13 14:02:46 oes
355 * - Included fix to repair broken HTTP requests that
356 * don't contain a path, not even '/'.
357 * - Removed all #ifdef PCRS
358 * - content_type now always inspected and classified as
359 * text, gif or other.
360 * - formatting / comments
362 * Revision 1.17 2001/06/29 21:45:41 oes
363 * Indentation, CRLF->LF, Tab-> Space
365 * Revision 1.16 2001/06/29 13:32:42 oes
367 * - Adapted free_http_request
368 * - Removed logentry from cancelled commit
370 * Revision 1.15 2001/06/03 19:12:38 oes
371 * deleted const struct interceptors
373 * Revision 1.14 2001/06/01 18:49:17 jongfoster
374 * Replaced "list_share" with "list" - the tiny memory gain was not
375 * worth the extra complexity.
377 * Revision 1.13 2001/05/31 21:30:33 jongfoster
378 * Removed list code - it's now in list.[ch]
379 * Renamed "permission" to "action", and changed many features
380 * to use the actions file rather than the global config.
382 * Revision 1.12 2001/05/31 17:33:13 oes
386 * Revision 1.11 2001/05/29 20:11:19 joergs
387 * '/ * inside comment' warning removed.
389 * Revision 1.10 2001/05/29 09:50:24 jongfoster
390 * Unified blocklist/imagelist/permissionslist.
391 * File format is still under discussion, but the internal changes
394 * Also modified interceptor behaviour:
395 * - We now intercept all URLs beginning with one of the following
396 * prefixes (and *only* these prefixes):
398 * * http://ijbswa.sf.net/config/
399 * * http://ijbswa.sourceforge.net/config/
400 * - New interceptors "home page" - go to http://i.j.b/ to see it.
401 * - Internal changes so that intercepted and fast redirect pages
402 * are not replaced with an image.
403 * - Interceptors now have the option to send a binary page direct
404 * to the client. (i.e. ijb-send-banner uses this)
405 * - Implemented show-url-info interceptor. (Which is why I needed
406 * the above interceptors changes - a typical URL is
407 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
408 * The previous mechanism would not have intercepted that, and
409 * if it had been intercepted then it then it would have replaced
412 * Revision 1.9 2001/05/28 17:26:33 jongfoster
413 * Fixing segfault if last header was crunched.
414 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
415 * can use the cross-platform sprintf() instead.)
417 * Revision 1.8 2001/05/27 22:17:04 oes
419 * - re_process_buffer no longer writes the modified buffer
420 * to the client, which was very ugly. It now returns the
421 * buffer, which it is then written by chat.
423 * - content_length now adjusts the Content-Length: header
424 * for modified documents rather than crunch()ing it.
425 * (Length info in csp->content_length, which is 0 for
426 * unmodified documents)
428 * - For this to work, sed() is called twice when filtering.
430 * Revision 1.7 2001/05/27 13:19:06 oes
431 * Patched Joergs solution for the content-length in.
433 * Revision 1.6 2001/05/26 13:39:32 jongfoster
434 * Only crunches Content-Length header if applying RE filtering.
435 * Without this fix, Microsoft Windows Update wouldn't work.
437 * Revision 1.5 2001/05/26 00:28:36 jongfoster
438 * Automatic reloading of config file.
439 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
440 * Most of the global variables have been moved to a new
441 * struct configuration_spec, accessed through csp->config->globalname
442 * Most of the globals remaining are used by the Win32 GUI.
444 * Revision 1.4 2001/05/22 18:46:04 oes
446 * - Enabled filtering banners by size rather than URL
447 * by adding patterns that replace all standard banner
448 * sizes with the "Junkbuster" gif to the re_filterfile
450 * - Enabled filtering WebBugs by providing a pattern
451 * which kills all 1x1 images
453 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
454 * which is selected by the (nonstandard and therefore
455 * capital) letter 'U' in the option string.
456 * It causes the quantifiers to be ungreedy by default.
457 * Appending a ? turns back to greedy (!).
459 * - Added a new interceptor ijb-send-banner, which
460 * sends back the "Junkbuster" gif. Without imagelist or
461 * MSIE detection support, or if tinygif = 1, or the
462 * URL isn't recognized as an imageurl, a lame HTML
463 * explanation is sent instead.
465 * - Added new feature, which permits blocking remote
466 * script redirects and firing back a local redirect
468 * The feature is conditionally compiled, i.e. it
469 * can be disabled with --disable-fast-redirects,
470 * plus it must be activated by a "fast-redirects"
471 * line in the config file, has its own log level
472 * and of course wants to be displayed by show-proxy-args
473 * Note: Boy, all the #ifdefs in 1001 locations and
474 * all the fumbling with configure.in and acconfig.h
475 * were *way* more work than the feature itself :-(
477 * - Because a generic redirect template was needed for
478 * this, tinygif = 3 now uses the same.
480 * - Moved GIFs, and other static HTTP response templates
485 * - Removed some >400 CRs again (Jon, you really worked
488 * Revision 1.3 2001/05/20 01:21:20 jongfoster
489 * Version 2.9.4 checkin.
490 * - Merged popupfile and cookiefile, and added control over PCRS
491 * filtering, in new "permissionsfile".
492 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
493 * file error you now get a message box (in the Win32 GUI) rather
494 * than the program exiting with no explanation.
495 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
497 * - Removed tabs from "config"
498 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
499 * - Bumped up version number.
501 * Revision 1.2 2001/05/17 23:02:36 oes
502 * - Made referrer option accept 'L' as a substitute for '§'
504 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
505 * Initial import of version 2.9.3 source tree
508 *********************************************************************/
515 #include <sys/types.h>
524 #if !defined(_WIN32) && !defined(__OS2__)
533 /* jcc.h is for mutex semapores only */
534 #endif /* def OSX_DARWIN */
540 #include "jbsockets.h"
541 #include "miscutil.h"
544 #ifndef HAVE_STRPTIME
545 #include "strptime.h"
548 const char parsers_h_rcs[] = PARSERS_H_VERSION;
550 /* Fix a problem with Solaris. There should be no effect on other
552 * Solaris's isspace() is a macro which uses it's argument directly
553 * as an array index. Therefore we need to make sure that high-bit
554 * characters generate +ve values, and ideally we also want to make
555 * the argument match the declared parameter type of "int".
557 * Why did they write a character function that can't take a simple
558 * "char" argument? Doh!
560 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
561 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
564 const struct parsers client_patterns[] = {
565 { "referer:", 8, client_referrer },
566 { "user-agent:", 11, client_uagent },
567 { "ua-", 3, client_ua },
568 { "from:", 5, client_from },
569 { "cookie:", 7, client_send_cookie },
570 { "x-forwarded-for:", 16, client_x_forwarded },
571 { "Accept-Encoding:", 16, client_accept_encoding },
572 { "TE:", 3, client_te },
573 { "Host:", 5, client_host },
574 { "if-modified-since:", 18, client_if_modified_since },
575 { "Keep-Alive:", 11, crumble },
576 { "connection:", 11, crumble },
577 { "proxy-connection:", 17, crumble },
578 { "max-forwards:", 13, client_max_forwards },
579 { "Accept-Language:", 16, client_accept_language },
580 { "if-none-match:", 14, client_if_none_match },
581 { "X-Filter:", 9, client_x_filter },
582 { "*", 0, crunch_client_header },
583 { "*", 0, filter_client_header },
587 const struct parsers server_patterns[] = {
588 { "HTTP", 4, server_http },
589 { "set-cookie:", 11, server_set_cookie },
590 { "connection:", 11, crumble },
591 { "Content-Type:", 13, server_content_type },
592 { "Content-Length:", 15, server_content_length },
593 { "Content-MD5:", 12, server_content_md5 },
594 { "Content-Encoding:", 17, server_content_encoding },
595 { "Transfer-Encoding:", 18, server_transfer_coding },
596 { "Keep-Alive:", 11, crumble },
597 { "content-disposition:", 20, server_content_disposition },
598 { "Last-Modified:", 14, server_last_modified },
599 { "*", 0, crunch_server_header },
600 { "*", 0, filter_server_header },
604 const struct parsers server_patterns_light[] = {
605 { "Content-Length:", 15, server_content_length },
606 { "Transfer-Encoding:", 18, server_transfer_coding },
610 const add_header_func_ptr add_client_headers[] = {
613 client_x_forwarded_adder,
615 /* Temporarily disabled: client_accept_encoding_adder, */
616 connection_close_adder,
621 const add_header_func_ptr add_server_headers[] = {
622 connection_close_adder,
626 /*********************************************************************
628 * Function : flush_socket
630 * Description : Write any pending "buffered" content.
633 * 1 : fd = file descriptor of the socket to read
634 * 2 : csp = Current client state (buffers, headers, etc...)
636 * Returns : On success, the number of bytes written are returned (zero
637 * indicates nothing was written). On error, -1 is returned,
638 * and errno is set appropriately. If count is zero and the
639 * file descriptor refers to a regular file, 0 will be
640 * returned without causing any other effect. For a special
641 * file, the results are not portable.
643 *********************************************************************/
644 int flush_socket(jb_socket fd, struct client_state *csp)
646 struct iob *iob = csp->iob;
647 int len = iob->eod - iob->cur;
654 if (write_socket(fd, iob->cur, (size_t)len))
658 iob->eod = iob->cur = iob->buf;
664 /*********************************************************************
666 * Function : add_to_iob
668 * Description : Add content to the buffered page, expanding the
669 * buffer if necessary.
672 * 1 : csp = Current client state (buffers, headers, etc...)
673 * 2 : buf = holds the content to be added to the page
674 * 3 : n = number of bytes to be added
676 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
677 * or buffer limit reached.
679 *********************************************************************/
680 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
682 struct iob *iob = csp->iob;
683 size_t used, offset, need, want;
686 if (n <= 0) return JB_ERR_OK;
688 used = iob->eod - iob->buf;
689 offset = iob->cur - iob->buf;
693 * If the buffer can't hold the new data, extend it first.
694 * Use the next power of two if possible, else use the actual need.
696 if (need > csp->config->buffer_limit)
698 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
699 return JB_ERR_MEMORY;
702 if (need > iob->size)
704 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
706 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
710 else if (NULL != (p = (char *)realloc(iob->buf, need)))
716 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
717 return JB_ERR_MEMORY;
720 /* Update the iob pointers */
721 iob->cur = p + offset;
726 /* copy the new data into the iob buffer */
727 memcpy(iob->eod, buf, (size_t)n);
729 /* point to the end of the data */
732 /* null terminate == cheap insurance */
740 /*********************************************************************
742 * Function : get_header
744 * Description : This (odd) routine will parse the csp->iob
747 * 1 : csp = Current client state (buffers, headers, etc...)
749 * Returns : Any one of the following:
751 * 1) a pointer to a dynamically allocated string that contains a header line
752 * 2) NULL indicating that the end of the header was reached
753 * 3) "" indicating that the end of the iob was reached before finding
754 * a complete header line.
756 *********************************************************************/
757 char *get_header(struct client_state *csp)
763 if ((iob->cur == NULL)
764 || ((p = strchr(iob->cur, '\n')) == NULL))
766 return(""); /* couldn't find a complete header */
771 ret = strdup(iob->cur);
774 /* FIXME No way to handle error properly */
775 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
780 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
782 /* is this a blank line (i.e. the end of the header) ? */
794 /*********************************************************************
796 * Function : get_header_value
798 * Description : Get the value of a given header from a chained list
799 * of header lines or return NULL if no such header is
800 * present in the list.
803 * 1 : header_list = pointer to list
804 * 2 : header_name = string with name of header to look for.
805 * Trailing colon required, capitalization
808 * Returns : NULL if not found, else value of header
810 *********************************************************************/
811 char *get_header_value(const struct list *header_list, const char *header_name)
813 struct list_entry *cur_entry;
819 length = strlen(header_name);
821 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
825 if (!strncmpic(cur_entry->str, header_name, length))
828 * Found: return pointer to start of value
830 ret = (char *) (cur_entry->str + length);
831 while (*ret && ijb_isspace(*ret)) ret++;
844 /*********************************************************************
848 * Description : add, delete or modify lines in the HTTP header streams.
849 * On entry, it receives a linked list of headers space
850 * that was allocated dynamically (both the list nodes
851 * and the header contents).
853 * As a side effect it frees the space used by the original
857 * 1 : pats = list of patterns to match against headers
858 * 2 : more_headers = list of functions to add more
859 * headers (client or server)
860 * 3 : csp = Current client state (buffers, headers, etc...)
862 * Returns : Single pointer to a fully formed header, or NULL
863 * on out-of-memory error.
865 *********************************************************************/
866 char *sed(const struct parsers pats[],
867 const add_header_func_ptr more_headers[],
868 struct client_state *csp)
870 struct list_entry *p;
871 const struct parsers *v;
872 const add_header_func_ptr *f;
873 jb_err err = JB_ERR_OK;
877 * If filtering is enabled, sed is run twice,
878 * but most of the work needs to be done only once.
880 first_run = (more_headers != NULL ) ? 1 : 0;
882 if (first_run) /* Parse and print */
884 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
886 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
888 /* Header crunch()ed in previous run? -> ignore */
889 if (p->str == NULL) continue;
891 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
893 /* Does the current parser handle this header? */
894 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
896 err = v->parser(csp, (char **)&(p->str));
900 /* place any additional headers on the csp->headers list */
901 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
906 else /* Parse only */
909 * The second run is only needed if the body was modified
910 * and the content-lenght has changed.
912 if (strncmpic(csp->http->cmd, "HEAD", 4))
914 /*XXX: Code duplication*/
915 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
917 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
919 /* Header crunch()ed in previous run? -> ignore */
920 if (p->str == NULL) continue;
922 /* Does the current parser handle this header? */
923 if (strncmpic(p->str, v->str, v->len) == 0)
925 err = v->parser(csp, (char **)&(p->str));
932 if (err != JB_ERR_OK)
937 return list_to_text(csp->headers);
941 /* here begins the family of parser functions that reformat header lines */
943 /*********************************************************************
945 * Function : filter_server_header
947 * Description : Checks if server header filtering is enabled.
948 * If it is, filter_header is called to do the work.
951 * 1 : csp = Current client state (buffers, headers, etc...)
952 * 2 : header = On input, pointer to header to modify.
953 * On output, pointer to the modified header, or NULL
954 * to remove the header. This function frees the
955 * original string if necessary.
957 * Returns : JB_ERR_OK on success and always succeeds
959 *********************************************************************/
960 jb_err filter_server_header(struct client_state *csp, char **header)
962 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
964 filter_header(csp, header);
969 /*********************************************************************
971 * Function : filter_client_header
973 * Description : Checks if client header filtering is enabled.
974 * If it is, filter_header is called to do the work.
977 * 1 : csp = Current client state (buffers, headers, etc...)
978 * 2 : header = On input, pointer to header to modify.
979 * On output, pointer to the modified header, or NULL
980 * to remove the header. This function frees the
981 * original string if necessary.
983 * Returns : JB_ERR_OK on success and always succeeds
985 *********************************************************************/
986 jb_err filter_client_header(struct client_state *csp, char **header)
988 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
990 filter_header(csp, header);
995 /*********************************************************************
997 * Function : filter_header
999 * Description : Executes all text substitutions from all applying
1000 * +filter actions on the header.
1001 * Most of the code was copied from pcrs_filter_response,
1002 * including the rather short variable names
1005 * 1 : csp = Current client state (buffers, headers, etc...)
1006 * 2 : header = On input, pointer to header to modify.
1007 * On output, pointer to the modified header, or NULL
1008 * to remove the header. This function frees the
1009 * original string if necessary.
1011 * Returns : JB_ERR_OK on success and always succeeds
1013 *********************************************************************/
1014 jb_err filter_header(struct client_state *csp, char **header)
1018 size_t size = strlen(*header);
1020 char *newheader = NULL;
1023 struct file_list *fl;
1024 struct re_filterfile_spec *b;
1025 struct list_entry *filtername;
1027 int i, found_filters = 0;
1030 * Need to check the set of re_filterfiles...
1032 for (i = 0; i < MAX_AF_FILES; i++)
1045 if (0 == found_filters)
1047 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1051 for (i = 0; i < MAX_AF_FILES; i++)
1054 if ((NULL == fl) || (NULL == fl->f))
1057 * For all applying +filter actions, look if a filter by that
1058 * name exists and if yes, execute its pcrs_joblist on the
1061 for (b = fl->f; b; b = b->next)
1063 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1064 filtername ; filtername = filtername->next)
1066 if (strcmp(b->name, filtername->str) == 0)
1068 int current_hits = 0;
1070 if ( NULL == b->joblist )
1072 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1076 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1077 *header, size, b->name);
1079 /* Apply all jobs from the joblist */
1080 for (job = b->joblist; NULL != job; job = job->next)
1082 matches = pcrs_execute(job, *header, size, &newheader, &size);
1085 current_hits += matches;
1086 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1088 *header = newheader;
1090 else if ( 0 == matches )
1092 /* Filter doesn't change header */
1098 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1099 *header, b->name, pcrs_strerror(matches));
1100 if( newheader != NULL)
1102 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1107 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1108 hits += current_hits;
1116 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1124 /*********************************************************************
1126 * Function : crumble
1128 * Description : This is called if a header matches a pattern to "crunch"
1131 * 1 : csp = Current client state (buffers, headers, etc...)
1132 * 2 : header = On input, pointer to header to modify.
1133 * On output, pointer to the modified header, or NULL
1134 * to remove the header. This function frees the
1135 * original string if necessary.
1137 * Returns : JB_ERR_OK on success, or
1138 * JB_ERR_MEMORY on out-of-memory error.
1140 *********************************************************************/
1141 jb_err crumble(struct client_state *csp, char **header)
1143 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1148 /*********************************************************************
1150 * Function : crunch_server_header
1152 * Description : Crunch server header if it matches a string supplied by the
1153 * user. Called from `sed'.
1156 * 1 : csp = Current client state (buffers, headers, etc...)
1157 * 2 : header = On input, pointer to header to modify.
1158 * On output, pointer to the modified header, or NULL
1159 * to remove the header. This function frees the
1160 * original string if necessary.
1162 * Returns : JB_ERR_OK on success and always succeeds
1164 *********************************************************************/
1165 jb_err crunch_server_header(struct client_state *csp, char **header)
1167 const char *crunch_pattern;
1168 /*Is there a header to crunch*/
1170 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1172 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1174 /*Is the current header the lucky one?*/
1175 if (strstr(*header, crunch_pattern))
1177 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1184 /*********************************************************************
1186 * Function : server_content_type
1188 * Description : Set the content-type for filterable types (text/.*,
1189 * javascript and image/gif) unless filtering has been
1190 * forbidden (CT_TABOO) while parsing earlier headers.
1191 * NOTE: Since text/plain is commonly used by web servers
1192 * for files whose correct type is unknown, we don't
1193 * set CT_TEXT for it.
1196 * 1 : csp = Current client state (buffers, headers, etc...)
1197 * 2 : header = On input, pointer to header to modify.
1198 * On output, pointer to the modified header, or NULL
1199 * to remove the header. This function frees the
1200 * original string if necessary.
1202 * Returns : JB_ERR_OK on success, or
1203 * JB_ERR_MEMORY on out-of-memory error.
1205 *********************************************************************/
1206 jb_err server_content_type(struct client_state *csp, char **header)
1210 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1212 if (csp->content_type != CT_TABOO)
1214 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1215 || strstr(*header, "xml")
1216 || strstr(*header, "application/x-javascript"))
1217 csp->content_type = CT_TEXT;
1218 else if (strstr(*header, " image/gif"))
1219 csp->content_type = CT_GIF;
1220 else if (strstr(*header, " image/jpeg"))
1221 csp->content_type = CT_JPEG;
1223 csp->content_type = 0;
1226 * Are we enabling text mode by force?
1228 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1231 * Do we really have to?
1233 if (csp->content_type == CT_TEXT)
1235 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1239 csp->content_type = CT_TEXT;
1240 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1244 * Are we messing with the content type?
1246 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1249 * Make sure the user doesn't accidently
1250 * change the content type of binary documents.
1252 if (csp->content_type == CT_TEXT)
1255 *header = strdup("Content-Type: ");
1256 string_append(header, newval);
1260 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1261 return JB_ERR_MEMORY;
1263 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1267 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1268 "Enable force-text-mode if you know what you're doing.", *header);
1275 /*********************************************************************
1277 * Function : server_transfer_coding
1279 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1280 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1281 * - Remove header if body was chunked but has been
1282 * de-chunked for filtering.
1285 * 1 : csp = Current client state (buffers, headers, etc...)
1286 * 2 : header = On input, pointer to header to modify.
1287 * On output, pointer to the modified header, or NULL
1288 * to remove the header. This function frees the
1289 * original string if necessary.
1291 * Returns : JB_ERR_OK on success, or
1292 * JB_ERR_MEMORY on out-of-memory error.
1294 *********************************************************************/
1295 jb_err server_transfer_coding(struct client_state *csp, char **header)
1298 * Turn off pcrs and gif filtering if body compressed
1300 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1302 csp->content_type = CT_TABOO;
1306 * Raise flag if body chunked
1308 if (strstr(*header, "chunked"))
1310 csp->flags |= CSP_FLAG_CHUNKED;
1313 * If the body was modified, it has been de-chunked first
1314 * and the header must be removed.
1316 if (csp->flags & CSP_FLAG_MODIFIED)
1318 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1327 /*********************************************************************
1329 * Function : server_content_encoding
1331 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1334 * 1 : csp = Current client state (buffers, headers, etc...)
1335 * 2 : header = On input, pointer to header to modify.
1336 * On output, pointer to the modified header, or NULL
1337 * to remove the header. This function frees the
1338 * original string if necessary.
1340 * Returns : JB_ERR_OK on success, or
1341 * JB_ERR_MEMORY on out-of-memory error.
1343 *********************************************************************/
1344 jb_err server_content_encoding(struct client_state *csp, char **header)
1347 * Turn off pcrs and gif filtering if body compressed
1349 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1351 csp->content_type = CT_TABOO;
1359 /*********************************************************************
1361 * Function : server_content_length
1363 * Description : Adjust Content-Length header if we modified
1367 * 1 : csp = Current client state (buffers, headers, etc...)
1368 * 2 : header = On input, pointer to header to modify.
1369 * On output, pointer to the modified header, or NULL
1370 * to remove the header. This function frees the
1371 * original string if necessary.
1373 * Returns : JB_ERR_OK on success, or
1374 * JB_ERR_MEMORY on out-of-memory error.
1376 *********************************************************************/
1377 jb_err server_content_length(struct client_state *csp, char **header)
1379 if (csp->content_length != 0) /* Content length could have been modified */
1382 * XXX: Shouldn't we check if csp->content_length
1383 * is different than the original value?
1386 *header = (char *) zalloc(100);
1387 if (*header == NULL)
1389 return JB_ERR_MEMORY;
1392 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1394 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1401 /*********************************************************************
1403 * Function : server_content_md5
1405 * Description : Crumble any Content-MD5 headers if the document was
1406 * modified. FIXME: Should we re-compute instead?
1409 * 1 : csp = Current client state (buffers, headers, etc...)
1410 * 2 : header = On input, pointer to header to modify.
1411 * On output, pointer to the modified header, or NULL
1412 * to remove the header. This function frees the
1413 * original string if necessary.
1415 * Returns : JB_ERR_OK on success, or
1416 * JB_ERR_MEMORY on out-of-memory error.
1418 *********************************************************************/
1419 jb_err server_content_md5(struct client_state *csp, char **header)
1421 if (csp->flags & CSP_FLAG_MODIFIED)
1423 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1430 /*********************************************************************
1432 * Function : server_content_disposition
1434 * Description : If enabled, blocks or modifies the "content-disposition" header.
1435 * Called from `sed'.
1438 * 1 : csp = Current client state (buffers, headers, etc...)
1439 * 2 : header = On input, pointer to header to modify.
1440 * On output, pointer to the modified header, or NULL
1441 * to remove the header. This function frees the
1442 * original string if necessary.
1444 * Returns : JB_ERR_OK on success, or
1445 * JB_ERR_MEMORY on out-of-memory error.
1447 *********************************************************************/
1448 jb_err server_content_disposition(struct client_state *csp, char **header)
1453 * Are we messing with the content-disposition header?
1455 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1461 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1463 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1466 * Blocking content-disposition header
1468 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1475 * Replacing content-disposition header
1478 *header = strdup("content-disposition: ");
1479 string_append(header, newval);
1481 if (*header == NULL)
1483 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1487 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1490 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1493 /*********************************************************************
1495 * Function : server_last_modified
1497 * Description : Changes Last-Modified header to the actual date
1498 * to help hide-if-modified-since.
1499 * Called from `sed'.
1502 * 1 : csp = Current client state (buffers, headers, etc...)
1503 * 2 : header = On input, pointer to header to modify.
1504 * On output, pointer to the modified header, or NULL
1505 * to remove the header. This function frees the
1506 * original string if necessary.
1508 * Returns : JB_ERR_OK on success, or
1509 * JB_ERR_MEMORY on out-of-memory error.
1511 *********************************************************************/
1512 jb_err server_last_modified(struct client_state *csp, char **header)
1515 char buf[BUFFER_SIZE];
1518 #ifdef HAVE_GMTIME_R
1521 struct tm *timeptr = NULL;
1522 time_t now, last_modified;
1524 long int days, hours, minutes, seconds;
1527 * Are we messing with the Last-Modified header?
1529 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1535 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1537 if (0 == strcmpic(newval, "block") )
1540 * Blocking Last-Modified header. Useless but why not.
1542 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1546 else if (0 == strcmpic(newval, "reset-to-request-time"))
1549 * Setting Last-Modified Header to now.
1551 get_http_time(0, buf);
1553 *header = strdup("Last-Modified: ");
1554 string_append(header, buf);
1556 if (*header == NULL)
1558 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1562 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1565 else if (0 == strcmpic(newval, "randomize"))
1567 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1569 #ifdef HAVE_GMTIME_R
1570 timeptr = gmtime_r(&now, &gmt);
1572 pthread_mutex_lock(&gmtime_mutex);
1573 timeptr = gmtime(&now);
1574 pthread_mutex_unlock(&gmtime_mutex);
1576 timeptr = gmtime(&now);
1578 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
1580 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1585 rtime = difftime(now, last_modified);
1588 rtime = pick_from_range(rtime);
1589 last_modified += rtime;
1590 #ifdef HAVE_GMTIME_R
1591 timeptr = gmtime_r(&last_modified, &gmt);
1593 pthread_mutex_lock(&gmtime_mutex);
1594 timeptr = gmtime(&last_modified);
1595 pthread_mutex_unlock(&gmtime_mutex);
1597 timeptr = gmtime(&last_modified);
1599 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1601 *header = strdup("Last-Modified: ");
1602 string_append(header, newheader);
1604 if (*header == NULL)
1606 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
1607 return JB_ERR_MEMORY;
1610 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1612 days = rtime / (3600 * 24);
1613 hours = rtime / 3600 % 24;
1614 minutes = rtime / 60 % 60;
1615 seconds = rtime % 60;
1617 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1618 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1619 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1624 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1632 /*********************************************************************
1634 * Function : client_accept_encoding
1636 * Description : Rewrite the client's Accept-Encoding header so that
1637 * if doesn't allow compression, if the action applies.
1638 * Note: For HTTP/1.0 the absence of the header is enough.
1641 * 1 : csp = Current client state (buffers, headers, etc...)
1642 * 2 : header = On input, pointer to header to modify.
1643 * On output, pointer to the modified header, or NULL
1644 * to remove the header. This function frees the
1645 * original string if necessary.
1647 * Returns : JB_ERR_OK on success, or
1648 * JB_ERR_MEMORY on out-of-memory error.
1650 *********************************************************************/
1651 jb_err client_accept_encoding(struct client_state *csp, char **header)
1653 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1655 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1659 /* Temporarily disable the correct behaviour to
1660 * work around a PHP bug.
1662 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1664 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1665 * if (*header == NULL)
1667 * return JB_ERR_MEMORY;
1678 /*********************************************************************
1680 * Function : client_te
1682 * Description : Rewrite the client's TE header so that
1683 * if doesn't allow compression, if the action applies.
1686 * 1 : csp = Current client state (buffers, headers, etc...)
1687 * 2 : header = On input, pointer to header to modify.
1688 * On output, pointer to the modified header, or NULL
1689 * to remove the header. This function frees the
1690 * original string if necessary.
1692 * Returns : JB_ERR_OK on success, or
1693 * JB_ERR_MEMORY on out-of-memory error.
1695 *********************************************************************/
1696 jb_err client_te(struct client_state *csp, char **header)
1698 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1701 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1707 /*********************************************************************
1709 * Function : client_referrer
1711 * Description : Handle the "referer" config setting properly.
1712 * Called from `sed'.
1715 * 1 : csp = Current client state (buffers, headers, etc...)
1716 * 2 : header = On input, pointer to header to modify.
1717 * On output, pointer to the modified header, or NULL
1718 * to remove the header. This function frees the
1719 * original string if necessary.
1721 * Returns : JB_ERR_OK on success, or
1722 * JB_ERR_MEMORY on out-of-memory error.
1724 *********************************************************************/
1725 jb_err client_referrer(struct client_state *csp, char **header)
1732 #ifdef FEATURE_FORCE_LOAD
1733 /* Since the referrer can include the prefix even
1734 * if the request itself is non-forced, we must
1735 * clean it unconditionally
1737 strclean(*header, FORCE_PREFIX);
1738 #endif /* def FEATURE_FORCE_LOAD */
1741 * Are we sending referer?
1743 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1748 newval = csp->action->string[ACTION_STRING_REFERER];
1750 if ((0 != strcmpic(newval, "conditional-block")))
1754 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1759 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1762 else if (0 == strcmpic(newval, "conditional-block"))
1765 * Block referer if host has changed.
1768 if (NULL == (host = strdup(csp->http->hostport)))
1771 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1772 return JB_ERR_MEMORY;
1774 if (NULL == (referer = strdup(*header)))
1778 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1779 return JB_ERR_MEMORY;
1781 hostlenght = strlen(host);
1782 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1784 /*Shorten referer to make sure the referer is blocked
1785 *if www.example.org/www.example.com-shall-see-the-referer/
1786 *links to www.example.com/
1788 referer[hostlenght+17] = '\0';
1790 if ( 0 == strstr(referer, host)) /*Host has changed*/
1792 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1797 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1803 else if (0 != strcmpic(newval, "forge"))
1806 * We have a specific (fixed) referer we want to send.
1808 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1810 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1812 *header = strdup("Referer: ");
1813 string_append(header, newval);
1814 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1816 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1821 * Forge a referer as http://[hostname:port of REQUEST]/
1822 * to fool stupid checks for in-site links
1825 *header = strdup("Referer: http://");
1826 string_append(header, csp->http->hostport);
1827 string_append(header, "/");
1828 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1830 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1834 /*********************************************************************
1836 * Function : client_accept_language
1838 * Description : Handle the "Accept-Language" config setting properly.
1839 * 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, or
1849 * JB_ERR_MEMORY on out-of-memory error.
1851 *********************************************************************/
1852 jb_err client_accept_language(struct client_state *csp, char **header)
1857 * Are we messing with the Accept-Language?
1859 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1861 /*I don't think so*/
1865 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1867 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1870 * Blocking Accept-Language header
1872 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1879 * Replacing Accept-Language header
1882 *header = strdup("Accept-Language: ");
1883 string_append(header, newval);
1885 if (*header == NULL)
1887 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1891 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1894 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1897 /*********************************************************************
1899 * Function : crunch_client_header
1901 * Description : Crunch client header if it matches a string supplied by the
1902 * user. Called from `sed'.
1905 * 1 : csp = Current client state (buffers, headers, etc...)
1906 * 2 : header = On input, pointer to header to modify.
1907 * On output, pointer to the modified header, or NULL
1908 * to remove the header. This function frees the
1909 * original string if necessary.
1911 * Returns : JB_ERR_OK on success and always succeeds
1913 *********************************************************************/
1914 jb_err crunch_client_header(struct client_state *csp, char **header)
1916 const char *crunch_pattern;
1917 /*Is there a header to crunch*/
1919 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1921 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1923 /*Is the current header the lucky one?*/
1924 if (strstr(*header, crunch_pattern))
1926 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1934 /*********************************************************************
1936 * Function : client_uagent
1938 * Description : Handle the "user-agent" config setting properly
1939 * and remember its original value to enable browser
1940 * bug workarounds. Called from `sed'.
1943 * 1 : csp = Current client state (buffers, headers, etc...)
1944 * 2 : header = On input, pointer to header to modify.
1945 * On output, pointer to the modified header, or NULL
1946 * to remove the header. This function frees the
1947 * original string if necessary.
1949 * Returns : JB_ERR_OK on success, or
1950 * JB_ERR_MEMORY on out-of-memory error.
1952 *********************************************************************/
1953 jb_err client_uagent(struct client_state *csp, char **header)
1957 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1962 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1969 *header = strdup("User-Agent: ");
1970 string_append(header, newval);
1972 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
1974 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1977 /*********************************************************************
1979 * Function : client_ua
1981 * Description : Handle "ua-" headers properly. Called from `sed'.
1984 * 1 : csp = Current client state (buffers, headers, etc...)
1985 * 2 : header = On input, pointer to header to modify.
1986 * On output, pointer to the modified header, or NULL
1987 * to remove the header. This function frees the
1988 * original string if necessary.
1990 * Returns : JB_ERR_OK on success, or
1991 * JB_ERR_MEMORY on out-of-memory error.
1993 *********************************************************************/
1994 jb_err client_ua(struct client_state *csp, char **header)
1996 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1998 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2006 /*********************************************************************
2008 * Function : client_from
2010 * Description : Handle the "from" config setting properly.
2011 * Called from `sed'.
2014 * 1 : csp = Current client state (buffers, headers, etc...)
2015 * 2 : header = On input, pointer to header to modify.
2016 * On output, pointer to the modified header, or NULL
2017 * to remove the header. This function frees the
2018 * original string if necessary.
2020 * Returns : JB_ERR_OK on success, or
2021 * JB_ERR_MEMORY on out-of-memory error.
2023 *********************************************************************/
2024 jb_err client_from(struct client_state *csp, char **header)
2028 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2035 newval = csp->action->string[ACTION_STRING_FROM];
2038 * Are we blocking the e-mail address?
2040 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2042 log_error(LOG_LEVEL_HEADER, "crunched From!");
2046 log_error(LOG_LEVEL_HEADER, " modified");
2048 *header = strdup("From: ");
2049 string_append(header, newval);
2051 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2055 /*********************************************************************
2057 * Function : client_send_cookie
2059 * Description : Handle the "cookie" header properly. Called from `sed'.
2060 * If cookie is accepted, add it to the cookie_list,
2061 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2064 * 1 : csp = Current client state (buffers, headers, etc...)
2065 * 2 : header = On input, pointer to header to modify.
2066 * On output, pointer to the modified header, or NULL
2067 * to remove the header. This function frees the
2068 * original string if necessary.
2070 * Returns : JB_ERR_OK on success, or
2071 * JB_ERR_MEMORY on out-of-memory error.
2073 *********************************************************************/
2074 jb_err client_send_cookie(struct client_state *csp, char **header)
2076 jb_err result = JB_ERR_OK;
2078 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2080 /* strlen("cookie: ") == 8 */
2081 result = enlist(csp->cookie_list, *header + 8);
2085 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2089 * Always remove the cookie here. The cookie header
2090 * will be sent at the end of the header.
2098 /*********************************************************************
2100 * Function : client_x_forwarded
2102 * Description : Handle the "x-forwarded-for" config setting properly,
2103 * also used in the add_client_headers list. Called from `sed'.
2106 * 1 : csp = Current client state (buffers, headers, etc...)
2107 * 2 : header = On input, pointer to header to modify.
2108 * On output, pointer to the modified header, or NULL
2109 * to remove the header. This function frees the
2110 * original string if necessary.
2112 * Returns : JB_ERR_OK on success, or
2113 * JB_ERR_MEMORY on out-of-memory error.
2115 *********************************************************************/
2116 jb_err client_x_forwarded(struct client_state *csp, char **header)
2118 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2120 /* Save it so we can re-add it later */
2121 freez(csp->x_forwarded);
2122 csp->x_forwarded = *header;
2125 * Always set *header = NULL, since this information
2126 * will be sent at the end of the header.
2133 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2140 /*********************************************************************
2142 * Function : client_max_forwards
2144 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2145 * from the value of the Max-Forwards header field.
2148 * 1 : csp = Current client state (buffers, headers, etc...)
2149 * 2 : header = On input, pointer to header to modify.
2150 * On output, pointer to the modified header, or NULL
2151 * to remove the header. This function frees the
2152 * original string if necessary.
2154 * Returns : JB_ERR_OK on success, or
2155 * JB_ERR_MEMORY on out-of-memory error.
2157 *********************************************************************/
2158 jb_err client_max_forwards(struct client_state *csp, char **header)
2160 unsigned int max_forwards;
2162 if ((0 == strcmpic(csp->http->gpc, "trace"))
2163 || (0 == strcmpic(csp->http->gpc, "options")))
2165 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2167 if (max_forwards-- >= 1)
2169 sprintf(*header, "Max-Forwards: %u", max_forwards);
2170 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2174 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2183 /*********************************************************************
2185 * Function : client_host
2187 * Description : If the request URI did not contain host and
2188 * port information, parse and evaluate the Host
2191 * Also, kill ill-formed HOST: headers as sent by
2192 * Apple's iTunes software when used with a proxy.
2195 * 1 : csp = Current client state (buffers, headers, etc...)
2196 * 2 : header = On input, pointer to header to modify.
2197 * On output, pointer to the modified header, or NULL
2198 * to remove the header. This function frees the
2199 * original string if necessary.
2201 * Returns : JB_ERR_OK on success, or
2202 * JB_ERR_MEMORY on out-of-memory error.
2204 *********************************************************************/
2205 jb_err client_host(struct client_state *csp, char **header)
2210 * If the header field name is all upper-case, chances are that it's
2211 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2212 * not a problem -- they are regenerated later.
2214 if ((*header)[1] == 'O')
2216 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2221 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2222 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2225 if (NULL == (p = strdup((*header)+6)))
2227 return JB_ERR_MEMORY;
2230 if (NULL == (q = strdup(p)))
2233 return JB_ERR_MEMORY;
2236 freez(csp->http->hostport);
2237 csp->http->hostport = p;
2238 freez(csp->http->host);
2239 csp->http->host = q;
2240 q = strchr(csp->http->host, ':');
2243 /* Terminate hostname and evaluate port string */
2245 csp->http->port = atoi(q);
2249 csp->http->port = csp->http->ssl ? 443 : 80;
2252 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2253 csp->http->hostport, csp->http->host, csp->http->port);
2259 /*********************************************************************
2261 * Function : client_if_modified_since
2263 * Description : Remove or modify the If-Modified-Since header.
2266 * 1 : csp = Current client state (buffers, headers, etc...)
2267 * 2 : header = On input, pointer to header to modify.
2268 * On output, pointer to the modified header, or NULL
2269 * to remove the header. This function frees the
2270 * original string if necessary.
2272 * Returns : JB_ERR_OK on success, or
2273 * JB_ERR_MEMORY on out-of-memory error.
2275 *********************************************************************/
2276 jb_err client_if_modified_since(struct client_state *csp, char **header)
2279 #ifdef HAVE_GMTIME_R
2282 struct tm *timeptr = NULL;
2286 long int hours, minutes, seconds;
2290 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2293 * The client got an error message because of a temporary problem,
2294 * the problem is gone and the client now tries to revalidate our
2295 * error message on the real server. The revalidation would always
2296 * end with the transmission of the whole document and there is
2297 * no need to expose the bogus If-Modified-Since header.
2299 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2302 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2304 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2306 if ((0 == strcmpic(newval, "block")))
2308 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2311 else /* add random value */
2313 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2315 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2320 rtime = strtol(newval, &endptr, 0);
2323 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
2324 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
2331 rtime = pick_from_range(rtime);
2335 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2338 tm += rtime * (negative ? -1 : 1);
2339 #ifdef HAVE_GMTIME_R
2340 timeptr = gmtime_r(&tm, &gmt);
2342 pthread_mutex_lock(&gmtime_mutex);
2343 timeptr = gmtime(&tm);
2344 pthread_mutex_unlock(&gmtime_mutex);
2346 timeptr = gmtime(&tm);
2348 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2351 *header = strdup("If-Modified-Since: ");
2352 string_append(header, newheader);
2354 if (*header == NULL)
2356 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2357 return JB_ERR_MEMORY;
2360 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2362 hours = rtime / 3600;
2363 minutes = rtime / 60 % 60;
2364 seconds = rtime % 60;
2366 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2367 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2368 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2377 /*********************************************************************
2379 * Function : client_if_none_match
2381 * Description : Remove the If-None-Match header.
2384 * 1 : csp = Current client state (buffers, headers, etc...)
2385 * 2 : header = On input, pointer to header to modify.
2386 * On output, pointer to the modified header, or NULL
2387 * to remove the header. This function frees the
2388 * original string if necessary.
2390 * Returns : JB_ERR_OK on success, or
2391 * JB_ERR_MEMORY on out-of-memory error.
2393 *********************************************************************/
2394 jb_err client_if_none_match(struct client_state *csp, char **header)
2396 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2398 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2405 /*********************************************************************
2407 * Function : client_x_filter
2409 * Description : Disables filtering if the client set "X-Filter: No".
2410 * Called from `sed'.
2413 * 1 : csp = Current client state (buffers, headers, etc...)
2414 * 2 : header = On input, pointer to header to modify.
2415 * On output, pointer to the modified header, or NULL
2416 * to remove the header. This function frees the
2417 * original string if necessary.
2419 * Returns : JB_ERR_OK on success
2421 *********************************************************************/
2422 jb_err client_x_filter(struct client_state *csp, char **header)
2424 if ( 0 == strcmpic(*header, "X-Filter: No"))
2426 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
2428 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
2432 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2434 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to fetch without filtering!");
2438 csp->content_type = CT_TABOO;
2439 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
2441 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2448 /* the following functions add headers directly to the header list */
2450 /*********************************************************************
2452 * Function : client_host_adder
2454 * Description : Adds the Host: header field if it is missing.
2455 * Called from `sed'.
2458 * 1 : csp = Current client state (buffers, headers, etc...)
2460 * Returns : JB_ERR_OK on success, or
2461 * JB_ERR_MEMORY on out-of-memory error.
2463 *********************************************************************/
2464 jb_err client_host_adder(struct client_state *csp)
2469 if ( !csp->http->hostport || !*(csp->http->hostport))
2475 * remove 'user:pass@' from 'proto://user:pass@host'
2477 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2483 p = csp->http->hostport;
2486 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2487 err = enlist_unique_header(csp->headers, "Host", p);
2493 /*********************************************************************
2495 * Function : client_cookie_adder
2497 * Description : Used in the add_client_headers list. Called from `sed'.
2500 * 1 : csp = Current client state (buffers, headers, etc...)
2502 * Returns : JB_ERR_OK on success, or
2503 * JB_ERR_MEMORY on out-of-memory error.
2505 *********************************************************************/
2506 jb_err client_cookie_adder(struct client_state *csp)
2508 struct list_entry *lst;
2510 struct list_entry *list1 = csp->cookie_list->first;
2511 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2512 int first_cookie = 1;
2515 if ((list1 == NULL) && (list2 == NULL))
2521 tmp = strdup("Cookie: ");
2523 for (lst = list1; lst ; lst = lst->next)
2531 string_append(&tmp, "; ");
2533 string_append(&tmp, lst->str);
2536 for (lst = list2; lst ; lst = lst->next)
2544 string_append(&tmp, "; ");
2546 string_join(&tmp, cookie_encode(lst->str));
2551 return JB_ERR_MEMORY;
2554 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2555 err = enlist(csp->headers, tmp);
2561 /*********************************************************************
2563 * Function : client_accept_encoding_adder
2565 * Description : Add an Accept-Encoding header to the client's request
2566 * that disables compression if the action applies, and
2567 * the header is not already there. Called from `sed'.
2568 * Note: For HTTP/1.0, the absence of the header is enough.
2571 * 1 : csp = Current client state (buffers, headers, etc...)
2573 * Returns : JB_ERR_OK on success, or
2574 * JB_ERR_MEMORY on out-of-memory error.
2576 *********************************************************************/
2577 jb_err client_accept_encoding_adder(struct client_state *csp)
2579 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2580 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2582 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2589 /*********************************************************************
2591 * Function : client_xtra_adder
2593 * Description : Used in the add_client_headers list. Called from `sed'.
2596 * 1 : csp = Current client state (buffers, headers, etc...)
2598 * Returns : JB_ERR_OK on success, or
2599 * JB_ERR_MEMORY on out-of-memory error.
2601 *********************************************************************/
2602 jb_err client_xtra_adder(struct client_state *csp)
2604 struct list_entry *lst;
2607 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2608 lst ; lst = lst->next)
2610 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2611 err = enlist(csp->headers, lst->str);
2623 /*********************************************************************
2625 * Function : client_x_forwarded_adder
2627 * Description : Used in the add_client_headers list. Called from `sed'.
2630 * 1 : csp = Current client state (buffers, headers, etc...)
2632 * Returns : JB_ERR_OK on success, or
2633 * JB_ERR_MEMORY on out-of-memory error.
2635 *********************************************************************/
2636 jb_err client_x_forwarded_adder(struct client_state *csp)
2641 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2646 if (csp->x_forwarded)
2648 p = strdup(csp->x_forwarded);
2649 string_append(&p, ", ");
2653 p = strdup("X-Forwarded-For: ");
2655 string_append(&p, csp->ip_addr_str);
2659 return JB_ERR_MEMORY;
2662 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2663 err = enlist(csp->headers, p);
2670 /*********************************************************************
2672 * Function : connection_close_adder
2674 * Description : Adds a "Connection: close" header to csp->headers
2675 * as a temporary fix for the needed but missing HTTP/1.1
2676 * support. Called from `sed'.
2677 * FIXME: This whole function shouldn't be neccessary!
2680 * 1 : csp = Current client state (buffers, headers, etc...)
2682 * Returns : JB_ERR_OK on success, or
2683 * JB_ERR_MEMORY on out-of-memory error.
2685 *********************************************************************/
2686 jb_err connection_close_adder(struct client_state *csp)
2688 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2689 return enlist(csp->headers, "Connection: close");
2693 /*********************************************************************
2695 * Function : server_http
2697 * Description : - Save the HTTP Status into csp->http->status
2698 * - Set CT_TABOO to prevent filtering if the answer
2699 * is a partial range (HTTP status 206)
2700 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2704 * 1 : csp = Current client state (buffers, headers, etc...)
2705 * 2 : header = On input, pointer to header to modify.
2706 * On output, pointer to the modified header, or NULL
2707 * to remove the header. This function frees the
2708 * original string if necessary.
2710 * Returns : JB_ERR_OK on success, or
2711 * JB_ERR_MEMORY on out-of-memory error.
2713 *********************************************************************/
2714 jb_err server_http(struct client_state *csp, char **header)
2716 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2717 if (csp->http->status == 206)
2719 csp->content_type = CT_TABOO;
2722 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2725 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2732 /*********************************************************************
2734 * Function : server_set_cookie
2736 * Description : Handle the server "cookie" header properly.
2737 * Log cookie to the jar file. Then "crunch" it,
2738 * or accept it. Called from `sed'.
2741 * 1 : csp = Current client state (buffers, headers, etc...)
2742 * 2 : header = On input, pointer to header to modify.
2743 * On output, pointer to the modified header, or NULL
2744 * to remove the header. This function frees the
2745 * original string if necessary.
2747 * Returns : JB_ERR_OK on success, or
2748 * JB_ERR_MEMORY on out-of-memory error.
2750 *********************************************************************/
2751 jb_err server_set_cookie(struct client_state *csp, char **header)
2753 #ifdef FEATURE_COOKIE_JAR
2754 if (csp->config->jar)
2757 * Write timestamp into outbuf.
2759 * Complex because not all OSs have tm_gmtoff or
2760 * the %z field in strftime()
2762 char tempbuf[ BUFFER_SIZE ];
2766 #ifdef HAVE_LOCALTIME_R
2767 tm_now = *localtime_r(&now, &tm_now);
2769 pthread_mutex_lock(&localtime_mutex);
2770 tm_now = *localtime (&now);
2771 pthread_mutex_unlock(&localtime_mutex);
2773 tm_now = *localtime (&now);
2775 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2777 /* strlen("set-cookie: ") = 12 */
2778 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2780 #endif /* def FEATURE_COOKIE_JAR */
2782 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2784 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2785 return crumble(csp, header);
2787 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2789 /* Flag whether or not to log a message */
2792 /* A variable to store the tag we're working on */
2795 /* Skip "Set-Cookie:" (11 characters) in header */
2796 cur_tag = *header + 11;
2798 /* skip whitespace between "Set-Cookie:" and value */
2799 while (*cur_tag && ijb_isspace(*cur_tag))
2804 /* Loop through each tag in the cookie */
2808 char *next_tag = strchr(cur_tag, ';');
2809 if (next_tag != NULL)
2811 /* Skip the ';' character itself */
2814 /* skip whitespace ";" and start of tag */
2815 while (*next_tag && ijb_isspace(*next_tag))
2822 /* "Next tag" is the end of the string */
2823 next_tag = cur_tag + strlen(cur_tag);
2826 /* Is this the "Expires" tag? */
2827 if (strncmpic(cur_tag, "expires=", 8) == 0)
2829 /* Delete the tag by copying the rest of the string over it.
2830 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2831 * since the behaviour of strcpy is undefined for overlapping
2834 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2836 /* That changed the header, need to issue a log message */
2839 /* Note that the next tag has now been moved to *cur_tag,
2840 * so we do not need to update the cur_tag pointer.
2845 /* Move on to next cookie tag */
2852 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2860 #ifdef FEATURE_FORCE_LOAD
2861 /*********************************************************************
2863 * Function : strclean
2865 * Description : In-Situ-Eliminate all occurances of substring in
2869 * 1 : string = string to clean
2870 * 2 : substring = substring to eliminate
2872 * Returns : Number of eliminations
2874 *********************************************************************/
2875 int strclean(const char *string, const char *substring)
2877 int hits = 0, len = strlen(substring);
2880 while((pos = strstr(string, substring)) != NULL)
2887 while (*p++ != '\0');
2894 #endif /* def FEATURE_FORCE_LOAD */
2896 /*********************************************************************
2898 * Function : parse_header_time
2900 * Description : Transforms time inside a HTTP header into
2901 * the usual time format.
2904 * 1 : header = header to parse
2905 * 2 : tm = storage for the resulting time in seconds
2907 * Returns : Time struct containing the header time, or
2908 * NULL in case of a parsing problem.
2910 *********************************************************************/
2911 struct tm *parse_header_time(char *header, time_t *tm) {
2915 struct tm * timeptr;
2917 /* Skipping header name */
2918 timestring = strstr(header, ": ");
2919 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)