1 const char parsers_rcs[] = "$Id: parsers.c,v 1.147 2008/11/04 17:20:31 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-2008 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.147 2008/11/04 17:20:31 fabiankeil
48 * HTTP/1.1 responses without Connection
49 * header imply keep-alive. Act accordingly.
51 * Revision 1.146 2008/10/12 16:46:35 fabiankeil
52 * Remove obsolete warning about delayed delivery with chunked
53 * transfer encoding and FEATURE_CONNECTION_KEEP_ALIVE enabled.
55 * Revision 1.145 2008/10/09 18:21:41 fabiankeil
56 * Flush work-in-progress changes to keep outgoing connections
57 * alive where possible. Incomplete and mostly #ifdef'd out.
59 * Revision 1.144 2008/09/21 13:59:33 fabiankeil
60 * Treat unknown change-x-forwarded-for parameters as fatal errors.
62 * Revision 1.143 2008/09/21 13:36:52 fabiankeil
63 * If change-x-forwarded-for{add} is used and the client
64 * sends multiple X-Forwarded-For headers, append the client's
65 * IP address to each one of them. "Traditionally" we would
66 * lose all but the last one.
68 * Revision 1.142 2008/09/20 10:04:33 fabiankeil
69 * Remove hide-forwarded-for-headers action which has
70 * been obsoleted by change-x-forwarded-for{block}.
72 * Revision 1.141 2008/09/19 15:26:28 fabiankeil
73 * Add change-x-forwarded-for{} action to block or add
74 * X-Forwarded-For headers. Mostly based on code removed
77 * Revision 1.140 2008/09/12 17:51:43 fabiankeil
78 * - A few style fixes.
79 * - Remove a pointless cast.
81 * Revision 1.139 2008/09/04 08:13:58 fabiankeil
82 * Prepare for critical sections on Windows by adding a
83 * layer of indirection before the pthread mutex functions.
85 * Revision 1.138 2008/08/30 12:03:07 fabiankeil
86 * Remove FEATURE_COOKIE_JAR.
88 * Revision 1.137 2008/05/30 15:50:08 fabiankeil
89 * Remove questionable micro-optimizations
90 * whose usefulness has never been measured.
92 * Revision 1.136 2008/05/26 16:02:24 fabiankeil
93 * s@Insufficent@Insufficient@
95 * Revision 1.135 2008/05/21 20:12:10 fabiankeil
96 * The whole point of strclean() is to modify the
97 * first parameter, so don't mark it immutable,
98 * even though the compiler lets us get away with it.
100 * Revision 1.134 2008/05/21 19:27:25 fabiankeil
101 * As the wafer actions are gone, we can stop including encode.h.
103 * Revision 1.133 2008/05/21 15:50:47 fabiankeil
104 * Ditch cast from (char **) to (char **).
106 * Revision 1.132 2008/05/21 15:47:14 fabiankeil
107 * Streamline sed()'s prototype and declare
108 * the header parse and add structures static.
110 * Revision 1.131 2008/05/20 20:13:30 fabiankeil
111 * Factor update_server_headers() out of sed(), ditch the
112 * first_run hack and make server_patterns_light static.
114 * Revision 1.130 2008/05/19 17:18:04 fabiankeil
115 * Wrap memmove() calls in string_move()
116 * to document the purpose in one place.
118 * Revision 1.129 2008/05/17 14:02:07 fabiankeil
119 * Normalize linear header white space.
121 * Revision 1.128 2008/05/16 16:39:03 fabiankeil
122 * If a header is split across multiple lines,
123 * merge them to a single line before parsing them.
125 * Revision 1.127 2008/05/10 13:23:38 fabiankeil
126 * Don't provide get_header() with the whole client state
127 * structure when it only needs access to csp->iob.
129 * Revision 1.126 2008/05/03 16:40:45 fabiankeil
130 * Change content_filters_enabled()'s parameter from
131 * csp->action to action so it can be also used in the
132 * CGI code. Don't bother checking if there are filters
133 * loaded, as that's somewhat besides the point.
135 * Revision 1.125 2008/04/17 14:40:49 fabiankeil
136 * Provide get_http_time() with the buffer size so it doesn't
137 * have to blindly assume that the buffer is big enough.
139 * Revision 1.124 2008/04/16 16:38:21 fabiankeil
140 * Don't pass the whole csp structure to flush_socket()
141 * when it only needs a file descriptor and a buffer.
143 * Revision 1.123 2008/03/29 12:13:46 fabiankeil
144 * Remove send-wafer and send-vanilla-wafer actions.
146 * Revision 1.122 2008/03/28 15:13:39 fabiankeil
147 * Remove inspect-jpegs action.
149 * Revision 1.121 2008/01/05 21:37:03 fabiankeil
150 * Let client_range() also handle Request-Range headers
151 * which apparently are still supported by many servers.
153 * Revision 1.120 2008/01/04 17:43:45 fabiankeil
154 * Improve the warning messages that get logged if the action files
155 * "enable" filters but no filters of that type have been loaded.
157 * Revision 1.119 2007/12/28 18:32:51 fabiankeil
158 * In server_content_type():
159 * - Don't require leading white space when detecting image content types.
160 * - Change '... not replaced ...' message to sound less crazy if the text
161 * type actually is 'text/plain'.
162 * - Mark the 'text/plain == binary data' assumption for removal.
163 * - Remove a bunch of trailing white space.
165 * Revision 1.118 2007/12/28 16:56:35 fabiankeil
166 * Minor server_content_disposition() changes:
167 * - Don't regenerate the header name all lower-case.
168 * - Some white space fixes.
169 * - Remove useless log message in case of ENOMEM.
171 * Revision 1.117 2007/12/06 18:11:50 fabiankeil
172 * Garbage-collect the code to add a X-Forwarded-For
173 * header as it seems to be mostly used by accident.
175 * Revision 1.116 2007/12/01 13:04:22 fabiankeil
176 * Fix a crash on mingw32 with some Last Modified times in the future.
178 * Revision 1.115 2007/11/02 16:52:50 fabiankeil
179 * Remove a "can't happen" error block which, over
180 * time, mutated into a "guaranteed to happen" block.
182 * Revision 1.114 2007/10/19 16:56:26 fabiankeil
183 * - Downgrade "Buffer limit reached" message to LOG_LEVEL_INFO.
184 * - Use shiny new content_filters_enabled() in client_range().
186 * Revision 1.113 2007/10/10 17:29:57 fabiankeil
187 * I forgot about Poland.
189 * Revision 1.112 2007/10/09 16:38:40 fabiankeil
190 * Remove Range and If-Range headers if content filtering is enabled.
192 * Revision 1.111 2007/10/04 18:07:00 fabiankeil
193 * Move ACTION_VANILLA_WAFER handling from jcc's chat() into
194 * client_cookie_adder() to make sure send-vanilla-wafer can be
195 * controlled through tags (and thus regression-tested).
197 * Revision 1.110 2007/09/29 10:42:37 fabiankeil
198 * - Remove "scanning headers for" log message again.
199 * - Some more whitespace fixes.
201 * Revision 1.109 2007/09/08 14:25:48 fabiankeil
202 * Refactor client_referrer() and add conditional-forge parameter.
204 * Revision 1.108 2007/08/28 18:21:03 fabiankeil
205 * A bunch of whitespace fixes, pointy hat to me.
207 * Revision 1.107 2007/08/28 18:16:32 fabiankeil
208 * Fix possible memory corruption in server_http, make sure it's not
209 * executed for ordinary server headers and mark some problems for later.
211 * Revision 1.106 2007/08/18 14:30:32 fabiankeil
212 * Let content-type-overwrite{} honour force-text-mode again.
214 * Revision 1.105 2007/08/11 14:49:49 fabiankeil
215 * - Add prototpyes for the header parsers and make them static.
216 * - Comment out client_accept_encoding_adder() which isn't used right now.
218 * Revision 1.104 2007/07/14 07:38:19 fabiankeil
219 * Move the ACTION_FORCE_TEXT_MODE check out of
220 * server_content_type(). Signal other functions
221 * whether or not a content type has been declared.
222 * Part of the fix for BR#1750917.
224 * Revision 1.103 2007/06/01 16:31:54 fabiankeil
225 * Change sed() to return a jb_err in preparation for forward-override{}.
227 * Revision 1.102 2007/05/27 12:39:32 fabiankeil
228 * Adjust "X-Filter: No" to disable dedicated header filters.
230 * Revision 1.101 2007/05/14 10:16:41 fabiankeil
231 * Streamline client_cookie_adder().
233 * Revision 1.100 2007/04/30 15:53:11 fabiankeil
234 * Make sure filters with dynamic jobs actually use them.
236 * Revision 1.99 2007/04/30 15:06:26 fabiankeil
237 * - Introduce dynamic pcrs jobs that can resolve variables.
238 * - Remove unnecessary update_action_bits_for_all_tags() call.
240 * Revision 1.98 2007/04/17 18:32:10 fabiankeil
241 * - Make tagging based on tags set by earlier taggers
242 * of the same kind possible.
243 * - Log whether or not new tags cause action bits updates
244 * (in which case a matching tag-pattern section exists).
245 * - Log if the user tries to set a tag that is already set.
247 * Revision 1.97 2007/04/15 16:39:21 fabiankeil
248 * Introduce tags as alternative way to specify which
249 * actions apply to a request. At the moment tags can be
250 * created based on client and server headers.
252 * Revision 1.96 2007/04/12 12:53:58 fabiankeil
253 * Log a warning if the content is compressed, filtering is
254 * enabled and Privoxy was compiled without zlib support.
257 * Revision 1.95 2007/03/25 14:26:40 fabiankeil
258 * - Fix warnings when compiled with glibc.
259 * - Don't use crumble() for cookie crunching.
260 * - Move cookie time parsing into parse_header_time().
261 * - Let parse_header_time() return a jb_err code
262 * instead of a pointer that can only be used to
263 * check for NULL anyway.
265 * Revision 1.94 2007/03/21 12:23:53 fabiankeil
266 * - Add better protection against malicious gzip headers.
267 * - Stop logging the first hundred bytes of decompressed content.
268 * It looks like it's working and there is always debug 16.
269 * - Log the content size after decompression in decompress_iob()
270 * instead of pcrs_filter_response().
272 * Revision 1.93 2007/03/20 15:21:44 fabiankeil
273 * - Use dedicated header filter actions instead of abusing "filter".
274 * Replace "filter-client-headers" and "filter-client-headers"
275 * with "server-header-filter" and "client-header-filter".
276 * - Remove filter_client_header() and filter_client_header(),
277 * filter_header() now checks the shiny new
278 * CSP_FLAG_CLIENT_HEADER_PARSING_DONE flag instead.
280 * Revision 1.92 2007/03/05 13:25:32 fabiankeil
281 * - Cosmetical changes for LOG_LEVEL_RE_FILTER messages.
282 * - Handle "Cookie:" and "Connection:" headers a bit smarter
283 * (don't crunch them just to recreate them later on).
284 * - Add another non-standard time format for the cookie
285 * expiration date detection.
286 * - Fix a valgrind warning.
288 * Revision 1.91 2007/02/24 12:27:32 fabiankeil
289 * Improve cookie expiration date detection.
291 * Revision 1.90 2007/02/08 19:12:35 fabiankeil
292 * Don't run server_content_length() the first time
293 * sed() parses server headers; only adjust the
294 * Content-Length header if the page was modified.
296 * Revision 1.89 2007/02/07 16:52:11 fabiankeil
297 * Fix log messages regarding the cookie time format
298 * (cookie and request URL were mixed up).
300 * Revision 1.88 2007/02/07 11:27:12 fabiankeil
301 * - Let decompress_iob()
302 * - not corrupt the content if decompression fails
303 * early. (the first byte(s) were lost).
304 * - use pointer arithmetics with defined outcome for
306 * - Use a different kludge to remember a failed decompression.
308 * Revision 1.87 2007/01/31 16:21:38 fabiankeil
309 * Search for Max-Forwards headers case-insensitive,
310 * don't generate the "501 unsupported" message for invalid
311 * Max-Forwards values and don't increase negative ones.
313 * Revision 1.86 2007/01/30 13:05:26 fabiankeil
314 * - Let server_set_cookie() check the expiration date
315 * of cookies and don't touch the ones that are already
316 * expired. Fixes problems with low quality web applications
317 * as described in BR 932612.
319 * - Adjust comment in client_max_forwards to reality;
320 * remove invalid Max-Forwards headers.
322 * Revision 1.85 2007/01/26 15:33:46 fabiankeil
323 * Stop filter_header() from unintentionally removing
324 * empty header lines that were enlisted by the continue
327 * Revision 1.84 2007/01/24 12:56:52 fabiankeil
328 * - Repeat the request URL before logging any headers.
329 * Makes reading the log easier in case of simultaneous requests.
330 * - If there are more than one Content-Type headers in one request,
331 * use the first one and remove the others.
332 * - Remove "newval" variable in server_content_type().
333 * It's only used once.
335 * Revision 1.83 2007/01/12 15:03:02 fabiankeil
336 * Correct a cast, check inflateEnd() exit code
337 * to see if we have to, replace sprintf calls
340 * Revision 1.82 2007/01/01 19:36:37 fabiankeil
341 * Integrate a modified version of Wil Mahan's
342 * zlib patch (PR #895531).
344 * Revision 1.81 2006/12/31 22:21:33 fabiankeil
345 * Skip empty filter files in filter_header()
346 * but don't ignore the ones that come afterwards.
347 * Fixes BR 1619208, this time for real.
349 * Revision 1.80 2006/12/29 19:08:22 fabiankeil
350 * Reverted parts of my last commit
351 * to keep error handling working.
353 * Revision 1.79 2006/12/29 18:04:40 fabiankeil
354 * Fixed gcc43 conversion warnings.
356 * Revision 1.78 2006/12/26 17:19:20 fabiankeil
357 * Bringing back the "useless" localtime() call
358 * I removed in revision 1.67. On some platforms
359 * it's necessary to prevent time zone offsets.
361 * Revision 1.77 2006/12/07 18:44:26 fabiankeil
362 * Rebuild request URL in get_destination_from_headers()
363 * to make sure redirect{pcrs command} works as expected
364 * for intercepted requests.
366 * Revision 1.76 2006/12/06 19:52:25 fabiankeil
367 * Added get_destination_from_headers().
369 * Revision 1.75 2006/11/13 19:05:51 fabiankeil
370 * Make pthread mutex locking more generic. Instead of
371 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
372 * and use mutex locking unless there is an _r function
373 * available. Better safe than sorry.
375 * Fixes "./configure --disable-pthread" and should result
376 * in less threading-related problems on pthread-using platforms,
377 * but it still doesn't fix BR#1122404.
379 * Revision 1.74 2006/10/02 16:59:12 fabiankeil
380 * The special header "X-Filter: No" now disables
381 * header filtering as well.
383 * Revision 1.73 2006/09/23 13:26:38 roro
384 * Replace TABs by spaces in source code.
386 * Revision 1.72 2006/09/23 12:37:21 fabiankeil
387 * Don't print a log message every time filter_headers is
388 * entered or left. It only creates noise without any real
391 * Revision 1.71 2006/09/21 19:55:17 fabiankeil
392 * Fix +hide-if-modified-since{-n}.
394 * Revision 1.70 2006/09/08 12:06:34 fabiankeil
395 * Have hide-if-modified-since interpret the random
396 * range value as minutes instead of hours. Allows
397 * more fine-grained configuration.
399 * Revision 1.69 2006/09/06 16:25:51 fabiankeil
400 * Always have parse_header_time return a pointer
401 * that actual makes sense, even though we currently
402 * only need it to detect problems.
404 * Revision 1.68 2006/09/06 10:43:32 fabiankeil
405 * Added config option enable-remote-http-toggle
406 * to specify if Privoxy should recognize special
407 * headers (currently only X-Filter) to change its
408 * behaviour. Disabled by default.
410 * Revision 1.67 2006/09/04 11:01:26 fabiankeil
411 * After filtering de-chunked instances, remove
412 * "Transfer-Encoding" header entirely instead of changing
413 * it to "Transfer-Encoding: identity", which is invalid.
414 * Thanks Michael Shields <shields@msrl.com>. Fixes PR 1318658.
416 * Don't use localtime in parse_header_time. An empty time struct
417 * is good enough, it gets overwritten by strptime anyway.
419 * Revision 1.66 2006/09/03 19:38:28 fabiankeil
420 * Use gmtime_r if available, fallback to gmtime with mutex
421 * protection for MacOSX and use vanilla gmtime for the rest.
423 * Revision 1.65 2006/08/22 10:55:56 fabiankeil
424 * Changed client_referrer to use the right type (size_t) for
425 * hostlenght and to shorten the temporary referrer string with
426 * '\0' instead of adding a useless line break.
428 * Revision 1.64 2006/08/17 17:15:10 fabiankeil
429 * - Back to timegm() using GnuPG's replacement if necessary.
430 * Using mktime() and localtime() could add a on hour offset if
431 * the randomize factor was big enough to lead to a summer/wintertime
434 * - Removed now-useless Privoxy 3.0.3 compatibility glue.
436 * - Moved randomization code into pick_from_range().
438 * - Changed parse_header_time definition.
439 * time_t isn't guaranteed to be signed and
440 * if it isn't, -1 isn't available as error code.
441 * Changed some variable types in client_if_modified_since()
442 * because of the same reason.
444 * Revision 1.63 2006/08/14 13:18:08 david__schmidt
445 * OS/2 compilation compatibility fixups
447 * Revision 1.62 2006/08/14 08:58:42 fabiankeil
448 * Changed include from strptime.c to strptime.h
450 * Revision 1.61 2006/08/14 08:25:19 fabiankeil
451 * Split filter-headers{} into filter-client-headers{}
452 * and filter-server-headers{}.
453 * Added parse_header_time() to share some code.
454 * Replaced timegm() with mktime().
456 * Revision 1.60 2006/08/12 03:54:37 david__schmidt
457 * Windows service integration
459 * Revision 1.59 2006/08/03 02:46:41 david__schmidt
460 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
462 * Revision 1.58 2006/07/18 14:48:47 david__schmidt
463 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
464 * with what was really the latest development (the v_3_0_branch branch)
466 * Revision 1.56.2.10 2006/01/21 16:16:08 david__schmidt
467 * Thanks to Edward Carrel for his patch to modernize OSX's
\rpthreads support. See bug #1409623.
469 * Revision 1.56.2.9 2004/10/03 12:53:45 david__schmidt
470 * Add the ability to check jpeg images for invalid
471 * lengths of comment blocks. Defensive strategy
472 * against the exploit:
473 * Microsoft Security Bulletin MS04-028
474 * Buffer Overrun in JPEG Processing (GDI+) Could
475 * Allow Code Execution (833987)
476 * Enabled with +inspect-jpegs in actions files.
478 * Revision 1.56.2.8 2003/07/11 13:21:25 oes
479 * Excluded text/plain objects from filtering. This fixes a
480 * couple of client-crashing, download corruption and
481 * Privoxy performance issues, whose root cause lies in
482 * web servers labelling content of unknown type as text/plain.
484 * Revision 1.56.2.7 2003/05/06 12:07:26 oes
485 * Fixed bug #729900: Suspicious HOST: headers are now killed and regenerated if necessary
487 * Revision 1.56.2.6 2003/04/14 21:28:30 oes
488 * Completing the previous change
490 * Revision 1.56.2.5 2003/04/14 12:08:16 oes
491 * Added temporary workaround for bug in PHP < 4.2.3
493 * Revision 1.56.2.4 2003/03/07 03:41:05 david__schmidt
494 * 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.
496 * Revision 1.56.2.3 2002/11/10 04:20:02 hal9
497 * Fix typo: supressed -> suppressed
499 * Revision 1.56.2.2 2002/09/25 14:59:53 oes
500 * Improved cookie logging
502 * Revision 1.56.2.1 2002/09/25 14:52:45 oes
503 * Added basic support for OPTIONS and TRACE HTTP methods:
504 * - New parser function client_max_forwards which decrements
505 * the Max-Forwards HTTP header field of OPTIONS and TRACE
506 * requests by one before forwarding
507 * - New parser function client_host which extracts the host
508 * and port information from the HTTP header field if the
509 * request URI was not absolute
510 * - Don't crumble and re-add the Host: header, but only generate
511 * and append if missing
513 * Revision 1.56 2002/05/12 15:34:22 jongfoster
514 * Fixing typo in a comment
516 * Revision 1.55 2002/05/08 16:01:07 oes
517 * Optimized add_to_iob:
518 * - Use realloc instead of malloc(), memcpy(), free()
519 * - Expand to powers of two if possible, to get
520 * O(log n) reallocs instead of O(n).
521 * - Moved check for buffer limit here from chat
522 * - Report failure via returncode
524 * Revision 1.54 2002/04/02 15:03:16 oes
525 * Tiny code cosmetics
527 * Revision 1.53 2002/03/26 22:29:55 swa
528 * we have a new homepage!
530 * Revision 1.52 2002/03/24 13:25:43 swa
531 * name change related issues
533 * Revision 1.51 2002/03/13 00:27:05 jongfoster
536 * Revision 1.50 2002/03/12 01:45:35 oes
537 * More verbose logging
539 * Revision 1.49 2002/03/09 20:03:52 jongfoster
540 * - Making various functions return int rather than size_t.
541 * (Undoing a recent change). Since size_t is unsigned on
542 * Windows, functions like read_socket that return -1 on
543 * error cannot return a size_t.
545 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
546 * crashes, and also frequently caused JB to jump to 100%
547 * CPU and stay there. (Because it thought it had just
548 * read ((unsigned)-1) == 4Gb of data...)
550 * - The signature of write_socket has changed, it now simply
551 * returns success=0/failure=nonzero.
553 * - Trying to get rid of a few warnings --with-debug on
554 * Windows, I've introduced a new type "jb_socket". This is
555 * used for the socket file descriptors. On Windows, this
556 * is SOCKET (a typedef for unsigned). Everywhere else, it's
557 * an int. The error value can't be -1 any more, so it's
558 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
559 * Windows it maps to the #define INVALID_SOCKET.)
561 * - The signature of bind_port has changed.
563 * Revision 1.48 2002/03/07 03:46:53 oes
564 * Fixed compiler warnings etc
566 * Revision 1.47 2002/02/20 23:15:13 jongfoster
567 * Parsing functions now handle out-of-memory gracefully by returning
570 * Revision 1.46 2002/01/17 21:03:47 jongfoster
571 * Moving all our URL and URL pattern parsing code to urlmatch.c.
573 * Revision 1.45 2002/01/09 14:33:03 oes
574 * Added support for localtime_r.
576 * Revision 1.44 2001/12/14 01:22:54 steudten
577 * Remove 'user:pass@' from 'proto://user:pass@host' for the
578 * new added header 'Host: ..'. (See Req ID 491818)
580 * Revision 1.43 2001/11/23 00:26:38 jongfoster
581 * Fixing two really stupid errors in my previous commit
583 * Revision 1.42 2001/11/22 21:59:30 jongfoster
584 * Adding code to handle +no-cookies-keep
586 * Revision 1.41 2001/11/05 23:43:05 steudten
587 * Add time+date to log files.
589 * Revision 1.40 2001/10/26 20:13:09 jongfoster
590 * ctype.h is needed in Windows, too.
592 * Revision 1.39 2001/10/26 17:40:04 oes
593 * Introduced get_header_value()
594 * Removed http->user_agent, csp->referrer and csp->accept_types
595 * Removed client_accept()
597 * Revision 1.38 2001/10/25 03:40:48 david__schmidt
598 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
599 * threads to call select() simultaneously. So, it's time to do a real, live,
600 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
601 * (native). Both versions will work, but using __OS2__ offers multi-threading.
603 * Revision 1.37 2001/10/23 21:36:02 jongfoster
604 * Documenting sed()'s error behaviou (doc change only)
606 * Revision 1.36 2001/10/13 12:51:51 joergs
607 * Removed client_host, (was only required for the old 2.0.2-11 http://noijb.
608 * force-load), instead crumble Host: and add it (again) in client_host_adder
609 * (in case we get a HTTP/1.0 request without Host: header and forward it to
610 * a HTTP/1.1 server/proxy).
612 * Revision 1.35 2001/10/09 22:39:21 jongfoster
613 * assert.h is also required under Win32, so moving out of #ifndef _WIN32
616 * Revision 1.34 2001/10/07 18:50:55 oes
617 * Added server_content_encoding, renamed server_transfer_encoding
619 * Revision 1.33 2001/10/07 18:04:49 oes
620 * Changed server_http11 to server_http and its pattern to "HTTP".
621 * Additional functionality: it now saves the HTTP status into
622 * csp->http->status and sets CT_TABOO for Status 206 (partial range)
624 * Revision 1.32 2001/10/07 15:43:28 oes
625 * Removed FEATURE_DENY_GZIP and replaced it with client_accept_encoding,
626 * client_te and client_accept_encoding_adder, triggered by the new
627 * +no-compression action. For HTTP/1.1 the Accept-Encoding header is
628 * changed to allow only identity and chunked, and the TE header is
629 * crunched. For HTTP/1.0, Accept-Encoding is crunched.
631 * parse_http_request no longer does anything than parsing. The rewriting
632 * of http->cmd and version mangling are gone. It now also recognizes
633 * the put and delete methods and saves the url in http->url. Removed
636 * renamed content_type and content_length to have the server_ prefix
638 * server_content_type now only works if csp->content_type != CT_TABOO
640 * added server_transfer_encoding, which
641 * - Sets CT_TABOO to prohibit filtering if encoding compresses
642 * - Raises the CSP_FLAG_CHUNKED flag if Encoding is "chunked"
643 * - Change from "chunked" to "identity" if body was chunked
644 * but has been de-chunked for filtering.
646 * added server_content_md5 which crunches any Content-MD5 headers
647 * if the body was modified.
649 * made server_http11 conditional on +downgrade action
651 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
653 * Revision 1.31 2001/10/05 14:25:02 oes
654 * Crumble Keep-Alive from Server
656 * Revision 1.30 2001/09/29 12:56:03 joergs
657 * IJB now changes HTTP/1.1 to HTTP/1.0 in requests and answers.
659 * Revision 1.29 2001/09/24 21:09:24 jongfoster
660 * Fixing 2 memory leaks that Guy spotted, where the paramater to
661 * enlist() was not being free()d.
663 * Revision 1.28 2001/09/22 16:32:28 jongfoster
664 * Removing unused #includes.
666 * Revision 1.27 2001/09/20 15:45:25 steudten
668 * add casting from size_t to int for printf()
669 * remove local variable shadow s2
671 * Revision 1.26 2001/09/16 17:05:14 jongfoster
672 * Removing unused #include showarg.h
674 * Revision 1.25 2001/09/16 13:21:27 jongfoster
675 * Changes to use new list functions.
677 * Revision 1.24 2001/09/13 23:05:50 jongfoster
678 * Changing the string paramater to the header parsers a "const".
680 * Revision 1.23 2001/09/12 18:08:19 steudten
682 * In parse_http_request() header rewriting miss the host value, so
683 * from http://www.mydomain.com the result was just " / " not
684 * http://www.mydomain.com/ in case we forward.
686 * Revision 1.22 2001/09/10 10:58:53 oes
687 * Silenced compiler warnings
689 * Revision 1.21 2001/07/31 14:46:00 oes
690 * - Persistant connections now suppressed
691 * - sed() no longer appends empty header to csp->headers
693 * Revision 1.20 2001/07/30 22:08:36 jongfoster
694 * Tidying up #defines:
695 * - All feature #defines are now of the form FEATURE_xxx
696 * - Permanently turned off WIN_GUI_EDIT
697 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
699 * Revision 1.19 2001/07/25 17:21:54 oes
700 * client_uagent now saves copy of User-Agent: header value
702 * Revision 1.18 2001/07/13 14:02:46 oes
703 * - Included fix to repair broken HTTP requests that
704 * don't contain a path, not even '/'.
705 * - Removed all #ifdef PCRS
706 * - content_type now always inspected and classified as
707 * text, gif or other.
708 * - formatting / comments
710 * Revision 1.17 2001/06/29 21:45:41 oes
711 * Indentation, CRLF->LF, Tab-> Space
713 * Revision 1.16 2001/06/29 13:32:42 oes
715 * - Adapted free_http_request
716 * - Removed logentry from cancelled commit
718 * Revision 1.15 2001/06/03 19:12:38 oes
719 * deleted const struct interceptors
721 * Revision 1.14 2001/06/01 18:49:17 jongfoster
722 * Replaced "list_share" with "list" - the tiny memory gain was not
723 * worth the extra complexity.
725 * Revision 1.13 2001/05/31 21:30:33 jongfoster
726 * Removed list code - it's now in list.[ch]
727 * Renamed "permission" to "action", and changed many features
728 * to use the actions file rather than the global config.
730 * Revision 1.12 2001/05/31 17:33:13 oes
734 * Revision 1.11 2001/05/29 20:11:19 joergs
735 * '/ * inside comment' warning removed.
737 * Revision 1.10 2001/05/29 09:50:24 jongfoster
738 * Unified blocklist/imagelist/permissionslist.
739 * File format is still under discussion, but the internal changes
742 * Also modified interceptor behaviour:
743 * - We now intercept all URLs beginning with one of the following
744 * prefixes (and *only* these prefixes):
746 * * http://ijbswa.sf.net/config/
747 * * http://ijbswa.sourceforge.net/config/
748 * - New interceptors "home page" - go to http://i.j.b/ to see it.
749 * - Internal changes so that intercepted and fast redirect pages
750 * are not replaced with an image.
751 * - Interceptors now have the option to send a binary page direct
752 * to the client. (i.e. ijb-send-banner uses this)
753 * - Implemented show-url-info interceptor. (Which is why I needed
754 * the above interceptors changes - a typical URL is
755 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
756 * The previous mechanism would not have intercepted that, and
757 * if it had been intercepted then it then it would have replaced
760 * Revision 1.9 2001/05/28 17:26:33 jongfoster
761 * Fixing segfault if last header was crunched.
762 * Fixing Windows build (snprintf() is _snprintf() under Win32, but we
763 * can use the cross-platform sprintf() instead.)
765 * Revision 1.8 2001/05/27 22:17:04 oes
767 * - re_process_buffer no longer writes the modified buffer
768 * to the client, which was very ugly. It now returns the
769 * buffer, which it is then written by chat.
771 * - content_length now adjusts the Content-Length: header
772 * for modified documents rather than crunch()ing it.
773 * (Length info in csp->content_length, which is 0 for
774 * unmodified documents)
776 * - For this to work, sed() is called twice when filtering.
778 * Revision 1.7 2001/05/27 13:19:06 oes
779 * Patched Joergs solution for the content-length in.
781 * Revision 1.6 2001/05/26 13:39:32 jongfoster
782 * Only crunches Content-Length header if applying RE filtering.
783 * Without this fix, Microsoft Windows Update wouldn't work.
785 * Revision 1.5 2001/05/26 00:28:36 jongfoster
786 * Automatic reloading of config file.
787 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
788 * Most of the global variables have been moved to a new
789 * struct configuration_spec, accessed through csp->config->globalname
790 * Most of the globals remaining are used by the Win32 GUI.
792 * Revision 1.4 2001/05/22 18:46:04 oes
794 * - Enabled filtering banners by size rather than URL
795 * by adding patterns that replace all standard banner
796 * sizes with the "Junkbuster" gif to the re_filterfile
798 * - Enabled filtering WebBugs by providing a pattern
799 * which kills all 1x1 images
801 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
802 * which is selected by the (nonstandard and therefore
803 * capital) letter 'U' in the option string.
804 * It causes the quantifiers to be ungreedy by default.
805 * Appending a ? turns back to greedy (!).
807 * - Added a new interceptor ijb-send-banner, which
808 * sends back the "Junkbuster" gif. Without imagelist or
809 * MSIE detection support, or if tinygif = 1, or the
810 * URL isn't recognized as an imageurl, a lame HTML
811 * explanation is sent instead.
813 * - Added new feature, which permits blocking remote
814 * script redirects and firing back a local redirect
816 * The feature is conditionally compiled, i.e. it
817 * can be disabled with --disable-fast-redirects,
818 * plus it must be activated by a "fast-redirects"
819 * line in the config file, has its own log level
820 * and of course wants to be displayed by show-proxy-args
821 * Note: Boy, all the #ifdefs in 1001 locations and
822 * all the fumbling with configure.in and acconfig.h
823 * were *way* more work than the feature itself :-(
825 * - Because a generic redirect template was needed for
826 * this, tinygif = 3 now uses the same.
828 * - Moved GIFs, and other static HTTP response templates
833 * - Removed some >400 CRs again (Jon, you really worked
836 * Revision 1.3 2001/05/20 01:21:20 jongfoster
837 * Version 2.9.4 checkin.
838 * - Merged popupfile and cookiefile, and added control over PCRS
839 * filtering, in new "permissionsfile".
840 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
841 * file error you now get a message box (in the Win32 GUI) rather
842 * than the program exiting with no explanation.
843 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
845 * - Removed tabs from "config"
846 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
847 * - Bumped up version number.
849 * Revision 1.2 2001/05/17 23:02:36 oes
850 * - Made referrer option accept 'L' as a substitute for '§'
852 * Revision 1.1.1.1 2001/05/15 13:59:01 oes
853 * Initial import of version 2.9.3 source tree
856 *********************************************************************/
863 #include <sys/types.h>
873 * Convince GNU's libc to provide a strptime prototype.
876 #endif /*__GLIBC__ */
883 #if !defined(_WIN32) && !defined(__OS2__)
889 #ifdef FEATURE_PTHREAD
891 /* jcc.h is for mutex semapores only */
892 #endif /* def FEATURE_PTHREAD */
897 #include "jbsockets.h"
898 #include "miscutil.h"
903 #ifndef HAVE_STRPTIME
904 #include "strptime.h"
907 const char parsers_h_rcs[] = PARSERS_H_VERSION;
909 /* Fix a problem with Solaris. There should be no effect on other
911 * Solaris's isspace() is a macro which uses its argument directly
912 * as an array index. Therefore we need to make sure that high-bit
913 * characters generate +ve values, and ideally we also want to make
914 * the argument match the declared parameter type of "int".
916 * Why did they write a character function that can't take a simple
917 * "char" argument? Doh!
919 #define ijb_isupper(__X) isupper((int)(unsigned char)(__X))
920 #define ijb_tolower(__X) tolower((int)(unsigned char)(__X))
922 static char *get_header_line(struct iob *iob);
923 static jb_err scan_headers(struct client_state *csp);
924 static jb_err header_tagger(struct client_state *csp, char *header);
925 static jb_err parse_header_time(const char *header_time, time_t *result);
927 static jb_err crumble (struct client_state *csp, char **header);
928 static jb_err filter_header (struct client_state *csp, char **header);
929 static jb_err client_connection (struct client_state *csp, char **header);
930 static jb_err client_referrer (struct client_state *csp, char **header);
931 static jb_err client_uagent (struct client_state *csp, char **header);
932 static jb_err client_ua (struct client_state *csp, char **header);
933 static jb_err client_from (struct client_state *csp, char **header);
934 static jb_err client_send_cookie (struct client_state *csp, char **header);
935 static jb_err client_x_forwarded (struct client_state *csp, char **header);
936 static jb_err client_accept_encoding (struct client_state *csp, char **header);
937 static jb_err client_te (struct client_state *csp, char **header);
938 static jb_err client_max_forwards (struct client_state *csp, char **header);
939 static jb_err client_host (struct client_state *csp, char **header);
940 static jb_err client_if_modified_since (struct client_state *csp, char **header);
941 static jb_err client_accept_language (struct client_state *csp, char **header);
942 static jb_err client_if_none_match (struct client_state *csp, char **header);
943 static jb_err crunch_client_header (struct client_state *csp, char **header);
944 static jb_err client_x_filter (struct client_state *csp, char **header);
945 static jb_err client_range (struct client_state *csp, char **header);
946 static jb_err server_set_cookie (struct client_state *csp, char **header);
947 static jb_err server_connection (struct client_state *csp, char **header);
948 static jb_err server_content_type (struct client_state *csp, char **header);
949 static jb_err server_adjust_content_length(struct client_state *csp, char **header);
950 static jb_err server_content_md5 (struct client_state *csp, char **header);
951 static jb_err server_content_encoding (struct client_state *csp, char **header);
952 static jb_err server_transfer_coding (struct client_state *csp, char **header);
953 static jb_err server_http (struct client_state *csp, char **header);
954 static jb_err crunch_server_header (struct client_state *csp, char **header);
955 static jb_err server_last_modified (struct client_state *csp, char **header);
956 static jb_err server_content_disposition(struct client_state *csp, char **header);
958 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
959 static jb_err server_save_content_length(struct client_state *csp, char **header);
960 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
962 static jb_err client_host_adder (struct client_state *csp);
963 static jb_err client_xtra_adder (struct client_state *csp);
964 static jb_err client_x_forwarded_for_adder(struct client_state *csp);
965 static jb_err client_connection_header_adder(struct client_state *csp);
966 static jb_err server_connection_close_adder(struct client_state *csp);
968 static jb_err create_forged_referrer(char **header, const char *hostport);
969 static jb_err create_fake_referrer(char **header, const char *fake_referrer);
970 static jb_err handle_conditional_hide_referrer_parameter(char **header,
971 const char *host, const int parameter_conditional_block);
972 static const char *get_appropiate_connection_header(const struct client_state *csp);
975 * List of functions to run on a list of headers.
979 /** The header prefix to match */
982 /** The length of the prefix to match */
985 /** The function to apply to this line */
986 const parser_func_ptr parser;
989 static const struct parsers client_patterns[] = {
990 { "referer:", 8, client_referrer },
991 { "user-agent:", 11, client_uagent },
992 { "ua-", 3, client_ua },
993 { "from:", 5, client_from },
994 { "cookie:", 7, client_send_cookie },
995 { "x-forwarded-for:", 16, client_x_forwarded },
996 { "Accept-Encoding:", 16, client_accept_encoding },
997 { "TE:", 3, client_te },
998 { "Host:", 5, client_host },
999 { "if-modified-since:", 18, client_if_modified_since },
1000 { "Keep-Alive:", 11, crumble },
1001 { "connection:", 11, client_connection },
1002 { "proxy-connection:", 17, crumble },
1003 { "max-forwards:", 13, client_max_forwards },
1004 { "Accept-Language:", 16, client_accept_language },
1005 { "if-none-match:", 14, client_if_none_match },
1006 { "Range:", 6, client_range },
1007 { "Request-Range:", 14, client_range },
1008 { "If-Range:", 9, client_range },
1009 { "X-Filter:", 9, client_x_filter },
1010 { "*", 0, crunch_client_header },
1011 { "*", 0, filter_header },
1015 static const struct parsers server_patterns[] = {
1016 { "HTTP/", 5, server_http },
1017 { "set-cookie:", 11, server_set_cookie },
1018 { "connection:", 11, server_connection },
1019 { "Content-Type:", 13, server_content_type },
1020 { "Content-MD5:", 12, server_content_md5 },
1021 { "Content-Encoding:", 17, server_content_encoding },
1022 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1023 { "Content-Length:", 15, server_save_content_length },
1024 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1025 { "Transfer-Encoding:", 18, server_transfer_coding },
1026 { "Keep-Alive:", 11, crumble },
1027 { "content-disposition:", 20, server_content_disposition },
1028 { "Last-Modified:", 14, server_last_modified },
1029 { "*", 0, crunch_server_header },
1030 { "*", 0, filter_header },
1034 static const add_header_func_ptr add_client_headers[] = {
1036 client_x_forwarded_for_adder,
1038 /* Temporarily disabled: client_accept_encoding_adder, */
1039 client_connection_header_adder,
1043 static const add_header_func_ptr add_server_headers[] = {
1044 server_connection_close_adder,
1048 /*********************************************************************
1050 * Function : flush_socket
1052 * Description : Write any pending "buffered" content.
1055 * 1 : fd = file descriptor of the socket to read
1056 * 2 : iob = The I/O buffer to flush, usually csp->iob.
1058 * Returns : On success, the number of bytes written are returned (zero
1059 * indicates nothing was written). On error, -1 is returned,
1060 * and errno is set appropriately. If count is zero and the
1061 * file descriptor refers to a regular file, 0 will be
1062 * returned without causing any other effect. For a special
1063 * file, the results are not portable.
1065 *********************************************************************/
1066 int flush_socket(jb_socket fd, struct iob *iob)
1068 int len = iob->eod - iob->cur;
1075 if (write_socket(fd, iob->cur, (size_t)len))
1079 iob->eod = iob->cur = iob->buf;
1085 /*********************************************************************
1087 * Function : add_to_iob
1089 * Description : Add content to the buffered page, expanding the
1090 * buffer if necessary.
1093 * 1 : csp = Current client state (buffers, headers, etc...)
1094 * 2 : buf = holds the content to be added to the page
1095 * 3 : n = number of bytes to be added
1097 * Returns : JB_ERR_OK on success, JB_ERR_MEMORY if out-of-memory
1098 * or buffer limit reached.
1100 *********************************************************************/
1101 jb_err add_to_iob(struct client_state *csp, char *buf, int n)
1103 struct iob *iob = csp->iob;
1104 size_t used, offset, need, want;
1107 if (n <= 0) return JB_ERR_OK;
1109 used = (size_t)(iob->eod - iob->buf);
1110 offset = (size_t)(iob->cur - iob->buf);
1111 need = used + (size_t)n + 1;
1114 * If the buffer can't hold the new data, extend it first.
1115 * Use the next power of two if possible, else use the actual need.
1117 if (need > csp->config->buffer_limit)
1119 log_error(LOG_LEVEL_INFO,
1120 "Buffer limit reached while extending the buffer (iob). Needed: %d. Limit: %d",
1121 need, csp->config->buffer_limit);
1122 return JB_ERR_MEMORY;
1125 if (need > iob->size)
1127 for (want = csp->iob->size ? csp->iob->size : 512; want <= need;) want *= 2;
1129 if (want <= csp->config->buffer_limit && NULL != (p = (char *)realloc(iob->buf, want)))
1133 else if (NULL != (p = (char *)realloc(iob->buf, need)))
1139 log_error(LOG_LEVEL_ERROR, "Extending the buffer (iob) failed: %E");
1140 return JB_ERR_MEMORY;
1143 /* Update the iob pointers */
1144 iob->cur = p + offset;
1145 iob->eod = p + used;
1149 /* copy the new data into the iob buffer */
1150 memcpy(iob->eod, buf, (size_t)n);
1152 /* point to the end of the data */
1155 /* null terminate == cheap insurance */
1164 /*********************************************************************
1166 * Function : decompress_iob
1168 * Description : Decompress buffered page, expanding the
1169 * buffer as necessary. csp->iob->cur
1170 * should point to the the beginning of the
1171 * compressed data block.
1174 * 1 : csp = Current client state (buffers, headers, etc...)
1176 * Returns : JB_ERR_OK on success,
1177 * JB_ERR_MEMORY if out-of-memory limit reached, and
1178 * JB_ERR_COMPRESS if error decompressing buffer.
1180 *********************************************************************/
1181 jb_err decompress_iob(struct client_state *csp)
1183 char *buf; /* new, uncompressed buffer */
1184 char *cur; /* Current iob position (to keep the original
1185 * iob->cur unmodified if we return early) */
1186 size_t bufsize; /* allocated size of the new buffer */
1187 size_t old_size; /* Content size before decompression */
1188 size_t skip_size; /* Number of bytes at the beginning of the iob
1189 that we should NOT decompress. */
1190 int status; /* return status of the inflate() call */
1191 z_stream zstr; /* used by calls to zlib */
1193 assert(csp->iob->cur - csp->iob->buf > 0);
1194 assert(csp->iob->eod - csp->iob->cur > 0);
1196 bufsize = csp->iob->size;
1197 skip_size = (size_t)(csp->iob->cur - csp->iob->buf);
1198 old_size = (size_t)(csp->iob->eod - csp->iob->cur);
1200 cur = csp->iob->cur;
1205 * This is to protect the parsing of gzipped data,
1206 * but it should(?) be valid for deflated data also.
1208 log_error(LOG_LEVEL_ERROR, "Buffer too small decompressing iob");
1209 return JB_ERR_COMPRESS;
1212 if (csp->content_type & CT_GZIP)
1215 * Our task is slightly complicated by the facts that data
1216 * compressed by gzip does not include a zlib header, and
1217 * that there is no easily accessible interface in zlib to
1218 * handle a gzip header. We strip off the gzip header by
1219 * hand, and later inform zlib not to expect a header.
1223 * Strip off the gzip header. Please see RFC 1952 for more
1224 * explanation of the appropriate fields.
1226 if ((*cur++ != (char)0x1f)
1227 || (*cur++ != (char)0x8b)
1228 || (*cur++ != Z_DEFLATED))
1230 log_error(LOG_LEVEL_ERROR, "Invalid gzip header when decompressing");
1231 return JB_ERR_COMPRESS;
1237 * XXX: These magic numbers should be replaced
1238 * with macros to give a better idea what they do.
1242 /* The gzip header has reserved bits set; bail out. */
1243 log_error(LOG_LEVEL_ERROR, "Invalid gzip header flags when decompressing");
1244 return JB_ERR_COMPRESS;
1248 /* Skip extra fields if necessary. */
1252 * Skip a given number of bytes, specified
1253 * as a 16-bit little-endian value.
1256 * XXX: This code used to be:
1258 * csp->iob->cur += *csp->iob->cur++ + (*csp->iob->cur++ << 8);
1260 * which I had to change into:
1262 * cur += *cur++ + (*cur++ << 8);
1264 * at which point gcc43 finally noticed that the value
1265 * of cur is undefined (it depends on which of the
1266 * summands is evaluated first).
1268 * I haven't come across a site where this
1269 * code is actually executed yet, but I hope
1273 skip_bytes = *cur++;
1274 skip_bytes = *cur++ << 8;
1276 assert(skip_bytes == *csp->iob->cur - 2 + ((*csp->iob->cur - 1) << 8));
1279 * The number of bytes to skip should be positive
1280 * and we'd like to stay in the buffer.
1282 if ((skip_bytes < 0) || (skip_bytes >= (csp->iob->eod - cur)))
1284 log_error(LOG_LEVEL_ERROR,
1285 "Unreasonable amount of bytes to skip (%d). Stopping decompression",
1287 return JB_ERR_COMPRESS;
1289 log_error(LOG_LEVEL_INFO,
1290 "Skipping %d bytes for gzip compression. Does this sound right?",
1295 /* Skip the filename if necessary. */
1298 /* A null-terminated string is supposed to follow. */
1299 while (*cur++ && (cur < csp->iob->eod));
1303 /* Skip the comment if necessary. */
1306 /* A null-terminated string is supposed to follow. */
1307 while (*cur++ && (cur < csp->iob->eod));
1310 /* Skip the CRC if necessary. */
1316 if (cur >= csp->iob->eod)
1319 * If the current position pointer reached or passed
1320 * the buffer end, we were obviously tricked to skip
1323 log_error(LOG_LEVEL_ERROR,
1324 "Malformed gzip header detected. Aborting decompression.");
1325 return JB_ERR_COMPRESS;
1329 else if (csp->content_type & CT_DEFLATE)
1332 * XXX: The debug level should be lowered
1333 * before the next stable release.
1335 log_error(LOG_LEVEL_INFO, "Decompressing deflated iob: %d", *cur);
1337 * In theory (that is, according to RFC 1950), deflate-compressed
1338 * data should begin with a two-byte zlib header and have an
1339 * adler32 checksum at the end. It seems that in practice only
1340 * the raw compressed data is sent. Note that this means that
1341 * we are not RFC 1950-compliant here, but the advantage is that
1342 * this actually works. :)
1344 * We add a dummy null byte to tell zlib where the data ends,
1345 * and later inform it not to expect a header.
1347 * Fortunately, add_to_iob() has thoughtfully null-terminated
1348 * the buffer; we can just increment the end pointer to include
1355 log_error(LOG_LEVEL_ERROR,
1356 "Unable to determine compression format for decompression");
1357 return JB_ERR_COMPRESS;
1360 /* Set up the fields required by zlib. */
1361 zstr.next_in = (Bytef *)cur;
1362 zstr.avail_in = (unsigned int)(csp->iob->eod - cur);
1363 zstr.zalloc = Z_NULL;
1364 zstr.zfree = Z_NULL;
1365 zstr.opaque = Z_NULL;
1368 * Passing -MAX_WBITS to inflateInit2 tells the library
1369 * that there is no zlib header.
1371 if (inflateInit2 (&zstr, -MAX_WBITS) != Z_OK)
1373 log_error(LOG_LEVEL_ERROR, "Error initializing decompression");
1374 return JB_ERR_COMPRESS;
1378 * Next, we allocate new storage for the inflated data.
1379 * We don't modify the existing iob yet, so in case there
1380 * is error in decompression we can recover gracefully.
1382 buf = zalloc(bufsize);
1385 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1386 return JB_ERR_MEMORY;
1389 assert(bufsize >= skip_size);
1390 memcpy(buf, csp->iob->buf, skip_size);
1391 zstr.avail_out = bufsize - skip_size;
1392 zstr.next_out = (Bytef *)buf + skip_size;
1394 /* Try to decompress the whole stream in one shot. */
1395 while (Z_BUF_ERROR == (status = inflate(&zstr, Z_FINISH)))
1397 /* We need to allocate more memory for the output buffer. */
1399 char *tmpbuf; /* used for realloc'ing the buffer */
1400 size_t oldbufsize = bufsize; /* keep track of the old bufsize */
1403 * If zlib wants more data then there's a problem, because
1404 * the complete compressed file should have been buffered.
1406 if (0 == zstr.avail_in)
1408 log_error(LOG_LEVEL_ERROR, "Unexpected end of compressed iob");
1409 return JB_ERR_COMPRESS;
1413 * If we tried the limit and still didn't have enough
1414 * memory, just give up.
1416 if (bufsize == csp->config->buffer_limit)
1418 log_error(LOG_LEVEL_ERROR, "Buffer limit reached while decompressing iob");
1419 return JB_ERR_MEMORY;
1422 /* Try doubling the buffer size each time. */
1425 /* Don't exceed the buffer limit. */
1426 if (bufsize > csp->config->buffer_limit)
1428 bufsize = csp->config->buffer_limit;
1431 /* Try to allocate the new buffer. */
1432 tmpbuf = realloc(buf, bufsize);
1435 log_error(LOG_LEVEL_ERROR, "Out of memory decompressing iob");
1437 return JB_ERR_MEMORY;
1441 char *oldnext_out = (char *)zstr.next_out;
1444 * Update the fields for inflate() to use the new
1445 * buffer, which may be in a location different from
1448 zstr.avail_out += bufsize - oldbufsize;
1449 zstr.next_out = (Bytef *)tmpbuf + bufsize - zstr.avail_out;
1452 * Compare with an uglier method of calculating these values
1453 * that doesn't require the extra oldbufsize variable.
1455 assert(zstr.avail_out == tmpbuf + bufsize - (char *)zstr.next_out);
1456 assert((char *)zstr.next_out == tmpbuf + ((char *)oldnext_out - buf));
1457 assert(zstr.avail_out > 0);
1463 if (Z_STREAM_ERROR == inflateEnd(&zstr))
1465 log_error(LOG_LEVEL_ERROR,
1466 "Inconsistent stream state after decompression: %s", zstr.msg);
1468 * XXX: Intentionally no return.
1470 * According to zlib.h, Z_STREAM_ERROR is returned
1471 * "if the stream state was inconsistent".
1473 * I assume in this case inflate()'s status
1474 * would also be something different than Z_STREAM_END
1475 * so this check should be redundant, but lets see.
1479 if (status != Z_STREAM_END)
1481 /* We failed to decompress the stream. */
1482 log_error(LOG_LEVEL_ERROR,
1483 "Error in decompressing to the buffer (iob): %s", zstr.msg);
1484 return JB_ERR_COMPRESS;
1488 * Finally, we can actually update the iob, since the
1489 * decompression was successful. First, free the old
1492 freez(csp->iob->buf);
1494 /* Now, update the iob to use the new buffer. */
1495 csp->iob->buf = buf;
1496 csp->iob->cur = csp->iob->buf + skip_size;
1497 csp->iob->eod = (char *)zstr.next_out;
1498 csp->iob->size = bufsize;
1501 * Make sure the new uncompressed iob obeys some minimal
1502 * consistency conditions.
1504 if ((csp->iob->buf < csp->iob->cur)
1505 && (csp->iob->cur <= csp->iob->eod)
1506 && (csp->iob->eod <= csp->iob->buf + csp->iob->size))
1508 const size_t new_size = (size_t)(csp->iob->eod - csp->iob->cur);
1511 log_error(LOG_LEVEL_RE_FILTER,
1512 "Decompression successful. Old size: %d, new size: %d.",
1513 old_size, new_size);
1517 /* zlib thinks this is OK, so lets do the same. */
1518 log_error(LOG_LEVEL_INFO, "Decompression didn't result in any content.");
1523 /* It seems that zlib did something weird. */
1524 log_error(LOG_LEVEL_ERROR,
1525 "Unexpected error decompressing the buffer (iob): %d==%d, %d>%d, %d<%d",
1526 csp->iob->cur, csp->iob->buf + skip_size, csp->iob->eod, csp->iob->buf,
1527 csp->iob->eod, csp->iob->buf + csp->iob->size);
1528 return JB_ERR_COMPRESS;
1534 #endif /* defined(FEATURE_ZLIB) */
1537 /*********************************************************************
1539 * Function : string_move
1541 * Description : memmove wrapper to move the last part of a string
1542 * towards the beginning, overwriting the part in
1543 * the middle. strlcpy() can't be used here as the
1547 * 1 : dst = Destination to overwrite
1548 * 2 : src = Source to move.
1552 *********************************************************************/
1553 static void string_move(char *dst, char *src)
1557 /* +1 to copy the terminating nul as well. */
1558 memmove(dst, src, strlen(src)+1);
1562 /*********************************************************************
1564 * Function : normalize_lws
1566 * Description : Reduces unquoted linear white space in headers
1567 * to a single space in accordance with RFC 2616 2.2.
1568 * This simplifies parsing and filtering later on.
1570 * XXX: Remove log messages before
1571 * the next stable release?
1574 * 1 : header = A header with linear white space to reduce.
1578 *********************************************************************/
1579 static void normalize_lws(char *header)
1585 if (ijb_isspace(*p) && ijb_isspace(*(p+1)))
1589 while (ijb_isspace(*q))
1593 log_error(LOG_LEVEL_HEADER, "Reducing white space in '%s'", header);
1594 string_move(p+1, q);
1599 log_error(LOG_LEVEL_HEADER,
1600 "Converting tab to space in '%s'", header);
1605 char *end_of_token = strstr(p+1, "\"");
1607 if (NULL != end_of_token)
1609 /* Don't mess with quoted text. */
1614 log_error(LOG_LEVEL_HEADER,
1615 "Ignoring single quote in '%s'", header);
1621 p = strchr(header, ':');
1622 if ((p != NULL) && (p != header) && ijb_isspace(*(p-1)))
1625 * There's still space before the colon.
1628 string_move(p-1, p);
1633 /*********************************************************************
1635 * Function : get_header
1637 * Description : This (odd) routine will parse the csp->iob
1638 * to get the next complete header.
1641 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1643 * Returns : Any one of the following:
1645 * 1) a pointer to a dynamically allocated string that contains a header line
1646 * 2) NULL indicating that the end of the header was reached
1647 * 3) "" indicating that the end of the iob was reached before finding
1648 * a complete header line.
1650 *********************************************************************/
1651 char *get_header(struct iob *iob)
1655 header = get_header_line(iob);
1657 if ((header == NULL) || (*header == '\0'))
1660 * No complete header read yet, tell the client.
1665 while ((iob->cur[0] == ' ') || (iob->cur[0] == '\t'))
1668 * Header spans multiple lines, append the next one.
1670 char *continued_header;
1672 continued_header = get_header_line(iob);
1673 if ((continued_header == NULL) || (*continued_header == '\0'))
1676 * No complete header read yet, return what we got.
1677 * XXX: Should "unread" header instead.
1679 log_error(LOG_LEVEL_INFO,
1680 "Failed to read a multi-line header properly: '%s'",
1685 if (JB_ERR_OK != string_join(&header, continued_header))
1687 log_error(LOG_LEVEL_FATAL,
1688 "Out of memory while appending multiple headers.");
1692 /* XXX: remove before next stable release. */
1693 log_error(LOG_LEVEL_HEADER,
1694 "Merged multiple header lines to: '%s'",
1699 normalize_lws(header);
1706 /*********************************************************************
1708 * Function : get_header_line
1710 * Description : This (odd) routine will parse the csp->iob
1711 * to get the next header line.
1714 * 1 : iob = The I/O buffer to parse, usually csp->iob.
1716 * Returns : Any one of the following:
1718 * 1) a pointer to a dynamically allocated string that contains a header line
1719 * 2) NULL indicating that the end of the header was reached
1720 * 3) "" indicating that the end of the iob was reached before finding
1721 * a complete header line.
1723 *********************************************************************/
1724 static char *get_header_line(struct iob *iob)
1728 if ((iob->cur == NULL)
1729 || ((p = strchr(iob->cur, '\n')) == NULL))
1731 return(""); /* couldn't find a complete header */
1736 ret = strdup(iob->cur);
1739 /* FIXME No way to handle error properly */
1740 log_error(LOG_LEVEL_FATAL, "Out of memory in get_header_line()");
1745 if ((q = strchr(ret, '\r')) != NULL) *q = '\0';
1747 /* is this a blank line (i.e. the end of the header) ? */
1759 /*********************************************************************
1761 * Function : get_header_value
1763 * Description : Get the value of a given header from a chained list
1764 * of header lines or return NULL if no such header is
1765 * present in the list.
1768 * 1 : header_list = pointer to list
1769 * 2 : header_name = string with name of header to look for.
1770 * Trailing colon required, capitalization
1773 * Returns : NULL if not found, else value of header
1775 *********************************************************************/
1776 char *get_header_value(const struct list *header_list, const char *header_name)
1778 struct list_entry *cur_entry;
1782 assert(header_list);
1783 assert(header_name);
1784 length = strlen(header_name);
1786 for (cur_entry = header_list->first; cur_entry ; cur_entry = cur_entry->next)
1790 if (!strncmpic(cur_entry->str, header_name, length))
1793 * Found: return pointer to start of value
1795 ret = cur_entry->str + length;
1796 while (*ret && ijb_isspace(*ret)) ret++;
1810 /*********************************************************************
1812 * Function : scan_headers
1814 * Description : Scans headers, applies tags and updates action bits.
1817 * 1 : csp = Current client state (buffers, headers, etc...)
1819 * Returns : JB_ERR_OK
1821 *********************************************************************/
1822 static jb_err scan_headers(struct client_state *csp)
1824 struct list_entry *h; /* Header */
1825 jb_err err = JB_ERR_OK;
1827 for (h = csp->headers->first; (err == JB_ERR_OK) && (h != NULL) ; h = h->next)
1829 /* Header crunch()ed in previous run? -> ignore */
1830 if (h->str == NULL) continue;
1831 log_error(LOG_LEVEL_HEADER, "scan: %s", h->str);
1832 err = header_tagger(csp, h->str);
1839 /*********************************************************************
1843 * Description : add, delete or modify lines in the HTTP header streams.
1844 * On entry, it receives a linked list of headers space
1845 * that was allocated dynamically (both the list nodes
1846 * and the header contents).
1848 * As a side effect it frees the space used by the original
1852 * 1 : csp = Current client state (buffers, headers, etc...)
1853 * 2 : filter_server_headers = Boolean to switch between
1854 * server and header filtering.
1856 * Returns : JB_ERR_OK in case off success, or
1857 * JB_ERR_MEMORY on out-of-memory error.
1859 *********************************************************************/
1860 jb_err sed(struct client_state *csp, int filter_server_headers)
1862 /* XXX: use more descriptive names. */
1863 struct list_entry *p;
1864 const struct parsers *v;
1865 const add_header_func_ptr *f;
1866 jb_err err = JB_ERR_OK;
1868 if (filter_server_headers)
1870 v = server_patterns;
1871 f = add_server_headers;
1875 v = client_patterns;
1876 f = add_client_headers;
1881 while ((err == JB_ERR_OK) && (v->str != NULL))
1883 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1885 /* Header crunch()ed in previous run? -> ignore */
1886 if (p->str == NULL) continue;
1888 /* Does the current parser handle this header? */
1889 if ((strncmpic(p->str, v->str, v->len) == 0) ||
1890 (v->len == CHECK_EVERY_HEADER_REMAINING))
1892 err = v->parser(csp, &(p->str));
1898 /* place additional headers on the csp->headers list */
1899 while ((err == JB_ERR_OK) && (*f))
1909 /*********************************************************************
1911 * Function : update_server_headers
1913 * Description : Updates server headers after the body has been modified.
1916 * 1 : csp = Current client state (buffers, headers, etc...)
1918 * Returns : JB_ERR_OK in case off success, or
1919 * JB_ERR_MEMORY on out-of-memory error.
1921 *********************************************************************/
1922 jb_err update_server_headers(struct client_state *csp)
1924 jb_err err = JB_ERR_OK;
1926 static const struct parsers server_patterns_light[] = {
1927 { "Content-Length:", 15, server_adjust_content_length },
1928 { "Transfer-Encoding:", 18, server_transfer_coding },
1930 { "Content-Encoding:", 17, server_content_encoding },
1931 #endif /* def FEATURE_ZLIB */
1935 if (strncmpic(csp->http->cmd, "HEAD", 4))
1937 const struct parsers *v;
1938 struct list_entry *p;
1940 for (v = server_patterns_light; (err == JB_ERR_OK) && (v->str != NULL); v++)
1942 for (p = csp->headers->first; (err == JB_ERR_OK) && (p != NULL); p = p->next)
1944 /* Header crunch()ed in previous run? -> ignore */
1945 if (p->str == NULL) continue;
1947 /* Does the current parser handle this header? */
1948 if (strncmpic(p->str, v->str, v->len) == 0)
1950 err = v->parser(csp, (char **)&(p->str));
1960 /*********************************************************************
1962 * Function : header_tagger
1964 * Description : Executes all text substitutions from applying
1965 * tag actions and saves the result as tag.
1967 * XXX: Shares enough code with filter_header() and
1968 * pcrs_filter_response() to warrant some helper functions.
1971 * 1 : csp = Current client state (buffers, headers, etc...)
1972 * 2 : header = Header that is used as tagger input
1974 * Returns : JB_ERR_OK on success and always succeeds
1976 *********************************************************************/
1977 static jb_err header_tagger(struct client_state *csp, char *header)
1979 int wanted_filter_type;
1980 int multi_action_index;
1984 struct file_list *fl;
1985 struct re_filterfile_spec *b;
1986 struct list_entry *tag_name;
1988 int found_filters = 0;
1989 const size_t header_length = strlen(header);
1991 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
1993 wanted_filter_type = FT_SERVER_HEADER_TAGGER;
1994 multi_action_index = ACTION_MULTI_SERVER_HEADER_TAGGER;
1998 wanted_filter_type = FT_CLIENT_HEADER_TAGGER;
1999 multi_action_index = ACTION_MULTI_CLIENT_HEADER_TAGGER;
2002 /* Check if there are any filters */
2003 for (i = 0; i < MAX_AF_FILES; i++)
2016 if (0 == found_filters)
2018 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2019 "tagging enabled, but no taggers available.");
2023 for (i = 0; i < MAX_AF_FILES; i++)
2026 if ((NULL == fl) || (NULL == fl->f))
2029 * Either there are no filter files
2030 * left, or this filter file just
2031 * contains no valid filters.
2033 * Continue to be sure we don't miss
2034 * valid filter files that are chained
2035 * after empty or invalid ones.
2040 /* For all filters, */
2041 for (b = fl->f; b; b = b->next)
2043 if (b->type != wanted_filter_type)
2045 /* skip the ones we don't care about, */
2048 /* leaving only taggers that could apply, of which we use the ones, */
2049 for (tag_name = csp->action->multi[multi_action_index]->first;
2050 NULL != tag_name; tag_name = tag_name->next)
2052 /* that do apply, and */
2053 if (strcmp(b->name, tag_name->str) == 0)
2055 char *modified_tag = NULL;
2057 size_t size = header_length;
2058 pcrs_job *joblist = b->joblist;
2060 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2062 if (NULL == joblist)
2064 log_error(LOG_LEVEL_RE_FILTER,
2065 "Tagger %s has empty joblist. Nothing to do.", b->name);
2069 /* execute their pcrs_joblist on the header. */
2070 for (job = joblist; NULL != job; job = job->next)
2072 const int hits = pcrs_execute(job, tag, size, &modified_tag, &size);
2076 /* Success, continue with the modified version. */
2085 /* Tagger doesn't match */
2088 /* Regex failure, log it but continue anyway. */
2089 log_error(LOG_LEVEL_ERROR,
2090 "Problems with tagger \'%s\' and header \'%s\': %s",
2091 b->name, *header, pcrs_strerror(hits));
2093 freez(modified_tag);
2097 if (b->dynamic) pcrs_free_joblist(joblist);
2099 /* If this tagger matched */
2105 * There is to technical limitation which makes
2106 * it impossible to use empty tags, but I assume
2107 * no one would do it intentionally.
2110 log_error(LOG_LEVEL_INFO,
2111 "Tagger \'%s\' created an empty tag. Ignored.",
2116 if (!list_contains_item(csp->tags, tag))
2118 if (JB_ERR_OK != enlist(csp->tags, tag))
2120 log_error(LOG_LEVEL_ERROR,
2121 "Insufficient memory to add tag \'%s\', "
2122 "based on tagger \'%s\' and header \'%s\'",
2123 tag, b->name, *header);
2127 char *action_message;
2129 * update the action bits right away, to make
2130 * tagging based on tags set by earlier taggers
2131 * of the same kind possible.
2133 if (update_action_bits_for_tag(csp, tag))
2135 action_message = "Action bits updated accordingly.";
2139 action_message = "No action bits update necessary.";
2142 log_error(LOG_LEVEL_HEADER,
2143 "Tagger \'%s\' added tag \'%s\'. %s",
2144 b->name, tag, action_message);
2149 /* XXX: Is this log-worthy? */
2150 log_error(LOG_LEVEL_HEADER,
2151 "Tagger \'%s\' didn't add tag \'%s\'. "
2152 "Tag already present", b->name, tag);
2155 } /* if the tagger matched */
2156 } /* if the tagger applies */
2157 } /* for every tagger that could apply */
2158 } /* for all filters */
2159 } /* for all filter files */
2164 /* here begins the family of parser functions that reformat header lines */
2166 /*********************************************************************
2168 * Function : filter_header
2170 * Description : Executes all text substitutions from all applying
2171 * +(server|client)-header-filter actions on the header.
2172 * Most of the code was copied from pcrs_filter_response,
2173 * including the rather short variable names
2176 * 1 : csp = Current client state (buffers, headers, etc...)
2177 * 2 : header = On input, pointer to header to modify.
2178 * On output, pointer to the modified header, or NULL
2179 * to remove the header. This function frees the
2180 * original string if necessary.
2182 * Returns : JB_ERR_OK on success and always succeeds
2184 *********************************************************************/
2185 static jb_err filter_header(struct client_state *csp, char **header)
2189 size_t size = strlen(*header);
2191 char *newheader = NULL;
2194 struct file_list *fl;
2195 struct re_filterfile_spec *b;
2196 struct list_entry *filtername;
2198 int i, found_filters = 0;
2199 int wanted_filter_type;
2200 int multi_action_index;
2202 if (csp->flags & CSP_FLAG_NO_FILTERING)
2207 if (csp->flags & CSP_FLAG_CLIENT_HEADER_PARSING_DONE)
2209 wanted_filter_type = FT_SERVER_HEADER_FILTER;
2210 multi_action_index = ACTION_MULTI_SERVER_HEADER_FILTER;
2214 wanted_filter_type = FT_CLIENT_HEADER_FILTER;
2215 multi_action_index = ACTION_MULTI_CLIENT_HEADER_FILTER;
2219 * Need to check the set of re_filterfiles...
2221 for (i = 0; i < MAX_AF_FILES; i++)
2234 if (0 == found_filters)
2236 log_error(LOG_LEVEL_ERROR, "Inconsistent configuration: "
2237 "header filtering enabled, but no matching filters available.");
2241 for (i = 0; i < MAX_AF_FILES; i++)
2244 if ((NULL == fl) || (NULL == fl->f))
2247 * Either there are no filter files
2248 * left, or this filter file just
2249 * contains no valid filters.
2251 * Continue to be sure we don't miss
2252 * valid filter files that are chained
2253 * after empty or invalid ones.
2258 * For all applying +filter actions, look if a filter by that
2259 * name exists and if yes, execute its pcrs_joblist on the
2262 for (b = fl->f; b; b = b->next)
2264 if (b->type != wanted_filter_type)
2266 /* Skip other filter types */
2270 for (filtername = csp->action->multi[multi_action_index]->first;
2271 filtername ; filtername = filtername->next)
2273 if (strcmp(b->name, filtername->str) == 0)
2275 int current_hits = 0;
2276 pcrs_job *joblist = b->joblist;
2278 if (b->dynamic) joblist = compile_dynamic_pcrs_job_list(csp, b);
2280 if (NULL == joblist)
2282 log_error(LOG_LEVEL_RE_FILTER, "Filter %s has empty joblist. Nothing to do.", b->name);
2286 log_error(LOG_LEVEL_RE_FILTER, "filtering \'%s\' (size %d) with \'%s\' ...",
2287 *header, size, b->name);
2289 /* Apply all jobs from the joblist */
2290 for (job = joblist; NULL != job; job = job->next)
2292 matches = pcrs_execute(job, *header, size, &newheader, &size);
2295 current_hits += matches;
2296 log_error(LOG_LEVEL_HEADER, "Transforming \"%s\" to \"%s\"", *header, newheader);
2298 *header = newheader;
2300 else if ( 0 == matches )
2302 /* Filter doesn't change header */
2308 log_error(LOG_LEVEL_ERROR, "Filtering \'%s\' with \'%s\' didn't work out: %s",
2309 *header, b->name, pcrs_strerror(matches));
2310 if (newheader != NULL)
2312 log_error(LOG_LEVEL_ERROR, "Freeing what's left: %s", newheader);
2318 if (b->dynamic) pcrs_free_joblist(joblist);
2320 log_error(LOG_LEVEL_RE_FILTER, "... produced %d hits (new size %d).", current_hits, size);
2321 hits += current_hits;
2328 * Additionally checking for hits is important because if
2329 * the continue hack is triggered, server headers can
2330 * arrive empty to separate multiple heads from each other.
2332 if ((0 == size) && hits)
2334 log_error(LOG_LEVEL_HEADER, "Removing empty header %s", *header);
2342 /*********************************************************************
2344 * Function : server_connection
2346 * Description : Makes sure that the value of the Connection: header
2347 * is "close" and signals server_connection_close_adder
2351 * 1 : csp = Current client state (buffers, headers, etc...)
2352 * 2 : header = On input, pointer to header to modify.
2353 * On output, pointer to the modified header, or NULL
2354 * to remove the header. This function frees the
2355 * original string if necessary.
2357 * Returns : JB_ERR_OK on success, or
2358 * JB_ERR_MEMORY on out-of-memory error.
2360 *********************************************************************/
2361 static jb_err server_connection(struct client_state *csp, char **header)
2363 char *old_header = *header;
2365 /* Do we have a 'Connection: close' header? */
2366 if (strcmpic(*header, "Connection: close"))
2368 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2369 if ((csp->config->feature_flags &
2370 RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2371 && !strcmpic(*header, "Connection: keep-alive"))
2373 /* Remember to keep the connection alive. */
2374 csp->flags |= CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
2376 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2378 *header = strdup("Connection: close");
2381 return JB_ERR_MEMORY;
2383 log_error(LOG_LEVEL_HEADER, "Replaced: \'%s\' with \'%s\'", old_header, *header);
2387 /* Signal server_connection_close_adder() to return early. */
2388 csp->flags |= CSP_FLAG_SERVER_CONNECTION_CLOSE_SET;
2393 /*********************************************************************
2395 * Function : client_connection
2397 * Description : Makes sure a proper "Connection:" header is
2398 * set and signals connection_header_adder
2402 * 1 : csp = Current client state (buffers, headers, etc...)
2403 * 2 : header = On input, pointer to header to modify.
2404 * On output, pointer to the modified header, or NULL
2405 * to remove the header. This function frees the
2406 * original string if necessary.
2408 * Returns : JB_ERR_OK on success, or
2409 * JB_ERR_MEMORY on out-of-memory error.
2411 *********************************************************************/
2412 static jb_err client_connection(struct client_state *csp, char **header)
2414 char *old_header = *header;
2415 const char *wanted_header = get_appropiate_connection_header(csp);
2417 if (strcmpic(*header, wanted_header))
2419 *header = strdup(wanted_header);
2422 return JB_ERR_MEMORY;
2424 log_error(LOG_LEVEL_HEADER,
2425 "Replaced: \'%s\' with \'%s\'", old_header, *header);
2429 /* Signal client_connection_close_adder() to return early. */
2430 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_HEADER_SET;
2436 /*********************************************************************
2438 * Function : crumble
2440 * Description : This is called if a header matches a pattern to "crunch"
2443 * 1 : csp = Current client state (buffers, headers, etc...)
2444 * 2 : header = On input, pointer to header to modify.
2445 * On output, pointer to the modified header, or NULL
2446 * to remove the header. This function frees the
2447 * original string if necessary.
2449 * Returns : JB_ERR_OK on success, or
2450 * JB_ERR_MEMORY on out-of-memory error.
2452 *********************************************************************/
2453 static jb_err crumble(struct client_state *csp, char **header)
2455 log_error(LOG_LEVEL_HEADER, "crumble crunched: %s!", *header);
2461 /*********************************************************************
2463 * Function : crunch_server_header
2465 * Description : Crunch server header if it matches a string supplied by the
2466 * user. Called from `sed'.
2469 * 1 : csp = Current client state (buffers, headers, etc...)
2470 * 2 : header = On input, pointer to header to modify.
2471 * On output, pointer to the modified header, or NULL
2472 * to remove the header. This function frees the
2473 * original string if necessary.
2475 * Returns : JB_ERR_OK on success and always succeeds
2477 *********************************************************************/
2478 static jb_err crunch_server_header(struct client_state *csp, char **header)
2480 const char *crunch_pattern;
2482 /* Do we feel like crunching? */
2483 if ((csp->action->flags & ACTION_CRUNCH_SERVER_HEADER))
2485 crunch_pattern = csp->action->string[ACTION_STRING_SERVER_HEADER];
2487 /* Is the current header the lucky one? */
2488 if (strstr(*header, crunch_pattern))
2490 log_error(LOG_LEVEL_HEADER, "Crunching server header: %s (contains: %s)", *header, crunch_pattern);
2499 /*********************************************************************
2501 * Function : server_content_type
2503 * Description : Set the content-type for filterable types (text/.*,
2504 * .*xml.*, javascript and image/gif) unless filtering has been
2505 * forbidden (CT_TABOO) while parsing earlier headers.
2506 * NOTE: Since text/plain is commonly used by web servers
2507 * for files whose correct type is unknown, we don't
2508 * set CT_TEXT for it.
2511 * 1 : csp = Current client state (buffers, headers, etc...)
2512 * 2 : header = On input, pointer to header to modify.
2513 * On output, pointer to the modified header, or NULL
2514 * to remove the header. This function frees the
2515 * original string if necessary.
2517 * Returns : JB_ERR_OK on success, or
2518 * JB_ERR_MEMORY on out-of-memory error.
2520 *********************************************************************/
2521 static jb_err server_content_type(struct client_state *csp, char **header)
2523 /* Remove header if it isn't the first Content-Type header */
2524 if ((csp->content_type & CT_DECLARED))
2527 * Another, slightly slower, way to see if
2528 * we already parsed another Content-Type header.
2530 assert(NULL != get_header_value(csp->headers, "Content-Type:"));
2532 log_error(LOG_LEVEL_ERROR,
2533 "Multiple Content-Type headers. Removing and ignoring: \'%s\'",
2541 * Signal that the Content-Type has been set.
2543 csp->content_type |= CT_DECLARED;
2545 if (!(csp->content_type & CT_TABOO))
2548 * XXX: The assumption that text/plain is a sign of
2549 * binary data seems to be somewhat unreasonable nowadays
2550 * and should be dropped after 3.0.8 is out.
2552 if ((strstr(*header, "text/") && !strstr(*header, "plain"))
2553 || strstr(*header, "xml")
2554 || strstr(*header, "application/x-javascript"))
2556 csp->content_type |= CT_TEXT;
2558 else if (strstr(*header, "image/gif"))
2560 csp->content_type |= CT_GIF;
2565 * Are we messing with the content type?
2567 if (csp->action->flags & ACTION_CONTENT_TYPE_OVERWRITE)
2570 * Make sure the user doesn't accidently
2571 * change the content type of binary documents.
2573 if ((csp->content_type & CT_TEXT) || (csp->action->flags & ACTION_FORCE_TEXT_MODE))
2576 *header = strdup("Content-Type: ");
2577 string_append(header, csp->action->string[ACTION_STRING_CONTENT_TYPE]);
2581 log_error(LOG_LEVEL_HEADER, "Insufficient memory to replace Content-Type!");
2582 return JB_ERR_MEMORY;
2584 log_error(LOG_LEVEL_HEADER, "Modified: %s!", *header);
2588 log_error(LOG_LEVEL_HEADER, "%s not replaced. "
2589 "It doesn't look like a content type that should be filtered. "
2590 "Enable force-text-mode if you know what you're doing.", *header);
2598 /*********************************************************************
2600 * Function : server_transfer_coding
2602 * Description : - Prohibit filtering (CT_TABOO) if transfer coding compresses
2603 * - Raise the CSP_FLAG_CHUNKED flag if coding is "chunked"
2604 * - Remove header if body was chunked but has been
2605 * de-chunked for filtering.
2608 * 1 : csp = Current client state (buffers, headers, etc...)
2609 * 2 : header = On input, pointer to header to modify.
2610 * On output, pointer to the modified header, or NULL
2611 * to remove the header. This function frees the
2612 * original string if necessary.
2614 * Returns : JB_ERR_OK on success, or
2615 * JB_ERR_MEMORY on out-of-memory error.
2617 *********************************************************************/
2618 static jb_err server_transfer_coding(struct client_state *csp, char **header)
2621 * Turn off pcrs and gif filtering if body compressed
2623 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2627 * XXX: Added to test if we could use CT_GZIP and CT_DEFLATE here.
2629 log_error(LOG_LEVEL_INFO, "Marking content type for %s as CT_TABOO because of %s.",
2630 csp->http->cmd, *header);
2631 #endif /* def FEATURE_ZLIB */
2632 csp->content_type = CT_TABOO;
2636 * Raise flag if body chunked
2638 if (strstr(*header, "chunked"))
2640 csp->flags |= CSP_FLAG_CHUNKED;
2643 * If the body was modified, it has been de-chunked first
2644 * and the header must be removed.
2646 * FIXME: If there is more than one transfer encoding,
2647 * only the "chunked" part should be removed here.
2649 if (csp->flags & CSP_FLAG_MODIFIED)
2651 log_error(LOG_LEVEL_HEADER, "Removing: %s", *header);
2660 /*********************************************************************
2662 * Function : server_content_encoding
2664 * Description : This function is run twice for each request,
2665 * unless FEATURE_ZLIB and filtering are disabled.
2667 * The first run is used to check if the content
2668 * is compressed, if FEATURE_ZLIB is disabled
2669 * filtering is then disabled as well, if FEATURE_ZLIB
2670 * is enabled the content is marked for decompression.
2672 * The second run is used to remove the Content-Encoding
2673 * header if the decompression was successful.
2676 * 1 : csp = Current client state (buffers, headers, etc...)
2677 * 2 : header = On input, pointer to header to modify.
2678 * On output, pointer to the modified header, or NULL
2679 * to remove the header. This function frees the
2680 * original string if necessary.
2682 * Returns : JB_ERR_OK on success, or
2683 * JB_ERR_MEMORY on out-of-memory error.
2685 *********************************************************************/
2686 static jb_err server_content_encoding(struct client_state *csp, char **header)
2689 if ((csp->flags & CSP_FLAG_MODIFIED)
2690 && (csp->content_type & (CT_GZIP | CT_DEFLATE)))
2693 * We successfully decompressed the content,
2694 * and have to clean the header now, so the
2695 * client no longer expects compressed data..
2697 * XXX: There is a difference between cleaning
2698 * and removing it completely.
2700 log_error(LOG_LEVEL_HEADER, "Crunching: %s", *header);
2703 else if (strstr(*header, "gzip"))
2705 /* Mark for gzip decompression */
2706 csp->content_type |= CT_GZIP;
2708 else if (strstr(*header, "deflate"))
2710 /* Mark for zlib decompression */
2711 csp->content_type |= CT_DEFLATE;
2713 else if (strstr(*header, "compress"))
2716 * We can't decompress this; therefore we can't filter
2719 csp->content_type |= CT_TABOO;
2721 #else /* !defined(FEATURE_ZLIB) */
2722 if (strstr(*header, "gzip") || strstr(*header, "compress") || strstr(*header, "deflate"))
2725 * Body is compressed, turn off pcrs and gif filtering.
2727 csp->content_type |= CT_TABOO;
2730 * Log a warning if the user expects the content to be filtered.
2732 if ((csp->rlist != NULL) &&
2733 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER])))
2735 log_error(LOG_LEVEL_INFO,
2736 "Compressed content detected, content filtering disabled. "
2737 "Consider recompiling Privoxy with zlib support or "
2738 "enable the prevent-compression action.");
2741 #endif /* defined(FEATURE_ZLIB) */
2748 /*********************************************************************
2750 * Function : server_adjust_content_length
2752 * Description : Adjust Content-Length header if we modified
2756 * 1 : csp = Current client state (buffers, headers, etc...)
2757 * 2 : header = On input, pointer to header to modify.
2758 * On output, pointer to the modified header, or NULL
2759 * to remove the header. This function frees the
2760 * original string if necessary.
2762 * Returns : JB_ERR_OK on success, or
2763 * JB_ERR_MEMORY on out-of-memory error.
2765 *********************************************************************/
2766 static jb_err server_adjust_content_length(struct client_state *csp, char **header)
2768 const size_t max_header_length = 80;
2770 /* Regenerate header if the content was modified. */
2771 if (csp->flags & CSP_FLAG_MODIFIED)
2774 *header = (char *) zalloc(max_header_length);
2775 if (*header == NULL)
2777 return JB_ERR_MEMORY;
2780 snprintf(*header, max_header_length, "Content-Length: %d",
2781 (int)csp->content_length);
2782 log_error(LOG_LEVEL_HEADER, "Adjusted Content-Length to %d",
2783 (int)csp->content_length);
2790 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2791 /*********************************************************************
2793 * Function : server_save_content_length
2795 * Description : Save the Content-Length sent by the server.
2798 * 1 : csp = Current client state (buffers, headers, etc...)
2799 * 2 : header = On input, pointer to header to modify.
2800 * On output, pointer to the modified header, or NULL
2801 * to remove the header. This function frees the
2802 * original string if necessary.
2804 * Returns : JB_ERR_OK on success, or
2805 * JB_ERR_MEMORY on out-of-memory error.
2807 *********************************************************************/
2808 static jb_err server_save_content_length(struct client_state *csp, char **header)
2810 unsigned int content_length = 0;
2812 assert(*(*header+14) == ':');
2814 if (1 != sscanf(*header+14, ": %u", &content_length))
2816 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
2821 csp->expected_content_length = content_length;
2822 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2827 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2830 /*********************************************************************
2832 * Function : server_content_md5
2834 * Description : Crumble any Content-MD5 headers if the document was
2835 * modified. FIXME: Should we re-compute instead?
2838 * 1 : csp = Current client state (buffers, headers, etc...)
2839 * 2 : header = On input, pointer to header to modify.
2840 * On output, pointer to the modified header, or NULL
2841 * to remove the header. This function frees the
2842 * original string if necessary.
2844 * Returns : JB_ERR_OK on success, or
2845 * JB_ERR_MEMORY on out-of-memory error.
2847 *********************************************************************/
2848 static jb_err server_content_md5(struct client_state *csp, char **header)
2850 if (csp->flags & CSP_FLAG_MODIFIED)
2852 log_error(LOG_LEVEL_HEADER, "Crunching Content-MD5");
2860 /*********************************************************************
2862 * Function : server_content_disposition
2864 * Description : If enabled, blocks or modifies the "Content-Disposition" header.
2865 * Called from `sed'.
2868 * 1 : csp = Current client state (buffers, headers, etc...)
2869 * 2 : header = On input, pointer to header to modify.
2870 * On output, pointer to the modified header, or NULL
2871 * to remove the header. This function frees the
2872 * original string if necessary.
2874 * Returns : JB_ERR_OK on success, or
2875 * JB_ERR_MEMORY on out-of-memory error.
2877 *********************************************************************/
2878 static jb_err server_content_disposition(struct client_state *csp, char **header)
2883 * Are we messing with the Content-Disposition header?
2885 if ((csp->action->flags & ACTION_HIDE_CONTENT_DISPOSITION) == 0)
2891 newval = csp->action->string[ACTION_STRING_CONTENT_DISPOSITION];
2893 if ((newval == NULL) || (0 == strcmpic(newval, "block")))
2896 * Blocking content-disposition header
2898 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2905 * Replacing Content-Disposition header
2908 *header = strdup("Content-Disposition: ");
2909 string_append(header, newval);
2911 if (*header != NULL)
2913 log_error(LOG_LEVEL_HEADER,
2914 "Content-Disposition header crunched and replaced with: %s", *header);
2917 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
2921 /*********************************************************************
2923 * Function : server_last_modified
2925 * Description : Changes Last-Modified header to the actual date
2926 * to help hide-if-modified-since.
2927 * Called from `sed'.
2930 * 1 : csp = Current client state (buffers, headers, etc...)
2931 * 2 : header = On input, pointer to header to modify.
2932 * On output, pointer to the modified header, or NULL
2933 * to remove the header. This function frees the
2934 * original string if necessary.
2936 * Returns : JB_ERR_OK on success, or
2937 * JB_ERR_MEMORY on out-of-memory error.
2939 *********************************************************************/
2940 static jb_err server_last_modified(struct client_state *csp, char **header)
2943 char buf[BUFFER_SIZE];
2946 #ifdef HAVE_GMTIME_R
2949 struct tm *timeptr = NULL;
2950 time_t now, last_modified;
2952 long int days, hours, minutes, seconds;
2955 * Are we messing with the Last-Modified header?
2957 if ((csp->action->flags & ACTION_OVERWRITE_LAST_MODIFIED) == 0)
2963 newval = csp->action->string[ACTION_STRING_LAST_MODIFIED];
2965 if (0 == strcmpic(newval, "block") )
2968 * Blocking Last-Modified header. Useless but why not.
2970 log_error(LOG_LEVEL_HEADER, "Crunching %s!", *header);
2974 else if (0 == strcmpic(newval, "reset-to-request-time"))
2977 * Setting Last-Modified Header to now.
2979 get_http_time(0, buf, sizeof(buf));
2981 *header = strdup("Last-Modified: ");
2982 string_append(header, buf);
2984 if (*header == NULL)
2986 log_error(LOG_LEVEL_HEADER, "Insufficient memory. Last-Modified header got lost, boohoo.");
2990 log_error(LOG_LEVEL_HEADER, "Reset to present time: %s", *header);
2993 else if (0 == strcmpic(newval, "randomize"))
2995 const char *header_time = *header + sizeof("Last-Modified:");
2997 log_error(LOG_LEVEL_HEADER, "Randomizing: %s", *header);
2999 #ifdef HAVE_GMTIME_R
3000 timeptr = gmtime_r(&now, &gmt);
3001 #elif FEATURE_PTHREAD
3002 privoxy_mutex_lock(&gmtime_mutex);
3003 timeptr = gmtime(&now);
3004 privoxy_mutex_unlock(&gmtime_mutex);
3006 timeptr = gmtime(&now);
3008 if (JB_ERR_OK != parse_header_time(header_time, &last_modified))
3010 log_error(LOG_LEVEL_HEADER, "Couldn't parse: %s in %s (crunching!)", header_time, *header);
3015 rtime = (long int)difftime(now, last_modified);
3024 log_error(LOG_LEVEL_HEADER, "Server time in the future.");
3026 rtime = pick_from_range(rtime);
3027 if (negative) rtime *= -1;
3028 last_modified += rtime;
3029 #ifdef HAVE_GMTIME_R
3030 timeptr = gmtime_r(&last_modified, &gmt);
3031 #elif FEATURE_PTHREAD
3032 privoxy_mutex_lock(&gmtime_mutex);
3033 timeptr = gmtime(&last_modified);
3034 privoxy_mutex_unlock(&gmtime_mutex);
3036 timeptr = gmtime(&last_modified);
3038 strftime(newheader, sizeof(newheader), "%a, %d %b %Y %H:%M:%S GMT", timeptr);
3040 *header = strdup("Last-Modified: ");
3041 string_append(header, newheader);
3043 if (*header == NULL)
3045 log_error(LOG_LEVEL_ERROR, "Insufficient memory, header crunched without replacement.");
3046 return JB_ERR_MEMORY;
3049 days = rtime / (3600 * 24);
3050 hours = rtime / 3600 % 24;
3051 minutes = rtime / 60 % 60;
3052 seconds = rtime % 60;
3054 log_error(LOG_LEVEL_HEADER,
3055 "Randomized: %s (added %d da%s %d hou%s %d minut%s %d second%s",
3056 *header, days, (days == 1) ? "y" : "ys", hours, (hours == 1) ? "r" : "rs",
3057 minutes, (minutes == 1) ? "e" : "es", seconds, (seconds == 1) ? ")" : "s)");
3061 log_error(LOG_LEVEL_HEADER, "Randomized ... or not. No time difference to work with.");
3070 /*********************************************************************
3072 * Function : client_accept_encoding
3074 * Description : Rewrite the client's Accept-Encoding header so that
3075 * if doesn't allow compression, if the action applies.
3076 * Note: For HTTP/1.0 the absence of the header is enough.
3079 * 1 : csp = Current client state (buffers, headers, etc...)
3080 * 2 : header = On input, pointer to header to modify.
3081 * On output, pointer to the modified header, or NULL
3082 * to remove the header. This function frees the
3083 * original string if necessary.
3085 * Returns : JB_ERR_OK on success, or
3086 * JB_ERR_MEMORY on out-of-memory error.
3088 *********************************************************************/
3089 static jb_err client_accept_encoding(struct client_state *csp, char **header)
3091 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3093 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress content");
3097 /* Temporarily disable the correct behaviour to
3098 * work around a PHP bug.
3100 * if (!strcmpic(csp->http->ver, "HTTP/1.1"))
3102 * *header = strdup("Accept-Encoding: identity;q=1.0, *;q=0");
3103 * if (*header == NULL)
3105 * return JB_ERR_MEMORY;
3116 /*********************************************************************
3118 * Function : client_te
3120 * Description : Rewrite the client's TE header so that
3121 * if doesn't allow compression, if the action applies.
3124 * 1 : csp = Current client state (buffers, headers, etc...)
3125 * 2 : header = On input, pointer to header to modify.
3126 * On output, pointer to the modified header, or NULL
3127 * to remove the header. This function frees the
3128 * original string if necessary.
3130 * Returns : JB_ERR_OK on success, or
3131 * JB_ERR_MEMORY on out-of-memory error.
3133 *********************************************************************/
3134 static jb_err client_te(struct client_state *csp, char **header)
3136 if ((csp->action->flags & ACTION_NO_COMPRESSION) != 0)
3139 log_error(LOG_LEVEL_HEADER, "Suppressed offer to compress transfer");
3146 /*********************************************************************
3148 * Function : client_referrer
3150 * Description : Handle the "referer" config setting properly.
3151 * Called from `sed'.
3154 * 1 : csp = Current client state (buffers, headers, etc...)
3155 * 2 : header = On input, pointer to header to modify.
3156 * On output, pointer to the modified header, or NULL
3157 * to remove the header. This function frees the
3158 * original string if necessary.
3160 * Returns : JB_ERR_OK on success, or
3161 * JB_ERR_MEMORY on out-of-memory error.
3163 *********************************************************************/
3164 static jb_err client_referrer(struct client_state *csp, char **header)
3166 const char *parameter;
3167 /* booleans for parameters we have to check multiple times */
3168 int parameter_conditional_block;
3169 int parameter_conditional_forge;
3171 #ifdef FEATURE_FORCE_LOAD
3173 * Since the referrer can include the prefix even
3174 * if the request itself is non-forced, we must
3175 * clean it unconditionally.
3177 * XXX: strclean is too broad
3179 strclean(*header, FORCE_PREFIX);
3180 #endif /* def FEATURE_FORCE_LOAD */
3182 if ((csp->action->flags & ACTION_HIDE_REFERER) == 0)
3184 /* Nothing left to do */
3188 parameter = csp->action->string[ACTION_STRING_REFERER];
3189 assert(parameter != NULL);
3190 parameter_conditional_block = (0 == strcmpic(parameter, "conditional-block"));
3191 parameter_conditional_forge = (0 == strcmpic(parameter, "conditional-forge"));
3193 if (!parameter_conditional_block && !parameter_conditional_forge)
3196 * As conditional-block and conditional-forge are the only
3197 * parameters that rely on the original referrer, we can
3198 * remove it now for all the others.
3203 if (0 == strcmpic(parameter, "block"))
3205 log_error(LOG_LEVEL_HEADER, "Referer crunched!");
3208 else if (parameter_conditional_block || parameter_conditional_forge)
3210 return handle_conditional_hide_referrer_parameter(header,
3211 csp->http->hostport, parameter_conditional_block);
3213 else if (0 == strcmpic(parameter, "forge"))
3215 return create_forged_referrer(header, csp->http->hostport);
3219 /* interpret parameter as user-supplied referer to fake */
3220 return create_fake_referrer(header, parameter);
3225 /*********************************************************************
3227 * Function : client_accept_language
3229 * Description : Handle the "Accept-Language" config setting properly.
3230 * Called from `sed'.
3233 * 1 : csp = Current client state (buffers, headers, etc...)
3234 * 2 : header = On input, pointer to header to modify.
3235 * On output, pointer to the modified header, or NULL
3236 * to remove the header. This function frees the
3237 * original string if necessary.
3239 * Returns : JB_ERR_OK on success, or
3240 * JB_ERR_MEMORY on out-of-memory error.
3242 *********************************************************************/
3243 static jb_err client_accept_language(struct client_state *csp, char **header)
3248 * Are we messing with the Accept-Language?
3250 if ((csp->action->flags & ACTION_HIDE_ACCEPT_LANGUAGE) == 0)
3252 /*I don't think so*/
3256 newval = csp->action->string[ACTION_STRING_LANGUAGE];
3258 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3261 * Blocking Accept-Language header
3263 log_error(LOG_LEVEL_HEADER, "Crunching Accept-Language!");
3270 * Replacing Accept-Language header
3273 *header = strdup("Accept-Language: ");
3274 string_append(header, newval);
3276 if (*header == NULL)
3278 log_error(LOG_LEVEL_ERROR,
3279 "Insufficient memory. Accept-Language header crunched without replacement.");
3283 log_error(LOG_LEVEL_HEADER,
3284 "Accept-Language header crunched and replaced with: %s", *header);
3287 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3291 /*********************************************************************
3293 * Function : crunch_client_header
3295 * Description : Crunch client header if it matches a string supplied by the
3296 * user. Called from `sed'.
3299 * 1 : csp = Current client state (buffers, headers, etc...)
3300 * 2 : header = On input, pointer to header to modify.
3301 * On output, pointer to the modified header, or NULL
3302 * to remove the header. This function frees the
3303 * original string if necessary.
3305 * Returns : JB_ERR_OK on success and always succeeds
3307 *********************************************************************/
3308 static jb_err crunch_client_header(struct client_state *csp, char **header)
3310 const char *crunch_pattern;
3312 /* Do we feel like crunching? */
3313 if ((csp->action->flags & ACTION_CRUNCH_CLIENT_HEADER))
3315 crunch_pattern = csp->action->string[ACTION_STRING_CLIENT_HEADER];
3317 /* Is the current header the lucky one? */
3318 if (strstr(*header, crunch_pattern))
3320 log_error(LOG_LEVEL_HEADER, "Crunching client header: %s (contains: %s)", *header, crunch_pattern);
3328 /*********************************************************************
3330 * Function : client_uagent
3332 * Description : Handle the "user-agent" config setting properly
3333 * and remember its original value to enable browser
3334 * bug workarounds. Called from `sed'.
3337 * 1 : csp = Current client state (buffers, headers, etc...)
3338 * 2 : header = On input, pointer to header to modify.
3339 * On output, pointer to the modified header, or NULL
3340 * to remove the header. This function frees the
3341 * original string if necessary.
3343 * Returns : JB_ERR_OK on success, or
3344 * JB_ERR_MEMORY on out-of-memory error.
3346 *********************************************************************/
3347 static jb_err client_uagent(struct client_state *csp, char **header)
3351 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) == 0)
3356 newval = csp->action->string[ACTION_STRING_USER_AGENT];
3363 *header = strdup("User-Agent: ");
3364 string_append(header, newval);
3366 log_error(LOG_LEVEL_HEADER, "Modified: %s", *header);
3368 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3372 /*********************************************************************
3374 * Function : client_ua
3376 * Description : Handle "ua-" headers properly. Called from `sed'.
3379 * 1 : csp = Current client state (buffers, headers, etc...)
3380 * 2 : header = On input, pointer to header to modify.
3381 * On output, pointer to the modified header, or NULL
3382 * to remove the header. This function frees the
3383 * original string if necessary.
3385 * Returns : JB_ERR_OK on success, or
3386 * JB_ERR_MEMORY on out-of-memory error.
3388 *********************************************************************/
3389 static jb_err client_ua(struct client_state *csp, char **header)
3391 if ((csp->action->flags & ACTION_HIDE_USER_AGENT) != 0)
3393 log_error(LOG_LEVEL_HEADER, "crunched User-Agent!");
3401 /*********************************************************************
3403 * Function : client_from
3405 * Description : Handle the "from" config setting properly.
3406 * Called from `sed'.
3409 * 1 : csp = Current client state (buffers, headers, etc...)
3410 * 2 : header = On input, pointer to header to modify.
3411 * On output, pointer to the modified header, or NULL
3412 * to remove the header. This function frees the
3413 * original string if necessary.
3415 * Returns : JB_ERR_OK on success, or
3416 * JB_ERR_MEMORY on out-of-memory error.
3418 *********************************************************************/
3419 static jb_err client_from(struct client_state *csp, char **header)
3423 if ((csp->action->flags & ACTION_HIDE_FROM) == 0)
3430 newval = csp->action->string[ACTION_STRING_FROM];
3433 * Are we blocking the e-mail address?
3435 if ((newval == NULL) || (0 == strcmpic(newval, "block")) )
3437 log_error(LOG_LEVEL_HEADER, "crunched From!");
3441 log_error(LOG_LEVEL_HEADER, " modified");
3443 *header = strdup("From: ");
3444 string_append(header, newval);
3446 return (*header == NULL) ? JB_ERR_MEMORY : JB_ERR_OK;
3450 /*********************************************************************
3452 * Function : client_send_cookie
3454 * Description : Crunches the "cookie" header if necessary.
3455 * Called from `sed'.
3457 * XXX: Stupid name, doesn't send squat.
3460 * 1 : csp = Current client state (buffers, headers, etc...)
3461 * 2 : header = On input, pointer to header to modify.
3462 * On output, pointer to the modified header, or NULL
3463 * to remove the header. This function frees the
3464 * original string if necessary.
3466 * Returns : JB_ERR_OK on success, or
3467 * JB_ERR_MEMORY on out-of-memory error.
3469 *********************************************************************/
3470 static jb_err client_send_cookie(struct client_state *csp, char **header)
3472 if (csp->action->flags & ACTION_NO_COOKIE_READ)
3474 log_error(LOG_LEVEL_HEADER, "Crunched outgoing cookie: %s", *header);
3482 /*********************************************************************
3484 * Function : client_x_forwarded
3486 * Description : Handle the "x-forwarded-for" config setting properly,
3487 * also used in the add_client_headers list. Called from `sed'.
3490 * 1 : csp = Current client state (buffers, headers, etc...)
3491 * 2 : header = On input, pointer to header to modify.
3492 * On output, pointer to the modified header, or NULL
3493 * to remove the header. This function frees the
3494 * original string if necessary.
3496 * Returns : JB_ERR_OK on success, or
3497 * JB_ERR_MEMORY on out-of-memory error.
3499 *********************************************************************/
3500 jb_err client_x_forwarded(struct client_state *csp, char **header)
3502 if (0 != (csp->action->flags & ACTION_CHANGE_X_FORWARDED_FOR))
3504 const char *parameter = csp->action->string[ACTION_STRING_CHANGE_X_FORWARDED_FOR];
3506 if (0 == strcmpic(parameter, "block"))
3509 log_error(LOG_LEVEL_HEADER, "crunched x-forwarded-for!");
3511 else if (0 == strcmpic(parameter, "add"))
3513 string_append(header, ", ");
3514 string_append(header, csp->ip_addr_str);
3516 if (*header == NULL)
3518 return JB_ERR_MEMORY;
3520 log_error(LOG_LEVEL_HEADER,
3521 "Appended client IP address to %s", *header);
3522 csp->flags |= CSP_FLAG_X_FORWARDED_FOR_APPENDED;
3526 log_error(LOG_LEVEL_FATAL,
3527 "Invalid change-x-forwarded-for parameter: '%s'", parameter);
3535 /*********************************************************************
3537 * Function : client_max_forwards
3539 * Description : If the HTTP method is OPTIONS or TRACE, subtract one
3540 * from the value of the Max-Forwards header field.
3543 * 1 : csp = Current client state (buffers, headers, etc...)
3544 * 2 : header = On input, pointer to header to modify.
3545 * On output, pointer to the modified header, or NULL
3546 * to remove the header. This function frees the
3547 * original string if necessary.
3549 * Returns : JB_ERR_OK on success, or
3550 * JB_ERR_MEMORY on out-of-memory error.
3552 *********************************************************************/
3553 static jb_err client_max_forwards(struct client_state *csp, char **header)
3557 if ((0 == strcmpic(csp->http->gpc, "trace")) ||
3558 (0 == strcmpic(csp->http->gpc, "options")))
3560 assert(*(*header+12) == ':');
3561 if (1 == sscanf(*header+12, ": %u", &max_forwards))
3563 if (max_forwards > 0)
3565 snprintf(*header, strlen(*header)+1, "Max-Forwards: %u", --max_forwards);
3566 log_error(LOG_LEVEL_HEADER, "Max-Forwards value for %s request reduced to %u.",
3567 csp->http->gpc, max_forwards);
3569 else if (max_forwards < 0)
3571 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3577 log_error(LOG_LEVEL_ERROR, "Crunching invalid header: %s", *header);
3586 /*********************************************************************
3588 * Function : client_host
3590 * Description : If the request URI did not contain host and
3591 * port information, parse and evaluate the Host
3594 * Also, kill ill-formed HOST: headers as sent by
3595 * Apple's iTunes software when used with a proxy.
3598 * 1 : csp = Current client state (buffers, headers, etc...)
3599 * 2 : header = On input, pointer to header to modify.
3600 * On output, pointer to the modified header, or NULL
3601 * to remove the header. This function frees the
3602 * original string if necessary.
3604 * Returns : JB_ERR_OK on success, or
3605 * JB_ERR_MEMORY on out-of-memory error.
3607 *********************************************************************/
3608 static jb_err client_host(struct client_state *csp, char **header)
3613 * If the header field name is all upper-case, chances are that it's
3614 * an ill-formed one from iTunes. BTW, killing innocent headers here is
3615 * not a problem -- they are regenerated later.
3617 if ((*header)[1] == 'O')
3619 log_error(LOG_LEVEL_HEADER, "Killed all-caps Host header line: %s", *header);
3624 if (!csp->http->hostport || (*csp->http->hostport == '*') ||
3625 *csp->http->hostport == ' ' || *csp->http->hostport == '\0')
3628 if (NULL == (p = strdup((*header)+6)))
3630 return JB_ERR_MEMORY;
3633 if (NULL == (q = strdup(p)))
3636 return JB_ERR_MEMORY;
3639 freez(csp->http->hostport);
3640 csp->http->hostport = p;
3641 freez(csp->http->host);
3642 csp->http->host = q;
3643 q = strchr(csp->http->host, ':');
3646 /* Terminate hostname and evaluate port string */
3648 csp->http->port = atoi(q);
3652 csp->http->port = csp->http->ssl ? 443 : 80;
3655 log_error(LOG_LEVEL_HEADER, "New host and port from Host field: %s = %s:%d",
3656 csp->http->hostport, csp->http->host, csp->http->port);
3659 /* Signal client_host_adder() to return right away */
3660 csp->flags |= CSP_FLAG_HOST_HEADER_IS_SET;
3666 /*********************************************************************
3668 * Function : client_if_modified_since
3670 * Description : Remove or modify the If-Modified-Since header.
3673 * 1 : csp = Current client state (buffers, headers, etc...)
3674 * 2 : header = On input, pointer to header to modify.
3675 * On output, pointer to the modified header, or NULL
3676 * to remove the header. This function frees the
3677 * original string if necessary.
3679 * Returns : JB_ERR_OK on success, or
3680 * JB_ERR_MEMORY on out-of-memory error.
3682 *********************************************************************/
3683 static jb_err client_if_modified_since(struct client_state *csp, char **header)
3686 #ifdef HAVE_GMTIME_R
3689 struct tm *timeptr = NULL;