1 const char parsers_rcs[] = "$Id: parsers.c,v 1.60 2006/08/12 03:54:37 david__schmidt 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.60 2006/08/12 03:54:37 david__schmidt
44 * Windows service integration
46 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
47 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
49 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
50 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
51 * with what was really the latest development (the v_3_0_branch branch)
53 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
54 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
56 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
57 * Add the ability to check jpeg images for invalid
58 * lengths of comment blocks. Defensive strategy
59 * against the exploit:
60 * Microsoft Security Bulletin MS04-028
61 * Buffer Overrun in JPEG Processing (GDI+) Could
62 * Allow Code Execution (833987)
63 * Enabled with +inspect-jpegs in actions files.
65 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
66 * Excluded text/plain objects from filtering. This fixes a
67 * couple of client-crashing, download corruption and
68 * Privoxy performance issues, whose root cause lies in
69 * web servers labelling content of unknown type as text/plain.
71 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
72 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
74 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
75 * Completing the previous change
77 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
78 * Added temporary workaround for bug in PHP < 4.2.3
80 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
81 * 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.
83 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
84 * Fix typo: supressed -> suppressed
86 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
87 * Improved cookie logging
89 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
90 * Added basic support for OPTIONS and TRACE HTTP methods:
91 * - New parser function client_max_forwards which decrements
92 * the Max-Forwards HTTP header field of OPTIONS and TRACE
93 * requests by one before forwarding
94 * - New parser function client_host which extracts the host
95 * and port information from the HTTP header field if the
96 * request URI was not absolute
97 * - Don't crumble and re-add the Host: header, but only generate
98 * and append if missing
100 * Revision 1.56 2002/05/12 15:34:22 jongfoster
101 * Fixing typo in a comment
103 * Revision 1.55 2002/05/08 16:01:07 oes
104 * Optimized add_to_iob:
105 * - Use realloc instead of malloc(), memcpy(), free()
106 * - Expand to powers of two if possible, to get
107 * O(log n) reallocs instead of O(n).
108 * - Moved check for buffer limit here from chat
109 * - Report failure via returncode
111 * Revision 1.54 2002/04/02 15:03:16 oes
112 * Tiny code cosmetics
114 * Revision 1.53 2002/03/26 22:29:55 swa
115 * we have a new homepage!
117 * Revision 1.52 2002/03/24 13:25:43 swa
118 * name change related issues
120 * Revision 1.51 2002/03/13 00:27:05 jongfoster
123 * Revision 1.50 2002/03/12 01:45:35 oes
124 * More verbose logging
126 * Revision 1.49 2002/03/09 20:03:52 jongfoster
127 * - Making various functions return int rather than size_t.
128 * (Undoing a recent change). Since size_t is unsigned on
129 * Windows, functions like read_socket that return -1 on
130 * error cannot return a size_t.
132 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
133 * crashes, and also frequently caused JB to jump to 100%
134 * CPU and stay there. (Because it thought it had just
135 * read ((unsigned)-1) == 4Gb of data...)
137 * - The signature of write_socket has changed, it now simply
138 * returns success=0/failure=nonzero.
140 * - Trying to get rid of a few warnings --with-debug on
141 * Windows, I've introduced a new type "jb_socket". This is
142 * used for the socket file descriptors. On Windows, this
143 * is SOCKET (a typedef for unsigned). Everywhere else, it's
144 * an int. The error value can't be -1 any more, so it's
145 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
146 * Windows it maps to the #define INVALID_SOCKET.)
148 * - The signature of bind_port has changed.
150 * Revision 1.48 2002/03/07 03:46:53 oes
151 * Fixed compiler warnings etc
153 * Revision 1.47 2002/02/20 23:15:13 jongfoster
154 * Parsing functions now handle out-of-memory gracefully by returning
157 * Revision 1.46 2002/01/17 21:03:47 jongfoster
158 * Moving all our URL and URL pattern parsing code to urlmatch.c.
160 * Revision 1.45 2002/01/09 14:33:03 oes
161 * Added support for localtime_r.
163 * Revision 1.44 2001/12/14 01:22:54 steudten
164 * Remove 'user:pass@' from 'proto://user:pass@host' for the
165 * new added header 'Host: ..'. (See Req ID 491818)
167 * Revision 1.43 2001/11/23 00:26:38 jongfoster
168 * Fixing two really stupid errors in my previous commit
170 * Revision 1.42 2001/11/22 21:59:30 jongfoster
171 * Adding code to handle +no-cookies-keep
173 * Revision 1.41 2001/11/05 23:43:05 steudten
174 * Add time+date to log files.
176 * Revision 1.40 2001/10/26 20:13:09 jongfoster
177 * ctype.h is needed in Windows, too.
179 * Revision 1.39 2001/10/26 17:40:04 oes
180 * Introduced get_header_value()
181 * Removed http->user_agent, csp->referrer and csp->accept_types
182 * Removed client_accept()
184 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
185 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
186 * threads to call select() simultaneously. So, it's time to do a real, live,
187 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
188 * (native). Both versions will work, but using __OS2__ offers multi-threading.
190 * Revision 1.37 2001/10/23 21:36:02 jongfoster
191 * Documenting sed()'s error behaviou (doc change only)
193 * Revision 1.36 2001/10/13 12:51:51 joergs
194 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
195 * force-load), instead crumble Host: and add it (again) in client_host_adder
196 * (in case we get a HTTP/1.0 request without Host: header and forward it to
197 * a HTTP/1.1 server/proxy).
199 * Revision 1.35 2001/10/09 22:39:21 jongfoster
200 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
203 * Revision 1.34 2001/10/07 18:50:55 oes
204 * Added server_content_encoding, renamed server_transfer_encoding
206 * Revision 1.33 2001/10/07 18:04:49 oes
207 * Changed server_http11 to server_http and its pattern to "HTTP".
208 * Additional functionality: it now saves the HTTP status into
209 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
211 * Revision 1.32 2001/10/07 15:43:28 oes
212 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
213 * client_te and client_accept_encoding_adder, triggered by the new
214 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
215 * changed to allow only identity and chunked, and the TE header is
216 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
218 * parse_http_request no longer does anything than parsing. The rewriting
219 * of http->cmd and version mangling are gone. It now also recognizes
220 * the put and delete methods and saves the url in http->url. Removed
223 * renamed content_type and content_length to have the server_ prefix
225 * server_content_type now only works if csp->content_type != CT_TABOO
227 * added server_transfer_encoding, which
228 * - Sets CT_TABOO to prohibit filtering if encoding compresses
229 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
230 * - Change from "chunked" to "identity" if body was chunked
231 * but has been de-chunked for filtering.
233 * added server_content_md5 which crunches any Content-MD5 headers
234 * if the body was modified.
236 * made server_http11 conditional on +downgrade action
238 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
240 * Revision 1.31 2001/10/05 14:25:02 oes
241 * Crumble Keep-Alive from Server
243 * Revision 1.30 2001/09/29 12:56:03 joergs
244 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
246 * Revision 1.29 2001/09/24 21:09:24 jongfoster
247 * Fixing 2 memory leaks that Guy spotted, where the paramater to
248 * enlist() was not being free()d.
250 * Revision 1.28 2001/09/22 16:32:28 jongfoster
251 * Removing unused #includes.
253 * Revision 1.27 2001/09/20 15:45:25 steudten
255 * add casting from size_t to int for printf()
256 * remove local variable shadow s2
258 * Revision 1.26 2001/09/16 17:05:14 jongfoster
259 * Removing unused #include showarg.h
261 * Revision 1.25 2001/09/16 13:21:27 jongfoster
262 * Changes to use new list functions.
264 * Revision 1.24 2001/09/13 23:05:50 jongfoster
265 * Changing the string paramater to the header parsers a "const".
267 * Revision 1.23 2001/09/12 18:08:19 steudten
269 * In parse_http_request() header rewriting miss the host value, so
270 * from http://www.mydomain.com the result was just " / " not
271 * http://www.mydomain.com/ in case we forward.
273 * Revision 1.22 2001/09/10 10:58:53 oes
274 * Silenced compiler warnings
276 * Revision 1.21 2001/07/31 14:46:00 oes
277 * - Persistant connections now suppressed
278 * - sed() no longer appends empty header to csp->headers
280 * Revision 1.20 2001/07/30 22:08:36 jongfoster
281 * Tidying up #defines:
282 * - All feature #defines are now of the form FEATURE_xxx
283 * - Permanently turned off WIN_GUI_EDIT
284 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
286 * Revision 1.19 2001/07/25 17:21:54 oes
287 * client_uagent now saves copy of User-Agent: header value
289 * Revision 1.18 2001/07/13 14:02:46 oes
290 * - Included fix to repair broken HTTP requests that
291 * don't contain a path, not even '/'.
292 * - Removed all #ifdef PCRS
293 * - content_type now always inspected and classified as
294 * text, gif or other.
295 * - formatting / comments
297 * Revision 1.17 2001/06/29 21:45:41 oes
298 * Indentation, CRLF->LF, Tab-> Space
300 * Revision 1.16 2001/06/29 13:32:42 oes
302 * - Adapted free_http_request
303 * - Removed logentry from cancelled commit
305 * Revision 1.15 2001/06/03 19:12:38 oes
306 * deleted const struct interceptors
308 * Revision 1.14 2001/06/01 18:49:17 jongfoster
309 * Replaced "list_share" with "list" - the tiny memory gain was not
310 * worth the extra complexity.
312 * Revision 1.13 2001/05/31 21:30:33 jongfoster
313 * Removed list code - it's now in list.[ch]
314 * Renamed "permission" to "action", and changed many features
315 * to use the actions file rather than the global config.
317 * Revision 1.12 2001/05/31 17:33:13 oes
321 * Revision 1.11 2001/05/29 20:11:19 joergs
322 * '/ * inside comment' warning removed.
324 * Revision 1.10 2001/05/29 09:50:24 jongfoster
325 * Unified blocklist/imagelist/permissionslist.
326 * File format is still under discussion, but the internal changes
329 * Also modified interceptor behaviour:
330 * - We now intercept all URLs beginning with one of the following
331 * prefixes (and *only* these prefixes):
333 * * http://ijbswa.sf.net/config/
334 * * http://ijbswa.sourceforge.net/config/
335 * - New interceptors "home page" - go to http://i.j.b/ to see it.
336 * - Internal changes so that intercepted and fast redirect pages
337 * are not replaced with an image.
338 * - Interceptors now have the option to send a binary page direct
339 * to the client. (i.e. ijb-send-banner uses this)
340 * - Implemented show-url-info interceptor. (Which is why I needed
341 * the above interceptors changes - a typical URL is
342 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
343 * The previous mechanism would not have intercepted that, and
344 * if it had been intercepted then it then it would have replaced
347 * Revision 1.9 2001/05/28 17:26:33 jongfoster
348 * Fixing segfault if last header was crunched.
349 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
350 * can use the cross-platform sprintf() instead.)
352 * Revision 1.8 2001/05/27 22:17:04 oes
354 * - re_process_buffer no longer writes the modified buffer
355 * to the client, which was very ugly. It now returns the
356 * buffer, which it is then written by chat.
358 * - content_length now adjusts the Content-Length: header
359 * for modified documents rather than crunch()ing it.
360 * (Length info in csp->content_length, which is 0 for
361 * unmodified documents)
363 * - For this to work, sed() is called twice when filtering.
365 * Revision 1.7 2001/05/27 13:19:06 oes
366 * Patched Joergs solution for the content-length in.
368 * Revision 1.6 2001/05/26 13:39:32 jongfoster
369 * Only crunches Content-Length header if applying RE filtering.
370 * Without this fix, Microsoft Windows Update wouldn't work.
372 * Revision 1.5 2001/05/26 00:28:36 jongfoster
373 * Automatic reloading of config file.
374 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
375 * Most of the global variables have been moved to a new
376 * struct configuration_spec, accessed through csp->config->globalname
377 * Most of the globals remaining are used by the Win32 GUI.
379 * Revision 1.4 2001/05/22 18:46:04 oes
381 * - Enabled filtering banners by size rather than URL
382 * by adding patterns that replace all standard banner
383 * sizes with the "Junkbuster" gif to the re_filterfile
385 * - Enabled filtering WebBugs by providing a pattern
386 * which kills all 1x1 images
388 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
389 * which is selected by the (nonstandard and therefore
390 * capital) letter 'U' in the option string.
391 * It causes the quantifiers to be ungreedy by default.
392 * Appending a ? turns back to greedy (!).
394 * - Added a new interceptor ijb-send-banner, which
395 * sends back the "Junkbuster" gif. Without imagelist or
396 * MSIE detection support, or if tinygif = 1, or the
397 * URL isn't recognized as an imageurl, a lame HTML
398 * explanation is sent instead.
400 * - Added new feature, which permits blocking remote
401 * script redirects and firing back a local redirect
403 * The feature is conditionally compiled, i.e. it
404 * can be disabled with --disable-fast-redirects,
405 * plus it must be activated by a "fast-redirects"
406 * line in the config file, has its own log level
407 * and of course wants to be displayed by show-proxy-args
408 * Note: Boy, all the #ifdefs in 1001 locations and
409 * all the fumbling with configure.in and acconfig.h
410 * were *way* more work than the feature itself :-(
412 * - Because a generic redirect template was needed for
413 * this, tinygif = 3 now uses the same.
415 * - Moved GIFs, and other static HTTP response templates
420 * - Removed some >400 CRs again (Jon, you really worked
423 * Revision 1.3 2001/05/20 01:21:20 jongfoster
424 * Version 2.9.4 checkin.
425 * - Merged popupfile and cookiefile, and added control over PCRS
426 * filtering, in new "permissionsfile".
427 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
428 * file error you now get a message box (in the Win32 GUI) rather
429 * than the program exiting with no explanation.
430 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
432 * - Removed tabs from "config"
433 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
434 * - Bumped up version number.
436 * Revision 1.2 2001/05/17 23:02:36 oes
437 * - Made referrer option accept 'L' as a substitute for '§'
439 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
440 * Initial import of version 2.9.3 source tree
443 *********************************************************************/
450 #include <sys/types.h>
459 #if !defined(_WIN32) && !defined(__OS2__)
468 /* jcc.h is for mutex semapores only */
469 #endif /* def OSX_DARWIN */
475 #include "jbsockets.h"
476 #include "miscutil.h"
479 #ifndef HAVE_STRPTIME
480 #include "strptime.c"
483 const char parsers_h_rcs[] = PARSERS_H_VERSION;
485 /* Fix a problem with Solaris. There should be no effect on other
487 * Solaris's isspace() is a macro which uses it's argument directly
488 * as an array index. Therefore we need to make sure that high-bit
489 * characters generate +ve values, and ideally we also want to make
490 * the argument match the declared parameter type of "int".
492 * Why did they write a character function that can't take a simple
493 * "char" argument? Doh!
495 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
496 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
499 const struct parsers client_patterns[] = {
500 { "referer:", 8, client_referrer },
501 { "user-agent:", 11, client_uagent },
502 { "ua-", 3, client_ua },
503 { "from:", 5, client_from },
504 { "cookie:", 7, client_send_cookie },
505 { "x-forwarded-for:", 16, client_x_forwarded },
506 { "Accept-Encoding:", 16, client_accept_encoding },
507 { "TE:", 3, client_te },
508 { "Host:", 5, client_host },
509 { "if-modified-since:", 18, client_if_modified_since },
510 { "Keep-Alive:", 11, crumble },
511 { "connection:", 11, crumble },
512 { "proxy-connection:", 17, crumble },
513 { "max-forwards:", 13, client_max_forwards },
514 { "Accept-Language:", 16, client_accept_language },
515 { "if-none-match:", 14, client_if_none_match },
516 { "X-Filter:", 9, client_x_filter },
517 { "*", 0, crunch_client_header },
518 { "*", 0, filter_client_header },
522 const struct parsers server_patterns[] = {
523 { "HTTP", 4, server_http },
524 { "set-cookie:", 11, server_set_cookie },
525 { "connection:", 11, crumble },
526 { "Content-Type:", 13, server_content_type },
527 { "Content-Length:", 15, server_content_length },
528 { "Content-MD5:", 12, server_content_md5 },
529 { "Content-Encoding:", 17, server_content_encoding },
530 { "Transfer-Encoding:", 18, server_transfer_coding },
531 { "Keep-Alive:", 11, crumble },
532 { "content-disposition:", 20, server_content_disposition },
533 { "Last-Modified:", 14, server_last_modified },
534 { "*", 0, crunch_server_header },
535 { "*", 0, filter_server_header },
539 const struct parsers server_patterns_light[] = {
540 { "Content-Length:", 15, server_content_length },
541 { "Transfer-Encoding:", 18, server_transfer_coding },
545 const add_header_func_ptr add_client_headers[] = {
548 client_x_forwarded_adder,
550 /* Temporarily disabled: client_accept_encoding_adder, */
551 connection_close_adder,
556 const add_header_func_ptr add_server_headers[] = {
557 connection_close_adder,
561 /*********************************************************************
563 * Function : flush_socket
565 * Description : Write any pending "buffered" content.
568 * 1 : fd = file descriptor of the socket to read
569 * 2 : csp = Current client state (buffers, headers, etc...)
571 * Returns : On success, the number of bytes written are returned (zero
572 * indicates nothing was written). On error, -1 is returned,
573 * and errno is set appropriately. If count is zero and the
574 * file descriptor refers to a regular file, 0 will be
575 * returned without causing any other effect. For a special
576 * file, the results are not portable.
578 *********************************************************************/
579 int flush_socket(jb_socket fd, struct client_state *csp)
581 struct iob *iob = csp->iob;
582 int len = iob->eod - iob->cur;
589 if (write_socket(fd, iob->cur, (size_t)len))
593 iob->eod = iob->cur = iob->buf;
599 /*********************************************************************
601 * Function : add_to_iob
603 * Description : Add content to the buffered page, expanding the
604 * buffer if necessary.
607 * 1 : csp = Current client state (buffers, headers, etc...)
608 * 2 : buf = holds the content to be added to the page
609 * 3 : n = number of bytes to be added
611 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
612 * or buffer limit reached.
614 *********************************************************************/
615 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
617 struct iob *iob = csp->iob;
618 size_t used, offset, need, want;
621 if (n <= 0) return JB_ERR_OK;
623 used = iob->eod - iob->buf;
624 offset = iob->cur - iob->buf;
628 * If the buffer can't hold the new data, extend it first.
629 * Use the next power of two if possible, else use the actual need.
631 if (need > csp->config->buffer_limit)
633 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
634 return JB_ERR_MEMORY;
637 if (need > iob->size)
639 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
641 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
645 else if (NULL != (p = (char *)realloc(iob->buf, need)))
651 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
652 return JB_ERR_MEMORY;
655 /* Update the iob pointers */
656 iob->cur = p + offset;
661 /* copy the new data into the iob buffer */
662 memcpy(iob->eod, buf, (size_t)n);
664 /* point to the end of the data */
667 /* null terminate == cheap insurance */
675 /*********************************************************************
677 * Function : get_header
679 * Description : This (odd) routine will parse the csp->iob
682 * 1 : csp = Current client state (buffers, headers, etc...)
684 * Returns : Any one of the following:
686 * 1) a pointer to a dynamically allocated string that contains a header line
687 * 2) NULL indicating that the end of the header was reached
688 * 3) "" indicating that the end of the iob was reached before finding
689 * a complete header line.
691 *********************************************************************/
692 char *get_header(struct client_state *csp)
698 if ((iob->cur == NULL)
699 || ((p = strchr(iob->cur, '\n')) == NULL))
701 return(""); /* couldn't find a complete header */
706 ret = strdup(iob->cur);
709 /* FIXME No way to handle error properly */
710 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
715 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
717 /* is this a blank line (i.e. the end of the header) ? */
729 /*********************************************************************
731 * Function : get_header_value
733 * Description : Get the value of a given header from a chained list
734 * of header lines or return NULL if no such header is
735 * present in the list.
738 * 1 : header_list = pointer to list
739 * 2 : header_name = string with name of header to look for.
740 * Trailing colon required, capitalization
743 * Returns : NULL if not found, else value of header
745 *********************************************************************/
746 char *get_header_value(const struct list *header_list, const char *header_name)
748 struct list_entry *cur_entry;
754 length = strlen(header_name);
756 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
760 if (!strncmpic(cur_entry->str, header_name, length))
763 * Found: return pointer to start of value
765 ret = (char *) (cur_entry->str + length);
766 while (*ret && ijb_isspace(*ret)) ret++;
779 /*********************************************************************
783 * Description : add, delete or modify lines in the HTTP header streams.
784 * On entry, it receives a linked list of headers space
785 * that was allocated dynamically (both the list nodes
786 * and the header contents).
788 * As a side effect it frees the space used by the original
792 * 1 : pats = list of patterns to match against headers
793 * 2 : more_headers = list of functions to add more
794 * headers (client or server)
795 * 3 : csp = Current client state (buffers, headers, etc...)
797 * Returns : Single pointer to a fully formed header, or NULL
798 * on out-of-memory error.
800 *********************************************************************/
801 char *sed(const struct parsers pats[],
802 const add_header_func_ptr more_headers[],
803 struct client_state *csp)
805 struct list_entry *p;
806 const struct parsers *v;
807 const add_header_func_ptr *f;
808 jb_err err = JB_ERR_OK;
812 * If filtering is enabled, sed is run twice,
813 * but most of the work needs to be done only once.
815 first_run = (more_headers != NULL ) ? 1 : 0;
817 if (first_run) /* Parse and print */
819 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
821 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
823 /* Header crunch()ed in previous run? -> ignore */
824 if (p->str == NULL) continue;
826 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
828 /* Does the current parser handle this header? */
829 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
831 err = v->parser(csp, (char **)&(p->str));
835 /* place any additional headers on the csp->headers list */
836 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
841 else /* Parse only */
844 * The second run is only needed if the body was modified
845 * and the content-lenght has changed.
847 if (strncmpic(csp->http->cmd, "HEAD", 4))
849 /*XXX: Code duplication*/
850 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
852 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
854 /* Header crunch()ed in previous run? -> ignore */
855 if (p->str == NULL) continue;
857 /* Does the current parser handle this header? */
858 if (strncmpic(p->str, v->str, v->len) == 0)
860 err = v->parser(csp, (char **)&(p->str));
867 if (err != JB_ERR_OK)
872 return list_to_text(csp->headers);
876 /* here begins the family of parser functions that reformat header lines */
878 /*********************************************************************
880 * Function : filter_server_header
882 * Description : Checks if server header filtering is enabled.
883 * If it is, filter_header is called to do the work.
886 * 1 : csp = Current client state (buffers, headers, etc...)
887 * 2 : header = On input, pointer to header to modify.
888 * On output, pointer to the modified header, or NULL
889 * to remove the header. This function frees the
890 * original string if necessary.
892 * Returns : JB_ERR_OK on success and always succeeds
894 *********************************************************************/
895 jb_err filter_server_header(struct client_state *csp, char **header)
897 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
899 filter_header(csp, header);
904 /*********************************************************************
906 * Function : filter_client_header
908 * Description : Checks if client header filtering is enabled.
909 * If it is, filter_header is called to do the work.
912 * 1 : csp = Current client state (buffers, headers, etc...)
913 * 2 : header = On input, pointer to header to modify.
914 * On output, pointer to the modified header, or NULL
915 * to remove the header. This function frees the
916 * original string if necessary.
918 * Returns : JB_ERR_OK on success and always succeeds
920 *********************************************************************/
921 jb_err filter_client_header(struct client_state *csp, char **header)
923 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
925 filter_header(csp, header);
930 /*********************************************************************
932 * Function : filter_header
934 * Description : Executes all text substitutions from all applying
935 * +filter actions on the header.
936 * Most of the code was copied from pcrs_filter_response,
937 * including the rather short variable names
940 * 1 : csp = Current client state (buffers, headers, etc...)
941 * 2 : header = On input, pointer to header to modify.
942 * On output, pointer to the modified header, or NULL
943 * to remove the header. This function frees the
944 * original string if necessary.
946 * Returns : JB_ERR_OK on success and always succeeds
948 *********************************************************************/
949 jb_err filter_header(struct client_state *csp, char **header)
953 size_t size = strlen(*header);
955 char *newheader = NULL;
958 struct file_list *fl;
959 struct re_filterfile_spec *b;
960 struct list_entry *filtername;
962 int i, found_filters = 0;
965 # define MAX_AF_FILES 1
966 # define INDEX_OR_NOT
968 # define INDEX_OR_NOT [i]
971 log_error(LOG_LEVEL_RE_FILTER, "Entered filter_headers");
973 * Need to check the set of re_filterfiles...
975 for (i = 0; i < MAX_AF_FILES; i++)
977 fl = csp->rlist INDEX_OR_NOT;
988 if (0 == found_filters)
990 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
994 for (i = 0; i < MAX_AF_FILES; i++)
996 fl = csp->rlist INDEX_OR_NOT;
997 if ((NULL == fl) || (NULL == fl->f))
1000 * For all applying +filter actions, look if a filter by that
1001 * name exists and if yes, execute it's pcrs_joblist on the
1004 for (b = fl->f; b; b = b->next)
1006 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1007 filtername ; filtername = filtername->next)
1009 if (strcmp(b->name, filtername->str) == 0)
1011 int current_hits = 0;
1013 if ( NULL == b->joblist )
1015 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1019 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1020 *header, size, b->name);
1022 /* Apply all jobs from the joblist */
1023 for (job = b->joblist; NULL != job; job = job->next)
1025 matches = pcrs_execute(job, *header, size, &newheader, &size);
1028 current_hits += matches;
1029 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1031 *header = newheader;
1033 else if ( 0 == matches )
1035 /* Filter doesn't change header */
1041 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1042 *header, b->name, pcrs_strerror(matches));
1043 if( newheader != NULL)
1045 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1050 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1051 hits += current_hits;
1059 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1062 log_error(LOG_LEVEL_RE_FILTER, "Leaving filter headers");
1068 /*********************************************************************
1070 * Function : crumble
1072 * Description : This is called if a header matches a pattern to "crunch"
1075 * 1 : csp = Current client state (buffers, headers, etc...)
1076 * 2 : header = On input, pointer to header to modify.
1077 * On output, pointer to the modified header, or NULL
1078 * to remove the header. This function frees the
1079 * original string if necessary.
1081 * Returns : JB_ERR_OK on success, or
1082 * JB_ERR_MEMORY on out-of-memory error.
1084 *********************************************************************/
1085 jb_err crumble(struct client_state *csp, char **header)
1087 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1092 /*********************************************************************
1094 * Function : crunch_server_header
1096 * Description : Crunch server header if it matches a string supplied by the
1097 * user. Called from `sed'.
1100 * 1 : csp = Current client state (buffers, headers, etc...)
1101 * 2 : header = On input, pointer to header to modify.
1102 * On output, pointer to the modified header, or NULL
1103 * to remove the header. This function frees the
1104 * original string if necessary.
1106 * Returns : JB_ERR_OK on success and always succeeds
1108 *********************************************************************/
1109 jb_err crunch_server_header(struct client_state *csp, char **header)
1111 const char *crunch_pattern;
1112 /*Is there a header to crunch*/
1114 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1116 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1118 /*Is the current header the lucky one?*/
1119 if (strstr(*header, crunch_pattern))
1121 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1128 /*********************************************************************
1130 * Function : server_content_type
1132 * Description : Set the content-type for filterable types (text/.*,
1133 * javascript and image/gif) unless filtering has been
1134 * forbidden (CT_TABOO) while parsing earlier headers.
1135 * NOTE: Since text/plain is commonly used by web servers
1136 * for files whose correct type is unknown, we don't
1137 * set CT_TEXT for it.
1140 * 1 : csp = Current client state (buffers, headers, etc...)
1141 * 2 : header = On input, pointer to header to modify.
1142 * On output, pointer to the modified header, or NULL
1143 * to remove the header. This function frees the
1144 * original string if necessary.
1146 * Returns : JB_ERR_OK on success, or
1147 * JB_ERR_MEMORY on out-of-memory error.
1149 *********************************************************************/
1150 jb_err server_content_type(struct client_state *csp, char **header)
1154 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1156 if (csp->content_type != CT_TABOO)
1158 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1159 || strstr(*header, "xml")
1160 || strstr(*header, "application/x-javascript"))
1161 csp->content_type = CT_TEXT;
1162 else if (strstr(*header, " image/gif"))
1163 csp->content_type = CT_GIF;
1164 else if (strstr(*header, " image/jpeg"))
1165 csp->content_type = CT_JPEG;
1167 csp->content_type = 0;
1170 * Are we enabling text mode by force?
1172 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1175 * Do we really have to?
1177 if (csp->content_type == CT_TEXT)
1179 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1183 csp->content_type = CT_TEXT;
1184 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1188 * Are we messing with the content type?
1190 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1193 * Make sure the user doesn't accidently
1194 * change the content type of binary documents.
1196 if (csp->content_type == CT_TEXT)
1199 *header = strdup("Content-Type: ");
1200 string_append(header, newval);
1204 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1205 return JB_ERR_MEMORY;
1207 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1211 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1212 "Enable force-text-mode if you know what you're doing.", *header);
1219 /*********************************************************************
1221 * Function : server_transfer_coding
1223 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1224 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1225 * - Change from "chunked" to "identity" if body was chunked
1226 * but has been de-chunked for filtering.
1229 * 1 : csp = Current client state (buffers, headers, etc...)
1230 * 2 : header = On input, pointer to header to modify.
1231 * On output, pointer to the modified header, or NULL
1232 * to remove the header. This function frees the
1233 * original string if necessary.
1235 * Returns : JB_ERR_OK on success, or
1236 * JB_ERR_MEMORY on out-of-memory error.
1238 *********************************************************************/
1239 jb_err server_transfer_coding(struct client_state *csp, char **header)
1242 * Turn off pcrs and gif filtering if body compressed
1244 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1246 csp->content_type = CT_TABOO;
1250 * Raise flag if body chunked
1252 if (strstr(*header, "chunked"))
1254 csp->flags |= CSP_FLAG_CHUNKED;
1257 * If the body was modified, it has been
1258 * de-chunked first, so adjust the header:
1260 if (csp->flags & CSP_FLAG_MODIFIED)
1263 *header = strdup("Transfer-Encoding: identity");
1264 log_error(LOG_LEVEL_HEADER, "Set: %s", *header);
1265 return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1273 /*********************************************************************
1275 * Function : server_content_encoding
1277 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1280 * 1 : csp = Current client state (buffers, headers, etc...)
1281 * 2 : header = On input, pointer to header to modify.
1282 * On output, pointer to the modified header, or NULL
1283 * to remove the header. This function frees the
1284 * original string if necessary.
1286 * Returns : JB_ERR_OK on success, or
1287 * JB_ERR_MEMORY on out-of-memory error.
1289 *********************************************************************/
1290 jb_err server_content_encoding(struct client_state *csp, char **header)
1293 * Turn off pcrs and gif filtering if body compressed
1295 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1297 csp->content_type = CT_TABOO;
1305 /*********************************************************************
1307 * Function : server_content_length
1309 * Description : Adjust Content-Length header if we modified
1313 * 1 : csp = Current client state (buffers, headers, etc...)
1314 * 2 : header = On input, pointer to header to modify.
1315 * On output, pointer to the modified header, or NULL
1316 * to remove the header. This function frees the
1317 * original string if necessary.
1319 * Returns : JB_ERR_OK on success, or
1320 * JB_ERR_MEMORY on out-of-memory error.
1322 *********************************************************************/
1323 jb_err server_content_length(struct client_state *csp, char **header)
1325 if (csp->content_length != 0) /* Content length could have been modified */
1328 * XXX: Shouldn't we check if csp->content_length
1329 * is different than the original value?
1332 *header = (char *) zalloc(100);
1333 if (*header == NULL)
1335 return JB_ERR_MEMORY;
1338 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1340 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1347 /*********************************************************************
1349 * Function : server_content_md5
1351 * Description : Crumble any Content-MD5 headers if the document was
1352 * modified. FIXME: Should we re-compute instead?
1355 * 1 : csp = Current client state (buffers, headers, etc...)
1356 * 2 : header = On input, pointer to header to modify.
1357 * On output, pointer to the modified header, or NULL
1358 * to remove the header. This function frees the
1359 * original string if necessary.
1361 * Returns : JB_ERR_OK on success, or
1362 * JB_ERR_MEMORY on out-of-memory error.
1364 *********************************************************************/
1365 jb_err server_content_md5(struct client_state *csp, char **header)
1367 if (csp->flags & CSP_FLAG_MODIFIED)
1369 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1376 /*********************************************************************
1378 * Function : server_content_disposition
1380 * Description : If enabled, blocks or modifies the "content-disposition" header.
1381 * Called from `sed'.
1384 * 1 : csp = Current client state (buffers, headers, etc...)
1385 * 2 : header = On input, pointer to header to modify.
1386 * On output, pointer to the modified header, or NULL
1387 * to remove the header. This function frees the
1388 * original string if necessary.
1390 * Returns : JB_ERR_OK on success, or
1391 * JB_ERR_MEMORY on out-of-memory error.
1393 *********************************************************************/
1394 jb_err server_content_disposition(struct client_state *csp, char **header)
1399 * Are we messing with the content-disposition header?
1401 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1407 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1409 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1412 * Blocking content-disposition header
1414 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1421 * Replacing content-disposition header
1424 *header = strdup("content-disposition: ");
1425 string_append(header, newval);
1427 if (*header == NULL)
1429 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1433 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1436 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1439 /*********************************************************************
1441 * Function : server_last_modified
1443 * Description : Changes Last-Modified header to the actual date
1444 * to help hide-if-modified-since.
1445 * Called from `sed'.
1448 * 1 : csp = Current client state (buffers, headers, etc...)
1449 * 2 : header = On input, pointer to header to modify.
1450 * On output, pointer to the modified header, or NULL
1451 * to remove the header. This function frees the
1452 * original string if necessary.
1454 * Returns : JB_ERR_OK on success, or
1455 * JB_ERR_MEMORY on out-of-memory error.
1457 *********************************************************************/
1458 jb_err server_last_modified(struct client_state *csp, char **header)
1461 char buf[BUFFER_SIZE];
1464 struct tm *timeptr = NULL;
1465 time_t now, last_modified;
1467 long int days, hours, minutes, seconds;
1470 * Are we messing with the Last-Modified header?
1472 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1478 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1480 if (0 == strcmpic(newval, "block") )
1483 * Blocking Last-Modified header. Useless but why not.
1485 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1489 else if (0 == strcmpic(newval, "reset-to-request-time"))
1492 * Setting Last-Modified Header to now.
1494 get_http_time(0, buf);
1496 *header = strdup("Last-Modified: ");
1497 string_append(header, buf);
1499 if (*header == NULL)
1501 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1505 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1508 else if (0 == strcmpic(newval, "randomize"))
1510 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1512 timeptr = gmtime(&now);
1513 if ( (last_modified = parse_header_time(*header, timeptr)) < 0 )
1515 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1520 rtime = difftime(now, last_modified);
1523 #if !defined(_WIN32) && !defined(__OS2__)
1524 rtime = random() % rtime + 1;
1526 rtime = rand() % rtime + 1;
1527 #endif /* (ifndef _WIN32 || __OS2__) */
1528 last_modified += rtime;
1529 timeptr = localtime(&last_modified);
1530 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1532 *header = strdup("Last-Modified: ");
1533 string_append(header, newheader);
1535 if (*header == NULL)
1537 log_error(LOG_LEVEL_ERROR, " Insufficent memory, header crunched without replacement.");
1538 return JB_ERR_MEMORY;
1541 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1543 days = rtime / (3600 * 24);
1544 hours = rtime / 3600 % 24;
1545 minutes = rtime / 60 % 60;
1546 seconds = rtime % 60;
1548 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1549 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1550 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1555 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1563 /*********************************************************************
1565 * Function : client_accept_encoding
1567 * Description : Rewrite the client's Accept-Encoding header so that
1568 * if doesn't allow compression, if the action applies.
1569 * Note: For HTTP/1.0 the absence of the header is enough.
1572 * 1 : csp = Current client state (buffers, headers, etc...)
1573 * 2 : header = On input, pointer to header to modify.
1574 * On output, pointer to the modified header, or NULL
1575 * to remove the header. This function frees the
1576 * original string if necessary.
1578 * Returns : JB_ERR_OK on success, or
1579 * JB_ERR_MEMORY on out-of-memory error.
1581 *********************************************************************/
1582 jb_err client_accept_encoding(struct client_state *csp, char **header)
1584 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1586 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1590 /* Temporarily disable the correct behaviour to
1591 * work around a PHP bug.
1593 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1595 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1596 * if (*header == NULL)
1598 * return JB_ERR_MEMORY;
1609 /*********************************************************************
1611 * Function : client_te
1613 * Description : Rewrite the client's TE header so that
1614 * if doesn't allow compression, if the action applies.
1617 * 1 : csp = Current client state (buffers, headers, etc...)
1618 * 2 : header = On input, pointer to header to modify.
1619 * On output, pointer to the modified header, or NULL
1620 * to remove the header. This function frees the
1621 * original string if necessary.
1623 * Returns : JB_ERR_OK on success, or
1624 * JB_ERR_MEMORY on out-of-memory error.
1626 *********************************************************************/
1627 jb_err client_te(struct client_state *csp, char **header)
1629 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1632 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1638 /*********************************************************************
1640 * Function : client_referrer
1642 * Description : Handle the "referer" config setting properly.
1643 * Called from `sed'.
1646 * 1 : csp = Current client state (buffers, headers, etc...)
1647 * 2 : header = On input, pointer to header to modify.
1648 * On output, pointer to the modified header, or NULL
1649 * to remove the header. This function frees the
1650 * original string if necessary.
1652 * Returns : JB_ERR_OK on success, or
1653 * JB_ERR_MEMORY on out-of-memory error.
1655 *********************************************************************/
1656 jb_err client_referrer(struct client_state *csp, char **header)
1663 #ifdef FEATURE_FORCE_LOAD
1664 /* Since the referrer can include the prefix even
1665 * if the request itself is non-forced, we must
1666 * clean it unconditionally
1668 strclean(*header, FORCE_PREFIX);
1669 #endif /* def FEATURE_FORCE_LOAD */
1672 * Are we sending referer?
1674 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1679 newval = csp->action->string[ACTION_STRING_REFERER];
1681 if ((0 != strcmpic(newval, "conditional-block")))
1685 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1690 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1693 else if (0 == strcmpic(newval, "conditional-block"))
1696 * Block referer if host has changed.
1699 if (NULL == (host = strdup(csp->http->hostport)))
1702 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1703 return JB_ERR_MEMORY;
1705 if (NULL == (referer = strdup(*header)))
1709 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1710 return JB_ERR_MEMORY;
1712 hostlenght = strlen(host);
1713 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1715 /*Shorten referer to make sure the referer is blocked
1716 *if www.example.org/www.example.com-shall-see-the-referer/
1717 *links to www.example.com/
1719 referer[hostlenght+17] = '\n';
1721 if ( 0 == strstr(referer, host)) /*Host has changed*/
1723 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1728 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1734 else if (0 != strcmpic(newval, "forge"))
1737 * We have a specific (fixed) referer we want to send.
1739 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1741 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1743 *header = strdup("Referer: ");
1744 string_append(header, newval);
1745 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1747 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1752 * Forge a referer as http://[hostname:port of REQUEST]/
1753 * to fool stupid checks for in-site links
1756 *header = strdup("Referer: http://");
1757 string_append(header, csp->http->hostport);
1758 string_append(header, "/");
1759 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1761 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1765 /*********************************************************************
1767 * Function : client_accept_language
1769 * Description : Handle the "Accept-Language" config setting properly.
1770 * Called from `sed'.
1773 * 1 : csp = Current client state (buffers, headers, etc...)
1774 * 2 : header = On input, pointer to header to modify.
1775 * On output, pointer to the modified header, or NULL
1776 * to remove the header. This function frees the
1777 * original string if necessary.
1779 * Returns : JB_ERR_OK on success, or
1780 * JB_ERR_MEMORY on out-of-memory error.
1782 *********************************************************************/
1783 jb_err client_accept_language(struct client_state *csp, char **header)
1788 * Are we messing with the Accept-Language?
1790 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1792 /*I don't think so*/
1796 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1798 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1801 * Blocking Accept-Language header
1803 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1810 * Replacing Accept-Language header
1813 *header = strdup("Accept-Language: ");
1814 string_append(header, newval);
1816 if (*header == NULL)
1818 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1822 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1825 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1828 /*********************************************************************
1830 * Function : crunch_client_header
1832 * Description : Crunch client header if it matches a string supplied by the
1833 * user. Called from `sed'.
1836 * 1 : csp = Current client state (buffers, headers, etc...)
1837 * 2 : header = On input, pointer to header to modify.
1838 * On output, pointer to the modified header, or NULL
1839 * to remove the header. This function frees the
1840 * original string if necessary.
1842 * Returns : JB_ERR_OK on success and always succeeds
1844 *********************************************************************/
1845 jb_err crunch_client_header(struct client_state *csp, char **header)
1847 const char *crunch_pattern;
1848 /*Is there a header to crunch*/
1850 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1852 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1854 /*Is the current header the lucky one?*/
1855 if (strstr(*header, crunch_pattern))
1857 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1865 /*********************************************************************
1867 * Function : client_uagent
1869 * Description : Handle the "user-agent" config setting properly
1870 * and remember its original value to enable browser
1871 * bug workarounds. Called from `sed'.
1874 * 1 : csp = Current client state (buffers, headers, etc...)
1875 * 2 : header = On input, pointer to header to modify.
1876 * On output, pointer to the modified header, or NULL
1877 * to remove the header. This function frees the
1878 * original string if necessary.
1880 * Returns : JB_ERR_OK on success, or
1881 * JB_ERR_MEMORY on out-of-memory error.
1883 *********************************************************************/
1884 jb_err client_uagent(struct client_state *csp, char **header)
1888 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1893 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1900 *header = strdup("User-Agent: ");
1901 string_append(header, newval);
1903 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
1905 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1908 /*********************************************************************
1910 * Function : client_ua
1912 * Description : Handle "ua-" headers properly. 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_ua(struct client_state *csp, char **header)
1927 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1929 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
1937 /*********************************************************************
1939 * Function : client_from
1941 * Description : Handle the "from" config setting properly.
1942 * Called from `sed'.
1945 * 1 : csp = Current client state (buffers, headers, etc...)
1946 * 2 : header = On input, pointer to header to modify.
1947 * On output, pointer to the modified header, or NULL
1948 * to remove the header. This function frees the
1949 * original string if necessary.
1951 * Returns : JB_ERR_OK on success, or
1952 * JB_ERR_MEMORY on out-of-memory error.
1954 *********************************************************************/
1955 jb_err client_from(struct client_state *csp, char **header)
1959 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1966 newval = csp->action->string[ACTION_STRING_FROM];
1969 * Are we blocking the e-mail address?
1971 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1973 log_error(LOG_LEVEL_HEADER, "crunched From!");
1977 log_error(LOG_LEVEL_HEADER, " modified");
1979 *header = strdup("From: ");
1980 string_append(header, newval);
1982 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1986 /*********************************************************************
1988 * Function : client_send_cookie
1990 * Description : Handle the "cookie" header properly. Called from `sed'.
1991 * If cookie is accepted, add it to the cookie_list,
1992 * else we crunch it. Mmmmmmmmmmm ... cookie ......
1995 * 1 : csp = Current client state (buffers, headers, etc...)
1996 * 2 : header = On input, pointer to header to modify.
1997 * On output, pointer to the modified header, or NULL
1998 * to remove the header. This function frees the
1999 * original string if necessary.
2001 * Returns : JB_ERR_OK on success, or
2002 * JB_ERR_MEMORY on out-of-memory error.
2004 *********************************************************************/
2005 jb_err client_send_cookie(struct client_state *csp, char **header)
2007 jb_err result = JB_ERR_OK;
2009 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2011 /* strlen("cookie: ") == 8 */
2012 result = enlist(csp->cookie_list, *header + 8);
2016 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2020 * Always remove the cookie here. The cookie header
2021 * will be sent at the end of the header.
2029 /*********************************************************************
2031 * Function : client_x_forwarded
2033 * Description : Handle the "x-forwarded-for" config setting properly,
2034 * also used in the add_client_headers list. Called from `sed'.
2037 * 1 : csp = Current client state (buffers, headers, etc...)
2038 * 2 : header = On input, pointer to header to modify.
2039 * On output, pointer to the modified header, or NULL
2040 * to remove the header. This function frees the
2041 * original string if necessary.
2043 * Returns : JB_ERR_OK on success, or
2044 * JB_ERR_MEMORY on out-of-memory error.
2046 *********************************************************************/
2047 jb_err client_x_forwarded(struct client_state *csp, char **header)
2049 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2051 /* Save it so we can re-add it later */
2052 freez(csp->x_forwarded);
2053 csp->x_forwarded = *header;
2056 * Always set *header = NULL, since this information
2057 * will be sent at the end of the header.
2064 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2071 /*********************************************************************
2073 * Function : client_max_forwards
2075 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2076 * from the value of the Max-Forwards header field.
2079 * 1 : csp = Current client state (buffers, headers, etc...)
2080 * 2 : header = On input, pointer to header to modify.
2081 * On output, pointer to the modified header, or NULL
2082 * to remove the header. This function frees the
2083 * original string if necessary.
2085 * Returns : JB_ERR_OK on success, or
2086 * JB_ERR_MEMORY on out-of-memory error.
2088 *********************************************************************/
2089 jb_err client_max_forwards(struct client_state *csp, char **header)
2091 unsigned int max_forwards;
2093 if ((0 == strcmpic(csp->http->gpc, "trace"))
2094 || (0 == strcmpic(csp->http->gpc, "options")))
2096 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2098 if (max_forwards-- >= 1)
2100 sprintf(*header, "Max-Forwards: %u", max_forwards);
2101 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2105 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2114 /*********************************************************************
2116 * Function : client_host
2118 * Description : If the request URI did not contain host and
2119 * port information, parse and evaluate the Host
2122 * Also, kill ill-formed HOST: headers as sent by
2123 * Apple's iTunes software when used with a proxy.
2126 * 1 : csp = Current client state (buffers, headers, etc...)
2127 * 2 : header = On input, pointer to header to modify.
2128 * On output, pointer to the modified header, or NULL
2129 * to remove the header. This function frees the
2130 * original string if necessary.
2132 * Returns : JB_ERR_OK on success, or
2133 * JB_ERR_MEMORY on out-of-memory error.
2135 *********************************************************************/
2136 jb_err client_host(struct client_state *csp, char **header)
2141 * If the header field name is all upper-case, chances are that it's
2142 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2143 * not a problem -- they are regenerated later.
2145 if ((*header)[1] == 'O')
2147 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2152 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2153 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2156 if (NULL == (p = strdup((*header)+6)))
2158 return JB_ERR_MEMORY;
2161 if (NULL == (q = strdup(p)))
2164 return JB_ERR_MEMORY;
2167 freez(csp->http->hostport);
2168 csp->http->hostport = p;
2169 freez(csp->http->host);
2170 csp->http->host = q;
2171 q = strchr(csp->http->host, ':');
2174 /* Terminate hostname and evaluate port string */
2176 csp->http->port = atoi(q);
2180 csp->http->port = csp->http->ssl ? 443 : 80;
2183 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2184 csp->http->hostport, csp->http->host, csp->http->port);
2190 /*********************************************************************
2192 * Function : client_if_modified_since
2194 * Description : Remove or modify the If-Modified-Since header.
2197 * 1 : csp = Current client state (buffers, headers, etc...)
2198 * 2 : header = On input, pointer to header to modify.
2199 * On output, pointer to the modified header, or NULL
2200 * to remove the header. This function frees the
2201 * original string if necessary.
2203 * Returns : JB_ERR_OK on success, or
2204 * JB_ERR_MEMORY on out-of-memory error.
2206 *********************************************************************/
2207 jb_err client_if_modified_since(struct client_state *csp, char **header)
2210 struct tm *timeptr = NULL;
2214 time_t hours, minutes, seconds;
2218 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2221 * The client got an error message because of a temporary problem,
2222 * the problem is gone and the client now tries to revalidate our
2223 * error message on the real server. The revalidation would always
2224 * end with the transmission of the whole document and there is
2225 * no need to expose the bogus If-Modified-Since header.
2227 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2230 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2232 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2234 if ((0 == strcmpic(newval, "block")))
2236 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2239 else /* add random value */
2241 if ( (tm = parse_header_time(*header, timeptr)) < 0 )
2243 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2248 rtime = (time_t) strtol(newval, &endptr, 0);
2251 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d hou%s)",
2252 *header, rtime, (rtime == 1 || rtime == -1) ? "r": "rs");
2254 #if !defined(_WIN32) && !defined(__OS2__)
2255 rtime = random() % rtime + 1;
2257 rtime = rand() % rtime + 1;
2258 #endif /* (_WIN32 || __OS2__) */
2259 if(newval[0] == '-')
2266 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2270 timeptr = localtime(&tm);
2271 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2274 *header = strdup("If-Modified-Since: ");
2275 string_append(header, newheader);
2277 if (*header == NULL)
2279 log_error(LOG_LEVEL_HEADER, " Insufficent memory, header crunched without replacement.");
2280 return JB_ERR_MEMORY;
2283 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2290 hours = rtime / 3600 % 24;
2291 minutes = rtime / 60 % 60;
2292 seconds = rtime % 60;
2294 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2295 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2296 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2305 /*********************************************************************
2307 * Function : client_if_none_match
2309 * Description : Remove the If-None-Match header.
2312 * 1 : csp = Current client state (buffers, headers, etc...)
2313 * 2 : header = On input, pointer to header to modify.
2314 * On output, pointer to the modified header, or NULL
2315 * to remove the header. This function frees the
2316 * original string if necessary.
2318 * Returns : JB_ERR_OK on success, or
2319 * JB_ERR_MEMORY on out-of-memory error.
2321 *********************************************************************/
2322 jb_err client_if_none_match(struct client_state *csp, char **header)
2324 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2326 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2333 /*********************************************************************
2335 * Function : client_x_filter
2337 * Description : Disables filtering if the client set "X-Filter: No".
2338 * Called from `sed'.
2341 * 1 : csp = Current client state (buffers, headers, etc...)
2342 * 2 : header = On input, pointer to header to modify.
2343 * On output, pointer to the modified header, or NULL
2344 * to remove the header. This function frees the
2345 * original string if necessary.
2347 * Returns : JB_ERR_OK on success
2349 *********************************************************************/
2350 jb_err client_x_filter(struct client_state *csp, char **header)
2352 if ( 0 == strcmpic(*header, "X-Filter: No"))
2354 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2356 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to disable filtering!");
2360 csp->content_type = CT_TABOO;
2361 log_error(LOG_LEVEL_HEADER, "Disabled filter mode on behalf of the client.");
2363 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2369 /* the following functions add headers directly to the header list */
2371 /*********************************************************************
2373 * Function : client_host_adder
2375 * Description : Adds the Host: header field if it is missing.
2376 * Called from `sed'.
2379 * 1 : csp = Current client state (buffers, headers, etc...)
2381 * Returns : JB_ERR_OK on success, or
2382 * JB_ERR_MEMORY on out-of-memory error.
2384 *********************************************************************/
2385 jb_err client_host_adder(struct client_state *csp)
2390 if ( !csp->http->hostport || !*(csp->http->hostport))
2396 * remove 'user:pass@' from 'proto://user:pass@host'
2398 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2404 p = csp->http->hostport;
2407 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2408 err = enlist_unique_header(csp->headers, "Host", p);
2414 /*********************************************************************
2416 * Function : client_cookie_adder
2418 * Description : Used in the add_client_headers list. Called from `sed'.
2421 * 1 : csp = Current client state (buffers, headers, etc...)
2423 * Returns : JB_ERR_OK on success, or
2424 * JB_ERR_MEMORY on out-of-memory error.
2426 *********************************************************************/
2427 jb_err client_cookie_adder(struct client_state *csp)
2429 struct list_entry *lst;
2431 struct list_entry *list1 = csp->cookie_list->first;
2432 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2433 int first_cookie = 1;
2436 if ((list1 == NULL) && (list2 == NULL))
2442 tmp = strdup("Cookie: ");
2444 for (lst = list1; lst ; lst = lst->next)
2452 string_append(&tmp, "; ");
2454 string_append(&tmp, lst->str);
2457 for (lst = list2; lst ; lst = lst->next)
2465 string_append(&tmp, "; ");
2467 string_join(&tmp, cookie_encode(lst->str));
2472 return JB_ERR_MEMORY;
2475 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2476 err = enlist(csp->headers, tmp);
2482 /*********************************************************************
2484 * Function : client_accept_encoding_adder
2486 * Description : Add an Accept-Encoding header to the client's request
2487 * that disables compression if the action applies, and
2488 * the header is not already there. Called from `sed'.
2489 * Note: For HTTP/1.0, the absence of the header is enough.
2492 * 1 : csp = Current client state (buffers, headers, etc...)
2494 * Returns : JB_ERR_OK on success, or
2495 * JB_ERR_MEMORY on out-of-memory error.
2497 *********************************************************************/
2498 jb_err client_accept_encoding_adder(struct client_state *csp)
2500 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2501 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2503 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2510 /*********************************************************************
2512 * Function : client_xtra_adder
2514 * Description : Used in the add_client_headers list. Called from `sed'.
2517 * 1 : csp = Current client state (buffers, headers, etc...)
2519 * Returns : JB_ERR_OK on success, or
2520 * JB_ERR_MEMORY on out-of-memory error.
2522 *********************************************************************/
2523 jb_err client_xtra_adder(struct client_state *csp)
2525 struct list_entry *lst;
2528 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2529 lst ; lst = lst->next)
2531 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2532 err = enlist(csp->headers, lst->str);
2544 /*********************************************************************
2546 * Function : client_x_forwarded_adder
2548 * Description : Used in the add_client_headers list. Called from `sed'.
2551 * 1 : csp = Current client state (buffers, headers, etc...)
2553 * Returns : JB_ERR_OK on success, or
2554 * JB_ERR_MEMORY on out-of-memory error.
2556 *********************************************************************/
2557 jb_err client_x_forwarded_adder(struct client_state *csp)
2562 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2567 if (csp->x_forwarded)
2569 p = strdup(csp->x_forwarded);
2570 string_append(&p, ", ");
2574 p = strdup("X-Forwarded-For: ");
2576 string_append(&p, csp->ip_addr_str);
2580 return JB_ERR_MEMORY;
2583 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2584 err = enlist(csp->headers, p);
2591 /*********************************************************************
2593 * Function : connection_close_adder
2595 * Description : Adds a "Connection: close" header to csp->headers
2596 * as a temporary fix for the needed but missing HTTP/1.1
2597 * support. Called from `sed'.
2598 * FIXME: This whole function shouldn't be neccessary!
2601 * 1 : csp = Current client state (buffers, headers, etc...)
2603 * Returns : JB_ERR_OK on success, or
2604 * JB_ERR_MEMORY on out-of-memory error.
2606 *********************************************************************/
2607 jb_err connection_close_adder(struct client_state *csp)
2609 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2610 return enlist(csp->headers, "Connection: close");
2614 /*********************************************************************
2616 * Function : server_http
2618 * Description : - Save the HTTP Status into csp->http->status
2619 * - Set CT_TABOO to prevent filtering if the answer
2620 * is a partial range (HTTP status 206)
2621 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2625 * 1 : csp = Current client state (buffers, headers, etc...)
2626 * 2 : header = On input, pointer to header to modify.
2627 * On output, pointer to the modified header, or NULL
2628 * to remove the header. This function frees the
2629 * original string if necessary.
2631 * Returns : JB_ERR_OK on success, or
2632 * JB_ERR_MEMORY on out-of-memory error.
2634 *********************************************************************/
2635 jb_err server_http(struct client_state *csp, char **header)
2637 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2638 if (csp->http->status == 206)
2640 csp->content_type = CT_TABOO;
2643 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2646 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2653 /*********************************************************************
2655 * Function : server_set_cookie
2657 * Description : Handle the server "cookie" header properly.
2658 * Log cookie to the jar file. Then "crunch" it,
2659 * or accept it. Called from `sed'.
2662 * 1 : csp = Current client state (buffers, headers, etc...)
2663 * 2 : header = On input, pointer to header to modify.
2664 * On output, pointer to the modified header, or NULL
2665 * to remove the header. This function frees the
2666 * original string if necessary.
2668 * Returns : JB_ERR_OK on success, or
2669 * JB_ERR_MEMORY on out-of-memory error.
2671 *********************************************************************/
2672 jb_err server_set_cookie(struct client_state *csp, char **header)
2674 #ifdef FEATURE_COOKIE_JAR
2675 if (csp->config->jar)
2678 * Write timestamp into outbuf.
2680 * Complex because not all OSs have tm_gmtoff or
2681 * the %z field in strftime()
2683 char tempbuf[ BUFFER_SIZE ];
2687 #ifdef HAVE_LOCALTIME_R
2688 tm_now = *localtime_r(&now, &tm_now);
2690 pthread_mutex_lock(&localtime_mutex);
2691 tm_now = *localtime (&now);
2692 pthread_mutex_unlock(&localtime_mutex);
2694 tm_now = *localtime (&now);
2696 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2698 /* strlen("set-cookie: ") = 12 */
2699 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2701 #endif /* def FEATURE_COOKIE_JAR */
2703 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2705 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2706 return crumble(csp, header);
2708 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2710 /* Flag whether or not to log a message */
2713 /* A variable to store the tag we're working on */
2716 /* Skip "Set-Cookie:" (11 characters) in header */
2717 cur_tag = *header + 11;
2719 /* skip whitespace between "Set-Cookie:" and value */
2720 while (*cur_tag && ijb_isspace(*cur_tag))
2725 /* Loop through each tag in the cookie */
2729 char *next_tag = strchr(cur_tag, ';');
2730 if (next_tag != NULL)
2732 /* Skip the ';' character itself */
2735 /* skip whitespace ";" and start of tag */
2736 while (*next_tag && ijb_isspace(*next_tag))
2743 /* "Next tag" is the end of the string */
2744 next_tag = cur_tag + strlen(cur_tag);
2747 /* Is this the "Expires" tag? */
2748 if (strncmpic(cur_tag, "expires=", 8) == 0)
2750 /* Delete the tag by copying the rest of the string over it.
2751 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2752 * since the behaviour of strcpy is undefined for overlapping
2755 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2757 /* That changed the header, need to issue a log message */
2760 /* Note that the next tag has now been moved to *cur_tag,
2761 * so we do not need to update the cur_tag pointer.
2766 /* Move on to next cookie tag */
2773 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2781 #ifdef FEATURE_FORCE_LOAD
2782 /*********************************************************************
2784 * Function : strclean
2786 * Description : In-Situ-Eliminate all occurances of substring in
2790 * 1 : string = string to clean
2791 * 2 : substring = substring to eliminate
2793 * Returns : Number of eliminations
2795 *********************************************************************/
2796 int strclean(const char *string, const char *substring)
2798 int hits = 0, len = strlen(substring);
2801 while((pos = strstr(string, substring)) != NULL)
2808 while (*p++ != '\0');
2815 #endif /* def FEATURE_FORCE_LOAD */
2817 /*********************************************************************
2819 * Function : parse_header_time
2821 * Description : Transforms time inside a HTTP header into
2822 * the usual time format.
2825 * 1 : header = header to parse
2826 * 2 : timeptr = storage for the resulting time structure
2828 * Returns : Time in seconds since Unix epoch or -1 for failure.
2830 *********************************************************************/
2831 time_t parse_header_time(char *header, struct tm *timeptr) {
2837 timeptr = localtime(&tm);
2838 /* Skipping header name */
2839 timestring = strstr(header, ": ");
2840 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", timeptr) == NULL)
2844 tm = mktime(timeptr);