1 const char parsers_rcs[] = "$Id: parsers.c,v 1.65 2006/08/22 10:55:56 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.65 2006/08/22 10:55:56 fabiankeil
44 * Changed client_referrer to use the right type (size_t) for
45 * hostlenght and to shorten the temporary referrer string with
46 * '\0' instead of adding a useless line break.
48 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
49 * - Back to timegm() using GnuPG's replacement if necessary.
50 * Using mktime() and localtime() could add a on hour offset if
51 * the randomize factor was big enough to lead to a summer/wintertime
54 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
56 * - Moved randomization code into pick_from_range().
58 * - Changed parse_header_time definition.
59 * time_t isn't guaranteed to be signed and
60 * if it isn't, -1 isn't available as error code.
61 * Changed some variable types in client_if_modified_since()
62 * because of the same reason.
64 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
65 * OS/2 compilation compatibility fixups
67 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
68 * Changed include from strptime.c to strptime.h
70 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
71 * Split filter-headers{} into filter-client-headers{}
72 * and filter-server-headers{}.
73 * Added parse_header_time() to share some code.
74 * Replaced timegm() with mktime().
76 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
77 * Windows service integration
79 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
80 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
82 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
83 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
84 * with what was really the latest development (the v_3_0_branch branch)
86 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
87 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
89 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
90 * Add the ability to check jpeg images for invalid
91 * lengths of comment blocks. Defensive strategy
92 * against the exploit:
93 * Microsoft Security Bulletin MS04-028
94 * Buffer Overrun in JPEG Processing (GDI+) Could
95 * Allow Code Execution (833987)
96 * Enabled with +inspect-jpegs in actions files.
98 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
99 * Excluded text/plain objects from filtering. This fixes a
100 * couple of client-crashing, download corruption and
101 * Privoxy performance issues, whose root cause lies in
102 * web servers labelling content of unknown type as text/plain.
104 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
105 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
107 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
108 * Completing the previous change
110 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
111 * Added temporary workaround for bug in PHP < 4.2.3
113 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
114 * 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.
116 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
117 * Fix typo: supressed -> suppressed
119 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
120 * Improved cookie logging
122 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
123 * Added basic support for OPTIONS and TRACE HTTP methods:
124 * - New parser function client_max_forwards which decrements
125 * the Max-Forwards HTTP header field of OPTIONS and TRACE
126 * requests by one before forwarding
127 * - New parser function client_host which extracts the host
128 * and port information from the HTTP header field if the
129 * request URI was not absolute
130 * - Don't crumble and re-add the Host: header, but only generate
131 * and append if missing
133 * Revision 1.56 2002/05/12 15:34:22 jongfoster
134 * Fixing typo in a comment
136 * Revision 1.55 2002/05/08 16:01:07 oes
137 * Optimized add_to_iob:
138 * - Use realloc instead of malloc(), memcpy(), free()
139 * - Expand to powers of two if possible, to get
140 * O(log n) reallocs instead of O(n).
141 * - Moved check for buffer limit here from chat
142 * - Report failure via returncode
144 * Revision 1.54 2002/04/02 15:03:16 oes
145 * Tiny code cosmetics
147 * Revision 1.53 2002/03/26 22:29:55 swa
148 * we have a new homepage!
150 * Revision 1.52 2002/03/24 13:25:43 swa
151 * name change related issues
153 * Revision 1.51 2002/03/13 00:27:05 jongfoster
156 * Revision 1.50 2002/03/12 01:45:35 oes
157 * More verbose logging
159 * Revision 1.49 2002/03/09 20:03:52 jongfoster
160 * - Making various functions return int rather than size_t.
161 * (Undoing a recent change). Since size_t is unsigned on
162 * Windows, functions like read_socket that return -1 on
163 * error cannot return a size_t.
165 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
166 * crashes, and also frequently caused JB to jump to 100%
167 * CPU and stay there. (Because it thought it had just
168 * read ((unsigned)-1) == 4Gb of data...)
170 * - The signature of write_socket has changed, it now simply
171 * returns success=0/failure=nonzero.
173 * - Trying to get rid of a few warnings --with-debug on
174 * Windows, I've introduced a new type "jb_socket". This is
175 * used for the socket file descriptors. On Windows, this
176 * is SOCKET (a typedef for unsigned). Everywhere else, it's
177 * an int. The error value can't be -1 any more, so it's
178 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
179 * Windows it maps to the #define INVALID_SOCKET.)
181 * - The signature of bind_port has changed.
183 * Revision 1.48 2002/03/07 03:46:53 oes
184 * Fixed compiler warnings etc
186 * Revision 1.47 2002/02/20 23:15:13 jongfoster
187 * Parsing functions now handle out-of-memory gracefully by returning
190 * Revision 1.46 2002/01/17 21:03:47 jongfoster
191 * Moving all our URL and URL pattern parsing code to urlmatch.c.
193 * Revision 1.45 2002/01/09 14:33:03 oes
194 * Added support for localtime_r.
196 * Revision 1.44 2001/12/14 01:22:54 steudten
197 * Remove 'user:pass@' from 'proto://user:pass@host' for the
198 * new added header 'Host: ..'. (See Req ID 491818)
200 * Revision 1.43 2001/11/23 00:26:38 jongfoster
201 * Fixing two really stupid errors in my previous commit
203 * Revision 1.42 2001/11/22 21:59:30 jongfoster
204 * Adding code to handle +no-cookies-keep
206 * Revision 1.41 2001/11/05 23:43:05 steudten
207 * Add time+date to log files.
209 * Revision 1.40 2001/10/26 20:13:09 jongfoster
210 * ctype.h is needed in Windows, too.
212 * Revision 1.39 2001/10/26 17:40:04 oes
213 * Introduced get_header_value()
214 * Removed http->user_agent, csp->referrer and csp->accept_types
215 * Removed client_accept()
217 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
218 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
219 * threads to call select() simultaneously. So, it's time to do a real, live,
220 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
221 * (native). Both versions will work, but using __OS2__ offers multi-threading.
223 * Revision 1.37 2001/10/23 21:36:02 jongfoster
224 * Documenting sed()'s error behaviou (doc change only)
226 * Revision 1.36 2001/10/13 12:51:51 joergs
227 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
228 * force-load), instead crumble Host: and add it (again) in client_host_adder
229 * (in case we get a HTTP/1.0 request without Host: header and forward it to
230 * a HTTP/1.1 server/proxy).
232 * Revision 1.35 2001/10/09 22:39:21 jongfoster
233 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
236 * Revision 1.34 2001/10/07 18:50:55 oes
237 * Added server_content_encoding, renamed server_transfer_encoding
239 * Revision 1.33 2001/10/07 18:04:49 oes
240 * Changed server_http11 to server_http and its pattern to "HTTP".
241 * Additional functionality: it now saves the HTTP status into
242 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
244 * Revision 1.32 2001/10/07 15:43:28 oes
245 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
246 * client_te and client_accept_encoding_adder, triggered by the new
247 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
248 * changed to allow only identity and chunked, and the TE header is
249 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
251 * parse_http_request no longer does anything than parsing. The rewriting
252 * of http->cmd and version mangling are gone. It now also recognizes
253 * the put and delete methods and saves the url in http->url. Removed
256 * renamed content_type and content_length to have the server_ prefix
258 * server_content_type now only works if csp->content_type != CT_TABOO
260 * added server_transfer_encoding, which
261 * - Sets CT_TABOO to prohibit filtering if encoding compresses
262 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
263 * - Change from "chunked" to "identity" if body was chunked
264 * but has been de-chunked for filtering.
266 * added server_content_md5 which crunches any Content-MD5 headers
267 * if the body was modified.
269 * made server_http11 conditional on +downgrade action
271 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
273 * Revision 1.31 2001/10/05 14:25:02 oes
274 * Crumble Keep-Alive from Server
276 * Revision 1.30 2001/09/29 12:56:03 joergs
277 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
279 * Revision 1.29 2001/09/24 21:09:24 jongfoster
280 * Fixing 2 memory leaks that Guy spotted, where the paramater to
281 * enlist() was not being free()d.
283 * Revision 1.28 2001/09/22 16:32:28 jongfoster
284 * Removing unused #includes.
286 * Revision 1.27 2001/09/20 15:45:25 steudten
288 * add casting from size_t to int for printf()
289 * remove local variable shadow s2
291 * Revision 1.26 2001/09/16 17:05:14 jongfoster
292 * Removing unused #include showarg.h
294 * Revision 1.25 2001/09/16 13:21:27 jongfoster
295 * Changes to use new list functions.
297 * Revision 1.24 2001/09/13 23:05:50 jongfoster
298 * Changing the string paramater to the header parsers a "const".
300 * Revision 1.23 2001/09/12 18:08:19 steudten
302 * In parse_http_request() header rewriting miss the host value, so
303 * from http://www.mydomain.com the result was just " / " not
304 * http://www.mydomain.com/ in case we forward.
306 * Revision 1.22 2001/09/10 10:58:53 oes
307 * Silenced compiler warnings
309 * Revision 1.21 2001/07/31 14:46:00 oes
310 * - Persistant connections now suppressed
311 * - sed() no longer appends empty header to csp->headers
313 * Revision 1.20 2001/07/30 22:08:36 jongfoster
314 * Tidying up #defines:
315 * - All feature #defines are now of the form FEATURE_xxx
316 * - Permanently turned off WIN_GUI_EDIT
317 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
319 * Revision 1.19 2001/07/25 17:21:54 oes
320 * client_uagent now saves copy of User-Agent: header value
322 * Revision 1.18 2001/07/13 14:02:46 oes
323 * - Included fix to repair broken HTTP requests that
324 * don't contain a path, not even '/'.
325 * - Removed all #ifdef PCRS
326 * - content_type now always inspected and classified as
327 * text, gif or other.
328 * - formatting / comments
330 * Revision 1.17 2001/06/29 21:45:41 oes
331 * Indentation, CRLF->LF, Tab-> Space
333 * Revision 1.16 2001/06/29 13:32:42 oes
335 * - Adapted free_http_request
336 * - Removed logentry from cancelled commit
338 * Revision 1.15 2001/06/03 19:12:38 oes
339 * deleted const struct interceptors
341 * Revision 1.14 2001/06/01 18:49:17 jongfoster
342 * Replaced "list_share" with "list" - the tiny memory gain was not
343 * worth the extra complexity.
345 * Revision 1.13 2001/05/31 21:30:33 jongfoster
346 * Removed list code - it's now in list.[ch]
347 * Renamed "permission" to "action", and changed many features
348 * to use the actions file rather than the global config.
350 * Revision 1.12 2001/05/31 17:33:13 oes
354 * Revision 1.11 2001/05/29 20:11:19 joergs
355 * '/ * inside comment' warning removed.
357 * Revision 1.10 2001/05/29 09:50:24 jongfoster
358 * Unified blocklist/imagelist/permissionslist.
359 * File format is still under discussion, but the internal changes
362 * Also modified interceptor behaviour:
363 * - We now intercept all URLs beginning with one of the following
364 * prefixes (and *only* these prefixes):
366 * * http://ijbswa.sf.net/config/
367 * * http://ijbswa.sourceforge.net/config/
368 * - New interceptors "home page" - go to http://i.j.b/ to see it.
369 * - Internal changes so that intercepted and fast redirect pages
370 * are not replaced with an image.
371 * - Interceptors now have the option to send a binary page direct
372 * to the client. (i.e. ijb-send-banner uses this)
373 * - Implemented show-url-info interceptor. (Which is why I needed
374 * the above interceptors changes - a typical URL is
375 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
376 * The previous mechanism would not have intercepted that, and
377 * if it had been intercepted then it then it would have replaced
380 * Revision 1.9 2001/05/28 17:26:33 jongfoster
381 * Fixing segfault if last header was crunched.
382 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
383 * can use the cross-platform sprintf() instead.)
385 * Revision 1.8 2001/05/27 22:17:04 oes
387 * - re_process_buffer no longer writes the modified buffer
388 * to the client, which was very ugly. It now returns the
389 * buffer, which it is then written by chat.
391 * - content_length now adjusts the Content-Length: header
392 * for modified documents rather than crunch()ing it.
393 * (Length info in csp->content_length, which is 0 for
394 * unmodified documents)
396 * - For this to work, sed() is called twice when filtering.
398 * Revision 1.7 2001/05/27 13:19:06 oes
399 * Patched Joergs solution for the content-length in.
401 * Revision 1.6 2001/05/26 13:39:32 jongfoster
402 * Only crunches Content-Length header if applying RE filtering.
403 * Without this fix, Microsoft Windows Update wouldn't work.
405 * Revision 1.5 2001/05/26 00:28:36 jongfoster
406 * Automatic reloading of config file.
407 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
408 * Most of the global variables have been moved to a new
409 * struct configuration_spec, accessed through csp->config->globalname
410 * Most of the globals remaining are used by the Win32 GUI.
412 * Revision 1.4 2001/05/22 18:46:04 oes
414 * - Enabled filtering banners by size rather than URL
415 * by adding patterns that replace all standard banner
416 * sizes with the "Junkbuster" gif to the re_filterfile
418 * - Enabled filtering WebBugs by providing a pattern
419 * which kills all 1x1 images
421 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
422 * which is selected by the (nonstandard and therefore
423 * capital) letter 'U' in the option string.
424 * It causes the quantifiers to be ungreedy by default.
425 * Appending a ? turns back to greedy (!).
427 * - Added a new interceptor ijb-send-banner, which
428 * sends back the "Junkbuster" gif. Without imagelist or
429 * MSIE detection support, or if tinygif = 1, or the
430 * URL isn't recognized as an imageurl, a lame HTML
431 * explanation is sent instead.
433 * - Added new feature, which permits blocking remote
434 * script redirects and firing back a local redirect
436 * The feature is conditionally compiled, i.e. it
437 * can be disabled with --disable-fast-redirects,
438 * plus it must be activated by a "fast-redirects"
439 * line in the config file, has its own log level
440 * and of course wants to be displayed by show-proxy-args
441 * Note: Boy, all the #ifdefs in 1001 locations and
442 * all the fumbling with configure.in and acconfig.h
443 * were *way* more work than the feature itself :-(
445 * - Because a generic redirect template was needed for
446 * this, tinygif = 3 now uses the same.
448 * - Moved GIFs, and other static HTTP response templates
453 * - Removed some >400 CRs again (Jon, you really worked
456 * Revision 1.3 2001/05/20 01:21:20 jongfoster
457 * Version 2.9.4 checkin.
458 * - Merged popupfile and cookiefile, and added control over PCRS
459 * filtering, in new "permissionsfile".
460 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
461 * file error you now get a message box (in the Win32 GUI) rather
462 * than the program exiting with no explanation.
463 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
465 * - Removed tabs from "config"
466 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
467 * - Bumped up version number.
469 * Revision 1.2 2001/05/17 23:02:36 oes
470 * - Made referrer option accept 'L' as a substitute for '§'
472 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
473 * Initial import of version 2.9.3 source tree
476 *********************************************************************/
483 #include <sys/types.h>
492 #if !defined(_WIN32) && !defined(__OS2__)
501 /* jcc.h is for mutex semapores only */
502 #endif /* def OSX_DARWIN */
508 #include "jbsockets.h"
509 #include "miscutil.h"
512 #ifndef HAVE_STRPTIME
513 #include "strptime.h"
516 const char parsers_h_rcs[] = PARSERS_H_VERSION;
518 /* Fix a problem with Solaris. There should be no effect on other
520 * Solaris's isspace() is a macro which uses it's argument directly
521 * as an array index. Therefore we need to make sure that high-bit
522 * characters generate +ve values, and ideally we also want to make
523 * the argument match the declared parameter type of "int".
525 * Why did they write a character function that can't take a simple
526 * "char" argument? Doh!
528 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
529 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
532 const struct parsers client_patterns[] = {
533 { "referer:", 8, client_referrer },
534 { "user-agent:", 11, client_uagent },
535 { "ua-", 3, client_ua },
536 { "from:", 5, client_from },
537 { "cookie:", 7, client_send_cookie },
538 { "x-forwarded-for:", 16, client_x_forwarded },
539 { "Accept-Encoding:", 16, client_accept_encoding },
540 { "TE:", 3, client_te },
541 { "Host:", 5, client_host },
542 { "if-modified-since:", 18, client_if_modified_since },
543 { "Keep-Alive:", 11, crumble },
544 { "connection:", 11, crumble },
545 { "proxy-connection:", 17, crumble },
546 { "max-forwards:", 13, client_max_forwards },
547 { "Accept-Language:", 16, client_accept_language },
548 { "if-none-match:", 14, client_if_none_match },
549 { "X-Filter:", 9, client_x_filter },
550 { "*", 0, crunch_client_header },
551 { "*", 0, filter_client_header },
555 const struct parsers server_patterns[] = {
556 { "HTTP", 4, server_http },
557 { "set-cookie:", 11, server_set_cookie },
558 { "connection:", 11, crumble },
559 { "Content-Type:", 13, server_content_type },
560 { "Content-Length:", 15, server_content_length },
561 { "Content-MD5:", 12, server_content_md5 },
562 { "Content-Encoding:", 17, server_content_encoding },
563 { "Transfer-Encoding:", 18, server_transfer_coding },
564 { "Keep-Alive:", 11, crumble },
565 { "content-disposition:", 20, server_content_disposition },
566 { "Last-Modified:", 14, server_last_modified },
567 { "*", 0, crunch_server_header },
568 { "*", 0, filter_server_header },
572 const struct parsers server_patterns_light[] = {
573 { "Content-Length:", 15, server_content_length },
574 { "Transfer-Encoding:", 18, server_transfer_coding },
578 const add_header_func_ptr add_client_headers[] = {
581 client_x_forwarded_adder,
583 /* Temporarily disabled: client_accept_encoding_adder, */
584 connection_close_adder,
589 const add_header_func_ptr add_server_headers[] = {
590 connection_close_adder,
594 /*********************************************************************
596 * Function : flush_socket
598 * Description : Write any pending "buffered" content.
601 * 1 : fd = file descriptor of the socket to read
602 * 2 : csp = Current client state (buffers, headers, etc...)
604 * Returns : On success, the number of bytes written are returned (zero
605 * indicates nothing was written). On error, -1 is returned,
606 * and errno is set appropriately. If count is zero and the
607 * file descriptor refers to a regular file, 0 will be
608 * returned without causing any other effect. For a special
609 * file, the results are not portable.
611 *********************************************************************/
612 int flush_socket(jb_socket fd, struct client_state *csp)
614 struct iob *iob = csp->iob;
615 int len = iob->eod - iob->cur;
622 if (write_socket(fd, iob->cur, (size_t)len))
626 iob->eod = iob->cur = iob->buf;
632 /*********************************************************************
634 * Function : add_to_iob
636 * Description : Add content to the buffered page, expanding the
637 * buffer if necessary.
640 * 1 : csp = Current client state (buffers, headers, etc...)
641 * 2 : buf = holds the content to be added to the page
642 * 3 : n = number of bytes to be added
644 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
645 * or buffer limit reached.
647 *********************************************************************/
648 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
650 struct iob *iob = csp->iob;
651 size_t used, offset, need, want;
654 if (n <= 0) return JB_ERR_OK;
656 used = iob->eod - iob->buf;
657 offset = iob->cur - iob->buf;
661 * If the buffer can't hold the new data, extend it first.
662 * Use the next power of two if possible, else use the actual need.
664 if (need > csp->config->buffer_limit)
666 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
667 return JB_ERR_MEMORY;
670 if (need > iob->size)
672 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
674 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
678 else if (NULL != (p = (char *)realloc(iob->buf, need)))
684 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
685 return JB_ERR_MEMORY;
688 /* Update the iob pointers */
689 iob->cur = p + offset;
694 /* copy the new data into the iob buffer */
695 memcpy(iob->eod, buf, (size_t)n);
697 /* point to the end of the data */
700 /* null terminate == cheap insurance */
708 /*********************************************************************
710 * Function : get_header
712 * Description : This (odd) routine will parse the csp->iob
715 * 1 : csp = Current client state (buffers, headers, etc...)
717 * Returns : Any one of the following:
719 * 1) a pointer to a dynamically allocated string that contains a header line
720 * 2) NULL indicating that the end of the header was reached
721 * 3) "" indicating that the end of the iob was reached before finding
722 * a complete header line.
724 *********************************************************************/
725 char *get_header(struct client_state *csp)
731 if ((iob->cur == NULL)
732 || ((p = strchr(iob->cur, '\n')) == NULL))
734 return(""); /* couldn't find a complete header */
739 ret = strdup(iob->cur);
742 /* FIXME No way to handle error properly */
743 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
748 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
750 /* is this a blank line (i.e. the end of the header) ? */
762 /*********************************************************************
764 * Function : get_header_value
766 * Description : Get the value of a given header from a chained list
767 * of header lines or return NULL if no such header is
768 * present in the list.
771 * 1 : header_list = pointer to list
772 * 2 : header_name = string with name of header to look for.
773 * Trailing colon required, capitalization
776 * Returns : NULL if not found, else value of header
778 *********************************************************************/
779 char *get_header_value(const struct list *header_list, const char *header_name)
781 struct list_entry *cur_entry;
787 length = strlen(header_name);
789 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
793 if (!strncmpic(cur_entry->str, header_name, length))
796 * Found: return pointer to start of value
798 ret = (char *) (cur_entry->str + length);
799 while (*ret && ijb_isspace(*ret)) ret++;
812 /*********************************************************************
816 * Description : add, delete or modify lines in the HTTP header streams.
817 * On entry, it receives a linked list of headers space
818 * that was allocated dynamically (both the list nodes
819 * and the header contents).
821 * As a side effect it frees the space used by the original
825 * 1 : pats = list of patterns to match against headers
826 * 2 : more_headers = list of functions to add more
827 * headers (client or server)
828 * 3 : csp = Current client state (buffers, headers, etc...)
830 * Returns : Single pointer to a fully formed header, or NULL
831 * on out-of-memory error.
833 *********************************************************************/
834 char *sed(const struct parsers pats[],
835 const add_header_func_ptr more_headers[],
836 struct client_state *csp)
838 struct list_entry *p;
839 const struct parsers *v;
840 const add_header_func_ptr *f;
841 jb_err err = JB_ERR_OK;
845 * If filtering is enabled, sed is run twice,
846 * but most of the work needs to be done only once.
848 first_run = (more_headers != NULL ) ? 1 : 0;
850 if (first_run) /* Parse and print */
852 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
854 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
856 /* Header crunch()ed in previous run? -> ignore */
857 if (p->str == NULL) continue;
859 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
861 /* Does the current parser handle this header? */
862 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
864 err = v->parser(csp, (char **)&(p->str));
868 /* place any additional headers on the csp->headers list */
869 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
874 else /* Parse only */
877 * The second run is only needed if the body was modified
878 * and the content-lenght has changed.
880 if (strncmpic(csp->http->cmd, "HEAD", 4))
882 /*XXX: Code duplication*/
883 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
885 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
887 /* Header crunch()ed in previous run? -> ignore */
888 if (p->str == NULL) continue;
890 /* Does the current parser handle this header? */
891 if (strncmpic(p->str, v->str, v->len) == 0)
893 err = v->parser(csp, (char **)&(p->str));
900 if (err != JB_ERR_OK)
905 return list_to_text(csp->headers);
909 /* here begins the family of parser functions that reformat header lines */
911 /*********************************************************************
913 * Function : filter_server_header
915 * Description : Checks if server header filtering is enabled.
916 * If it is, filter_header is called to do the work.
919 * 1 : csp = Current client state (buffers, headers, etc...)
920 * 2 : header = On input, pointer to header to modify.
921 * On output, pointer to the modified header, or NULL
922 * to remove the header. This function frees the
923 * original string if necessary.
925 * Returns : JB_ERR_OK on success and always succeeds
927 *********************************************************************/
928 jb_err filter_server_header(struct client_state *csp, char **header)
930 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
932 filter_header(csp, header);
937 /*********************************************************************
939 * Function : filter_client_header
941 * Description : Checks if client header filtering is enabled.
942 * If it is, filter_header is called to do the work.
945 * 1 : csp = Current client state (buffers, headers, etc...)
946 * 2 : header = On input, pointer to header to modify.
947 * On output, pointer to the modified header, or NULL
948 * to remove the header. This function frees the
949 * original string if necessary.
951 * Returns : JB_ERR_OK on success and always succeeds
953 *********************************************************************/
954 jb_err filter_client_header(struct client_state *csp, char **header)
956 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
958 filter_header(csp, header);
963 /*********************************************************************
965 * Function : filter_header
967 * Description : Executes all text substitutions from all applying
968 * +filter actions on the header.
969 * Most of the code was copied from pcrs_filter_response,
970 * including the rather short variable names
973 * 1 : csp = Current client state (buffers, headers, etc...)
974 * 2 : header = On input, pointer to header to modify.
975 * On output, pointer to the modified header, or NULL
976 * to remove the header. This function frees the
977 * original string if necessary.
979 * Returns : JB_ERR_OK on success and always succeeds
981 *********************************************************************/
982 jb_err filter_header(struct client_state *csp, char **header)
986 size_t size = strlen(*header);
988 char *newheader = NULL;
991 struct file_list *fl;
992 struct re_filterfile_spec *b;
993 struct list_entry *filtername;
995 int i, found_filters = 0;
997 log_error(LOG_LEVEL_RE_FILTER, "Entered filter_headers");
999 * Need to check the set of re_filterfiles...
1001 for (i = 0; i < MAX_AF_FILES; i++)
1014 if (0 == found_filters)
1016 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1020 for (i = 0; i < MAX_AF_FILES; i++)
1023 if ((NULL == fl) || (NULL == fl->f))
1026 * For all applying +filter actions, look if a filter by that
1027 * name exists and if yes, execute its pcrs_joblist on the
1030 for (b = fl->f; b; b = b->next)
1032 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1033 filtername ; filtername = filtername->next)
1035 if (strcmp(b->name, filtername->str) == 0)
1037 int current_hits = 0;
1039 if ( NULL == b->joblist )
1041 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1045 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1046 *header, size, b->name);
1048 /* Apply all jobs from the joblist */
1049 for (job = b->joblist; NULL != job; job = job->next)
1051 matches = pcrs_execute(job, *header, size, &newheader, &size);
1054 current_hits += matches;
1055 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1057 *header = newheader;
1059 else if ( 0 == matches )
1061 /* Filter doesn't change header */
1067 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1068 *header, b->name, pcrs_strerror(matches));
1069 if( newheader != NULL)
1071 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1076 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1077 hits += current_hits;
1085 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1088 log_error(LOG_LEVEL_RE_FILTER, "Leaving filter headers");
1094 /*********************************************************************
1096 * Function : crumble
1098 * Description : This is called if a header matches a pattern to "crunch"
1101 * 1 : csp = Current client state (buffers, headers, etc...)
1102 * 2 : header = On input, pointer to header to modify.
1103 * On output, pointer to the modified header, or NULL
1104 * to remove the header. This function frees the
1105 * original string if necessary.
1107 * Returns : JB_ERR_OK on success, or
1108 * JB_ERR_MEMORY on out-of-memory error.
1110 *********************************************************************/
1111 jb_err crumble(struct client_state *csp, char **header)
1113 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1118 /*********************************************************************
1120 * Function : crunch_server_header
1122 * Description : Crunch server header if it matches a string supplied by the
1123 * user. Called from `sed'.
1126 * 1 : csp = Current client state (buffers, headers, etc...)
1127 * 2 : header = On input, pointer to header to modify.
1128 * On output, pointer to the modified header, or NULL
1129 * to remove the header. This function frees the
1130 * original string if necessary.
1132 * Returns : JB_ERR_OK on success and always succeeds
1134 *********************************************************************/
1135 jb_err crunch_server_header(struct client_state *csp, char **header)
1137 const char *crunch_pattern;
1138 /*Is there a header to crunch*/
1140 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1142 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1144 /*Is the current header the lucky one?*/
1145 if (strstr(*header, crunch_pattern))
1147 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1154 /*********************************************************************
1156 * Function : server_content_type
1158 * Description : Set the content-type for filterable types (text/.*,
1159 * javascript and image/gif) unless filtering has been
1160 * forbidden (CT_TABOO) while parsing earlier headers.
1161 * NOTE: Since text/plain is commonly used by web servers
1162 * for files whose correct type is unknown, we don't
1163 * set CT_TEXT for it.
1166 * 1 : csp = Current client state (buffers, headers, etc...)
1167 * 2 : header = On input, pointer to header to modify.
1168 * On output, pointer to the modified header, or NULL
1169 * to remove the header. This function frees the
1170 * original string if necessary.
1172 * Returns : JB_ERR_OK on success, or
1173 * JB_ERR_MEMORY on out-of-memory error.
1175 *********************************************************************/
1176 jb_err server_content_type(struct client_state *csp, char **header)
1180 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1182 if (csp->content_type != CT_TABOO)
1184 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1185 || strstr(*header, "xml")
1186 || strstr(*header, "application/x-javascript"))
1187 csp->content_type = CT_TEXT;
1188 else if (strstr(*header, " image/gif"))
1189 csp->content_type = CT_GIF;
1190 else if (strstr(*header, " image/jpeg"))
1191 csp->content_type = CT_JPEG;
1193 csp->content_type = 0;
1196 * Are we enabling text mode by force?
1198 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1201 * Do we really have to?
1203 if (csp->content_type == CT_TEXT)
1205 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1209 csp->content_type = CT_TEXT;
1210 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1214 * Are we messing with the content type?
1216 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1219 * Make sure the user doesn't accidently
1220 * change the content type of binary documents.
1222 if (csp->content_type == CT_TEXT)
1225 *header = strdup("Content-Type: ");
1226 string_append(header, newval);
1230 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1231 return JB_ERR_MEMORY;
1233 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1237 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1238 "Enable force-text-mode if you know what you're doing.", *header);
1245 /*********************************************************************
1247 * Function : server_transfer_coding
1249 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1250 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1251 * - Change from "chunked" to "identity" if body was chunked
1252 * but has been de-chunked for filtering.
1255 * 1 : csp = Current client state (buffers, headers, etc...)
1256 * 2 : header = On input, pointer to header to modify.
1257 * On output, pointer to the modified header, or NULL
1258 * to remove the header. This function frees the
1259 * original string if necessary.
1261 * Returns : JB_ERR_OK on success, or
1262 * JB_ERR_MEMORY on out-of-memory error.
1264 *********************************************************************/
1265 jb_err server_transfer_coding(struct client_state *csp, char **header)
1268 * Turn off pcrs and gif filtering if body compressed
1270 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1272 csp->content_type = CT_TABOO;
1276 * Raise flag if body chunked
1278 if (strstr(*header, "chunked"))
1280 csp->flags |= CSP_FLAG_CHUNKED;
1283 * If the body was modified, it has been
1284 * de-chunked first, so adjust the header:
1286 if (csp->flags & CSP_FLAG_MODIFIED)
1289 *header = strdup("Transfer-Encoding: identity");
1290 log_error(LOG_LEVEL_HEADER, "Set: %s", *header);
1291 return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1299 /*********************************************************************
1301 * Function : server_content_encoding
1303 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1306 * 1 : csp = Current client state (buffers, headers, etc...)
1307 * 2 : header = On input, pointer to header to modify.
1308 * On output, pointer to the modified header, or NULL
1309 * to remove the header. This function frees the
1310 * original string if necessary.
1312 * Returns : JB_ERR_OK on success, or
1313 * JB_ERR_MEMORY on out-of-memory error.
1315 *********************************************************************/
1316 jb_err server_content_encoding(struct client_state *csp, char **header)
1319 * Turn off pcrs and gif filtering if body compressed
1321 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1323 csp->content_type = CT_TABOO;
1331 /*********************************************************************
1333 * Function : server_content_length
1335 * Description : Adjust Content-Length header if we modified
1339 * 1 : csp = Current client state (buffers, headers, etc...)
1340 * 2 : header = On input, pointer to header to modify.
1341 * On output, pointer to the modified header, or NULL
1342 * to remove the header. This function frees the
1343 * original string if necessary.
1345 * Returns : JB_ERR_OK on success, or
1346 * JB_ERR_MEMORY on out-of-memory error.
1348 *********************************************************************/
1349 jb_err server_content_length(struct client_state *csp, char **header)
1351 if (csp->content_length != 0) /* Content length could have been modified */
1354 * XXX: Shouldn't we check if csp->content_length
1355 * is different than the original value?
1358 *header = (char *) zalloc(100);
1359 if (*header == NULL)
1361 return JB_ERR_MEMORY;
1364 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1366 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1373 /*********************************************************************
1375 * Function : server_content_md5
1377 * Description : Crumble any Content-MD5 headers if the document was
1378 * modified. FIXME: Should we re-compute instead?
1381 * 1 : csp = Current client state (buffers, headers, etc...)
1382 * 2 : header = On input, pointer to header to modify.
1383 * On output, pointer to the modified header, or NULL
1384 * to remove the header. This function frees the
1385 * original string if necessary.
1387 * Returns : JB_ERR_OK on success, or
1388 * JB_ERR_MEMORY on out-of-memory error.
1390 *********************************************************************/
1391 jb_err server_content_md5(struct client_state *csp, char **header)
1393 if (csp->flags & CSP_FLAG_MODIFIED)
1395 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1402 /*********************************************************************
1404 * Function : server_content_disposition
1406 * Description : If enabled, blocks or modifies the "content-disposition" header.
1407 * Called from `sed'.
1410 * 1 : csp = Current client state (buffers, headers, etc...)
1411 * 2 : header = On input, pointer to header to modify.
1412 * On output, pointer to the modified header, or NULL
1413 * to remove the header. This function frees the
1414 * original string if necessary.
1416 * Returns : JB_ERR_OK on success, or
1417 * JB_ERR_MEMORY on out-of-memory error.
1419 *********************************************************************/
1420 jb_err server_content_disposition(struct client_state *csp, char **header)
1425 * Are we messing with the content-disposition header?
1427 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1433 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1435 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1438 * Blocking content-disposition header
1440 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1447 * Replacing content-disposition header
1450 *header = strdup("content-disposition: ");
1451 string_append(header, newval);
1453 if (*header == NULL)
1455 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1459 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1462 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1465 /*********************************************************************
1467 * Function : server_last_modified
1469 * Description : Changes Last-Modified header to the actual date
1470 * to help hide-if-modified-since.
1471 * Called from `sed'.
1474 * 1 : csp = Current client state (buffers, headers, etc...)
1475 * 2 : header = On input, pointer to header to modify.
1476 * On output, pointer to the modified header, or NULL
1477 * to remove the header. This function frees the
1478 * original string if necessary.
1480 * Returns : JB_ERR_OK on success, or
1481 * JB_ERR_MEMORY on out-of-memory error.
1483 *********************************************************************/
1484 jb_err server_last_modified(struct client_state *csp, char **header)
1487 char buf[BUFFER_SIZE];
1490 #ifdef HAVE_GMTIME_R
1493 struct tm *timeptr = NULL;
1494 time_t now, last_modified;
1496 long int days, hours, minutes, seconds;
1499 * Are we messing with the Last-Modified header?
1501 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1507 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1509 if (0 == strcmpic(newval, "block") )
1512 * Blocking Last-Modified header. Useless but why not.
1514 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1518 else if (0 == strcmpic(newval, "reset-to-request-time"))
1521 * Setting Last-Modified Header to now.
1523 get_http_time(0, buf);
1525 *header = strdup("Last-Modified: ");
1526 string_append(header, buf);
1528 if (*header == NULL)
1530 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1534 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1537 else if (0 == strcmpic(newval, "randomize"))
1539 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1541 #ifdef HAVE_GMTIME_R
1542 timeptr = gmtime_r(&now, &gmt);
1544 pthread_mutex_lock(&gmtime_mutex);
1545 timeptr = gmtime(&now);
1546 pthread_mutex_unlock(&gmtime_mutex);
1548 timeptr = gmtime(&now);
1550 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
1552 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1557 rtime = difftime(now, last_modified);
1560 rtime = pick_from_range(rtime);
1561 last_modified += rtime;
1562 #ifdef HAVE_GMTIME_R
1563 timeptr = gmtime_r(&last_modified, &gmt);
1565 pthread_mutex_lock(&gmtime_mutex);
1566 timeptr = gmtime(&last_modified);
1567 pthread_mutex_unlock(&gmtime_mutex);
1569 timeptr = gmtime(&last_modified);
1571 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1573 *header = strdup("Last-Modified: ");
1574 string_append(header, newheader);
1576 if (*header == NULL)
1578 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
1579 return JB_ERR_MEMORY;
1582 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1584 days = rtime / (3600 * 24);
1585 hours = rtime / 3600 % 24;
1586 minutes = rtime / 60 % 60;
1587 seconds = rtime % 60;
1589 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1590 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1591 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1596 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1604 /*********************************************************************
1606 * Function : client_accept_encoding
1608 * Description : Rewrite the client's Accept-Encoding header so that
1609 * if doesn't allow compression, if the action applies.
1610 * Note: For HTTP/1.0 the absence of the header is enough.
1613 * 1 : csp = Current client state (buffers, headers, etc...)
1614 * 2 : header = On input, pointer to header to modify.
1615 * On output, pointer to the modified header, or NULL
1616 * to remove the header. This function frees the
1617 * original string if necessary.
1619 * Returns : JB_ERR_OK on success, or
1620 * JB_ERR_MEMORY on out-of-memory error.
1622 *********************************************************************/
1623 jb_err client_accept_encoding(struct client_state *csp, char **header)
1625 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1627 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1631 /* Temporarily disable the correct behaviour to
1632 * work around a PHP bug.
1634 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1636 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1637 * if (*header == NULL)
1639 * return JB_ERR_MEMORY;
1650 /*********************************************************************
1652 * Function : client_te
1654 * Description : Rewrite the client's TE header so that
1655 * if doesn't allow compression, if the action applies.
1658 * 1 : csp = Current client state (buffers, headers, etc...)
1659 * 2 : header = On input, pointer to header to modify.
1660 * On output, pointer to the modified header, or NULL
1661 * to remove the header. This function frees the
1662 * original string if necessary.
1664 * Returns : JB_ERR_OK on success, or
1665 * JB_ERR_MEMORY on out-of-memory error.
1667 *********************************************************************/
1668 jb_err client_te(struct client_state *csp, char **header)
1670 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1673 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1679 /*********************************************************************
1681 * Function : client_referrer
1683 * Description : Handle the "referer" config setting properly.
1684 * Called from `sed'.
1687 * 1 : csp = Current client state (buffers, headers, etc...)
1688 * 2 : header = On input, pointer to header to modify.
1689 * On output, pointer to the modified header, or NULL
1690 * to remove the header. This function frees the
1691 * original string if necessary.
1693 * Returns : JB_ERR_OK on success, or
1694 * JB_ERR_MEMORY on out-of-memory error.
1696 *********************************************************************/
1697 jb_err client_referrer(struct client_state *csp, char **header)
1704 #ifdef FEATURE_FORCE_LOAD
1705 /* Since the referrer can include the prefix even
1706 * if the request itself is non-forced, we must
1707 * clean it unconditionally
1709 strclean(*header, FORCE_PREFIX);
1710 #endif /* def FEATURE_FORCE_LOAD */
1713 * Are we sending referer?
1715 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1720 newval = csp->action->string[ACTION_STRING_REFERER];
1722 if ((0 != strcmpic(newval, "conditional-block")))
1726 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1731 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1734 else if (0 == strcmpic(newval, "conditional-block"))
1737 * Block referer if host has changed.
1740 if (NULL == (host = strdup(csp->http->hostport)))
1743 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1744 return JB_ERR_MEMORY;
1746 if (NULL == (referer = strdup(*header)))
1750 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1751 return JB_ERR_MEMORY;
1753 hostlenght = strlen(host);
1754 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1756 /*Shorten referer to make sure the referer is blocked
1757 *if www.example.org/www.example.com-shall-see-the-referer/
1758 *links to www.example.com/
1760 referer[hostlenght+17] = '\0';
1762 if ( 0 == strstr(referer, host)) /*Host has changed*/
1764 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1769 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1775 else if (0 != strcmpic(newval, "forge"))
1778 * We have a specific (fixed) referer we want to send.
1780 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1782 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1784 *header = strdup("Referer: ");
1785 string_append(header, newval);
1786 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1788 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1793 * Forge a referer as http://[hostname:port of REQUEST]/
1794 * to fool stupid checks for in-site links
1797 *header = strdup("Referer: http://");
1798 string_append(header, csp->http->hostport);
1799 string_append(header, "/");
1800 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1802 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1806 /*********************************************************************
1808 * Function : client_accept_language
1810 * Description : Handle the "Accept-Language" config setting properly.
1811 * Called from `sed'.
1814 * 1 : csp = Current client state (buffers, headers, etc...)
1815 * 2 : header = On input, pointer to header to modify.
1816 * On output, pointer to the modified header, or NULL
1817 * to remove the header. This function frees the
1818 * original string if necessary.
1820 * Returns : JB_ERR_OK on success, or
1821 * JB_ERR_MEMORY on out-of-memory error.
1823 *********************************************************************/
1824 jb_err client_accept_language(struct client_state *csp, char **header)
1829 * Are we messing with the Accept-Language?
1831 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1833 /*I don't think so*/
1837 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1839 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1842 * Blocking Accept-Language header
1844 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1851 * Replacing Accept-Language header
1854 *header = strdup("Accept-Language: ");
1855 string_append(header, newval);
1857 if (*header == NULL)
1859 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1863 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1866 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1869 /*********************************************************************
1871 * Function : crunch_client_header
1873 * Description : Crunch client header if it matches a string supplied by the
1874 * user. Called from `sed'.
1877 * 1 : csp = Current client state (buffers, headers, etc...)
1878 * 2 : header = On input, pointer to header to modify.
1879 * On output, pointer to the modified header, or NULL
1880 * to remove the header. This function frees the
1881 * original string if necessary.
1883 * Returns : JB_ERR_OK on success and always succeeds
1885 *********************************************************************/
1886 jb_err crunch_client_header(struct client_state *csp, char **header)
1888 const char *crunch_pattern;
1889 /*Is there a header to crunch*/
1891 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1893 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1895 /*Is the current header the lucky one?*/
1896 if (strstr(*header, crunch_pattern))
1898 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1906 /*********************************************************************
1908 * Function : client_uagent
1910 * Description : Handle the "user-agent" config setting properly
1911 * and remember its original value to enable browser
1912 * bug workarounds. Called from `sed'.
1915 * 1 : csp = Current client state (buffers, headers, etc...)
1916 * 2 : header = On input, pointer to header to modify.
1917 * On output, pointer to the modified header, or NULL
1918 * to remove the header. This function frees the
1919 * original string if necessary.
1921 * Returns : JB_ERR_OK on success, or
1922 * JB_ERR_MEMORY on out-of-memory error.
1924 *********************************************************************/
1925 jb_err client_uagent(struct client_state *csp, char **header)
1929 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1934 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1941 *header = strdup("User-Agent: ");
1942 string_append(header, newval);
1944 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
1946 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1949 /*********************************************************************
1951 * Function : client_ua
1953 * Description : Handle "ua-" headers properly. Called from `sed'.
1956 * 1 : csp = Current client state (buffers, headers, etc...)
1957 * 2 : header = On input, pointer to header to modify.
1958 * On output, pointer to the modified header, or NULL
1959 * to remove the header. This function frees the
1960 * original string if necessary.
1962 * Returns : JB_ERR_OK on success, or
1963 * JB_ERR_MEMORY on out-of-memory error.
1965 *********************************************************************/
1966 jb_err client_ua(struct client_state *csp, char **header)
1968 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1970 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
1978 /*********************************************************************
1980 * Function : client_from
1982 * Description : Handle the "from" config setting properly.
1983 * Called from `sed'.
1986 * 1 : csp = Current client state (buffers, headers, etc...)
1987 * 2 : header = On input, pointer to header to modify.
1988 * On output, pointer to the modified header, or NULL
1989 * to remove the header. This function frees the
1990 * original string if necessary.
1992 * Returns : JB_ERR_OK on success, or
1993 * JB_ERR_MEMORY on out-of-memory error.
1995 *********************************************************************/
1996 jb_err client_from(struct client_state *csp, char **header)
2000 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2007 newval = csp->action->string[ACTION_STRING_FROM];
2010 * Are we blocking the e-mail address?
2012 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2014 log_error(LOG_LEVEL_HEADER, "crunched From!");
2018 log_error(LOG_LEVEL_HEADER, " modified");
2020 *header = strdup("From: ");
2021 string_append(header, newval);
2023 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2027 /*********************************************************************
2029 * Function : client_send_cookie
2031 * Description : Handle the "cookie" header properly. Called from `sed'.
2032 * If cookie is accepted, add it to the cookie_list,
2033 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2036 * 1 : csp = Current client state (buffers, headers, etc...)
2037 * 2 : header = On input, pointer to header to modify.
2038 * On output, pointer to the modified header, or NULL
2039 * to remove the header. This function frees the
2040 * original string if necessary.
2042 * Returns : JB_ERR_OK on success, or
2043 * JB_ERR_MEMORY on out-of-memory error.
2045 *********************************************************************/
2046 jb_err client_send_cookie(struct client_state *csp, char **header)
2048 jb_err result = JB_ERR_OK;
2050 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2052 /* strlen("cookie: ") == 8 */
2053 result = enlist(csp->cookie_list, *header + 8);
2057 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2061 * Always remove the cookie here. The cookie header
2062 * will be sent at the end of the header.
2070 /*********************************************************************
2072 * Function : client_x_forwarded
2074 * Description : Handle the "x-forwarded-for" config setting properly,
2075 * also used in the add_client_headers list. Called from `sed'.
2078 * 1 : csp = Current client state (buffers, headers, etc...)
2079 * 2 : header = On input, pointer to header to modify.
2080 * On output, pointer to the modified header, or NULL
2081 * to remove the header. This function frees the
2082 * original string if necessary.
2084 * Returns : JB_ERR_OK on success, or
2085 * JB_ERR_MEMORY on out-of-memory error.
2087 *********************************************************************/
2088 jb_err client_x_forwarded(struct client_state *csp, char **header)
2090 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2092 /* Save it so we can re-add it later */
2093 freez(csp->x_forwarded);
2094 csp->x_forwarded = *header;
2097 * Always set *header = NULL, since this information
2098 * will be sent at the end of the header.
2105 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2112 /*********************************************************************
2114 * Function : client_max_forwards
2116 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2117 * from the value of the Max-Forwards header field.
2120 * 1 : csp = Current client state (buffers, headers, etc...)
2121 * 2 : header = On input, pointer to header to modify.
2122 * On output, pointer to the modified header, or NULL
2123 * to remove the header. This function frees the
2124 * original string if necessary.
2126 * Returns : JB_ERR_OK on success, or
2127 * JB_ERR_MEMORY on out-of-memory error.
2129 *********************************************************************/
2130 jb_err client_max_forwards(struct client_state *csp, char **header)
2132 unsigned int max_forwards;
2134 if ((0 == strcmpic(csp->http->gpc, "trace"))
2135 || (0 == strcmpic(csp->http->gpc, "options")))
2137 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2139 if (max_forwards-- >= 1)
2141 sprintf(*header, "Max-Forwards: %u", max_forwards);
2142 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2146 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2155 /*********************************************************************
2157 * Function : client_host
2159 * Description : If the request URI did not contain host and
2160 * port information, parse and evaluate the Host
2163 * Also, kill ill-formed HOST: headers as sent by
2164 * Apple's iTunes software when used with a proxy.
2167 * 1 : csp = Current client state (buffers, headers, etc...)
2168 * 2 : header = On input, pointer to header to modify.
2169 * On output, pointer to the modified header, or NULL
2170 * to remove the header. This function frees the
2171 * original string if necessary.
2173 * Returns : JB_ERR_OK on success, or
2174 * JB_ERR_MEMORY on out-of-memory error.
2176 *********************************************************************/
2177 jb_err client_host(struct client_state *csp, char **header)
2182 * If the header field name is all upper-case, chances are that it's
2183 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2184 * not a problem -- they are regenerated later.
2186 if ((*header)[1] == 'O')
2188 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2193 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2194 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2197 if (NULL == (p = strdup((*header)+6)))
2199 return JB_ERR_MEMORY;
2202 if (NULL == (q = strdup(p)))
2205 return JB_ERR_MEMORY;
2208 freez(csp->http->hostport);
2209 csp->http->hostport = p;
2210 freez(csp->http->host);
2211 csp->http->host = q;
2212 q = strchr(csp->http->host, ':');
2215 /* Terminate hostname and evaluate port string */
2217 csp->http->port = atoi(q);
2221 csp->http->port = csp->http->ssl ? 443 : 80;
2224 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2225 csp->http->hostport, csp->http->host, csp->http->port);
2231 /*********************************************************************
2233 * Function : client_if_modified_since
2235 * Description : Remove or modify the If-Modified-Since header.
2238 * 1 : csp = Current client state (buffers, headers, etc...)
2239 * 2 : header = On input, pointer to header to modify.
2240 * On output, pointer to the modified header, or NULL
2241 * to remove the header. This function frees the
2242 * original string if necessary.
2244 * Returns : JB_ERR_OK on success, or
2245 * JB_ERR_MEMORY on out-of-memory error.
2247 *********************************************************************/
2248 jb_err client_if_modified_since(struct client_state *csp, char **header)
2251 #ifdef HAVE_GMTIME_R
2254 struct tm *timeptr = NULL;
2258 long int hours, minutes, seconds;
2262 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2265 * The client got an error message because of a temporary problem,
2266 * the problem is gone and the client now tries to revalidate our
2267 * error message on the real server. The revalidation would always
2268 * end with the transmission of the whole document and there is
2269 * no need to expose the bogus If-Modified-Since header.
2271 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2274 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2276 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2278 if ((0 == strcmpic(newval, "block")))
2280 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2283 else /* add random value */
2285 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2287 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2292 rtime = strtol(newval, &endptr, 0);
2300 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d hou%s)",
2301 *header, rtime, (rtime == 1 || rtime == -1) ? "r": "rs");
2303 rtime = pick_from_range(rtime);
2307 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2311 #ifdef HAVE_GMTIME_R
2312 timeptr = gmtime_r(&tm, &gmt);
2314 pthread_mutex_lock(&gmtime_mutex);
2315 timeptr = gmtime(&tm);
2316 pthread_mutex_unlock(&gmtime_mutex);
2318 timeptr = gmtime(&tm);
2320 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2323 *header = strdup("If-Modified-Since: ");
2324 string_append(header, newheader);
2326 if (*header == NULL)
2328 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2329 return JB_ERR_MEMORY;
2332 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2334 hours = rtime / 3600;
2335 minutes = rtime / 60 % 60;
2336 seconds = rtime % 60;
2338 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2339 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2340 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2349 /*********************************************************************
2351 * Function : client_if_none_match
2353 * Description : Remove the If-None-Match header.
2356 * 1 : csp = Current client state (buffers, headers, etc...)
2357 * 2 : header = On input, pointer to header to modify.
2358 * On output, pointer to the modified header, or NULL
2359 * to remove the header. This function frees the
2360 * original string if necessary.
2362 * Returns : JB_ERR_OK on success, or
2363 * JB_ERR_MEMORY on out-of-memory error.
2365 *********************************************************************/
2366 jb_err client_if_none_match(struct client_state *csp, char **header)
2368 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2370 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2377 /*********************************************************************
2379 * Function : client_x_filter
2381 * Description : Disables filtering if the client set "X-Filter: No".
2382 * Called from `sed'.
2385 * 1 : csp = Current client state (buffers, headers, etc...)
2386 * 2 : header = On input, pointer to header to modify.
2387 * On output, pointer to the modified header, or NULL
2388 * to remove the header. This function frees the
2389 * original string if necessary.
2391 * Returns : JB_ERR_OK on success
2393 *********************************************************************/
2394 jb_err client_x_filter(struct client_state *csp, char **header)
2396 if ( 0 == strcmpic(*header, "X-Filter: No"))
2398 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2400 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to disable filtering!");
2404 csp->content_type = CT_TABOO;
2405 log_error(LOG_LEVEL_HEADER, "Disabled filter mode on behalf of the client.");
2407 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2413 /* the following functions add headers directly to the header list */
2415 /*********************************************************************
2417 * Function : client_host_adder
2419 * Description : Adds the Host: header field if it is missing.
2420 * Called from `sed'.
2423 * 1 : csp = Current client state (buffers, headers, etc...)
2425 * Returns : JB_ERR_OK on success, or
2426 * JB_ERR_MEMORY on out-of-memory error.
2428 *********************************************************************/
2429 jb_err client_host_adder(struct client_state *csp)
2434 if ( !csp->http->hostport || !*(csp->http->hostport))
2440 * remove 'user:pass@' from 'proto://user:pass@host'
2442 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2448 p = csp->http->hostport;
2451 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2452 err = enlist_unique_header(csp->headers, "Host", p);
2458 /*********************************************************************
2460 * Function : client_cookie_adder
2462 * Description : Used in the add_client_headers list. Called from `sed'.
2465 * 1 : csp = Current client state (buffers, headers, etc...)
2467 * Returns : JB_ERR_OK on success, or
2468 * JB_ERR_MEMORY on out-of-memory error.
2470 *********************************************************************/
2471 jb_err client_cookie_adder(struct client_state *csp)
2473 struct list_entry *lst;
2475 struct list_entry *list1 = csp->cookie_list->first;
2476 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2477 int first_cookie = 1;
2480 if ((list1 == NULL) && (list2 == NULL))
2486 tmp = strdup("Cookie: ");
2488 for (lst = list1; lst ; lst = lst->next)
2496 string_append(&tmp, "; ");
2498 string_append(&tmp, lst->str);
2501 for (lst = list2; lst ; lst = lst->next)
2509 string_append(&tmp, "; ");
2511 string_join(&tmp, cookie_encode(lst->str));
2516 return JB_ERR_MEMORY;
2519 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2520 err = enlist(csp->headers, tmp);
2526 /*********************************************************************
2528 * Function : client_accept_encoding_adder
2530 * Description : Add an Accept-Encoding header to the client's request
2531 * that disables compression if the action applies, and
2532 * the header is not already there. Called from `sed'.
2533 * Note: For HTTP/1.0, the absence of the header is enough.
2536 * 1 : csp = Current client state (buffers, headers, etc...)
2538 * Returns : JB_ERR_OK on success, or
2539 * JB_ERR_MEMORY on out-of-memory error.
2541 *********************************************************************/
2542 jb_err client_accept_encoding_adder(struct client_state *csp)
2544 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2545 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2547 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2554 /*********************************************************************
2556 * Function : client_xtra_adder
2558 * Description : Used in the add_client_headers list. Called from `sed'.
2561 * 1 : csp = Current client state (buffers, headers, etc...)
2563 * Returns : JB_ERR_OK on success, or
2564 * JB_ERR_MEMORY on out-of-memory error.
2566 *********************************************************************/
2567 jb_err client_xtra_adder(struct client_state *csp)
2569 struct list_entry *lst;
2572 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2573 lst ; lst = lst->next)
2575 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2576 err = enlist(csp->headers, lst->str);
2588 /*********************************************************************
2590 * Function : client_x_forwarded_adder
2592 * Description : Used in the add_client_headers list. Called from `sed'.
2595 * 1 : csp = Current client state (buffers, headers, etc...)
2597 * Returns : JB_ERR_OK on success, or
2598 * JB_ERR_MEMORY on out-of-memory error.
2600 *********************************************************************/
2601 jb_err client_x_forwarded_adder(struct client_state *csp)
2606 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2611 if (csp->x_forwarded)
2613 p = strdup(csp->x_forwarded);
2614 string_append(&p, ", ");
2618 p = strdup("X-Forwarded-For: ");
2620 string_append(&p, csp->ip_addr_str);
2624 return JB_ERR_MEMORY;
2627 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2628 err = enlist(csp->headers, p);
2635 /*********************************************************************
2637 * Function : connection_close_adder
2639 * Description : Adds a "Connection: close" header to csp->headers
2640 * as a temporary fix for the needed but missing HTTP/1.1
2641 * support. Called from `sed'.
2642 * FIXME: This whole function shouldn't be neccessary!
2645 * 1 : csp = Current client state (buffers, headers, etc...)
2647 * Returns : JB_ERR_OK on success, or
2648 * JB_ERR_MEMORY on out-of-memory error.
2650 *********************************************************************/
2651 jb_err connection_close_adder(struct client_state *csp)
2653 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2654 return enlist(csp->headers, "Connection: close");
2658 /*********************************************************************
2660 * Function : server_http
2662 * Description : - Save the HTTP Status into csp->http->status
2663 * - Set CT_TABOO to prevent filtering if the answer
2664 * is a partial range (HTTP status 206)
2665 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2669 * 1 : csp = Current client state (buffers, headers, etc...)
2670 * 2 : header = On input, pointer to header to modify.
2671 * On output, pointer to the modified header, or NULL
2672 * to remove the header. This function frees the
2673 * original string if necessary.
2675 * Returns : JB_ERR_OK on success, or
2676 * JB_ERR_MEMORY on out-of-memory error.
2678 *********************************************************************/
2679 jb_err server_http(struct client_state *csp, char **header)
2681 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2682 if (csp->http->status == 206)
2684 csp->content_type = CT_TABOO;
2687 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2690 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2697 /*********************************************************************
2699 * Function : server_set_cookie
2701 * Description : Handle the server "cookie" header properly.
2702 * Log cookie to the jar file. Then "crunch" it,
2703 * or accept it. Called from `sed'.
2706 * 1 : csp = Current client state (buffers, headers, etc...)
2707 * 2 : header = On input, pointer to header to modify.
2708 * On output, pointer to the modified header, or NULL
2709 * to remove the header. This function frees the
2710 * original string if necessary.
2712 * Returns : JB_ERR_OK on success, or
2713 * JB_ERR_MEMORY on out-of-memory error.
2715 *********************************************************************/
2716 jb_err server_set_cookie(struct client_state *csp, char **header)
2718 #ifdef FEATURE_COOKIE_JAR
2719 if (csp->config->jar)
2722 * Write timestamp into outbuf.
2724 * Complex because not all OSs have tm_gmtoff or
2725 * the %z field in strftime()
2727 char tempbuf[ BUFFER_SIZE ];
2731 #ifdef HAVE_LOCALTIME_R
2732 tm_now = *localtime_r(&now, &tm_now);
2734 pthread_mutex_lock(&localtime_mutex);
2735 tm_now = *localtime (&now);
2736 pthread_mutex_unlock(&localtime_mutex);
2738 tm_now = *localtime (&now);
2740 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2742 /* strlen("set-cookie: ") = 12 */
2743 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2745 #endif /* def FEATURE_COOKIE_JAR */
2747 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2749 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2750 return crumble(csp, header);
2752 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2754 /* Flag whether or not to log a message */
2757 /* A variable to store the tag we're working on */
2760 /* Skip "Set-Cookie:" (11 characters) in header */
2761 cur_tag = *header + 11;
2763 /* skip whitespace between "Set-Cookie:" and value */
2764 while (*cur_tag && ijb_isspace(*cur_tag))
2769 /* Loop through each tag in the cookie */
2773 char *next_tag = strchr(cur_tag, ';');
2774 if (next_tag != NULL)
2776 /* Skip the ';' character itself */
2779 /* skip whitespace ";" and start of tag */
2780 while (*next_tag && ijb_isspace(*next_tag))
2787 /* "Next tag" is the end of the string */
2788 next_tag = cur_tag + strlen(cur_tag);
2791 /* Is this the "Expires" tag? */
2792 if (strncmpic(cur_tag, "expires=", 8) == 0)
2794 /* Delete the tag by copying the rest of the string over it.
2795 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2796 * since the behaviour of strcpy is undefined for overlapping
2799 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2801 /* That changed the header, need to issue a log message */
2804 /* Note that the next tag has now been moved to *cur_tag,
2805 * so we do not need to update the cur_tag pointer.
2810 /* Move on to next cookie tag */
2817 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2825 #ifdef FEATURE_FORCE_LOAD
2826 /*********************************************************************
2828 * Function : strclean
2830 * Description : In-Situ-Eliminate all occurances of substring in
2834 * 1 : string = string to clean
2835 * 2 : substring = substring to eliminate
2837 * Returns : Number of eliminations
2839 *********************************************************************/
2840 int strclean(const char *string, const char *substring)
2842 int hits = 0, len = strlen(substring);
2845 while((pos = strstr(string, substring)) != NULL)
2852 while (*p++ != '\0');
2859 #endif /* def FEATURE_FORCE_LOAD */
2861 /*********************************************************************
2863 * Function : parse_header_time
2865 * Description : Transforms time inside a HTTP header into
2866 * the usual time format.
2869 * 1 : header = header to parse
2870 * 2 : tm = storage for the resulting time in seconds
2872 * Returns : Time struct containing the header time, or
2873 * NULL in case of a parsing problem.
2875 *********************************************************************/
2876 struct tm *parse_header_time(char *header, time_t *tm) {
2879 struct tm * timeptr;
2882 timeptr = localtime(tm);
2883 /* Skipping header name */
2884 timestring = strstr(header, ": ");
2885 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", timeptr) == NULL)
2891 *tm = timegm(timeptr);