1 const char parsers_rcs[] = "$Id: parsers.c,v 1.66 2006/09/03 19:38:28 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.66 2006/09/03 19:38:28 fabiankeil
44 * Use gmtime_r if available, fallback to gmtime with mutex
45 * protection for MacOSX and use vanilla gmtime for the rest.
47 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
48 * Changed client_referrer to use the right type (size_t) for
49 * hostlenght and to shorten the temporary referrer string with
50 * '\0' instead of adding a useless line break.
52 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
53 * - Back to timegm() using GnuPG's replacement if necessary.
54 * Using mktime() and localtime() could add a on hour offset if
55 * the randomize factor was big enough to lead to a summer/wintertime
58 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
60 * - Moved randomization code into pick_from_range().
62 * - Changed parse_header_time definition.
63 * time_t isn't guaranteed to be signed and
64 * if it isn't, -1 isn't available as error code.
65 * Changed some variable types in client_if_modified_since()
66 * because of the same reason.
68 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
69 * OS/2 compilation compatibility fixups
71 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
72 * Changed include from strptime.c to strptime.h
74 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
75 * Split filter-headers{} into filter-client-headers{}
76 * and filter-server-headers{}.
77 * Added parse_header_time() to share some code.
78 * Replaced timegm() with mktime().
80 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
81 * Windows service integration
83 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
84 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
86 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
87 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
88 * with what was really the latest development (the v_3_0_branch branch)
90 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
91 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
93 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
94 * Add the ability to check jpeg images for invalid
95 * lengths of comment blocks. Defensive strategy
96 * against the exploit:
97 * Microsoft Security Bulletin MS04-028
98 * Buffer Overrun in JPEG Processing (GDI+) Could
99 * Allow Code Execution (833987)
100 * Enabled with +inspect-jpegs in actions files.
102 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
103 * Excluded text/plain objects from filtering. This fixes a
104 * couple of client-crashing, download corruption and
105 * Privoxy performance issues, whose root cause lies in
106 * web servers labelling content of unknown type as text/plain.
108 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
109 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
111 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
112 * Completing the previous change
114 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
115 * Added temporary workaround for bug in PHP < 4.2.3
117 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
118 * 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.
120 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
121 * Fix typo: supressed -> suppressed
123 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
124 * Improved cookie logging
126 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
127 * Added basic support for OPTIONS and TRACE HTTP methods:
128 * - New parser function client_max_forwards which decrements
129 * the Max-Forwards HTTP header field of OPTIONS and TRACE
130 * requests by one before forwarding
131 * - New parser function client_host which extracts the host
132 * and port information from the HTTP header field if the
133 * request URI was not absolute
134 * - Don't crumble and re-add the Host: header, but only generate
135 * and append if missing
137 * Revision 1.56 2002/05/12 15:34:22 jongfoster
138 * Fixing typo in a comment
140 * Revision 1.55 2002/05/08 16:01:07 oes
141 * Optimized add_to_iob:
142 * - Use realloc instead of malloc(), memcpy(), free()
143 * - Expand to powers of two if possible, to get
144 * O(log n) reallocs instead of O(n).
145 * - Moved check for buffer limit here from chat
146 * - Report failure via returncode
148 * Revision 1.54 2002/04/02 15:03:16 oes
149 * Tiny code cosmetics
151 * Revision 1.53 2002/03/26 22:29:55 swa
152 * we have a new homepage!
154 * Revision 1.52 2002/03/24 13:25:43 swa
155 * name change related issues
157 * Revision 1.51 2002/03/13 00:27:05 jongfoster
160 * Revision 1.50 2002/03/12 01:45:35 oes
161 * More verbose logging
163 * Revision 1.49 2002/03/09 20:03:52 jongfoster
164 * - Making various functions return int rather than size_t.
165 * (Undoing a recent change). Since size_t is unsigned on
166 * Windows, functions like read_socket that return -1 on
167 * error cannot return a size_t.
169 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
170 * crashes, and also frequently caused JB to jump to 100%
171 * CPU and stay there. (Because it thought it had just
172 * read ((unsigned)-1) == 4Gb of data...)
174 * - The signature of write_socket has changed, it now simply
175 * returns success=0/failure=nonzero.
177 * - Trying to get rid of a few warnings --with-debug on
178 * Windows, I've introduced a new type "jb_socket". This is
179 * used for the socket file descriptors. On Windows, this
180 * is SOCKET (a typedef for unsigned). Everywhere else, it's
181 * an int. The error value can't be -1 any more, so it's
182 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
183 * Windows it maps to the #define INVALID_SOCKET.)
185 * - The signature of bind_port has changed.
187 * Revision 1.48 2002/03/07 03:46:53 oes
188 * Fixed compiler warnings etc
190 * Revision 1.47 2002/02/20 23:15:13 jongfoster
191 * Parsing functions now handle out-of-memory gracefully by returning
194 * Revision 1.46 2002/01/17 21:03:47 jongfoster
195 * Moving all our URL and URL pattern parsing code to urlmatch.c.
197 * Revision 1.45 2002/01/09 14:33:03 oes
198 * Added support for localtime_r.
200 * Revision 1.44 2001/12/14 01:22:54 steudten
201 * Remove 'user:pass@' from 'proto://user:pass@host' for the
202 * new added header 'Host: ..'. (See Req ID 491818)
204 * Revision 1.43 2001/11/23 00:26:38 jongfoster
205 * Fixing two really stupid errors in my previous commit
207 * Revision 1.42 2001/11/22 21:59:30 jongfoster
208 * Adding code to handle +no-cookies-keep
210 * Revision 1.41 2001/11/05 23:43:05 steudten
211 * Add time+date to log files.
213 * Revision 1.40 2001/10/26 20:13:09 jongfoster
214 * ctype.h is needed in Windows, too.
216 * Revision 1.39 2001/10/26 17:40:04 oes
217 * Introduced get_header_value()
218 * Removed http->user_agent, csp->referrer and csp->accept_types
219 * Removed client_accept()
221 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
222 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
223 * threads to call select() simultaneously. So, it's time to do a real, live,
224 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
225 * (native). Both versions will work, but using __OS2__ offers multi-threading.
227 * Revision 1.37 2001/10/23 21:36:02 jongfoster
228 * Documenting sed()'s error behaviou (doc change only)
230 * Revision 1.36 2001/10/13 12:51:51 joergs
231 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
232 * force-load), instead crumble Host: and add it (again) in client_host_adder
233 * (in case we get a HTTP/1.0 request without Host: header and forward it to
234 * a HTTP/1.1 server/proxy).
236 * Revision 1.35 2001/10/09 22:39:21 jongfoster
237 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
240 * Revision 1.34 2001/10/07 18:50:55 oes
241 * Added server_content_encoding, renamed server_transfer_encoding
243 * Revision 1.33 2001/10/07 18:04:49 oes
244 * Changed server_http11 to server_http and its pattern to "HTTP".
245 * Additional functionality: it now saves the HTTP status into
246 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
248 * Revision 1.32 2001/10/07 15:43:28 oes
249 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
250 * client_te and client_accept_encoding_adder, triggered by the new
251 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
252 * changed to allow only identity and chunked, and the TE header is
253 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
255 * parse_http_request no longer does anything than parsing. The rewriting
256 * of http->cmd and version mangling are gone. It now also recognizes
257 * the put and delete methods and saves the url in http->url. Removed
260 * renamed content_type and content_length to have the server_ prefix
262 * server_content_type now only works if csp->content_type != CT_TABOO
264 * added server_transfer_encoding, which
265 * - Sets CT_TABOO to prohibit filtering if encoding compresses
266 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
267 * - Change from "chunked" to "identity" if body was chunked
268 * but has been de-chunked for filtering.
270 * added server_content_md5 which crunches any Content-MD5 headers
271 * if the body was modified.
273 * made server_http11 conditional on +downgrade action
275 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
277 * Revision 1.31 2001/10/05 14:25:02 oes
278 * Crumble Keep-Alive from Server
280 * Revision 1.30 2001/09/29 12:56:03 joergs
281 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
283 * Revision 1.29 2001/09/24 21:09:24 jongfoster
284 * Fixing 2 memory leaks that Guy spotted, where the paramater to
285 * enlist() was not being free()d.
287 * Revision 1.28 2001/09/22 16:32:28 jongfoster
288 * Removing unused #includes.
290 * Revision 1.27 2001/09/20 15:45:25 steudten
292 * add casting from size_t to int for printf()
293 * remove local variable shadow s2
295 * Revision 1.26 2001/09/16 17:05:14 jongfoster
296 * Removing unused #include showarg.h
298 * Revision 1.25 2001/09/16 13:21:27 jongfoster
299 * Changes to use new list functions.
301 * Revision 1.24 2001/09/13 23:05:50 jongfoster
302 * Changing the string paramater to the header parsers a "const".
304 * Revision 1.23 2001/09/12 18:08:19 steudten
306 * In parse_http_request() header rewriting miss the host value, so
307 * from http://www.mydomain.com the result was just " / " not
308 * http://www.mydomain.com/ in case we forward.
310 * Revision 1.22 2001/09/10 10:58:53 oes
311 * Silenced compiler warnings
313 * Revision 1.21 2001/07/31 14:46:00 oes
314 * - Persistant connections now suppressed
315 * - sed() no longer appends empty header to csp->headers
317 * Revision 1.20 2001/07/30 22:08:36 jongfoster
318 * Tidying up #defines:
319 * - All feature #defines are now of the form FEATURE_xxx
320 * - Permanently turned off WIN_GUI_EDIT
321 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
323 * Revision 1.19 2001/07/25 17:21:54 oes
324 * client_uagent now saves copy of User-Agent: header value
326 * Revision 1.18 2001/07/13 14:02:46 oes
327 * - Included fix to repair broken HTTP requests that
328 * don't contain a path, not even '/'.
329 * - Removed all #ifdef PCRS
330 * - content_type now always inspected and classified as
331 * text, gif or other.
332 * - formatting / comments
334 * Revision 1.17 2001/06/29 21:45:41 oes
335 * Indentation, CRLF->LF, Tab-> Space
337 * Revision 1.16 2001/06/29 13:32:42 oes
339 * - Adapted free_http_request
340 * - Removed logentry from cancelled commit
342 * Revision 1.15 2001/06/03 19:12:38 oes
343 * deleted const struct interceptors
345 * Revision 1.14 2001/06/01 18:49:17 jongfoster
346 * Replaced "list_share" with "list" - the tiny memory gain was not
347 * worth the extra complexity.
349 * Revision 1.13 2001/05/31 21:30:33 jongfoster
350 * Removed list code - it's now in list.[ch]
351 * Renamed "permission" to "action", and changed many features
352 * to use the actions file rather than the global config.
354 * Revision 1.12 2001/05/31 17:33:13 oes
358 * Revision 1.11 2001/05/29 20:11:19 joergs
359 * '/ * inside comment' warning removed.
361 * Revision 1.10 2001/05/29 09:50:24 jongfoster
362 * Unified blocklist/imagelist/permissionslist.
363 * File format is still under discussion, but the internal changes
366 * Also modified interceptor behaviour:
367 * - We now intercept all URLs beginning with one of the following
368 * prefixes (and *only* these prefixes):
370 * * http://ijbswa.sf.net/config/
371 * * http://ijbswa.sourceforge.net/config/
372 * - New interceptors "home page" - go to http://i.j.b/ to see it.
373 * - Internal changes so that intercepted and fast redirect pages
374 * are not replaced with an image.
375 * - Interceptors now have the option to send a binary page direct
376 * to the client. (i.e. ijb-send-banner uses this)
377 * - Implemented show-url-info interceptor. (Which is why I needed
378 * the above interceptors changes - a typical URL is
379 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
380 * The previous mechanism would not have intercepted that, and
381 * if it had been intercepted then it then it would have replaced
384 * Revision 1.9 2001/05/28 17:26:33 jongfoster
385 * Fixing segfault if last header was crunched.
386 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
387 * can use the cross-platform sprintf() instead.)
389 * Revision 1.8 2001/05/27 22:17:04 oes
391 * - re_process_buffer no longer writes the modified buffer
392 * to the client, which was very ugly. It now returns the
393 * buffer, which it is then written by chat.
395 * - content_length now adjusts the Content-Length: header
396 * for modified documents rather than crunch()ing it.
397 * (Length info in csp->content_length, which is 0 for
398 * unmodified documents)
400 * - For this to work, sed() is called twice when filtering.
402 * Revision 1.7 2001/05/27 13:19:06 oes
403 * Patched Joergs solution for the content-length in.
405 * Revision 1.6 2001/05/26 13:39:32 jongfoster
406 * Only crunches Content-Length header if applying RE filtering.
407 * Without this fix, Microsoft Windows Update wouldn't work.
409 * Revision 1.5 2001/05/26 00:28:36 jongfoster
410 * Automatic reloading of config file.
411 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
412 * Most of the global variables have been moved to a new
413 * struct configuration_spec, accessed through csp->config->globalname
414 * Most of the globals remaining are used by the Win32 GUI.
416 * Revision 1.4 2001/05/22 18:46:04 oes
418 * - Enabled filtering banners by size rather than URL
419 * by adding patterns that replace all standard banner
420 * sizes with the "Junkbuster" gif to the re_filterfile
422 * - Enabled filtering WebBugs by providing a pattern
423 * which kills all 1x1 images
425 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
426 * which is selected by the (nonstandard and therefore
427 * capital) letter 'U' in the option string.
428 * It causes the quantifiers to be ungreedy by default.
429 * Appending a ? turns back to greedy (!).
431 * - Added a new interceptor ijb-send-banner, which
432 * sends back the "Junkbuster" gif. Without imagelist or
433 * MSIE detection support, or if tinygif = 1, or the
434 * URL isn't recognized as an imageurl, a lame HTML
435 * explanation is sent instead.
437 * - Added new feature, which permits blocking remote
438 * script redirects and firing back a local redirect
440 * The feature is conditionally compiled, i.e. it
441 * can be disabled with --disable-fast-redirects,
442 * plus it must be activated by a "fast-redirects"
443 * line in the config file, has its own log level
444 * and of course wants to be displayed by show-proxy-args
445 * Note: Boy, all the #ifdefs in 1001 locations and
446 * all the fumbling with configure.in and acconfig.h
447 * were *way* more work than the feature itself :-(
449 * - Because a generic redirect template was needed for
450 * this, tinygif = 3 now uses the same.
452 * - Moved GIFs, and other static HTTP response templates
457 * - Removed some >400 CRs again (Jon, you really worked
460 * Revision 1.3 2001/05/20 01:21:20 jongfoster
461 * Version 2.9.4 checkin.
462 * - Merged popupfile and cookiefile, and added control over PCRS
463 * filtering, in new "permissionsfile".
464 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
465 * file error you now get a message box (in the Win32 GUI) rather
466 * than the program exiting with no explanation.
467 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
469 * - Removed tabs from "config"
470 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
471 * - Bumped up version number.
473 * Revision 1.2 2001/05/17 23:02:36 oes
474 * - Made referrer option accept 'L' as a substitute for '§'
476 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
477 * Initial import of version 2.9.3 source tree
480 *********************************************************************/
487 #include <sys/types.h>
496 #if !defined(_WIN32) && !defined(__OS2__)
505 /* jcc.h is for mutex semapores only */
506 #endif /* def OSX_DARWIN */
512 #include "jbsockets.h"
513 #include "miscutil.h"
516 #ifndef HAVE_STRPTIME
517 #include "strptime.h"
520 const char parsers_h_rcs[] = PARSERS_H_VERSION;
522 /* Fix a problem with Solaris. There should be no effect on other
524 * Solaris's isspace() is a macro which uses it's argument directly
525 * as an array index. Therefore we need to make sure that high-bit
526 * characters generate +ve values, and ideally we also want to make
527 * the argument match the declared parameter type of "int".
529 * Why did they write a character function that can't take a simple
530 * "char" argument? Doh!
532 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
533 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
536 const struct parsers client_patterns[] = {
537 { "referer:", 8, client_referrer },
538 { "user-agent:", 11, client_uagent },
539 { "ua-", 3, client_ua },
540 { "from:", 5, client_from },
541 { "cookie:", 7, client_send_cookie },
542 { "x-forwarded-for:", 16, client_x_forwarded },
543 { "Accept-Encoding:", 16, client_accept_encoding },
544 { "TE:", 3, client_te },
545 { "Host:", 5, client_host },
546 { "if-modified-since:", 18, client_if_modified_since },
547 { "Keep-Alive:", 11, crumble },
548 { "connection:", 11, crumble },
549 { "proxy-connection:", 17, crumble },
550 { "max-forwards:", 13, client_max_forwards },
551 { "Accept-Language:", 16, client_accept_language },
552 { "if-none-match:", 14, client_if_none_match },
553 { "X-Filter:", 9, client_x_filter },
554 { "*", 0, crunch_client_header },
555 { "*", 0, filter_client_header },
559 const struct parsers server_patterns[] = {
560 { "HTTP", 4, server_http },
561 { "set-cookie:", 11, server_set_cookie },
562 { "connection:", 11, crumble },
563 { "Content-Type:", 13, server_content_type },
564 { "Content-Length:", 15, server_content_length },
565 { "Content-MD5:", 12, server_content_md5 },
566 { "Content-Encoding:", 17, server_content_encoding },
567 { "Transfer-Encoding:", 18, server_transfer_coding },
568 { "Keep-Alive:", 11, crumble },
569 { "content-disposition:", 20, server_content_disposition },
570 { "Last-Modified:", 14, server_last_modified },
571 { "*", 0, crunch_server_header },
572 { "*", 0, filter_server_header },
576 const struct parsers server_patterns_light[] = {
577 { "Content-Length:", 15, server_content_length },
578 { "Transfer-Encoding:", 18, server_transfer_coding },
582 const add_header_func_ptr add_client_headers[] = {
585 client_x_forwarded_adder,
587 /* Temporarily disabled: client_accept_encoding_adder, */
588 connection_close_adder,
593 const add_header_func_ptr add_server_headers[] = {
594 connection_close_adder,
598 /*********************************************************************
600 * Function : flush_socket
602 * Description : Write any pending "buffered" content.
605 * 1 : fd = file descriptor of the socket to read
606 * 2 : csp = Current client state (buffers, headers, etc...)
608 * Returns : On success, the number of bytes written are returned (zero
609 * indicates nothing was written). On error, -1 is returned,
610 * and errno is set appropriately. If count is zero and the
611 * file descriptor refers to a regular file, 0 will be
612 * returned without causing any other effect. For a special
613 * file, the results are not portable.
615 *********************************************************************/
616 int flush_socket(jb_socket fd, struct client_state *csp)
618 struct iob *iob = csp->iob;
619 int len = iob->eod - iob->cur;
626 if (write_socket(fd, iob->cur, (size_t)len))
630 iob->eod = iob->cur = iob->buf;
636 /*********************************************************************
638 * Function : add_to_iob
640 * Description : Add content to the buffered page, expanding the
641 * buffer if necessary.
644 * 1 : csp = Current client state (buffers, headers, etc...)
645 * 2 : buf = holds the content to be added to the page
646 * 3 : n = number of bytes to be added
648 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
649 * or buffer limit reached.
651 *********************************************************************/
652 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
654 struct iob *iob = csp->iob;
655 size_t used, offset, need, want;
658 if (n <= 0) return JB_ERR_OK;
660 used = iob->eod - iob->buf;
661 offset = iob->cur - iob->buf;
665 * If the buffer can't hold the new data, extend it first.
666 * Use the next power of two if possible, else use the actual need.
668 if (need > csp->config->buffer_limit)
670 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
671 return JB_ERR_MEMORY;
674 if (need > iob->size)
676 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
678 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
682 else if (NULL != (p = (char *)realloc(iob->buf, need)))
688 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
689 return JB_ERR_MEMORY;
692 /* Update the iob pointers */
693 iob->cur = p + offset;
698 /* copy the new data into the iob buffer */
699 memcpy(iob->eod, buf, (size_t)n);
701 /* point to the end of the data */
704 /* null terminate == cheap insurance */
712 /*********************************************************************
714 * Function : get_header
716 * Description : This (odd) routine will parse the csp->iob
719 * 1 : csp = Current client state (buffers, headers, etc...)
721 * Returns : Any one of the following:
723 * 1) a pointer to a dynamically allocated string that contains a header line
724 * 2) NULL indicating that the end of the header was reached
725 * 3) "" indicating that the end of the iob was reached before finding
726 * a complete header line.
728 *********************************************************************/
729 char *get_header(struct client_state *csp)
735 if ((iob->cur == NULL)
736 || ((p = strchr(iob->cur, '\n')) == NULL))
738 return(""); /* couldn't find a complete header */
743 ret = strdup(iob->cur);
746 /* FIXME No way to handle error properly */
747 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
752 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
754 /* is this a blank line (i.e. the end of the header) ? */
766 /*********************************************************************
768 * Function : get_header_value
770 * Description : Get the value of a given header from a chained list
771 * of header lines or return NULL if no such header is
772 * present in the list.
775 * 1 : header_list = pointer to list
776 * 2 : header_name = string with name of header to look for.
777 * Trailing colon required, capitalization
780 * Returns : NULL if not found, else value of header
782 *********************************************************************/
783 char *get_header_value(const struct list *header_list, const char *header_name)
785 struct list_entry *cur_entry;
791 length = strlen(header_name);
793 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
797 if (!strncmpic(cur_entry->str, header_name, length))
800 * Found: return pointer to start of value
802 ret = (char *) (cur_entry->str + length);
803 while (*ret && ijb_isspace(*ret)) ret++;
816 /*********************************************************************
820 * Description : add, delete or modify lines in the HTTP header streams.
821 * On entry, it receives a linked list of headers space
822 * that was allocated dynamically (both the list nodes
823 * and the header contents).
825 * As a side effect it frees the space used by the original
829 * 1 : pats = list of patterns to match against headers
830 * 2 : more_headers = list of functions to add more
831 * headers (client or server)
832 * 3 : csp = Current client state (buffers, headers, etc...)
834 * Returns : Single pointer to a fully formed header, or NULL
835 * on out-of-memory error.
837 *********************************************************************/
838 char *sed(const struct parsers pats[],
839 const add_header_func_ptr more_headers[],
840 struct client_state *csp)
842 struct list_entry *p;
843 const struct parsers *v;
844 const add_header_func_ptr *f;
845 jb_err err = JB_ERR_OK;
849 * If filtering is enabled, sed is run twice,
850 * but most of the work needs to be done only once.
852 first_run = (more_headers != NULL ) ? 1 : 0;
854 if (first_run) /* Parse and print */
856 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
858 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
860 /* Header crunch()ed in previous run? -> ignore */
861 if (p->str == NULL) continue;
863 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
865 /* Does the current parser handle this header? */
866 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
868 err = v->parser(csp, (char **)&(p->str));
872 /* place any additional headers on the csp->headers list */
873 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
878 else /* Parse only */
881 * The second run is only needed if the body was modified
882 * and the content-lenght has changed.
884 if (strncmpic(csp->http->cmd, "HEAD", 4))
886 /*XXX: Code duplication*/
887 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
889 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
891 /* Header crunch()ed in previous run? -> ignore */
892 if (p->str == NULL) continue;
894 /* Does the current parser handle this header? */
895 if (strncmpic(p->str, v->str, v->len) == 0)
897 err = v->parser(csp, (char **)&(p->str));
904 if (err != JB_ERR_OK)
909 return list_to_text(csp->headers);
913 /* here begins the family of parser functions that reformat header lines */
915 /*********************************************************************
917 * Function : filter_server_header
919 * Description : Checks if server header filtering is enabled.
920 * If it is, filter_header is called to do the work.
923 * 1 : csp = Current client state (buffers, headers, etc...)
924 * 2 : header = On input, pointer to header to modify.
925 * On output, pointer to the modified header, or NULL
926 * to remove the header. This function frees the
927 * original string if necessary.
929 * Returns : JB_ERR_OK on success and always succeeds
931 *********************************************************************/
932 jb_err filter_server_header(struct client_state *csp, char **header)
934 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
936 filter_header(csp, header);
941 /*********************************************************************
943 * Function : filter_client_header
945 * Description : Checks if client header filtering is enabled.
946 * If it is, filter_header is called to do the work.
949 * 1 : csp = Current client state (buffers, headers, etc...)
950 * 2 : header = On input, pointer to header to modify.
951 * On output, pointer to the modified header, or NULL
952 * to remove the header. This function frees the
953 * original string if necessary.
955 * Returns : JB_ERR_OK on success and always succeeds
957 *********************************************************************/
958 jb_err filter_client_header(struct client_state *csp, char **header)
960 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
962 filter_header(csp, header);
967 /*********************************************************************
969 * Function : filter_header
971 * Description : Executes all text substitutions from all applying
972 * +filter actions on the header.
973 * Most of the code was copied from pcrs_filter_response,
974 * including the rather short variable names
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_header(struct client_state *csp, char **header)
990 size_t size = strlen(*header);
992 char *newheader = NULL;
995 struct file_list *fl;
996 struct re_filterfile_spec *b;
997 struct list_entry *filtername;
999 int i, found_filters = 0;
1001 log_error(LOG_LEVEL_RE_FILTER, "Entered filter_headers");
1003 * Need to check the set of re_filterfiles...
1005 for (i = 0; i < MAX_AF_FILES; i++)
1018 if (0 == found_filters)
1020 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1024 for (i = 0; i < MAX_AF_FILES; i++)
1027 if ((NULL == fl) || (NULL == fl->f))
1030 * For all applying +filter actions, look if a filter by that
1031 * name exists and if yes, execute its pcrs_joblist on the
1034 for (b = fl->f; b; b = b->next)
1036 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1037 filtername ; filtername = filtername->next)
1039 if (strcmp(b->name, filtername->str) == 0)
1041 int current_hits = 0;
1043 if ( NULL == b->joblist )
1045 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1049 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1050 *header, size, b->name);
1052 /* Apply all jobs from the joblist */
1053 for (job = b->joblist; NULL != job; job = job->next)
1055 matches = pcrs_execute(job, *header, size, &newheader, &size);
1058 current_hits += matches;
1059 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1061 *header = newheader;
1063 else if ( 0 == matches )
1065 /* Filter doesn't change header */
1071 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1072 *header, b->name, pcrs_strerror(matches));
1073 if( newheader != NULL)
1075 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1080 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1081 hits += current_hits;
1089 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1092 log_error(LOG_LEVEL_RE_FILTER, "Leaving filter headers");
1098 /*********************************************************************
1100 * Function : crumble
1102 * Description : This is called if a header matches a pattern to "crunch"
1105 * 1 : csp = Current client state (buffers, headers, etc...)
1106 * 2 : header = On input, pointer to header to modify.
1107 * On output, pointer to the modified header, or NULL
1108 * to remove the header. This function frees the
1109 * original string if necessary.
1111 * Returns : JB_ERR_OK on success, or
1112 * JB_ERR_MEMORY on out-of-memory error.
1114 *********************************************************************/
1115 jb_err crumble(struct client_state *csp, char **header)
1117 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1122 /*********************************************************************
1124 * Function : crunch_server_header
1126 * Description : Crunch server header if it matches a string supplied by the
1127 * user. Called from `sed'.
1130 * 1 : csp = Current client state (buffers, headers, etc...)
1131 * 2 : header = On input, pointer to header to modify.
1132 * On output, pointer to the modified header, or NULL
1133 * to remove the header. This function frees the
1134 * original string if necessary.
1136 * Returns : JB_ERR_OK on success and always succeeds
1138 *********************************************************************/
1139 jb_err crunch_server_header(struct client_state *csp, char **header)
1141 const char *crunch_pattern;
1142 /*Is there a header to crunch*/
1144 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1146 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1148 /*Is the current header the lucky one?*/
1149 if (strstr(*header, crunch_pattern))
1151 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1158 /*********************************************************************
1160 * Function : server_content_type
1162 * Description : Set the content-type for filterable types (text/.*,
1163 * javascript and image/gif) unless filtering has been
1164 * forbidden (CT_TABOO) while parsing earlier headers.
1165 * NOTE: Since text/plain is commonly used by web servers
1166 * for files whose correct type is unknown, we don't
1167 * set CT_TEXT for it.
1170 * 1 : csp = Current client state (buffers, headers, etc...)
1171 * 2 : header = On input, pointer to header to modify.
1172 * On output, pointer to the modified header, or NULL
1173 * to remove the header. This function frees the
1174 * original string if necessary.
1176 * Returns : JB_ERR_OK on success, or
1177 * JB_ERR_MEMORY on out-of-memory error.
1179 *********************************************************************/
1180 jb_err server_content_type(struct client_state *csp, char **header)
1184 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1186 if (csp->content_type != CT_TABOO)
1188 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1189 || strstr(*header, "xml")
1190 || strstr(*header, "application/x-javascript"))
1191 csp->content_type = CT_TEXT;
1192 else if (strstr(*header, " image/gif"))
1193 csp->content_type = CT_GIF;
1194 else if (strstr(*header, " image/jpeg"))
1195 csp->content_type = CT_JPEG;
1197 csp->content_type = 0;
1200 * Are we enabling text mode by force?
1202 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1205 * Do we really have to?
1207 if (csp->content_type == CT_TEXT)
1209 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1213 csp->content_type = CT_TEXT;
1214 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1218 * Are we messing with the content type?
1220 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1223 * Make sure the user doesn't accidently
1224 * change the content type of binary documents.
1226 if (csp->content_type == CT_TEXT)
1229 *header = strdup("Content-Type: ");
1230 string_append(header, newval);
1234 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1235 return JB_ERR_MEMORY;
1237 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1241 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1242 "Enable force-text-mode if you know what you're doing.", *header);
1249 /*********************************************************************
1251 * Function : server_transfer_coding
1253 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1254 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1255 * - Remove header if body was chunked but has been
1256 * de-chunked for filtering.
1259 * 1 : csp = Current client state (buffers, headers, etc...)
1260 * 2 : header = On input, pointer to header to modify.
1261 * On output, pointer to the modified header, or NULL
1262 * to remove the header. This function frees the
1263 * original string if necessary.
1265 * Returns : JB_ERR_OK on success, or
1266 * JB_ERR_MEMORY on out-of-memory error.
1268 *********************************************************************/
1269 jb_err server_transfer_coding(struct client_state *csp, char **header)
1272 * Turn off pcrs and gif filtering if body compressed
1274 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1276 csp->content_type = CT_TABOO;
1280 * Raise flag if body chunked
1282 if (strstr(*header, "chunked"))
1284 csp->flags |= CSP_FLAG_CHUNKED;
1287 * If the body was modified, it has been de-chunked first
1288 * and the header must be removed.
1290 if (csp->flags & CSP_FLAG_MODIFIED)
1292 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
1301 /*********************************************************************
1303 * Function : server_content_encoding
1305 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1308 * 1 : csp = Current client state (buffers, headers, etc...)
1309 * 2 : header = On input, pointer to header to modify.
1310 * On output, pointer to the modified header, or NULL
1311 * to remove the header. This function frees the
1312 * original string if necessary.
1314 * Returns : JB_ERR_OK on success, or
1315 * JB_ERR_MEMORY on out-of-memory error.
1317 *********************************************************************/
1318 jb_err server_content_encoding(struct client_state *csp, char **header)
1321 * Turn off pcrs and gif filtering if body compressed
1323 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1325 csp->content_type = CT_TABOO;
1333 /*********************************************************************
1335 * Function : server_content_length
1337 * Description : Adjust Content-Length header if we modified
1341 * 1 : csp = Current client state (buffers, headers, etc...)
1342 * 2 : header = On input, pointer to header to modify.
1343 * On output, pointer to the modified header, or NULL
1344 * to remove the header. This function frees the
1345 * original string if necessary.
1347 * Returns : JB_ERR_OK on success, or
1348 * JB_ERR_MEMORY on out-of-memory error.
1350 *********************************************************************/
1351 jb_err server_content_length(struct client_state *csp, char **header)
1353 if (csp->content_length != 0) /* Content length could have been modified */
1356 * XXX: Shouldn't we check if csp->content_length
1357 * is different than the original value?
1360 *header = (char *) zalloc(100);
1361 if (*header == NULL)
1363 return JB_ERR_MEMORY;
1366 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1368 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1375 /*********************************************************************
1377 * Function : server_content_md5
1379 * Description : Crumble any Content-MD5 headers if the document was
1380 * modified. FIXME: Should we re-compute instead?
1383 * 1 : csp = Current client state (buffers, headers, etc...)
1384 * 2 : header = On input, pointer to header to modify.
1385 * On output, pointer to the modified header, or NULL
1386 * to remove the header. This function frees the
1387 * original string if necessary.
1389 * Returns : JB_ERR_OK on success, or
1390 * JB_ERR_MEMORY on out-of-memory error.
1392 *********************************************************************/
1393 jb_err server_content_md5(struct client_state *csp, char **header)
1395 if (csp->flags & CSP_FLAG_MODIFIED)
1397 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1404 /*********************************************************************
1406 * Function : server_content_disposition
1408 * Description : If enabled, blocks or modifies the "content-disposition" header.
1409 * Called from `sed'.
1412 * 1 : csp = Current client state (buffers, headers, etc...)
1413 * 2 : header = On input, pointer to header to modify.
1414 * On output, pointer to the modified header, or NULL
1415 * to remove the header. This function frees the
1416 * original string if necessary.
1418 * Returns : JB_ERR_OK on success, or
1419 * JB_ERR_MEMORY on out-of-memory error.
1421 *********************************************************************/
1422 jb_err server_content_disposition(struct client_state *csp, char **header)
1427 * Are we messing with the content-disposition header?
1429 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1435 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1437 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1440 * Blocking content-disposition header
1442 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1449 * Replacing content-disposition header
1452 *header = strdup("content-disposition: ");
1453 string_append(header, newval);
1455 if (*header == NULL)
1457 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1461 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1464 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1467 /*********************************************************************
1469 * Function : server_last_modified
1471 * Description : Changes Last-Modified header to the actual date
1472 * to help hide-if-modified-since.
1473 * Called from `sed'.
1476 * 1 : csp = Current client state (buffers, headers, etc...)
1477 * 2 : header = On input, pointer to header to modify.
1478 * On output, pointer to the modified header, or NULL
1479 * to remove the header. This function frees the
1480 * original string if necessary.
1482 * Returns : JB_ERR_OK on success, or
1483 * JB_ERR_MEMORY on out-of-memory error.
1485 *********************************************************************/
1486 jb_err server_last_modified(struct client_state *csp, char **header)
1489 char buf[BUFFER_SIZE];
1492 #ifdef HAVE_GMTIME_R
1495 struct tm *timeptr = NULL;
1496 time_t now, last_modified;
1498 long int days, hours, minutes, seconds;
1501 * Are we messing with the Last-Modified header?
1503 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1509 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1511 if (0 == strcmpic(newval, "block") )
1514 * Blocking Last-Modified header. Useless but why not.
1516 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1520 else if (0 == strcmpic(newval, "reset-to-request-time"))
1523 * Setting Last-Modified Header to now.
1525 get_http_time(0, buf);
1527 *header = strdup("Last-Modified: ");
1528 string_append(header, buf);
1530 if (*header == NULL)
1532 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1536 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1539 else if (0 == strcmpic(newval, "randomize"))
1541 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1543 #ifdef HAVE_GMTIME_R
1544 timeptr = gmtime_r(&now, &gmt);
1546 pthread_mutex_lock(&gmtime_mutex);
1547 timeptr = gmtime(&now);
1548 pthread_mutex_unlock(&gmtime_mutex);
1550 timeptr = gmtime(&now);
1552 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
1554 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1559 rtime = difftime(now, last_modified);
1562 rtime = pick_from_range(rtime);
1563 last_modified += rtime;
1564 #ifdef HAVE_GMTIME_R
1565 timeptr = gmtime_r(&last_modified, &gmt);
1567 pthread_mutex_lock(&gmtime_mutex);
1568 timeptr = gmtime(&last_modified);
1569 pthread_mutex_unlock(&gmtime_mutex);
1571 timeptr = gmtime(&last_modified);
1573 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1575 *header = strdup("Last-Modified: ");
1576 string_append(header, newheader);
1578 if (*header == NULL)
1580 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
1581 return JB_ERR_MEMORY;
1584 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1586 days = rtime / (3600 * 24);
1587 hours = rtime / 3600 % 24;
1588 minutes = rtime / 60 % 60;
1589 seconds = rtime % 60;
1591 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1592 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1593 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1598 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1606 /*********************************************************************
1608 * Function : client_accept_encoding
1610 * Description : Rewrite the client's Accept-Encoding header so that
1611 * if doesn't allow compression, if the action applies.
1612 * Note: For HTTP/1.0 the absence of the header is enough.
1615 * 1 : csp = Current client state (buffers, headers, etc...)
1616 * 2 : header = On input, pointer to header to modify.
1617 * On output, pointer to the modified header, or NULL
1618 * to remove the header. This function frees the
1619 * original string if necessary.
1621 * Returns : JB_ERR_OK on success, or
1622 * JB_ERR_MEMORY on out-of-memory error.
1624 *********************************************************************/
1625 jb_err client_accept_encoding(struct client_state *csp, char **header)
1627 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1629 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1633 /* Temporarily disable the correct behaviour to
1634 * work around a PHP bug.
1636 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1638 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1639 * if (*header == NULL)
1641 * return JB_ERR_MEMORY;
1652 /*********************************************************************
1654 * Function : client_te
1656 * Description : Rewrite the client's TE header so that
1657 * if doesn't allow compression, if the action applies.
1660 * 1 : csp = Current client state (buffers, headers, etc...)
1661 * 2 : header = On input, pointer to header to modify.
1662 * On output, pointer to the modified header, or NULL
1663 * to remove the header. This function frees the
1664 * original string if necessary.
1666 * Returns : JB_ERR_OK on success, or
1667 * JB_ERR_MEMORY on out-of-memory error.
1669 *********************************************************************/
1670 jb_err client_te(struct client_state *csp, char **header)
1672 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1675 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1681 /*********************************************************************
1683 * Function : client_referrer
1685 * Description : Handle the "referer" config setting properly.
1686 * Called from `sed'.
1689 * 1 : csp = Current client state (buffers, headers, etc...)
1690 * 2 : header = On input, pointer to header to modify.
1691 * On output, pointer to the modified header, or NULL
1692 * to remove the header. This function frees the
1693 * original string if necessary.
1695 * Returns : JB_ERR_OK on success, or
1696 * JB_ERR_MEMORY on out-of-memory error.
1698 *********************************************************************/
1699 jb_err client_referrer(struct client_state *csp, char **header)
1706 #ifdef FEATURE_FORCE_LOAD
1707 /* Since the referrer can include the prefix even
1708 * if the request itself is non-forced, we must
1709 * clean it unconditionally
1711 strclean(*header, FORCE_PREFIX);
1712 #endif /* def FEATURE_FORCE_LOAD */
1715 * Are we sending referer?
1717 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1722 newval = csp->action->string[ACTION_STRING_REFERER];
1724 if ((0 != strcmpic(newval, "conditional-block")))
1728 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1733 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1736 else if (0 == strcmpic(newval, "conditional-block"))
1739 * Block referer if host has changed.
1742 if (NULL == (host = strdup(csp->http->hostport)))
1745 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1746 return JB_ERR_MEMORY;
1748 if (NULL == (referer = strdup(*header)))
1752 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1753 return JB_ERR_MEMORY;
1755 hostlenght = strlen(host);
1756 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1758 /*Shorten referer to make sure the referer is blocked
1759 *if www.example.org/www.example.com-shall-see-the-referer/
1760 *links to www.example.com/
1762 referer[hostlenght+17] = '\0';
1764 if ( 0 == strstr(referer, host)) /*Host has changed*/
1766 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1771 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1777 else if (0 != strcmpic(newval, "forge"))
1780 * We have a specific (fixed) referer we want to send.
1782 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1784 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1786 *header = strdup("Referer: ");
1787 string_append(header, newval);
1788 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1790 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1795 * Forge a referer as http://[hostname:port of REQUEST]/
1796 * to fool stupid checks for in-site links
1799 *header = strdup("Referer: http://");
1800 string_append(header, csp->http->hostport);
1801 string_append(header, "/");
1802 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1804 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1808 /*********************************************************************
1810 * Function : client_accept_language
1812 * Description : Handle the "Accept-Language" config setting properly.
1813 * Called from `sed'.
1816 * 1 : csp = Current client state (buffers, headers, etc...)
1817 * 2 : header = On input, pointer to header to modify.
1818 * On output, pointer to the modified header, or NULL
1819 * to remove the header. This function frees the
1820 * original string if necessary.
1822 * Returns : JB_ERR_OK on success, or
1823 * JB_ERR_MEMORY on out-of-memory error.
1825 *********************************************************************/
1826 jb_err client_accept_language(struct client_state *csp, char **header)
1831 * Are we messing with the Accept-Language?
1833 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1835 /*I don't think so*/
1839 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1841 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1844 * Blocking Accept-Language header
1846 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1853 * Replacing Accept-Language header
1856 *header = strdup("Accept-Language: ");
1857 string_append(header, newval);
1859 if (*header == NULL)
1861 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1865 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1868 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1871 /*********************************************************************
1873 * Function : crunch_client_header
1875 * Description : Crunch client header if it matches a string supplied by the
1876 * user. Called from `sed'.
1879 * 1 : csp = Current client state (buffers, headers, etc...)
1880 * 2 : header = On input, pointer to header to modify.
1881 * On output, pointer to the modified header, or NULL
1882 * to remove the header. This function frees the
1883 * original string if necessary.
1885 * Returns : JB_ERR_OK on success and always succeeds
1887 *********************************************************************/
1888 jb_err crunch_client_header(struct client_state *csp, char **header)
1890 const char *crunch_pattern;
1891 /*Is there a header to crunch*/
1893 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1895 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1897 /*Is the current header the lucky one?*/
1898 if (strstr(*header, crunch_pattern))
1900 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1908 /*********************************************************************
1910 * Function : client_uagent
1912 * Description : Handle the "user-agent" config setting properly
1913 * and remember its original value to enable browser
1914 * bug workarounds. Called from `sed'.
1917 * 1 : csp = Current client state (buffers, headers, etc...)
1918 * 2 : header = On input, pointer to header to modify.
1919 * On output, pointer to the modified header, or NULL
1920 * to remove the header. This function frees the
1921 * original string if necessary.
1923 * Returns : JB_ERR_OK on success, or
1924 * JB_ERR_MEMORY on out-of-memory error.
1926 *********************************************************************/
1927 jb_err client_uagent(struct client_state *csp, char **header)
1931 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1936 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1943 *header = strdup("User-Agent: ");
1944 string_append(header, newval);
1946 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
1948 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1951 /*********************************************************************
1953 * Function : client_ua
1955 * Description : Handle "ua-" headers properly. Called from `sed'.
1958 * 1 : csp = Current client state (buffers, headers, etc...)
1959 * 2 : header = On input, pointer to header to modify.
1960 * On output, pointer to the modified header, or NULL
1961 * to remove the header. This function frees the
1962 * original string if necessary.
1964 * Returns : JB_ERR_OK on success, or
1965 * JB_ERR_MEMORY on out-of-memory error.
1967 *********************************************************************/
1968 jb_err client_ua(struct client_state *csp, char **header)
1970 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1972 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
1980 /*********************************************************************
1982 * Function : client_from
1984 * Description : Handle the "from" config setting properly.
1985 * Called from `sed'.
1988 * 1 : csp = Current client state (buffers, headers, etc...)
1989 * 2 : header = On input, pointer to header to modify.
1990 * On output, pointer to the modified header, or NULL
1991 * to remove the header. This function frees the
1992 * original string if necessary.
1994 * Returns : JB_ERR_OK on success, or
1995 * JB_ERR_MEMORY on out-of-memory error.
1997 *********************************************************************/
1998 jb_err client_from(struct client_state *csp, char **header)
2002 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2009 newval = csp->action->string[ACTION_STRING_FROM];
2012 * Are we blocking the e-mail address?
2014 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2016 log_error(LOG_LEVEL_HEADER, "crunched From!");
2020 log_error(LOG_LEVEL_HEADER, " modified");
2022 *header = strdup("From: ");
2023 string_append(header, newval);
2025 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2029 /*********************************************************************
2031 * Function : client_send_cookie
2033 * Description : Handle the "cookie" header properly. Called from `sed'.
2034 * If cookie is accepted, add it to the cookie_list,
2035 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2038 * 1 : csp = Current client state (buffers, headers, etc...)
2039 * 2 : header = On input, pointer to header to modify.
2040 * On output, pointer to the modified header, or NULL
2041 * to remove the header. This function frees the
2042 * original string if necessary.
2044 * Returns : JB_ERR_OK on success, or
2045 * JB_ERR_MEMORY on out-of-memory error.
2047 *********************************************************************/
2048 jb_err client_send_cookie(struct client_state *csp, char **header)
2050 jb_err result = JB_ERR_OK;
2052 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2054 /* strlen("cookie: ") == 8 */
2055 result = enlist(csp->cookie_list, *header + 8);
2059 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2063 * Always remove the cookie here. The cookie header
2064 * will be sent at the end of the header.
2072 /*********************************************************************
2074 * Function : client_x_forwarded
2076 * Description : Handle the "x-forwarded-for" config setting properly,
2077 * also used in the add_client_headers list. Called from `sed'.
2080 * 1 : csp = Current client state (buffers, headers, etc...)
2081 * 2 : header = On input, pointer to header to modify.
2082 * On output, pointer to the modified header, or NULL
2083 * to remove the header. This function frees the
2084 * original string if necessary.
2086 * Returns : JB_ERR_OK on success, or
2087 * JB_ERR_MEMORY on out-of-memory error.
2089 *********************************************************************/
2090 jb_err client_x_forwarded(struct client_state *csp, char **header)
2092 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2094 /* Save it so we can re-add it later */
2095 freez(csp->x_forwarded);
2096 csp->x_forwarded = *header;
2099 * Always set *header = NULL, since this information
2100 * will be sent at the end of the header.
2107 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2114 /*********************************************************************
2116 * Function : client_max_forwards
2118 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2119 * from the value of the Max-Forwards header field.
2122 * 1 : csp = Current client state (buffers, headers, etc...)
2123 * 2 : header = On input, pointer to header to modify.
2124 * On output, pointer to the modified header, or NULL
2125 * to remove the header. This function frees the
2126 * original string if necessary.
2128 * Returns : JB_ERR_OK on success, or
2129 * JB_ERR_MEMORY on out-of-memory error.
2131 *********************************************************************/
2132 jb_err client_max_forwards(struct client_state *csp, char **header)
2134 unsigned int max_forwards;
2136 if ((0 == strcmpic(csp->http->gpc, "trace"))
2137 || (0 == strcmpic(csp->http->gpc, "options")))
2139 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2141 if (max_forwards-- >= 1)
2143 sprintf(*header, "Max-Forwards: %u", max_forwards);
2144 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2148 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2157 /*********************************************************************
2159 * Function : client_host
2161 * Description : If the request URI did not contain host and
2162 * port information, parse and evaluate the Host
2165 * Also, kill ill-formed HOST: headers as sent by
2166 * Apple's iTunes software when used with a proxy.
2169 * 1 : csp = Current client state (buffers, headers, etc...)
2170 * 2 : header = On input, pointer to header to modify.
2171 * On output, pointer to the modified header, or NULL
2172 * to remove the header. This function frees the
2173 * original string if necessary.
2175 * Returns : JB_ERR_OK on success, or
2176 * JB_ERR_MEMORY on out-of-memory error.
2178 *********************************************************************/
2179 jb_err client_host(struct client_state *csp, char **header)
2184 * If the header field name is all upper-case, chances are that it's
2185 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2186 * not a problem -- they are regenerated later.
2188 if ((*header)[1] == 'O')
2190 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2195 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2196 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2199 if (NULL == (p = strdup((*header)+6)))
2201 return JB_ERR_MEMORY;
2204 if (NULL == (q = strdup(p)))
2207 return JB_ERR_MEMORY;
2210 freez(csp->http->hostport);
2211 csp->http->hostport = p;
2212 freez(csp->http->host);
2213 csp->http->host = q;
2214 q = strchr(csp->http->host, ':');
2217 /* Terminate hostname and evaluate port string */
2219 csp->http->port = atoi(q);
2223 csp->http->port = csp->http->ssl ? 443 : 80;
2226 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2227 csp->http->hostport, csp->http->host, csp->http->port);
2233 /*********************************************************************
2235 * Function : client_if_modified_since
2237 * Description : Remove or modify the If-Modified-Since header.
2240 * 1 : csp = Current client state (buffers, headers, etc...)
2241 * 2 : header = On input, pointer to header to modify.
2242 * On output, pointer to the modified header, or NULL
2243 * to remove the header. This function frees the
2244 * original string if necessary.
2246 * Returns : JB_ERR_OK on success, or
2247 * JB_ERR_MEMORY on out-of-memory error.
2249 *********************************************************************/
2250 jb_err client_if_modified_since(struct client_state *csp, char **header)
2253 #ifdef HAVE_GMTIME_R
2256 struct tm *timeptr = NULL;
2260 long int hours, minutes, seconds;
2264 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2267 * The client got an error message because of a temporary problem,
2268 * the problem is gone and the client now tries to revalidate our
2269 * error message on the real server. The revalidation would always
2270 * end with the transmission of the whole document and there is
2271 * no need to expose the bogus If-Modified-Since header.
2273 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2276 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2278 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2280 if ((0 == strcmpic(newval, "block")))
2282 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2285 else /* add random value */
2287 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2289 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2294 rtime = strtol(newval, &endptr, 0);
2302 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d hou%s)",
2303 *header, rtime, (rtime == 1 || rtime == -1) ? "r": "rs");
2305 rtime = pick_from_range(rtime);
2309 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2313 #ifdef HAVE_GMTIME_R
2314 timeptr = gmtime_r(&tm, &gmt);
2316 pthread_mutex_lock(&gmtime_mutex);
2317 timeptr = gmtime(&tm);
2318 pthread_mutex_unlock(&gmtime_mutex);
2320 timeptr = gmtime(&tm);
2322 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2325 *header = strdup("If-Modified-Since: ");
2326 string_append(header, newheader);
2328 if (*header == NULL)
2330 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2331 return JB_ERR_MEMORY;
2334 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2336 hours = rtime / 3600;
2337 minutes = rtime / 60 % 60;
2338 seconds = rtime % 60;
2340 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2341 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2342 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2351 /*********************************************************************
2353 * Function : client_if_none_match
2355 * Description : Remove the If-None-Match header.
2358 * 1 : csp = Current client state (buffers, headers, etc...)
2359 * 2 : header = On input, pointer to header to modify.
2360 * On output, pointer to the modified header, or NULL
2361 * to remove the header. This function frees the
2362 * original string if necessary.
2364 * Returns : JB_ERR_OK on success, or
2365 * JB_ERR_MEMORY on out-of-memory error.
2367 *********************************************************************/
2368 jb_err client_if_none_match(struct client_state *csp, char **header)
2370 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2372 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2379 /*********************************************************************
2381 * Function : client_x_filter
2383 * Description : Disables filtering if the client set "X-Filter: No".
2384 * Called from `sed'.
2387 * 1 : csp = Current client state (buffers, headers, etc...)
2388 * 2 : header = On input, pointer to header to modify.
2389 * On output, pointer to the modified header, or NULL
2390 * to remove the header. This function frees the
2391 * original string if necessary.
2393 * Returns : JB_ERR_OK on success
2395 *********************************************************************/
2396 jb_err client_x_filter(struct client_state *csp, char **header)
2398 if ( 0 == strcmpic(*header, "X-Filter: No"))
2400 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2402 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to disable filtering!");
2406 csp->content_type = CT_TABOO;
2407 log_error(LOG_LEVEL_HEADER, "Disabled filter mode on behalf of the client.");
2409 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2415 /* the following functions add headers directly to the header list */
2417 /*********************************************************************
2419 * Function : client_host_adder
2421 * Description : Adds the Host: header field if it is missing.
2422 * Called from `sed'.
2425 * 1 : csp = Current client state (buffers, headers, etc...)
2427 * Returns : JB_ERR_OK on success, or
2428 * JB_ERR_MEMORY on out-of-memory error.
2430 *********************************************************************/
2431 jb_err client_host_adder(struct client_state *csp)
2436 if ( !csp->http->hostport || !*(csp->http->hostport))
2442 * remove 'user:pass@' from 'proto://user:pass@host'
2444 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2450 p = csp->http->hostport;
2453 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2454 err = enlist_unique_header(csp->headers, "Host", p);
2460 /*********************************************************************
2462 * Function : client_cookie_adder
2464 * Description : Used in the add_client_headers list. Called from `sed'.
2467 * 1 : csp = Current client state (buffers, headers, etc...)
2469 * Returns : JB_ERR_OK on success, or
2470 * JB_ERR_MEMORY on out-of-memory error.
2472 *********************************************************************/
2473 jb_err client_cookie_adder(struct client_state *csp)
2475 struct list_entry *lst;
2477 struct list_entry *list1 = csp->cookie_list->first;
2478 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2479 int first_cookie = 1;
2482 if ((list1 == NULL) && (list2 == NULL))
2488 tmp = strdup("Cookie: ");
2490 for (lst = list1; lst ; lst = lst->next)
2498 string_append(&tmp, "; ");
2500 string_append(&tmp, lst->str);
2503 for (lst = list2; lst ; lst = lst->next)
2511 string_append(&tmp, "; ");
2513 string_join(&tmp, cookie_encode(lst->str));
2518 return JB_ERR_MEMORY;
2521 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2522 err = enlist(csp->headers, tmp);
2528 /*********************************************************************
2530 * Function : client_accept_encoding_adder
2532 * Description : Add an Accept-Encoding header to the client's request
2533 * that disables compression if the action applies, and
2534 * the header is not already there. Called from `sed'.
2535 * Note: For HTTP/1.0, the absence of the header is enough.
2538 * 1 : csp = Current client state (buffers, headers, etc...)
2540 * Returns : JB_ERR_OK on success, or
2541 * JB_ERR_MEMORY on out-of-memory error.
2543 *********************************************************************/
2544 jb_err client_accept_encoding_adder(struct client_state *csp)
2546 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2547 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2549 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2556 /*********************************************************************
2558 * Function : client_xtra_adder
2560 * Description : Used in the add_client_headers list. Called from `sed'.
2563 * 1 : csp = Current client state (buffers, headers, etc...)
2565 * Returns : JB_ERR_OK on success, or
2566 * JB_ERR_MEMORY on out-of-memory error.
2568 *********************************************************************/
2569 jb_err client_xtra_adder(struct client_state *csp)
2571 struct list_entry *lst;
2574 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2575 lst ; lst = lst->next)
2577 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2578 err = enlist(csp->headers, lst->str);
2590 /*********************************************************************
2592 * Function : client_x_forwarded_adder
2594 * Description : Used in the add_client_headers list. Called from `sed'.
2597 * 1 : csp = Current client state (buffers, headers, etc...)
2599 * Returns : JB_ERR_OK on success, or
2600 * JB_ERR_MEMORY on out-of-memory error.
2602 *********************************************************************/
2603 jb_err client_x_forwarded_adder(struct client_state *csp)
2608 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2613 if (csp->x_forwarded)
2615 p = strdup(csp->x_forwarded);
2616 string_append(&p, ", ");
2620 p = strdup("X-Forwarded-For: ");
2622 string_append(&p, csp->ip_addr_str);
2626 return JB_ERR_MEMORY;
2629 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2630 err = enlist(csp->headers, p);
2637 /*********************************************************************
2639 * Function : connection_close_adder
2641 * Description : Adds a "Connection: close" header to csp->headers
2642 * as a temporary fix for the needed but missing HTTP/1.1
2643 * support. Called from `sed'.
2644 * FIXME: This whole function shouldn't be neccessary!
2647 * 1 : csp = Current client state (buffers, headers, etc...)
2649 * Returns : JB_ERR_OK on success, or
2650 * JB_ERR_MEMORY on out-of-memory error.
2652 *********************************************************************/
2653 jb_err connection_close_adder(struct client_state *csp)
2655 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2656 return enlist(csp->headers, "Connection: close");
2660 /*********************************************************************
2662 * Function : server_http
2664 * Description : - Save the HTTP Status into csp->http->status
2665 * - Set CT_TABOO to prevent filtering if the answer
2666 * is a partial range (HTTP status 206)
2667 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2671 * 1 : csp = Current client state (buffers, headers, etc...)
2672 * 2 : header = On input, pointer to header to modify.
2673 * On output, pointer to the modified header, or NULL
2674 * to remove the header. This function frees the
2675 * original string if necessary.
2677 * Returns : JB_ERR_OK on success, or
2678 * JB_ERR_MEMORY on out-of-memory error.
2680 *********************************************************************/
2681 jb_err server_http(struct client_state *csp, char **header)
2683 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2684 if (csp->http->status == 206)
2686 csp->content_type = CT_TABOO;
2689 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2692 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2699 /*********************************************************************
2701 * Function : server_set_cookie
2703 * Description : Handle the server "cookie" header properly.
2704 * Log cookie to the jar file. Then "crunch" it,
2705 * or accept it. Called from `sed'.
2708 * 1 : csp = Current client state (buffers, headers, etc...)
2709 * 2 : header = On input, pointer to header to modify.
2710 * On output, pointer to the modified header, or NULL
2711 * to remove the header. This function frees the
2712 * original string if necessary.
2714 * Returns : JB_ERR_OK on success, or
2715 * JB_ERR_MEMORY on out-of-memory error.
2717 *********************************************************************/
2718 jb_err server_set_cookie(struct client_state *csp, char **header)
2720 #ifdef FEATURE_COOKIE_JAR
2721 if (csp->config->jar)
2724 * Write timestamp into outbuf.
2726 * Complex because not all OSs have tm_gmtoff or
2727 * the %z field in strftime()
2729 char tempbuf[ BUFFER_SIZE ];
2733 #ifdef HAVE_LOCALTIME_R
2734 tm_now = *localtime_r(&now, &tm_now);
2736 pthread_mutex_lock(&localtime_mutex);
2737 tm_now = *localtime (&now);
2738 pthread_mutex_unlock(&localtime_mutex);
2740 tm_now = *localtime (&now);
2742 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2744 /* strlen("set-cookie: ") = 12 */
2745 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2747 #endif /* def FEATURE_COOKIE_JAR */
2749 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2751 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2752 return crumble(csp, header);
2754 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2756 /* Flag whether or not to log a message */
2759 /* A variable to store the tag we're working on */
2762 /* Skip "Set-Cookie:" (11 characters) in header */
2763 cur_tag = *header + 11;
2765 /* skip whitespace between "Set-Cookie:" and value */
2766 while (*cur_tag && ijb_isspace(*cur_tag))
2771 /* Loop through each tag in the cookie */
2775 char *next_tag = strchr(cur_tag, ';');
2776 if (next_tag != NULL)
2778 /* Skip the ';' character itself */
2781 /* skip whitespace ";" and start of tag */
2782 while (*next_tag && ijb_isspace(*next_tag))
2789 /* "Next tag" is the end of the string */
2790 next_tag = cur_tag + strlen(cur_tag);
2793 /* Is this the "Expires" tag? */
2794 if (strncmpic(cur_tag, "expires=", 8) == 0)
2796 /* Delete the tag by copying the rest of the string over it.
2797 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2798 * since the behaviour of strcpy is undefined for overlapping
2801 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2803 /* That changed the header, need to issue a log message */
2806 /* Note that the next tag has now been moved to *cur_tag,
2807 * so we do not need to update the cur_tag pointer.
2812 /* Move on to next cookie tag */
2819 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2827 #ifdef FEATURE_FORCE_LOAD
2828 /*********************************************************************
2830 * Function : strclean
2832 * Description : In-Situ-Eliminate all occurances of substring in
2836 * 1 : string = string to clean
2837 * 2 : substring = substring to eliminate
2839 * Returns : Number of eliminations
2841 *********************************************************************/
2842 int strclean(const char *string, const char *substring)
2844 int hits = 0, len = strlen(substring);
2847 while((pos = strstr(string, substring)) != NULL)
2854 while (*p++ != '\0');
2861 #endif /* def FEATURE_FORCE_LOAD */
2863 /*********************************************************************
2865 * Function : parse_header_time
2867 * Description : Transforms time inside a HTTP header into
2868 * the usual time format.
2871 * 1 : header = header to parse
2872 * 2 : tm = storage for the resulting time in seconds
2874 * Returns : Time struct containing the header time, or
2875 * NULL in case of a parsing problem.
2877 *********************************************************************/
2878 struct tm *parse_header_time(char *header, time_t *tm) {
2882 struct tm * timeptr;
2884 /* Skipping header name */
2885 timestring = strstr(header, ": ");
2886 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", &gmt) == NULL)