1 const char jcc_rcs[] = "$Id: jcc.c,v 1.232 2009/03/08 19:29:16 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
6 * Purpose : Main file. Contains main() method, main loop, and
7 * the main connection-handling function.
9 * Copyright : Written by and Copyright (C) 2001-2009 the SourceForge
10 * Privoxy team. http://www.privoxy.org/
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
36 * Revision 1.232 2009/03/08 19:29:16 fabiankeil
37 * Reinitialize the timeout structure every time before passing
38 * it to select(). Apparently some implementations mess with it.
39 * Probably fixes #2669131 reported by cyberpatrol.
41 * Revision 1.231 2009/03/08 14:19:23 fabiankeil
42 * Fix justified (but harmless) compiler warnings
43 * on platforms where sizeof(int) < sizeof(long).
45 * Revision 1.230 2009/03/07 13:09:17 fabiankeil
46 * Change csp->expected_content and_csp->expected_content_length from
47 * size_t to unsigned long long to reduce the likelihood of integer
48 * overflows that would let us close the connection prematurely.
49 * Bug found while investigating #2669131, reported by cyberpatrol.
51 * Revision 1.229 2009/03/07 11:17:01 fabiankeil
52 * Fix compiler warning.
54 * Revision 1.228 2009/03/06 20:30:13 fabiankeil
55 * Log unsigned values as such.
57 * Revision 1.227 2009/03/02 19:18:11 fabiankeil
58 * Streamline parse_http_request()'s prototype. As
59 * cparser pointed out it doesn't actually use csp.
61 * Revision 1.226 2009/03/01 18:28:24 fabiankeil
62 * Help clang understand that we aren't dereferencing
65 * Revision 1.225 2009/02/19 18:09:32 fabiankeil
66 * Unbreak build without FEATURE_CONNECTION_KEEP_ALIVE.
69 * Revision 1.224 2009/02/14 15:32:04 fabiankeil
70 * Add the request URL to the timeout message in chat().
73 * Revision 1.223 2009/02/09 21:21:16 fabiankeil
74 * Now that init_log_module() is called earlier, call show_version()
75 * later on from main() directly so it doesn't get called for --help
78 * Revision 1.222 2009/02/08 12:56:51 fabiankeil
79 * Call initialize_mutexes() before init_log_module() again.
80 * Broken since r220, might be the cause of Lee's #2579448.
82 * Revision 1.221 2009/02/06 18:02:58 fabiankeil
83 * When dropping privileges, also give up membership in supplementary
84 * groups. Thanks to Matthias Drochner for reporting the problem,
85 * providing the initial patch and testing the final version.
87 * Revision 1.220 2009/02/04 18:29:07 fabiankeil
88 * Initialize the log module before parsing arguments.
89 * Thanks to Matthias Drochner for the report.
91 * Revision 1.219 2009/01/31 16:08:21 fabiankeil
92 * Remove redundant error check in receive_client_request().
94 * Revision 1.218 2009/01/31 12:25:54 fabiankeil
95 * Flatten indentation in receive_client_request().
97 * Revision 1.217 2009/01/07 19:50:09 fabiankeil
98 * - If the socket-timeout has been reached and the client
99 * hasn't received any data yet, send an explanation before
100 * closing the connection.
101 * - In get_request_line(), signal timeouts the right way.
103 * Revision 1.216 2008/12/24 22:13:11 ler762
104 * fix GCC 3.4.4 warning
106 * Revision 1.215 2008/12/24 17:06:19 fabiankeil
107 * Keep a thread around to timeout alive connections
108 * even if no new requests are coming in.
110 * Revision 1.214 2008/12/20 14:53:55 fabiankeil
111 * Add config option socket-timeout to control the time
112 * Privoxy waits for data to arrive on a socket. Useful
113 * in case of stale ssh tunnels or when fuzz-testing.
115 * Revision 1.213 2008/12/15 18:45:51 fabiankeil
116 * When logging crunches, log the whole URL, so one can easily
117 * differentiate between vanilla HTTP and CONNECT requests.
119 * Revision 1.212 2008/12/14 15:46:22 fabiankeil
120 * Give crunched requests their own log level.
122 * Revision 1.211 2008/12/06 10:05:03 fabiankeil
123 * Downgrade "Received x bytes while expecting y." message to
124 * LOG_LEVEL_CONNECT as it doesn't necessarily indicate an error.
126 * Revision 1.210 2008/12/02 22:03:18 fabiankeil
127 * Don't miscalculate byte_count if we don't get all the
128 * server headers with one read_socket() call. With keep-alive
129 * support enabled, this caused delays until the server closed
132 * Revision 1.209 2008/11/27 09:44:04 fabiankeil
133 * Cosmetics for the last commit: Don't watch out for
134 * the last chunk if the content isn't chunk-encoded or
135 * if we already determined the content length previously.
137 * Revision 1.208 2008/11/26 18:24:17 fabiankeil
138 * Recognize that the server response is complete if the
139 * last chunk is read together with the server headers.
142 * Revision 1.207 2008/11/25 17:25:16 fabiankeil
143 * Don't convert the client-header list to text until we need to.
145 * Revision 1.206 2008/11/23 17:00:11 fabiankeil
146 * Some more chat() cosmetics.
148 * Revision 1.205 2008/11/16 12:43:49 fabiankeil
149 * Turn keep-alive support into a runtime feature
150 * that is disabled by setting keep-alive-timeout
151 * to a negative value.
153 * Revision 1.204 2008/11/06 19:42:17 fabiankeil
154 * Fix last-chunk detection hack to also apply
155 * if buf[] contains nothing but the last-chunk.
157 * Revision 1.203 2008/11/06 18:34:35 fabiankeil
158 * Factor receive_client_request() and
159 * parse_client_request() out of chat().
161 * Revision 1.202 2008/11/02 18:40:34 fabiankeil
162 * If we received a different amount of data than we expected,
163 * log a warning and make sure the server socket isn't reused.
165 * Revision 1.201 2008/11/02 16:48:20 fabiankeil
166 * Revert revision 1.195 and try again.
168 * Revision 1.200 2008/10/26 16:53:18 fabiankeil
171 * Revision 1.199 2008/10/26 15:36:10 fabiankeil
172 * Remove two debug messages with LOG_LEVEL_INFO.
174 * Revision 1.198 2008/10/22 15:19:55 fabiankeil
175 * Once More, With Feeling: if there is no logfile
176 * because the user didn't specify one, we shouldn't
177 * call init_error_log() after receiving SIGHUP either.
179 * Revision 1.197 2008/10/20 17:02:40 fabiankeil
180 * If SIGHUP is received while we aren't running in daemon
181 * mode, calling init_error_log() would be a mistake.
183 * Revision 1.196 2008/10/16 09:16:41 fabiankeil
184 * - Fix two gcc44 conversion warnings.
185 * - Don't bother logging the last five bytes
188 * Revision 1.195 2008/10/13 16:04:37 fabiankeil
189 * Make sure we don't try to reuse tainted server sockets.
191 * Revision 1.194 2008/10/12 18:35:18 fabiankeil
192 * The last commit was a bit too ambitious, apparently the content
193 * length adjustment is only necessary if we aren't buffering.
195 * Revision 1.193 2008/10/12 15:57:35 fabiankeil
196 * Fix content length calculation if we read headers
197 * and the start of the body at once. Now that we have
198 * FEATURE_CONNECTION_KEEP_ALIVE, it actually matters.
200 * Revision 1.192 2008/10/11 18:19:14 fabiankeil
201 * Even more chat() cosmetics.
203 * Revision 1.191 2008/10/11 18:00:14 fabiankeil
204 * Reformat some comments in chat().
206 * Revision 1.190 2008/10/11 14:58:00 fabiankeil
207 * In case of chunk-encoded content, stop reading if
208 * the buffer looks like it ends with the last chunk.
210 * Revision 1.189 2008/10/11 09:53:00 fabiankeil
211 * Let server_response_is_complete() deal properly with
212 * content that is neither buffered nor read all at once.
214 * Revision 1.188 2008/10/09 18:21:41 fabiankeil
215 * Flush work-in-progress changes to keep outgoing connections
216 * alive where possible. Incomplete and mostly #ifdef'd out.
218 * Revision 1.187 2008/09/07 12:35:05 fabiankeil
219 * Add mutex lock support for _WIN32.
221 * Revision 1.186 2008/09/04 08:13:58 fabiankeil
222 * Prepare for critical sections on Windows by adding a
223 * layer of indirection before the pthread mutex functions.
225 * Revision 1.185 2008/08/30 12:03:07 fabiankeil
226 * Remove FEATURE_COOKIE_JAR.
228 * Revision 1.184 2008/08/22 15:34:45 fabiankeil
229 * - Silence LLVM/Clang complaint.
230 * - Make received_hup_signal static.
231 * - Hide definitions for basedir, pidfile and received_hup_signal
232 * from __EMX__ as they only seem to be used in case of #ifdef unix.
234 * Revision 1.183 2008/08/21 07:09:35 fabiankeil
235 * Accept Shoutcast responses again. Problem reported
236 * and fix suggested by Stefan in #2062860.
238 * Revision 1.182 2008/06/27 11:13:56 fabiankeil
239 * Fix possible NULL-pointer dereference reported
240 * by din_a4 in #2003937. Pointy hat to me.
242 * Revision 1.181 2008/05/21 15:47:15 fabiankeil
243 * Streamline sed()'s prototype and declare
244 * the header parse and add structures static.
246 * Revision 1.180 2008/05/21 15:26:32 fabiankeil
247 * - Mark csp as immutable for send_crunch_response().
248 * - Fix comment spelling.
250 * Revision 1.179 2008/05/20 20:13:32 fabiankeil
251 * Factor update_server_headers() out of sed(), ditch the
252 * first_run hack and make server_patterns_light static.
254 * Revision 1.178 2008/05/10 13:23:38 fabiankeil
255 * Don't provide get_header() with the whole client state
256 * structure when it only needs access to csp->iob.
258 * Revision 1.177 2008/05/10 11:51:12 fabiankeil
259 * Make the "read the rest of the headers" loop a bit more readable.
261 * Revision 1.176 2008/05/10 11:37:57 fabiankeil
262 * - Instead of logging when the IIS5 hack is enabled, log when it fails.
263 * - Remove useless comment.
265 * Revision 1.175 2008/05/09 18:53:59 fabiankeil
266 * Fix comment grammar.
268 * Revision 1.174 2008/05/07 18:05:53 fabiankeil
269 * Remove the pointless buffer in client_protocol_is_unsupported().
271 * Revision 1.173 2008/05/06 15:09:00 fabiankeil
272 * Least-effort fix for bug #1821930 (reported by Lee):
273 * If the response doesn't look like HTTP,
274 * tell the client and log the problem.
276 * Revision 1.172 2008/04/16 16:38:21 fabiankeil
277 * Don't pass the whole csp structure to flush_socket()
278 * when it only needs a file descriptor and a buffer.
280 * Revision 1.171 2008/03/27 18:27:25 fabiankeil
281 * Remove kill-popups action.
283 * Revision 1.170 2008/03/06 16:33:46 fabiankeil
284 * If limit-connect isn't used, don't limit CONNECT requests to port 443.
286 * Revision 1.169 2008/03/04 18:30:39 fabiankeil
287 * Remove the treat-forbidden-connects-like-blocks action. We now
288 * use the "blocked" page for forbidden CONNECT requests by default.
290 * Revision 1.168 2008/03/02 12:25:25 fabiankeil
291 * Also use shiny new connect_port_is_forbidden() in jcc.c.
293 * Revision 1.167 2008/02/23 16:57:12 fabiankeil
294 * Rename url_actions() to get_url_actions() and let it
295 * use the standard parameter ordering.
297 * Revision 1.166 2008/02/23 16:33:43 fabiankeil
298 * Let forward_url() use the standard parameter ordering
299 * and mark its second parameter immutable.
301 * Revision 1.165 2008/02/02 19:36:56 fabiankeil
302 * Remove the "Listening ... for local connections only" log message.
303 * Whether or not remote connections are able to reach Privoxy is up
304 * to the operating system.
306 * Revision 1.164 2007/12/16 18:32:46 fabiankeil
307 * Prevent the log messages for CONNECT requests to unacceptable
308 * ports from printing the limit-connect argument as [null] if
309 * limit-connect hasn't been explicitly enabled.
311 * Revision 1.163 2007/12/13 01:47:11 david__schmidt
312 * Make sure all console-mode apps get a usage() instance
314 * Revision 1.162 2007/12/06 17:54:57 fabiankeil
315 * Reword NO_SERVER_DATA_RESPONSE to make it harder
316 * to misunderstand what the message is all about.
318 * Revision 1.161 2007/12/04 19:44:22 fabiankeil
319 * Unbreak trustfile which previously didn't work without
320 * FEATURE_TOGGLE. Fixes BR#1843585, reported by Lee.
322 * Revision 1.160 2007/11/29 18:00:29 fabiankeil
323 * Plug memory leak. Spotted by Valgrind, triggered by
324 * Privoxy-Regression-Test feeding proxyfuzz.py.
326 * Revision 1.159 2007/11/24 14:34:09 fabiankeil
327 * In the HTTP snipplets, refer to the client as client.
329 * Revision 1.158 2007/11/11 16:44:17 fabiankeil
330 * Emit a log message when activating the MS IIS5 hack.
332 * Revision 1.157 2007/11/03 17:34:49 fabiankeil
333 * Log the "weak randomization factor" warning only
334 * once for mingw32 and provide some more details.
336 * Revision 1.156 2007/11/01 18:20:58 fabiankeil
337 * Initialize log module after initializing mutexes, future
338 * deadlocks in that code should now work cross-platform.
340 * Revision 1.155 2007/10/23 20:12:45 fabiankeil
341 * Fix first CSUCCEED line to end in \r\n as required by RFC1945.
342 * Reported by Bert van Leeuwen in BR#1818808.
344 * Revision 1.154 2007/10/19 17:00:08 fabiankeil
345 * Downgrade "Flushing header and buffers" message to LOG_LEVEL_INFO.
347 * Revision 1.153 2007/10/14 14:12:41 fabiankeil
348 * When in daemon mode, close stderr after the configuration file has been
349 * parsed the first time. If logfile isn't set, stop logging. Fixes BR#897436.
351 * Revision 1.152 2007/10/04 18:03:34 fabiankeil
352 * - Fix a crash when parsing invalid requests whose first header
353 * is rejected by get_header(). Regression (re?)introduced
354 * in r1.143 by yours truly.
355 * - Move ACTION_VANILLA_WAFER handling into parsers.c's
356 * client_cookie_adder() to make sure send-vanilla-wafer can be
357 * controlled through tags (and thus regression-tested).
359 * Revision 1.151 2007/09/29 10:21:16 fabiankeil
360 * - Move get_filter_function() from jcc.c to filters.c
361 * so the filter functions can be static.
362 * - Don't bother filtering body-less responses.
364 * Revision 1.150 2007/09/28 16:39:29 fabiankeil
365 * Execute content filters through execute_content_filter().
367 * Revision 1.149 2007/09/04 15:08:48 fabiankeil
368 * Initialize req to NULL to make sure it's defined if the
369 * first read_socket() call fails. Reported by icmp30.
371 * Revision 1.148 2007/08/26 16:47:13 fabiankeil
372 * Add Stephen Gildea's --pre-chroot-nslookup patch [#1276666],
373 * extensive comments moved to user manual.
375 * Revision 1.147 2007/08/25 14:42:40 fabiankeil
376 * Don't crash if a broken header filter wiped out the request line.
378 * Revision 1.146 2007/08/20 17:09:32 fabiankeil
379 * Fix byte_count calculation in case of flushes
380 * and don't parse the server headers a second time.
382 * Revision 1.145 2007/08/19 13:13:31 fabiankeil
383 * - If there's a connection problem after we already forwarded
384 * parts of the original content, just hang up. Fixes BR#1776724.
385 * - Fix warnings about unused code on mingw32.
386 * - In case of flushes, calculate the byte count
387 * less incorrectly (I think).
389 * Revision 1.144 2007/08/11 14:43:22 fabiankeil
390 * Add some more prototypes for static functions.
392 * Revision 1.143 2007/08/05 13:58:19 fabiankeil
393 * Comment out request_contains_null_bytes() until it's used again.
395 * Revision 1.142 2007/08/05 13:50:26 fabiankeil
396 * #1763173 from Stefan Huehner: s@const static@static const@
397 * and declare some more functions static.
399 * Revision 1.141 2007/08/04 09:56:23 fabiankeil
400 * - Log rejected CONNECT requests with LOG_LEVEL_INFO
401 * and explain why they were rejected in the first place.
402 * - Fix the LOG_LEVEL_CLF message for crunches of unallowed
403 * CONNECT requests. The request line was missing.
404 * - Add two more XXX reminders as we don't have enough already.
406 * Revision 1.140 2007/07/21 11:51:36 fabiankeil
407 * As Hal noticed, checking dispatch_cgi() as the last cruncher
408 * looks like a bug if CGI requests are blocked unintentionally,
409 * so don't do it unless the user enabled the new config option
410 * "allow-cgi-request-crunching".
412 * Revision 1.139 2007/07/14 07:46:41 fabiankeil
413 * - Allow to rewrite the request destination behind the client's back.
414 * - Turn the weird-looking unconditional for loop that
415 * reads the client request into a conditional while loop.
416 * Move the stuff that only runs once out of the loop.
417 * - Move parts of chat(), server_content_type() and the
418 * necessary stuff to fix BR#1750917 into get_filter_function().
420 * Revision 1.138 2007/06/03 18:45:18 fabiankeil
421 * Temporary workaround for BR#1730105.
423 * Revision 1.137 2007/06/01 18:16:36 fabiankeil
424 * Use the same mutex for gethostbyname() and gethostbyaddr() to prevent
425 * deadlocks and crashes on OpenBSD and possibly other OS with neither
426 * gethostbyname_r() nor gethostaddr_r(). Closes BR#1729174.
427 * Thanks to Ralf Horstmann for report and solution.
429 * Revision 1.136 2007/06/01 16:41:11 fabiankeil
430 * Add forward-override{} to change the forwarding settings through
431 * action sections. This is mainly interesting to forward different
432 * clients differently (for example based on User-Agent or request
435 * Revision 1.135 2007/05/24 17:03:50 fabiankeil
436 * - Let usage() mention the --chroot parameter.
437 * - Use read_socket() consistently and always leave
438 * the last buffer byte alone, even in cases where
439 * null termination (currently) doesn't matter.
441 * Revision 1.134 2007/05/16 14:59:46 fabiankeil
442 * - Fix config file loading on Unix if no config file is specified.
443 * Since r1.97 Privoxy would always interpret the last argument as
444 * config file, even if it's a valid command line option.
445 * - Abort in case of unrecognized command line options. Closes #1719696.
446 * - Remove a bunch of unnecessary strcpy() calls (yay for c&p without thinking).
447 * - Replace the remaining strcpy() and strcat() calls with strlcpy() and strcat().
449 * Revision 1.133 2007/05/04 11:23:19 fabiankeil
450 * - Don't rerun crunchers that only depend on the request URL.
451 * - Don't count redirects and CGI requests as "blocked requests".
453 * Revision 1.132 2007/04/25 15:15:17 fabiankeil
454 * Support crunching based on tags created by server-header taggers.
456 * Revision 1.131 2007/04/22 13:24:50 fabiankeil
457 * Make HTTP snippets static (again). Add a Content-Type for those
458 * with content so the browser doesn't guess it based on the URL.
460 * Revision 1.130 2007/04/19 13:47:34 fabiankeil
461 * Move crunching and request line rebuilding out of chat().
463 * Revision 1.129 2007/04/15 16:39:20 fabiankeil
464 * Introduce tags as alternative way to specify which
465 * actions apply to a request. At the moment tags can be
466 * created based on client and server headers.
468 * Revision 1.128 2007/03/25 16:55:54 fabiankeil
469 * Don't CLF-log CONNECT requests twice.
471 * Revision 1.127 2007/03/20 13:53:17 fabiankeil
472 * Log the source address for ACL-related connection drops.
474 * Revision 1.126 2007/03/17 15:20:05 fabiankeil
475 * New config option: enforce-blocks.
477 * Revision 1.125 2007/03/09 14:12:00 fabiankeil
478 * - Move null byte check into separate function.
479 * - Don't confuse the client with error pages
480 * if a CONNECT request was already confirmed.
482 * Revision 1.124 2007/02/23 14:59:54 fabiankeil
483 * Speed up NULL byte escaping and only log the complete
484 * NULL byte requests with header debugging enabled.
486 * Revision 1.123 2007/02/21 18:42:10 fabiankeil
487 * Answer requests that contain NULL bytes with
488 * a custom response instead of waiting for more
489 * data until the client eventually hangs up.
491 * Revision 1.122 2007/02/07 11:12:02 fabiankeil
492 * - Move delivery and logging of crunched responses
493 * from chat() into send_crunch_response().
494 * - Display the reason for generating http_responses.
495 * - Log the content length for LOG_LEVEL_CLF correctly
496 * (still incorrect for some fixed responses).
497 * - Reword an incorrect comment about
498 * treat-forbidden-connects-like-blocks violating
500 * - Add some log messages.
502 * Revision 1.121 2007/01/27 10:52:56 fabiankeil
503 * Move mutex initialization into separate
504 * function and exit in case of errors.
506 * Revision 1.120 2007/01/26 14:18:42 fabiankeil
507 * - Start to reduce chat()'s line count and move
508 * parts of it into separate functions.
509 * - Add "HTTP/1.1 100 Continue" hack for BR 756734.
511 * Revision 1.119 2007/01/25 14:02:30 fabiankeil
512 * - Add Proxy-Agent header to HTTP snippets that are
513 * supposed to reach HTTP clients only.
514 * - Made a few CONNECT log messages more descriptive.
515 * - Catch completely empty server responses (as seen
516 * with Tor's fake ".noconnect" top level domain).
517 * - Use shiny new "forwarding-failed" template for socks errors.
519 * Revision 1.118 2007/01/07 07:43:43 joergs
520 * AmigaOS4 support added.
522 * Revision 1.117 2006/12/31 17:56:37 fabiankeil
523 * Added config option accept-intercepted-requests
524 * and disabled it by default.
526 * Revision 1.116 2006/12/29 19:08:22 fabiankeil
527 * Reverted parts of my last commit
528 * to keep error handling working.
530 * Revision 1.115 2006/12/29 17:38:57 fabiankeil
531 * Fixed gcc43 conversion warnings.
533 * Revision 1.114 2006/12/27 18:52:02 fabiankeil
534 * Fix -pedantic ISO C warning about converting
535 * from function pointer to object pointer.
537 * Revision 1.113 2006/12/26 17:38:50 fabiankeil
538 * Silence compiler warning I introduced with my last commit.
540 * Revision 1.112 2006/12/26 17:31:41 fabiankeil
541 * Mutex protect rand() if POSIX threading
542 * is used, warn the user if that's not possible
543 * and stop using it on _WIN32 where it could
546 * Revision 1.111 2006/12/23 16:15:06 fabiankeil
547 * Don't prevent core dumps by catching SIGABRT.
548 * It's rude and makes debugging unreasonable painful.
550 * Revision 1.110 2006/12/13 14:52:53 etresoft
551 * Fix build failure on MacOS X. Global symbols can be either static or extern, but not both.
553 * Revision 1.109 2006/12/06 19:41:40 fabiankeil
554 * Privoxy is now able to run as intercepting
555 * proxy in combination with any packet filter
556 * that does the port redirection. The destination
557 * is extracted from the "Host:" header which
558 * should be available for nearly all requests.
560 * Moved HTTP snipplets into jcc.c.
561 * Added error message for gopher proxy requests.
563 * Revision 1.108 2006/11/28 15:38:51 fabiankeil
564 * Only unlink the pidfile if it's actually used.
566 * Change order of interception checks to make
567 * it possible to block or redirect requests for
570 * Revision 1.107 2006/11/13 19:05:51 fabiankeil
571 * Make pthread mutex locking more generic. Instead of
572 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
573 * and use mutex locking unless there is an _r function
574 * available. Better safe than sorry.
576 * Fixes "./configure --disable-pthread" and should result
577 * in less threading-related problems on pthread-using platforms,
578 * but it still doesn't fix BR#1122404.
580 * Revision 1.106 2006/11/06 19:58:23 fabiankeil
581 * Move pthread.h inclusion from jcc.c to jcc.h.
582 * Fixes build on x86-freebsd1 (FreeBSD 5.4-RELEASE).
584 * Revision 1.105 2006/11/06 14:26:02 fabiankeil
585 * Don't exit after receiving the second SIGHUP on Solaris.
587 * Fixes BR 1052235, but the same problem may exist on other
588 * systems. Once 3.0.6 is out we should use sigset()
589 * where available and see if it breaks anything.
591 * Revision 1.104 2006/09/23 13:26:38 roro
592 * Replace TABs by spaces in source code.
594 * Revision 1.103 2006/09/21 12:54:43 fabiankeil
595 * Fix +redirect{}. Didn't work with -fast-redirects.
597 * Revision 1.102 2006/09/06 13:03:04 fabiankeil
598 * Respond with 400 and a short text message
599 * if the client tries to use Privoxy as FTP proxy.
601 * Revision 1.101 2006/09/06 09:23:37 fabiankeil
602 * Make number of retries in case of forwarded-connect problems
603 * a config file option (forwarded-connect-retries) and use 0 as
606 * Revision 1.100 2006/09/03 19:42:59 fabiankeil
607 * Set random(3) seed.
609 * Revision 1.99 2006/09/02 15:36:42 fabiankeil
610 * Follow the OpenBSD port's lead and protect the resolve
611 * functions on OpenBSD as well.
613 * Revision 1.98 2006/08/24 11:01:34 fabiankeil
614 * --user fix. Only use the user as group if no group is specified.
615 * Solves BR 1492612. Thanks to Spinor S. and David Laight.
617 * Revision 1.97 2006/08/18 15:23:17 david__schmidt
618 * Windows service (re-)integration
622 * --install[:service_name]
623 * --uninstall[:service_name]
626 * They work as follows:
627 * --install will create a service for you and then terminate.
628 * By default the service name will be "privoxy" (without the quotes).
629 * However you can run multiple services if you wish, just by adding
630 * a colon and then a name (no spaces).
632 * --uninstall follows the exact same rules a --install.
634 * --service is used when the program is executed by the service
635 * control manager, and in normal circumstances would never be
636 * used as a command line argument.
638 * Revision 1.96 2006/08/15 20:12:36 david__schmidt
639 * Windows service integration
641 * Revision 1.95 2006/08/03 02:46:41 david__schmidt
642 * Incorporate Fabian Keil's patch work:
643 http://www.fabiankeil.de/sourcecode/privoxy/
645 * Revision 1.94 2006/07/18 14:48:46 david__schmidt
646 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
647 * with what was really the latest development (the v_3_0_branch branch)
649 * Revision 1.92.2.16 2005/04/03 20:10:50 david__schmidt
650 * Thanks to Jindrich Makovicka for a race condition fix for the log
651 * file. The race condition remains for non-pthread implementations.
652 * Reference patch #1175720.
654 * Revision 1.92.2.15 2004/10/03 12:53:32 david__schmidt
655 * Add the ability to check jpeg images for invalid
656 * lengths of comment blocks. Defensive strategy
657 * against the exploit:
658 * Microsoft Security Bulletin MS04-028
659 * Buffer Overrun in JPEG Processing (GDI+) Could
660 * Allow Code Execution (833987)
661 * Enabled with +inspect-jpegs in actions files.
663 * Revision 1.92.2.14 2003/12/12 12:52:53 oes
664 * - Fixed usage info for non-unix platforms
665 * - Fixed small cmdline parsing bug
667 * Revision 1.92.2.13 2003/11/27 19:20:27 oes
668 * Diagnostics: Now preserve the returncode of pthread_create
669 * in errno. Closes BR #775721. Thanks to Geoffrey Hausheer.
671 * Revision 1.92.2.12 2003/07/11 11:34:19 oes
672 * No longer ignore SIGCHLD. Fixes bug #769381
674 * Revision 1.92.2.11 2003/05/14 12:32:02 oes
675 * Close jarfile on graceful exit, remove stray line
677 * Revision 1.92.2.10 2003/05/08 15:13:46 oes
678 * Cosmetics: Killed a warning, a typo and an allocation left at exit
680 * Revision 1.92.2.9 2003/04/03 15:08:42 oes
681 * No longer rely on non-POSIX.1 extensions of getcwd().
684 * Revision 1.92.2.8 2003/03/31 13:12:32 oes
685 * Replaced setenv() by posix-compliant putenv()
686 * Thanks to Neil McCalden (nmcc AT users.sf.net).
688 * Revision 1.92.2.7 2003/03/17 16:48:59 oes
689 * Added chroot ability, thanks to patch by Sviatoslav Sviridov
691 * Revision 1.92.2.6 2003/03/11 11:55:00 oes
692 * Clean-up and extension of improvements for forked mode:
693 * - Child's return code now consists of flags RC_FLAG_*
694 * - Reporting toggle to parent now properly #ifdef'ed
695 * - Children now report blocking to parent. This enables
696 * statistics in forked mode
698 * Revision 1.92.2.5 2003/03/10 23:45:32 oes
699 * Fixed bug #700381: Non-Threaded version now capable of being toggled.
700 * Children now report having been toggled through _exit(17), parents
701 * watch for that code and toggle themselves if found.
703 * Revision 1.92.2.4 2003/03/07 03:41:04 david__schmidt
704 * Wrapping all *_r functions (the non-_r versions of them) with
705 * mutex semaphores for OSX. Hopefully this will take care of all
706 * of those pesky crash reports.
708 * Revision 1.92.2.3 2003/02/28 12:53:06 oes
709 * Fixed two mostly harmless mem leaks
711 * Revision 1.92.2.2 2002/11/20 14:37:47 oes
712 * Fix: Head of global clients list now initialized to NULL
714 * Revision 1.92.2.1 2002/09/25 14:52:24 oes
715 * Added basic support for OPTIONS and TRACE HTTP methods:
716 * - New interceptor direct_response() added in chat().
717 * - sed() moved to earlier in the process, so that the
718 * Host: header is evaluated before actions and forwarding
721 * Revision 1.92 2002/05/08 16:00:46 oes
722 * Chat's buffer handling:
723 * - Fixed bug with unchecked out-of-mem conditions
724 * while reading client request & server headers
725 * - No longer predict if the buffer limit will be exceeded
726 * in the next read -- check add_to_iob's new
727 * return code. If buffer couldn't be extended
728 * (policy or out-of-mem) while
729 * - reading from client: abort
730 * - reading server headers: send error page
731 * - buffering server body for filter: flush,
732 * and if that fails: send error page
734 * Revision 1.91 2002/04/08 20:35:58 swa
737 * Revision 1.90 2002/04/02 14:57:28 oes
738 * Made sending wafers independent of FEATURE_COOKIE_JAR
740 * Revision 1.89 2002/03/31 17:18:59 jongfoster
741 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
743 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
744 * More compiler warning message maintenance
746 * Revision 1.87 2002/03/26 22:29:54 swa
747 * we have a new homepage!
749 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
750 * Workaround for closing the jarfile before load_config() comes around again
752 * Revision 1.85 2002/03/24 15:23:33 jongfoster
755 * Revision 1.84 2002/03/24 13:25:43 swa
756 * name change related issues
758 * Revision 1.83 2002/03/16 23:54:06 jongfoster
759 * Adding graceful termination feature, to help look for memory leaks.
760 * If you enable this (which, by design, has to be done by hand
761 * editing config.h) and then go to http://i.j.b/die, then the program
762 * will exit cleanly after the *next* request. It should free all the
763 * memory that was used.
765 * Revision 1.82 2002/03/13 00:27:05 jongfoster
768 * Revision 1.81 2002/03/12 01:42:50 oes
769 * Introduced modular filters
771 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
772 * OS/2 port maintenance:
773 * - Fixed EMX build - it had decayed a little
774 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
775 * substituted a memset for now.
777 * Revision 1.79 2002/03/09 20:03:52 jongfoster
778 * - Making various functions return int rather than size_t.
779 * (Undoing a recent change). Since size_t is unsigned on
780 * Windows, functions like read_socket that return -1 on
781 * error cannot return a size_t.
783 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
784 * crashes, and also frequently caused JB to jump to 100%
785 * CPU and stay there. (Because it thought it had just
786 * read ((unsigned)-1) == 4Gb of data...)
788 * - The signature of write_socket has changed, it now simply
789 * returns success=0/failure=nonzero.
791 * - Trying to get rid of a few warnings --with-debug on
792 * Windows, I've introduced a new type "jb_socket". This is
793 * used for the socket file descriptors. On Windows, this
794 * is SOCKET (a typedef for unsigned). Everywhere else, it's
795 * an int. The error value can't be -1 any more, so it's
796 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
797 * Windows it maps to the #define INVALID_SOCKET.)
799 * - The signature of bind_port has changed.
801 * Revision 1.78 2002/03/08 21:35:04 oes
802 * Added optional group supplement to --user option. Will now use default group of user if no group given
804 * Revision 1.77 2002/03/07 03:52:06 oes
805 * - Fixed compiler warnings etc
806 * - Improved handling of failed DNS lookups
808 * Revision 1.76 2002/03/06 22:54:35 jongfoster
809 * Automated function-comment nitpicking.
811 * Revision 1.75 2002/03/06 10:02:19 oes
812 * Fixed stupid bug when --user was not given
814 * Revision 1.74 2002/03/06 00:49:31 jongfoster
815 * Fixing warning on Windows
816 * Making #ifdefs that refer to the same variable consistently
817 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
819 * Revision 1.73 2002/03/05 23:57:30 hal9
820 * Stray character 's' on line 1618 was breaking build.
822 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
823 * - Re-enable OS/2 building after new parms were added
824 * - Fix false out of memory report when resolving CGI templates when no IP
825 * address is available of failed attempt (a la no such domain)
827 * Revision 1.71 2002/03/05 18:13:56 oes
828 * Added --user option
830 * Revision 1.70 2002/03/05 04:52:42 oes
831 * Deleted non-errlog debugging code
833 * Revision 1.69 2002/03/04 23:50:00 jongfoster
834 * Splitting off bind_port() call into bind_port_helper(), with
837 * Revision 1.68 2002/03/04 20:17:32 oes
840 * Revision 1.67 2002/03/04 18:18:57 oes
841 * - Removed _DEBUG mode
842 * - Cleand up cmdline parsing
843 * - Introduced --no-daemon, --pidfile options
844 * - Cleaned up signal handling:
845 * - Terminate cleanly on INT, TERM and ABRT
846 * - Schedule logfile for re-opening on HUP
847 * - Ignore CHLD and PIPE
848 * - Leave the rest with their default handlers
849 * - Uniform handler registration
850 * - Added usage() function
851 * - Played styleguide police
853 * Revision 1.66 2002/03/03 15:06:55 oes
854 * Re-enabled automatic config reloading
856 * Revision 1.65 2002/03/03 14:49:11 oes
857 * Fixed CLF logging: Now uses client's original HTTP request
859 * Revision 1.64 2002/03/03 09:18:03 joergs
860 * Made jumbjuster work on AmigaOS again.
862 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
863 * Clean up a little CRLF unpleasantness that suddenly appeared
865 * Revision 1.62 2002/02/20 23:17:23 jongfoster
866 * Detecting some out-of memory conditions and exiting with a log message.
868 * Revision 1.61 2002/01/17 21:01:52 jongfoster
869 * Moving all our URL and URL pattern parsing code to urlmatch.c.
871 * Revision 1.60 2001/12/30 14:07:32 steudten
872 * - Add signal handling (unix)
873 * - Add SIGHUP handler (unix)
874 * - Add creation of pidfile (unix)
875 * - Add action 'top' in rc file (RH)
876 * - Add entry 'SIGNALS' to manpage
877 * - Add exit message to logfile (unix)
879 * Revision 1.59 2001/12/13 14:07:18 oes
880 * Fixed Bug: 503 error page now sent OK
882 * Revision 1.58 2001/11/30 23:37:24 jongfoster
883 * Renaming the Win32 config file to config.txt - this is almost the
884 * same as the corresponding UNIX name "config"
886 * Revision 1.57 2001/11/16 00:47:43 jongfoster
887 * Changing the tty-disconnection code to use setsid().
889 * Revision 1.56 2001/11/13 20:20:54 jongfoster
890 * Tabs->spaces, fixing a bug with missing {} around an if()
892 * Revision 1.55 2001/11/13 20:14:53 jongfoster
893 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
895 * Revision 1.54 2001/11/07 00:03:14 steudten
896 * Give reliable return value if an error
897 * occurs not just 0 with new daemon mode.
899 * Revision 1.53 2001/11/05 21:41:43 steudten
900 * Add changes to be a real daemon just for unix os.
901 * (change cwd to /, detach from controlling tty, set
902 * process group and session leader to the own process.
904 * Add some fatal-error log message for failed malloc().
905 * Add '-d' if compiled with 'configure --with-debug' to
906 * enable debug output.
908 * Revision 1.52 2001/10/26 20:11:20 jongfoster
909 * Fixing type mismatch
911 * Revision 1.51 2001/10/26 17:38:28 oes
914 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
915 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
916 * threads to call select() simultaneously. So, it's time to do a real, live,
917 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
918 * (native). Both versions will work, but using __OS2__ offers multi-threading.
920 * Revision 1.49 2001/10/23 21:41:35 jongfoster
921 * Added call to initialize the (statically-allocated of course)
922 * "out of memory" CGI response.
924 * Revision 1.48 2001/10/10 19:56:46 jongfoster
925 * Moving some code that wasn't cookie-related out of an #ifdef
928 * Revision 1.47 2001/10/10 16:44:36 oes
929 * Added CONNECT destination port limitation check
931 * Revision 1.46 2001/10/08 15:17:41 oes
932 * Re-enabled SSL forwarding
934 * Revision 1.45 2001/10/07 15:42:11 oes
935 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
937 * Moved downgrading of the HTTP version from parse_http_request to
938 * chat(), since we can't decide if it is necessary before we have
939 * determined the actions for the URL. The HTTP command is now
940 * *always* re-built so the repairs need no longer be special-cased.
942 * filter_popups now gets a csp pointer so it can raise the new
943 * CSP_FLAG_MODIFIED flag.
947 * Added configurable size limit for the IOB. If the IOB grows so
948 * large that the next read would exceed the limit, the header
949 * is generated, and the header & unfiltered buffer are flushed
950 * to the client. Chat then continues in non-buffering,
951 * non-filtering body mode.
953 * Revision 1.44 2001/10/02 18:13:57 oes
956 * Revision 1.43 2001/10/02 15:32:13 oes
957 * Moved generation of hdr
959 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
960 * Cleaning up 2 compiler warnings on OS/2.
962 * Revision 1.41 2001/09/16 17:05:14 jongfoster
963 * Removing unused #include showarg.h
965 * Revision 1.40 2001/09/16 15:41:45 jongfoster
966 * Fixing signed/unsigned comparison warning.
968 * Revision 1.39 2001/09/16 13:21:27 jongfoster
969 * Changes to use new list functions.
971 * Revision 1.38 2001/09/16 13:01:46 jongfoster
972 * Removing redundant function call that zeroed zalloc()'d memory.
974 * Revision 1.37 2001/09/10 11:12:24 oes
975 * Deleted unused variable
977 * Revision 1.36 2001/09/10 10:56:15 oes
978 * Silenced compiler warnings
980 * Revision 1.35 2001/07/31 14:44:22 oes
981 * Deleted unused size parameter from filter_popups()
983 * Revision 1.34 2001/07/30 22:08:36 jongfoster
984 * Tidying up #defines:
985 * - All feature #defines are now of the form FEATURE_xxx
986 * - Permanently turned off WIN_GUI_EDIT
987 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
989 * Revision 1.33 2001/07/29 19:32:00 jongfoster
990 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
992 * Revision 1.32 2001/07/29 18:47:05 jongfoster
993 * Adding missing #include "loadcfg.h"
995 * Revision 1.31 2001/07/29 12:17:48 oes
996 * Applied pthread fix by Paul Lieverse
998 * Revision 1.30 2001/07/25 22:57:13 jongfoster
999 * __BEOS__ no longer overrides FEATURE_PTHREAD.
1000 * This is because FEATURE_PTHREAD will soon be widely used, so I
1001 * want to keep it simple.
1003 * Revision 1.29 2001/07/24 12:47:06 oes
1004 * Applied BeOS support update by Eugenia
1006 * Revision 1.28 2001/07/23 13:26:12 oes
1007 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
1009 * Revision 1.27 2001/07/19 19:09:47 haroon
1010 * - Added code to take care of the situation where while processing the first
1011 * server response (which includes the server header), after finding the end
1012 * of the headers we were not looking past the end of the headers for
1013 * content modification. I enabled it for filter_popups.
1014 * Someone else should look to see if other similar operations should be
1015 * done to the discarded portion of the buffer.
1017 * Note 2001/07/20: No, the other content modification mechanisms will process
1018 * the whole iob later anyway. --oes
1020 * Revision 1.26 2001/07/18 12:31:36 oes
1023 * Revision 1.25 2001/07/15 19:43:49 jongfoster
1024 * Supports POSIX threads.
1025 * Also removed some unused #includes.
1027 * Revision 1.24 2001/07/13 14:00:40 oes
1028 * - Generic content modification scheme:
1029 * Each feature has its own applicability flag that is set
1030 * from csp->action->flags.
1031 * Replaced the "filtering" int flag , by a function pointer
1032 * "content_filter" to the function that will do the content
1033 * modification. If it is != NULL, the document will be buffered
1034 * and processed through *content_filter, which must set
1035 * csp->content_length and return a modified copy of the body
1036 * or return NULL (on failiure).
1037 * - Changed csp->is_text to the more generic bitmap csp->content_type
1038 * which can currently take the valued CT_TEXT or CT_GIF
1039 * - Reformatting etc
1040 * - Removed all #ifdef PCRS
1042 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
1043 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
1044 * the `block_acl' call. This prevents a compilation error when the user
1045 * does not wish to use the "ACL" feature.
1047 * Revision 1.22 2001/06/29 21:45:41 oes
1048 * Indentation, CRLF->LF, Tab-> Space
1050 * Revision 1.21 2001/06/29 13:29:36 oes
1051 * - Cleaned up, improved comments
1052 * - Unified all possible interceptors (CGI,
1053 * block, trust, fast_redirect) in one
1054 * place, with one (CGI) answer generation
1055 * mechansim. Much clearer now.
1056 * - Removed the GIF image generation, which
1057 * is now done in filters.c:block_url()
1058 * - Made error conditions like domain lookup
1059 * failiure or (various) problems while talking
1060 * to the server use cgi.c:error_response()
1061 * instead of generating HTML/HTTP in chat() (yuck!)
1062 * - Removed logentry from cancelled commit
1064 * Revision 1.20 2001/06/09 10:55:28 jongfoster
1065 * Changing BUFSIZ ==> BUFFER_SIZE
1067 * Revision 1.19 2001/06/07 23:12:52 jongfoster
1068 * Replacing function pointer in struct gateway with a directly
1069 * called function forwarded_connect().
1070 * Replacing struct gateway with struct forward_spec
1072 * Revision 1.18 2001/06/03 19:12:16 oes
1073 * introduced new cgi handling
1075 * Revision 1.17 2001/06/01 20:07:23 jongfoster
1076 * Now uses action +image-blocker{} rather than config->tinygif
1078 * Revision 1.16 2001/06/01 18:49:17 jongfoster
1079 * Replaced "list_share" with "list" - the tiny memory gain was not
1080 * worth the extra complexity.
1082 * Revision 1.15 2001/05/31 21:24:47 jongfoster
1083 * Changed "permission" to "action" throughout.
1084 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
1085 * Moved vanilla wafer check into chat(), since we must now
1086 * decide whether or not to add it based on the URL.
1088 * Revision 1.14 2001/05/29 20:14:01 joergs
1089 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
1092 * Revision 1.13 2001/05/29 09:50:24 jongfoster
1093 * Unified blocklist/imagelist/permissionslist.
1094 * File format is still under discussion, but the internal changes
1095 * are (mostly) done.
1097 * Also modified interceptor behaviour:
1098 * - We now intercept all URLs beginning with one of the following
1099 * prefixes (and *only* these prefixes):
1101 * * http://ijbswa.sf.net/config/
1102 * * http://ijbswa.sourceforge.net/config/
1103 * - New interceptors "home page" - go to http://i.j.b/ to see it.
1104 * - Internal changes so that intercepted and fast redirect pages
1105 * are not replaced with an image.
1106 * - Interceptors now have the option to send a binary page direct
1107 * to the client. (i.e. ijb-send-banner uses this)
1108 * - Implemented show-url-info interceptor. (Which is why I needed
1109 * the above interceptors changes - a typical URL is
1110 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
1111 * The previous mechanism would not have intercepted that, and
1112 * if it had been intercepted then it then it would have replaced
1113 * it with an image.)
1115 * Revision 1.12 2001/05/27 22:17:04 oes
1117 * - re_process_buffer no longer writes the modified buffer
1118 * to the client, which was very ugly. It now returns the
1119 * buffer, which it is then written by chat.
1121 * - content_length now adjusts the Content-Length: header
1122 * for modified documents rather than crunch()ing it.
1123 * (Length info in csp->content_length, which is 0 for
1124 * unmodified documents)
1126 * - For this to work, sed() is called twice when filtering.
1128 * Revision 1.11 2001/05/26 17:27:53 jongfoster
1129 * Added support for CLF and fixed LOG_LEVEL_LOG.
1130 * Also did CRLF->LF fix of my previous patch.
1132 * Revision 1.10 2001/05/26 15:26:15 jongfoster
1133 * ACL feature now provides more security by immediately dropping
1134 * connections from untrusted hosts.
1136 * Revision 1.9 2001/05/26 00:28:36 jongfoster
1137 * Automatic reloading of config file.
1138 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
1139 * Most of the global variables have been moved to a new
1140 * struct configuration_spec, accessed through csp->config->globalname
1141 * Most of the globals remaining are used by the Win32 GUI.
1143 * Revision 1.8 2001/05/25 22:43:18 jongfoster
1144 * Fixing minor memory leak and buffer overflow.
1146 * Revision 1.7 2001/05/25 22:34:30 jongfoster
1149 * Revision 1.6 2001/05/23 00:13:58 joergs
1150 * AmigaOS support fixed.
1152 * Revision 1.5 2001/05/22 18:46:04 oes
1154 * - Enabled filtering banners by size rather than URL
1155 * by adding patterns that replace all standard banner
1156 * sizes with the "Junkbuster" gif to the re_filterfile
1158 * - Enabled filtering WebBugs by providing a pattern
1159 * which kills all 1x1 images
1161 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
1162 * which is selected by the (nonstandard and therefore
1163 * capital) letter 'U' in the option string.
1164 * It causes the quantifiers to be ungreedy by default.
1165 * Appending a ? turns back to greedy (!).
1167 * - Added a new interceptor ijb-send-banner, which
1168 * sends back the "Junkbuster" gif. Without imagelist or
1169 * MSIE detection support, or if tinygif = 1, or the
1170 * URL isn't recognized as an imageurl, a lame HTML
1171 * explanation is sent instead.
1173 * - Added new feature, which permits blocking remote
1174 * script redirects and firing back a local redirect
1176 * The feature is conditionally compiled, i.e. it
1177 * can be disabled with --disable-fast-redirects,
1178 * plus it must be activated by a "fast-redirects"
1179 * line in the config file, has its own log level
1180 * and of course wants to be displayed by show-proxy-args
1181 * Note: Boy, all the #ifdefs in 1001 locations and
1182 * all the fumbling with configure.in and acconfig.h
1183 * were *way* more work than the feature itself :-(
1185 * - Because a generic redirect template was needed for
1186 * this, tinygif = 3 now uses the same.
1188 * - Moved GIFs, and other static HTTP response templates
1191 * - Some minor fixes
1193 * - Removed some >400 CRs again (Jon, you really worked
1196 * Revision 1.4 2001/05/21 19:34:01 jongfoster
1197 * Made failure to bind() a fatal error.
1199 * Revision 1.3 2001/05/20 01:21:20 jongfoster
1200 * Version 2.9.4 checkin.
1201 * - Merged popupfile and cookiefile, and added control over PCRS
1202 * filtering, in new "permissionsfile".
1203 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
1204 * file error you now get a message box (in the Win32 GUI) rather
1205 * than the program exiting with no explanation.
1206 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
1208 * - Removed tabs from "config"
1209 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
1210 * - Bumped up version number.
1212 * Revision 1.2 2001/05/17 22:34:44 oes
1213 * - Added hint on GIF char array generation to jcc.c
1214 * - Cleaned CRLF's from the sources and related files
1215 * - Repaired logging for REF and FRC
1217 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
1218 * Initial import of version 2.9.3 source tree
1221 *********************************************************************/
1227 #include <sys/types.h>
1236 # ifndef FEATURE_PTHREAD
1240 # include <windows.h>
1241 # include <process.h>
1242 # endif /* ndef FEATURE_PTHREAD */
1245 # ifndef _WIN_CONSOLE
1246 # include "w32log.h"
1247 # endif /* ndef _WIN_CONSOLE */
1248 # include "w32svrapi.h"
1250 #else /* ifndef _WIN32 */
1252 # if !defined (__OS2__)
1253 # include <unistd.h>
1254 # include <sys/wait.h>
1255 # endif /* ndef __OS2__ */
1256 # include <sys/time.h>
1257 # include <sys/stat.h>
1258 # include <sys/ioctl.h>
1261 #include <sys/termios.h>
1269 # include <signal.h>
1272 # include <socket.h> /* BeOS has select() for sockets only. */
1273 # include <OS.h> /* declarations for threads and stuff. */
1276 # if defined(__EMX__) || defined(__OS2__)
1277 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
1282 #define bzero(B,N) memset(B,0x00,n)
1286 # include <select.h>
1291 #include "project.h"
1294 #include "filters.h"
1295 #include "loaders.h"
1296 #include "parsers.h"
1297 #include "miscutil.h"
1299 #include "jbsockets.h"
1300 #include "gateway.h"
1301 #include "actions.h"
1303 #include "loadcfg.h"
1304 #include "urlmatch.h"
1306 const char jcc_h_rcs[] = JCC_H_VERSION;
1307 const char project_h_rcs[] = PROJECT_H_VERSION;
1310 struct client_state clients[1];
1311 struct file_list files[1];
1313 #ifdef FEATURE_STATISTICS
1314 int urls_read = 0; /* total nr of urls read inc rejected */
1315 int urls_rejected = 0; /* total nr of urls rejected */
1316 #endif /* def FEATURE_STATISTICS */
1318 #ifdef FEATURE_GRACEFUL_TERMINATION
1319 int g_terminate = 0;
1322 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1323 static void sig_handler(int the_signal);
1325 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
1326 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
1327 static jb_err get_server_headers(struct client_state *csp);
1328 static const char *crunch_reason(const struct http_response *rsp);
1329 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
1330 static char *get_request_line(struct client_state *csp);
1331 static jb_err receive_client_request(struct client_state *csp);
1332 static jb_err parse_client_request(struct client_state *csp);
1333 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
1334 static jb_err change_request_destination(struct client_state *csp);
1335 static void chat(struct client_state *csp);
1336 static void serve(struct client_state *csp);
1337 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1338 static void usage(const char *myname);
1340 static void initialize_mutexes(void);
1341 static jb_socket bind_port_helper(struct configuration_spec *config);
1342 static void listen_loop(void);
1345 void serve(struct client_state *csp);
1346 #else /* ifndef AMIGA */
1347 static void serve(struct client_state *csp);
1348 #endif /* def AMIGA */
1351 static int32 server_thread(void *data);
1352 #endif /* def __BEOS__ */
1355 #define sleep(N) Sleep(((N) * 1000))
1359 #define sleep(N) DosSleep(((N) * 100))
1362 #ifdef MUTEX_LOCKS_AVAILABLE
1364 * XXX: Does the locking stuff really belong in this file?
1366 privoxy_mutex_t log_mutex;
1367 privoxy_mutex_t log_init_mutex;
1368 privoxy_mutex_t connection_reuse_mutex;
1370 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
1371 privoxy_mutex_t resolver_mutex;
1372 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
1374 #ifndef HAVE_GMTIME_R
1375 privoxy_mutex_t gmtime_mutex;
1376 #endif /* ndef HAVE_GMTIME_R */
1378 #ifndef HAVE_LOCALTIME_R
1379 privoxy_mutex_t localtime_mutex;
1380 #endif /* ndef HAVE_GMTIME_R */
1383 privoxy_mutex_t rand_mutex;
1384 #endif /* ndef HAVE_RANDOM */
1386 #endif /* def MUTEX_LOCKS_AVAILABLE */
1389 const char *basedir = NULL;
1390 const char *pidfile = NULL;
1391 static int received_hup_signal = 0;
1392 #endif /* defined unix */
1394 /* HTTP snipplets. */
1395 static const char CSUCCEED[] =
1396 "HTTP/1.0 200 Connection established\r\n"
1397 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
1399 static const char CHEADER[] =
1400 "HTTP/1.0 400 Invalid header received from client\r\n"
1401 "Proxy-Agent: Privoxy " VERSION "\r\n"
1402 "Content-Type: text/plain\r\n"
1403 "Connection: close\r\n\r\n"
1404 "Invalid header received from client.\r\n";
1406 static const char FTP_RESPONSE[] =
1407 "HTTP/1.0 400 Invalid request received from client\r\n"
1408 "Content-Type: text/plain\r\n"
1409 "Connection: close\r\n\r\n"
1410 "Invalid request. Privoxy doesn't support FTP.\r\n";
1412 static const char GOPHER_RESPONSE[] =
1413 "HTTP/1.0 400 Invalid request received from client\r\n"
1414 "Content-Type: text/plain\r\n"
1415 "Connection: close\r\n\r\n"
1416 "Invalid request. Privoxy doesn't support gopher.\r\n";
1418 /* XXX: should be a template */
1419 static const char MISSING_DESTINATION_RESPONSE[] =
1420 "HTTP/1.0 400 Bad request received from client\r\n"
1421 "Proxy-Agent: Privoxy " VERSION "\r\n"
1422 "Content-Type: text/plain\r\n"
1423 "Connection: close\r\n\r\n"
1424 "Bad request. Privoxy was unable to extract the destination.\r\n";
1426 /* XXX: should be a template */
1427 static const char NO_SERVER_DATA_RESPONSE[] =
1428 "HTTP/1.0 502 Server or forwarder response empty\r\n"
1429 "Proxy-Agent: Privoxy " VERSION "\r\n"
1430 "Content-Type: text/plain\r\n"
1431 "Connection: close\r\n\r\n"
1432 "Empty server or forwarder response.\r\n"
1433 "The connection has been closed but Privoxy didn't receive any data.\r\n";
1435 /* XXX: should be a template */
1436 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
1437 "HTTP/1.0 502 Server or forwarder response invalid\r\n"
1438 "Proxy-Agent: Privoxy " VERSION "\r\n"
1439 "Content-Type: text/plain\r\n"
1440 "Connection: close\r\n\r\n"
1441 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
1444 /* XXX: should be a template */
1445 static const char NULL_BYTE_RESPONSE[] =
1446 "HTTP/1.0 400 Bad request received from client\r\n"
1447 "Proxy-Agent: Privoxy " VERSION "\r\n"
1448 "Content-Type: text/plain\r\n"
1449 "Connection: close\r\n\r\n"
1450 "Bad request. Null byte(s) before end of request.\r\n";
1453 /* XXX: should be a template */
1454 static const char MESSED_UP_REQUEST_RESPONSE[] =
1455 "HTTP/1.0 400 Malformed request after rewriting\r\n"
1456 "Proxy-Agent: Privoxy " VERSION "\r\n"
1457 "Content-Type: text/plain\r\n"
1458 "Connection: close\r\n\r\n"
1459 "Bad request. Messed up with header filters.\r\n";
1461 /* XXX: should be a template */
1462 static const char CONNECTION_TIMEOUT_RESPONSE[] =
1463 "HTTP/1.0 502 Connection timeout\r\n"
1464 "Proxy-Agent: Privoxy " VERSION "\r\n"
1465 "Content-Type: text/plain\r\n"
1466 "Connection: close\r\n\r\n"
1467 "The connection timed out.\r\n";
1469 /* A function to crunch a response */
1470 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
1472 /* Crunch function flags */
1473 #define CF_NO_FLAGS 0
1474 /* Cruncher applies to forced requests as well */
1475 #define CF_IGNORE_FORCE 1
1476 /* Crunched requests are counted for the block statistics */
1477 #define CF_COUNT_AS_REJECT 2
1479 /* A crunch function and its flags */
1482 const crunch_func_ptr cruncher;
1486 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
1488 /* Complete list of cruncher functions */
1489 static const struct cruncher crunchers_all[] = {
1490 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
1491 { block_url, CF_COUNT_AS_REJECT },
1492 #ifdef FEATURE_TRUST
1493 { trust_url, CF_COUNT_AS_REJECT },
1494 #endif /* def FEATURE_TRUST */
1495 { redirect_url, CF_NO_FLAGS },
1496 { dispatch_cgi, CF_IGNORE_FORCE},
1500 /* Light version, used after tags are applied */
1501 static const struct cruncher crunchers_light[] = {
1502 { block_url, CF_COUNT_AS_REJECT },
1503 { redirect_url, CF_NO_FLAGS },
1509 * XXX: Don't we really mean
1515 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1516 /*********************************************************************
1518 * Function : sig_handler
1520 * Description : Signal handler for different signals.
1521 * Exit gracefully on TERM and INT
1522 * or set a flag that will cause the errlog
1523 * to be reopened by the main thread on HUP.
1526 * 1 : the_signal = the signal cause this function to call
1530 *********************************************************************/
1531 static void sig_handler(int the_signal)
1537 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
1549 received_hup_signal = 1;
1555 * We shouldn't be here, unless we catch signals
1556 * in main() that we can't handle here!
1558 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
1566 /*********************************************************************
1568 * Function : client_protocol_is_unsupported
1570 * Description : Checks if the client used a known unsupported
1571 * protocol and deals with it by sending an error
1575 * 1 : csp = Current client state (buffers, headers, etc...)
1576 * 2 : req = the first request line send by the client
1578 * Returns : TRUE if an error response has been generated, or
1579 * FALSE if the request doesn't look invalid.
1581 *********************************************************************/
1582 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
1585 * If it's a FTP or gopher request, we don't support it.
1587 * These checks are better than nothing, but they might
1588 * not work in all configurations and some clients might
1589 * have problems digesting the answer.
1591 * They should, however, never cause more problems than
1592 * Privoxy's old behaviour (returning the misleading HTML
1595 * "Could not resolve http://(ftp|gopher)://example.org").
1597 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
1599 const char *response = NULL;
1600 const char *protocol = NULL;
1602 if (!strncmpic(req, "GET ftp://", 10))
1604 response = FTP_RESPONSE;
1609 response = GOPHER_RESPONSE;
1610 protocol = "GOPHER";
1612 log_error(LOG_LEVEL_ERROR,
1613 "%s tried to use Privoxy as %s proxy: %s",
1614 csp->ip_addr_str, protocol, req);
1615 log_error(LOG_LEVEL_CLF,
1616 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
1618 write_socket(csp->cfd, response, strlen(response));
1627 /*********************************************************************
1629 * Function : get_request_destination_elsewhere
1631 * Description : If the client's request was redirected into
1632 * Privoxy without the client's knowledge,
1633 * the request line lacks the destination host.
1635 * This function tries to get it elsewhere,
1636 * provided accept-intercepted-requests is enabled.
1638 * "Elsewhere" currently only means "Host: header",
1639 * but in the future we may ask the redirecting
1640 * packet filter to look the destination up.
1642 * If the destination stays unknown, an error
1643 * response is send to the client and headers
1644 * are freed so that chat() can return directly.
1647 * 1 : csp = Current client state (buffers, headers, etc...)
1648 * 2 : headers = a header list
1650 * Returns : JB_ERR_OK if the destination is now known, or
1651 * JB_ERR_PARSE if it isn't.
1653 *********************************************************************/
1654 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
1658 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
1660 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
1661 " Privoxy isn't configured to accept intercepted requests.",
1662 csp->ip_addr_str, csp->http->cmd);
1663 /* XXX: Use correct size */
1664 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1665 csp->ip_addr_str, csp->http->cmd);
1667 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1668 destroy_list(headers);
1670 return JB_ERR_PARSE;
1672 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
1674 /* Split the domain we just got for pattern matching */
1675 init_domain_components(csp->http);
1681 /* We can't work without destination. Go spread the news.*/
1683 req = list_to_text(headers);
1685 /* XXX: Use correct size */
1686 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1687 csp->ip_addr_str, csp->http->cmd);
1688 log_error(LOG_LEVEL_ERROR,
1689 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
1690 csp->ip_addr_str, csp->http->cmd, req);
1693 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
1694 destroy_list(headers);
1696 return JB_ERR_PARSE;
1699 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
1700 * to get the destination IP address, use it as host directly
1701 * or do a reverse DNS lookup first.
1706 /*********************************************************************
1708 * Function : get_server_headers
1710 * Description : Parses server headers in iob and fills them
1711 * into csp->headers so that they can later be
1715 * 1 : csp = Current client state (buffers, headers, etc...)
1717 * Returns : JB_ERR_OK if everything went fine, or
1718 * JB_ERR_PARSE if the headers were incomplete.
1720 *********************************************************************/
1721 static jb_err get_server_headers(struct client_state *csp)
1723 int continue_hack_in_da_house = 0;
1726 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
1731 * continue hack in da house. Ignore the ending of
1732 * this head and continue enlisting header lines.
1733 * The reason is described below.
1735 enlist(csp->headers, "");
1736 continue_hack_in_da_house = 0;
1739 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
1742 * It's a bodyless continue response, don't
1743 * stop header parsing after reaching its end.
1745 * As a result Privoxy will concatenate the
1746 * next response's head and parse and deliver
1747 * the headers as if they belonged to one request.
1749 * The client will separate them because of the
1750 * empty line between them.
1752 * XXX: What we're doing here is clearly against
1753 * the intended purpose of the continue header,
1754 * and under some conditions (HTTP/1.0 client request)
1755 * it's a standard violation.
1757 * Anyway, "sort of against the spec" is preferable
1758 * to "always getting confused by Continue responses"
1759 * (Privoxy's behaviour before this hack was added)
1761 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
1762 continue_hack_in_da_house = 1;
1764 else if (*header == '\0')
1767 * If the header is empty, but the Continue hack
1768 * isn't active, we can assume that we reached the
1769 * end of the buffer before we hit the end of the
1772 * Inform the caller an let it decide how to handle it.
1774 return JB_ERR_PARSE;
1777 if (JB_ERR_MEMORY == enlist(csp->headers, header))
1780 * XXX: Should we quit the request and return a
1781 * out of memory error page instead?
1783 log_error(LOG_LEVEL_ERROR,
1784 "Out of memory while enlisting server headers. %s lost.",
1794 /*********************************************************************
1796 * Function : crunch_reason
1798 * Description : Translates the crunch reason code into a string.
1801 * 1 : rsp = a http_response
1803 * Returns : A string with the crunch reason or an error description.
1805 *********************************************************************/
1806 static const char *crunch_reason(const struct http_response *rsp)
1808 char * reason = NULL;
1810 assert(rsp != NULL);
1813 return "Internal error while searching for crunch reason";
1816 switch (rsp->reason)
1818 case RSP_REASON_UNSUPPORTED:
1819 reason = "Unsupported HTTP feature";
1821 case RSP_REASON_BLOCKED:
1824 case RSP_REASON_UNTRUSTED:
1825 reason = "Untrusted";
1827 case RSP_REASON_REDIRECTED:
1828 reason = "Redirected";
1830 case RSP_REASON_CGI_CALL:
1831 reason = "CGI Call";
1833 case RSP_REASON_NO_SUCH_DOMAIN:
1834 reason = "DNS failure";
1836 case RSP_REASON_FORWARDING_FAILED:
1837 reason = "Forwarding failed";
1839 case RSP_REASON_CONNECT_FAILED:
1840 reason = "Connection failure";
1842 case RSP_REASON_OUT_OF_MEMORY:
1843 reason = "Out of memory (may mask other reasons)";
1846 reason = "No reason recorded";
1854 /*********************************************************************
1856 * Function : send_crunch_response
1858 * Description : Delivers already prepared response for
1859 * intercepted requests, logs the interception
1860 * and frees the response.
1863 * 1 : csp = Current client state (buffers, headers, etc...)
1864 * 1 : rsp = Fully prepared response. Will be freed on exit.
1866 * Returns : Nothing.
1868 *********************************************************************/
1869 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
1871 const struct http_request *http = csp->http;
1872 char status_code[4];
1874 assert(rsp != NULL);
1875 assert(rsp->head != NULL);
1880 * Not supposed to happen. If it does
1881 * anyway, treat it as an unknown error.
1883 cgi_error_unknown(csp, rsp, RSP_REASON_INTERNAL_ERROR);
1884 /* return code doesn't matter */
1889 /* If rsp is still NULL, we have serious internal problems. */
1890 log_error(LOG_LEVEL_FATAL,
1891 "NULL response in send_crunch_response and cgi_error_unknown failed as well.");
1895 * Extract the status code from the actual head
1896 * that was send to the client. It is the only
1897 * way to get it right for all requests, including
1898 * the fixed ones for out-of-memory problems.
1900 * A head starts like this: 'HTTP/1.1 200...'
1904 status_code[0] = rsp->head[9];
1905 status_code[1] = rsp->head[10];
1906 status_code[2] = rsp->head[11];
1907 status_code[3] = '\0';
1909 /* Write the answer to the client */
1910 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1911 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1913 /* There is nothing we can do about it. */
1914 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", csp->http->host);
1917 /* Log that the request was crunched and why. */
1918 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
1919 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
1920 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
1922 /* Clean up and return */
1923 if (cgi_error_memory() != rsp)
1925 free_http_response(rsp);
1932 /*********************************************************************
1934 * Function : request_contains_null_bytes
1936 * Description : Checks for NULL bytes in the request and sends
1937 * an error message to the client if any were found.
1939 * XXX: currently not used, see comment in chat().
1942 * 1 : csp = Current client state (buffers, headers, etc...)
1943 * 2 : buf = Data from the client's request to check.
1944 * 3 : len = The data length.
1946 * Returns : TRUE if the request contained one or more NULL bytes, or
1949 *********************************************************************/
1950 static int request_contains_null_bytes(const struct client_state *csp, char *buf, int len)
1952 size_t c_len; /* Request lenght when treated as C string */
1954 c_len = strlen(buf);
1959 * Null byte(s) found. Log the request,
1960 * return an error response and hang up.
1962 size_t tmp_len = c_len;
1967 * Replace NULL byte(s) with '°' characters
1968 * so the request can be logged as string.
1969 * XXX: Is there a better replacement character?
1972 tmp_len += strlen(buf+tmp_len);
1973 } while (tmp_len < len);
1975 log_error(LOG_LEVEL_ERROR, "%s\'s request contains at least one NULL byte "
1976 "(length=%d, strlen=%u).", csp->ip_addr_str, len, c_len);
1977 log_error(LOG_LEVEL_HEADER,
1978 "Offending request data with NULL bytes turned into \'°\' characters: %s", buf);
1980 write_socket(csp->cfd, NULL_BYTE_RESPONSE, strlen(NULL_BYTE_RESPONSE));
1982 /* XXX: Log correct size */
1983 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1993 /*********************************************************************
1995 * Function : crunch_response_triggered
1997 * Description : Checks if the request has to be crunched,
1998 * and delivers the crunch response if necessary.
2001 * 1 : csp = Current client state (buffers, headers, etc...)
2002 * 2 : crunchers = list of cruncher functions to run
2004 * Returns : TRUE if the request was answered with a crunch response
2007 *********************************************************************/
2008 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
2010 struct http_response *rsp = NULL;
2011 const struct cruncher *c;
2014 * If CGI request crunching is disabled,
2015 * check the CGI dispatcher out of order to
2016 * prevent unintentional blocks or redirects.
2018 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
2019 && (NULL != (rsp = dispatch_cgi(csp))))
2021 /* Deliver, log and free the interception response. */
2022 send_crunch_response(csp, rsp);
2026 for (c = crunchers; c->cruncher != NULL; c++)
2029 * Check the cruncher if either Privoxy is toggled
2030 * on and the request isn't forced, or if the cruncher
2031 * applies to forced requests as well.
2033 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
2034 !(csp->flags & CSP_FLAG_FORCED)) ||
2035 (c->flags & CF_IGNORE_FORCE))
2037 rsp = c->cruncher(csp);
2040 /* Deliver, log and free the interception response. */
2041 send_crunch_response(csp, rsp);
2042 #ifdef FEATURE_STATISTICS
2043 if (c->flags & CF_COUNT_AS_REJECT)
2045 csp->flags |= CSP_FLAG_REJECTED;
2047 #endif /* def FEATURE_STATISTICS */
2058 /*********************************************************************
2060 * Function : build_request_line
2062 * Description : Builds the HTTP request line.
2064 * If a HTTP forwarder is used it expects the whole URL,
2065 * web servers only get the path.
2068 * 1 : csp = Current client state (buffers, headers, etc...)
2069 * 2 : fwd = The forwarding spec used for the request
2070 * XXX: Should use http->fwd instead.
2071 * 3 : request_line = The old request line which will be replaced.
2073 * Returns : Nothing. Terminates in case of memory problems.
2075 *********************************************************************/
2076 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
2078 struct http_request *http = csp->http;
2080 assert(http->ssl == 0);
2083 * Downgrade http version from 1.1 to 1.0
2084 * if +downgrade action applies.
2086 if ( (csp->action->flags & ACTION_DOWNGRADE)
2087 && (!strcmpic(http->ver, "HTTP/1.1")))
2090 http->ver = strdup("HTTP/1.0");
2092 if (http->ver == NULL)
2094 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
2099 * Rebuild the request line.
2101 freez(*request_line);
2102 *request_line = strdup(http->gpc);
2103 string_append(request_line, " ");
2105 if (fwd->forward_host)
2107 string_append(request_line, http->url);
2111 string_append(request_line, http->path);
2113 string_append(request_line, " ");
2114 string_append(request_line, http->ver);
2116 if (*request_line == NULL)
2118 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
2120 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
2124 /*********************************************************************
2126 * Function : change_request_destination
2128 * Description : Parse a (rewritten) request line and regenerate
2129 * the http request data.
2132 * 1 : csp = Current client state (buffers, headers, etc...)
2134 * Returns : Forwards the parse_http_request() return code.
2135 * Terminates in case of memory problems.
2137 *********************************************************************/
2138 static jb_err change_request_destination(struct client_state *csp)
2140 struct http_request *http = csp->http;
2143 log_error(LOG_LEVEL_INFO, "Rewrite detected: %s", csp->headers->first->str);
2144 free_http_request(http);
2145 err = parse_http_request(csp->headers->first->str, http);
2146 if (JB_ERR_OK != err)
2148 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2149 jb_err_to_string(err));
2153 /* XXX: ocmd is a misleading name */
2154 http->ocmd = strdup(http->cmd);
2155 if (http->ocmd == NULL)
2157 log_error(LOG_LEVEL_FATAL,
2158 "Out of memory copying rewritten HTTP request line");
2166 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2167 /*********************************************************************
2169 * Function : server_response_is_complete
2171 * Description : Determines whether we should stop reading
2172 * from the server socket.
2175 * 1 : csp = Current client state (buffers, headers, etc...)
2176 * 2 : content_length = Length of content received so far.
2178 * Returns : TRUE if the response is complete,
2181 *********************************************************************/
2182 static int server_response_is_complete(struct client_state *csp,
2183 unsigned long long content_length)
2185 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
2187 if (!strcmpic(csp->http->gpc, "HEAD"))
2190 * "HEAD" implies no body, we are thus expecting
2191 * no content. XXX: incomplete "list" of methods?
2193 csp->expected_content_length = 0;
2194 content_length_known = TRUE;
2197 if (csp->http->status == 304)
2200 * Expect no body. XXX: incomplete "list" of status codes?
2202 csp->expected_content_length = 0;
2203 content_length_known = TRUE;
2206 return (content_length_known && ((0 == csp->expected_content_length)
2207 || (csp->expected_content_length <= content_length)));
2211 /*********************************************************************
2213 * Function : wait_for_alive_connections
2215 * Description : Waits for alive connections to timeout.
2221 *********************************************************************/
2222 static void wait_for_alive_connections()
2224 int connections_alive = close_unusable_connections();
2226 while (0 < connections_alive)
2228 log_error(LOG_LEVEL_CONNECT,
2229 "Waiting for %d connections to timeout.",
2232 connections_alive = close_unusable_connections();
2235 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
2238 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2241 /*********************************************************************
2243 * Function : mark_server_socket_tainted
2245 * Description : Makes sure we don't reuse a server socket
2246 * (if we didn't read everything the server sent
2247 * us reusing the socket would lead to garbage).
2250 * 1 : csp = Current client state (buffers, headers, etc...)
2254 *********************************************************************/
2255 static void mark_server_socket_tainted(struct client_state *csp)
2257 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE))
2259 log_error(LOG_LEVEL_CONNECT, "Unsetting keep-alive flag.");
2260 csp->flags &= ~CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE;
2264 /*********************************************************************
2266 * Function : get_request_line
2268 * Description : Read the client request line.
2271 * 1 : csp = Current client state (buffers, headers, etc...)
2273 * Returns : Pointer to request line or NULL in case of errors.
2275 *********************************************************************/
2276 static char *get_request_line(struct client_state *csp)
2278 char buf[BUFFER_SIZE];
2279 char *request_line = NULL;
2282 memset(buf, 0, sizeof(buf));
2286 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
2288 log_error(LOG_LEVEL_ERROR,
2289 "Stopped waiting for the request line.");
2290 write_socket(csp->cfd, CONNECTION_TIMEOUT_RESPONSE,
2291 strlen(CONNECTION_TIMEOUT_RESPONSE));
2295 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
2297 if (len <= 0) return NULL;
2300 * If there is no memory left for buffering the
2301 * request, there is nothing we can do but hang up
2303 if (add_to_iob(csp, buf, len))
2308 request_line = get_header(csp->iob);
2310 } while ((NULL != request_line) && ('\0' == *request_line));
2312 return request_line;
2317 /*********************************************************************
2319 * Function : receive_client_request
2321 * Description : Read the client's request (more precisely the
2322 * client headers) and answer it if necessary.
2324 * Note that since we're not using select() we could get
2325 * blocked here if a client connected, then didn't say
2329 * 1 : csp = Current client state (buffers, headers, etc...)
2331 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
2333 *********************************************************************/
2334 static jb_err receive_client_request(struct client_state *csp)
2336 char buf[BUFFER_SIZE];
2339 struct http_request *http;
2343 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
2344 struct list header_list;
2345 struct list *headers = &header_list;
2349 memset(buf, 0, sizeof(buf));
2351 req = get_request_line(csp);
2354 return JB_ERR_PARSE;
2356 assert(*req != '\0');
2358 if (client_protocol_is_unsupported(csp, req))
2360 return JB_ERR_PARSE;
2363 #ifdef FEATURE_FORCE_LOAD
2365 * If this request contains the FORCE_PREFIX and blocks
2366 * aren't enforced, get rid of it and set the force flag.
2368 if (strstr(req, FORCE_PREFIX))
2370 if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
2372 log_error(LOG_LEVEL_FORCE,
2373 "Ignored force prefix in request: \"%s\".", req);
2377 strclean(req, FORCE_PREFIX);
2378 log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
2379 csp->flags |= CSP_FLAG_FORCED;
2382 #endif /* def FEATURE_FORCE_LOAD */
2384 err = parse_http_request(req, http);
2386 if (JB_ERR_OK != err)
2388 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
2389 /* XXX: Use correct size */
2390 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2391 log_error(LOG_LEVEL_ERROR,
2392 "Couldn't parse request line received from %s: %s",
2393 csp->ip_addr_str, jb_err_to_string(err));
2395 free_http_request(http);
2396 return JB_ERR_PARSE;
2399 /* grab the rest of the client's headers */
2403 p = get_header(csp->iob);
2407 /* There are no additional headers to read. */
2414 * We didn't receive a complete header
2415 * line yet, get the rest of it.
2417 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
2419 log_error(LOG_LEVEL_ERROR,
2420 "Stopped grabbing the client headers.");
2421 return JB_ERR_PARSE;
2424 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
2427 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
2428 destroy_list(headers);
2429 return JB_ERR_PARSE;
2432 if (add_to_iob(csp, buf, len))
2435 * If there is no memory left for buffering the
2436 * request, there is nothing we can do but hang up
2438 destroy_list(headers);
2439 return JB_ERR_MEMORY;
2445 * We were able to read a complete
2446 * header and can finaly enlist it.
2453 if (http->host == NULL)
2456 * If we still don't know the request destination,
2457 * the request is invalid or the client uses
2458 * Privoxy without its knowledge.
2460 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
2463 * Our attempts to get the request destination
2464 * elsewhere failed or Privoxy is configured
2465 * to only accept proxy requests.
2467 * An error response has already been send
2468 * and we're done here.
2470 return JB_ERR_PARSE;
2475 * Determine the actions for this URL
2477 #ifdef FEATURE_TOGGLE
2478 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
2480 /* Most compatible set of actions (i.e. none) */
2481 init_current_action(csp->action);
2484 #endif /* ndef FEATURE_TOGGLE */
2486 get_url_actions(csp, http);
2490 * Save a copy of the original request for logging
2492 http->ocmd = strdup(http->cmd);
2493 if (http->ocmd == NULL)
2495 log_error(LOG_LEVEL_FATAL,
2496 "Out of memory copying HTTP request line");
2498 enlist(csp->headers, http->cmd);
2500 /* Append the previously read headers */
2501 list_append_list_unique(csp->headers, headers);
2502 destroy_list(headers);
2509 /*********************************************************************
2511 * Function : parse_client_request
2513 * Description : Parses the client's request and decides what to do
2516 * Note that since we're not using select() we could get
2517 * blocked here if a client connected, then didn't say
2521 * 1 : csp = Current client state (buffers, headers, etc...)
2523 * Returns : JB_ERR_OK or JB_ERR_PARSE
2525 *********************************************************************/
2526 static jb_err parse_client_request(struct client_state *csp)
2528 struct http_request *http = csp->http;
2531 err = sed(csp, FILTER_CLIENT_HEADERS);
2532 if (JB_ERR_OK != err)
2534 /* XXX: Should be handled in sed(). */
2535 assert(err == JB_ERR_PARSE);
2536 log_error(LOG_LEVEL_FATAL, "Failed to parse client headers.");
2538 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
2540 /* Check request line for rewrites. */
2541 if ((NULL == csp->headers->first->str)
2542 || (strcmp(http->cmd, csp->headers->first->str) &&
2543 (JB_ERR_OK != change_request_destination(csp))))
2546 * A header filter broke the request line - bail out.
2548 write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
2549 /* XXX: Use correct size */
2550 log_error(LOG_LEVEL_CLF,
2551 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
2552 log_error(LOG_LEVEL_ERROR,
2553 "Invalid request line after applying header filters.");
2554 free_http_request(http);
2556 return JB_ERR_PARSE;
2564 /*********************************************************************
2568 * Description : Once a connection to the client has been accepted,
2569 * this function is called (via serve()) to handle the
2570 * main business of the communication. When this
2571 * function returns, the caller must close the client
2574 * FIXME: chat is nearly thousand lines long.
2578 * 1 : csp = Current client state (buffers, headers, etc...)
2580 * Returns : Nothing.
2582 *********************************************************************/
2583 static void chat(struct client_state *csp)
2585 char buf[BUFFER_SIZE];
2592 int ms_iis5_hack = 0;
2593 unsigned long long byte_count = 0;
2594 int forwarded_connect_retries = 0;
2595 int max_forwarded_connect_retries = csp->config->forwarded_connect_retries;
2596 const struct forward_spec *fwd;
2597 struct http_request *http;
2598 long len = 0; /* for buffer sizes (and negative error codes) */
2600 /* Function that does the content filtering for the current request */
2601 filter_function_ptr content_filter = NULL;
2603 /* Skeleton for HTTP response, if we should intercept the request */
2604 struct http_response *rsp;
2605 struct timeval timeout;
2607 memset(buf, 0, sizeof(buf));
2611 if (receive_client_request(csp) != JB_ERR_OK)
2615 if (parse_client_request(csp) != JB_ERR_OK)
2620 /* decide how to route the HTTP request */
2621 fwd = forward_url(csp, http);
2624 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
2625 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2630 * build the http request to send to the server
2631 * we have to do one of the following:
2633 * create = use the original HTTP request to create a new
2634 * HTTP request that has either the path component
2635 * without the http://domainspec (w/path) or the
2636 * full orininal URL (w/url)
2637 * Note that the path and/or the HTTP version may
2638 * have been altered by now.
2640 * connect = Open a socket to the host:port of the server
2641 * and short-circuit server and client socket.
2643 * pass = Pass the request unchanged if forwarding a CONNECT
2644 * request to a parent proxy. Note that we'll be sending
2645 * the CFAIL message ourselves if connecting to the parent
2646 * fails, but we won't send a CSUCCEED message if it works,
2647 * since that would result in a double message (ours and the
2648 * parent's). After sending the request to the parent, we simply
2651 * here's the matrix:
2654 * +--------+--------+
2656 * 0 | create | connect|
2658 * Forwarding +--------+--------+
2660 * 1 | create | pass |
2662 * +--------+--------+
2666 if (http->ssl && connect_port_is_forbidden(csp))
2668 const char *acceptable_connect_ports =
2669 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
2670 assert(NULL != acceptable_connect_ports);
2671 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
2672 "limit-connect{%s} doesn't allow CONNECT requests to port %d.",
2673 csp->ip_addr_str, acceptable_connect_ports, csp->http->port);
2674 csp->action->flags |= ACTION_BLOCK;
2680 freez(csp->headers->first->str);
2681 build_request_line(csp, fwd, &csp->headers->first->str);
2685 * We have a request. Check if one of the crunchers wants it.
2687 if (crunch_response_triggered(csp, crunchers_all))
2690 * Yes. The client got the crunch response
2691 * and we are done here after cleaning up.
2693 /* XXX: why list_remove_all()? */
2694 list_remove_all(csp->headers);
2699 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
2701 if (fwd->forward_host)
2703 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
2704 fwd->forward_host, fwd->forward_port, http->hostport);
2708 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
2711 /* here we connect to the server, gateway, or the forwarder */
2713 while ((csp->sfd = forwarded_connect(fwd, http, csp))
2714 && (errno == EINVAL)
2715 && (forwarded_connect_retries++ < max_forwarded_connect_retries))
2717 log_error(LOG_LEVEL_ERROR,
2718 "failed request #%u to connect to %s. Trying again.",
2719 forwarded_connect_retries, http->hostport);
2722 if (csp->sfd == JB_INVALID_SOCKET)
2724 if (fwd->type != SOCKS_NONE)
2727 rsp = error_response(csp, "forwarding-failed", errno);
2729 else if (errno == EINVAL)
2731 rsp = error_response(csp, "no-such-domain", errno);
2735 rsp = error_response(csp, "connect-failed", errno);
2736 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
2740 /* Write the answer to the client */
2743 send_crunch_response(csp, rsp);
2749 hdr = list_to_text(csp->headers);
2752 /* FIXME Should handle error properly */
2753 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2755 list_remove_all(csp->headers);
2757 if (fwd->forward_host || (http->ssl == 0))
2760 * Write the client's (modified) header to the server
2761 * (along with anything else that may be in the buffer)
2763 if (write_socket(csp->sfd, hdr, strlen(hdr))
2764 || (flush_socket(csp->sfd, csp->iob) < 0))
2766 log_error(LOG_LEVEL_CONNECT,
2767 "write header to: %s failed: %E", http->hostport);
2769 rsp = error_response(csp, "connect-failed", errno);
2772 send_crunch_response(csp, rsp);
2782 * We're running an SSL tunnel and we're not forwarding,
2783 * so just send the "connect succeeded" message to the
2784 * client, flush the rest, and get out of the way.
2786 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
2794 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
2796 /* we're finished with the client's header */
2799 maxfd = (csp->cfd > csp->sfd) ? csp->cfd : csp->sfd;
2801 /* pass data between the client and server
2802 * until one or the other shuts down the connection.
2811 * FD_ZERO here seems to point to an errant macro which crashes.
2812 * So do this by hand for now...
2814 memset(&rfds,0x00,sizeof(fd_set));
2818 FD_SET(csp->cfd, &rfds);
2819 FD_SET(csp->sfd, &rfds);
2821 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2822 if ((csp->flags & CSP_FLAG_CHUNKED)
2823 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2824 && ((csp->iob->eod - csp->iob->cur) >= 5)
2825 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2827 log_error(LOG_LEVEL_CONNECT,
2828 "Looks like we read the last chunk together with "
2829 "the server headers. We better stop reading.");
2830 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2831 csp->expected_content_length = byte_count;
2832 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2834 if (server_body && server_response_is_complete(csp, byte_count))
2836 log_error(LOG_LEVEL_CONNECT,
2837 "Done reading from server. Expected content length: %llu. "
2838 "Actual content length: %llu. Most recently received: %d.",
2839 csp->expected_content_length, byte_count, len);
2842 * XXX: should not jump around,
2843 * chat() is complicated enough already.
2847 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2849 timeout.tv_sec = csp->config->socket_timeout;
2850 timeout.tv_usec = 0;
2851 n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
2855 log_error(LOG_LEVEL_ERROR,
2856 "Didn't receive data in time: %s", http->url);
2857 if ((byte_count == 0) && (http->ssl == 0))
2859 write_socket(csp->cfd, CONNECTION_TIMEOUT_RESPONSE,
2860 strlen(CONNECTION_TIMEOUT_RESPONSE));
2862 mark_server_socket_tainted(csp);
2867 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2868 mark_server_socket_tainted(csp);
2873 * This is the body of the browser's request,
2874 * just read and write it.
2876 if (FD_ISSET(csp->cfd, &rfds))
2878 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
2882 /* XXX: not sure if this is necessary. */
2883 mark_server_socket_tainted(csp);
2884 break; /* "game over, man" */
2887 if (write_socket(csp->sfd, buf, (size_t)len))
2889 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2890 mark_server_socket_tainted(csp);
2897 * The server wants to talk. It could be the header or the body.
2898 * If `hdr' is null, then it's the header otherwise it's the body.
2899 * FIXME: Does `hdr' really mean `host'? No.
2901 if (FD_ISSET(csp->sfd, &rfds))
2904 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
2908 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2910 if (http->ssl && (fwd->forward_host == NULL))
2913 * Just hang up. We already confirmed the client's CONNECT
2914 * request with status code 200 and unencrypted content is
2915 * no longer welcome.
2917 log_error(LOG_LEVEL_ERROR,
2918 "CONNECT already confirmed. Unable to tell the client about the problem.");
2921 else if (byte_count)
2924 * Just hang up. We already transmitted the original headers
2925 * and parts of the original content and therefore missed the
2926 * chance to send an error message (without risking data corruption).
2928 * XXX: we could retry with a fancy range request here.
2930 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2931 "Unable to tell the client about the problem.");
2932 mark_server_socket_tainted(csp);
2936 rsp = error_response(csp, "connect-failed", errno);
2939 send_crunch_response(csp, rsp);
2945 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2946 if (csp->flags & CSP_FLAG_CHUNKED)
2948 if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2950 /* XXX: this is a temporary hack */
2951 log_error(LOG_LEVEL_CONNECT,
2952 "Looks like we reached the end of the last chunk. "
2953 "We better stop reading.");
2954 csp->expected_content_length = byte_count + (unsigned long long)len;
2955 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2959 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2962 * Add a trailing zero to let be able to use string operations.
2963 * XXX: do we still need this with filter_popups gone?
2968 * Normally, this would indicate that we've read
2969 * as much as the server has sent us and we can
2970 * close the client connection. However, Microsoft
2971 * in its wisdom has released IIS/5 with a bug that
2972 * prevents it from sending the trailing \r\n in
2973 * a 302 redirect header (and possibly other headers).
2974 * To work around this if we've haven't parsed
2975 * a full header we'll append a trailing \r\n
2976 * and see if this now generates a valid one.
2978 * This hack shouldn't have any impacts. If we've
2979 * already transmitted the header or if this is a
2980 * SSL connection, then we won't bother with this
2981 * hack. So we only work on partially received
2982 * headers. If we append a \r\n and this still
2983 * doesn't generate a valid header, then we won't
2984 * transmit anything to the client.
2989 if (server_body || http->ssl)
2992 * If we have been buffering up the document,
2993 * now is the time to apply content modification
2994 * and send the result to the client.
2998 p = execute_content_filter(csp, content_filter);
3000 * If the content filter fails, use the original
3001 * buffer and length.
3002 * (see p != NULL ? p : csp->iob->cur below)
3006 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3009 if (JB_ERR_OK != update_server_headers(csp))
3011 log_error(LOG_LEVEL_FATAL,
3012 "Failed to update server headers. after filtering.");
3015 hdr = list_to_text(csp->headers);
3018 /* FIXME Should handle error properly */
3019 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3022 if (write_socket(csp->cfd, hdr, strlen(hdr))
3023 || write_socket(csp->cfd,
3024 ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
3026 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3029 mark_server_socket_tainted(csp);
3037 break; /* "game over, man" */
3041 * This is NOT the body, so
3042 * Let's pretend the server just sent us a blank line.
3044 snprintf(buf, sizeof(buf), "\r\n");
3045 len = (int)strlen(buf);
3048 * Now, let the normal header parsing algorithm below do its
3049 * job. If it fails, we'll exit instead of continuing.
3056 * If this is an SSL connection or we're in the body
3057 * of the server document, just write it to the client,
3058 * unless we need to buffer the body for later content-filtering
3060 if (server_body || http->ssl)
3065 * If there is no memory left for buffering the content, or the buffer limit
3066 * has been reached, switch to non-filtering mode, i.e. make & write the
3067 * header, flush the iob and buf, and get out of the way.
3069 if (add_to_iob(csp, buf, len))
3074 log_error(LOG_LEVEL_INFO,
3075 "Flushing header and buffers. Stepping back from filtering.");
3077 hdr = list_to_text(csp->headers);
3081 * Memory is too tight to even generate the header.
3082 * Send our static "Out-of-memory" page.
3084 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3085 rsp = cgi_error_memory();
3086 send_crunch_response(csp, rsp);
3087 mark_server_socket_tainted(csp);
3090 hdrlen = strlen(hdr);
3092 if (write_socket(csp->cfd, hdr, hdrlen)
3093 || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
3094 || (write_socket(csp->cfd, buf, (size_t)len)))
3096 log_error(LOG_LEVEL_CONNECT,
3097 "Flush header and buffers to client failed: %E");
3099 mark_server_socket_tainted(csp);
3104 * Reset the byte_count to the amount of bytes
3105 * we just flushed. len will be added a few lines below,
3106 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3108 byte_count = (unsigned long long)flushed;
3110 content_filter = NULL;
3116 if (write_socket(csp->cfd, buf, (size_t)len))
3118 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3119 mark_server_socket_tainted(csp);
3123 byte_count += (unsigned long long)len;
3128 const char *header_start;
3130 * We're still looking for the end of the server's header.
3131 * Buffer up the data we just read. If that fails, there's
3132 * little we can do but send our static out-of-memory page.
3134 if (add_to_iob(csp, buf, len))
3136 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3137 rsp = cgi_error_memory();
3138 send_crunch_response(csp, rsp);
3139 mark_server_socket_tainted(csp);
3143 header_start = csp->iob->cur;
3145 /* Convert iob into something sed() can digest */
3146 if (JB_ERR_PARSE == get_server_headers(csp))
3151 * Well, we tried our MS IIS/5 hack and it didn't work.
3152 * The header is incomplete and there isn't anything
3153 * we can do about it.
3155 log_error(LOG_LEVEL_INFO,
3156 "MS IIS5 hack didn't produce valid headers.");
3162 * Since we have to wait for more from the server before
3163 * we can parse the headers we just continue here.
3165 long header_offset = csp->iob->cur - header_start;
3166 assert(csp->iob->cur >= header_start);
3167 byte_count += (unsigned long long)(len - header_offset);
3168 log_error(LOG_LEVEL_CONNECT, "Continuing buffering headers. "
3169 "byte_count: %llu. header_offset: %d. len: %d.",
3170 byte_count, header_offset, len);
3175 /* Did we actually get anything? */
3176 if (NULL == csp->headers->first)
3178 log_error(LOG_LEVEL_ERROR, "Empty server or forwarder response.");
3179 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3180 write_socket(csp->cfd, NO_SERVER_DATA_RESPONSE, strlen(NO_SERVER_DATA_RESPONSE));
3181 free_http_request(http);
3182 mark_server_socket_tainted(csp);
3186 assert(csp->headers->first->str);
3188 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3189 strncmpic(csp->headers->first->str, "ICY", 3))
3192 * It doesn't look like a HTTP (or Shoutcast) response:
3193 * tell the client and log the problem.
3195 if (strlen(csp->headers->first->str) > 30)
3197 csp->headers->first->str[30] = '\0';
3199 log_error(LOG_LEVEL_ERROR,
3200 "Invalid server or forwarder response. Starts with: %s",
3201 csp->headers->first->str);
3202 log_error(LOG_LEVEL_CLF,
3203 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3204 write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3205 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3206 free_http_request(http);
3207 mark_server_socket_tainted(csp);
3212 * We have now received the entire server header,
3213 * filter it and send the result to the client
3215 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3217 log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
3219 hdr = list_to_text(csp->headers);
3222 /* FIXME Should handle error properly */
3223 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3226 if (crunch_response_triggered(csp, crunchers_light))
3229 * One of the tags created by a server-header
3230 * tagger triggered a crunch. We already
3231 * delivered the crunch response to the client
3232 * and are done here after cleaning up.
3235 mark_server_socket_tainted(csp);
3238 /* Buffer and pcrs filter this if appropriate. */
3240 if (!http->ssl) /* We talk plaintext */
3242 content_filter = get_filter_function(csp);
3245 * Only write if we're not buffering for content modification
3247 if (!content_filter)
3250 * Write the server's (modified) header to
3251 * the client (along with anything else that
3252 * may be in the buffer)
3255 if (write_socket(csp->cfd, hdr, strlen(hdr))
3256 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
3258 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
3261 * The write failed, so don't bother mentioning it
3262 * to the client... it probably can't hear us anyway.
3265 mark_server_socket_tainted(csp);
3269 byte_count += (unsigned long long)len;
3274 * XXX: the header lenght should probably
3275 * be calculated by get_server_headers().
3277 long header_length = csp->iob->cur - header_start;
3278 assert(csp->iob->cur > header_start);
3279 byte_count += (unsigned long long)(len - header_length);
3282 /* we're finished with the server's header */
3288 * If this was a MS IIS/5 hack then it means the server
3289 * has already closed the connection. Nothing more to read.
3294 log_error(LOG_LEVEL_INFO,
3295 "Closed server connection detected with MS IIS5 hack enabled.");
3301 mark_server_socket_tainted(csp);
3302 return; /* huh? we should never get here */
3305 if (csp->content_length == 0)
3308 * If Privoxy didn't recalculate the Content-Lenght,
3309 * byte_count is still correct.
3311 csp->content_length = byte_count;
3314 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3315 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3316 && (csp->expected_content_length != byte_count))
3318 log_error(LOG_LEVEL_CONNECT,
3319 "Received %llu bytes while expecting %llu.",
3320 byte_count, csp->expected_content_length);
3321 mark_server_socket_tainted(csp);
3325 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3326 csp->ip_addr_str, http->ocmd, csp->content_length);
3330 /*********************************************************************
3334 * Description : This is little more than chat. We only "serve" to
3335 * to close any socket that chat may have opened.
3338 * 1 : csp = Current client state (buffers, headers, etc...)
3342 *********************************************************************/
3344 void serve(struct client_state *csp)
3345 #else /* ifndef AMIGA */
3346 static void serve(struct client_state *csp)
3347 #endif /* def AMIGA */
3350 close_socket(csp->cfd);
3352 if (csp->sfd != JB_INVALID_SOCKET)
3354 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3355 static int monitor_thread_running = 0;
3357 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3358 && (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE))
3360 remember_connection(csp->sfd, csp->http, forward_url(csp, csp->http));
3361 privoxy_mutex_lock(&connection_reuse_mutex);
3362 if (!monitor_thread_running)
3364 monitor_thread_running = 1;
3365 privoxy_mutex_unlock(&connection_reuse_mutex);
3366 wait_for_alive_connections();
3367 privoxy_mutex_lock(&connection_reuse_mutex);
3368 monitor_thread_running = 0;
3370 privoxy_mutex_unlock(&connection_reuse_mutex);
3374 forget_connection(csp->sfd);
3375 close_socket(csp->sfd);
3378 close_socket(csp->sfd);
3379 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3382 csp->flags &= ~CSP_FLAG_ACTIVE;
3388 /*********************************************************************
3390 * Function : server_thread
3392 * Description : We only exist to call `serve' in a threaded environment.
3395 * 1 : data = Current client state (buffers, headers, etc...)
3397 * Returns : Always 0.
3399 *********************************************************************/
3400 static int32 server_thread(void *data)
3402 serve((struct client_state *) data);
3409 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3410 /*********************************************************************
3414 * Description : Print usage info & exit.
3416 * Parameters : Pointer to argv[0] for identifying ourselves
3420 *********************************************************************/
3421 static void usage(const char *myname)
3423 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3427 #endif /* defined(unix) */
3430 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3431 #endif /* defined(unix) */
3432 "[--version] [configfile]\n"
3433 "Aborting\n", myname);
3438 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3441 #ifdef MUTEX_LOCKS_AVAILABLE
3442 /*********************************************************************
3444 * Function : privoxy_mutex_lock
3446 * Description : Locks a mutex.
3449 * 1 : mutex = The mutex to lock.
3451 * Returns : Void. May exit in case of errors.
3453 *********************************************************************/
3454 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3456 #ifdef FEATURE_PTHREAD
3457 int err = pthread_mutex_lock(mutex);
3460 if (mutex != &log_mutex)
3462 log_error(LOG_LEVEL_FATAL,
3463 "Mutex locking failed: %s.\n", strerror(err));
3468 EnterCriticalSection(mutex);
3469 #endif /* def FEATURE_PTHREAD */
3473 /*********************************************************************
3475 * Function : privoxy_mutex_unlock
3477 * Description : Unlocks a mutex.
3480 * 1 : mutex = The mutex to unlock.
3482 * Returns : Void. May exit in case of errors.
3484 *********************************************************************/
3485 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3487 #ifdef FEATURE_PTHREAD
3488 int err = pthread_mutex_unlock(mutex);
3491 if (mutex != &log_mutex)
3493 log_error(LOG_LEVEL_FATAL,
3494 "Mutex unlocking failed: %s.\n", strerror(err));
3499 LeaveCriticalSection(mutex);
3500 #endif /* def FEATURE_PTHREAD */
3504 /*********************************************************************
3506 * Function : privoxy_mutex_init
3508 * Description : Prepares a mutex.
3511 * 1 : mutex = The mutex to initialize.
3513 * Returns : Void. May exit in case of errors.
3515 *********************************************************************/
3516 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3518 #ifdef FEATURE_PTHREAD
3519 int err = pthread_mutex_init(mutex, 0);
3522 printf("Fatal error. Mutex initialization failed: %s.\n",
3527 InitializeCriticalSection(mutex);
3528 #endif /* def FEATURE_PTHREAD */
3530 #endif /* def MUTEX_LOCKS_AVAILABLE */
3532 /*********************************************************************
3534 * Function : initialize_mutexes
3536 * Description : Prepares mutexes if mutex support is available.
3540 * Returns : Void, exits in case of errors.
3542 *********************************************************************/
3543 static void initialize_mutexes(void)
3545 #ifdef MUTEX_LOCKS_AVAILABLE
3547 * Prepare global mutex semaphores
3549 privoxy_mutex_init(&log_mutex);
3550 privoxy_mutex_init(&log_init_mutex);
3551 privoxy_mutex_init(&connection_reuse_mutex);
3554 * XXX: The assumptions below are a bit naive
3555 * and can cause locks that aren't necessary.
3557 * For example older FreeBSD versions (< 6.x?)
3558 * have no gethostbyname_r, but gethostbyname is
3561 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3562 privoxy_mutex_init(&resolver_mutex);
3563 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3565 * XXX: should we use a single mutex for
3566 * localtime() and gmtime() as well?
3568 #ifndef HAVE_GMTIME_R
3569 privoxy_mutex_init(&gmtime_mutex);
3570 #endif /* ndef HAVE_GMTIME_R */
3572 #ifndef HAVE_LOCALTIME_R
3573 privoxy_mutex_init(&localtime_mutex);
3574 #endif /* ndef HAVE_GMTIME_R */
3577 privoxy_mutex_init(&rand_mutex);
3578 #endif /* ndef HAVE_RANDOM */
3579 #endif /* def MUTEX_LOCKS_AVAILABLE */
3583 /*********************************************************************
3587 * Description : Load the config file and start the listen loop.
3588 * This function is a lot more *sane* with the `load_config'
3589 * and `listen_loop' functions; although it stills does
3590 * a *little* too much for my taste.
3593 * 1 : argc = Number of parameters (including $0).
3594 * 2 : argv = Array of (char *)'s to the parameters.
3596 * Returns : 1 if : can't open config file, unrecognized directive,
3597 * stats requested in multi-thread mode, can't open the
3598 * log file, can't open the jar file, listen port is invalid,
3599 * any load fails, and can't bind port.
3601 * Else main never returns, the process must be signaled
3602 * to terminate execution. Or, on Windows, use the
3603 * "File", "Exit" menu option.
3605 *********************************************************************/
3607 int real_main(int argc, const char *argv[])
3609 int main(int argc, const char *argv[])
3613 unsigned int random_seed;
3615 struct passwd *pw = NULL;
3616 struct group *grp = NULL;
3619 char *pre_chroot_nslookup_to_load_resolver = NULL;
3626 #if !defined(_WIN32)
3633 /* Prepare mutexes if supported and necessary. */
3634 initialize_mutexes();
3636 /* Enable logging until further notice. */
3640 * Parse the command line arguments
3642 * XXX: simply printing usage information in case of
3643 * invalid arguments isn't particularly user friendly.
3645 while (++argc_pos < argc)
3648 /* Check to see if the service must be installed or uninstalled */
3649 if (strncmp(argv[argc_pos], "--install", 9) == 0)
3651 const char *pName = argv[argc_pos] + 9;
3654 exit( (install_service(pName)) ? 0 : 1 );
3656 else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
3658 const char *pName = argv[argc_pos] + 11;
3661 exit((uninstall_service(pName)) ? 0 : 1);
3663 else if (strcmp(argv[argc_pos], "--service" ) == 0)
3665 bRunAsService = TRUE;
3666 w32_set_service_cwd();
3667 atexit(w32_service_exit_notify);
3670 #endif /* defined(_WIN32) */
3673 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3675 if (strcmp(argv[argc_pos], "--help") == 0)
3680 else if(strcmp(argv[argc_pos], "--version") == 0)
3682 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3688 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
3693 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
3695 if (++argc_pos == argc) usage(argv[0]);
3696 pidfile = strdup(argv[argc_pos]);
3699 else if (strcmp(argv[argc_pos], "--user" ) == 0)
3701 if (++argc_pos == argc) usage(argv[argc_pos]);
3703 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
3706 if (NULL == (grp = getgrnam(p)))
3708 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
3712 if (NULL == (pw = getpwnam(argv[argc_pos])))
3714 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
3717 if (p != NULL) *--p = '\0';
3720 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup" ) == 0)
3722 if (++argc_pos == argc) usage(argv[0]);
3723 pre_chroot_nslookup_to_load_resolver = strdup(argv[argc_pos]);
3726 else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
3730 #endif /* defined(unix) */
3732 else if (argc_pos + 1 != argc)
3735 * This is neither the last command line
3736 * option, nor was it recognized before,
3737 * therefore it must be invalid.
3743 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3745 configfile = argv[argc_pos];
3748 } /* -END- while (more arguments) */
3750 show_version(Argv[0]);
3753 if ( *configfile != '/' )
3755 char cwd[BUFFER_SIZE];
3757 size_t abs_file_size;
3759 /* make config-filename absolute here */
3760 if (NULL == getcwd(cwd, sizeof(cwd)))
3762 perror("failed to get current working directory");
3767 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3768 basedir = strdup(cwd);
3770 if (NULL == basedir ||
3771 NULL == (abs_file = malloc(abs_file_size)))
3773 perror("malloc failed");
3776 strlcpy(abs_file, basedir, abs_file_size);
3777 strlcat(abs_file, "/", abs_file_size );
3778 strlcat(abs_file, configfile, abs_file_size);
3779 configfile = abs_file;
3781 #endif /* defined unix */
3785 clients->next = NULL;
3787 /* XXX: factor out initialising after the next stable release. */
3790 #elif defined(_WIN32)
3794 random_seed = (unsigned int)time(NULL);
3796 srandom(random_seed);
3799 #endif /* ifdef HAVE_RANDOM */
3802 * Unix signal handling
3804 * Catch the abort, interrupt and terminate signals for a graceful exit
3805 * Catch the hangup signal so the errlog can be reopened.
3806 * Ignore the broken pipe signals (FIXME: Why?)
3808 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3811 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP, 0 };
3812 const int ignored_signals[] = { SIGPIPE, 0 };
3814 for (idx = 0; catched_signals[idx] != 0; idx++)
3816 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3817 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3819 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3820 #endif /* ifdef sun */
3822 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3826 for (idx = 0; ignored_signals[idx] != 0; idx++)
3828 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
3830 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
3835 #else /* ifdef _WIN32 */
3836 # ifdef _WIN_CONSOLE
3838 * We *are* in a windows console app.
3839 * Print a verbose messages about FAQ's and such
3841 printf("%s", win32_blurb);
3842 # endif /* def _WIN_CONSOLE */
3843 #endif /* def _WIN32 */
3846 /* Initialize the CGI subsystem */
3847 cgi_init_error_messages();
3850 * If runnig on unix and without the --nodaemon
3851 * option, become a daemon. I.e. fork, detach
3852 * from tty and get process group leadership
3865 if ( pid < 0 ) /* error */
3870 else if ( pid != 0 ) /* parent */
3875 * must check for errors
3876 * child died due to missing files aso
3879 wpid = waitpid( pid, &status, WNOHANG );
3888 /* Should be more portable, but not as well tested */
3893 #else /* ndef __FreeBSD__ */
3895 #endif /* ndef __FreeBSD__ */
3896 fd = open("/dev/tty", O_RDONLY);
3899 /* no error check here */
3900 ioctl( fd, TIOCNOTTY,0 );
3905 * stderr (fd 2) will be closed later on, when the
3906 * log file has been parsed.
3913 } /* -END- if (!no_daemon) */
3916 * As soon as we have written the PID file, we can switch
3917 * to the user and group ID indicated by the --user option
3923 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3925 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3929 if (setgroups(1, &grp->gr_gid))
3931 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3934 else if (initgroups(pw->pw_name, pw->pw_gid))
3936 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3942 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3944 /* Read the time zone file from /etc before doing chroot. */
3946 if (NULL != pre_chroot_nslookup_to_load_resolver
3947 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3949 /* Initialize resolver library. */
3950 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3952 if (chroot(pw->pw_dir) < 0)
3954 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3958 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3961 if (setuid(pw->pw_uid))
3963 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3967 char putenv_dummy[64];
3969 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3970 if (putenv(putenv_dummy) != 0)
3972 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3975 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3976 if (putenv(putenv_dummy) != 0)
3978 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3984 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3987 #endif /* defined unix */
3990 /* This will be FALSE unless the command line specified --service
3994 /* Yup, so now we must attempt to establish a connection
3995 * with the service dispatcher. This will only work if this
3996 * process was launched by the service control manager to
3997 * actually run as a service. If this isn't the case, i've
3998 * known it take around 30 seconds or so for the call to return.
4001 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
4002 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
4004 /* Service has run, and at this point is now being stopped, so just return */
4009 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
4011 /* An error occurred. Usually it's because --service was wrongly specified
4012 * and we were unable to connect to the Service Control Dispatcher because
4013 * it wasn't expecting us and is therefore not listening.
4015 * For now, just continue below to call the listen_loop function.
4018 #endif /* def _WIN32 */
4028 /*********************************************************************
4030 * Function : bind_port_helper
4032 * Description : Bind the listen port. Handles logging, and aborts
4036 * 1 : config = Privoxy configuration. Specifies port
4039 * Returns : Port that was opened.
4041 *********************************************************************/
4042 static jb_socket bind_port_helper(struct configuration_spec * config)
4047 if (config->haddr == NULL)
4049 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
4054 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
4055 config->hport, config->haddr);
4058 result = bind_port(config->haddr, config->hport, &bfd);
4065 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
4066 "There may be another Privoxy or some other "
4067 "proxy running on port %d",
4068 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
4069 config->hport, config->hport);
4072 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
4073 "The hostname is not resolvable",
4074 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
4077 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
4078 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
4081 /* shouldn't get here */
4082 return JB_INVALID_SOCKET;
4085 config->need_bind = 0;
4092 /* Without this simple workaround we get this compiler warning from _beginthread
4093 * warning C4028: formal parameter 1 different from declaration
4095 void w32_service_listen_loop(void *p)
4099 #endif /* def _WIN32 */
4102 /*********************************************************************
4104 * Function : listen_loop
4106 * Description : bind the listen port and enter a "FOREVER" listening loop.
4112 *********************************************************************/
4113 static void listen_loop(void)
4115 struct client_state *csp = NULL;
4117 struct configuration_spec * config;
4119 config = load_config();
4121 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4123 * XXX: Should be relocated once it no
4124 * longer needs to emit log messages.
4126 initialize_reusable_connections();
4127 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4129 bfd = bind_port_helper(config);
4131 #ifdef FEATURE_GRACEFUL_TERMINATION
4132 while (!g_terminate)
4137 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
4138 while (waitpid(-1, NULL, WNOHANG) > 0)
4140 /* zombie children */
4142 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
4145 * Free data that was used by died threads
4151 * Re-open the errlog after HUP signal
4153 if (received_hup_signal)
4155 if (NULL != config->logfile)
4157 init_error_log(Argv[0], config->logfile);
4159 received_hup_signal = 0;
4163 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
4165 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
4169 csp->flags |= CSP_FLAG_ACTIVE;
4170 csp->sfd = JB_INVALID_SOCKET;
4172 csp->config = config = load_config();
4174 if ( config->need_bind )
4177 * Since we were listening to the "old port", we will not see
4178 * a "listen" param change until the next IJB request. So, at
4179 * least 1 more request must be made for us to find the new
4180 * setting. I am simply closing the old socket and binding the
4183 * Which-ever is correct, we will serve 1 more page via the
4184 * old settings. This should probably be a "show-proxy-args"
4185 * request. This should not be a so common of an operation
4186 * that this will hurt people's feelings.
4191 bfd = bind_port_helper(config);
4194 log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
4196 if (!accept_connection(csp, bfd))
4198 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
4211 log_error(LOG_LEVEL_CONNECT, "accepted connection from %s", csp->ip_addr_str);
4214 #ifdef FEATURE_TOGGLE
4215 if (global_toggle_state)
4216 #endif /* def FEATURE_TOGGLE */
4218 csp->flags |= CSP_FLAG_TOGGLED_ON;
4221 if (run_loader(csp))
4223 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
4224 /* Never get here - LOG_LEVEL_FATAL causes program exit */
4228 if (block_acl(NULL,csp))
4230 log_error(LOG_LEVEL_CONNECT, "Connection from %s dropped due to ACL", csp->ip_addr_str);
4231 close_socket(csp->cfd);
4235 #endif /* def FEATURE_ACL */
4237 /* add it to the list of clients */
4238 csp->next = clients->next;
4239 clients->next = csp;
4241 if (config->multi_threaded)
4245 /* this is a switch () statment in the C preprocessor - ugh */
4246 #undef SELECTED_ONE_OPTION
4248 /* Use Pthreads in preference to native code */
4249 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
4250 #define SELECTED_ONE_OPTION
4252 pthread_t the_thread;
4253 pthread_attr_t attrs;
4255 pthread_attr_init(&attrs);
4256 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
4257 errno = pthread_create(&the_thread, &attrs,
4258 (void * (*)(void *))serve, csp);
4259 child_id = errno ? -1 : 0;
4260 pthread_attr_destroy(&attrs);
4264 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
4265 #define SELECTED_ONE_OPTION
4266 child_id = _beginthread(
4267 (void (*)(void *))serve,
4272 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
4273 #define SELECTED_ONE_OPTION
4274 child_id = _beginthread(
4275 (void(* _Optlink)(void*))serve,
4281 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
4282 #define SELECTED_ONE_OPTION
4284 thread_id tid = spawn_thread
4285 (server_thread, "server", B_NORMAL_PRIORITY, csp);
4287 if ((tid >= 0) && (resume_thread(tid) == B_OK))
4289 child_id = (int) tid;
4298 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
4299 #define SELECTED_ONE_OPTION
4300 csp->cfd = ReleaseSocket(csp->cfd, -1);
4303 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4304 NP_Output, Output(),
4305 NP_CloseOutput, FALSE,
4306 NP_Name, (ULONG)"privoxy child",
4310 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4311 NP_Output, Output(),
4312 NP_CloseOutput, FALSE,
4313 NP_Name, (ULONG)"privoxy child",
4314 NP_StackSize, 200*1024,
4320 ((struct Task *)child_id)->tc_UserData = csp;
4321 Signal((struct Task *)child_id, SIGF_SINGLE);
4326 #if !defined(SELECTED_ONE_OPTION)
4329 /* This block is only needed when using fork().
4330 * When using threads, the server thread was
4331 * created and run by the call to _beginthread().
4333 if (child_id == 0) /* child */
4336 #ifdef FEATURE_TOGGLE
4337 int inherited_toggle_state = global_toggle_state;
4338 #endif /* def FEATURE_TOGGLE */
4343 * If we've been toggled or we've blocked the request, tell Mom
4346 #ifdef FEATURE_TOGGLE
4347 if (inherited_toggle_state != global_toggle_state)
4349 rc |= RC_FLAG_TOGGLED;
4351 #endif /* def FEATURE_TOGGLE */
4353 #ifdef FEATURE_STATISTICS
4354 if (csp->flags & CSP_FLAG_REJECTED)
4356 rc |= RC_FLAG_BLOCKED;
4358 #endif /* ndef FEATURE_STATISTICS */
4362 else if (child_id > 0) /* parent */
4364 /* in a fork()'d environment, the parent's
4365 * copy of the client socket and the CSP
4369 #if !defined(_WIN32) && !defined(__CYGWIN__)
4371 wait( &child_status );
4374 * Evaluate child's return code: If the child has
4375 * - been toggled, toggle ourselves
4376 * - blocked its request, bump up the stats counter
4379 #ifdef FEATURE_TOGGLE
4380 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4382 global_toggle_state = !global_toggle_state;
4384 #endif /* def FEATURE_TOGGLE */
4386 #ifdef FEATURE_STATISTICS
4388 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4392 #endif /* def FEATURE_STATISTICS */
4394 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4395 close_socket(csp->cfd);
4396 csp->flags &= ~CSP_FLAG_ACTIVE;
4400 #undef SELECTED_ONE_OPTION
4401 /* end of cpp switch () */
4403 if (child_id < 0) /* failed */
4405 char buf[BUFFER_SIZE];
4407 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
4409 snprintf(buf , sizeof(buf), "Privoxy: can't fork: errno = %d", errno);
4411 write_socket(csp->cfd, buf, strlen(buf));
4412 close_socket(csp->cfd);
4413 csp->flags &= ~CSP_FLAG_ACTIVE;
4424 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4426 /* Clean up. Aim: free all memory (no leaks) */
4427 #ifdef FEATURE_GRACEFUL_TERMINATION
4429 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4431 unload_current_config_file();
4432 unload_current_actions_file();
4433 unload_current_re_filterfile();
4434 #ifdef FEATURE_TRUST
4435 unload_current_trust_file();
4438 if (config->multi_threaded)
4445 } while ((clients->next != NULL) && (--i > 0));
4449 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4460 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4461 /* Cleanup - remove taskbar icon etc. */
4466 #endif /* FEATURE_GRACEFUL_TERMINATION */