1 const char parsers_rcs[] = "$Id: parsers.c,v 1.64 2006/08/17 17:15:10 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.64 2006/08/17 17:15:10 fabiankeil
44 * - Back to timegm() using GnuPG's replacement if necessary.
45 * Using mktime() and localtime() could add a on hour offset if
46 * the randomize factor was big enough to lead to a summer/wintertime
49 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
51 * - Moved randomization code into pick_from_range().
53 * - Changed parse_header_time definition.
54 * time_t isn't guaranteed to be signed and
55 * if it isn't, -1 isn't available as error code.
56 * Changed some variable types in client_if_modified_since()
57 * because of the same reason.
59 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
60 * OS/2 compilation compatibility fixups
62 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
63 * Changed include from strptime.c to strptime.h
65 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
66 * Split filter-headers{} into filter-client-headers{}
67 * and filter-server-headers{}.
68 * Added parse_header_time() to share some code.
69 * Replaced timegm() with mktime().
71 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
72 * Windows service integration
74 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
75 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
77 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
78 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
79 * with what was really the latest development (the v_3_0_branch branch)
81 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
82 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
84 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
85 * Add the ability to check jpeg images for invalid
86 * lengths of comment blocks. Defensive strategy
87 * against the exploit:
88 * Microsoft Security Bulletin MS04-028
89 * Buffer Overrun in JPEG Processing (GDI+) Could
90 * Allow Code Execution (833987)
91 * Enabled with +inspect-jpegs in actions files.
93 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
94 * Excluded text/plain objects from filtering. This fixes a
95 * couple of client-crashing, download corruption and
96 * Privoxy performance issues, whose root cause lies in
97 * web servers labelling content of unknown type as text/plain.
99 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
100 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
102 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
103 * Completing the previous change
105 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
106 * Added temporary workaround for bug in PHP < 4.2.3
108 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
109 * 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.
111 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
112 * Fix typo: supressed -> suppressed
114 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
115 * Improved cookie logging
117 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
118 * Added basic support for OPTIONS and TRACE HTTP methods:
119 * - New parser function client_max_forwards which decrements
120 * the Max-Forwards HTTP header field of OPTIONS and TRACE
121 * requests by one before forwarding
122 * - New parser function client_host which extracts the host
123 * and port information from the HTTP header field if the
124 * request URI was not absolute
125 * - Don't crumble and re-add the Host: header, but only generate
126 * and append if missing
128 * Revision 1.56 2002/05/12 15:34:22 jongfoster
129 * Fixing typo in a comment
131 * Revision 1.55 2002/05/08 16:01:07 oes
132 * Optimized add_to_iob:
133 * - Use realloc instead of malloc(), memcpy(), free()
134 * - Expand to powers of two if possible, to get
135 * O(log n) reallocs instead of O(n).
136 * - Moved check for buffer limit here from chat
137 * - Report failure via returncode
139 * Revision 1.54 2002/04/02 15:03:16 oes
140 * Tiny code cosmetics
142 * Revision 1.53 2002/03/26 22:29:55 swa
143 * we have a new homepage!
145 * Revision 1.52 2002/03/24 13:25:43 swa
146 * name change related issues
148 * Revision 1.51 2002/03/13 00:27:05 jongfoster
151 * Revision 1.50 2002/03/12 01:45:35 oes
152 * More verbose logging
154 * Revision 1.49 2002/03/09 20:03:52 jongfoster
155 * - Making various functions return int rather than size_t.
156 * (Undoing a recent change). Since size_t is unsigned on
157 * Windows, functions like read_socket that return -1 on
158 * error cannot return a size_t.
160 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
161 * crashes, and also frequently caused JB to jump to 100%
162 * CPU and stay there. (Because it thought it had just
163 * read ((unsigned)-1) == 4Gb of data...)
165 * - The signature of write_socket has changed, it now simply
166 * returns success=0/failure=nonzero.
168 * - Trying to get rid of a few warnings --with-debug on
169 * Windows, I've introduced a new type "jb_socket". This is
170 * used for the socket file descriptors. On Windows, this
171 * is SOCKET (a typedef for unsigned). Everywhere else, it's
172 * an int. The error value can't be -1 any more, so it's
173 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
174 * Windows it maps to the #define INVALID_SOCKET.)
176 * - The signature of bind_port has changed.
178 * Revision 1.48 2002/03/07 03:46:53 oes
179 * Fixed compiler warnings etc
181 * Revision 1.47 2002/02/20 23:15:13 jongfoster
182 * Parsing functions now handle out-of-memory gracefully by returning
185 * Revision 1.46 2002/01/17 21:03:47 jongfoster
186 * Moving all our URL and URL pattern parsing code to urlmatch.c.
188 * Revision 1.45 2002/01/09 14:33:03 oes
189 * Added support for localtime_r.
191 * Revision 1.44 2001/12/14 01:22:54 steudten
192 * Remove 'user:pass@' from 'proto://user:pass@host' for the
193 * new added header 'Host: ..'. (See Req ID 491818)
195 * Revision 1.43 2001/11/23 00:26:38 jongfoster
196 * Fixing two really stupid errors in my previous commit
198 * Revision 1.42 2001/11/22 21:59:30 jongfoster
199 * Adding code to handle +no-cookies-keep
201 * Revision 1.41 2001/11/05 23:43:05 steudten
202 * Add time+date to log files.
204 * Revision 1.40 2001/10/26 20:13:09 jongfoster
205 * ctype.h is needed in Windows, too.
207 * Revision 1.39 2001/10/26 17:40:04 oes
208 * Introduced get_header_value()
209 * Removed http->user_agent, csp->referrer and csp->accept_types
210 * Removed client_accept()
212 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
213 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
214 * threads to call select() simultaneously. So, it's time to do a real, live,
215 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
216 * (native). Both versions will work, but using __OS2__ offers multi-threading.
218 * Revision 1.37 2001/10/23 21:36:02 jongfoster
219 * Documenting sed()'s error behaviou (doc change only)
221 * Revision 1.36 2001/10/13 12:51:51 joergs
222 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
223 * force-load), instead crumble Host: and add it (again) in client_host_adder
224 * (in case we get a HTTP/1.0 request without Host: header and forward it to
225 * a HTTP/1.1 server/proxy).
227 * Revision 1.35 2001/10/09 22:39:21 jongfoster
228 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
231 * Revision 1.34 2001/10/07 18:50:55 oes
232 * Added server_content_encoding, renamed server_transfer_encoding
234 * Revision 1.33 2001/10/07 18:04:49 oes
235 * Changed server_http11 to server_http and its pattern to "HTTP".
236 * Additional functionality: it now saves the HTTP status into
237 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
239 * Revision 1.32 2001/10/07 15:43:28 oes
240 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
241 * client_te and client_accept_encoding_adder, triggered by the new
242 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
243 * changed to allow only identity and chunked, and the TE header is
244 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
246 * parse_http_request no longer does anything than parsing. The rewriting
247 * of http->cmd and version mangling are gone. It now also recognizes
248 * the put and delete methods and saves the url in http->url. Removed
251 * renamed content_type and content_length to have the server_ prefix
253 * server_content_type now only works if csp->content_type != CT_TABOO
255 * added server_transfer_encoding, which
256 * - Sets CT_TABOO to prohibit filtering if encoding compresses
257 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
258 * - Change from "chunked" to "identity" if body was chunked
259 * but has been de-chunked for filtering.
261 * added server_content_md5 which crunches any Content-MD5 headers
262 * if the body was modified.
264 * made server_http11 conditional on +downgrade action
266 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
268 * Revision 1.31 2001/10/05 14:25:02 oes
269 * Crumble Keep-Alive from Server
271 * Revision 1.30 2001/09/29 12:56:03 joergs
272 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
274 * Revision 1.29 2001/09/24 21:09:24 jongfoster
275 * Fixing 2 memory leaks that Guy spotted, where the paramater to
276 * enlist() was not being free()d.
278 * Revision 1.28 2001/09/22 16:32:28 jongfoster
279 * Removing unused #includes.
281 * Revision 1.27 2001/09/20 15:45:25 steudten
283 * add casting from size_t to int for printf()
284 * remove local variable shadow s2
286 * Revision 1.26 2001/09/16 17:05:14 jongfoster
287 * Removing unused #include showarg.h
289 * Revision 1.25 2001/09/16 13:21:27 jongfoster
290 * Changes to use new list functions.
292 * Revision 1.24 2001/09/13 23:05:50 jongfoster
293 * Changing the string paramater to the header parsers a "const".
295 * Revision 1.23 2001/09/12 18:08:19 steudten
297 * In parse_http_request() header rewriting miss the host value, so
298 * from http://www.mydomain.com the result was just " / " not
299 * http://www.mydomain.com/ in case we forward.
301 * Revision 1.22 2001/09/10 10:58:53 oes
302 * Silenced compiler warnings
304 * Revision 1.21 2001/07/31 14:46:00 oes
305 * - Persistant connections now suppressed
306 * - sed() no longer appends empty header to csp->headers
308 * Revision 1.20 2001/07/30 22:08:36 jongfoster
309 * Tidying up #defines:
310 * - All feature #defines are now of the form FEATURE_xxx
311 * - Permanently turned off WIN_GUI_EDIT
312 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
314 * Revision 1.19 2001/07/25 17:21:54 oes
315 * client_uagent now saves copy of User-Agent: header value
317 * Revision 1.18 2001/07/13 14:02:46 oes
318 * - Included fix to repair broken HTTP requests that
319 * don't contain a path, not even '/'.
320 * - Removed all #ifdef PCRS
321 * - content_type now always inspected and classified as
322 * text, gif or other.
323 * - formatting / comments
325 * Revision 1.17 2001/06/29 21:45:41 oes
326 * Indentation, CRLF->LF, Tab-> Space
328 * Revision 1.16 2001/06/29 13:32:42 oes
330 * - Adapted free_http_request
331 * - Removed logentry from cancelled commit
333 * Revision 1.15 2001/06/03 19:12:38 oes
334 * deleted const struct interceptors
336 * Revision 1.14 2001/06/01 18:49:17 jongfoster
337 * Replaced "list_share" with "list" - the tiny memory gain was not
338 * worth the extra complexity.
340 * Revision 1.13 2001/05/31 21:30:33 jongfoster
341 * Removed list code - it's now in list.[ch]
342 * Renamed "permission" to "action", and changed many features
343 * to use the actions file rather than the global config.
345 * Revision 1.12 2001/05/31 17:33:13 oes
349 * Revision 1.11 2001/05/29 20:11:19 joergs
350 * '/ * inside comment' warning removed.
352 * Revision 1.10 2001/05/29 09:50:24 jongfoster
353 * Unified blocklist/imagelist/permissionslist.
354 * File format is still under discussion, but the internal changes
357 * Also modified interceptor behaviour:
358 * - We now intercept all URLs beginning with one of the following
359 * prefixes (and *only* these prefixes):
361 * * http://ijbswa.sf.net/config/
362 * * http://ijbswa.sourceforge.net/config/
363 * - New interceptors "home page" - go to http://i.j.b/ to see it.
364 * - Internal changes so that intercepted and fast redirect pages
365 * are not replaced with an image.
366 * - Interceptors now have the option to send a binary page direct
367 * to the client. (i.e. ijb-send-banner uses this)
368 * - Implemented show-url-info interceptor. (Which is why I needed
369 * the above interceptors changes - a typical URL is
370 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
371 * The previous mechanism would not have intercepted that, and
372 * if it had been intercepted then it then it would have replaced
375 * Revision 1.9 2001/05/28 17:26:33 jongfoster
376 * Fixing segfault if last header was crunched.
377 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
378 * can use the cross-platform sprintf() instead.)
380 * Revision 1.8 2001/05/27 22:17:04 oes
382 * - re_process_buffer no longer writes the modified buffer
383 * to the client, which was very ugly. It now returns the
384 * buffer, which it is then written by chat.
386 * - content_length now adjusts the Content-Length: header
387 * for modified documents rather than crunch()ing it.
388 * (Length info in csp->content_length, which is 0 for
389 * unmodified documents)
391 * - For this to work, sed() is called twice when filtering.
393 * Revision 1.7 2001/05/27 13:19:06 oes
394 * Patched Joergs solution for the content-length in.
396 * Revision 1.6 2001/05/26 13:39:32 jongfoster
397 * Only crunches Content-Length header if applying RE filtering.
398 * Without this fix, Microsoft Windows Update wouldn't work.
400 * Revision 1.5 2001/05/26 00:28:36 jongfoster
401 * Automatic reloading of config file.
402 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
403 * Most of the global variables have been moved to a new
404 * struct configuration_spec, accessed through csp->config->globalname
405 * Most of the globals remaining are used by the Win32 GUI.
407 * Revision 1.4 2001/05/22 18:46:04 oes
409 * - Enabled filtering banners by size rather than URL
410 * by adding patterns that replace all standard banner
411 * sizes with the "Junkbuster" gif to the re_filterfile
413 * - Enabled filtering WebBugs by providing a pattern
414 * which kills all 1x1 images
416 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
417 * which is selected by the (nonstandard and therefore
418 * capital) letter 'U' in the option string.
419 * It causes the quantifiers to be ungreedy by default.
420 * Appending a ? turns back to greedy (!).
422 * - Added a new interceptor ijb-send-banner, which
423 * sends back the "Junkbuster" gif. Without imagelist or
424 * MSIE detection support, or if tinygif = 1, or the
425 * URL isn't recognized as an imageurl, a lame HTML
426 * explanation is sent instead.
428 * - Added new feature, which permits blocking remote
429 * script redirects and firing back a local redirect
431 * The feature is conditionally compiled, i.e. it
432 * can be disabled with --disable-fast-redirects,
433 * plus it must be activated by a "fast-redirects"
434 * line in the config file, has its own log level
435 * and of course wants to be displayed by show-proxy-args
436 * Note: Boy, all the #ifdefs in 1001 locations and
437 * all the fumbling with configure.in and acconfig.h
438 * were *way* more work than the feature itself :-(
440 * - Because a generic redirect template was needed for
441 * this, tinygif = 3 now uses the same.
443 * - Moved GIFs, and other static HTTP response templates
448 * - Removed some >400 CRs again (Jon, you really worked
451 * Revision 1.3 2001/05/20 01:21:20 jongfoster
452 * Version 2.9.4 checkin.
453 * - Merged popupfile and cookiefile, and added control over PCRS
454 * filtering, in new "permissionsfile".
455 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
456 * file error you now get a message box (in the Win32 GUI) rather
457 * than the program exiting with no explanation.
458 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
460 * - Removed tabs from "config"
461 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
462 * - Bumped up version number.
464 * Revision 1.2 2001/05/17 23:02:36 oes
465 * - Made referrer option accept 'L' as a substitute for '§'
467 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
468 * Initial import of version 2.9.3 source tree
471 *********************************************************************/
478 #include <sys/types.h>
487 #if !defined(_WIN32) && !defined(__OS2__)
496 /* jcc.h is for mutex semapores only */
497 #endif /* def OSX_DARWIN */
503 #include "jbsockets.h"
504 #include "miscutil.h"
507 #ifndef HAVE_STRPTIME
508 #include "strptime.h"
511 const char parsers_h_rcs[] = PARSERS_H_VERSION;
513 /* Fix a problem with Solaris. There should be no effect on other
515 * Solaris's isspace() is a macro which uses it's argument directly
516 * as an array index. Therefore we need to make sure that high-bit
517 * characters generate +ve values, and ideally we also want to make
518 * the argument match the declared parameter type of "int".
520 * Why did they write a character function that can't take a simple
521 * "char" argument? Doh!
523 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
524 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
527 const struct parsers client_patterns[] = {
528 { "referer:", 8, client_referrer },
529 { "user-agent:", 11, client_uagent },
530 { "ua-", 3, client_ua },
531 { "from:", 5, client_from },
532 { "cookie:", 7, client_send_cookie },
533 { "x-forwarded-for:", 16, client_x_forwarded },
534 { "Accept-Encoding:", 16, client_accept_encoding },
535 { "TE:", 3, client_te },
536 { "Host:", 5, client_host },
537 { "if-modified-since:", 18, client_if_modified_since },
538 { "Keep-Alive:", 11, crumble },
539 { "connection:", 11, crumble },
540 { "proxy-connection:", 17, crumble },
541 { "max-forwards:", 13, client_max_forwards },
542 { "Accept-Language:", 16, client_accept_language },
543 { "if-none-match:", 14, client_if_none_match },
544 { "X-Filter:", 9, client_x_filter },
545 { "*", 0, crunch_client_header },
546 { "*", 0, filter_client_header },
550 const struct parsers server_patterns[] = {
551 { "HTTP", 4, server_http },
552 { "set-cookie:", 11, server_set_cookie },
553 { "connection:", 11, crumble },
554 { "Content-Type:", 13, server_content_type },
555 { "Content-Length:", 15, server_content_length },
556 { "Content-MD5:", 12, server_content_md5 },
557 { "Content-Encoding:", 17, server_content_encoding },
558 { "Transfer-Encoding:", 18, server_transfer_coding },
559 { "Keep-Alive:", 11, crumble },
560 { "content-disposition:", 20, server_content_disposition },
561 { "Last-Modified:", 14, server_last_modified },
562 { "*", 0, crunch_server_header },
563 { "*", 0, filter_server_header },
567 const struct parsers server_patterns_light[] = {
568 { "Content-Length:", 15, server_content_length },
569 { "Transfer-Encoding:", 18, server_transfer_coding },
573 const add_header_func_ptr add_client_headers[] = {
576 client_x_forwarded_adder,
578 /* Temporarily disabled: client_accept_encoding_adder, */
579 connection_close_adder,
584 const add_header_func_ptr add_server_headers[] = {
585 connection_close_adder,
589 /*********************************************************************
591 * Function : flush_socket
593 * Description : Write any pending "buffered" content.
596 * 1 : fd = file descriptor of the socket to read
597 * 2 : csp = Current client state (buffers, headers, etc...)
599 * Returns : On success, the number of bytes written are returned (zero
600 * indicates nothing was written). On error, -1 is returned,
601 * and errno is set appropriately. If count is zero and the
602 * file descriptor refers to a regular file, 0 will be
603 * returned without causing any other effect. For a special
604 * file, the results are not portable.
606 *********************************************************************/
607 int flush_socket(jb_socket fd, struct client_state *csp)
609 struct iob *iob = csp->iob;
610 int len = iob->eod - iob->cur;
617 if (write_socket(fd, iob->cur, (size_t)len))
621 iob->eod = iob->cur = iob->buf;
627 /*********************************************************************
629 * Function : add_to_iob
631 * Description : Add content to the buffered page, expanding the
632 * buffer if necessary.
635 * 1 : csp = Current client state (buffers, headers, etc...)
636 * 2 : buf = holds the content to be added to the page
637 * 3 : n = number of bytes to be added
639 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
640 * or buffer limit reached.
642 *********************************************************************/
643 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
645 struct iob *iob = csp->iob;
646 size_t used, offset, need, want;
649 if (n <= 0) return JB_ERR_OK;
651 used = iob->eod - iob->buf;
652 offset = iob->cur - iob->buf;
656 * If the buffer can't hold the new data, extend it first.
657 * Use the next power of two if possible, else use the actual need.
659 if (need > csp->config->buffer_limit)
661 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
662 return JB_ERR_MEMORY;
665 if (need > iob->size)
667 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
669 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
673 else if (NULL != (p = (char *)realloc(iob->buf, need)))
679 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
680 return JB_ERR_MEMORY;
683 /* Update the iob pointers */
684 iob->cur = p + offset;
689 /* copy the new data into the iob buffer */
690 memcpy(iob->eod, buf, (size_t)n);
692 /* point to the end of the data */
695 /* null terminate == cheap insurance */
703 /*********************************************************************
705 * Function : get_header
707 * Description : This (odd) routine will parse the csp->iob
710 * 1 : csp = Current client state (buffers, headers, etc...)
712 * Returns : Any one of the following:
714 * 1) a pointer to a dynamically allocated string that contains a header line
715 * 2) NULL indicating that the end of the header was reached
716 * 3) "" indicating that the end of the iob was reached before finding
717 * a complete header line.
719 *********************************************************************/
720 char *get_header(struct client_state *csp)
726 if ((iob->cur == NULL)
727 || ((p = strchr(iob->cur, '\n')) == NULL))
729 return(""); /* couldn't find a complete header */
734 ret = strdup(iob->cur);
737 /* FIXME No way to handle error properly */
738 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
743 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
745 /* is this a blank line (i.e. the end of the header) ? */
757 /*********************************************************************
759 * Function : get_header_value
761 * Description : Get the value of a given header from a chained list
762 * of header lines or return NULL if no such header is
763 * present in the list.
766 * 1 : header_list = pointer to list
767 * 2 : header_name = string with name of header to look for.
768 * Trailing colon required, capitalization
771 * Returns : NULL if not found, else value of header
773 *********************************************************************/
774 char *get_header_value(const struct list *header_list, const char *header_name)
776 struct list_entry *cur_entry;
782 length = strlen(header_name);
784 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
788 if (!strncmpic(cur_entry->str, header_name, length))
791 * Found: return pointer to start of value
793 ret = (char *) (cur_entry->str + length);
794 while (*ret && ijb_isspace(*ret)) ret++;
807 /*********************************************************************
811 * Description : add, delete or modify lines in the HTTP header streams.
812 * On entry, it receives a linked list of headers space
813 * that was allocated dynamically (both the list nodes
814 * and the header contents).
816 * As a side effect it frees the space used by the original
820 * 1 : pats = list of patterns to match against headers
821 * 2 : more_headers = list of functions to add more
822 * headers (client or server)
823 * 3 : csp = Current client state (buffers, headers, etc...)
825 * Returns : Single pointer to a fully formed header, or NULL
826 * on out-of-memory error.
828 *********************************************************************/
829 char *sed(const struct parsers pats[],
830 const add_header_func_ptr more_headers[],
831 struct client_state *csp)
833 struct list_entry *p;
834 const struct parsers *v;
835 const add_header_func_ptr *f;
836 jb_err err = JB_ERR_OK;
840 * If filtering is enabled, sed is run twice,
841 * but most of the work needs to be done only once.
843 first_run = (more_headers != NULL ) ? 1 : 0;
845 if (first_run) /* Parse and print */
847 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
849 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
851 /* Header crunch()ed in previous run? -> ignore */
852 if (p->str == NULL) continue;
854 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
856 /* Does the current parser handle this header? */
857 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
859 err = v->parser(csp, (char **)&(p->str));
863 /* place any additional headers on the csp->headers list */
864 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
869 else /* Parse only */
872 * The second run is only needed if the body was modified
873 * and the content-lenght has changed.
875 if (strncmpic(csp->http->cmd, "HEAD", 4))
877 /*XXX: Code duplication*/
878 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
880 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
882 /* Header crunch()ed in previous run? -> ignore */
883 if (p->str == NULL) continue;
885 /* Does the current parser handle this header? */
886 if (strncmpic(p->str, v->str, v->len) == 0)
888 err = v->parser(csp, (char **)&(p->str));
895 if (err != JB_ERR_OK)
900 return list_to_text(csp->headers);
904 /* here begins the family of parser functions that reformat header lines */
906 /*********************************************************************
908 * Function : filter_server_header
910 * Description : Checks if server header filtering is enabled.
911 * If it is, filter_header is called to do the work.
914 * 1 : csp = Current client state (buffers, headers, etc...)
915 * 2 : header = On input, pointer to header to modify.
916 * On output, pointer to the modified header, or NULL
917 * to remove the header. This function frees the
918 * original string if necessary.
920 * Returns : JB_ERR_OK on success and always succeeds
922 *********************************************************************/
923 jb_err filter_server_header(struct client_state *csp, char **header)
925 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
927 filter_header(csp, header);
932 /*********************************************************************
934 * Function : filter_client_header
936 * Description : Checks if client header filtering is enabled.
937 * If it is, filter_header is called to do the work.
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_client_header(struct client_state *csp, char **header)
951 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
953 filter_header(csp, header);
958 /*********************************************************************
960 * Function : filter_header
962 * Description : Executes all text substitutions from all applying
963 * +filter actions on the header.
964 * Most of the code was copied from pcrs_filter_response,
965 * including the rather short variable names
968 * 1 : csp = Current client state (buffers, headers, etc...)
969 * 2 : header = On input, pointer to header to modify.
970 * On output, pointer to the modified header, or NULL
971 * to remove the header. This function frees the
972 * original string if necessary.
974 * Returns : JB_ERR_OK on success and always succeeds
976 *********************************************************************/
977 jb_err filter_header(struct client_state *csp, char **header)
981 size_t size = strlen(*header);
983 char *newheader = NULL;
986 struct file_list *fl;
987 struct re_filterfile_spec *b;
988 struct list_entry *filtername;
990 int i, found_filters = 0;
992 log_error(LOG_LEVEL_RE_FILTER, "Entered filter_headers");
994 * Need to check the set of re_filterfiles...
996 for (i = 0; i < MAX_AF_FILES; i++)
1009 if (0 == found_filters)
1011 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1015 for (i = 0; i < MAX_AF_FILES; i++)
1018 if ((NULL == fl) || (NULL == fl->f))
1021 * For all applying +filter actions, look if a filter by that
1022 * name exists and if yes, execute its pcrs_joblist on the
1025 for (b = fl->f; b; b = b->next)
1027 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1028 filtername ; filtername = filtername->next)
1030 if (strcmp(b->name, filtername->str) == 0)
1032 int current_hits = 0;
1034 if ( NULL == b->joblist )
1036 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1040 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1041 *header, size, b->name);
1043 /* Apply all jobs from the joblist */
1044 for (job = b->joblist; NULL != job; job = job->next)
1046 matches = pcrs_execute(job, *header, size, &newheader, &size);
1049 current_hits += matches;
1050 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1052 *header = newheader;
1054 else if ( 0 == matches )
1056 /* Filter doesn't change header */
1062 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1063 *header, b->name, pcrs_strerror(matches));
1064 if( newheader != NULL)
1066 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1071 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1072 hits += current_hits;
1080 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1083 log_error(LOG_LEVEL_RE_FILTER, "Leaving filter headers");
1089 /*********************************************************************
1091 * Function : crumble
1093 * Description : This is called if a header matches a pattern to "crunch"
1096 * 1 : csp = Current client state (buffers, headers, etc...)
1097 * 2 : header = On input, pointer to header to modify.
1098 * On output, pointer to the modified header, or NULL
1099 * to remove the header. This function frees the
1100 * original string if necessary.
1102 * Returns : JB_ERR_OK on success, or
1103 * JB_ERR_MEMORY on out-of-memory error.
1105 *********************************************************************/
1106 jb_err crumble(struct client_state *csp, char **header)
1108 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1113 /*********************************************************************
1115 * Function : crunch_server_header
1117 * Description : Crunch server header if it matches a string supplied by the
1118 * user. Called from `sed'.
1121 * 1 : csp = Current client state (buffers, headers, etc...)
1122 * 2 : header = On input, pointer to header to modify.
1123 * On output, pointer to the modified header, or NULL
1124 * to remove the header. This function frees the
1125 * original string if necessary.
1127 * Returns : JB_ERR_OK on success and always succeeds
1129 *********************************************************************/
1130 jb_err crunch_server_header(struct client_state *csp, char **header)
1132 const char *crunch_pattern;
1133 /*Is there a header to crunch*/
1135 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1137 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1139 /*Is the current header the lucky one?*/
1140 if (strstr(*header, crunch_pattern))
1142 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1149 /*********************************************************************
1151 * Function : server_content_type
1153 * Description : Set the content-type for filterable types (text/.*,
1154 * javascript and image/gif) unless filtering has been
1155 * forbidden (CT_TABOO) while parsing earlier headers.
1156 * NOTE: Since text/plain is commonly used by web servers
1157 * for files whose correct type is unknown, we don't
1158 * set CT_TEXT for it.
1161 * 1 : csp = Current client state (buffers, headers, etc...)
1162 * 2 : header = On input, pointer to header to modify.
1163 * On output, pointer to the modified header, or NULL
1164 * to remove the header. This function frees the
1165 * original string if necessary.
1167 * Returns : JB_ERR_OK on success, or
1168 * JB_ERR_MEMORY on out-of-memory error.
1170 *********************************************************************/
1171 jb_err server_content_type(struct client_state *csp, char **header)
1175 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1177 if (csp->content_type != CT_TABOO)
1179 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1180 || strstr(*header, "xml")
1181 || strstr(*header, "application/x-javascript"))
1182 csp->content_type = CT_TEXT;
1183 else if (strstr(*header, " image/gif"))
1184 csp->content_type = CT_GIF;
1185 else if (strstr(*header, " image/jpeg"))
1186 csp->content_type = CT_JPEG;
1188 csp->content_type = 0;
1191 * Are we enabling text mode by force?
1193 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1196 * Do we really have to?
1198 if (csp->content_type == CT_TEXT)
1200 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1204 csp->content_type = CT_TEXT;
1205 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1209 * Are we messing with the content type?
1211 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1214 * Make sure the user doesn't accidently
1215 * change the content type of binary documents.
1217 if (csp->content_type == CT_TEXT)
1220 *header = strdup("Content-Type: ");
1221 string_append(header, newval);
1225 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1226 return JB_ERR_MEMORY;
1228 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1232 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1233 "Enable force-text-mode if you know what you're doing.", *header);
1240 /*********************************************************************
1242 * Function : server_transfer_coding
1244 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1245 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1246 * - Change from "chunked" to "identity" if body was chunked
1247 * but has been de-chunked for filtering.
1250 * 1 : csp = Current client state (buffers, headers, etc...)
1251 * 2 : header = On input, pointer to header to modify.
1252 * On output, pointer to the modified header, or NULL
1253 * to remove the header. This function frees the
1254 * original string if necessary.
1256 * Returns : JB_ERR_OK on success, or
1257 * JB_ERR_MEMORY on out-of-memory error.
1259 *********************************************************************/
1260 jb_err server_transfer_coding(struct client_state *csp, char **header)
1263 * Turn off pcrs and gif filtering if body compressed
1265 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1267 csp->content_type = CT_TABOO;
1271 * Raise flag if body chunked
1273 if (strstr(*header, "chunked"))
1275 csp->flags |= CSP_FLAG_CHUNKED;
1278 * If the body was modified, it has been
1279 * de-chunked first, so adjust the header:
1281 if (csp->flags & CSP_FLAG_MODIFIED)
1284 *header = strdup("Transfer-Encoding: identity");
1285 log_error(LOG_LEVEL_HEADER, "Set: %s", *header);
1286 return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1294 /*********************************************************************
1296 * Function : server_content_encoding
1298 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1301 * 1 : csp = Current client state (buffers, headers, etc...)
1302 * 2 : header = On input, pointer to header to modify.
1303 * On output, pointer to the modified header, or NULL
1304 * to remove the header. This function frees the
1305 * original string if necessary.
1307 * Returns : JB_ERR_OK on success, or
1308 * JB_ERR_MEMORY on out-of-memory error.
1310 *********************************************************************/
1311 jb_err server_content_encoding(struct client_state *csp, char **header)
1314 * Turn off pcrs and gif filtering if body compressed
1316 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1318 csp->content_type = CT_TABOO;
1326 /*********************************************************************
1328 * Function : server_content_length
1330 * Description : Adjust Content-Length header if we modified
1334 * 1 : csp = Current client state (buffers, headers, etc...)
1335 * 2 : header = On input, pointer to header to modify.
1336 * On output, pointer to the modified header, or NULL
1337 * to remove the header. This function frees the
1338 * original string if necessary.
1340 * Returns : JB_ERR_OK on success, or
1341 * JB_ERR_MEMORY on out-of-memory error.
1343 *********************************************************************/
1344 jb_err server_content_length(struct client_state *csp, char **header)
1346 if (csp->content_length != 0) /* Content length could have been modified */
1349 * XXX: Shouldn't we check if csp->content_length
1350 * is different than the original value?
1353 *header = (char *) zalloc(100);
1354 if (*header == NULL)
1356 return JB_ERR_MEMORY;
1359 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1361 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1368 /*********************************************************************
1370 * Function : server_content_md5
1372 * Description : Crumble any Content-MD5 headers if the document was
1373 * modified. FIXME: Should we re-compute instead?
1376 * 1 : csp = Current client state (buffers, headers, etc...)
1377 * 2 : header = On input, pointer to header to modify.
1378 * On output, pointer to the modified header, or NULL
1379 * to remove the header. This function frees the
1380 * original string if necessary.
1382 * Returns : JB_ERR_OK on success, or
1383 * JB_ERR_MEMORY on out-of-memory error.
1385 *********************************************************************/
1386 jb_err server_content_md5(struct client_state *csp, char **header)
1388 if (csp->flags & CSP_FLAG_MODIFIED)
1390 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1397 /*********************************************************************
1399 * Function : server_content_disposition
1401 * Description : If enabled, blocks or modifies the "content-disposition" header.
1402 * Called from `sed'.
1405 * 1 : csp = Current client state (buffers, headers, etc...)
1406 * 2 : header = On input, pointer to header to modify.
1407 * On output, pointer to the modified header, or NULL
1408 * to remove the header. This function frees the
1409 * original string if necessary.
1411 * Returns : JB_ERR_OK on success, or
1412 * JB_ERR_MEMORY on out-of-memory error.
1414 *********************************************************************/
1415 jb_err server_content_disposition(struct client_state *csp, char **header)
1420 * Are we messing with the content-disposition header?
1422 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1428 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1430 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1433 * Blocking content-disposition header
1435 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1442 * Replacing content-disposition header
1445 *header = strdup("content-disposition: ");
1446 string_append(header, newval);
1448 if (*header == NULL)
1450 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1454 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1457 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1460 /*********************************************************************
1462 * Function : server_last_modified
1464 * Description : Changes Last-Modified header to the actual date
1465 * to help hide-if-modified-since.
1466 * Called from `sed'.
1469 * 1 : csp = Current client state (buffers, headers, etc...)
1470 * 2 : header = On input, pointer to header to modify.
1471 * On output, pointer to the modified header, or NULL
1472 * to remove the header. This function frees the
1473 * original string if necessary.
1475 * Returns : JB_ERR_OK on success, or
1476 * JB_ERR_MEMORY on out-of-memory error.
1478 *********************************************************************/
1479 jb_err server_last_modified(struct client_state *csp, char **header)
1482 char buf[BUFFER_SIZE];
1485 struct tm *timeptr = NULL;
1486 time_t now, last_modified;
1488 long int days, hours, minutes, seconds;
1491 * Are we messing with the Last-Modified header?
1493 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1499 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1501 if (0 == strcmpic(newval, "block") )
1504 * Blocking Last-Modified header. Useless but why not.
1506 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1510 else if (0 == strcmpic(newval, "reset-to-request-time"))
1513 * Setting Last-Modified Header to now.
1515 get_http_time(0, buf);
1517 *header = strdup("Last-Modified: ");
1518 string_append(header, buf);
1520 if (*header == NULL)
1522 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1526 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1529 else if (0 == strcmpic(newval, "randomize"))
1531 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1533 timeptr = gmtime(&now);
1534 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
1536 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1541 rtime = difftime(now, last_modified);
1544 rtime = pick_from_range(rtime);
1545 last_modified += rtime;
1546 timeptr = gmtime(&last_modified);
1547 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1549 *header = strdup("Last-Modified: ");
1550 string_append(header, newheader);
1552 if (*header == NULL)
1554 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
1555 return JB_ERR_MEMORY;
1558 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1560 days = rtime / (3600 * 24);
1561 hours = rtime / 3600 % 24;
1562 minutes = rtime / 60 % 60;
1563 seconds = rtime % 60;
1565 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1566 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1567 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1572 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1580 /*********************************************************************
1582 * Function : client_accept_encoding
1584 * Description : Rewrite the client's Accept-Encoding header so that
1585 * if doesn't allow compression, if the action applies.
1586 * Note: For HTTP/1.0 the absence of the header is enough.
1589 * 1 : csp = Current client state (buffers, headers, etc...)
1590 * 2 : header = On input, pointer to header to modify.
1591 * On output, pointer to the modified header, or NULL
1592 * to remove the header. This function frees the
1593 * original string if necessary.
1595 * Returns : JB_ERR_OK on success, or
1596 * JB_ERR_MEMORY on out-of-memory error.
1598 *********************************************************************/
1599 jb_err client_accept_encoding(struct client_state *csp, char **header)
1601 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1603 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1607 /* Temporarily disable the correct behaviour to
1608 * work around a PHP bug.
1610 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1612 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1613 * if (*header == NULL)
1615 * return JB_ERR_MEMORY;
1626 /*********************************************************************
1628 * Function : client_te
1630 * Description : Rewrite the client's TE header so that
1631 * if doesn't allow compression, if the action applies.
1634 * 1 : csp = Current client state (buffers, headers, etc...)
1635 * 2 : header = On input, pointer to header to modify.
1636 * On output, pointer to the modified header, or NULL
1637 * to remove the header. This function frees the
1638 * original string if necessary.
1640 * Returns : JB_ERR_OK on success, or
1641 * JB_ERR_MEMORY on out-of-memory error.
1643 *********************************************************************/
1644 jb_err client_te(struct client_state *csp, char **header)
1646 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1649 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1655 /*********************************************************************
1657 * Function : client_referrer
1659 * Description : Handle the "referer" config setting properly.
1660 * Called from `sed'.
1663 * 1 : csp = Current client state (buffers, headers, etc...)
1664 * 2 : header = On input, pointer to header to modify.
1665 * On output, pointer to the modified header, or NULL
1666 * to remove the header. This function frees the
1667 * original string if necessary.
1669 * Returns : JB_ERR_OK on success, or
1670 * JB_ERR_MEMORY on out-of-memory error.
1672 *********************************************************************/
1673 jb_err client_referrer(struct client_state *csp, char **header)
1680 #ifdef FEATURE_FORCE_LOAD
1681 /* Since the referrer can include the prefix even
1682 * if the request itself is non-forced, we must
1683 * clean it unconditionally
1685 strclean(*header, FORCE_PREFIX);
1686 #endif /* def FEATURE_FORCE_LOAD */
1689 * Are we sending referer?
1691 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1696 newval = csp->action->string[ACTION_STRING_REFERER];
1698 if ((0 != strcmpic(newval, "conditional-block")))
1702 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1707 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1710 else if (0 == strcmpic(newval, "conditional-block"))
1713 * Block referer if host has changed.
1716 if (NULL == (host = strdup(csp->http->hostport)))
1719 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1720 return JB_ERR_MEMORY;
1722 if (NULL == (referer = strdup(*header)))
1726 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1727 return JB_ERR_MEMORY;
1729 hostlenght = strlen(host);
1730 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1732 /*Shorten referer to make sure the referer is blocked
1733 *if www.example.org/www.example.com-shall-see-the-referer/
1734 *links to www.example.com/
1736 referer[hostlenght+17] = '\0';
1738 if ( 0 == strstr(referer, host)) /*Host has changed*/
1740 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1745 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1751 else if (0 != strcmpic(newval, "forge"))
1754 * We have a specific (fixed) referer we want to send.
1756 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1758 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1760 *header = strdup("Referer: ");
1761 string_append(header, newval);
1762 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1764 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1769 * Forge a referer as http://[hostname:port of REQUEST]/
1770 * to fool stupid checks for in-site links
1773 *header = strdup("Referer: http://");
1774 string_append(header, csp->http->hostport);
1775 string_append(header, "/");
1776 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1778 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1782 /*********************************************************************
1784 * Function : client_accept_language
1786 * Description : Handle the "Accept-Language" config setting properly.
1787 * Called from `sed'.
1790 * 1 : csp = Current client state (buffers, headers, etc...)
1791 * 2 : header = On input, pointer to header to modify.
1792 * On output, pointer to the modified header, or NULL
1793 * to remove the header. This function frees the
1794 * original string if necessary.
1796 * Returns : JB_ERR_OK on success, or
1797 * JB_ERR_MEMORY on out-of-memory error.
1799 *********************************************************************/
1800 jb_err client_accept_language(struct client_state *csp, char **header)
1805 * Are we messing with the Accept-Language?
1807 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1809 /*I don't think so*/
1813 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1815 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1818 * Blocking Accept-Language header
1820 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1827 * Replacing Accept-Language header
1830 *header = strdup("Accept-Language: ");
1831 string_append(header, newval);
1833 if (*header == NULL)
1835 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1839 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1842 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1845 /*********************************************************************
1847 * Function : crunch_client_header
1849 * Description : Crunch client header if it matches a string supplied by the
1850 * user. Called from `sed'.
1853 * 1 : csp = Current client state (buffers, headers, etc...)
1854 * 2 : header = On input, pointer to header to modify.
1855 * On output, pointer to the modified header, or NULL
1856 * to remove the header. This function frees the
1857 * original string if necessary.
1859 * Returns : JB_ERR_OK on success and always succeeds
1861 *********************************************************************/
1862 jb_err crunch_client_header(struct client_state *csp, char **header)
1864 const char *crunch_pattern;
1865 /*Is there a header to crunch*/
1867 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1869 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1871 /*Is the current header the lucky one?*/
1872 if (strstr(*header, crunch_pattern))
1874 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1882 /*********************************************************************
1884 * Function : client_uagent
1886 * Description : Handle the "user-agent" config setting properly
1887 * and remember its original value to enable browser
1888 * bug workarounds. Called from `sed'.
1891 * 1 : csp = Current client state (buffers, headers, etc...)
1892 * 2 : header = On input, pointer to header to modify.
1893 * On output, pointer to the modified header, or NULL
1894 * to remove the header. This function frees the
1895 * original string if necessary.
1897 * Returns : JB_ERR_OK on success, or
1898 * JB_ERR_MEMORY on out-of-memory error.
1900 *********************************************************************/
1901 jb_err client_uagent(struct client_state *csp, char **header)
1905 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1910 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1917 *header = strdup("User-Agent: ");
1918 string_append(header, newval);
1920 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
1922 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1925 /*********************************************************************
1927 * Function : client_ua
1929 * Description : Handle "ua-" headers properly. Called from `sed'.
1932 * 1 : csp = Current client state (buffers, headers, etc...)
1933 * 2 : header = On input, pointer to header to modify.
1934 * On output, pointer to the modified header, or NULL
1935 * to remove the header. This function frees the
1936 * original string if necessary.
1938 * Returns : JB_ERR_OK on success, or
1939 * JB_ERR_MEMORY on out-of-memory error.
1941 *********************************************************************/
1942 jb_err client_ua(struct client_state *csp, char **header)
1944 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1946 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
1954 /*********************************************************************
1956 * Function : client_from
1958 * Description : Handle the "from" config setting properly.
1959 * Called from `sed'.
1962 * 1 : csp = Current client state (buffers, headers, etc...)
1963 * 2 : header = On input, pointer to header to modify.
1964 * On output, pointer to the modified header, or NULL
1965 * to remove the header. This function frees the
1966 * original string if necessary.
1968 * Returns : JB_ERR_OK on success, or
1969 * JB_ERR_MEMORY on out-of-memory error.
1971 *********************************************************************/
1972 jb_err client_from(struct client_state *csp, char **header)
1976 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1983 newval = csp->action->string[ACTION_STRING_FROM];
1986 * Are we blocking the e-mail address?
1988 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1990 log_error(LOG_LEVEL_HEADER, "crunched From!");
1994 log_error(LOG_LEVEL_HEADER, " modified");
1996 *header = strdup("From: ");
1997 string_append(header, newval);
1999 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2003 /*********************************************************************
2005 * Function : client_send_cookie
2007 * Description : Handle the "cookie" header properly. Called from `sed'.
2008 * If cookie is accepted, add it to the cookie_list,
2009 * else we crunch it. Mmmmmmmmmmm ... cookie ......
2012 * 1 : csp = Current client state (buffers, headers, etc...)
2013 * 2 : header = On input, pointer to header to modify.
2014 * On output, pointer to the modified header, or NULL
2015 * to remove the header. This function frees the
2016 * original string if necessary.
2018 * Returns : JB_ERR_OK on success, or
2019 * JB_ERR_MEMORY on out-of-memory error.
2021 *********************************************************************/
2022 jb_err client_send_cookie(struct client_state *csp, char **header)
2024 jb_err result = JB_ERR_OK;
2026 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2028 /* strlen("cookie: ") == 8 */
2029 result = enlist(csp->cookie_list, *header + 8);
2033 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2037 * Always remove the cookie here. The cookie header
2038 * will be sent at the end of the header.
2046 /*********************************************************************
2048 * Function : client_x_forwarded
2050 * Description : Handle the "x-forwarded-for" config setting properly,
2051 * also used in the add_client_headers list. Called from `sed'.
2054 * 1 : csp = Current client state (buffers, headers, etc...)
2055 * 2 : header = On input, pointer to header to modify.
2056 * On output, pointer to the modified header, or NULL
2057 * to remove the header. This function frees the
2058 * original string if necessary.
2060 * Returns : JB_ERR_OK on success, or
2061 * JB_ERR_MEMORY on out-of-memory error.
2063 *********************************************************************/
2064 jb_err client_x_forwarded(struct client_state *csp, char **header)
2066 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2068 /* Save it so we can re-add it later */
2069 freez(csp->x_forwarded);
2070 csp->x_forwarded = *header;
2073 * Always set *header = NULL, since this information
2074 * will be sent at the end of the header.
2081 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2088 /*********************************************************************
2090 * Function : client_max_forwards
2092 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2093 * from the value of the Max-Forwards header field.
2096 * 1 : csp = Current client state (buffers, headers, etc...)
2097 * 2 : header = On input, pointer to header to modify.
2098 * On output, pointer to the modified header, or NULL
2099 * to remove the header. This function frees the
2100 * original string if necessary.
2102 * Returns : JB_ERR_OK on success, or
2103 * JB_ERR_MEMORY on out-of-memory error.
2105 *********************************************************************/
2106 jb_err client_max_forwards(struct client_state *csp, char **header)
2108 unsigned int max_forwards;
2110 if ((0 == strcmpic(csp->http->gpc, "trace"))
2111 || (0 == strcmpic(csp->http->gpc, "options")))
2113 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2115 if (max_forwards-- >= 1)
2117 sprintf(*header, "Max-Forwards: %u", max_forwards);
2118 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2122 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2131 /*********************************************************************
2133 * Function : client_host
2135 * Description : If the request URI did not contain host and
2136 * port information, parse and evaluate the Host
2139 * Also, kill ill-formed HOST: headers as sent by
2140 * Apple's iTunes software when used with a proxy.
2143 * 1 : csp = Current client state (buffers, headers, etc...)
2144 * 2 : header = On input, pointer to header to modify.
2145 * On output, pointer to the modified header, or NULL
2146 * to remove the header. This function frees the
2147 * original string if necessary.
2149 * Returns : JB_ERR_OK on success, or
2150 * JB_ERR_MEMORY on out-of-memory error.
2152 *********************************************************************/
2153 jb_err client_host(struct client_state *csp, char **header)
2158 * If the header field name is all upper-case, chances are that it's
2159 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2160 * not a problem -- they are regenerated later.
2162 if ((*header)[1] == 'O')
2164 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2169 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2170 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2173 if (NULL == (p = strdup((*header)+6)))
2175 return JB_ERR_MEMORY;
2178 if (NULL == (q = strdup(p)))
2181 return JB_ERR_MEMORY;
2184 freez(csp->http->hostport);
2185 csp->http->hostport = p;
2186 freez(csp->http->host);
2187 csp->http->host = q;
2188 q = strchr(csp->http->host, ':');
2191 /* Terminate hostname and evaluate port string */
2193 csp->http->port = atoi(q);
2197 csp->http->port = csp->http->ssl ? 443 : 80;
2200 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2201 csp->http->hostport, csp->http->host, csp->http->port);
2207 /*********************************************************************
2209 * Function : client_if_modified_since
2211 * Description : Remove or modify the If-Modified-Since header.
2214 * 1 : csp = Current client state (buffers, headers, etc...)
2215 * 2 : header = On input, pointer to header to modify.
2216 * On output, pointer to the modified header, or NULL
2217 * to remove the header. This function frees the
2218 * original string if necessary.
2220 * Returns : JB_ERR_OK on success, or
2221 * JB_ERR_MEMORY on out-of-memory error.
2223 *********************************************************************/
2224 jb_err client_if_modified_since(struct client_state *csp, char **header)
2227 struct tm *timeptr = NULL;
2231 long int hours, minutes, seconds;
2235 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2238 * The client got an error message because of a temporary problem,
2239 * the problem is gone and the client now tries to revalidate our
2240 * error message on the real server. The revalidation would always
2241 * end with the transmission of the whole document and there is
2242 * no need to expose the bogus If-Modified-Since header.
2244 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2247 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2249 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2251 if ((0 == strcmpic(newval, "block")))
2253 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2256 else /* add random value */
2258 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2260 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2265 rtime = strtol(newval, &endptr, 0);
2273 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d hou%s)",
2274 *header, rtime, (rtime == 1 || rtime == -1) ? "r": "rs");
2276 rtime = pick_from_range(rtime);
2280 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2284 timeptr = gmtime(&tm);
2285 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2288 *header = strdup("If-Modified-Since: ");
2289 string_append(header, newheader);
2291 if (*header == NULL)
2293 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2294 return JB_ERR_MEMORY;
2297 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2299 hours = rtime / 3600;
2300 minutes = rtime / 60 % 60;
2301 seconds = rtime % 60;
2303 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2304 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2305 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2314 /*********************************************************************
2316 * Function : client_if_none_match
2318 * Description : Remove the If-None-Match header.
2321 * 1 : csp = Current client state (buffers, headers, etc...)
2322 * 2 : header = On input, pointer to header to modify.
2323 * On output, pointer to the modified header, or NULL
2324 * to remove the header. This function frees the
2325 * original string if necessary.
2327 * Returns : JB_ERR_OK on success, or
2328 * JB_ERR_MEMORY on out-of-memory error.
2330 *********************************************************************/
2331 jb_err client_if_none_match(struct client_state *csp, char **header)
2333 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2335 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2342 /*********************************************************************
2344 * Function : client_x_filter
2346 * Description : Disables filtering if the client set "X-Filter: No".
2347 * Called from `sed'.
2350 * 1 : csp = Current client state (buffers, headers, etc...)
2351 * 2 : header = On input, pointer to header to modify.
2352 * On output, pointer to the modified header, or NULL
2353 * to remove the header. This function frees the
2354 * original string if necessary.
2356 * Returns : JB_ERR_OK on success
2358 *********************************************************************/
2359 jb_err client_x_filter(struct client_state *csp, char **header)
2361 if ( 0 == strcmpic(*header, "X-Filter: No"))
2363 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2365 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to disable filtering!");
2369 csp->content_type = CT_TABOO;
2370 log_error(LOG_LEVEL_HEADER, "Disabled filter mode on behalf of the client.");
2372 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2378 /* the following functions add headers directly to the header list */
2380 /*********************************************************************
2382 * Function : client_host_adder
2384 * Description : Adds the Host: header field if it is missing.
2385 * Called from `sed'.
2388 * 1 : csp = Current client state (buffers, headers, etc...)
2390 * Returns : JB_ERR_OK on success, or
2391 * JB_ERR_MEMORY on out-of-memory error.
2393 *********************************************************************/
2394 jb_err client_host_adder(struct client_state *csp)
2399 if ( !csp->http->hostport || !*(csp->http->hostport))
2405 * remove 'user:pass@' from 'proto://user:pass@host'
2407 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2413 p = csp->http->hostport;
2416 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2417 err = enlist_unique_header(csp->headers, "Host", p);
2423 /*********************************************************************
2425 * Function : client_cookie_adder
2427 * Description : Used in the add_client_headers list. Called from `sed'.
2430 * 1 : csp = Current client state (buffers, headers, etc...)
2432 * Returns : JB_ERR_OK on success, or
2433 * JB_ERR_MEMORY on out-of-memory error.
2435 *********************************************************************/
2436 jb_err client_cookie_adder(struct client_state *csp)
2438 struct list_entry *lst;
2440 struct list_entry *list1 = csp->cookie_list->first;
2441 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2442 int first_cookie = 1;
2445 if ((list1 == NULL) && (list2 == NULL))
2451 tmp = strdup("Cookie: ");
2453 for (lst = list1; lst ; lst = lst->next)
2461 string_append(&tmp, "; ");
2463 string_append(&tmp, lst->str);
2466 for (lst = list2; lst ; lst = lst->next)
2474 string_append(&tmp, "; ");
2476 string_join(&tmp, cookie_encode(lst->str));
2481 return JB_ERR_MEMORY;
2484 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2485 err = enlist(csp->headers, tmp);
2491 /*********************************************************************
2493 * Function : client_accept_encoding_adder
2495 * Description : Add an Accept-Encoding header to the client's request
2496 * that disables compression if the action applies, and
2497 * the header is not already there. Called from `sed'.
2498 * Note: For HTTP/1.0, the absence of the header is enough.
2501 * 1 : csp = Current client state (buffers, headers, etc...)
2503 * Returns : JB_ERR_OK on success, or
2504 * JB_ERR_MEMORY on out-of-memory error.
2506 *********************************************************************/
2507 jb_err client_accept_encoding_adder(struct client_state *csp)
2509 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2510 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2512 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2519 /*********************************************************************
2521 * Function : client_xtra_adder
2523 * Description : Used in the add_client_headers list. Called from `sed'.
2526 * 1 : csp = Current client state (buffers, headers, etc...)
2528 * Returns : JB_ERR_OK on success, or
2529 * JB_ERR_MEMORY on out-of-memory error.
2531 *********************************************************************/
2532 jb_err client_xtra_adder(struct client_state *csp)
2534 struct list_entry *lst;
2537 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2538 lst ; lst = lst->next)
2540 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2541 err = enlist(csp->headers, lst->str);
2553 /*********************************************************************
2555 * Function : client_x_forwarded_adder
2557 * Description : Used in the add_client_headers list. Called from `sed'.
2560 * 1 : csp = Current client state (buffers, headers, etc...)
2562 * Returns : JB_ERR_OK on success, or
2563 * JB_ERR_MEMORY on out-of-memory error.
2565 *********************************************************************/
2566 jb_err client_x_forwarded_adder(struct client_state *csp)
2571 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2576 if (csp->x_forwarded)
2578 p = strdup(csp->x_forwarded);
2579 string_append(&p, ", ");
2583 p = strdup("X-Forwarded-For: ");
2585 string_append(&p, csp->ip_addr_str);
2589 return JB_ERR_MEMORY;
2592 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2593 err = enlist(csp->headers, p);
2600 /*********************************************************************
2602 * Function : connection_close_adder
2604 * Description : Adds a "Connection: close" header to csp->headers
2605 * as a temporary fix for the needed but missing HTTP/1.1
2606 * support. Called from `sed'.
2607 * FIXME: This whole function shouldn't be neccessary!
2610 * 1 : csp = Current client state (buffers, headers, etc...)
2612 * Returns : JB_ERR_OK on success, or
2613 * JB_ERR_MEMORY on out-of-memory error.
2615 *********************************************************************/
2616 jb_err connection_close_adder(struct client_state *csp)
2618 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2619 return enlist(csp->headers, "Connection: close");
2623 /*********************************************************************
2625 * Function : server_http
2627 * Description : - Save the HTTP Status into csp->http->status
2628 * - Set CT_TABOO to prevent filtering if the answer
2629 * is a partial range (HTTP status 206)
2630 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2634 * 1 : csp = Current client state (buffers, headers, etc...)
2635 * 2 : header = On input, pointer to header to modify.
2636 * On output, pointer to the modified header, or NULL
2637 * to remove the header. This function frees the
2638 * original string if necessary.
2640 * Returns : JB_ERR_OK on success, or
2641 * JB_ERR_MEMORY on out-of-memory error.
2643 *********************************************************************/
2644 jb_err server_http(struct client_state *csp, char **header)
2646 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2647 if (csp->http->status == 206)
2649 csp->content_type = CT_TABOO;
2652 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2655 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2662 /*********************************************************************
2664 * Function : server_set_cookie
2666 * Description : Handle the server "cookie" header properly.
2667 * Log cookie to the jar file. Then "crunch" it,
2668 * or accept it. Called from `sed'.
2671 * 1 : csp = Current client state (buffers, headers, etc...)
2672 * 2 : header = On input, pointer to header to modify.
2673 * On output, pointer to the modified header, or NULL
2674 * to remove the header. This function frees the
2675 * original string if necessary.
2677 * Returns : JB_ERR_OK on success, or
2678 * JB_ERR_MEMORY on out-of-memory error.
2680 *********************************************************************/
2681 jb_err server_set_cookie(struct client_state *csp, char **header)
2683 #ifdef FEATURE_COOKIE_JAR
2684 if (csp->config->jar)
2687 * Write timestamp into outbuf.
2689 * Complex because not all OSs have tm_gmtoff or
2690 * the %z field in strftime()
2692 char tempbuf[ BUFFER_SIZE ];
2696 #ifdef HAVE_LOCALTIME_R
2697 tm_now = *localtime_r(&now, &tm_now);
2699 pthread_mutex_lock(&localtime_mutex);
2700 tm_now = *localtime (&now);
2701 pthread_mutex_unlock(&localtime_mutex);
2703 tm_now = *localtime (&now);
2705 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2707 /* strlen("set-cookie: ") = 12 */
2708 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2710 #endif /* def FEATURE_COOKIE_JAR */
2712 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2714 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2715 return crumble(csp, header);
2717 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2719 /* Flag whether or not to log a message */
2722 /* A variable to store the tag we're working on */
2725 /* Skip "Set-Cookie:" (11 characters) in header */
2726 cur_tag = *header + 11;
2728 /* skip whitespace between "Set-Cookie:" and value */
2729 while (*cur_tag && ijb_isspace(*cur_tag))
2734 /* Loop through each tag in the cookie */
2738 char *next_tag = strchr(cur_tag, ';');
2739 if (next_tag != NULL)
2741 /* Skip the ';' character itself */
2744 /* skip whitespace ";" and start of tag */
2745 while (*next_tag && ijb_isspace(*next_tag))
2752 /* "Next tag" is the end of the string */
2753 next_tag = cur_tag + strlen(cur_tag);
2756 /* Is this the "Expires" tag? */
2757 if (strncmpic(cur_tag, "expires=", 8) == 0)
2759 /* Delete the tag by copying the rest of the string over it.
2760 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2761 * since the behaviour of strcpy is undefined for overlapping
2764 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2766 /* That changed the header, need to issue a log message */
2769 /* Note that the next tag has now been moved to *cur_tag,
2770 * so we do not need to update the cur_tag pointer.
2775 /* Move on to next cookie tag */
2782 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2790 #ifdef FEATURE_FORCE_LOAD
2791 /*********************************************************************
2793 * Function : strclean
2795 * Description : In-Situ-Eliminate all occurances of substring in
2799 * 1 : string = string to clean
2800 * 2 : substring = substring to eliminate
2802 * Returns : Number of eliminations
2804 *********************************************************************/
2805 int strclean(const char *string, const char *substring)
2807 int hits = 0, len = strlen(substring);
2810 while((pos = strstr(string, substring)) != NULL)
2817 while (*p++ != '\0');
2824 #endif /* def FEATURE_FORCE_LOAD */
2826 /*********************************************************************
2828 * Function : parse_header_time
2830 * Description : Transforms time inside a HTTP header into
2831 * the usual time format.
2834 * 1 : header = header to parse
2835 * 2 : tm = storage for the resulting time in seconds
2837 * Returns : Time struct containing the header time, or
2838 * NULL in case of a parsing problem.
2840 *********************************************************************/
2841 struct tm *parse_header_time(char *header, time_t *tm) {
2844 struct tm * timeptr;
2847 timeptr = localtime(tm);
2848 /* Skipping header name */
2849 timestring = strstr(header, ": ");
2850 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", timeptr) == NULL)
2856 *tm = timegm(timeptr);