1 const char parsers_rcs[] = "$Id: parsers.c,v 1.63 2006/08/14 13:18:08 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.63 2006/08/14 13:18:08 david__schmidt
44 * OS/2 compilation compatibility fixups
46 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
47 * Changed include from strptime.c to strptime.h
49 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
50 * Split filter-headers{} into filter-client-headers{}
51 * and filter-server-headers{}.
52 * Added parse_header_time() to share some code.
53 * Replaced timegm() with mktime().
55 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
56 * Windows service integration
58 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
59 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
61 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
62 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
63 * with what was really the latest development (the v_3_0_branch branch)
65 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
66 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
68 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
69 * Add the ability to check jpeg images for invalid
70 * lengths of comment blocks. Defensive strategy
71 * against the exploit:
72 * Microsoft Security Bulletin MS04-028
73 * Buffer Overrun in JPEG Processing (GDI+) Could
74 * Allow Code Execution (833987)
75 * Enabled with +inspect-jpegs in actions files.
77 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
78 * Excluded text/plain objects from filtering. This fixes a
79 * couple of client-crashing, download corruption and
80 * Privoxy performance issues, whose root cause lies in
81 * web servers labelling content of unknown type as text/plain.
83 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
84 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
86 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
87 * Completing the previous change
89 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
90 * Added temporary workaround for bug in PHP < 4.2.3
92 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
93 * 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.
95 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
96 * Fix typo: supressed -> suppressed
98 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
99 * Improved cookie logging
101 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
102 * Added basic support for OPTIONS and TRACE HTTP methods:
103 * - New parser function client_max_forwards which decrements
104 * the Max-Forwards HTTP header field of OPTIONS and TRACE
105 * requests by one before forwarding
106 * - New parser function client_host which extracts the host
107 * and port information from the HTTP header field if the
108 * request URI was not absolute
109 * - Don't crumble and re-add the Host: header, but only generate
110 * and append if missing
112 * Revision 1.56 2002/05/12 15:34:22 jongfoster
113 * Fixing typo in a comment
115 * Revision 1.55 2002/05/08 16:01:07 oes
116 * Optimized add_to_iob:
117 * - Use realloc instead of malloc(), memcpy(), free()
118 * - Expand to powers of two if possible, to get
119 * O(log n) reallocs instead of O(n).
120 * - Moved check for buffer limit here from chat
121 * - Report failure via returncode
123 * Revision 1.54 2002/04/02 15:03:16 oes
124 * Tiny code cosmetics
126 * Revision 1.53 2002/03/26 22:29:55 swa
127 * we have a new homepage!
129 * Revision 1.52 2002/03/24 13:25:43 swa
130 * name change related issues
132 * Revision 1.51 2002/03/13 00:27:05 jongfoster
135 * Revision 1.50 2002/03/12 01:45:35 oes
136 * More verbose logging
138 * Revision 1.49 2002/03/09 20:03:52 jongfoster
139 * - Making various functions return int rather than size_t.
140 * (Undoing a recent change). Since size_t is unsigned on
141 * Windows, functions like read_socket that return -1 on
142 * error cannot return a size_t.
144 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
145 * crashes, and also frequently caused JB to jump to 100%
146 * CPU and stay there. (Because it thought it had just
147 * read ((unsigned)-1) == 4Gb of data...)
149 * - The signature of write_socket has changed, it now simply
150 * returns success=0/failure=nonzero.
152 * - Trying to get rid of a few warnings --with-debug on
153 * Windows, I've introduced a new type "jb_socket". This is
154 * used for the socket file descriptors. On Windows, this
155 * is SOCKET (a typedef for unsigned). Everywhere else, it's
156 * an int. The error value can't be -1 any more, so it's
157 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
158 * Windows it maps to the #define INVALID_SOCKET.)
160 * - The signature of bind_port has changed.
162 * Revision 1.48 2002/03/07 03:46:53 oes
163 * Fixed compiler warnings etc
165 * Revision 1.47 2002/02/20 23:15:13 jongfoster
166 * Parsing functions now handle out-of-memory gracefully by returning
169 * Revision 1.46 2002/01/17 21:03:47 jongfoster
170 * Moving all our URL and URL pattern parsing code to urlmatch.c.
172 * Revision 1.45 2002/01/09 14:33:03 oes
173 * Added support for localtime_r.
175 * Revision 1.44 2001/12/14 01:22:54 steudten
176 * Remove 'user:pass@' from 'proto://user:pass@host' for the
177 * new added header 'Host: ..'. (See Req ID 491818)
179 * Revision 1.43 2001/11/23 00:26:38 jongfoster
180 * Fixing two really stupid errors in my previous commit
182 * Revision 1.42 2001/11/22 21:59:30 jongfoster
183 * Adding code to handle +no-cookies-keep
185 * Revision 1.41 2001/11/05 23:43:05 steudten
186 * Add time+date to log files.
188 * Revision 1.40 2001/10/26 20:13:09 jongfoster
189 * ctype.h is needed in Windows, too.
191 * Revision 1.39 2001/10/26 17:40:04 oes
192 * Introduced get_header_value()
193 * Removed http->user_agent, csp->referrer and csp->accept_types
194 * Removed client_accept()
196 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
197 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
198 * threads to call select() simultaneously. So, it's time to do a real, live,
199 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
200 * (native). Both versions will work, but using __OS2__ offers multi-threading.
202 * Revision 1.37 2001/10/23 21:36:02 jongfoster
203 * Documenting sed()'s error behaviou (doc change only)
205 * Revision 1.36 2001/10/13 12:51:51 joergs
206 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
207 * force-load), instead crumble Host: and add it (again) in client_host_adder
208 * (in case we get a HTTP/1.0 request without Host: header and forward it to
209 * a HTTP/1.1 server/proxy).
211 * Revision 1.35 2001/10/09 22:39:21 jongfoster
212 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
215 * Revision 1.34 2001/10/07 18:50:55 oes
216 * Added server_content_encoding, renamed server_transfer_encoding
218 * Revision 1.33 2001/10/07 18:04:49 oes
219 * Changed server_http11 to server_http and its pattern to "HTTP".
220 * Additional functionality: it now saves the HTTP status into
221 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
223 * Revision 1.32 2001/10/07 15:43:28 oes
224 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
225 * client_te and client_accept_encoding_adder, triggered by the new
226 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
227 * changed to allow only identity and chunked, and the TE header is
228 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
230 * parse_http_request no longer does anything than parsing. The rewriting
231 * of http->cmd and version mangling are gone. It now also recognizes
232 * the put and delete methods and saves the url in http->url. Removed
235 * renamed content_type and content_length to have the server_ prefix
237 * server_content_type now only works if csp->content_type != CT_TABOO
239 * added server_transfer_encoding, which
240 * - Sets CT_TABOO to prohibit filtering if encoding compresses
241 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
242 * - Change from "chunked" to "identity" if body was chunked
243 * but has been de-chunked for filtering.
245 * added server_content_md5 which crunches any Content-MD5 headers
246 * if the body was modified.
248 * made server_http11 conditional on +downgrade action
250 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
252 * Revision 1.31 2001/10/05 14:25:02 oes
253 * Crumble Keep-Alive from Server
255 * Revision 1.30 2001/09/29 12:56:03 joergs
256 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
258 * Revision 1.29 2001/09/24 21:09:24 jongfoster
259 * Fixing 2 memory leaks that Guy spotted, where the paramater to
260 * enlist() was not being free()d.
262 * Revision 1.28 2001/09/22 16:32:28 jongfoster
263 * Removing unused #includes.
265 * Revision 1.27 2001/09/20 15:45:25 steudten
267 * add casting from size_t to int for printf()
268 * remove local variable shadow s2
270 * Revision 1.26 2001/09/16 17:05:14 jongfoster
271 * Removing unused #include showarg.h
273 * Revision 1.25 2001/09/16 13:21:27 jongfoster
274 * Changes to use new list functions.
276 * Revision 1.24 2001/09/13 23:05:50 jongfoster
277 * Changing the string paramater to the header parsers a "const".
279 * Revision 1.23 2001/09/12 18:08:19 steudten
281 * In parse_http_request() header rewriting miss the host value, so
282 * from http://www.mydomain.com the result was just " / " not
283 * http://www.mydomain.com/ in case we forward.
285 * Revision 1.22 2001/09/10 10:58:53 oes
286 * Silenced compiler warnings
288 * Revision 1.21 2001/07/31 14:46:00 oes
289 * - Persistant connections now suppressed
290 * - sed() no longer appends empty header to csp->headers
292 * Revision 1.20 2001/07/30 22:08:36 jongfoster
293 * Tidying up #defines:
294 * - All feature #defines are now of the form FEATURE_xxx
295 * - Permanently turned off WIN_GUI_EDIT
296 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
298 * Revision 1.19 2001/07/25 17:21:54 oes
299 * client_uagent now saves copy of User-Agent: header value
301 * Revision 1.18 2001/07/13 14:02:46 oes
302 * - Included fix to repair broken HTTP requests that
303 * don't contain a path, not even '/'.
304 * - Removed all #ifdef PCRS
305 * - content_type now always inspected and classified as
306 * text, gif or other.
307 * - formatting / comments
309 * Revision 1.17 2001/06/29 21:45:41 oes
310 * Indentation, CRLF->LF, Tab-> Space
312 * Revision 1.16 2001/06/29 13:32:42 oes
314 * - Adapted free_http_request
315 * - Removed logentry from cancelled commit
317 * Revision 1.15 2001/06/03 19:12:38 oes
318 * deleted const struct interceptors
320 * Revision 1.14 2001/06/01 18:49:17 jongfoster
321 * Replaced "list_share" with "list" - the tiny memory gain was not
322 * worth the extra complexity.
324 * Revision 1.13 2001/05/31 21:30:33 jongfoster
325 * Removed list code - it's now in list.[ch]
326 * Renamed "permission" to "action", and changed many features
327 * to use the actions file rather than the global config.
329 * Revision 1.12 2001/05/31 17:33:13 oes
333 * Revision 1.11 2001/05/29 20:11:19 joergs
334 * '/ * inside comment' warning removed.
336 * Revision 1.10 2001/05/29 09:50:24 jongfoster
337 * Unified blocklist/imagelist/permissionslist.
338 * File format is still under discussion, but the internal changes
341 * Also modified interceptor behaviour:
342 * - We now intercept all URLs beginning with one of the following
343 * prefixes (and *only* these prefixes):
345 * * http://ijbswa.sf.net/config/
346 * * http://ijbswa.sourceforge.net/config/
347 * - New interceptors "home page" - go to http://i.j.b/ to see it.
348 * - Internal changes so that intercepted and fast redirect pages
349 * are not replaced with an image.
350 * - Interceptors now have the option to send a binary page direct
351 * to the client. (i.e. ijb-send-banner uses this)
352 * - Implemented show-url-info interceptor. (Which is why I needed
353 * the above interceptors changes - a typical URL is
354 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
355 * The previous mechanism would not have intercepted that, and
356 * if it had been intercepted then it then it would have replaced
359 * Revision 1.9 2001/05/28 17:26:33 jongfoster
360 * Fixing segfault if last header was crunched.
361 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
362 * can use the cross-platform sprintf() instead.)
364 * Revision 1.8 2001/05/27 22:17:04 oes
366 * - re_process_buffer no longer writes the modified buffer
367 * to the client, which was very ugly. It now returns the
368 * buffer, which it is then written by chat.
370 * - content_length now adjusts the Content-Length: header
371 * for modified documents rather than crunch()ing it.
372 * (Length info in csp->content_length, which is 0 for
373 * unmodified documents)
375 * - For this to work, sed() is called twice when filtering.
377 * Revision 1.7 2001/05/27 13:19:06 oes
378 * Patched Joergs solution for the content-length in.
380 * Revision 1.6 2001/05/26 13:39:32 jongfoster
381 * Only crunches Content-Length header if applying RE filtering.
382 * Without this fix, Microsoft Windows Update wouldn't work.
384 * Revision 1.5 2001/05/26 00:28:36 jongfoster
385 * Automatic reloading of config file.
386 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
387 * Most of the global variables have been moved to a new
388 * struct configuration_spec, accessed through csp->config->globalname
389 * Most of the globals remaining are used by the Win32 GUI.
391 * Revision 1.4 2001/05/22 18:46:04 oes
393 * - Enabled filtering banners by size rather than URL
394 * by adding patterns that replace all standard banner
395 * sizes with the "Junkbuster" gif to the re_filterfile
397 * - Enabled filtering WebBugs by providing a pattern
398 * which kills all 1x1 images
400 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
401 * which is selected by the (nonstandard and therefore
402 * capital) letter 'U' in the option string.
403 * It causes the quantifiers to be ungreedy by default.
404 * Appending a ? turns back to greedy (!).
406 * - Added a new interceptor ijb-send-banner, which
407 * sends back the "Junkbuster" gif. Without imagelist or
408 * MSIE detection support, or if tinygif = 1, or the
409 * URL isn't recognized as an imageurl, a lame HTML
410 * explanation is sent instead.
412 * - Added new feature, which permits blocking remote
413 * script redirects and firing back a local redirect
415 * The feature is conditionally compiled, i.e. it
416 * can be disabled with --disable-fast-redirects,
417 * plus it must be activated by a "fast-redirects"
418 * line in the config file, has its own log level
419 * and of course wants to be displayed by show-proxy-args
420 * Note: Boy, all the #ifdefs in 1001 locations and
421 * all the fumbling with configure.in and acconfig.h
422 * were *way* more work than the feature itself :-(
424 * - Because a generic redirect template was needed for
425 * this, tinygif = 3 now uses the same.
427 * - Moved GIFs, and other static HTTP response templates
432 * - Removed some >400 CRs again (Jon, you really worked
435 * Revision 1.3 2001/05/20 01:21:20 jongfoster
436 * Version 2.9.4 checkin.
437 * - Merged popupfile and cookiefile, and added control over PCRS
438 * filtering, in new "permissionsfile".
439 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
440 * file error you now get a message box (in the Win32 GUI) rather
441 * than the program exiting with no explanation.
442 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
444 * - Removed tabs from "config"
445 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
446 * - Bumped up version number.
448 * Revision 1.2 2001/05/17 23:02:36 oes
449 * - Made referrer option accept 'L' as a substitute for '§'
451 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
452 * Initial import of version 2.9.3 source tree
455 *********************************************************************/
462 #include <sys/types.h>
471 #if !defined(_WIN32) && !defined(__OS2__)
480 /* jcc.h is for mutex semapores only */
481 #endif /* def OSX_DARWIN */
487 #include "jbsockets.h"
488 #include "miscutil.h"
491 #ifndef HAVE_STRPTIME
492 #include "strptime.h"
495 const char parsers_h_rcs[] = PARSERS_H_VERSION;
497 /* Fix a problem with Solaris. There should be no effect on other
499 * Solaris's isspace() is a macro which uses it's argument directly
500 * as an array index. Therefore we need to make sure that high-bit
501 * characters generate +ve values, and ideally we also want to make
502 * the argument match the declared parameter type of "int".
504 * Why did they write a character function that can't take a simple
505 * "char" argument? Doh!
507 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
508 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
511 const struct parsers client_patterns[] = {
512 { "referer:", 8, client_referrer },
513 { "user-agent:", 11, client_uagent },
514 { "ua-", 3, client_ua },
515 { "from:", 5, client_from },
516 { "cookie:", 7, client_send_cookie },
517 { "x-forwarded-for:", 16, client_x_forwarded },
518 { "Accept-Encoding:", 16, client_accept_encoding },
519 { "TE:", 3, client_te },
520 { "Host:", 5, client_host },
521 { "if-modified-since:", 18, client_if_modified_since },
522 { "Keep-Alive:", 11, crumble },
523 { "connection:", 11, crumble },
524 { "proxy-connection:", 17, crumble },
525 { "max-forwards:", 13, client_max_forwards },
526 { "Accept-Language:", 16, client_accept_language },
527 { "if-none-match:", 14, client_if_none_match },
528 { "X-Filter:", 9, client_x_filter },
529 { "*", 0, crunch_client_header },
530 { "*", 0, filter_client_header },
534 const struct parsers server_patterns[] = {
535 { "HTTP", 4, server_http },
536 { "set-cookie:", 11, server_set_cookie },
537 { "connection:", 11, crumble },
538 { "Content-Type:", 13, server_content_type },
539 { "Content-Length:", 15, server_content_length },
540 { "Content-MD5:", 12, server_content_md5 },
541 { "Content-Encoding:", 17, server_content_encoding },
542 { "Transfer-Encoding:", 18, server_transfer_coding },
543 { "Keep-Alive:", 11, crumble },
544 { "content-disposition:", 20, server_content_disposition },
545 { "Last-Modified:", 14, server_last_modified },
546 { "*", 0, crunch_server_header },
547 { "*", 0, filter_server_header },
551 const struct parsers server_patterns_light[] = {
552 { "Content-Length:", 15, server_content_length },
553 { "Transfer-Encoding:", 18, server_transfer_coding },
557 const add_header_func_ptr add_client_headers[] = {
560 client_x_forwarded_adder,
562 /* Temporarily disabled: client_accept_encoding_adder, */
563 connection_close_adder,
568 const add_header_func_ptr add_server_headers[] = {
569 connection_close_adder,
573 /*********************************************************************
575 * Function : flush_socket
577 * Description : Write any pending "buffered" content.
580 * 1 : fd = file descriptor of the socket to read
581 * 2 : csp = Current client state (buffers, headers, etc...)
583 * Returns : On success, the number of bytes written are returned (zero
584 * indicates nothing was written). On error, -1 is returned,
585 * and errno is set appropriately. If count is zero and the
586 * file descriptor refers to a regular file, 0 will be
587 * returned without causing any other effect. For a special
588 * file, the results are not portable.
590 *********************************************************************/
591 int flush_socket(jb_socket fd, struct client_state *csp)
593 struct iob *iob = csp->iob;
594 int len = iob->eod - iob->cur;
601 if (write_socket(fd, iob->cur, (size_t)len))
605 iob->eod = iob->cur = iob->buf;
611 /*********************************************************************
613 * Function : add_to_iob
615 * Description : Add content to the buffered page, expanding the
616 * buffer if necessary.
619 * 1 : csp = Current client state (buffers, headers, etc...)
620 * 2 : buf = holds the content to be added to the page
621 * 3 : n = number of bytes to be added
623 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
624 * or buffer limit reached.
626 *********************************************************************/
627 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
629 struct iob *iob = csp->iob;
630 size_t used, offset, need, want;
633 if (n <= 0) return JB_ERR_OK;
635 used = iob->eod - iob->buf;
636 offset = iob->cur - iob->buf;
640 * If the buffer can't hold the new data, extend it first.
641 * Use the next power of two if possible, else use the actual need.
643 if (need > csp->config->buffer_limit)
645 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
646 return JB_ERR_MEMORY;
649 if (need > iob->size)
651 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
653 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
657 else if (NULL != (p = (char *)realloc(iob->buf, need)))
663 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
664 return JB_ERR_MEMORY;
667 /* Update the iob pointers */
668 iob->cur = p + offset;
673 /* copy the new data into the iob buffer */
674 memcpy(iob->eod, buf, (size_t)n);
676 /* point to the end of the data */
679 /* null terminate == cheap insurance */
687 /*********************************************************************
689 * Function : get_header
691 * Description : This (odd) routine will parse the csp->iob
694 * 1 : csp = Current client state (buffers, headers, etc...)
696 * Returns : Any one of the following:
698 * 1) a pointer to a dynamically allocated string that contains a header line
699 * 2) NULL indicating that the end of the header was reached
700 * 3) "" indicating that the end of the iob was reached before finding
701 * a complete header line.
703 *********************************************************************/
704 char *get_header(struct client_state *csp)
710 if ((iob->cur == NULL)
711 || ((p = strchr(iob->cur, '\n')) == NULL))
713 return(""); /* couldn't find a complete header */
718 ret = strdup(iob->cur);
721 /* FIXME No way to handle error properly */
722 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
727 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
729 /* is this a blank line (i.e. the end of the header) ? */
741 /*********************************************************************
743 * Function : get_header_value
745 * Description : Get the value of a given header from a chained list
746 * of header lines or return NULL if no such header is
747 * present in the list.
750 * 1 : header_list = pointer to list
751 * 2 : header_name = string with name of header to look for.
752 * Trailing colon required, capitalization
755 * Returns : NULL if not found, else value of header
757 *********************************************************************/
758 char *get_header_value(const struct list *header_list, const char *header_name)
760 struct list_entry *cur_entry;
766 length = strlen(header_name);
768 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
772 if (!strncmpic(cur_entry->str, header_name, length))
775 * Found: return pointer to start of value
777 ret = (char *) (cur_entry->str + length);
778 while (*ret && ijb_isspace(*ret)) ret++;
791 /*********************************************************************
795 * Description : add, delete or modify lines in the HTTP header streams.
796 * On entry, it receives a linked list of headers space
797 * that was allocated dynamically (both the list nodes
798 * and the header contents).
800 * As a side effect it frees the space used by the original
804 * 1 : pats = list of patterns to match against headers
805 * 2 : more_headers = list of functions to add more
806 * headers (client or server)
807 * 3 : csp = Current client state (buffers, headers, etc...)
809 * Returns : Single pointer to a fully formed header, or NULL
810 * on out-of-memory error.
812 *********************************************************************/
813 char *sed(const struct parsers pats[],
814 const add_header_func_ptr more_headers[],
815 struct client_state *csp)
817 struct list_entry *p;
818 const struct parsers *v;
819 const add_header_func_ptr *f;
820 jb_err err = JB_ERR_OK;
824 * If filtering is enabled, sed is run twice,
825 * but most of the work needs to be done only once.
827 first_run = (more_headers != NULL ) ? 1 : 0;
829 if (first_run) /* Parse and print */
831 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
833 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
835 /* Header crunch()ed in previous run? -> ignore */
836 if (p->str == NULL) continue;
838 if (v == pats) log_error(LOG_LEVEL_HEADER, "scan: %s", p->str);
840 /* Does the current parser handle this header? */
841 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
843 err = v->parser(csp, (char **)&(p->str));
847 /* place any additional headers on the csp->headers list */
848 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
853 else /* Parse only */
856 * The second run is only needed if the body was modified
857 * and the content-lenght has changed.
859 if (strncmpic(csp->http->cmd, "HEAD", 4))
861 /*XXX: Code duplication*/
862 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
864 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
866 /* Header crunch()ed in previous run? -> ignore */
867 if (p->str == NULL) continue;
869 /* Does the current parser handle this header? */
870 if (strncmpic(p->str, v->str, v->len) == 0)
872 err = v->parser(csp, (char **)&(p->str));
879 if (err != JB_ERR_OK)
884 return list_to_text(csp->headers);
888 /* here begins the family of parser functions that reformat header lines */
890 /*********************************************************************
892 * Function : filter_server_header
894 * Description : Checks if server header filtering is enabled.
895 * If it is, filter_header is called to do the work.
898 * 1 : csp = Current client state (buffers, headers, etc...)
899 * 2 : header = On input, pointer to header to modify.
900 * On output, pointer to the modified header, or NULL
901 * to remove the header. This function frees the
902 * original string if necessary.
904 * Returns : JB_ERR_OK on success and always succeeds
906 *********************************************************************/
907 jb_err filter_server_header(struct client_state *csp, char **header)
909 if (csp->action->flags & ACTION_FILTER_SERVER_HEADERS)
911 filter_header(csp, header);
916 /*********************************************************************
918 * Function : filter_client_header
920 * Description : Checks if client header filtering is enabled.
921 * If it is, filter_header is called to do the work.
924 * 1 : csp = Current client state (buffers, headers, etc...)
925 * 2 : header = On input, pointer to header to modify.
926 * On output, pointer to the modified header, or NULL
927 * to remove the header. This function frees the
928 * original string if necessary.
930 * Returns : JB_ERR_OK on success and always succeeds
932 *********************************************************************/
933 jb_err filter_client_header(struct client_state *csp, char **header)
935 if (csp->action->flags & ACTION_FILTER_CLIENT_HEADERS)
937 filter_header(csp, header);
942 /*********************************************************************
944 * Function : filter_header
946 * Description : Executes all text substitutions from all applying
947 * +filter actions on the header.
948 * Most of the code was copied from pcrs_filter_response,
949 * including the rather short variable names
952 * 1 : csp = Current client state (buffers, headers, etc...)
953 * 2 : header = On input, pointer to header to modify.
954 * On output, pointer to the modified header, or NULL
955 * to remove the header. This function frees the
956 * original string if necessary.
958 * Returns : JB_ERR_OK on success and always succeeds
960 *********************************************************************/
961 jb_err filter_header(struct client_state *csp, char **header)
965 size_t size = strlen(*header);
967 char *newheader = NULL;
970 struct file_list *fl;
971 struct re_filterfile_spec *b;
972 struct list_entry *filtername;
974 int i, found_filters = 0;
976 log_error(LOG_LEVEL_RE_FILTER, "Entered filter_headers");
978 * Need to check the set of re_filterfiles...
980 for (i = 0; i < MAX_AF_FILES; i++)
993 if (0 == found_filters)
995 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
999 for (i = 0; i < MAX_AF_FILES; i++)
1002 if ((NULL == fl) || (NULL == fl->f))
1005 * For all applying +filter actions, look if a filter by that
1006 * name exists and if yes, execute its pcrs_joblist on the
1009 for (b = fl->f; b; b = b->next)
1011 for (filtername = csp->action->multi[ACTION_MULTI_FILTER]->first;
1012 filtername ; filtername = filtername->next)
1014 if (strcmp(b->name, filtername->str) == 0)
1016 int current_hits = 0;
1018 if ( NULL == b->joblist )
1020 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1024 log_error(LOG_LEVEL_RE_FILTER, "re_filtering %s (size %d) with filter %s...",
1025 *header, size, b->name);
1027 /* Apply all jobs from the joblist */
1028 for (job = b->joblist; NULL != job; job = job->next)
1030 matches = pcrs_execute(job, *header, size, &newheader, &size);
1033 current_hits += matches;
1034 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1036 *header = newheader;
1038 else if ( 0 == matches )
1040 /* Filter doesn't change header */
1046 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1047 *header, b->name, pcrs_strerror(matches));
1048 if( newheader != NULL)
1050 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1055 log_error(LOG_LEVEL_RE_FILTER, " ...produced %d hits (new size %d).", current_hits, size);
1056 hits += current_hits;
1064 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1067 log_error(LOG_LEVEL_RE_FILTER, "Leaving filter headers");
1073 /*********************************************************************
1075 * Function : crumble
1077 * Description : This is called if a header matches a pattern to "crunch"
1080 * 1 : csp = Current client state (buffers, headers, etc...)
1081 * 2 : header = On input, pointer to header to modify.
1082 * On output, pointer to the modified header, or NULL
1083 * to remove the header. This function frees the
1084 * original string if necessary.
1086 * Returns : JB_ERR_OK on success, or
1087 * JB_ERR_MEMORY on out-of-memory error.
1089 *********************************************************************/
1090 jb_err crumble(struct client_state *csp, char **header)
1092 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
1097 /*********************************************************************
1099 * Function : crunch_server_header
1101 * Description : Crunch server header if it matches a string supplied by the
1102 * user. Called from `sed'.
1105 * 1 : csp = Current client state (buffers, headers, etc...)
1106 * 2 : header = On input, pointer to header to modify.
1107 * On output, pointer to the modified header, or NULL
1108 * to remove the header. This function frees the
1109 * original string if necessary.
1111 * Returns : JB_ERR_OK on success and always succeeds
1113 *********************************************************************/
1114 jb_err crunch_server_header(struct client_state *csp, char **header)
1116 const char *crunch_pattern;
1117 /*Is there a header to crunch*/
1119 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
1121 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
1123 /*Is the current header the lucky one?*/
1124 if (strstr(*header, crunch_pattern))
1126 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
1133 /*********************************************************************
1135 * Function : server_content_type
1137 * Description : Set the content-type for filterable types (text/.*,
1138 * javascript and image/gif) unless filtering has been
1139 * forbidden (CT_TABOO) while parsing earlier headers.
1140 * NOTE: Since text/plain is commonly used by web servers
1141 * for files whose correct type is unknown, we don't
1142 * set CT_TEXT for it.
1145 * 1 : csp = Current client state (buffers, headers, etc...)
1146 * 2 : header = On input, pointer to header to modify.
1147 * On output, pointer to the modified header, or NULL
1148 * to remove the header. This function frees the
1149 * original string if necessary.
1151 * Returns : JB_ERR_OK on success, or
1152 * JB_ERR_MEMORY on out-of-memory error.
1154 *********************************************************************/
1155 jb_err server_content_type(struct client_state *csp, char **header)
1159 newval = csp->action->string[ACTION_STRING_CONTENT_TYPE];
1161 if (csp->content_type != CT_TABOO)
1163 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
1164 || strstr(*header, "xml")
1165 || strstr(*header, "application/x-javascript"))
1166 csp->content_type = CT_TEXT;
1167 else if (strstr(*header, " image/gif"))
1168 csp->content_type = CT_GIF;
1169 else if (strstr(*header, " image/jpeg"))
1170 csp->content_type = CT_JPEG;
1172 csp->content_type = 0;
1175 * Are we enabling text mode by force?
1177 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
1180 * Do we really have to?
1182 if (csp->content_type == CT_TEXT)
1184 log_error(LOG_LEVEL_HEADER, "Text mode is already enabled.");
1188 csp->content_type = CT_TEXT;
1189 log_error(LOG_LEVEL_HEADER, "Text mode enabled by force. Take cover!");
1193 * Are we messing with the content type?
1195 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
1198 * Make sure the user doesn't accidently
1199 * change the content type of binary documents.
1201 if (csp->content_type == CT_TEXT)
1204 *header = strdup("Content-Type: ");
1205 string_append(header, newval);
1209 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Conten-Type crunched without replacement!");
1210 return JB_ERR_MEMORY;
1212 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
1216 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
1217 "Enable force-text-mode if you know what you're doing.", *header);
1224 /*********************************************************************
1226 * Function : server_transfer_coding
1228 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
1229 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
1230 * - Change from "chunked" to "identity" if body was chunked
1231 * but has been de-chunked for filtering.
1234 * 1 : csp = Current client state (buffers, headers, etc...)
1235 * 2 : header = On input, pointer to header to modify.
1236 * On output, pointer to the modified header, or NULL
1237 * to remove the header. This function frees the
1238 * original string if necessary.
1240 * Returns : JB_ERR_OK on success, or
1241 * JB_ERR_MEMORY on out-of-memory error.
1243 *********************************************************************/
1244 jb_err server_transfer_coding(struct client_state *csp, char **header)
1247 * Turn off pcrs and gif filtering if body compressed
1249 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1251 csp->content_type = CT_TABOO;
1255 * Raise flag if body chunked
1257 if (strstr(*header, "chunked"))
1259 csp->flags |= CSP_FLAG_CHUNKED;
1262 * If the body was modified, it has been
1263 * de-chunked first, so adjust the header:
1265 if (csp->flags & CSP_FLAG_MODIFIED)
1268 *header = strdup("Transfer-Encoding: identity");
1269 log_error(LOG_LEVEL_HEADER, "Set: %s", *header);
1270 return (header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1278 /*********************************************************************
1280 * Function : server_content_encoding
1282 * Description : Prohibit filtering (CT_TABOO) if content encoding compresses
1285 * 1 : csp = Current client state (buffers, headers, etc...)
1286 * 2 : header = On input, pointer to header to modify.
1287 * On output, pointer to the modified header, or NULL
1288 * to remove the header. This function frees the
1289 * original string if necessary.
1291 * Returns : JB_ERR_OK on success, or
1292 * JB_ERR_MEMORY on out-of-memory error.
1294 *********************************************************************/
1295 jb_err server_content_encoding(struct client_state *csp, char **header)
1298 * Turn off pcrs and gif filtering if body compressed
1300 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
1302 csp->content_type = CT_TABOO;
1310 /*********************************************************************
1312 * Function : server_content_length
1314 * Description : Adjust Content-Length header if we modified
1318 * 1 : csp = Current client state (buffers, headers, etc...)
1319 * 2 : header = On input, pointer to header to modify.
1320 * On output, pointer to the modified header, or NULL
1321 * to remove the header. This function frees the
1322 * original string if necessary.
1324 * Returns : JB_ERR_OK on success, or
1325 * JB_ERR_MEMORY on out-of-memory error.
1327 *********************************************************************/
1328 jb_err server_content_length(struct client_state *csp, char **header)
1330 if (csp->content_length != 0) /* Content length could have been modified */
1333 * XXX: Shouldn't we check if csp->content_length
1334 * is different than the original value?
1337 *header = (char *) zalloc(100);
1338 if (*header == NULL)
1340 return JB_ERR_MEMORY;
1343 sprintf(*header, "Content-Length: %d", (int) csp->content_length);
1345 log_error(LOG_LEVEL_HEADER, "Adjust Content-Length to %d", (int) csp->content_length);
1352 /*********************************************************************
1354 * Function : server_content_md5
1356 * Description : Crumble any Content-MD5 headers if the document was
1357 * modified. FIXME: Should we re-compute instead?
1360 * 1 : csp = Current client state (buffers, headers, etc...)
1361 * 2 : header = On input, pointer to header to modify.
1362 * On output, pointer to the modified header, or NULL
1363 * to remove the header. This function frees the
1364 * original string if necessary.
1366 * Returns : JB_ERR_OK on success, or
1367 * JB_ERR_MEMORY on out-of-memory error.
1369 *********************************************************************/
1370 jb_err server_content_md5(struct client_state *csp, char **header)
1372 if (csp->flags & CSP_FLAG_MODIFIED)
1374 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
1381 /*********************************************************************
1383 * Function : server_content_disposition
1385 * Description : If enabled, blocks or modifies the "content-disposition" header.
1386 * Called from `sed'.
1389 * 1 : csp = Current client state (buffers, headers, etc...)
1390 * 2 : header = On input, pointer to header to modify.
1391 * On output, pointer to the modified header, or NULL
1392 * to remove the header. This function frees the
1393 * original string if necessary.
1395 * Returns : JB_ERR_OK on success, or
1396 * JB_ERR_MEMORY on out-of-memory error.
1398 *********************************************************************/
1399 jb_err server_content_disposition(struct client_state *csp, char **header)
1404 * Are we messing with the content-disposition header?
1406 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
1412 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
1414 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1417 * Blocking content-disposition header
1419 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1426 * Replacing content-disposition header
1429 *header = strdup("content-disposition: ");
1430 string_append(header, newval);
1432 if (*header == NULL)
1434 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
1438 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
1441 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1444 /*********************************************************************
1446 * Function : server_last_modified
1448 * Description : Changes Last-Modified header to the actual date
1449 * to help hide-if-modified-since.
1450 * Called from `sed'.
1453 * 1 : csp = Current client state (buffers, headers, etc...)
1454 * 2 : header = On input, pointer to header to modify.
1455 * On output, pointer to the modified header, or NULL
1456 * to remove the header. This function frees the
1457 * original string if necessary.
1459 * Returns : JB_ERR_OK on success, or
1460 * JB_ERR_MEMORY on out-of-memory error.
1462 *********************************************************************/
1463 jb_err server_last_modified(struct client_state *csp, char **header)
1466 char buf[BUFFER_SIZE];
1469 struct tm *timeptr = NULL;
1470 time_t now, last_modified;
1472 long int days, hours, minutes, seconds;
1475 * Are we messing with the Last-Modified header?
1477 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
1483 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
1485 if (0 == strcmpic(newval, "block") )
1488 * Blocking Last-Modified header. Useless but why not.
1490 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
1494 else if (0 == strcmpic(newval, "reset-to-request-time"))
1497 * Setting Last-Modified Header to now.
1499 get_http_time(0, buf);
1501 *header = strdup("Last-Modified: ");
1502 string_append(header, buf);
1504 if (*header == NULL)
1506 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
1510 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
1513 else if (0 == strcmpic(newval, "randomize"))
1515 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
1517 timeptr = gmtime(&now);
1518 if ((timeptr = parse_header_time(*header, &last_modified)) == NULL)
1520 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
1525 rtime = difftime(now, last_modified);
1528 rtime = pick_from_range(rtime);
1529 last_modified += rtime;
1530 timeptr = gmtime(&last_modified);
1531 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
1533 *header = strdup("Last-Modified: ");
1534 string_append(header, newheader);
1536 if (*header == NULL)
1538 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
1539 return JB_ERR_MEMORY;
1542 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
1544 days = rtime / (3600 * 24);
1545 hours = rtime / 3600 % 24;
1546 minutes = rtime / 60 % 60;
1547 seconds = rtime % 60;
1549 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
1550 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
1551 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
1556 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
1564 /*********************************************************************
1566 * Function : client_accept_encoding
1568 * Description : Rewrite the client's Accept-Encoding header so that
1569 * if doesn't allow compression, if the action applies.
1570 * Note: For HTTP/1.0 the absence of the header is enough.
1573 * 1 : csp = Current client state (buffers, headers, etc...)
1574 * 2 : header = On input, pointer to header to modify.
1575 * On output, pointer to the modified header, or NULL
1576 * to remove the header. This function frees the
1577 * original string if necessary.
1579 * Returns : JB_ERR_OK on success, or
1580 * JB_ERR_MEMORY on out-of-memory error.
1582 *********************************************************************/
1583 jb_err client_accept_encoding(struct client_state *csp, char **header)
1585 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1587 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
1591 /* Temporarily disable the correct behaviour to
1592 * work around a PHP bug.
1594 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
1596 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
1597 * if (*header == NULL)
1599 * return JB_ERR_MEMORY;
1610 /*********************************************************************
1612 * Function : client_te
1614 * Description : Rewrite the client's TE header so that
1615 * if doesn't allow compression, if the action applies.
1618 * 1 : csp = Current client state (buffers, headers, etc...)
1619 * 2 : header = On input, pointer to header to modify.
1620 * On output, pointer to the modified header, or NULL
1621 * to remove the header. This function frees the
1622 * original string if necessary.
1624 * Returns : JB_ERR_OK on success, or
1625 * JB_ERR_MEMORY on out-of-memory error.
1627 *********************************************************************/
1628 jb_err client_te(struct client_state *csp, char **header)
1630 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
1633 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
1639 /*********************************************************************
1641 * Function : client_referrer
1643 * Description : Handle the "referer" config setting properly.
1644 * Called from `sed'.
1647 * 1 : csp = Current client state (buffers, headers, etc...)
1648 * 2 : header = On input, pointer to header to modify.
1649 * On output, pointer to the modified header, or NULL
1650 * to remove the header. This function frees the
1651 * original string if necessary.
1653 * Returns : JB_ERR_OK on success, or
1654 * JB_ERR_MEMORY on out-of-memory error.
1656 *********************************************************************/
1657 jb_err client_referrer(struct client_state *csp, char **header)
1664 #ifdef FEATURE_FORCE_LOAD
1665 /* Since the referrer can include the prefix even
1666 * if the request itself is non-forced, we must
1667 * clean it unconditionally
1669 strclean(*header, FORCE_PREFIX);
1670 #endif /* def FEATURE_FORCE_LOAD */
1673 * Are we sending referer?
1675 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
1680 newval = csp->action->string[ACTION_STRING_REFERER];
1682 if ((0 != strcmpic(newval, "conditional-block")))
1686 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1691 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
1694 else if (0 == strcmpic(newval, "conditional-block"))
1697 * Block referer if host has changed.
1700 if (NULL == (host = strdup(csp->http->hostport)))
1703 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary host copy.");
1704 return JB_ERR_MEMORY;
1706 if (NULL == (referer = strdup(*header)))
1710 log_error(LOG_LEVEL_HEADER, "Referer crunched! Couldn't allocate memory for temporary referer copy.");
1711 return JB_ERR_MEMORY;
1713 hostlenght = strlen(host);
1714 if ( hostlenght < (strlen(referer)-17) ) /*referer begins with 'Referer: http[s]://'*/
1716 /*Shorten referer to make sure the referer is blocked
1717 *if www.example.org/www.example.com-shall-see-the-referer/
1718 *links to www.example.com/
1720 referer[hostlenght+17] = '\n';
1722 if ( 0 == strstr(referer, host)) /*Host has changed*/
1724 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
1729 log_error(LOG_LEVEL_HEADER, "%s (not modified, still on %s)", *header, host);
1735 else if (0 != strcmpic(newval, "forge"))
1738 * We have a specific (fixed) referer we want to send.
1740 if ((0 != strncmpic(newval, "http://", 7)) && (0 != strncmpic(newval, "https://", 8)))
1742 log_error(LOG_LEVEL_HEADER, "Parameter: +referrer{%s} is a bad idea, but I don't care.", newval);
1744 *header = strdup("Referer: ");
1745 string_append(header, newval);
1746 log_error(LOG_LEVEL_HEADER, "Referer overwritten with: %s", *header);
1748 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1753 * Forge a referer as http://[hostname:port of REQUEST]/
1754 * to fool stupid checks for in-site links
1757 *header = strdup("Referer: http://");
1758 string_append(header, csp->http->hostport);
1759 string_append(header, "/");
1760 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
1762 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1766 /*********************************************************************
1768 * Function : client_accept_language
1770 * Description : Handle the "Accept-Language" config setting properly.
1771 * Called from `sed'.
1774 * 1 : csp = Current client state (buffers, headers, etc...)
1775 * 2 : header = On input, pointer to header to modify.
1776 * On output, pointer to the modified header, or NULL
1777 * to remove the header. This function frees the
1778 * original string if necessary.
1780 * Returns : JB_ERR_OK on success, or
1781 * JB_ERR_MEMORY on out-of-memory error.
1783 *********************************************************************/
1784 jb_err client_accept_language(struct client_state *csp, char **header)
1789 * Are we messing with the Accept-Language?
1791 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
1793 /*I don't think so*/
1797 newval = csp->action->string[ACTION_STRING_LANGUAGE];
1799 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1802 * Blocking Accept-Language header
1804 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
1811 * Replacing Accept-Language header
1814 *header = strdup("Accept-Language: ");
1815 string_append(header, newval);
1817 if (*header == NULL)
1819 log_error(LOG_LEVEL_ERROR, " Insufficent memory. Accept-Language header crunched without replacement.");
1823 log_error(LOG_LEVEL_HEADER, "Accept-Language header crunched and replaced with: %s", *header);
1826 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1829 /*********************************************************************
1831 * Function : crunch_client_header
1833 * Description : Crunch client header if it matches a string supplied by the
1834 * user. Called from `sed'.
1837 * 1 : csp = Current client state (buffers, headers, etc...)
1838 * 2 : header = On input, pointer to header to modify.
1839 * On output, pointer to the modified header, or NULL
1840 * to remove the header. This function frees the
1841 * original string if necessary.
1843 * Returns : JB_ERR_OK on success and always succeeds
1845 *********************************************************************/
1846 jb_err crunch_client_header(struct client_state *csp, char **header)
1848 const char *crunch_pattern;
1849 /*Is there a header to crunch*/
1851 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
1853 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
1855 /*Is the current header the lucky one?*/
1856 if (strstr(*header, crunch_pattern))
1858 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
1866 /*********************************************************************
1868 * Function : client_uagent
1870 * Description : Handle the "user-agent" config setting properly
1871 * and remember its original value to enable browser
1872 * bug workarounds. Called from `sed'.
1875 * 1 : csp = Current client state (buffers, headers, etc...)
1876 * 2 : header = On input, pointer to header to modify.
1877 * On output, pointer to the modified header, or NULL
1878 * to remove the header. This function frees the
1879 * original string if necessary.
1881 * Returns : JB_ERR_OK on success, or
1882 * JB_ERR_MEMORY on out-of-memory error.
1884 *********************************************************************/
1885 jb_err client_uagent(struct client_state *csp, char **header)
1889 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
1894 newval = csp->action->string[ACTION_STRING_USER_AGENT];
1901 *header = strdup("User-Agent: ");
1902 string_append(header, newval);
1904 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
1906 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1909 /*********************************************************************
1911 * Function : client_ua
1913 * Description : Handle "ua-" headers properly. Called from `sed'.
1916 * 1 : csp = Current client state (buffers, headers, etc...)
1917 * 2 : header = On input, pointer to header to modify.
1918 * On output, pointer to the modified header, or NULL
1919 * to remove the header. This function frees the
1920 * original string if necessary.
1922 * Returns : JB_ERR_OK on success, or
1923 * JB_ERR_MEMORY on out-of-memory error.
1925 *********************************************************************/
1926 jb_err client_ua(struct client_state *csp, char **header)
1928 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
1930 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
1938 /*********************************************************************
1940 * Function : client_from
1942 * Description : Handle the "from" config setting properly.
1943 * Called from `sed'.
1946 * 1 : csp = Current client state (buffers, headers, etc...)
1947 * 2 : header = On input, pointer to header to modify.
1948 * On output, pointer to the modified header, or NULL
1949 * to remove the header. This function frees the
1950 * original string if necessary.
1952 * Returns : JB_ERR_OK on success, or
1953 * JB_ERR_MEMORY on out-of-memory error.
1955 *********************************************************************/
1956 jb_err client_from(struct client_state *csp, char **header)
1960 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
1967 newval = csp->action->string[ACTION_STRING_FROM];
1970 * Are we blocking the e-mail address?
1972 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
1974 log_error(LOG_LEVEL_HEADER, "crunched From!");
1978 log_error(LOG_LEVEL_HEADER, " modified");
1980 *header = strdup("From: ");
1981 string_append(header, newval);
1983 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
1987 /*********************************************************************
1989 * Function : client_send_cookie
1991 * Description : Handle the "cookie" header properly. Called from `sed'.
1992 * If cookie is accepted, add it to the cookie_list,
1993 * else we crunch it. Mmmmmmmmmmm ... cookie ......
1996 * 1 : csp = Current client state (buffers, headers, etc...)
1997 * 2 : header = On input, pointer to header to modify.
1998 * On output, pointer to the modified header, or NULL
1999 * to remove the header. This function frees the
2000 * original string if necessary.
2002 * Returns : JB_ERR_OK on success, or
2003 * JB_ERR_MEMORY on out-of-memory error.
2005 *********************************************************************/
2006 jb_err client_send_cookie(struct client_state *csp, char **header)
2008 jb_err result = JB_ERR_OK;
2010 if ((csp->action->flags & ACTION_NO_COOKIE_READ) == 0)
2012 /* strlen("cookie: ") == 8 */
2013 result = enlist(csp->cookie_list, *header + 8);
2017 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie -- yum!");
2021 * Always remove the cookie here. The cookie header
2022 * will be sent at the end of the header.
2030 /*********************************************************************
2032 * Function : client_x_forwarded
2034 * Description : Handle the "x-forwarded-for" config setting properly,
2035 * also used in the add_client_headers list. Called from `sed'.
2038 * 1 : csp = Current client state (buffers, headers, etc...)
2039 * 2 : header = On input, pointer to header to modify.
2040 * On output, pointer to the modified header, or NULL
2041 * to remove the header. This function frees the
2042 * original string if necessary.
2044 * Returns : JB_ERR_OK on success, or
2045 * JB_ERR_MEMORY on out-of-memory error.
2047 *********************************************************************/
2048 jb_err client_x_forwarded(struct client_state *csp, char **header)
2050 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
2052 /* Save it so we can re-add it later */
2053 freez(csp->x_forwarded);
2054 csp->x_forwarded = *header;
2057 * Always set *header = NULL, since this information
2058 * will be sent at the end of the header.
2065 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
2072 /*********************************************************************
2074 * Function : client_max_forwards
2076 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
2077 * from the value of the Max-Forwards header field.
2080 * 1 : csp = Current client state (buffers, headers, etc...)
2081 * 2 : header = On input, pointer to header to modify.
2082 * On output, pointer to the modified header, or NULL
2083 * to remove the header. This function frees the
2084 * original string if necessary.
2086 * Returns : JB_ERR_OK on success, or
2087 * JB_ERR_MEMORY on out-of-memory error.
2089 *********************************************************************/
2090 jb_err client_max_forwards(struct client_state *csp, char **header)
2092 unsigned int max_forwards;
2094 if ((0 == strcmpic(csp->http->gpc, "trace"))
2095 || (0 == strcmpic(csp->http->gpc, "options")))
2097 if (1 == sscanf(*header, "Max-Forwards: %u", &max_forwards))
2099 if (max_forwards-- >= 1)
2101 sprintf(*header, "Max-Forwards: %u", max_forwards);
2102 log_error(LOG_LEVEL_HEADER, "Max forwards of %s request now %d", csp->http->gpc, max_forwards);
2106 log_error(LOG_LEVEL_ERROR, "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
2115 /*********************************************************************
2117 * Function : client_host
2119 * Description : If the request URI did not contain host and
2120 * port information, parse and evaluate the Host
2123 * Also, kill ill-formed HOST: headers as sent by
2124 * Apple's iTunes software when used with a proxy.
2127 * 1 : csp = Current client state (buffers, headers, etc...)
2128 * 2 : header = On input, pointer to header to modify.
2129 * On output, pointer to the modified header, or NULL
2130 * to remove the header. This function frees the
2131 * original string if necessary.
2133 * Returns : JB_ERR_OK on success, or
2134 * JB_ERR_MEMORY on out-of-memory error.
2136 *********************************************************************/
2137 jb_err client_host(struct client_state *csp, char **header)
2142 * If the header field name is all upper-case, chances are that it's
2143 * an ill-formed one from iTunes. BTW, killing innocent headers here is
2144 * not a problem -- they are regenerated later.
2146 if ((*header)[1] == 'O')
2148 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
2153 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
2154 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
2157 if (NULL == (p = strdup((*header)+6)))
2159 return JB_ERR_MEMORY;
2162 if (NULL == (q = strdup(p)))
2165 return JB_ERR_MEMORY;
2168 freez(csp->http->hostport);
2169 csp->http->hostport = p;
2170 freez(csp->http->host);
2171 csp->http->host = q;
2172 q = strchr(csp->http->host, ':');
2175 /* Terminate hostname and evaluate port string */
2177 csp->http->port = atoi(q);
2181 csp->http->port = csp->http->ssl ? 443 : 80;
2184 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
2185 csp->http->hostport, csp->http->host, csp->http->port);
2191 /*********************************************************************
2193 * Function : client_if_modified_since
2195 * Description : Remove or modify the If-Modified-Since header.
2198 * 1 : csp = Current client state (buffers, headers, etc...)
2199 * 2 : header = On input, pointer to header to modify.
2200 * On output, pointer to the modified header, or NULL
2201 * to remove the header. This function frees the
2202 * original string if necessary.
2204 * Returns : JB_ERR_OK on success, or
2205 * JB_ERR_MEMORY on out-of-memory error.
2207 *********************************************************************/
2208 jb_err client_if_modified_since(struct client_state *csp, char **header)
2211 struct tm *timeptr = NULL;
2215 long int hours, minutes, seconds;
2219 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
2222 * The client got an error message because of a temporary problem,
2223 * the problem is gone and the client now tries to revalidate our
2224 * error message on the real server. The revalidation would always
2225 * end with the transmission of the whole document and there is
2226 * no need to expose the bogus If-Modified-Since header.
2228 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
2231 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
2233 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
2235 if ((0 == strcmpic(newval, "block")))
2237 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2240 else /* add random value */
2242 if ((timeptr = parse_header_time(*header, &tm)) == NULL)
2244 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s (crunching!)", *header);
2249 rtime = strtol(newval, &endptr, 0);
2257 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d hou%s)",
2258 *header, rtime, (rtime == 1 || rtime == -1) ? "r": "rs");
2260 rtime = pick_from_range(rtime);
2264 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
2268 timeptr = gmtime(&tm);
2269 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2272 *header = strdup("If-Modified-Since: ");
2273 string_append(header, newheader);
2275 if (*header == NULL)
2277 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
2278 return JB_ERR_MEMORY;
2281 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2283 hours = rtime / 3600;
2284 minutes = rtime / 60 % 60;
2285 seconds = rtime % 60;
2287 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
2288 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
2289 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2298 /*********************************************************************
2300 * Function : client_if_none_match
2302 * Description : Remove the If-None-Match header.
2305 * 1 : csp = Current client state (buffers, headers, etc...)
2306 * 2 : header = On input, pointer to header to modify.
2307 * On output, pointer to the modified header, or NULL
2308 * to remove the header. This function frees the
2309 * original string if necessary.
2311 * Returns : JB_ERR_OK on success, or
2312 * JB_ERR_MEMORY on out-of-memory error.
2314 *********************************************************************/
2315 jb_err client_if_none_match(struct client_state *csp, char **header)
2317 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
2319 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2326 /*********************************************************************
2328 * Function : client_x_filter
2330 * Description : Disables filtering if the client set "X-Filter: No".
2331 * Called from `sed'.
2334 * 1 : csp = Current client state (buffers, headers, etc...)
2335 * 2 : header = On input, pointer to header to modify.
2336 * On output, pointer to the modified header, or NULL
2337 * to remove the header. This function frees the
2338 * original string if necessary.
2340 * Returns : JB_ERR_OK on success
2342 *********************************************************************/
2343 jb_err client_x_filter(struct client_state *csp, char **header)
2345 if ( 0 == strcmpic(*header, "X-Filter: No"))
2347 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
2349 log_error(LOG_LEVEL_HEADER, "force-text-mode overruled the client's request to disable filtering!");
2353 csp->content_type = CT_TABOO;
2354 log_error(LOG_LEVEL_HEADER, "Disabled filter mode on behalf of the client.");
2356 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
2362 /* the following functions add headers directly to the header list */
2364 /*********************************************************************
2366 * Function : client_host_adder
2368 * Description : Adds the Host: header field if it is missing.
2369 * Called from `sed'.
2372 * 1 : csp = Current client state (buffers, headers, etc...)
2374 * Returns : JB_ERR_OK on success, or
2375 * JB_ERR_MEMORY on out-of-memory error.
2377 *********************************************************************/
2378 jb_err client_host_adder(struct client_state *csp)
2383 if ( !csp->http->hostport || !*(csp->http->hostport))
2389 * remove 'user:pass@' from 'proto://user:pass@host'
2391 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
2397 p = csp->http->hostport;
2400 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
2401 err = enlist_unique_header(csp->headers, "Host", p);
2407 /*********************************************************************
2409 * Function : client_cookie_adder
2411 * Description : Used in the add_client_headers list. Called from `sed'.
2414 * 1 : csp = Current client state (buffers, headers, etc...)
2416 * Returns : JB_ERR_OK on success, or
2417 * JB_ERR_MEMORY on out-of-memory error.
2419 *********************************************************************/
2420 jb_err client_cookie_adder(struct client_state *csp)
2422 struct list_entry *lst;
2424 struct list_entry *list1 = csp->cookie_list->first;
2425 struct list_entry *list2 = csp->action->multi[ACTION_MULTI_WAFER]->first;
2426 int first_cookie = 1;
2429 if ((list1 == NULL) && (list2 == NULL))
2435 tmp = strdup("Cookie: ");
2437 for (lst = list1; lst ; lst = lst->next)
2445 string_append(&tmp, "; ");
2447 string_append(&tmp, lst->str);
2450 for (lst = list2; lst ; lst = lst->next)
2458 string_append(&tmp, "; ");
2460 string_join(&tmp, cookie_encode(lst->str));
2465 return JB_ERR_MEMORY;
2468 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
2469 err = enlist(csp->headers, tmp);
2475 /*********************************************************************
2477 * Function : client_accept_encoding_adder
2479 * Description : Add an Accept-Encoding header to the client's request
2480 * that disables compression if the action applies, and
2481 * the header is not already there. Called from `sed'.
2482 * Note: For HTTP/1.0, the absence of the header is enough.
2485 * 1 : csp = Current client state (buffers, headers, etc...)
2487 * Returns : JB_ERR_OK on success, or
2488 * JB_ERR_MEMORY on out-of-memory error.
2490 *********************************************************************/
2491 jb_err client_accept_encoding_adder(struct client_state *csp)
2493 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2494 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
2496 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
2503 /*********************************************************************
2505 * Function : client_xtra_adder
2507 * Description : Used in the add_client_headers list. Called from `sed'.
2510 * 1 : csp = Current client state (buffers, headers, etc...)
2512 * Returns : JB_ERR_OK on success, or
2513 * JB_ERR_MEMORY on out-of-memory error.
2515 *********************************************************************/
2516 jb_err client_xtra_adder(struct client_state *csp)
2518 struct list_entry *lst;
2521 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
2522 lst ; lst = lst->next)
2524 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
2525 err = enlist(csp->headers, lst->str);
2537 /*********************************************************************
2539 * Function : client_x_forwarded_adder
2541 * Description : Used in the add_client_headers list. Called from `sed'.
2544 * 1 : csp = Current client state (buffers, headers, etc...)
2546 * Returns : JB_ERR_OK on success, or
2547 * JB_ERR_MEMORY on out-of-memory error.
2549 *********************************************************************/
2550 jb_err client_x_forwarded_adder(struct client_state *csp)
2555 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
2560 if (csp->x_forwarded)
2562 p = strdup(csp->x_forwarded);
2563 string_append(&p, ", ");
2567 p = strdup("X-Forwarded-For: ");
2569 string_append(&p, csp->ip_addr_str);
2573 return JB_ERR_MEMORY;
2576 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
2577 err = enlist(csp->headers, p);
2584 /*********************************************************************
2586 * Function : connection_close_adder
2588 * Description : Adds a "Connection: close" header to csp->headers
2589 * as a temporary fix for the needed but missing HTTP/1.1
2590 * support. Called from `sed'.
2591 * FIXME: This whole function shouldn't be neccessary!
2594 * 1 : csp = Current client state (buffers, headers, etc...)
2596 * Returns : JB_ERR_OK on success, or
2597 * JB_ERR_MEMORY on out-of-memory error.
2599 *********************************************************************/
2600 jb_err connection_close_adder(struct client_state *csp)
2602 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
2603 return enlist(csp->headers, "Connection: close");
2607 /*********************************************************************
2609 * Function : server_http
2611 * Description : - Save the HTTP Status into csp->http->status
2612 * - Set CT_TABOO to prevent filtering if the answer
2613 * is a partial range (HTTP status 206)
2614 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
2618 * 1 : csp = Current client state (buffers, headers, etc...)
2619 * 2 : header = On input, pointer to header to modify.
2620 * On output, pointer to the modified header, or NULL
2621 * to remove the header. This function frees the
2622 * original string if necessary.
2624 * Returns : JB_ERR_OK on success, or
2625 * JB_ERR_MEMORY on out-of-memory error.
2627 *********************************************************************/
2628 jb_err server_http(struct client_state *csp, char **header)
2630 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
2631 if (csp->http->status == 206)
2633 csp->content_type = CT_TABOO;
2636 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
2639 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
2646 /*********************************************************************
2648 * Function : server_set_cookie
2650 * Description : Handle the server "cookie" header properly.
2651 * Log cookie to the jar file. Then "crunch" it,
2652 * or accept it. Called from `sed'.
2655 * 1 : csp = Current client state (buffers, headers, etc...)
2656 * 2 : header = On input, pointer to header to modify.
2657 * On output, pointer to the modified header, or NULL
2658 * to remove the header. This function frees the
2659 * original string if necessary.
2661 * Returns : JB_ERR_OK on success, or
2662 * JB_ERR_MEMORY on out-of-memory error.
2664 *********************************************************************/
2665 jb_err server_set_cookie(struct client_state *csp, char **header)
2667 #ifdef FEATURE_COOKIE_JAR
2668 if (csp->config->jar)
2671 * Write timestamp into outbuf.
2673 * Complex because not all OSs have tm_gmtoff or
2674 * the %z field in strftime()
2676 char tempbuf[ BUFFER_SIZE ];
2680 #ifdef HAVE_LOCALTIME_R
2681 tm_now = *localtime_r(&now, &tm_now);
2683 pthread_mutex_lock(&localtime_mutex);
2684 tm_now = *localtime (&now);
2685 pthread_mutex_unlock(&localtime_mutex);
2687 tm_now = *localtime (&now);
2689 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
2691 /* strlen("set-cookie: ") = 12 */
2692 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
2694 #endif /* def FEATURE_COOKIE_JAR */
2696 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
2698 log_error(LOG_LEVEL_HEADER, "Crunched incoming cookie -- yum!");
2699 return crumble(csp, header);
2701 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
2703 /* Flag whether or not to log a message */
2706 /* A variable to store the tag we're working on */
2709 /* Skip "Set-Cookie:" (11 characters) in header */
2710 cur_tag = *header + 11;
2712 /* skip whitespace between "Set-Cookie:" and value */
2713 while (*cur_tag && ijb_isspace(*cur_tag))
2718 /* Loop through each tag in the cookie */
2722 char *next_tag = strchr(cur_tag, ';');
2723 if (next_tag != NULL)
2725 /* Skip the ';' character itself */
2728 /* skip whitespace ";" and start of tag */
2729 while (*next_tag && ijb_isspace(*next_tag))
2736 /* "Next tag" is the end of the string */
2737 next_tag = cur_tag + strlen(cur_tag);
2740 /* Is this the "Expires" tag? */
2741 if (strncmpic(cur_tag, "expires=", 8) == 0)
2743 /* Delete the tag by copying the rest of the string over it.
2744 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
2745 * since the behaviour of strcpy is undefined for overlapping
2748 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
2750 /* That changed the header, need to issue a log message */
2753 /* Note that the next tag has now been moved to *cur_tag,
2754 * so we do not need to update the cur_tag pointer.
2759 /* Move on to next cookie tag */
2766 log_error(LOG_LEVEL_HEADER, "Changed cookie to a temporary one.");
2774 #ifdef FEATURE_FORCE_LOAD
2775 /*********************************************************************
2777 * Function : strclean
2779 * Description : In-Situ-Eliminate all occurances of substring in
2783 * 1 : string = string to clean
2784 * 2 : substring = substring to eliminate
2786 * Returns : Number of eliminations
2788 *********************************************************************/
2789 int strclean(const char *string, const char *substring)
2791 int hits = 0, len = strlen(substring);
2794 while((pos = strstr(string, substring)) != NULL)
2801 while (*p++ != '\0');
2808 #endif /* def FEATURE_FORCE_LOAD */
2810 /*********************************************************************
2812 * Function : parse_header_time
2814 * Description : Transforms time inside a HTTP header into
2815 * the usual time format.
2818 * 1 : header = header to parse
2819 * 2 : tm = storage for the resulting time in seconds
2821 * Returns : Time struct containing the header time, or
2822 * NULL in case of a parsing problem.
2824 *********************************************************************/
2825 struct tm *parse_header_time(char *header, time_t *tm) {
2828 struct tm * timeptr;
2831 timeptr = localtime(tm);
2832 /* Skipping header name */
2833 timestring = strstr(header, ": ");
2834 if (strptime(timestring, ": %a, %d %b %Y %H:%M:%S", timeptr) == NULL)
2840 *tm = timegm(timeptr);