1 const char parsers_rcs[] = "$Id: parsers.c,v 1.108 2007/08/28 18:21:03 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', `filter_header'
14 * `server_content_encoding', `server_content_disposition',
15 * `server_last_modified', `client_accept_language',
16 * `crunch_client_header', `client_if_modified_since',
17 * `client_if_none_match', `get_destination_from_headers',
18 * `parse_header_time', `decompress_iob' and `server_set_cookie'.
20 * Copyright : Written by and Copyright (C) 2001-2007 the SourceForge
21 * Privoxy team. http://www.privoxy.org/
23 * Based on the Internet Junkbuster originally written
24 * by and Copyright (C) 1997 Anonymous Coders and
25 * Junkbusters Corporation. http://www.junkbusters.com
27 * This program is free software; you can redistribute it
28 * and/or modify it under the terms of the GNU General
29 * Public License as published by the Free Software
30 * Foundation; either version 2 of the License, or (at
31 * your option) any later version.
33 * This program is distributed in the hope that it will
34 * be useful, but WITHOUT ANY WARRANTY; without even the
35 * implied warranty of MERCHANTABILITY or FITNESS FOR A
36 * PARTICULAR PURPOSE. See the GNU General Public
37 * License for more details.
39 * The GNU General Public License should be included with
40 * this file. If not, you can view it at
41 * http://www.gnu.org/copyleft/gpl.html
42 * or write to the Free Software Foundation, Inc., 59
43 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
47 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
48 * A bunch of whitespace fixes, pointy hat to me.
50 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
51 * Fix possible memory corruption in server_http, make sure it's not
52 * executed for ordinary server headers and mark some problems for later.
54 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
55 * Let content-type-overwrite{} honour force-text-mode again.
57 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
58 * - Add prototpyes for the header parsers and make them static.
59 * - Comment out client_accept_encoding_adder() which isn't used right now.
61 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
62 * Move the ACTION_FORCE_TEXT_MODE check out of
63 * server_content_type(). Signal other functions
64 * whether or not a content type has been declared.
65 * Part of the fix for BR#1750917.
67 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
68 * Change sed() to return a jb_err in preparation for forward-override{}.
70 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
71 * Adjust "X-Filter: No" to disable dedicated header filters.
73 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
74 * Streamline client_cookie_adder().
76 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
77 * Make sure filters with dynamic jobs actually use them.
79 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
80 * - Introduce dynamic pcrs jobs that can resolve variables.
81 * - Remove unnecessary update_action_bits_for_all_tags() call.
83 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
84 * - Make tagging based on tags set by earlier taggers
85 * of the same kind possible.
86 * - Log whether or not new tags cause action bits updates
87 * (in which case a matching tag-pattern section exists).
88 * - Log if the user tries to set a tag that is already set.
90 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
91 * Introduce tags as alternative way to specify which
92 * actions apply to a request. At the moment tags can be
93 * created based on client and server headers.
95 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
96 * Log a warning if the content is compressed, filtering is
97 * enabled and Privoxy was compiled without zlib support.
100 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
101 * - Fix warnings when compiled with glibc.
102 * - Don't use crumble() for cookie crunching.
103 * - Move cookie time parsing into parse_header_time().
104 * - Let parse_header_time() return a jb_err code
105 * instead of a pointer that can only be used to
106 * check for NULL anyway.
108 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
109 * - Add better protection against malicious gzip headers.
110 * - Stop logging the first hundred bytes of decompressed content.
111 * It looks like it's working and there is always debug 16.
112 * - Log the content size after decompression in decompress_iob()
113 * instead of pcrs_filter_response().
115 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
116 * - Use dedicated header filter actions instead of abusing "filter".
117 * Replace "filter-client-headers" and "filter-client-headers"
118 * with "server-header-filter" and "client-header-filter".
119 * - Remove filter_client_header() and filter_client_header(),
120 * filter_header() now checks the shiny new
121 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
123 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
124 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
125 * - Handle "Cookie:" and "Connection:" headers a bit smarter
126 * (don't crunch them just to recreate them later on).
127 * - Add another non-standard time format for the cookie
128 * expiration date detection.
129 * - Fix a valgrind warning.
131 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
132 * Improve cookie expiration date detection.
134 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
135 * Don't run server_content_length() the first time
136 * sed() parses server headers; only adjust the
137 * Content-Length header if the page was modified.
139 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
140 * Fix log messages regarding the cookie time format
141 * (cookie and request URL were mixed up).
143 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
144 * - Let decompress_iob()
145 * - not corrupt the content if decompression fails
146 * early. (the first byte(s) were lost).
147 * - use pointer arithmetics with defined outcome for
149 * - Use a different kludge to remember a failed decompression.
151 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
152 * Search for Max-Forwards headers case-insensitive,
153 * don't generate the "501 unsupported" message for invalid
154 * Max-Forwards values and don't increase negative ones.
156 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
157 * - Let server_set_cookie() check the expiration date
158 * of cookies and don't touch the ones that are already
159 * expired. Fixes problems with low quality web applications
160 * as described in BR 932612.
162 * - Adjust comment in client_max_forwards to reality;
163 * remove invalid Max-Forwards headers.
165 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
166 * Stop filter_header() from unintentionally removing
167 * empty header lines that were enlisted by the continue
170 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
171 * - Repeat the request URL before logging any headers.
172 * Makes reading the log easier in case of simultaneous requests.
173 * - If there are more than one Content-Type headers in one request,
174 * use the first one and remove the others.
175 * - Remove "newval" variable in server_content_type().
176 * It's only used once.
178 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
179 * Correct a cast, check inflateEnd() exit code
180 * to see if we have to, replace sprintf calls
183 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
184 * Integrate a modified version of Wil Mahan's
185 * zlib patch (PR #895531).
187 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
188 * Skip empty filter files in filter_header()
189 * but don't ignore the ones that come afterwards.
190 * Fixes BR 1619208, this time for real.
192 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
193 * Reverted parts of my last commit
194 * to keep error handling working.
196 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
197 * Fixed gcc43 conversion warnings.
199 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
200 * Bringing back the "useless" localtime() call
201 * I removed in revision 1.67. On some platforms
202 * it's necessary to prevent time zone offsets.
204 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
205 * Rebuild request URL in get_destination_from_headers()
206 * to make sure redirect{pcrs command} works as expected
207 * for intercepted requests.
209 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
210 * Added get_destination_from_headers().
212 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
213 * Make pthread mutex locking more generic. Instead of
214 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
215 * and use mutex locking unless there is an _r function
216 * available. Better safe than sorry.
218 * Fixes "./configure --disable-pthread" and should result
219 * in less threading-related problems on pthread-using platforms,
220 * but it still doesn't fix BR#1122404.
222 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
223 * The special header "X-Filter: No" now disables
224 * header filtering as well.
226 * Revision 1.73 2006/09/23 13:26:38 roro
227 * Replace TABs by spaces in source code.
229 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
230 * Don't print a log message every time filter_headers is
231 * entered or left. It only creates noise without any real
234 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
235 * Fix +hide-if-modified-since{-n}.
237 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
238 * Have hide-if-modified-since interpret the random
239 * range value as minutes instead of hours. Allows
240 * more fine-grained configuration.
242 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
243 * Always have parse_header_time return a pointer
244 * that actual makes sense, even though we currently
245 * only need it to detect problems.
247 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
248 * Added config option enable-remote-http-toggle
249 * to specify if Privoxy should recognize special
250 * headers (currently only X-Filter) to change its
251 * behaviour. Disabled by default.
253 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
254 * After filtering de-chunked instances, remove
255 * "Transfer-Encoding" header entirely instead of changing
256 * it to "Transfer-Encoding: identity", which is invalid.
257 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
259 * Don't use localtime in parse_header_time. An empty time struct
260 * is good enough, it gets overwritten by strptime anyway.
262 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
263 * Use gmtime_r if available, fallback to gmtime with mutex
264 * protection for MacOSX and use vanilla gmtime for the rest.
266 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
267 * Changed client_referrer to use the right type (size_t) for
268 * hostlenght and to shorten the temporary referrer string with
269 * '\0' instead of adding a useless line break.
271 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
272 * - Back to timegm() using GnuPG's replacement if necessary.
273 * Using mktime() and localtime() could add a on hour offset if
274 * the randomize factor was big enough to lead to a summer/wintertime
277 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
279 * - Moved randomization code into pick_from_range().
281 * - Changed parse_header_time definition.
282 * time_t isn't guaranteed to be signed and
283 * if it isn't, -1 isn't available as error code.
284 * Changed some variable types in client_if_modified_since()
285 * because of the same reason.
287 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
288 * OS/2 compilation compatibility fixups
290 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
291 * Changed include from strptime.c to strptime.h
293 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
294 * Split filter-headers{} into filter-client-headers{}
295 * and filter-server-headers{}.
296 * Added parse_header_time() to share some code.
297 * Replaced timegm() with mktime().
299 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
300 * Windows service integration
302 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
303 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
305 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
306 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
307 * with what was really the latest development (the v_3_0_branch branch)
309 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
310 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
312 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
313 * Add the ability to check jpeg images for invalid
314 * lengths of comment blocks. Defensive strategy
315 * against the exploit:
316 * Microsoft Security Bulletin MS04-028
317 * Buffer Overrun in JPEG Processing (GDI+) Could
318 * Allow Code Execution (833987)
319 * Enabled with +inspect-jpegs in actions files.
321 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
322 * Excluded text/plain objects from filtering. This fixes a
323 * couple of client-crashing, download corruption and
324 * Privoxy performance issues, whose root cause lies in
325 * web servers labelling content of unknown type as text/plain.
327 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
328 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
330 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
331 * Completing the previous change
333 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
334 * Added temporary workaround for bug in PHP < 4.2.3
336 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
337 * 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.
339 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
340 * Fix typo: supressed -> suppressed
342 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
343 * Improved cookie logging
345 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
346 * Added basic support for OPTIONS and TRACE HTTP methods:
347 * - New parser function client_max_forwards which decrements
348 * the Max-Forwards HTTP header field of OPTIONS and TRACE
349 * requests by one before forwarding
350 * - New parser function client_host which extracts the host
351 * and port information from the HTTP header field if the
352 * request URI was not absolute
353 * - Don't crumble and re-add the Host: header, but only generate
354 * and append if missing
356 * Revision 1.56 2002/05/12 15:34:22 jongfoster
357 * Fixing typo in a comment
359 * Revision 1.55 2002/05/08 16:01:07 oes
360 * Optimized add_to_iob:
361 * - Use realloc instead of malloc(), memcpy(), free()
362 * - Expand to powers of two if possible, to get
363 * O(log n) reallocs instead of O(n).
364 * - Moved check for buffer limit here from chat
365 * - Report failure via returncode
367 * Revision 1.54 2002/04/02 15:03:16 oes
368 * Tiny code cosmetics
370 * Revision 1.53 2002/03/26 22:29:55 swa
371 * we have a new homepage!
373 * Revision 1.52 2002/03/24 13:25:43 swa
374 * name change related issues
376 * Revision 1.51 2002/03/13 00:27:05 jongfoster
379 * Revision 1.50 2002/03/12 01:45:35 oes
380 * More verbose logging
382 * Revision 1.49 2002/03/09 20:03:52 jongfoster
383 * - Making various functions return int rather than size_t.
384 * (Undoing a recent change). Since size_t is unsigned on
385 * Windows, functions like read_socket that return -1 on
386 * error cannot return a size_t.
388 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
389 * crashes, and also frequently caused JB to jump to 100%
390 * CPU and stay there. (Because it thought it had just
391 * read ((unsigned)-1) == 4Gb of data...)
393 * - The signature of write_socket has changed, it now simply
394 * returns success=0/failure=nonzero.
396 * - Trying to get rid of a few warnings --with-debug on
397 * Windows, I've introduced a new type "jb_socket". This is
398 * used for the socket file descriptors. On Windows, this
399 * is SOCKET (a typedef for unsigned). Everywhere else, it's
400 * an int. The error value can't be -1 any more, so it's
401 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
402 * Windows it maps to the #define INVALID_SOCKET.)
404 * - The signature of bind_port has changed.
406 * Revision 1.48 2002/03/07 03:46:53 oes
407 * Fixed compiler warnings etc
409 * Revision 1.47 2002/02/20 23:15:13 jongfoster
410 * Parsing functions now handle out-of-memory gracefully by returning
413 * Revision 1.46 2002/01/17 21:03:47 jongfoster
414 * Moving all our URL and URL pattern parsing code to urlmatch.c.
416 * Revision 1.45 2002/01/09 14:33:03 oes
417 * Added support for localtime_r.
419 * Revision 1.44 2001/12/14 01:22:54 steudten
420 * Remove 'user:pass@' from 'proto://user:pass@host' for the
421 * new added header 'Host: ..'. (See Req ID 491818)
423 * Revision 1.43 2001/11/23 00:26:38 jongfoster
424 * Fixing two really stupid errors in my previous commit
426 * Revision 1.42 2001/11/22 21:59:30 jongfoster
427 * Adding code to handle +no-cookies-keep
429 * Revision 1.41 2001/11/05 23:43:05 steudten
430 * Add time+date to log files.
432 * Revision 1.40 2001/10/26 20:13:09 jongfoster
433 * ctype.h is needed in Windows, too.
435 * Revision 1.39 2001/10/26 17:40:04 oes
436 * Introduced get_header_value()
437 * Removed http->user_agent, csp->referrer and csp->accept_types
438 * Removed client_accept()
440 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
441 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
442 * threads to call select() simultaneously. So, it's time to do a real, live,
443 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
444 * (native). Both versions will work, but using __OS2__ offers multi-threading.
446 * Revision 1.37 2001/10/23 21:36:02 jongfoster
447 * Documenting sed()'s error behaviou (doc change only)
449 * Revision 1.36 2001/10/13 12:51:51 joergs
450 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
451 * force-load), instead crumble Host: and add it (again) in client_host_adder
452 * (in case we get a HTTP/1.0 request without Host: header and forward it to
453 * a HTTP/1.1 server/proxy).
455 * Revision 1.35 2001/10/09 22:39:21 jongfoster
456 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
459 * Revision 1.34 2001/10/07 18:50:55 oes
460 * Added server_content_encoding, renamed server_transfer_encoding
462 * Revision 1.33 2001/10/07 18:04:49 oes
463 * Changed server_http11 to server_http and its pattern to "HTTP".
464 * Additional functionality: it now saves the HTTP status into
465 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
467 * Revision 1.32 2001/10/07 15:43:28 oes
468 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
469 * client_te and client_accept_encoding_adder, triggered by the new
470 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
471 * changed to allow only identity and chunked, and the TE header is
472 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
474 * parse_http_request no longer does anything than parsing. The rewriting
475 * of http->cmd and version mangling are gone. It now also recognizes
476 * the put and delete methods and saves the url in http->url. Removed
479 * renamed content_type and content_length to have the server_ prefix
481 * server_content_type now only works if csp->content_type != CT_TABOO
483 * added server_transfer_encoding, which
484 * - Sets CT_TABOO to prohibit filtering if encoding compresses
485 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
486 * - Change from "chunked" to "identity" if body was chunked
487 * but has been de-chunked for filtering.
489 * added server_content_md5 which crunches any Content-MD5 headers
490 * if the body was modified.
492 * made server_http11 conditional on +downgrade action
494 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
496 * Revision 1.31 2001/10/05 14:25:02 oes
497 * Crumble Keep-Alive from Server
499 * Revision 1.30 2001/09/29 12:56:03 joergs
500 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
502 * Revision 1.29 2001/09/24 21:09:24 jongfoster
503 * Fixing 2 memory leaks that Guy spotted, where the paramater to
504 * enlist() was not being free()d.
506 * Revision 1.28 2001/09/22 16:32:28 jongfoster
507 * Removing unused #includes.
509 * Revision 1.27 2001/09/20 15:45:25 steudten
511 * add casting from size_t to int for printf()
512 * remove local variable shadow s2
514 * Revision 1.26 2001/09/16 17:05:14 jongfoster
515 * Removing unused #include showarg.h
517 * Revision 1.25 2001/09/16 13:21:27 jongfoster
518 * Changes to use new list functions.
520 * Revision 1.24 2001/09/13 23:05:50 jongfoster
521 * Changing the string paramater to the header parsers a "const".
523 * Revision 1.23 2001/09/12 18:08:19 steudten
525 * In parse_http_request() header rewriting miss the host value, so
526 * from http://www.mydomain.com the result was just " / " not
527 * http://www.mydomain.com/ in case we forward.
529 * Revision 1.22 2001/09/10 10:58:53 oes
530 * Silenced compiler warnings
532 * Revision 1.21 2001/07/31 14:46:00 oes
533 * - Persistant connections now suppressed
534 * - sed() no longer appends empty header to csp->headers
536 * Revision 1.20 2001/07/30 22:08:36 jongfoster
537 * Tidying up #defines:
538 * - All feature #defines are now of the form FEATURE_xxx
539 * - Permanently turned off WIN_GUI_EDIT
540 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
542 * Revision 1.19 2001/07/25 17:21:54 oes
543 * client_uagent now saves copy of User-Agent: header value
545 * Revision 1.18 2001/07/13 14:02:46 oes
546 * - Included fix to repair broken HTTP requests that
547 * don't contain a path, not even '/'.
548 * - Removed all #ifdef PCRS
549 * - content_type now always inspected and classified as
550 * text, gif or other.
551 * - formatting / comments
553 * Revision 1.17 2001/06/29 21:45:41 oes
554 * Indentation, CRLF->LF, Tab-> Space
556 * Revision 1.16 2001/06/29 13:32:42 oes
558 * - Adapted free_http_request
559 * - Removed logentry from cancelled commit
561 * Revision 1.15 2001/06/03 19:12:38 oes
562 * deleted const struct interceptors
564 * Revision 1.14 2001/06/01 18:49:17 jongfoster
565 * Replaced "list_share" with "list" - the tiny memory gain was not
566 * worth the extra complexity.
568 * Revision 1.13 2001/05/31 21:30:33 jongfoster
569 * Removed list code - it's now in list.[ch]
570 * Renamed "permission" to "action", and changed many features
571 * to use the actions file rather than the global config.
573 * Revision 1.12 2001/05/31 17:33:13 oes
577 * Revision 1.11 2001/05/29 20:11:19 joergs
578 * '/ * inside comment' warning removed.
580 * Revision 1.10 2001/05/29 09:50:24 jongfoster
581 * Unified blocklist/imagelist/permissionslist.
582 * File format is still under discussion, but the internal changes
585 * Also modified interceptor behaviour:
586 * - We now intercept all URLs beginning with one of the following
587 * prefixes (and *only* these prefixes):
589 * * http://ijbswa.sf.net/config/
590 * * http://ijbswa.sourceforge.net/config/
591 * - New interceptors "home page" - go to http://i.j.b/ to see it.
592 * - Internal changes so that intercepted and fast redirect pages
593 * are not replaced with an image.
594 * - Interceptors now have the option to send a binary page direct
595 * to the client. (i.e. ijb-send-banner uses this)
596 * - Implemented show-url-info interceptor. (Which is why I needed
597 * the above interceptors changes - a typical URL is
598 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
599 * The previous mechanism would not have intercepted that, and
600 * if it had been intercepted then it then it would have replaced
603 * Revision 1.9 2001/05/28 17:26:33 jongfoster
604 * Fixing segfault if last header was crunched.
605 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
606 * can use the cross-platform sprintf() instead.)
608 * Revision 1.8 2001/05/27 22:17:04 oes
610 * - re_process_buffer no longer writes the modified buffer
611 * to the client, which was very ugly. It now returns the
612 * buffer, which it is then written by chat.
614 * - content_length now adjusts the Content-Length: header
615 * for modified documents rather than crunch()ing it.
616 * (Length info in csp->content_length, which is 0 for
617 * unmodified documents)
619 * - For this to work, sed() is called twice when filtering.
621 * Revision 1.7 2001/05/27 13:19:06 oes
622 * Patched Joergs solution for the content-length in.
624 * Revision 1.6 2001/05/26 13:39:32 jongfoster
625 * Only crunches Content-Length header if applying RE filtering.
626 * Without this fix, Microsoft Windows Update wouldn't work.
628 * Revision 1.5 2001/05/26 00:28:36 jongfoster
629 * Automatic reloading of config file.
630 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
631 * Most of the global variables have been moved to a new
632 * struct configuration_spec, accessed through csp->config->globalname
633 * Most of the globals remaining are used by the Win32 GUI.
635 * Revision 1.4 2001/05/22 18:46:04 oes
637 * - Enabled filtering banners by size rather than URL
638 * by adding patterns that replace all standard banner
639 * sizes with the "Junkbuster" gif to the re_filterfile
641 * - Enabled filtering WebBugs by providing a pattern
642 * which kills all 1x1 images
644 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
645 * which is selected by the (nonstandard and therefore
646 * capital) letter 'U' in the option string.
647 * It causes the quantifiers to be ungreedy by default.
648 * Appending a ? turns back to greedy (!).
650 * - Added a new interceptor ijb-send-banner, which
651 * sends back the "Junkbuster" gif. Without imagelist or
652 * MSIE detection support, or if tinygif = 1, or the
653 * URL isn't recognized as an imageurl, a lame HTML
654 * explanation is sent instead.
656 * - Added new feature, which permits blocking remote
657 * script redirects and firing back a local redirect
659 * The feature is conditionally compiled, i.e. it
660 * can be disabled with --disable-fast-redirects,
661 * plus it must be activated by a "fast-redirects"
662 * line in the config file, has its own log level
663 * and of course wants to be displayed by show-proxy-args
664 * Note: Boy, all the #ifdefs in 1001 locations and
665 * all the fumbling with configure.in and acconfig.h
666 * were *way* more work than the feature itself :-(
668 * - Because a generic redirect template was needed for
669 * this, tinygif = 3 now uses the same.
671 * - Moved GIFs, and other static HTTP response templates
676 * - Removed some >400 CRs again (Jon, you really worked
679 * Revision 1.3 2001/05/20 01:21:20 jongfoster
680 * Version 2.9.4 checkin.
681 * - Merged popupfile and cookiefile, and added control over PCRS
682 * filtering, in new "permissionsfile".
683 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
684 * file error you now get a message box (in the Win32 GUI) rather
685 * than the program exiting with no explanation.
686 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
688 * - Removed tabs from "config"
689 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
690 * - Bumped up version number.
692 * Revision 1.2 2001/05/17 23:02:36 oes
693 * - Made referrer option accept 'L' as a substitute for '§'
695 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
696 * Initial import of version 2.9.3 source tree
699 *********************************************************************/
706 #include <sys/types.h>
716 * Convince GNU's libc to provide a strptime prototype.
719 #endif /*__GLIBC__ */
726 #if !defined(_WIN32) && !defined(__OS2__)
732 #ifdef FEATURE_PTHREAD
734 /* jcc.h is for mutex semapores only */
735 #endif /* def FEATURE_PTHREAD */
741 #include "jbsockets.h"
742 #include "miscutil.h"
747 #ifndef HAVE_STRPTIME
748 #include "strptime.h"
751 const char parsers_h_rcs[] = PARSERS_H_VERSION;
753 /* Fix a problem with Solaris. There should be no effect on other
755 * Solaris's isspace() is a macro which uses its argument directly
756 * as an array index. Therefore we need to make sure that high-bit
757 * characters generate +ve values, and ideally we also want to make
758 * the argument match the declared parameter type of "int".
760 * Why did they write a character function that can't take a simple
761 * "char" argument? Doh!
763 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
764 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
766 static jb_err scan_headers(struct client_state *csp);
767 static jb_err header_tagger(struct client_state *csp, char *header);
768 static jb_err parse_header_time(const char *header_time, time_t *result);
770 static jb_err crumble (struct client_state *csp, char **header);
771 static jb_err connection (struct client_state *csp, char **header);
772 static jb_err filter_header (struct client_state *csp, char **header);
773 static jb_err client_referrer (struct client_state *csp, char **header);
774 static jb_err client_uagent (struct client_state *csp, char **header);
775 static jb_err client_ua (struct client_state *csp, char **header);
776 static jb_err client_from (struct client_state *csp, char **header);
777 static jb_err client_send_cookie (struct client_state *csp, char **header);
778 static jb_err client_x_forwarded (struct client_state *csp, char **header);
779 static jb_err client_accept_encoding (struct client_state *csp, char **header);
780 static jb_err client_te (struct client_state *csp, char **header);
781 static jb_err client_max_forwards (struct client_state *csp, char **header);
782 static jb_err client_host (struct client_state *csp, char **header);
783 static jb_err client_if_modified_since (struct client_state *csp, char **header);
784 static jb_err client_accept_language (struct client_state *csp, char **header);
785 static jb_err client_if_none_match (struct client_state *csp, char **header);
786 static jb_err crunch_client_header (struct client_state *csp, char **header);
787 static jb_err client_x_filter (struct client_state *csp, char **header);
788 static jb_err server_set_cookie (struct client_state *csp, char **header);
789 static jb_err server_content_type (struct client_state *csp, char **header);
790 static jb_err server_content_length (struct client_state *csp, char **header);
791 static jb_err server_content_md5 (struct client_state *csp, char **header);
792 static jb_err server_content_encoding (struct client_state *csp, char **header);
793 static jb_err server_transfer_coding (struct client_state *csp, char **header);
794 static jb_err server_http (struct client_state *csp, char **header);
795 static jb_err crunch_server_header (struct client_state *csp, char **header);
796 static jb_err server_last_modified (struct client_state *csp, char **header);
797 static jb_err server_content_disposition(struct client_state *csp, char **header);
799 static jb_err client_host_adder (struct client_state *csp);
800 static jb_err client_cookie_adder (struct client_state *csp);
801 static jb_err client_xtra_adder (struct client_state *csp);
802 static jb_err client_x_forwarded_adder(struct client_state *csp);
803 static jb_err connection_close_adder (struct client_state *csp);
805 static jb_err create_forged_referrer(char **header, const char *hostport);
806 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
807 static jb_err handle_conditional_hide_referrer_parameter(char **header,
808 const char *host, const int parameter_conditional_block);
810 const struct parsers client_patterns[] = {
811 { "referer:", 8, client_referrer },
812 { "user-agent:", 11, client_uagent },
813 { "ua-", 3, client_ua },
814 { "from:", 5, client_from },
815 { "cookie:", 7, client_send_cookie },
816 { "x-forwarded-for:", 16, client_x_forwarded },
817 { "Accept-Encoding:", 16, client_accept_encoding },
818 { "TE:", 3, client_te },
819 { "Host:", 5, client_host },
820 { "if-modified-since:", 18, client_if_modified_since },
821 { "Keep-Alive:", 11, crumble },
822 { "connection:", 11, connection },
823 { "proxy-connection:", 17, crumble },
824 { "max-forwards:", 13, client_max_forwards },
825 { "Accept-Language:", 16, client_accept_language },
826 { "if-none-match:", 14, client_if_none_match },
827 { "X-Filter:", 9, client_x_filter },
828 { "*", 0, crunch_client_header },
829 { "*", 0, filter_header },
833 const struct parsers server_patterns[] = {
834 { "HTTP/", 5, server_http },
835 { "set-cookie:", 11, server_set_cookie },
836 { "connection:", 11, connection },
837 { "Content-Type:", 13, server_content_type },
838 { "Content-MD5:", 12, server_content_md5 },
839 { "Content-Encoding:", 17, server_content_encoding },
840 { "Transfer-Encoding:", 18, server_transfer_coding },
841 { "Keep-Alive:", 11, crumble },
842 { "content-disposition:", 20, server_content_disposition },
843 { "Last-Modified:", 14, server_last_modified },
844 { "*", 0, crunch_server_header },
845 { "*", 0, filter_header },
849 const struct parsers server_patterns_light[] = {
850 { "Content-Length:", 15, server_content_length },
851 { "Transfer-Encoding:", 18, server_transfer_coding },
853 { "Content-Encoding:", 17, server_content_encoding },
854 #endif /* def FEATURE_ZLIB */
858 const add_header_func_ptr add_client_headers[] = {
861 client_x_forwarded_adder,
863 /* Temporarily disabled: client_accept_encoding_adder, */
864 connection_close_adder,
869 const add_header_func_ptr add_server_headers[] = {
870 connection_close_adder,
874 /*********************************************************************
876 * Function : flush_socket
878 * Description : Write any pending "buffered" content.
881 * 1 : fd = file descriptor of the socket to read
882 * 2 : csp = Current client state (buffers, headers, etc...)
884 * Returns : On success, the number of bytes written are returned (zero
885 * indicates nothing was written). On error, -1 is returned,
886 * and errno is set appropriately. If count is zero and the
887 * file descriptor refers to a regular file, 0 will be
888 * returned without causing any other effect. For a special
889 * file, the results are not portable.
891 *********************************************************************/
892 int flush_socket(jb_socket fd, struct client_state *csp)
894 struct iob *iob = csp->iob;
895 int len = iob->eod - iob->cur;
902 if (write_socket(fd, iob->cur, (size_t)len))
906 iob->eod = iob->cur = iob->buf;
912 /*********************************************************************
914 * Function : add_to_iob
916 * Description : Add content to the buffered page, expanding the
917 * buffer if necessary.
920 * 1 : csp = Current client state (buffers, headers, etc...)
921 * 2 : buf = holds the content to be added to the page
922 * 3 : n = number of bytes to be added
924 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
925 * or buffer limit reached.
927 *********************************************************************/
928 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
930 struct iob *iob = csp->iob;
931 size_t used, offset, need, want;
934 if (n <= 0) return JB_ERR_OK;
936 used = (size_t)(iob->eod - iob->buf);
937 offset = (size_t)(iob->cur - iob->buf);
938 need = used + (size_t)n + 1;
941 * If the buffer can't hold the new data, extend it first.
942 * Use the next power of two if possible, else use the actual need.
944 if (need > csp->config->buffer_limit)
946 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while extending the buffer (iob)");
947 return JB_ERR_MEMORY;
950 if (need > iob->size)
952 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
954 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
958 else if (NULL != (p = (char *)realloc(iob->buf, need)))
964 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
965 return JB_ERR_MEMORY;
968 /* Update the iob pointers */
969 iob->cur = p + offset;
974 /* copy the new data into the iob buffer */
975 memcpy(iob->eod, buf, (size_t)n);
977 /* point to the end of the data */
980 /* null terminate == cheap insurance */
989 /*********************************************************************
991 * Function : decompress_iob
993 * Description : Decompress buffered page, expanding the
994 * buffer as necessary. csp->iob->cur
995 * should point to the the beginning of the
996 * compressed data block.
999 * 1 : csp = Current client state (buffers, headers, etc...)
1001 * Returns : JB_ERR_OK on success,
1002 * JB_ERR_MEMORY if out-of-memory limit reached, and
1003 * JB_ERR_COMPRESS if error decompressing buffer.
1005 *********************************************************************/
1006 jb_err decompress_iob(struct client_state *csp)
1008 char *buf; /* new, uncompressed buffer */
1009 char *cur; /* Current iob position (to keep the original
1010 * iob->cur unmodified if we return early) */
1011 size_t bufsize; /* allocated size of the new buffer */
1012 size_t old_size; /* Content size before decompression */
1013 size_t skip_size; /* Number of bytes at the beginning of the iob
1014 that we should NOT decompress. */
1015 int status; /* return status of the inflate() call */
1016 z_stream zstr; /* used by calls to zlib */
1018 assert(csp->iob->cur - csp->iob->buf > 0);
1019 assert(csp->iob->eod - csp->iob->cur > 0);
1021 bufsize = csp->iob->size;
1022 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1023 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1025 cur = csp->iob->cur;
1030 * This is to protect the parsing of gzipped data,
1031 * but it should(?) be valid for deflated data also.
1033 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1034 return JB_ERR_COMPRESS;
1037 if (csp->content_type & CT_GZIP)
1040 * Our task is slightly complicated by the facts that data
1041 * compressed by gzip does not include a zlib header, and
1042 * that there is no easily accessible interface in zlib to
1043 * handle a gzip header. We strip off the gzip header by
1044 * hand, and later inform zlib not to expect a header.
1048 * Strip off the gzip header. Please see RFC 1952 for more
1049 * explanation of the appropriate fields.
1051 if ((*cur++ != (char)0x1f)
1052 || (*cur++ != (char)0x8b)
1053 || (*cur++ != Z_DEFLATED))
1055 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1056 return JB_ERR_COMPRESS;
1062 * XXX: These magic numbers should be replaced
1063 * with macros to give a better idea what they do.
1067 /* The gzip header has reserved bits set; bail out. */
1068 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1069 return JB_ERR_COMPRESS;
1073 /* Skip extra fields if necessary. */
1077 * Skip a given number of bytes, specified
1078 * as a 16-bit little-endian value.
1081 * XXX: This code used to be:
1083 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1085 * which I had to change into:
1087 * cur += *cur++ + (*cur++ << 8);
1089 * at which point gcc43 finally noticed that the value
1090 * of cur is undefined (it depends on which of the
1091 * summands is evaluated first).
1093 * I haven't come across a site where this
1094 * code is actually executed yet, but I hope
1098 skip_bytes = *cur++;
1099 skip_bytes = *cur++ << 8;
1101 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1104 * The number of bytes to skip should be positive
1105 * and we'd like to stay in the buffer.
1107 if((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1109 log_error(LOG_LEVEL_ERROR,
1110 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1112 return JB_ERR_COMPRESS;
1114 log_error(LOG_LEVEL_INFO,
1115 "Skipping %d bytes for gzip compression. Does this sound right?",
1120 /* Skip the filename if necessary. */
1123 /* A null-terminated string is supposed to follow. */
1124 while (*cur++ && (cur < csp->iob->eod));
1128 /* Skip the comment if necessary. */
1131 /* A null-terminated string is supposed to follow. */
1132 while (*cur++ && (cur < csp->iob->eod));
1135 /* Skip the CRC if necessary. */
1141 if (cur >= csp->iob->eod)
1144 * If the current position pointer reached or passed
1145 * the buffer end, we were obviously tricked to skip
1148 log_error(LOG_LEVEL_ERROR,
1149 "Malformed gzip header detected. Aborting decompression.");
1150 return JB_ERR_COMPRESS;
1154 else if (csp->content_type & CT_DEFLATE)
1157 * XXX: The debug level should be lowered
1158 * before the next stable release.
1160 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1162 * In theory (that is, according to RFC 1950), deflate-compressed
1163 * data should begin with a two-byte zlib header and have an
1164 * adler32 checksum at the end. It seems that in practice only
1165 * the raw compressed data is sent. Note that this means that
1166 * we are not RFC 1950-compliant here, but the advantage is that
1167 * this actually works. :)
1169 * We add a dummy null byte to tell zlib where the data ends,
1170 * and later inform it not to expect a header.
1172 * Fortunately, add_to_iob() has thoughtfully null-terminated
1173 * the buffer; we can just increment the end pointer to include
1180 log_error(LOG_LEVEL_ERROR,
1181 "Unable to determine compression format for decompression");
1182 return JB_ERR_COMPRESS;
1185 /* Set up the fields required by zlib. */
1186 zstr.next_in = (Bytef *)cur;
1187 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1188 zstr.zalloc = Z_NULL;
1189 zstr.zfree = Z_NULL;
1190 zstr.opaque = Z_NULL;
1193 * Passing -MAX_WBITS to inflateInit2 tells the library
1194 * that there is no zlib header.
1196 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1198 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1199 return JB_ERR_COMPRESS;
1203 * Next, we allocate new storage for the inflated data.
1204 * We don't modify the existing iob yet, so in case there
1205 * is error in decompression we can recover gracefully.
1207 buf = zalloc(bufsize);
1210 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1211 return JB_ERR_MEMORY;
1214 assert(bufsize >= skip_size);
1215 memcpy(buf, csp->iob->buf, skip_size);
1216 zstr.avail_out = bufsize - skip_size;
1217 zstr.next_out = (Bytef *)buf + skip_size;
1219 /* Try to decompress the whole stream in one shot. */
1220 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1222 /* We need to allocate more memory for the output buffer. */
1224 char *tmpbuf; /* used for realloc'ing the buffer */
1225 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1228 * If zlib wants more data then there's a problem, because
1229 * the complete compressed file should have been buffered.
1231 if (0 == zstr.avail_in)
1233 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1234 return JB_ERR_COMPRESS;
1238 * If we tried the limit and still didn't have enough
1239 * memory, just give up.
1241 if (bufsize == csp->config->buffer_limit)
1243 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1244 return JB_ERR_MEMORY;
1247 /* Try doubling the buffer size each time. */
1250 /* Don't exceed the buffer limit. */
1251 if (bufsize > csp->config->buffer_limit)
1253 bufsize = csp->config->buffer_limit;
1256 /* Try to allocate the new buffer. */
1257 tmpbuf = realloc(buf, bufsize);
1260 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1262 return JB_ERR_MEMORY;
1266 char *oldnext_out = (char *)zstr.next_out;
1269 * Update the fields for inflate() to use the new
1270 * buffer, which may be in a location different from
1273 zstr.avail_out += bufsize - oldbufsize;
1274 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1277 * Compare with an uglier method of calculating these values
1278 * that doesn't require the extra oldbufsize variable.
1280 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1281 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1282 assert(zstr.avail_out > 0);
1288 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1290 log_error(LOG_LEVEL_ERROR,
1291 "Inconsistent stream state after decompression: %s", zstr.msg);
1293 * XXX: Intentionally no return.
1295 * According to zlib.h, Z_STREAM_ERROR is returned
1296 * "if the stream state was inconsistent".
1298 * I assume in this case inflate()'s status
1299 * would also be something different than Z_STREAM_END
1300 * so this check should be redundant, but lets see.
1304 if (status != Z_STREAM_END)
1306 /* We failed to decompress the stream. */
1307 log_error(LOG_LEVEL_ERROR,
1308 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1309 return JB_ERR_COMPRESS;
1313 * Finally, we can actually update the iob, since the
1314 * decompression was successful. First, free the old
1317 freez(csp->iob->buf);
1319 /* Now, update the iob to use the new buffer. */
1320 csp->iob->buf = buf;
1321 csp->iob->cur = csp->iob->buf + skip_size;
1322 csp->iob->eod = (char *)zstr.next_out;
1323 csp->iob->size = bufsize;
1326 * Make sure the new uncompressed iob obeys some minimal
1327 * consistency conditions.
1329 if ((csp->iob->buf < csp->iob->cur)
1330 && (csp->iob->cur <= csp->iob->eod)
1331 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1333 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1336 log_error(LOG_LEVEL_RE_FILTER,
1337 "Decompression successful. Old size: %d, new size: %d.",
1338 old_size, new_size);
1342 /* zlib thinks this is OK, so lets do the same. */
1343 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1348 /* It seems that zlib did something weird. */
1349 log_error(LOG_LEVEL_ERROR,
1350 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1351 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1352 csp->iob->eod, csp->iob->buf + csp->iob->size);
1353 return JB_ERR_COMPRESS;
1359 #endif /* defined(FEATURE_ZLIB) */
1362 /*********************************************************************
1364 * Function : get_header
1366 * Description : This (odd) routine will parse the csp->iob
1369 * 1 : csp = Current client state (buffers, headers, etc...)
1371 * Returns : Any one of the following:
1373 * 1) a pointer to a dynamically allocated string that contains a header line
1374 * 2) NULL indicating that the end of the header was reached
1375 * 3) "" indicating that the end of the iob was reached before finding
1376 * a complete header line.
1378 *********************************************************************/
1379 char *get_header(struct client_state *csp)
1385 if ((iob->cur == NULL)
1386 || ((p = strchr(iob->cur, '\n')) == NULL))
1388 return(""); /* couldn't find a complete header */
1393 ret = strdup(iob->cur);
1396 /* FIXME No way to handle error properly */
1397 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header()");
1402 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1404 /* is this a blank line (i.e. the end of the header) ? */
1416 /*********************************************************************
1418 * Function : get_header_value
1420 * Description : Get the value of a given header from a chained list
1421 * of header lines or return NULL if no such header is
1422 * present in the list.
1425 * 1 : header_list = pointer to list
1426 * 2 : header_name = string with name of header to look for.
1427 * Trailing colon required, capitalization
1430 * Returns : NULL if not found, else value of header
1432 *********************************************************************/
1433 char *get_header_value(const struct list *header_list, const char *header_name)
1435 struct list_entry *cur_entry;
1439 assert(header_list);
1440 assert(header_name);
1441 length = strlen(header_name);
1443 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1447 if (!strncmpic(cur_entry->str, header_name, length))
1450 * Found: return pointer to start of value
1452 ret = (char *) (cur_entry->str + length);
1453 while (*ret && ijb_isspace(*ret)) ret++;
1467 /*********************************************************************
1469 * Function : scan_headers
1471 * Description : Scans headers, applies tags and updates action bits.
1474 * 1 : csp = Current client state (buffers, headers, etc...)
1476 * Returns : JB_ERR_OK
1478 *********************************************************************/
1479 static jb_err scan_headers(struct client_state *csp)
1481 struct list_entry *h; /* Header */
1482 jb_err err = JB_ERR_OK;
1484 log_error(LOG_LEVEL_HEADER, "scanning headers for: %s", csp->http->url);
1486 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1488 /* Header crunch()ed in previous run? -> ignore */
1489 if (h->str == NULL) continue;
1490 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1491 err = header_tagger(csp, h->str);
1498 /*********************************************************************
1502 * Description : add, delete or modify lines in the HTTP header streams.
1503 * On entry, it receives a linked list of headers space
1504 * that was allocated dynamically (both the list nodes
1505 * and the header contents).
1507 * As a side effect it frees the space used by the original
1511 * 1 : pats = list of patterns to match against headers
1512 * 2 : more_headers = list of functions to add more
1513 * headers (client or server)
1514 * 3 : csp = Current client state (buffers, headers, etc...)
1516 * Returns : JB_ERR_OK in case off success, or
1517 * JB_ERR_MEMORY on out-of-memory error.
1519 *********************************************************************/
1520 jb_err sed(const struct parsers pats[],
1521 const add_header_func_ptr more_headers[],
1522 struct client_state *csp)
1524 struct list_entry *p;
1525 const struct parsers *v;
1526 const add_header_func_ptr *f;
1527 jb_err err = JB_ERR_OK;
1531 * If filtering is enabled, sed is run twice,
1532 * but most of the work needs to be done only once.
1534 first_run = (more_headers != NULL ) ? 1 : 0;
1536 if (first_run) /* Parse and print */
1540 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1542 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1544 /* Header crunch()ed in previous run? -> ignore */
1545 if (p->str == NULL) continue;
1547 /* Does the current parser handle this header? */
1548 if ((strncmpic(p->str, v->str, v->len) == 0) || (v->len == CHECK_EVERY_HEADER_REMAINING))
1550 err = v->parser(csp, (char **)&(p->str));
1554 /* place any additional headers on the csp->headers list */
1555 for (f = more_headers; (err == JB_ERR_OK) && (*f) ; f++)
1560 else /* Parse only */
1563 * The second run is only needed if the body was modified
1564 * and the content-lenght has changed.
1566 if (strncmpic(csp->http->cmd, "HEAD", 4))
1568 /*XXX: Code duplication */
1569 for (v = pats; (err == JB_ERR_OK) && (v->str != NULL) ; v++)
1571 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL) ; p = p->next)
1573 /* Header crunch()ed in previous run? -> ignore */
1574 if (p->str == NULL) continue;
1576 /* Does the current parser handle this header? */
1577 if (strncmpic(p->str, v->str, v->len) == 0)
1579 err = v->parser(csp, (char **)&(p->str));
1591 /*********************************************************************
1593 * Function : header_tagger
1595 * Description : Executes all text substitutions from applying
1596 * tag actions and saves the result as tag.
1598 * XXX: Shares enough code with filter_header() and
1599 * pcrs_filter_response() to warrant some helper functions.
1602 * 1 : csp = Current client state (buffers, headers, etc...)
1603 * 2 : header = Header that is used as tagger input
1605 * Returns : JB_ERR_OK on success and always succeeds
1607 *********************************************************************/
1608 static jb_err header_tagger(struct client_state *csp, char *header)
1610 int wanted_filter_type;
1611 int multi_action_index;
1615 struct file_list *fl;
1616 struct re_filterfile_spec *b;
1617 struct list_entry *tag_name;
1619 int found_filters = 0;
1620 const size_t header_length = strlen(header);
1622 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1624 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1625 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1629 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1630 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
1633 /* Check if there are any filters */
1634 for (i = 0; i < MAX_AF_FILES; i++)
1647 if (0 == found_filters)
1649 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regex tagging.");
1653 for (i = 0; i < MAX_AF_FILES; i++)
1656 if ((NULL == fl) || (NULL == fl->f))
1659 * Either there are no filter files
1660 * left, or this filter file just
1661 * contains no valid filters.
1663 * Continue to be sure we don't miss
1664 * valid filter files that are chained
1665 * after empty or invalid ones.
1670 /* For all filters, */
1671 for (b = fl->f; b; b = b->next)
1673 if (b->type != wanted_filter_type)
1675 /* skip the ones we don't care about, */
1678 /* leaving only taggers that could apply, of which we use the ones, */
1679 for (tag_name = csp->action->multi[multi_action_index]->first;
1680 NULL != tag_name; tag_name = tag_name->next)
1682 /* that do apply, and */
1683 if (strcmp(b->name, tag_name->str) == 0)
1685 char *modified_tag = NULL;
1687 size_t size = header_length;
1688 pcrs_job *joblist = b->joblist;
1690 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1692 if (NULL == joblist)
1694 log_error(LOG_LEVEL_RE_FILTER,
1695 "Tagger %s has empty joblist. Nothing to do.", b->name);
1699 /* execute their pcrs_joblist on the header. */
1700 for (job = joblist; NULL != job; job = job->next)
1702 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
1706 /* Success, continue with the modified version. */
1715 /* Tagger doesn't match */
1718 /* Regex failure, log it but continue anyway. */
1719 log_error(LOG_LEVEL_ERROR,
1720 "Problems with tagger \'%s\' and header \'%s\': %s",
1721 b->name, *header, pcrs_strerror(hits));
1723 freez(modified_tag);
1727 if (b->dynamic) pcrs_free_joblist(joblist);
1729 /* If this tagger matched */
1735 * There is to technical limitation which makes
1736 * it impossible to use empty tags, but I assume
1737 * no one would do it intentionally.
1740 log_error(LOG_LEVEL_INFO,
1741 "Tagger \'%s\' created an empty tag. Ignored.",
1746 if (!list_contains_item(csp->tags, tag))
1748 if (JB_ERR_OK != enlist(csp->tags, tag))
1750 log_error(LOG_LEVEL_ERROR,
1751 "Insufficient memory to add tag \'%s\', "
1752 "based on tagger \'%s\' and header \'%s\'",
1753 tag, b->name, *header);
1757 char *action_message;
1759 * update the action bits right away, to make
1760 * tagging based on tags set by earlier taggers
1761 * of the same kind possible.
1763 if (update_action_bits_for_tag(csp, tag))
1765 action_message = "Action bits updated accordingly.";
1769 action_message = "No action bits update necessary.";
1772 log_error(LOG_LEVEL_HEADER,
1773 "Tagger \'%s\' added tag \'%s\'. %s",
1774 b->name, tag, action_message);
1779 /* XXX: Is this log-worthy? */
1780 log_error(LOG_LEVEL_HEADER,
1781 "Tagger \'%s\' didn't add tag \'%s\'. "
1782 "Tag already present", b->name, tag);
1785 } /* if the tagger matched */
1786 } /* if the tagger applies */
1787 } /* for every tagger that could apply */
1788 } /* for all filters */
1789 } /* for all filter files */
1794 /* here begins the family of parser functions that reformat header lines */
1796 /*********************************************************************
1798 * Function : filter_header
1800 * Description : Executes all text substitutions from all applying
1801 * +(server|client)-header-filter actions on the header.
1802 * Most of the code was copied from pcrs_filter_response,
1803 * including the rather short variable names
1806 * 1 : csp = Current client state (buffers, headers, etc...)
1807 * 2 : header = On input, pointer to header to modify.
1808 * On output, pointer to the modified header, or NULL
1809 * to remove the header. This function frees the
1810 * original string if necessary.
1812 * Returns : JB_ERR_OK on success and always succeeds
1814 *********************************************************************/
1815 static jb_err filter_header(struct client_state *csp, char **header)
1819 size_t size = strlen(*header);
1821 char *newheader = NULL;
1824 struct file_list *fl;
1825 struct re_filterfile_spec *b;
1826 struct list_entry *filtername;
1828 int i, found_filters = 0;
1829 int wanted_filter_type;
1830 int multi_action_index;
1832 if (csp->flags & CSP_FLAG_NO_FILTERING)
1837 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1839 wanted_filter_type = FT_SERVER_HEADER_FILTER;
1840 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
1844 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
1845 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
1849 * Need to check the set of re_filterfiles...
1851 for (i = 0; i < MAX_AF_FILES; i++)
1864 if (0 == found_filters)
1866 log_error(LOG_LEVEL_ERROR, "Unable to get current state of regexp filtering.");
1870 for (i = 0; i < MAX_AF_FILES; i++)
1873 if ((NULL == fl) || (NULL == fl->f))
1876 * Either there are no filter files
1877 * left, or this filter file just
1878 * contains no valid filters.
1880 * Continue to be sure we don't miss
1881 * valid filter files that are chained
1882 * after empty or invalid ones.
1887 * For all applying +filter actions, look if a filter by that
1888 * name exists and if yes, execute its pcrs_joblist on the
1891 for (b = fl->f; b; b = b->next)
1893 if (b->type != wanted_filter_type)
1895 /* Skip other filter types */
1899 for (filtername = csp->action->multi[multi_action_index]->first;
1900 filtername ; filtername = filtername->next)
1902 if (strcmp(b->name, filtername->str) == 0)
1904 int current_hits = 0;
1905 pcrs_job *joblist = b->joblist;
1907 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
1909 if (NULL == joblist)
1911 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
1915 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
1916 *header, size, b->name);
1918 /* Apply all jobs from the joblist */
1919 for (job = joblist; NULL != job; job = job->next)
1921 matches = pcrs_execute(job, *header, size, &newheader, &size);
1924 current_hits += matches;
1925 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
1927 *header = newheader;
1929 else if ( 0 == matches )
1931 /* Filter doesn't change header */
1937 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
1938 *header, b->name, pcrs_strerror(matches));
1939 if( newheader != NULL)
1941 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
1947 if (b->dynamic) pcrs_free_joblist(joblist);
1949 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
1950 hits += current_hits;
1957 * Additionally checking for hits is important because if
1958 * the continue hack is triggered, server headers can
1959 * arrive empty to separate multiple heads from each other.
1961 if ((0 == size) && hits)
1963 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
1971 /*********************************************************************
1973 * Function : connection
1975 * Description : Makes sure that the value of the Connection: header
1976 * is "close" and signals connection_close_adder
1980 * 1 : csp = Current client state (buffers, headers, etc...)
1981 * 2 : header = On input, pointer to header to modify.
1982 * On output, pointer to the modified header, or NULL
1983 * to remove the header. This function frees the
1984 * original string if necessary.
1986 * Returns : JB_ERR_OK on success, or
1987 * JB_ERR_MEMORY on out-of-memory error.
1989 *********************************************************************/
1990 static jb_err connection(struct client_state *csp, char **header)
1992 char *old_header = *header;
1994 /* Do we have a 'Connection: close' header? */
1995 if (strcmpic(*header, "Connection: close"))
1997 /* No, create one */
1998 *header = strdup("Connection: close");
2001 return JB_ERR_MEMORY;
2003 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2007 /* Signal connection_close_adder() to return early. */
2008 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2010 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2014 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET;
2021 /*********************************************************************
2023 * Function : crumble
2025 * Description : This is called if a header matches a pattern to "crunch"
2028 * 1 : csp = Current client state (buffers, headers, etc...)
2029 * 2 : header = On input, pointer to header to modify.
2030 * On output, pointer to the modified header, or NULL
2031 * to remove the header. This function frees the
2032 * original string if necessary.
2034 * Returns : JB_ERR_OK on success, or
2035 * JB_ERR_MEMORY on out-of-memory error.
2037 *********************************************************************/
2038 static jb_err crumble(struct client_state *csp, char **header)
2040 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2045 /*********************************************************************
2047 * Function : crunch_server_header
2049 * Description : Crunch server header if it matches a string supplied by the
2050 * user. Called from `sed'.
2053 * 1 : csp = Current client state (buffers, headers, etc...)
2054 * 2 : header = On input, pointer to header to modify.
2055 * On output, pointer to the modified header, or NULL
2056 * to remove the header. This function frees the
2057 * original string if necessary.
2059 * Returns : JB_ERR_OK on success and always succeeds
2061 *********************************************************************/
2062 static jb_err crunch_server_header(struct client_state *csp, char **header)
2064 const char *crunch_pattern;
2066 /* Do we feel like crunching? */
2067 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2069 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2071 /* Is the current header the lucky one? */
2072 if (strstr(*header, crunch_pattern))
2074 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2083 /*********************************************************************
2085 * Function : server_content_type
2087 * Description : Set the content-type for filterable types (text/.*,
2088 * .*xml.*, javascript and image/gif) unless filtering has been
2089 * forbidden (CT_TABOO) while parsing earlier headers.
2090 * NOTE: Since text/plain is commonly used by web servers
2091 * for files whose correct type is unknown, we don't
2092 * set CT_TEXT for it.
2095 * 1 : csp = Current client state (buffers, headers, etc...)
2096 * 2 : header = On input, pointer to header to modify.
2097 * On output, pointer to the modified header, or NULL
2098 * to remove the header. This function frees the
2099 * original string if necessary.
2101 * Returns : JB_ERR_OK on success, or
2102 * JB_ERR_MEMORY on out-of-memory error.
2104 *********************************************************************/
2105 static jb_err server_content_type(struct client_state *csp, char **header)
2107 /* Remove header if it isn't the first Content-Type header */
2108 if ((csp->content_type & CT_DECLARED))
2111 * Another, slightly slower, way to see if
2112 * we already parsed another Content-Type header.
2114 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2116 log_error(LOG_LEVEL_ERROR,
2117 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2125 * Signal that the Content-Type has been set.
2127 csp->content_type |= CT_DECLARED;
2129 if (!(csp->content_type & CT_TABOO))
2131 if ((strstr(*header, " text/") && !strstr(*header, "plain"))
2132 || strstr(*header, "xml")
2133 || strstr(*header, "application/x-javascript"))
2135 csp->content_type |= CT_TEXT;
2137 else if (strstr(*header, " image/gif"))
2139 csp->content_type |= CT_GIF;
2141 else if (strstr(*header, " image/jpeg"))
2143 csp->content_type |= CT_JPEG;
2148 * Are we messing with the content type?
2150 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2153 * Make sure the user doesn't accidently
2154 * change the content type of binary documents.
2156 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2159 *header = strdup("Content-Type: ");
2160 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2164 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2165 return JB_ERR_MEMORY;
2167 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2171 log_error(LOG_LEVEL_HEADER, "%s not replaced. It doesn't look like text. "
2172 "Enable force-text-mode if you know what you're doing.", *header);
2180 /*********************************************************************
2182 * Function : server_transfer_coding
2184 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2185 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2186 * - Remove header if body was chunked but has been
2187 * de-chunked for filtering.
2190 * 1 : csp = Current client state (buffers, headers, etc...)
2191 * 2 : header = On input, pointer to header to modify.
2192 * On output, pointer to the modified header, or NULL
2193 * to remove the header. This function frees the
2194 * original string if necessary.
2196 * Returns : JB_ERR_OK on success, or
2197 * JB_ERR_MEMORY on out-of-memory error.
2199 *********************************************************************/
2200 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2203 * Turn off pcrs and gif filtering if body compressed
2205 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2209 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2211 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2212 csp->http->cmd, *header);
2213 #endif /* def FEATURE_ZLIB */
2214 csp->content_type = CT_TABOO;
2218 * Raise flag if body chunked
2220 if (strstr(*header, "chunked"))
2222 csp->flags |= CSP_FLAG_CHUNKED;
2225 * If the body was modified, it has been de-chunked first
2226 * and the header must be removed.
2228 * FIXME: If there is more than one transfer encoding,
2229 * only the "chunked" part should be removed here.
2231 if (csp->flags & CSP_FLAG_MODIFIED)
2233 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2242 /*********************************************************************
2244 * Function : server_content_encoding
2246 * Description : This function is run twice for each request,
2247 * unless FEATURE_ZLIB and filtering are disabled.
2249 * The first run is used to check if the content
2250 * is compressed, if FEATURE_ZLIB is disabled
2251 * filtering is then disabled as well, if FEATURE_ZLIB
2252 * is enabled the content is marked for decompression.
2254 * The second run is used to remove the Content-Encoding
2255 * header if the decompression was successful.
2258 * 1 : csp = Current client state (buffers, headers, etc...)
2259 * 2 : header = On input, pointer to header to modify.
2260 * On output, pointer to the modified header, or NULL
2261 * to remove the header. This function frees the
2262 * original string if necessary.
2264 * Returns : JB_ERR_OK on success, or
2265 * JB_ERR_MEMORY on out-of-memory error.
2267 *********************************************************************/
2268 static jb_err server_content_encoding(struct client_state *csp, char **header)
2271 if ((csp->flags & CSP_FLAG_MODIFIED)
2272 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2275 * We successfully decompressed the content,
2276 * and have to clean the header now, so the
2277 * client no longer expects compressed data..
2279 * XXX: There is a difference between cleaning
2280 * and removing it completely.
2282 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2285 else if (strstr(*header, "gzip"))
2287 /* Mark for gzip decompression */
2288 csp->content_type |= CT_GZIP;
2290 else if (strstr(*header, "deflate"))
2292 /* Mark for zlib decompression */
2293 csp->content_type |= CT_DEFLATE;
2295 else if (strstr(*header, "compress"))
2298 * We can't decompress this; therefore we can't filter
2301 csp->content_type |= CT_TABOO;
2303 #else /* !defined(FEATURE_ZLIB) */
2304 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2307 * Body is compressed, turn off pcrs and gif filtering.
2309 csp->content_type |= CT_TABOO;
2312 * Log a warning if the user expects the content to be filtered.
2314 if ((csp->rlist != NULL) &&
2315 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2317 log_error(LOG_LEVEL_INFO,
2318 "Compressed content detected, content filtering disabled. "
2319 "Consider recompiling Privoxy with zlib support or "
2320 "enable the prevent-compression action.");
2323 #endif /* defined(FEATURE_ZLIB) */
2330 /*********************************************************************
2332 * Function : server_content_length
2334 * Description : Adjust Content-Length header if we modified
2338 * 1 : csp = Current client state (buffers, headers, etc...)
2339 * 2 : header = On input, pointer to header to modify.
2340 * On output, pointer to the modified header, or NULL
2341 * to remove the header. This function frees the
2342 * original string if necessary.
2344 * Returns : JB_ERR_OK on success, or
2345 * JB_ERR_MEMORY on out-of-memory error.
2347 *********************************************************************/
2348 static jb_err server_content_length(struct client_state *csp, char **header)
2350 const size_t max_header_length = 80;
2352 /* Regenerate header if the content was modified. */
2353 if (csp->flags & CSP_FLAG_MODIFIED)
2356 *header = (char *) zalloc(max_header_length);
2357 if (*header == NULL)
2359 return JB_ERR_MEMORY;
2362 snprintf(*header, max_header_length, "Content-Length: %d",
2363 (int)csp->content_length);
2364 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2365 (int)csp->content_length);
2372 /*********************************************************************
2374 * Function : server_content_md5
2376 * Description : Crumble any Content-MD5 headers if the document was
2377 * modified. FIXME: Should we re-compute instead?
2380 * 1 : csp = Current client state (buffers, headers, etc...)
2381 * 2 : header = On input, pointer to header to modify.
2382 * On output, pointer to the modified header, or NULL
2383 * to remove the header. This function frees the
2384 * original string if necessary.
2386 * Returns : JB_ERR_OK on success, or
2387 * JB_ERR_MEMORY on out-of-memory error.
2389 *********************************************************************/
2390 static jb_err server_content_md5(struct client_state *csp, char **header)
2392 if (csp->flags & CSP_FLAG_MODIFIED)
2394 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2401 /*********************************************************************
2403 * Function : server_content_disposition
2405 * Description : If enabled, blocks or modifies the "content-disposition" header.
2406 * Called from `sed'.
2409 * 1 : csp = Current client state (buffers, headers, etc...)
2410 * 2 : header = On input, pointer to header to modify.
2411 * On output, pointer to the modified header, or NULL
2412 * to remove the header. This function frees the
2413 * original string if necessary.
2415 * Returns : JB_ERR_OK on success, or
2416 * JB_ERR_MEMORY on out-of-memory error.
2418 *********************************************************************/
2419 static jb_err server_content_disposition(struct client_state *csp, char **header)
2424 * Are we messing with the content-disposition header?
2426 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2432 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2434 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2437 * Blocking content-disposition header
2439 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2446 * Replacing content-disposition header
2449 *header = strdup("content-disposition: ");
2450 string_append(header, newval);
2452 if (*header == NULL)
2454 log_error(LOG_LEVEL_HEADER, "Insufficent memory. content-disposition header not fully replaced.");
2458 log_error(LOG_LEVEL_HEADER, "content-disposition header crunched and replaced with: %s", *header);
2461 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2464 /*********************************************************************
2466 * Function : server_last_modified
2468 * Description : Changes Last-Modified header to the actual date
2469 * to help hide-if-modified-since.
2470 * Called from `sed'.
2473 * 1 : csp = Current client state (buffers, headers, etc...)
2474 * 2 : header = On input, pointer to header to modify.
2475 * On output, pointer to the modified header, or NULL
2476 * to remove the header. This function frees the
2477 * original string if necessary.
2479 * Returns : JB_ERR_OK on success, or
2480 * JB_ERR_MEMORY on out-of-memory error.
2482 *********************************************************************/
2483 static jb_err server_last_modified(struct client_state *csp, char **header)
2486 char buf[BUFFER_SIZE];
2489 #ifdef HAVE_GMTIME_R
2492 struct tm *timeptr = NULL;
2493 time_t now, last_modified;
2495 long int days, hours, minutes, seconds;
2498 * Are we messing with the Last-Modified header?
2500 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2506 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2508 if (0 == strcmpic(newval, "block") )
2511 * Blocking Last-Modified header. Useless but why not.
2513 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2517 else if (0 == strcmpic(newval, "reset-to-request-time"))
2520 * Setting Last-Modified Header to now.
2522 get_http_time(0, buf);
2524 *header = strdup("Last-Modified: ");
2525 string_append(header, buf);
2527 if (*header == NULL)
2529 log_error(LOG_LEVEL_HEADER, "Insufficent memory. Last-Modified header got lost, boohoo.");
2533 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2536 else if (0 == strcmpic(newval, "randomize"))
2538 const char *header_time = *header + sizeof("Last-Modified:");
2540 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2542 #ifdef HAVE_GMTIME_R
2543 timeptr = gmtime_r(&now, &gmt);
2544 #elif FEATURE_PTHREAD
2545 pthread_mutex_lock(&gmtime_mutex);
2546 timeptr = gmtime(&now);
2547 pthread_mutex_unlock(&gmtime_mutex);
2549 timeptr = gmtime(&now);
2551 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
2553 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
2558 rtime = (long int)difftime(now, last_modified);
2561 rtime = pick_from_range(rtime);
2562 last_modified += rtime;
2563 #ifdef HAVE_GMTIME_R
2564 timeptr = gmtime_r(&last_modified, &gmt);
2565 #elif FEATURE_PTHREAD
2566 pthread_mutex_lock(&gmtime_mutex);
2567 timeptr = gmtime(&last_modified);
2568 pthread_mutex_unlock(&gmtime_mutex);
2570 timeptr = gmtime(&last_modified);
2572 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
2574 *header = strdup("Last-Modified: ");
2575 string_append(header, newheader);
2577 if (*header == NULL)
2579 log_error(LOG_LEVEL_ERROR, "Insufficent memory, header crunched without replacement.");
2580 return JB_ERR_MEMORY;
2583 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
2585 days = rtime / (3600 * 24);
2586 hours = rtime / 3600 % 24;
2587 minutes = rtime / 60 % 60;
2588 seconds = rtime % 60;
2590 log_error(LOG_LEVEL_HEADER, "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
2591 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
2592 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
2597 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
2606 /*********************************************************************
2608 * Function : client_accept_encoding
2610 * Description : Rewrite the client's Accept-Encoding header so that
2611 * if doesn't allow compression, if the action applies.
2612 * Note: For HTTP/1.0 the absence of the header is enough.
2615 * 1 : csp = Current client state (buffers, headers, etc...)
2616 * 2 : header = On input, pointer to header to modify.
2617 * On output, pointer to the modified header, or NULL
2618 * to remove the header. This function frees the
2619 * original string if necessary.
2621 * Returns : JB_ERR_OK on success, or
2622 * JB_ERR_MEMORY on out-of-memory error.
2624 *********************************************************************/
2625 static jb_err client_accept_encoding(struct client_state *csp, char **header)
2627 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2629 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
2633 /* Temporarily disable the correct behaviour to
2634 * work around a PHP bug.
2636 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
2638 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
2639 * if (*header == NULL)
2641 * return JB_ERR_MEMORY;
2652 /*********************************************************************
2654 * Function : client_te
2656 * Description : Rewrite the client's TE header so that
2657 * if doesn't allow compression, if the action applies.
2660 * 1 : csp = Current client state (buffers, headers, etc...)
2661 * 2 : header = On input, pointer to header to modify.
2662 * On output, pointer to the modified header, or NULL
2663 * to remove the header. This function frees the
2664 * original string if necessary.
2666 * Returns : JB_ERR_OK on success, or
2667 * JB_ERR_MEMORY on out-of-memory error.
2669 *********************************************************************/
2670 static jb_err client_te(struct client_state *csp, char **header)
2672 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
2675 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
2682 /*********************************************************************
2684 * Function : client_referrer
2686 * Description : Handle the "referer" config setting properly.
2687 * Called from `sed'.
2690 * 1 : csp = Current client state (buffers, headers, etc...)
2691 * 2 : header = On input, pointer to header to modify.
2692 * On output, pointer to the modified header, or NULL
2693 * to remove the header. This function frees the
2694 * original string if necessary.
2696 * Returns : JB_ERR_OK on success, or
2697 * JB_ERR_MEMORY on out-of-memory error.
2699 *********************************************************************/
2700 static jb_err client_referrer(struct client_state *csp, char **header)
2702 const char *parameter;
2703 /* booleans for parameters we have to check multiple times */
2704 int parameter_conditional_block;
2705 int parameter_conditional_forge;
2707 #ifdef FEATURE_FORCE_LOAD
2709 * Since the referrer can include the prefix even
2710 * if the request itself is non-forced, we must
2711 * clean it unconditionally.
2713 * XXX: strclean is too broad
2715 strclean(*header, FORCE_PREFIX);
2716 #endif /* def FEATURE_FORCE_LOAD */
2718 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
2720 /* Nothing left to do */
2724 parameter = csp->action->string[ACTION_STRING_REFERER];
2725 assert(parameter != NULL);
2726 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
2727 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
2729 if (!parameter_conditional_block && !parameter_conditional_forge)
2732 * As conditional-block and conditional-forge are the only
2733 * parameters that rely on the original referrer, we can
2734 * remove it now for all the others.
2739 if (0 == strcmpic(parameter, "block"))
2741 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
2744 else if (parameter_conditional_block || parameter_conditional_forge)
2746 return handle_conditional_hide_referrer_parameter(header,
2747 csp->http->hostport, parameter_conditional_block);
2749 else if (0 == strcmpic(parameter, "forge"))
2751 return create_forged_referrer(header, csp->http->hostport);
2755 /* interpret parameter as user-supplied referer to fake */
2756 return create_fake_referrer(header, parameter);
2761 /*********************************************************************
2763 * Function : client_accept_language
2765 * Description : Handle the "Accept-Language" config setting properly.
2766 * Called from `sed'.
2769 * 1 : csp = Current client state (buffers, headers, etc...)
2770 * 2 : header = On input, pointer to header to modify.
2771 * On output, pointer to the modified header, or NULL
2772 * to remove the header. This function frees the
2773 * original string if necessary.
2775 * Returns : JB_ERR_OK on success, or
2776 * JB_ERR_MEMORY on out-of-memory error.
2778 *********************************************************************/
2779 static jb_err client_accept_language(struct client_state *csp, char **header)
2784 * Are we messing with the Accept-Language?
2786 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
2788 /*I don't think so*/
2792 newval = csp->action->string[ACTION_STRING_LANGUAGE];
2794 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2797 * Blocking Accept-Language header
2799 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
2806 * Replacing Accept-Language header
2809 *header = strdup("Accept-Language: ");
2810 string_append(header, newval);
2812 if (*header == NULL)
2814 log_error(LOG_LEVEL_ERROR,
2815 "Insufficent memory. Accept-Language header crunched without replacement.");
2819 log_error(LOG_LEVEL_HEADER,
2820 "Accept-Language header crunched and replaced with: %s", *header);
2823 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2827 /*********************************************************************
2829 * Function : crunch_client_header
2831 * Description : Crunch client header if it matches a string supplied by the
2832 * user. Called from `sed'.
2835 * 1 : csp = Current client state (buffers, headers, etc...)
2836 * 2 : header = On input, pointer to header to modify.
2837 * On output, pointer to the modified header, or NULL
2838 * to remove the header. This function frees the
2839 * original string if necessary.
2841 * Returns : JB_ERR_OK on success and always succeeds
2843 *********************************************************************/
2844 static jb_err crunch_client_header(struct client_state *csp, char **header)
2846 const char *crunch_pattern;
2848 /* Do we feel like crunching? */
2849 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
2851 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
2853 /* Is the current header the lucky one? */
2854 if (strstr(*header, crunch_pattern))
2856 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
2864 /*********************************************************************
2866 * Function : client_uagent
2868 * Description : Handle the "user-agent" config setting properly
2869 * and remember its original value to enable browser
2870 * bug workarounds. Called from `sed'.
2873 * 1 : csp = Current client state (buffers, headers, etc...)
2874 * 2 : header = On input, pointer to header to modify.
2875 * On output, pointer to the modified header, or NULL
2876 * to remove the header. This function frees the
2877 * original string if necessary.
2879 * Returns : JB_ERR_OK on success, or
2880 * JB_ERR_MEMORY on out-of-memory error.
2882 *********************************************************************/
2883 static jb_err client_uagent(struct client_state *csp, char **header)
2887 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
2892 newval = csp->action->string[ACTION_STRING_USER_AGENT];
2899 *header = strdup("User-Agent: ");
2900 string_append(header, newval);
2902 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
2904 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2907 /*********************************************************************
2909 * Function : client_ua
2911 * Description : Handle "ua-" headers properly. Called from `sed'.
2914 * 1 : csp = Current client state (buffers, headers, etc...)
2915 * 2 : header = On input, pointer to header to modify.
2916 * On output, pointer to the modified header, or NULL
2917 * to remove the header. This function frees the
2918 * original string if necessary.
2920 * Returns : JB_ERR_OK on success, or
2921 * JB_ERR_MEMORY on out-of-memory error.
2923 *********************************************************************/
2924 static jb_err client_ua(struct client_state *csp, char **header)
2926 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
2928 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
2936 /*********************************************************************
2938 * Function : client_from
2940 * Description : Handle the "from" config setting properly.
2941 * Called from `sed'.
2944 * 1 : csp = Current client state (buffers, headers, etc...)
2945 * 2 : header = On input, pointer to header to modify.
2946 * On output, pointer to the modified header, or NULL
2947 * to remove the header. This function frees the
2948 * original string if necessary.
2950 * Returns : JB_ERR_OK on success, or
2951 * JB_ERR_MEMORY on out-of-memory error.
2953 *********************************************************************/
2954 static jb_err client_from(struct client_state *csp, char **header)
2958 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
2965 newval = csp->action->string[ACTION_STRING_FROM];
2968 * Are we blocking the e-mail address?
2970 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
2972 log_error(LOG_LEVEL_HEADER, "crunched From!");
2976 log_error(LOG_LEVEL_HEADER, " modified");
2978 *header = strdup("From: ");
2979 string_append(header, newval);
2981 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2985 /*********************************************************************
2987 * Function : client_send_cookie
2989 * Description : Crunches the "cookie" header if necessary.
2990 * Called from `sed'.
2992 * XXX: Stupid name, doesn't send squat.
2995 * 1 : csp = Current client state (buffers, headers, etc...)
2996 * 2 : header = On input, pointer to header to modify.
2997 * On output, pointer to the modified header, or NULL
2998 * to remove the header. This function frees the
2999 * original string if necessary.
3001 * Returns : JB_ERR_OK on success, or
3002 * JB_ERR_MEMORY on out-of-memory error.
3004 *********************************************************************/
3005 static jb_err client_send_cookie(struct client_state *csp, char **header)
3007 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3009 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3017 /*********************************************************************
3019 * Function : client_x_forwarded
3021 * Description : Handle the "x-forwarded-for" config setting properly,
3022 * also used in the add_client_headers list. Called from `sed'.
3025 * 1 : csp = Current client state (buffers, headers, etc...)
3026 * 2 : header = On input, pointer to header to modify.
3027 * On output, pointer to the modified header, or NULL
3028 * to remove the header. This function frees the
3029 * original string if necessary.
3031 * Returns : JB_ERR_OK on success, or
3032 * JB_ERR_MEMORY on out-of-memory error.
3034 *********************************************************************/
3035 jb_err client_x_forwarded(struct client_state *csp, char **header)
3037 if ((csp->action->flags & ACTION_HIDE_FORWARDED) == 0)
3039 /* Save it so we can re-add it later */
3040 freez(csp->x_forwarded);
3041 csp->x_forwarded = *header;
3044 * Always set *header = NULL, since this information
3045 * will be sent at the end of the header.
3052 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3059 /*********************************************************************
3061 * Function : client_max_forwards
3063 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3064 * from the value of the Max-Forwards header field.
3067 * 1 : csp = Current client state (buffers, headers, etc...)
3068 * 2 : header = On input, pointer to header to modify.
3069 * On output, pointer to the modified header, or NULL
3070 * to remove the header. This function frees the
3071 * original string if necessary.
3073 * Returns : JB_ERR_OK on success, or
3074 * JB_ERR_MEMORY on out-of-memory error.
3076 *********************************************************************/
3077 static jb_err client_max_forwards(struct client_state *csp, char **header)
3081 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3082 (0 == strcmpic(csp->http->gpc, "options")))
3084 assert(*(*header+12) == ':');
3085 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3087 if (max_forwards > 0)
3089 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3090 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3091 csp->http->gpc, max_forwards);
3093 else if (max_forwards < 0)
3095 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3101 * Not supposed to be reached. direct_response() which
3102 * was already called earlier in chat() should have
3103 * intercepted the request.
3105 log_error(LOG_LEVEL_ERROR,
3106 "Non-intercepted %s request with Max-Forwards zero!", csp->http->gpc);
3107 assert(max_forwards != 0);
3112 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3121 /*********************************************************************
3123 * Function : client_host
3125 * Description : If the request URI did not contain host and
3126 * port information, parse and evaluate the Host
3129 * Also, kill ill-formed HOST: headers as sent by
3130 * Apple's iTunes software when used with a proxy.
3133 * 1 : csp = Current client state (buffers, headers, etc...)
3134 * 2 : header = On input, pointer to header to modify.
3135 * On output, pointer to the modified header, or NULL
3136 * to remove the header. This function frees the
3137 * original string if necessary.
3139 * Returns : JB_ERR_OK on success, or
3140 * JB_ERR_MEMORY on out-of-memory error.
3142 *********************************************************************/
3143 static jb_err client_host(struct client_state *csp, char **header)
3148 * If the header field name is all upper-case, chances are that it's
3149 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3150 * not a problem -- they are regenerated later.
3152 if ((*header)[1] == 'O')
3154 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3159 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3160 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3163 if (NULL == (p = strdup((*header)+6)))
3165 return JB_ERR_MEMORY;
3168 if (NULL == (q = strdup(p)))
3171 return JB_ERR_MEMORY;
3174 freez(csp->http->hostport);
3175 csp->http->hostport = p;
3176 freez(csp->http->host);
3177 csp->http->host = q;
3178 q = strchr(csp->http->host, ':');
3181 /* Terminate hostname and evaluate port string */
3183 csp->http->port = atoi(q);
3187 csp->http->port = csp->http->ssl ? 443 : 80;
3190 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3191 csp->http->hostport, csp->http->host, csp->http->port);
3194 /* Signal client_host_adder() to return right away */
3195 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3200 /*********************************************************************
3202 * Function : client_if_modified_since
3204 * Description : Remove or modify the If-Modified-Since header.
3207 * 1 : csp = Current client state (buffers, headers, etc...)
3208 * 2 : header = On input, pointer to header to modify.
3209 * On output, pointer to the modified header, or NULL
3210 * to remove the header. This function frees the
3211 * original string if necessary.
3213 * Returns : JB_ERR_OK on success, or
3214 * JB_ERR_MEMORY on out-of-memory error.
3216 *********************************************************************/
3217 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3220 #ifdef HAVE_GMTIME_R
3223 struct tm *timeptr = NULL;
3227 long int hours, minutes, seconds;
3231 if ( 0 == strcmpic(*header, "If-Modified-Since: Wed, 08 Jun 1955 12:00:00 GMT"))
3234 * The client got an error message because of a temporary problem,
3235 * the problem is gone and the client now tries to revalidate our
3236 * error message on the real server. The revalidation would always
3237 * end with the transmission of the whole document and there is
3238 * no need to expose the bogus If-Modified-Since header.
3240 log_error(LOG_LEVEL_HEADER, "Crunching useless If-Modified-Since header.");
3243 else if (csp->action->flags & ACTION_HIDE_IF_MODIFIED_SINCE)
3245 newval = csp->action->string[ACTION_STRING_IF_MODIFIED_SINCE];
3247 if ((0 == strcmpic(newval, "block")))
3249 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3252 else /* add random value */
3254 const char *header_time = *header + sizeof("If-Modified-Since:");
3256 if (JB_ERR_OK != parse_header_time(header_time, &tm))
3258 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3263 rtime = strtol(newval, &endptr, 0);
3266 log_error(LOG_LEVEL_HEADER, "Randomizing: %s (random range: %d minut%s)",
3267 *header, rtime, (rtime == 1 || rtime == -1) ? "e": "es");
3274 rtime = pick_from_range(rtime);
3278 log_error(LOG_LEVEL_ERROR, "Random range is 0. Assuming time transformation test.",
3281 tm += rtime * (negative ? -1 : 1);
3282 #ifdef HAVE_GMTIME_R
3283 timeptr = gmtime_r(&tm, &gmt);
3284 #elif FEATURE_PTHREAD
3285 pthread_mutex_lock(&gmtime_mutex);
3286 timeptr = gmtime(&tm);
3287 pthread_mutex_unlock(&gmtime_mutex);
3289 timeptr = gmtime(&tm);
3291 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3294 *header = strdup("If-Modified-Since: ");
3295 string_append(header, newheader);
3297 if (*header == NULL)
3299 log_error(LOG_LEVEL_HEADER, "Insufficent memory, header crunched without replacement.");
3300 return JB_ERR_MEMORY;
3303 if(LOG_LEVEL_HEADER & debug) /* Save cycles if the user isn't interested. */
3305 hours = rtime / 3600;
3306 minutes = rtime / 60 % 60;
3307 seconds = rtime % 60;
3309 log_error(LOG_LEVEL_HEADER, "Randomized: %s (%s %d hou%s %d minut%s %d second%s",
3310 *header, (negative) ? "subtracted" : "added", hours, (hours == 1) ? "r" : "rs",
3311 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3320 /*********************************************************************
3322 * Function : client_if_none_match
3324 * Description : Remove the If-None-Match header.
3327 * 1 : csp = Current client state (buffers, headers, etc...)
3328 * 2 : header = On input, pointer to header to modify.
3329 * On output, pointer to the modified header, or NULL
3330 * to remove the header. This function frees the
3331 * original string if necessary.
3333 * Returns : JB_ERR_OK on success, or
3334 * JB_ERR_MEMORY on out-of-memory error.
3336 *********************************************************************/
3337 static jb_err client_if_none_match(struct client_state *csp, char **header)
3339 if (csp->action->flags & ACTION_CRUNCH_IF_NONE_MATCH)
3341 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3348 /*********************************************************************
3350 * Function : client_x_filter
3352 * Description : Disables filtering if the client set "X-Filter: No".
3353 * Called from `sed'.
3356 * 1 : csp = Current client state (buffers, headers, etc...)
3357 * 2 : header = On input, pointer to header to modify.
3358 * On output, pointer to the modified header, or NULL
3359 * to remove the header. This function frees the
3360 * original string if necessary.
3362 * Returns : JB_ERR_OK on success
3364 *********************************************************************/
3365 jb_err client_x_filter(struct client_state *csp, char **header)
3367 if ( 0 == strcmpic(*header, "X-Filter: No"))
3369 if (!(csp->config->feature_flags & RUNTIME_FEATURE_HTTP_TOGGLE))
3371 log_error(LOG_LEVEL_INFO, "Ignored the client's request to fetch without filtering.");
3375 if (csp->action->flags & ACTION_FORCE_TEXT_MODE)
3377 log_error(LOG_LEVEL_HEADER,
3378 "force-text-mode overruled the client's request to fetch without filtering!");
3382 csp->content_type = CT_TABOO; /* XXX: This hack shouldn't be necessary */
3383 csp->flags |= CSP_FLAG_NO_FILTERING;
3384 log_error(LOG_LEVEL_HEADER, "Accepted the client's request to fetch without filtering.");
3386 log_error(LOG_LEVEL_HEADER, "Crunching %s", *header);
3393 /* the following functions add headers directly to the header list */
3395 /*********************************************************************
3397 * Function : client_host_adder
3399 * Description : Adds the Host: header field if it is missing.
3400 * Called from `sed'.
3403 * 1 : csp = Current client state (buffers, headers, etc...)
3405 * Returns : JB_ERR_OK on success, or
3406 * JB_ERR_MEMORY on out-of-memory error.
3408 *********************************************************************/
3409 static jb_err client_host_adder(struct client_state *csp)
3414 if (csp->flags & CSP_FLAG_HOST_HEADER_IS_SET)
3416 /* Header already set by the client, nothing to do. */
3420 if ( !csp->http->hostport || !*(csp->http->hostport))
3422 /* XXX: When does this happen and why is it OK? */
3423 log_error(LOG_LEVEL_INFO, "Weirdness in client_host_adder detected and ignored.");
3428 * remove 'user:pass@' from 'proto://user:pass@host'
3430 if ( (p = strchr( csp->http->hostport, '@')) != NULL )
3436 p = csp->http->hostport;
3439 /* XXX: Just add it, we already made sure that it will be unique */
3440 log_error(LOG_LEVEL_HEADER, "addh-unique: Host: %s", p);
3441 err = enlist_unique_header(csp->headers, "Host", p);
3447 /*********************************************************************
3449 * Function : client_cookie_adder
3451 * Description : Used in the add_client_headers list to add "wafers".
3452 * Called from `sed'.
3455 * 1 : csp = Current client state (buffers, headers, etc...)
3457 * Returns : JB_ERR_OK on success, or
3458 * JB_ERR_MEMORY on out-of-memory error.
3460 *********************************************************************/
3461 jb_err client_cookie_adder(struct client_state *csp)
3464 struct list_entry *wafer;
3465 struct list_entry *wafer_list = csp->action->multi[ACTION_MULTI_WAFER]->first;
3468 if (NULL == wafer_list)
3474 tmp = strdup("Cookie: ");
3476 for (wafer = wafer_list; (NULL != tmp) && (NULL != wafer); wafer = wafer->next)
3478 if (wafer != wafer_list)
3480 /* As this isn't the first wafer, we need a delimiter. */
3481 string_append(&tmp, "; ");
3483 string_join(&tmp, cookie_encode(wafer->str));
3488 return JB_ERR_MEMORY;
3491 log_error(LOG_LEVEL_HEADER, "addh: %s", tmp);
3492 err = enlist(csp->headers, tmp);
3499 /*********************************************************************
3501 * Function : client_accept_encoding_adder
3503 * Description : Add an Accept-Encoding header to the client's request
3504 * that disables compression if the action applies, and
3505 * the header is not already there. Called from `sed'.
3506 * Note: For HTTP/1.0, the absence of the header is enough.
3509 * 1 : csp = Current client state (buffers, headers, etc...)
3511 * Returns : JB_ERR_OK on success, or
3512 * JB_ERR_MEMORY on out-of-memory error.
3514 *********************************************************************/
3515 static jb_err client_accept_encoding_adder(struct client_state *csp)
3517 if ( ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3518 && (!strcmpic(csp->http->ver, "HTTP/1.1")) )
3520 return enlist_unique(csp->headers, "Accept-Encoding: identity;q=1.0, *;q=0", 16);
3528 /*********************************************************************
3530 * Function : client_xtra_adder
3532 * Description : Used in the add_client_headers list. Called from `sed'.
3535 * 1 : csp = Current client state (buffers, headers, etc...)
3537 * Returns : JB_ERR_OK on success, or
3538 * JB_ERR_MEMORY on out-of-memory error.
3540 *********************************************************************/
3541 static jb_err client_xtra_adder(struct client_state *csp)
3543 struct list_entry *lst;
3546 for (lst = csp->action->multi[ACTION_MULTI_ADD_HEADER]->first;
3547 lst ; lst = lst->next)
3549 log_error(LOG_LEVEL_HEADER, "addh: %s", lst->str);
3550 err = enlist(csp->headers, lst->str);
3562 /*********************************************************************
3564 * Function : client_x_forwarded_adder
3566 * Description : Used in the add_client_headers list. Called from `sed'.
3569 * 1 : csp = Current client state (buffers, headers, etc...)
3571 * Returns : JB_ERR_OK on success, or
3572 * JB_ERR_MEMORY on out-of-memory error.
3574 *********************************************************************/
3575 static jb_err client_x_forwarded_adder(struct client_state *csp)
3580 if ((csp->action->flags & ACTION_HIDE_FORWARDED) != 0)
3585 if (csp->x_forwarded)
3587 p = strdup(csp->x_forwarded);
3588 string_append(&p, ", ");
3592 p = strdup("X-Forwarded-For: ");
3594 string_append(&p, csp->ip_addr_str);
3598 return JB_ERR_MEMORY;
3601 log_error(LOG_LEVEL_HEADER, "addh: %s", p);
3602 err = enlist(csp->headers, p);
3609 /*********************************************************************
3611 * Function : connection_close_adder
3613 * Description : "Temporary" fix for the needed but missing HTTP/1.1
3614 * support. Adds a "Connection: close" header to csp->headers
3615 * unless the header was already present. Called from `sed'.
3617 * FIXME: This whole function shouldn't be neccessary!
3620 * 1 : csp = Current client state (buffers, headers, etc...)
3622 * Returns : JB_ERR_OK on success, or
3623 * JB_ERR_MEMORY on out-of-memory error.
3625 *********************************************************************/
3626 static jb_err connection_close_adder(struct client_state *csp)
3628 const unsigned int flags = csp->flags;
3631 * Return right away if
3633 * - we're parsing server headers and the server header
3634 * "Connection: close" is already set, or if
3636 * - we're parsing client headers and the client header
3637 * "Connection: close" is already set.
3639 if ((flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE
3640 && flags & CSP_FLAG_SERVER_CONNECTION_CLOSE_SET)
3641 ||(!(flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
3642 && flags & CSP_FLAG_CLIENT_CONNECTION_CLOSE_SET))
3647 log_error(LOG_LEVEL_HEADER, "Adding: Connection: close");
3649 return enlist(csp->headers, "Connection: close");
3653 /*********************************************************************
3655 * Function : server_http
3657 * Description : - Save the HTTP Status into csp->http->status
3658 * - Set CT_TABOO to prevent filtering if the answer
3659 * is a partial range (HTTP status 206)
3660 * - Rewrite HTTP/1.1 answers to HTTP/1.0 if +downgrade
3664 * 1 : csp = Current client state (buffers, headers, etc...)
3665 * 2 : header = On input, pointer to header to modify.
3666 * On output, pointer to the modified header, or NULL
3667 * to remove the header. This function frees the
3668 * original string if necessary.
3670 * Returns : JB_ERR_OK on success, or
3671 * JB_ERR_MEMORY on out-of-memory error.
3673 *********************************************************************/
3674 static jb_err server_http(struct client_state *csp, char **header)
3676 sscanf(*header, "HTTP/%*d.%*d %d", &(csp->http->status));
3677 if (csp->http->status == 206)
3679 csp->content_type = CT_TABOO;
3682 if ((csp->action->flags & ACTION_DOWNGRADE) != 0)
3684 /* XXX: Should we do a real validity check here? */
3685 if (strlen(*header) > 8)
3688 log_error(LOG_LEVEL_HEADER, "Downgraded answer to HTTP/1.0");
3693 * XXX: Should we block the request or
3694 * enlist a valid status code line here?
3696 log_error(LOG_LEVEL_INFO, "Malformed server response detected. "
3697 "Downgrading to HTTP/1.0 impossible.");
3705 /*********************************************************************
3707 * Function : server_set_cookie
3709 * Description : Handle the server "cookie" header properly.
3710 * Log cookie to the jar file. Then "crunch",
3711 * accept or rewrite it to a session cookie.
3712 * Called from `sed'.
3714 * TODO: Allow the user to specify a new expiration
3715 * time to cause the cookie to expire even before the
3716 * browser is closed.
3719 * 1 : csp = Current client state (buffers, headers, etc...)
3720 * 2 : header = On input, pointer to header to modify.
3721 * On output, pointer to the modified header, or NULL
3722 * to remove the header. This function frees the
3723 * original string if necessary.
3725 * Returns : JB_ERR_OK on success, or
3726 * JB_ERR_MEMORY on out-of-memory error.
3728 *********************************************************************/
3729 static jb_err server_set_cookie(struct client_state *csp, char **header)
3736 #ifdef FEATURE_COOKIE_JAR
3737 if (csp->config->jar)
3740 * Write timestamp into outbuf.
3742 * Complex because not all OSs have tm_gmtoff or
3743 * the %z field in strftime()
3745 char tempbuf[ BUFFER_SIZE ];
3747 #ifdef HAVE_LOCALTIME_R
3748 tm_now = *localtime_r(&now, &tm_now);
3749 #elif FEATURE_PTHREAD
3750 pthread_mutex_lock(&localtime_mutex);
3751 tm_now = *localtime (&now);
3752 pthread_mutex_unlock(&localtime_mutex);
3754 tm_now = *localtime (&now);
3756 strftime(tempbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now);
3758 /* strlen("set-cookie: ") = 12 */
3759 fprintf(csp->config->jar, "%s %s\t%s\n", tempbuf, csp->http->host, *header + 12);
3761 #endif /* def FEATURE_COOKIE_JAR */
3763 if ((csp->action->flags & ACTION_NO_COOKIE_SET) != 0)
3765 log_error(LOG_LEVEL_HEADER, "Crunching incoming cookie: %s", *header);
3768 else if ((csp->action->flags & ACTION_NO_COOKIE_KEEP) != 0)
3770 /* Flag whether or not to log a message */
3773 /* A variable to store the tag we're working on */
3776 /* Skip "Set-Cookie:" (11 characters) in header */
3777 cur_tag = *header + 11;
3779 /* skip whitespace between "Set-Cookie:" and value */
3780 while (*cur_tag && ijb_isspace(*cur_tag))
3785 /* Loop through each tag in the cookie */
3789 char *next_tag = strchr(cur_tag, ';');
3790 if (next_tag != NULL)
3792 /* Skip the ';' character itself */
3795 /* skip whitespace ";" and start of tag */
3796 while (*next_tag && ijb_isspace(*next_tag))
3803 /* "Next tag" is the end of the string */
3804 next_tag = cur_tag + strlen(cur_tag);
3808 * Check the expiration date to see
3809 * if the cookie is still valid, if yes,
3810 * rewrite it to a session cookie.
3812 if ((strncmpic(cur_tag, "expires=", 8) == 0) && *(cur_tag + 8))
3814 char *expiration_date = cur_tag + 8; /* Skip "[Ee]xpires=" */
3816 /* Did we detect the date properly? */
3817 if (JB_ERR_OK != parse_header_time(expiration_date, &cookie_time))
3820 * Nope, treat it as if it was still valid.
3822 * XXX: Should we remove the whole cookie instead?
3824 log_error(LOG_LEVEL_ERROR,
3825 "Can't parse \'%s\', send by %s. Unsupported time format?", cur_tag, csp->http->url);
3826 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3832 * Yes. Check if the cookie is still valid.
3834 * If the cookie is already expired it's probably
3835 * a delete cookie and even if it isn't, the browser
3836 * will discard it anyway.
3840 * XXX: timegm() isn't available on some AmigaOS
3841 * versions and our replacement doesn't work.
3843 * Our options are to either:
3845 * - disable session-cookies-only completely if timegm
3848 * - to simply remove all expired tags, like it has
3849 * been done until Privoxy 3.0.6 and to live with
3850 * the consequence that it can cause login/logout
3851 * problems on servers that don't validate their
3852 * input properly, or
3854 * - to replace it with mktime in which
3855 * case there is a slight chance of valid cookies
3856 * passing as already expired.
3858 * This is the way it's currently done and it's not
3859 * as bad as it sounds. If the missing GMT offset is
3860 * enough to change the result of the expiration check
3861 * the cookie will be only valid for a few hours
3862 * anyway, which in many cases will be shorter
3863 * than a browser session.
3865 if (cookie_time - now < 0)
3867 log_error(LOG_LEVEL_HEADER,
3868 "Cookie \'%s\' is already expired and can pass unmodified.", *header);
3869 /* Just in case some clown sets more then one expiration date */
3875 * Still valid, delete expiration date by copying
3876 * the rest of the string over it.
3878 * (Note that we cannot just use "strcpy(cur_tag, next_tag)",
3879 * since the behaviour of strcpy is undefined for overlapping
3882 memmove(cur_tag, next_tag, strlen(next_tag) + 1);
3884 /* That changed the header, need to issue a log message */
3888 * Note that the next tag has now been moved to *cur_tag,
3889 * so we do not need to update the cur_tag pointer.
3897 /* Move on to next cookie tag */
3904 assert(NULL != *header);
3905 log_error(LOG_LEVEL_HEADER, "Cookie rewritten to a temporary one: %s",
3914 #ifdef FEATURE_FORCE_LOAD
3915 /*********************************************************************
3917 * Function : strclean
3919 * Description : In-Situ-Eliminate all occurances of substring in
3923 * 1 : string = string to clean
3924 * 2 : substring = substring to eliminate
3926 * Returns : Number of eliminations
3928 *********************************************************************/
3929 int strclean(const char *string, const char *substring)
3935 len = strlen(substring);
3937 while((pos = strstr(string, substring)) != NULL)
3944 while (*p++ != '\0');
3951 #endif /* def FEATURE_FORCE_LOAD */
3953 /*********************************************************************
3955 * Function : parse_header_time
3957 * Description : Parses time formats used in HTTP header strings
3958 * to get the numerical respresentation.
3961 * 1 : header_time = HTTP header time as string.
3962 * 2 : result = storage for header_time in seconds
3964 * Returns : JB_ERR_OK if the time format was recognized, or
3965 * JB_ERR_PARSE otherwise.
3967 *********************************************************************/
3968 static jb_err parse_header_time(const char *header_time, time_t *result)
3973 * Zero out gmt to prevent time zone offsets.
3975 * While this is only necessary on some platforms
3976 * (mingw32 for example), I don't know how to
3977 * detect these automatically and doing it everywhere
3980 memset(&gmt, 0, sizeof(gmt));
3982 /* Tue, 02 Jun 2037 20:00:00 */
3983 if ((NULL == strptime(header_time, "%a, %d %b %Y %H:%M:%S", &gmt))
3984 /* Tue, 02-Jun-2037 20:00:00 */
3985 && (NULL == strptime(header_time, "%a, %d-%b-%Y %H:%M:%S", &gmt))
3986 /* Tue, 02-Jun-37 20:00:00 */
3987 && (NULL == strptime(header_time, "%a, %d-%b-%y %H:%M:%S", &gmt))
3988 /* Tuesday, 02-Jun-2037 20:00:00 */
3989 && (NULL == strptime(header_time, "%A, %d-%b-%Y %H:%M:%S", &gmt))
3990 /* Tuesday Jun 02 20:00:00 2037 */
3991 && (NULL == strptime(header_time, "%A %b %d %H:%M:%S %Y", &gmt)))
3993 return JB_ERR_PARSE;
3996 *result = timegm(&gmt);
4002 /*********************************************************************
4004 * Function : get_destination_from_headers
4006 * Description : Parse the "Host:" header to get the request's destination.
4007 * Only needed if the client's request was forcefully
4008 * redirected into Privoxy.
4010 * Code mainly copied from client_host() which is currently
4011 * run too late for this purpose.
4014 * 1 : headers = List of headers (one of them hopefully being
4015 * the "Host:" header)
4016 * 2 : http = storage for the result (host, port and hostport).
4018 * Returns : JB_ERR_MEMORY in case of memory problems,
4019 * JB_ERR_PARSE if the host header couldn't be found,
4020 * JB_ERR_OK otherwise.
4022 *********************************************************************/
4023 jb_err get_destination_from_headers(const struct list *headers, struct http_request *http)
4029 host = get_header_value(headers, "Host:");
4033 log_error(LOG_LEVEL_ERROR, "No \"Host:\" header found.");
4034 return JB_ERR_PARSE;
4037 if (NULL == (p = strdup((host))))
4039 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4040 return JB_ERR_MEMORY;
4043 if (NULL == (q = strdup(p)))
4046 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing \"Host:\" header");
4047 return JB_ERR_MEMORY;
4050 freez(http->hostport);
4054 q = strchr(http->host, ':');
4057 /* Terminate hostname and evaluate port string */
4059 http->port = atoi(q);
4063 http->port = http->ssl ? 443 : 80;
4066 /* Rebuild request URL */
4068 http->url = strdup(http->ssl ? "https://" : "http://");
4069 string_append(&http->url, http->hostport);
4070 string_append(&http->url, http->path);
4071 if (http->url == NULL)
4073 return JB_ERR_MEMORY;
4076 log_error(LOG_LEVEL_HEADER, "Destination extracted from \"Host:\" header. New request URL: %s",
4084 /*********************************************************************
4086 * Function : create_forged_referrer
4088 * Description : Helper for client_referrer to forge a referer as
4089 * 'http://[hostname:port/' to fool stupid
4090 * checks for in-site links
4093 * 1 : header = Pointer to header pointer
4094 * 2 : hostport = Host and optionally port as string
4096 * Returns : JB_ERR_OK in case of success, or
4097 * JB_ERR_MEMORY in case of memory problems.
4099 *********************************************************************/
4100 static jb_err create_forged_referrer(char **header, const char *hostport)
4102 assert(NULL == *header);
4104 *header = strdup("Referer: http://");
4105 string_append(header, hostport);
4106 string_append(header, "/");
4108 if (NULL == *header)
4110 return JB_ERR_MEMORY;
4113 log_error(LOG_LEVEL_HEADER, "Referer forged to: %s", *header);
4120 /*********************************************************************
4122 * Function : create_fake_referrer
4124 * Description : Helper for client_referrer to create a fake referrer
4125 * based on a string supplied by the user.
4128 * 1 : header = Pointer to header pointer
4129 * 2 : hosthost = Referrer to fake
4131 * Returns : JB_ERR_OK in case of success, or
4132 * JB_ERR_MEMORY in case of memory problems.
4134 *********************************************************************/
4135 static jb_err create_fake_referrer(char **header, const char *fake_referrer)
4137 assert(NULL == *header);
4139 if ((0 != strncmpic(fake_referrer, "http://", 7)) && (0 != strncmpic(fake_referrer, "https://", 8)))
4141 log_error(LOG_LEVEL_HEADER,
4142 "Parameter: +hide-referrer{%s} is a bad idea, but I don't care.", fake_referrer);
4144 *header = strdup("Referer: ");
4145 string_append(header, fake_referrer);
4147 if (NULL == *header)
4149 return JB_ERR_MEMORY;
4152 log_error(LOG_LEVEL_HEADER, "Referer replaced with: %s", *header);
4159 /*********************************************************************
4161 * Function : handle_conditional_hide_referrer_parameter
4163 * Description : Helper for client_referrer to crunch or forge
4164 * the referrer header if the host has changed.
4167 * 1 : header = Pointer to header pointer
4168 * 2 : host = The target host (may include the port)
4169 * 3 : parameter_conditional_block = Boolean to signal
4170 * if we're in conditional-block mode. If not set,
4171 * we're in conditional-forge mode.
4173 * Returns : JB_ERR_OK in case of success, or
4174 * JB_ERR_MEMORY in case of memory problems.
4176 *********************************************************************/
4177 static jb_err handle_conditional_hide_referrer_parameter(char **header,
4178 const char *host, const int parameter_conditional_block)
4180 char *referer = strdup(*header);
4181 const size_t hostlenght = strlen(host);
4183 if (NULL == referer)
4186 return JB_ERR_MEMORY;
4189 /* referer begins with 'Referer: http[s]://' */
4190 if (hostlenght < (strlen(referer)-17))
4193 * Shorten referer to make sure the referer is blocked
4194 * if www.example.org/www.example.com-shall-see-the-referer/
4195 * links to www.example.com/
4197 referer[hostlenght+17] = '\0';
4199 if (NULL == strstr(referer, host))
4201 /* Host has changed */
4202 if (parameter_conditional_block)
4204 log_error(LOG_LEVEL_HEADER, "New host is: %s. Crunching %s!", host, *header);
4211 return create_forged_referrer(header, host);