1 const char jcc_rcs[] = "$Id: jcc.c,v 1.133 2007/05/04 11:23:19 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-2007 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.133 2007/05/04 11:23:19 fabiankeil
37 * - Don't rerun crunchers that only depend on the request URL.
38 * - Don't count redirects and CGI requests as "blocked requests".
40 * Revision 1.132 2007/04/25 15:15:17 fabiankeil
41 * Support crunching based on tags created by server-header taggers.
43 * Revision 1.131 2007/04/22 13:24:50 fabiankeil
44 * Make HTTP snippets static (again). Add a Content-Type for those
45 * with content so the browser doesn't guess it based on the URL.
47 * Revision 1.130 2007/04/19 13:47:34 fabiankeil
48 * Move crunching and request line rebuilding out of chat().
50 * Revision 1.129 2007/04/15 16:39:20 fabiankeil
51 * Introduce tags as alternative way to specify which
52 * actions apply to a request. At the moment tags can be
53 * created based on client and server headers.
55 * Revision 1.128 2007/03/25 16:55:54 fabiankeil
56 * Don't CLF-log CONNECT requests twice.
58 * Revision 1.127 2007/03/20 13:53:17 fabiankeil
59 * Log the source address for ACL-related connection drops.
61 * Revision 1.126 2007/03/17 15:20:05 fabiankeil
62 * New config option: enforce-blocks.
64 * Revision 1.125 2007/03/09 14:12:00 fabiankeil
65 * - Move null byte check into separate function.
66 * - Don't confuse the client with error pages
67 * if a CONNECT request was already confirmed.
69 * Revision 1.124 2007/02/23 14:59:54 fabiankeil
70 * Speed up NULL byte escaping and only log the complete
71 * NULL byte requests with header debugging enabled.
73 * Revision 1.123 2007/02/21 18:42:10 fabiankeil
74 * Answer requests that contain NULL bytes with
75 * a custom response instead of waiting for more
76 * data until the client eventually hangs up.
78 * Revision 1.122 2007/02/07 11:12:02 fabiankeil
79 * - Move delivery and logging of crunched responses
80 * from chat() into send_crunch_response().
81 * - Display the reason for generating http_responses.
82 * - Log the content length for LOG_LEVEL_CLF correctly
83 * (still incorrect for some fixed responses).
84 * - Reword an incorrect comment about
85 * treat-forbidden-connects-like-blocks violating
87 * - Add some log messages.
89 * Revision 1.121 2007/01/27 10:52:56 fabiankeil
90 * Move mutex initialization into separate
91 * function and exit in case of errors.
93 * Revision 1.120 2007/01/26 14:18:42 fabiankeil
94 * - Start to reduce chat()'s line count and move
95 * parts of it into separate functions.
96 * - Add "HTTP/1.1 100 Continue" hack for BR 756734.
98 * Revision 1.119 2007/01/25 14:02:30 fabiankeil
99 * - Add Proxy-Agent header to HTTP snippets that are
100 * supposed to reach HTTP clients only.
101 * - Made a few CONNECT log messages more descriptive.
102 * - Catch completely empty server responses (as seen
103 * with Tor's fake ".noconnect" top level domain).
104 * - Use shiny new "forwarding-failed" template for socks errors.
106 * Revision 1.118 2007/01/07 07:43:43 joergs
107 * AmigaOS4 support added.
109 * Revision 1.117 2006/12/31 17:56:37 fabiankeil
110 * Added config option accept-intercepted-requests
111 * and disabled it by default.
113 * Revision 1.116 2006/12/29 19:08:22 fabiankeil
114 * Reverted parts of my last commit
115 * to keep error handling working.
117 * Revision 1.115 2006/12/29 17:38:57 fabiankeil
118 * Fixed gcc43 conversion warnings.
120 * Revision 1.114 2006/12/27 18:52:02 fabiankeil
121 * Fix -pedantic ISO C warning about converting
122 * from function pointer to object pointer.
124 * Revision 1.113 2006/12/26 17:38:50 fabiankeil
125 * Silence compiler warning I introduced with my last commit.
127 * Revision 1.112 2006/12/26 17:31:41 fabiankeil
128 * Mutex protect rand() if POSIX threading
129 * is used, warn the user if that's not possible
130 * and stop using it on _WIN32 where it could
133 * Revision 1.111 2006/12/23 16:15:06 fabiankeil
134 * Don't prevent core dumps by catching SIGABRT.
135 * It's rude and makes debugging unreasonable painful.
137 * Revision 1.110 2006/12/13 14:52:53 etresoft
138 * Fix build failure on MacOS X. Global symbols can be either static or extern, but not both.
140 * Revision 1.109 2006/12/06 19:41:40 fabiankeil
141 * Privoxy is now able to run as intercepting
142 * proxy in combination with any packet filter
143 * that does the port redirection. The destination
144 * is extracted from the "Host:" header which
145 * should be available for nearly all requests.
147 * Moved HTTP snipplets into jcc.c.
148 * Added error message for gopher proxy requests.
150 * Revision 1.108 2006/11/28 15:38:51 fabiankeil
151 * Only unlink the pidfile if it's actually used.
153 * Change order of interception checks to make
154 * it possible to block or redirect requests for
157 * Revision 1.107 2006/11/13 19:05:51 fabiankeil
158 * Make pthread mutex locking more generic. Instead of
159 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
160 * and use mutex locking unless there is an _r function
161 * available. Better safe than sorry.
163 * Fixes "./configure --disable-pthread" and should result
164 * in less threading-related problems on pthread-using platforms,
165 * but it still doesn't fix BR#1122404.
167 * Revision 1.106 2006/11/06 19:58:23 fabiankeil
168 * Move pthread.h inclusion from jcc.c to jcc.h.
169 * Fixes build on x86-freebsd1 (FreeBSD 5.4-RELEASE).
171 * Revision 1.105 2006/11/06 14:26:02 fabiankeil
172 * Don't exit after receiving the second SIGHUP on Solaris.
174 * Fixes BR 1052235, but the same problem may exist on other
175 * systems. Once 3.0.6 is out we should use sigset()
176 * where available and see if it breaks anything.
178 * Revision 1.104 2006/09/23 13:26:38 roro
179 * Replace TABs by spaces in source code.
181 * Revision 1.103 2006/09/21 12:54:43 fabiankeil
182 * Fix +redirect{}. Didn't work with -fast-redirects.
184 * Revision 1.102 2006/09/06 13:03:04 fabiankeil
185 * Respond with 400 and a short text message
186 * if the client tries to use Privoxy as FTP proxy.
188 * Revision 1.101 2006/09/06 09:23:37 fabiankeil
189 * Make number of retries in case of forwarded-connect problems
190 * a config file option (forwarded-connect-retries) and use 0 as
193 * Revision 1.100 2006/09/03 19:42:59 fabiankeil
194 * Set random(3) seed.
196 * Revision 1.99 2006/09/02 15:36:42 fabiankeil
197 * Follow the OpenBSD port's lead and protect the resolve
198 * functions on OpenBSD as well.
200 * Revision 1.98 2006/08/24 11:01:34 fabiankeil
201 * --user fix. Only use the user as group if no group is specified.
202 * Solves BR 1492612. Thanks to Spinor S. and David Laight.
204 * Revision 1.97 2006/08/18 15:23:17 david__schmidt
205 * Windows service (re-)integration
209 * --install[:service_name]
210 * --uninstall[:service_name]
213 * They work as follows:
214 * --install will create a service for you and then terminate.
215 * By default the service name will be "privoxy" (without the quotes).
216 * However you can run multiple services if you wish, just by adding
217 * a colon and then a name (no spaces).
219 * --uninstall follows the exact same rules a --install.
221 * --service is used when the program is executed by the service
222 * control manager, and in normal circumstances would never be
223 * used as a command line argument.
225 * Revision 1.96 2006/08/15 20:12:36 david__schmidt
226 * Windows service integration
228 * Revision 1.95 2006/08/03 02:46:41 david__schmidt
229 * Incorporate Fabian Keil's patch work:
230 http://www.fabiankeil.de/sourcecode/privoxy/
232 * Revision 1.94 2006/07/18 14:48:46 david__schmidt
233 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
234 * with what was really the latest development (the v_3_0_branch branch)
236 * Revision 1.92.2.16 2005/04/03 20:10:50 david__schmidt
237 * Thanks to Jindrich Makovicka for a race condition fix for the log
238 * file. The race condition remains for non-pthread implementations.
239 * Reference patch #1175720.
241 * Revision 1.92.2.15 2004/10/03 12:53:32 david__schmidt
242 * Add the ability to check jpeg images for invalid
243 * lengths of comment blocks. Defensive strategy
244 * against the exploit:
245 * Microsoft Security Bulletin MS04-028
246 * Buffer Overrun in JPEG Processing (GDI+) Could
247 * Allow Code Execution (833987)
248 * Enabled with +inspect-jpegs in actions files.
250 * Revision 1.92.2.14 2003/12/12 12:52:53 oes
251 * - Fixed usage info for non-unix platforms
252 * - Fixed small cmdline parsing bug
254 * Revision 1.92.2.13 2003/11/27 19:20:27 oes
255 * Diagnostics: Now preserve the returncode of pthread_create
256 * in errno. Closes BR #775721. Thanks to Geoffrey Hausheer.
258 * Revision 1.92.2.12 2003/07/11 11:34:19 oes
259 * No longer ignore SIGCHLD. Fixes bug #769381
261 * Revision 1.92.2.11 2003/05/14 12:32:02 oes
262 * Close jarfile on graceful exit, remove stray line
264 * Revision 1.92.2.10 2003/05/08 15:13:46 oes
265 * Cosmetics: Killed a warning, a typo and an allocation left at exit
267 * Revision 1.92.2.9 2003/04/03 15:08:42 oes
268 * No longer rely on non-POSIX.1 extensions of getcwd().
271 * Revision 1.92.2.8 2003/03/31 13:12:32 oes
272 * Replaced setenv() by posix-compliant putenv()
273 * Thanks to Neil McCalden (nmcc AT users.sf.net).
275 * Revision 1.92.2.7 2003/03/17 16:48:59 oes
276 * Added chroot ability, thanks to patch by Sviatoslav Sviridov
278 * Revision 1.92.2.6 2003/03/11 11:55:00 oes
279 * Clean-up and extension of improvements for forked mode:
280 * - Child's return code now consists of flags RC_FLAG_*
281 * - Reporting toggle to parent now properly #ifdef'ed
282 * - Children now report blocking to parent. This enables
283 * statistics in forked mode
285 * Revision 1.92.2.5 2003/03/10 23:45:32 oes
286 * Fixed bug #700381: Non-Threaded version now capable of being toggled.
287 * Children now report having been toggled through _exit(17), parents
288 * watch for that code and toggle themselves if found.
290 * Revision 1.92.2.4 2003/03/07 03:41:04 david__schmidt
291 * Wrapping all *_r functions (the non-_r versions of them) with
292 * mutex semaphores for OSX. Hopefully this will take care of all
293 * of those pesky crash reports.
295 * Revision 1.92.2.3 2003/02/28 12:53:06 oes
296 * Fixed two mostly harmless mem leaks
298 * Revision 1.92.2.2 2002/11/20 14:37:47 oes
299 * Fix: Head of global clients list now initialized to NULL
301 * Revision 1.92.2.1 2002/09/25 14:52:24 oes
302 * Added basic support for OPTIONS and TRACE HTTP methods:
303 * - New interceptor direct_response() added in chat().
304 * - sed() moved to earlier in the process, so that the
305 * Host: header is evaluated before actions and forwarding
308 * Revision 1.92 2002/05/08 16:00:46 oes
309 * Chat's buffer handling:
310 * - Fixed bug with unchecked out-of-mem conditions
311 * while reading client request & server headers
312 * - No longer predict if the buffer limit will be exceeded
313 * in the next read -- check add_to_iob's new
314 * return code. If buffer couldn't be extended
315 * (policy or out-of-mem) while
316 * - reading from client: abort
317 * - reading server headers: send error page
318 * - buffering server body for filter: flush,
319 * and if that fails: send error page
321 * Revision 1.91 2002/04/08 20:35:58 swa
324 * Revision 1.90 2002/04/02 14:57:28 oes
325 * Made sending wafers independent of FEATURE_COOKIE_JAR
327 * Revision 1.89 2002/03/31 17:18:59 jongfoster
328 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
330 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
331 * More compiler warning message maintenance
333 * Revision 1.87 2002/03/26 22:29:54 swa
334 * we have a new homepage!
336 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
337 * Workaround for closing the jarfile before load_config() comes around again
339 * Revision 1.85 2002/03/24 15:23:33 jongfoster
342 * Revision 1.84 2002/03/24 13:25:43 swa
343 * name change related issues
345 * Revision 1.83 2002/03/16 23:54:06 jongfoster
346 * Adding graceful termination feature, to help look for memory leaks.
347 * If you enable this (which, by design, has to be done by hand
348 * editing config.h) and then go to http://i.j.b/die, then the program
349 * will exit cleanly after the *next* request. It should free all the
350 * memory that was used.
352 * Revision 1.82 2002/03/13 00:27:05 jongfoster
355 * Revision 1.81 2002/03/12 01:42:50 oes
356 * Introduced modular filters
358 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
359 * OS/2 port maintenance:
360 * - Fixed EMX build - it had decayed a little
361 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
362 * substituted a memset for now.
364 * Revision 1.79 2002/03/09 20:03:52 jongfoster
365 * - Making various functions return int rather than size_t.
366 * (Undoing a recent change). Since size_t is unsigned on
367 * Windows, functions like read_socket that return -1 on
368 * error cannot return a size_t.
370 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
371 * crashes, and also frequently caused JB to jump to 100%
372 * CPU and stay there. (Because it thought it had just
373 * read ((unsigned)-1) == 4Gb of data...)
375 * - The signature of write_socket has changed, it now simply
376 * returns success=0/failure=nonzero.
378 * - Trying to get rid of a few warnings --with-debug on
379 * Windows, I've introduced a new type "jb_socket". This is
380 * used for the socket file descriptors. On Windows, this
381 * is SOCKET (a typedef for unsigned). Everywhere else, it's
382 * an int. The error value can't be -1 any more, so it's
383 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
384 * Windows it maps to the #define INVALID_SOCKET.)
386 * - The signature of bind_port has changed.
388 * Revision 1.78 2002/03/08 21:35:04 oes
389 * Added optional group supplement to --user option. Will now use default group of user if no group given
391 * Revision 1.77 2002/03/07 03:52:06 oes
392 * - Fixed compiler warnings etc
393 * - Improved handling of failed DNS lookups
395 * Revision 1.76 2002/03/06 22:54:35 jongfoster
396 * Automated function-comment nitpicking.
398 * Revision 1.75 2002/03/06 10:02:19 oes
399 * Fixed stupid bug when --user was not given
401 * Revision 1.74 2002/03/06 00:49:31 jongfoster
402 * Fixing warning on Windows
403 * Making #ifdefs that refer to the same variable consistently
404 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
406 * Revision 1.73 2002/03/05 23:57:30 hal9
407 * Stray character 's' on line 1618 was breaking build.
409 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
410 * - Re-enable OS/2 building after new parms were added
411 * - Fix false out of memory report when resolving CGI templates when no IP
412 * address is available of failed attempt (a la no such domain)
414 * Revision 1.71 2002/03/05 18:13:56 oes
415 * Added --user option
417 * Revision 1.70 2002/03/05 04:52:42 oes
418 * Deleted non-errlog debugging code
420 * Revision 1.69 2002/03/04 23:50:00 jongfoster
421 * Splitting off bind_port() call into bind_port_helper(), with
424 * Revision 1.68 2002/03/04 20:17:32 oes
427 * Revision 1.67 2002/03/04 18:18:57 oes
428 * - Removed _DEBUG mode
429 * - Cleand up cmdline parsing
430 * - Introduced --no-daemon, --pidfile options
431 * - Cleaned up signal handling:
432 * - Terminate cleanly on INT, TERM and ABRT
433 * - Schedule logfile for re-opening on HUP
434 * - Ignore CHLD and PIPE
435 * - Leave the rest with their default handlers
436 * - Uniform handler registration
437 * - Added usage() function
438 * - Played styleguide police
440 * Revision 1.66 2002/03/03 15:06:55 oes
441 * Re-enabled automatic config reloading
443 * Revision 1.65 2002/03/03 14:49:11 oes
444 * Fixed CLF logging: Now uses client's original HTTP request
446 * Revision 1.64 2002/03/03 09:18:03 joergs
447 * Made jumbjuster work on AmigaOS again.
449 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
450 * Clean up a little CRLF unpleasantness that suddenly appeared
452 * Revision 1.62 2002/02/20 23:17:23 jongfoster
453 * Detecting some out-of memory conditions and exiting with a log message.
455 * Revision 1.61 2002/01/17 21:01:52 jongfoster
456 * Moving all our URL and URL pattern parsing code to urlmatch.c.
458 * Revision 1.60 2001/12/30 14:07:32 steudten
459 * - Add signal handling (unix)
460 * - Add SIGHUP handler (unix)
461 * - Add creation of pidfile (unix)
462 * - Add action 'top' in rc file (RH)
463 * - Add entry 'SIGNALS' to manpage
464 * - Add exit message to logfile (unix)
466 * Revision 1.59 2001/12/13 14:07:18 oes
467 * Fixed Bug: 503 error page now sent OK
469 * Revision 1.58 2001/11/30 23:37:24 jongfoster
470 * Renaming the Win32 config file to config.txt - this is almost the
471 * same as the corresponding UNIX name "config"
473 * Revision 1.57 2001/11/16 00:47:43 jongfoster
474 * Changing the tty-disconnection code to use setsid().
476 * Revision 1.56 2001/11/13 20:20:54 jongfoster
477 * Tabs->spaces, fixing a bug with missing {} around an if()
479 * Revision 1.55 2001/11/13 20:14:53 jongfoster
480 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
482 * Revision 1.54 2001/11/07 00:03:14 steudten
483 * Give reliable return value if an error
484 * occurs not just 0 with new daemon mode.
486 * Revision 1.53 2001/11/05 21:41:43 steudten
487 * Add changes to be a real daemon just for unix os.
488 * (change cwd to /, detach from controlling tty, set
489 * process group and session leader to the own process.
491 * Add some fatal-error log message for failed malloc().
492 * Add '-d' if compiled with 'configure --with-debug' to
493 * enable debug output.
495 * Revision 1.52 2001/10/26 20:11:20 jongfoster
496 * Fixing type mismatch
498 * Revision 1.51 2001/10/26 17:38:28 oes
501 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
502 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
503 * threads to call select() simultaneously. So, it's time to do a real, live,
504 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
505 * (native). Both versions will work, but using __OS2__ offers multi-threading.
507 * Revision 1.49 2001/10/23 21:41:35 jongfoster
508 * Added call to initialize the (statically-allocated of course)
509 * "out of memory" CGI response.
511 * Revision 1.48 2001/10/10 19:56:46 jongfoster
512 * Moving some code that wasn't cookie-related out of an #ifdef
515 * Revision 1.47 2001/10/10 16:44:36 oes
516 * Added CONNECT destination port limitation check
518 * Revision 1.46 2001/10/08 15:17:41 oes
519 * Re-enabled SSL forwarding
521 * Revision 1.45 2001/10/07 15:42:11 oes
522 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
524 * Moved downgrading of the HTTP version from parse_http_request to
525 * chat(), since we can't decide if it is necessary before we have
526 * determined the actions for the URL. The HTTP command is now
527 * *always* re-built so the repairs need no longer be special-cased.
529 * filter_popups now gets a csp pointer so it can raise the new
530 * CSP_FLAG_MODIFIED flag.
534 * Added configurable size limit for the IOB. If the IOB grows so
535 * large that the next read would exceed the limit, the header
536 * is generated, and the header & unfiltered buffer are flushed
537 * to the client. Chat then continues in non-buffering,
538 * non-filtering body mode.
540 * Revision 1.44 2001/10/02 18:13:57 oes
543 * Revision 1.43 2001/10/02 15:32:13 oes
544 * Moved generation of hdr
546 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
547 * Cleaning up 2 compiler warnings on OS/2.
549 * Revision 1.41 2001/09/16 17:05:14 jongfoster
550 * Removing unused #include showarg.h
552 * Revision 1.40 2001/09/16 15:41:45 jongfoster
553 * Fixing signed/unsigned comparison warning.
555 * Revision 1.39 2001/09/16 13:21:27 jongfoster
556 * Changes to use new list functions.
558 * Revision 1.38 2001/09/16 13:01:46 jongfoster
559 * Removing redundant function call that zeroed zalloc()'d memory.
561 * Revision 1.37 2001/09/10 11:12:24 oes
562 * Deleted unused variable
564 * Revision 1.36 2001/09/10 10:56:15 oes
565 * Silenced compiler warnings
567 * Revision 1.35 2001/07/31 14:44:22 oes
568 * Deleted unused size parameter from filter_popups()
570 * Revision 1.34 2001/07/30 22:08:36 jongfoster
571 * Tidying up #defines:
572 * - All feature #defines are now of the form FEATURE_xxx
573 * - Permanently turned off WIN_GUI_EDIT
574 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
576 * Revision 1.33 2001/07/29 19:32:00 jongfoster
577 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
579 * Revision 1.32 2001/07/29 18:47:05 jongfoster
580 * Adding missing #include "loadcfg.h"
582 * Revision 1.31 2001/07/29 12:17:48 oes
583 * Applied pthread fix by Paul Lieverse
585 * Revision 1.30 2001/07/25 22:57:13 jongfoster
586 * __BEOS__ no longer overrides FEATURE_PTHREAD.
587 * This is because FEATURE_PTHREAD will soon be widely used, so I
588 * want to keep it simple.
590 * Revision 1.29 2001/07/24 12:47:06 oes
591 * Applied BeOS support update by Eugenia
593 * Revision 1.28 2001/07/23 13:26:12 oes
594 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
596 * Revision 1.27 2001/07/19 19:09:47 haroon
597 * - Added code to take care of the situation where while processing the first
598 * server response (which includes the server header), after finding the end
599 * of the headers we were not looking past the end of the headers for
600 * content modification. I enabled it for filter_popups.
601 * Someone else should look to see if other similar operations should be
602 * done to the discarded portion of the buffer.
604 * Note 2001/07/20: No, the other content modification mechanisms will process
605 * the whole iob later anyway. --oes
607 * Revision 1.26 2001/07/18 12:31:36 oes
610 * Revision 1.25 2001/07/15 19:43:49 jongfoster
611 * Supports POSIX threads.
612 * Also removed some unused #includes.
614 * Revision 1.24 2001/07/13 14:00:40 oes
615 * - Generic content modification scheme:
616 * Each feature has its own applicability flag that is set
617 * from csp->action->flags.
618 * Replaced the "filtering" int flag , by a function pointer
619 * "content_filter" to the function that will do the content
620 * modification. If it is != NULL, the document will be buffered
621 * and processed through *content_filter, which must set
622 * csp->content_length and return a modified copy of the body
623 * or return NULL (on failiure).
624 * - Changed csp->is_text to the more generic bitmap csp->content_type
625 * which can currently take the valued CT_TEXT or CT_GIF
627 * - Removed all #ifdef PCRS
629 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
630 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
631 * the `block_acl' call. This prevents a compilation error when the user
632 * does not wish to use the "ACL" feature.
634 * Revision 1.22 2001/06/29 21:45:41 oes
635 * Indentation, CRLF->LF, Tab-> Space
637 * Revision 1.21 2001/06/29 13:29:36 oes
638 * - Cleaned up, improved comments
639 * - Unified all possible interceptors (CGI,
640 * block, trust, fast_redirect) in one
641 * place, with one (CGI) answer generation
642 * mechansim. Much clearer now.
643 * - Removed the GIF image generation, which
644 * is now done in filters.c:block_url()
645 * - Made error conditions like domain lookup
646 * failiure or (various) problems while talking
647 * to the server use cgi.c:error_response()
648 * instead of generating HTML/HTTP in chat() (yuck!)
649 * - Removed logentry from cancelled commit
651 * Revision 1.20 2001/06/09 10:55:28 jongfoster
652 * Changing BUFSIZ ==> BUFFER_SIZE
654 * Revision 1.19 2001/06/07 23:12:52 jongfoster
655 * Replacing function pointer in struct gateway with a directly
656 * called function forwarded_connect().
657 * Replacing struct gateway with struct forward_spec
659 * Revision 1.18 2001/06/03 19:12:16 oes
660 * introduced new cgi handling
662 * Revision 1.17 2001/06/01 20:07:23 jongfoster
663 * Now uses action +image-blocker{} rather than config->tinygif
665 * Revision 1.16 2001/06/01 18:49:17 jongfoster
666 * Replaced "list_share" with "list" - the tiny memory gain was not
667 * worth the extra complexity.
669 * Revision 1.15 2001/05/31 21:24:47 jongfoster
670 * Changed "permission" to "action" throughout.
671 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
672 * Moved vanilla wafer check into chat(), since we must now
673 * decide whether or not to add it based on the URL.
675 * Revision 1.14 2001/05/29 20:14:01 joergs
676 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
679 * Revision 1.13 2001/05/29 09:50:24 jongfoster
680 * Unified blocklist/imagelist/permissionslist.
681 * File format is still under discussion, but the internal changes
684 * Also modified interceptor behaviour:
685 * - We now intercept all URLs beginning with one of the following
686 * prefixes (and *only* these prefixes):
688 * * http://ijbswa.sf.net/config/
689 * * http://ijbswa.sourceforge.net/config/
690 * - New interceptors "home page" - go to http://i.j.b/ to see it.
691 * - Internal changes so that intercepted and fast redirect pages
692 * are not replaced with an image.
693 * - Interceptors now have the option to send a binary page direct
694 * to the client. (i.e. ijb-send-banner uses this)
695 * - Implemented show-url-info interceptor. (Which is why I needed
696 * the above interceptors changes - a typical URL is
697 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
698 * The previous mechanism would not have intercepted that, and
699 * if it had been intercepted then it then it would have replaced
702 * Revision 1.12 2001/05/27 22:17:04 oes
704 * - re_process_buffer no longer writes the modified buffer
705 * to the client, which was very ugly. It now returns the
706 * buffer, which it is then written by chat.
708 * - content_length now adjusts the Content-Length: header
709 * for modified documents rather than crunch()ing it.
710 * (Length info in csp->content_length, which is 0 for
711 * unmodified documents)
713 * - For this to work, sed() is called twice when filtering.
715 * Revision 1.11 2001/05/26 17:27:53 jongfoster
716 * Added support for CLF and fixed LOG_LEVEL_LOG.
717 * Also did CRLF->LF fix of my previous patch.
719 * Revision 1.10 2001/05/26 15:26:15 jongfoster
720 * ACL feature now provides more security by immediately dropping
721 * connections from untrusted hosts.
723 * Revision 1.9 2001/05/26 00:28:36 jongfoster
724 * Automatic reloading of config file.
725 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
726 * Most of the global variables have been moved to a new
727 * struct configuration_spec, accessed through csp->config->globalname
728 * Most of the globals remaining are used by the Win32 GUI.
730 * Revision 1.8 2001/05/25 22:43:18 jongfoster
731 * Fixing minor memory leak and buffer overflow.
733 * Revision 1.7 2001/05/25 22:34:30 jongfoster
736 * Revision 1.6 2001/05/23 00:13:58 joergs
737 * AmigaOS support fixed.
739 * Revision 1.5 2001/05/22 18:46:04 oes
741 * - Enabled filtering banners by size rather than URL
742 * by adding patterns that replace all standard banner
743 * sizes with the "Junkbuster" gif to the re_filterfile
745 * - Enabled filtering WebBugs by providing a pattern
746 * which kills all 1x1 images
748 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
749 * which is selected by the (nonstandard and therefore
750 * capital) letter 'U' in the option string.
751 * It causes the quantifiers to be ungreedy by default.
752 * Appending a ? turns back to greedy (!).
754 * - Added a new interceptor ijb-send-banner, which
755 * sends back the "Junkbuster" gif. Without imagelist or
756 * MSIE detection support, or if tinygif = 1, or the
757 * URL isn't recognized as an imageurl, a lame HTML
758 * explanation is sent instead.
760 * - Added new feature, which permits blocking remote
761 * script redirects and firing back a local redirect
763 * The feature is conditionally compiled, i.e. it
764 * can be disabled with --disable-fast-redirects,
765 * plus it must be activated by a "fast-redirects"
766 * line in the config file, has its own log level
767 * and of course wants to be displayed by show-proxy-args
768 * Note: Boy, all the #ifdefs in 1001 locations and
769 * all the fumbling with configure.in and acconfig.h
770 * were *way* more work than the feature itself :-(
772 * - Because a generic redirect template was needed for
773 * this, tinygif = 3 now uses the same.
775 * - Moved GIFs, and other static HTTP response templates
780 * - Removed some >400 CRs again (Jon, you really worked
783 * Revision 1.4 2001/05/21 19:34:01 jongfoster
784 * Made failure to bind() a fatal error.
786 * Revision 1.3 2001/05/20 01:21:20 jongfoster
787 * Version 2.9.4 checkin.
788 * - Merged popupfile and cookiefile, and added control over PCRS
789 * filtering, in new "permissionsfile".
790 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
791 * file error you now get a message box (in the Win32 GUI) rather
792 * than the program exiting with no explanation.
793 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
795 * - Removed tabs from "config"
796 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
797 * - Bumped up version number.
799 * Revision 1.2 2001/05/17 22:34:44 oes
800 * - Added hint on GIF char array generation to jcc.c
801 * - Cleaned CRLF's from the sources and related files
802 * - Repaired logging for REF and FRC
804 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
805 * Initial import of version 2.9.3 source tree
808 *********************************************************************/
814 #include <sys/types.h>
823 # ifndef FEATURE_PTHREAD
827 # include <windows.h>
828 # include <process.h>
829 # endif /* ndef FEATURE_PTHREAD */
832 # ifndef _WIN_CONSOLE
834 # endif /* ndef _WIN_CONSOLE */
835 # include "w32svrapi.h"
837 #else /* ifndef _WIN32 */
839 # if !defined (__OS2__)
841 # include <sys/wait.h>
842 # endif /* ndef __OS2__ */
843 # include <sys/time.h>
844 # include <sys/stat.h>
845 # include <sys/ioctl.h>
848 #include <sys/termios.h>
859 # include <socket.h> /* BeOS has select() for sockets only. */
860 # include <OS.h> /* declarations for threads and stuff. */
863 # if defined(__EMX__) || defined(__OS2__)
864 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
869 #define bzero(B,N) memset(B,0x00,n)
884 #include "killpopup.h"
885 #include "miscutil.h"
887 #include "jbsockets.h"
892 #include "urlmatch.h"
894 const char jcc_h_rcs[] = JCC_H_VERSION;
895 const char project_h_rcs[] = PROJECT_H_VERSION;
898 struct client_state clients[1];
899 struct file_list files[1];
901 #ifdef FEATURE_STATISTICS
902 int urls_read = 0; /* total nr of urls read inc rejected */
903 int urls_rejected = 0; /* total nr of urls rejected */
904 #endif /* def FEATURE_STATISTICS */
906 #ifdef FEATURE_GRACEFUL_TERMINATION
910 static void listen_loop(void);
911 static void chat(struct client_state *csp);
913 void serve(struct client_state *csp);
914 #else /* ifndef AMIGA */
915 static void serve(struct client_state *csp);
916 #endif /* def AMIGA */
919 static int32 server_thread(void *data);
920 #endif /* def __BEOS__ */
923 #define sleep(N) Sleep(((N) * 1000))
927 #define sleep(N) DosSleep(((N) * 100))
930 #ifdef FEATURE_PTHREAD
931 pthread_mutex_t log_mutex;
932 pthread_mutex_t log_init_mutex;
934 #ifndef HAVE_GMTIME_R
935 pthread_mutex_t gmtime_mutex;
936 #endif /* ndef HAVE_GMTIME_R */
938 #ifndef HAVE_LOCALTIME_R
939 pthread_mutex_t localtime_mutex;
940 #endif /* ndef HAVE_GMTIME_R */
942 #ifndef HAVE_GETHOSTBYADDR_R
943 pthread_mutex_t gethostbyaddr_mutex;
944 #endif /* ndef HAVE_GETHOSTBYADDR_R */
946 #ifndef HAVE_GETHOSTBYNAME_R
947 pthread_mutex_t gethostbyname_mutex;
948 #endif /* ndef HAVE_GETHOSTBYNAME_R */
951 pthread_mutex_t rand_mutex;
952 #endif /* ndef HAVE_RANDOM */
954 #endif /* FEATURE_PTHREAD */
956 #if defined(unix) || defined(__EMX__)
957 const char *basedir = NULL;
958 const char *pidfile = NULL;
959 int received_hup_signal = 0;
960 #endif /* defined unix */
962 /* The vanilla wafer. */
963 static const char VANILLA_WAFER[] =
964 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
965 "Do_not_send_me_any_copyrighted_information_other_than_the_"
966 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
967 "In_particular_do_not_send_me_any_cookies_that_"
968 "are_subject_to_a_claim_of_copyright_by_anybody._"
969 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
970 "(copyright_or_otherwise)_applying_to_any_cookie._";
972 /* HTTP snipplets. */
973 const static char CSUCCEED[] =
974 "HTTP/1.0 200 Connection established\n"
975 "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
977 const static char CHEADER[] =
978 "HTTP/1.0 400 Invalid header received from browser\r\n"
979 "Proxy-Agent: Privoxy " VERSION "\r\n"
980 "Content-Type: text/plain\r\n"
981 "Connection: close\r\n\r\n"
982 "Invalid header received from browser.\r\n";
984 const static char CFORBIDDEN[] =
985 "HTTP/1.0 403 Connection not allowable\r\n"
986 "Proxy-Agent: Privoxy " VERSION "\r\n"
987 "X-Hint: If you read this message interactively, then you know why this happens ,-)\r\n"
988 "Connection: close\r\n\r\n";
990 const static char FTP_RESPONSE[] =
991 "HTTP/1.0 400 Invalid request received from browser\r\n"
992 "Content-Type: text/plain\r\n"
993 "Connection: close\r\n\r\n"
994 "Invalid request. Privoxy doesn't support FTP.\r\n";
996 const static char GOPHER_RESPONSE[] =
997 "HTTP/1.0 400 Invalid request received from browser\r\n"
998 "Content-Type: text/plain\r\n"
999 "Connection: close\r\n\r\n"
1000 "Invalid request. Privoxy doesn't support gopher.\r\n";
1002 /* XXX: should be a template */
1003 const static char MISSING_DESTINATION_RESPONSE[] =
1004 "HTTP/1.0 400 Bad request received from browser\r\n"
1005 "Proxy-Agent: Privoxy " VERSION "\r\n"
1006 "Content-Type: text/plain\r\n"
1007 "Connection: close\r\n\r\n"
1008 "Bad request. Privoxy was unable to extract the destination.\r\n";
1010 /* XXX: should be a template */
1011 const static char NO_SERVER_DATA_RESPONSE[] =
1012 "HTTP/1.0 502 Server or forwarder response empty\r\n"
1013 "Proxy-Agent: Privoxy " VERSION "\r\n"
1014 "Content-Type: text/plain\r\n"
1015 "Connection: close\r\n\r\n"
1016 "Empty server or forwarder response.\r\n"
1017 "The connection was closed without sending any data.\r\n";
1019 /* XXX: should be a template */
1020 const static char NULL_BYTE_RESPONSE[] =
1021 "HTTP/1.0 400 Bad request received from browser\r\n"
1022 "Proxy-Agent: Privoxy " VERSION "\r\n"
1023 "Content-Type: text/plain\r\n"
1024 "Connection: close\r\n\r\n"
1025 "Bad request. Null byte(s) before end of request.\r\n";
1027 /* A function to crunch a response */
1028 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
1030 /* Crunch function flags */
1031 #define CF_NO_FLAGS 0
1032 /* Cruncher applies to forced requests as well */
1033 #define CF_IGNORE_FORCE 1
1034 /* Crunched requests are counted for the block statistics */
1035 #define CF_COUNT_AS_REJECT 2
1037 /* A crunch function and its flags */
1040 const crunch_func_ptr cruncher;
1044 /* Complete list of cruncher functions */
1045 const static struct cruncher crunchers_all[] = {
1046 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
1047 { block_url, CF_COUNT_AS_REJECT },
1048 #ifdef FEATURE_TRUST
1049 { trust_url, CF_COUNT_AS_REJECT },
1050 #endif /* def FEATURE_TRUST */
1051 { redirect_url, CF_NO_FLAGS },
1052 { dispatch_cgi, CF_IGNORE_FORCE},
1056 /* Light version, used after tags are applied */
1057 const static struct cruncher crunchers_light[] = {
1058 { block_url, CF_COUNT_AS_REJECT },
1059 { redirect_url, CF_NO_FLAGS },
1064 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1065 /*********************************************************************
1067 * Function : sig_handler
1069 * Description : Signal handler for different signals.
1070 * Exit gracefully on TERM and INT
1071 * or set a flag that will cause the errlog
1072 * to be reopened by the main thread on HUP.
1075 * 1 : the_signal = the signal cause this function to call
1079 *********************************************************************/
1080 static void sig_handler(int the_signal)
1086 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
1097 received_hup_signal = 1;
1102 * We shouldn't be here, unless we catch signals
1103 * in main() that we can't handle here!
1105 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
1113 /*********************************************************************
1115 * Function : client_protocol_is_unsupported
1117 * Description : Checks if the client used a known unsupported
1118 * protocol and deals with it by sending an error
1122 * 1 : csp = Current client state (buffers, headers, etc...)
1123 * 2 : req = the first request line send by the client
1125 * Returns : TRUE if an error response has been generated, or
1126 * FALSE if the request doesn't look invalid.
1128 *********************************************************************/
1129 int client_protocol_is_unsupported(const struct client_state *csp, char *req)
1131 char buf[BUFFER_SIZE];
1134 * If it's a FTP or gopher request, we don't support it.
1136 * These checks are better than nothing, but they might
1137 * not work in all configurations and some clients might
1138 * have problems digesting the answer.
1140 * They should, however, never cause more problems than
1141 * Privoxy's old behaviour (returning the misleading HTML
1144 * "Could not resolve http://(ftp|gopher)://example.org").
1146 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
1148 if (!strncmpic(req, "GET ftp://", 10))
1150 strlcpy(buf, FTP_RESPONSE, sizeof(buf));
1151 log_error(LOG_LEVEL_ERROR, "%s tried to use Privoxy as FTP proxy: %s",
1152 csp->ip_addr_str, req);
1156 strlcpy(buf, GOPHER_RESPONSE, sizeof(buf));
1157 log_error(LOG_LEVEL_ERROR, "%s tried to use Privoxy as gopher proxy: %s",
1158 csp->ip_addr_str, req);
1160 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
1162 write_socket(csp->cfd, buf, strlen(buf));
1171 /*********************************************************************
1173 * Function : get_request_destination_elsewhere
1175 * Description : If the client's request was redirected into
1176 * Privoxy without the client's knowledge,
1177 * the request line lacks the destination host.
1179 * This function tries to get it elsewhere,
1180 * provided accept-intercepted-requests is enabled.
1182 * "Elsewhere" currently only means "Host: header",
1183 * but in the future we may ask the redirecting
1184 * packet filter to look the destination up.
1186 * If the destination stays unknown, an error
1187 * response is send to the client and headers
1188 * are freed so that chat() can return directly.
1191 * 1 : csp = Current client state (buffers, headers, etc...)
1192 * 2 : headers = a header list
1194 * Returns : JB_ERR_OK if the destination is now known, or
1195 * JB_ERR_PARSE if it isn't.
1197 *********************************************************************/
1198 jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
1202 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
1204 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
1205 " Privoxy isn't configured to accept intercepted requests.",
1206 csp->ip_addr_str, csp->http->cmd);
1207 /* XXX: Use correct size */
1208 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1209 csp->ip_addr_str, csp->http->cmd);
1211 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1212 destroy_list(headers);
1214 return JB_ERR_PARSE;
1216 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
1218 /* Split the domain we just got for pattern matching */
1219 init_domain_components(csp->http);
1225 /* We can't work without destination. Go spread the news.*/
1227 req = list_to_text(headers);
1229 /* XXX: Use correct size */
1230 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1231 csp->ip_addr_str, csp->http->cmd);
1232 log_error(LOG_LEVEL_ERROR,
1233 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
1234 csp->ip_addr_str, csp->http->cmd, req);
1237 write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
1238 destroy_list(headers);
1240 return JB_ERR_PARSE;
1243 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
1244 * to get the destination IP address, use it as host directly
1245 * or do a reverse DNS lookup first.
1250 /*********************************************************************
1252 * Function : get_server_headers
1254 * Description : Parses server headers in iob and fills them
1255 * into csp->headers so that they can later be
1259 * 1 : csp = Current client state (buffers, headers, etc...)
1261 * Returns : JB_ERR_OK if everything went fine, or
1262 * JB_ERR_PARSE if the headers were incomplete.
1264 *********************************************************************/
1265 jb_err get_server_headers(struct client_state *csp)
1267 int continue_hack_in_da_house = 0;
1270 while (((header = get_header(csp)) != NULL) || continue_hack_in_da_house)
1275 * continue hack in da house. Ignore the ending of
1276 * this head and continue enlisting header lines.
1277 * The reason is described below.
1279 enlist(csp->headers, "");
1280 continue_hack_in_da_house = 0;
1283 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
1286 * It's a bodyless continue response, don't
1287 * stop header parsing after reaching it's end.
1289 * As a result Privoxy will concatenate the
1290 * next response's head and parse and deliver
1291 * the headers as if they belonged to one request.
1293 * The client will separate them because of the
1294 * empty line between them.
1296 * XXX: What we're doing here is clearly against
1297 * the intended purpose of the continue header,
1298 * and under some conditions (HTTP/1.0 client request)
1299 * it's a standard violation.
1301 * Anyway, "sort of against the spec" is preferable
1302 * to "always getting confused by Continue responses"
1303 * (Privoxy's behaviour before this hack was added)
1305 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
1306 continue_hack_in_da_house = 1;
1308 else if (*header == '\0')
1311 * If the header is empty, but the Continue hack
1312 * isn't active, we can assume that we reached the
1313 * end of the buffer before we hit the end of the
1316 * Inform the caller an let it decide how to handle it.
1318 return JB_ERR_PARSE;
1322 if (JB_ERR_MEMORY == enlist(csp->headers, header))
1325 * XXX: Should we quit the request and return a
1326 * out of memory error page instead?
1328 log_error(LOG_LEVEL_ERROR,
1329 "Out of memory while enlisting server headers. %s lost.",
1339 /*********************************************************************
1341 * Function : crunch_reason
1343 * Description : Translates the crunch reason code into a string.
1346 * 1 : rsp = a http_response
1348 * Returns : A string with the crunch reason or an error description.
1350 *********************************************************************/
1351 const char *crunch_reason(const struct http_response *rsp)
1353 char * reason = NULL;
1355 assert(rsp != NULL);
1358 return "Internal error while searching for crunch reason";
1361 switch (rsp->reason)
1363 case RSP_REASON_UNSUPPORTED:
1364 reason = "Unsupported HTTP feature";
1366 case RSP_REASON_BLOCKED:
1369 case RSP_REASON_UNTRUSTED:
1370 reason = "Untrusted";
1372 case RSP_REASON_REDIRECTED:
1373 reason = "Redirected";
1375 case RSP_REASON_CGI_CALL:
1376 reason = "CGI Call";
1378 case RSP_REASON_NO_SUCH_DOMAIN:
1379 reason = "DNS failure";
1381 case RSP_REASON_FORWARDING_FAILED:
1382 reason = "Forwarding failed";
1384 case RSP_REASON_CONNECT_FAILED:
1385 reason = "Connection failure";
1387 case RSP_REASON_OUT_OF_MEMORY:
1388 reason = "Out of memory (may mask other reasons)";
1391 reason = "No reason recorded";
1399 /*********************************************************************
1401 * Function : send_crunch_response
1403 * Description : Delivers already prepared response for
1404 * intercepted requests, logs the interception
1405 * and frees the response.
1408 * 1 : csp = Current client state (buffers, headers, etc...)
1409 * 1 : rsp = Fully prepared response. Will be freed on exit.
1411 * Returns : Nothing.
1413 *********************************************************************/
1414 void send_crunch_response(struct client_state *csp, struct http_response *rsp)
1416 const struct http_request *http = csp->http;
1417 char status_code[4];
1419 assert(rsp != NULL);
1420 assert(rsp->head != NULL);
1425 * Not supposed to happen. If it does
1426 * anyway, treat it as an unknown error.
1428 cgi_error_unknown(csp, rsp, RSP_REASON_INTERNAL_ERROR);
1429 /* return code doesn't matter */
1434 /* If rsp is still NULL, we have serious internal problems. */
1435 log_error(LOG_LEVEL_FATAL,
1436 "NULL response in send_crunch_response and cgi_error_unknown failed as well.");
1440 * Extract the status code from the actual head
1441 * that was send to the client. It is the only
1442 * way to get it right for all requests, including
1443 * the fixed ones for out-of-memory problems.
1445 * A head starts like this: 'HTTP/1.1 200...'
1449 status_code[0] = rsp->head[9];
1450 status_code[1] = rsp->head[10];
1451 status_code[2] = rsp->head[11];
1452 status_code[3] = '\0';
1454 /* Write the answer to the client */
1455 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1456 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1458 /* There is nothing we can do about it. */
1459 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", csp->http->host);
1462 /* Log that the request was crunched and why. */
1463 log_error(LOG_LEVEL_GPC, "%s%s crunch! (%s)",
1464 http->hostport, http->path, crunch_reason(rsp));
1465 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %d",
1466 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
1468 /* Clean up and return */
1469 if (cgi_error_memory() != rsp)
1471 free_http_response(rsp);
1477 /*********************************************************************
1479 * Function : request_contains_null_bytes
1481 * Description : Checks for NULL bytes in the request and sends
1482 * an error message to the client if any were found.
1485 * 1 : csp = Current client state (buffers, headers, etc...)
1486 * 2 : buf = Data from the client's request to check.
1487 * 3 : len = The data length.
1489 * Returns : TRUE if the request contained one or more NULL bytes, or
1492 *********************************************************************/
1493 int request_contains_null_bytes(const struct client_state *csp, char *buf, int len)
1495 size_t c_len; /* Request lenght when treated as C string */
1497 c_len = strlen(buf);
1502 * Null byte(s) found. Log the request,
1503 * return an error response and hang up.
1505 size_t tmp_len = c_len;
1510 * Replace NULL byte(s) with '°' characters
1511 * so the request can be logged as string.
1512 * XXX: Is there a better replacement character?
1515 tmp_len += strlen(buf+tmp_len);
1516 } while (tmp_len < len);
1518 log_error(LOG_LEVEL_ERROR, "%s\'s request contains at least one NULL byte "
1519 "(length=%d, strlen=%d).", csp->ip_addr_str, len, c_len);
1520 log_error(LOG_LEVEL_HEADER,
1521 "Offending request data with NULL bytes turned into \'°\' characters: %s", buf);
1523 write_socket(csp->cfd, NULL_BYTE_RESPONSE, strlen(NULL_BYTE_RESPONSE));
1525 /* XXX: Log correct size */
1526 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1535 /*********************************************************************
1537 * Function : crunch_response_triggered
1539 * Description : Checks if the request has to be crunched,
1540 * and delivers the crunch response if necessary.
1543 * 1 : csp = Current client state (buffers, headers, etc...)
1544 * 2 : crunchers = list of cruncher functions to run
1546 * Returns : TRUE if the request was answered with a crunch response
1549 *********************************************************************/
1550 int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
1552 struct http_response *rsp = NULL;
1553 const struct cruncher *c;
1555 for (c = crunchers; c->cruncher != NULL; c++)
1558 * Check the cruncher if either Privoxy is toggled
1559 * on and the request isn't forced, or if the cruncher
1560 * applies to forced requests as well.
1562 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
1563 !(csp->flags & CSP_FLAG_FORCED)) ||
1564 (c->flags & CF_IGNORE_FORCE))
1566 rsp = c->cruncher(csp);
1569 /* Deliver, log and free the interception response. */
1570 send_crunch_response(csp, rsp);
1571 #ifdef FEATURE_STATISTICS
1572 if (c->flags & CF_COUNT_AS_REJECT)
1574 csp->flags |= CSP_FLAG_REJECTED;
1576 #endif /* def FEATURE_STATISTICS */
1587 /*********************************************************************
1589 * Function : build_request_line
1591 * Description : Builds the HTTP request line.
1593 * If a HTTP forwarder is used it expects the whole URL,
1594 * web servers only get the path.
1597 * 1 : csp = Current client state (buffers, headers, etc...)
1598 * 2 : fwd = The forwarding spec used for the request
1600 * Returns : Nothing. Terminates in case of memory problems.
1602 *********************************************************************/
1603 void build_request_line(struct client_state *csp, const struct forward_spec *fwd)
1605 struct http_request *http = csp->http;
1607 assert(http->ssl == 0);
1610 * Downgrade http version from 1.1 to 1.0
1611 * if +downgrade action applies.
1613 if ( (csp->action->flags & ACTION_DOWNGRADE)
1614 && (!strcmpic(http->ver, "HTTP/1.1")))
1617 http->ver = strdup("HTTP/1.0");
1619 if (http->ver == NULL)
1621 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
1626 * Rebuild the request line.
1627 * XXX: If a http forwarder is used and the HTTP version
1628 * wasn't downgraded, we don't have to rebuild anything.
1632 http->cmd = strdup(http->gpc);
1633 string_append(&http->cmd, " ");
1635 if (fwd->forward_host)
1637 string_append(&http->cmd, http->url);
1641 string_append(&http->cmd, http->path);
1643 string_append(&http->cmd, " ");
1644 string_append(&http->cmd, http->ver);
1646 if (http->cmd == NULL)
1648 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1650 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", http->cmd);
1654 /*********************************************************************
1658 * Description : Once a connection to the client has been accepted,
1659 * this function is called (via serve()) to handle the
1660 * main business of the communication. When this
1661 * function returns, the caller must close the client
1664 * FIXME: chat is nearly thousand lines long.
1668 * 1 : csp = Current client state (buffers, headers, etc...)
1670 * Returns : Nothing.
1672 *********************************************************************/
1673 static void chat(struct client_state *csp)
1675 char buf[BUFFER_SIZE];
1683 int ms_iis5_hack = 0;
1684 size_t byte_count = 0;
1685 int forwarded_connect_retries = 0;
1686 int max_forwarded_connect_retries = csp->config->forwarded_connect_retries;
1687 const struct forward_spec * fwd;
1688 struct http_request *http;
1689 int len; /* for buffer sizes (and negative error codes) */
1690 #ifdef FEATURE_KILL_POPUPS
1691 int block_popups; /* bool, 1==will block popups */
1692 int block_popups_now = 0; /* bool, 1==currently blocking popups */
1693 #endif /* def FEATURE_KILL_POPUPS */
1695 int pcrs_filter; /* bool, 1==will filter through pcrs */
1696 int gif_deanimate; /* bool, 1==will deanimate gifs */
1697 int jpeg_inspect; /* bool, 1==will inspect jpegs */
1699 /* Function that does the content filtering for the current request */
1700 char *(*content_filter)() = NULL;
1702 /* Skeleton for HTTP response, if we should intercept the request */
1703 struct http_response *rsp;
1705 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1706 struct list header_list;
1707 struct list *headers = &header_list;
1711 memset(buf, 0, sizeof(buf));
1714 * Read the client's request. Note that since we're not using select() we
1715 * could get blocked here if a client connected, then didn't say anything!
1720 len = read_socket(csp->cfd, buf, sizeof(buf)-1);
1722 if (len <= 0) break; /* error! */
1724 if (request_contains_null_bytes(csp, buf, len))
1726 /* NULL bytes found and dealt with, just hang up. */
1731 * If there is no memory left for buffering the
1732 * request, there is nothing we can do but hang up
1734 if (add_to_iob(csp, buf, len))
1739 req = get_header(csp);
1743 break; /* no HTTP request! */
1748 continue; /* more to come! */
1751 /* Does the request line look invalid? */
1752 if (client_protocol_is_unsupported(csp, req))
1755 * Yes. The request has already been
1756 * answered with a error response, the buffers
1757 * were freed and we're done with chatting.
1762 #ifdef FEATURE_FORCE_LOAD
1764 * If this request contains the FORCE_PREFIX and blocks
1765 * aren't enforced, get rid of it and set the force flag.
1767 if (strstr(req, FORCE_PREFIX))
1769 if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1771 log_error(LOG_LEVEL_FORCE,
1772 "Ignored force prefix in request: \"%s\".", req);
1776 strclean(req, FORCE_PREFIX);
1777 log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
1778 csp->flags |= CSP_FLAG_FORCED;
1782 #endif /* def FEATURE_FORCE_LOAD */
1784 switch( parse_http_request(req, http, csp) )
1787 log_error(LOG_LEVEL_ERROR, "Out of memory while parsing request.");
1790 log_error(LOG_LEVEL_ERROR, "Couldn't parse request: %s.", req);
1798 if (http->cmd == NULL)
1800 write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1801 /* XXX: Use correct size */
1802 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1803 log_error(LOG_LEVEL_ERROR, "Invalid header received from %s.", csp->ip_addr_str);
1805 free_http_request(http);
1809 /* grab the rest of the client's headers */
1813 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
1815 len = read_socket(csp->cfd, buf, sizeof(buf));
1818 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1823 * If there is no memory left for buffering the
1824 * request, there is nothing we can do but hang up
1826 if (add_to_iob(csp, buf, len))
1833 if (p == NULL) break;
1840 if (http->host == NULL)
1843 * If we still don't know the request destination,
1844 * the request is invalid or the client uses
1845 * Privoxy without its knowledge.
1847 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1850 * Our attempts to get the request destination
1851 * elsewhere failed or Privoxy is configured
1852 * to only accept proxy requests.
1854 * An error response has already been send
1855 * and we're done here.
1861 /* decide how to route the HTTP request */
1863 if ((fwd = forward_url(http, csp)) == NULL)
1865 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
1866 /* Never get here - LOG_LEVEL_FATAL causes program exit */
1869 /* build the http request to send to the server
1870 * we have to do one of the following:
1872 * create = use the original HTTP request to create a new
1873 * HTTP request that has either the path component
1874 * without the http://domainspec (w/path) or the
1875 * full orininal URL (w/url)
1876 * Note that the path and/or the HTTP version may
1877 * have been altered by now.
1879 * connect = Open a socket to the host:port of the server
1880 * and short-circuit server and client socket.
1882 * pass = Pass the request unchanged if forwarding a CONNECT
1883 * request to a parent proxy. Note that we'll be sending
1884 * the CFAIL message ourselves if connecting to the parent
1885 * fails, but we won't send a CSUCCEED message if it works,
1886 * since that would result in a double message (ours and the
1887 * parent's). After sending the request to the parent, we simply
1890 * here's the matrix:
1893 * +--------+--------+
1895 * 0 | create | connect|
1897 * Forwarding +--------+--------+
1899 * 1 | create | pass |
1901 * +--------+--------+
1906 * Determine the actions for this URL
1908 #ifdef FEATURE_TOGGLE
1909 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1911 /* Most compatible set of actions (i.e. none) */
1912 init_current_action(csp->action);
1915 #endif /* ndef FEATURE_TOGGLE */
1917 url_actions(http, csp);
1922 * Check if a CONNECT request is allowable:
1923 * In the absence of a +limit-connect action, allow only port 443.
1924 * If there is an action, allow whatever matches the specificaton.
1928 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
1929 || (csp->action->flags & ACTION_LIMIT_CONNECT
1930 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
1932 if (csp->action->flags & ACTION_TREAT_FORBIDDEN_CONNECTS_LIKE_BLOCKS)
1935 * The response may confuse some clients,
1936 * but makes unblocking easier.
1938 log_error(LOG_LEVEL_ERROR, "Marking suspicious CONNECT request from %s for blocking.",
1940 csp->action->flags |= ACTION_BLOCK;
1945 write_socket(csp->cfd, CFORBIDDEN, strlen(CFORBIDDEN));
1946 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
1947 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
1955 * Save a copy of the original request for logging
1957 http->ocmd = strdup(http->cmd);
1959 if (http->ocmd == NULL)
1961 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
1965 * (Re)build the HTTP request for non-SSL requests.
1969 build_request_line(csp, fwd);
1971 enlist(csp->headers, http->cmd);
1973 /* Append the previously read headers */
1974 list_append_list_unique(csp->headers, headers);
1975 destroy_list(headers);
1978 * If the user has not supplied any wafers, and the user has not
1979 * told us to suppress the vanilla wafer, then send the vanilla wafer.
1981 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
1982 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
1984 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
1987 hdr = sed(client_patterns, add_client_headers, csp);
1990 /* FIXME Should handle error properly */
1991 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1993 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1995 #ifdef FEATURE_KILL_POPUPS
1996 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1997 #endif /* def FEATURE_KILL_POPUPS */
1999 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
2000 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
2002 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
2004 jpeg_inspect = ((csp->action->flags & ACTION_JPEG_INSPECT) != 0);
2007 * We have a request. Check if one of the crunchers wants it.
2009 if (crunch_response_triggered(csp, crunchers_all))
2012 * Yes. The client got the crunch response
2013 * and we are done here after cleaning up.
2016 list_remove_all(csp->headers);
2022 * The headers can't be removed earlier because
2023 * they were still needed for the referrer check
2024 * in case of CGI crunches.
2026 * XXX: Would it be worth to move the referrer check
2027 * into client_referrer() and set a flag if it's trusted?
2029 list_remove_all(csp->headers);
2031 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
2033 if (fwd->forward_host)
2035 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
2036 fwd->forward_host, fwd->forward_port, http->hostport);
2040 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
2043 /* here we connect to the server, gateway, or the forwarder */
2045 while ( (csp->sfd = forwarded_connect(fwd, http, csp))
2046 && (errno == EINVAL) && (forwarded_connect_retries++ < max_forwarded_connect_retries))
2048 log_error(LOG_LEVEL_ERROR, "failed request #%u to connect to %s. Trying again.",
2049 forwarded_connect_retries, http->hostport);
2052 if (csp->sfd == JB_INVALID_SOCKET)
2054 if (fwd->type != SOCKS_NONE)
2057 rsp = error_response(csp, "forwarding-failed", errno);
2059 else if (errno == EINVAL)
2061 rsp = error_response(csp, "no-such-domain", errno);
2065 rsp = error_response(csp, "connect-failed", errno);
2066 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
2071 /* Write the answer to the client */
2074 send_crunch_response(csp, rsp);
2081 if (fwd->forward_host || (http->ssl == 0))
2083 /* write the client's (modified) header to the server
2084 * (along with anything else that may be in the buffer)
2087 if (write_socket(csp->sfd, hdr, strlen(hdr))
2088 || (flush_socket(csp->sfd, csp) < 0))
2090 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
2093 rsp = error_response(csp, "connect-failed", errno);
2097 send_crunch_response(csp, rsp);
2107 * We're running an SSL tunnel and we're not forwarding,
2108 * so just send the "connect succeeded" message to the
2109 * client, flush the rest, and get out of the way.
2111 if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
2119 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
2121 /* we're finished with the client's header */
2124 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
2126 /* pass data between the client and server
2127 * until one or the other shuts down the connection.
2136 * FD_ZERO here seems to point to an errant macro which crashes.
2137 * So do this by hand for now...
2139 memset(&rfds,0x00,sizeof(fd_set));
2143 FD_SET(csp->cfd, &rfds);
2144 FD_SET(csp->sfd, &rfds);
2146 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
2150 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2154 /* this is the body of the browser's request
2155 * just read it and write it.
2158 if (FD_ISSET(csp->cfd, &rfds))
2160 len = read_socket(csp->cfd, buf, sizeof(buf));
2164 break; /* "game over, man" */
2167 if (write_socket(csp->sfd, buf, (size_t)len))
2169 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2176 * The server wants to talk. It could be the header or the body.
2177 * If `hdr' is null, then it's the header otherwise it's the body.
2178 * FIXME: Does `hdr' really mean `host'? No.
2182 if (FD_ISSET(csp->sfd, &rfds))
2185 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
2189 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2191 if (http->ssl && (fwd->forward_host == NULL))
2194 * Just hang up. We already confirmed the client's CONNECT
2195 * request with status code 200 and unencrypted content is
2196 * no longer welcome.
2198 log_error(LOG_LEVEL_ERROR,
2199 "CONNECT already confirmed. Unable to tell the client about the problem.");
2203 rsp = error_response(csp, "connect-failed", errno);
2207 send_crunch_response(csp, rsp);
2213 /* Add a trailing zero. This lets filter_popups
2214 * use string operations.
2218 #ifdef FEATURE_KILL_POPUPS
2219 /* Filter the popups on this read. */
2220 if (block_popups_now)
2222 filter_popups(buf, csp);
2224 #endif /* def FEATURE_KILL_POPUPS */
2226 /* Normally, this would indicate that we've read
2227 * as much as the server has sent us and we can
2228 * close the client connection. However, Microsoft
2229 * in its wisdom has released IIS/5 with a bug that
2230 * prevents it from sending the trailing \r\n in
2231 * a 302 redirect header (and possibly other headers).
2232 * To work around this if we've haven't parsed
2233 * a full header we'll append a trailing \r\n
2234 * and see if this now generates a valid one.
2236 * This hack shouldn't have any impacts. If we've
2237 * already transmitted the header or if this is a
2238 * SSL connection, then we won't bother with this
2239 * hack. So we only work on partially received
2240 * headers. If we append a \r\n and this still
2241 * doesn't generate a valid header, then we won't
2242 * transmit anything to the client.
2247 if (server_body || http->ssl)
2250 * If we have been buffering up the document,
2251 * now is the time to apply content modification
2252 * and send the result to the client.
2257 * If the content filter fails, use the original
2258 * buffer and length.
2259 * (see p != NULL ? p : csp->iob->cur below)
2261 if (NULL == (p = (*content_filter)(csp)))
2263 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2266 hdr = sed(server_patterns_light, NULL, csp);
2270 /* FIXME Should handle error properly */
2271 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2275 * Shouldn't happen because this was the second sed run
2276 * and tags are only created for the first one.
2278 assert(!crunch_response_triggered(csp, crunchers_all));
2280 if (write_socket(csp->cfd, hdr, strlen(hdr))
2281 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
2283 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2293 break; /* "game over, man" */
2297 * This is NOT the body, so
2298 * Let's pretend the server just sent us a blank line.
2300 snprintf(buf, sizeof(buf), "\r\n");
2301 len = (int)strlen(buf);
2304 * Now, let the normal header parsing algorithm below do its
2305 * job. If it fails, we'll exit instead of continuing.
2312 * If this is an SSL connection or we're in the body
2313 * of the server document, just write it to the client,
2314 * unless we need to buffer the body for later content-filtering
2317 if (server_body || http->ssl)
2322 * If there is no memory left for buffering the content, or the buffer limit
2323 * has been reached, switch to non-filtering mode, i.e. make & write the
2324 * header, flush the iob and buf, and get out of the way.
2326 if (add_to_iob(csp, buf, len))
2331 log_error(LOG_LEVEL_ERROR, "Flushing header and buffers. Stepping back from filtering.");
2333 hdr = sed(server_patterns, add_server_headers, csp);
2337 * Memory is too tight to even generate the header.
2338 * Send our static "Out-of-memory" page.
2340 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2341 rsp = cgi_error_memory();
2342 send_crunch_response(csp, rsp);
2347 if (crunch_response_triggered(csp, crunchers_light))
2350 * One of the tags created by a server-header
2351 * tagger triggered a crunch. We already
2352 * delivered the crunch response to the client
2353 * and are done here after cleaning up.
2359 hdrlen = strlen(hdr);
2361 if (write_socket(csp->cfd, hdr, hdrlen)
2362 || ((flushed = flush_socket(csp->cfd, csp)) < 0)
2363 || (write_socket(csp->cfd, buf, (size_t)len)))
2365 log_error(LOG_LEVEL_CONNECT, "Flush header and buffers to client failed: %E");
2371 byte_count += hdrlen + (size_t)flushed + (size_t)len;
2373 content_filter = NULL;
2380 if (write_socket(csp->cfd, buf, (size_t)len))
2382 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2386 byte_count += (size_t)len;
2391 /* we're still looking for the end of the
2392 * server's header ... (does that make header
2393 * parsing an "out of body experience" ?
2397 * buffer up the data we just read. If that fails,
2398 * there's little we can do but send our static
2399 * out-of-memory page.
2401 if (add_to_iob(csp, buf, len))
2403 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2404 rsp = cgi_error_memory();
2405 send_crunch_response(csp, rsp);
2410 /* Convert iob into something sed() can digest */
2411 if (JB_ERR_PARSE == get_server_headers(csp))
2415 /* Well, we tried our MS IIS/5
2416 * hack and it didn't work.
2417 * The header is incomplete
2418 * and there isn't anything
2419 * we can do about it.
2425 /* Since we have to wait for
2426 * more from the server before
2427 * we can parse the headers
2428 * we just continue here.
2434 /* Did we actually get anything? */
2435 if (NULL == csp->headers->first)
2437 log_error(LOG_LEVEL_ERROR, "Empty server or forwarder response.");
2438 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2439 write_socket(csp->cfd, NO_SERVER_DATA_RESPONSE, strlen(NO_SERVER_DATA_RESPONSE));
2440 free_http_request(http);
2444 /* we have now received the entire header.
2445 * filter it and send the result to the client
2448 hdr = sed(server_patterns, add_server_headers, csp);
2451 /* FIXME Should handle error properly */
2452 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2455 if (crunch_response_triggered(csp, crunchers_light))
2458 * One of the tags created by a server-header
2459 * tagger triggered a crunch. We already
2460 * delivered the crunch response to the client
2461 * and are done here after cleaning up.
2466 #ifdef FEATURE_KILL_POPUPS
2467 /* Start blocking popups if appropriate. */
2469 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
2470 !http->ssl && /* We talk plaintext */
2471 block_popups) /* Policy allows */
2473 block_popups_now = 1;
2475 * Filter the part of the body that came in the same read
2476 * as the last headers:
2478 filter_popups(csp->iob->cur, csp);
2481 #endif /* def FEATURE_KILL_POPUPS */
2483 /* Buffer and pcrs filter this if appropriate. */
2485 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
2486 !http->ssl && /* We talk plaintext */
2487 pcrs_filter) /* Policy allows */
2489 content_filter = pcrs_filter_response;
2492 /* Buffer and gif_deanimate this if appropriate. */
2494 if ((csp->content_type & CT_GIF) && /* It's an image/gif MIME-Type */
2495 !http->ssl && /* We talk plaintext */
2496 gif_deanimate) /* Policy allows */
2498 content_filter = gif_deanimate_response;
2501 /* Buffer and jpg_inspect this if appropriate. */
2503 if ((csp->content_type & CT_JPEG) && /* It's an image/jpeg MIME-Type */
2504 !http->ssl && /* We talk plaintext */
2505 jpeg_inspect) /* Policy allows */
2507 content_filter = jpeg_inspect_response;
2511 * Only write if we're not buffering for content modification
2513 if (!content_filter)
2515 /* write the server's (modified) header to
2516 * the client (along with anything else that
2517 * may be in the buffer)
2520 if (write_socket(csp->cfd, hdr, strlen(hdr))
2521 || ((len = flush_socket(csp->cfd, csp)) < 0))
2523 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2525 /* the write failed, so don't bother
2526 * mentioning it to the client...
2527 * it probably can't hear us anyway.
2533 byte_count += (size_t)len;
2536 /* we're finished with the server's header */
2541 /* If this was a MS IIS/5 hack then it means
2542 * the server has already closed the
2543 * connection. Nothing more to read. Time
2554 return; /* huh? we should never get here */
2557 if (csp->content_length == 0)
2560 * If Privoxy didn't recalculate the
2561 * Content-Lenght, byte_count is still
2564 csp->content_length = byte_count;
2567 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
2568 csp->ip_addr_str, http->ocmd, csp->content_length);
2572 /*********************************************************************
2576 * Description : This is little more than chat. We only "serve" to
2577 * to close any socket that chat may have opened.
2580 * 1 : csp = Current client state (buffers, headers, etc...)
2584 *********************************************************************/
2586 void serve(struct client_state *csp)
2587 #else /* ifndef AMIGA */
2588 static void serve(struct client_state *csp)
2589 #endif /* def AMIGA */
2592 close_socket(csp->cfd);
2594 if (csp->sfd != JB_INVALID_SOCKET)
2596 close_socket(csp->sfd);
2599 csp->flags &= ~CSP_FLAG_ACTIVE;
2605 /*********************************************************************
2607 * Function : server_thread
2609 * Description : We only exist to call `serve' in a threaded environment.
2612 * 1 : data = Current client state (buffers, headers, etc...)
2614 * Returns : Always 0.
2616 *********************************************************************/
2617 static int32 server_thread(void *data)
2619 serve((struct client_state *) data);
2626 /*********************************************************************
2630 * Description : Print usage info & exit.
2632 * Parameters : Pointer to argv[0] for identifying ourselves
2636 *********************************************************************/
2637 void usage(const char *myname)
2639 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
2640 "Usage: %s [--help] [--version] "
2642 "[--no-daemon] [--pidfile pidfile] [--user user[.group]] "
2643 #endif /* defined(unix) */
2645 "Aborting\n", myname);
2652 /*********************************************************************
2654 * Function : initialize_mutexes
2656 * Description : Prepares mutexes if mutex support is available.
2660 * Returns : Void, exits in case of errors.
2662 *********************************************************************/
2663 void initialize_mutexes()
2667 #ifdef FEATURE_PTHREAD
2669 * Prepare global mutex semaphores
2671 err = pthread_mutex_init(&log_mutex, 0);
2673 if (!err) err = pthread_mutex_init(&log_init_mutex, 0);
2676 * XXX: The assumptions below are a bit naive
2677 * and can cause locks that aren't necessary.
2679 * For example older FreeBSD versions (< 6.x?)
2680 * have no gethostbyname_r, but gethostbyname is
2683 #ifndef HAVE_GMTIME_R
2684 if (!err) err = pthread_mutex_init(&gmtime_mutex, 0);
2685 #endif /* ndef HAVE_GMTIME_R */
2687 #ifndef HAVE_LOCALTIME_R
2688 if (!err) err = pthread_mutex_init(&localtime_mutex, 0);
2689 #endif /* ndef HAVE_GMTIME_R */
2691 #ifndef HAVE_GETHOSTBYADDR_R
2692 if (!err) err = pthread_mutex_init(&gethostbyaddr_mutex, 0);
2693 #endif /* ndef HAVE_GETHOSTBYADDR_R */
2695 #ifndef HAVE_GETHOSTBYNAME_R
2696 if (!err) err = pthread_mutex_init(&gethostbyname_mutex, 0);
2697 #endif /* ndef HAVE_GETHOSTBYNAME_R */
2700 if (!err) err = pthread_mutex_init(&rand_mutex, 0);
2701 #endif /* ndef HAVE_RANDOM */
2702 #endif /* FEATURE_PTHREAD */
2705 * TODO: mutex support for mingw32 would be swell.
2710 printf("Fatal error. Mutex initialization failed: %s.\n",
2719 /*********************************************************************
2723 * Description : Load the config file and start the listen loop.
2724 * This function is a lot more *sane* with the `load_config'
2725 * and `listen_loop' functions; although it stills does
2726 * a *little* too much for my taste.
2729 * 1 : argc = Number of parameters (including $0).
2730 * 2 : argv = Array of (char *)'s to the parameters.
2732 * Returns : 1 if : can't open config file, unrecognized directive,
2733 * stats requested in multi-thread mode, can't open the
2734 * log file, can't open the jar file, listen port is invalid,
2735 * any load fails, and can't bind port.
2737 * Else main never returns, the process must be signaled
2738 * to terminate execution. Or, on Windows, use the
2739 * "File", "Exit" menu option.
2741 *********************************************************************/
2743 int real_main(int argc, const char *argv[])
2745 int main(int argc, const char *argv[])
2749 unsigned int random_seed;
2751 struct passwd *pw = NULL;
2752 struct group *grp = NULL;
2761 #if !defined(_WIN32)
2769 * Parse the command line arguments
2771 * XXX: simply printing usage information in case of
2772 * invalid arguments isn't particular user friendly.
2774 while (++argc_pos < argc)
2777 /* Check to see if the service must be installed or uninstalled */
2778 if (strncmp(argv[argc_pos], "--install", 9) == 0)
2780 const char *pName = argv[argc_pos] + 9;
2783 exit( (install_service(pName)) ? 0 : 1 );
2785 else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
2787 const char *pName = argv[argc_pos] + 11;
2790 exit((uninstall_service(pName)) ? 0 : 1);
2792 else if (strcmp(argv[argc_pos], "--service" ) == 0)
2794 bRunAsService = TRUE;
2795 w32_set_service_cwd();
2796 atexit(w32_service_exit_notify);
2799 #endif /* defined(_WIN32) */
2802 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2804 if (strcmp(argv[argc_pos], "--help") == 0)
2809 else if(strcmp(argv[argc_pos], "--version") == 0)
2811 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
2817 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
2822 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
2824 if (++argc_pos == argc) usage(argv[0]);
2825 pidfile = strdup(argv[argc_pos]);
2828 else if (strcmp(argv[argc_pos], "--user" ) == 0)
2830 if (++argc_pos == argc) usage(argv[argc_pos]);
2832 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
2835 if (NULL == (grp = getgrnam(p)))
2837 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
2841 if (NULL == (pw = getpwnam(argv[argc_pos])))
2843 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
2846 if (p != NULL) *--p = '\0';
2849 else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
2853 #endif /* defined(unix) */
2855 else if (argc_pos + 1 != argc)
2858 * This is neither the last command line
2859 * option, nor was it recognized before,
2860 * therefore it must be invalid.
2866 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
2868 configfile = argv[argc_pos];
2871 } /* -END- while (more arguments) */
2874 if ( *configfile != '/' )
2876 char cwd[BUFFER_SIZE];
2878 size_t abs_file_size;
2880 /* make config-filename absolute here */
2881 if (NULL == getcwd(cwd, sizeof(cwd)))
2883 perror("failed to get current working directory");
2888 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
2889 basedir = strdup(cwd);
2891 if (NULL == basedir ||
2892 NULL == (abs_file = malloc(abs_file_size)))
2894 perror("malloc failed");
2897 strlcpy(abs_file, basedir, abs_file_size);
2898 strlcat(abs_file, "/", abs_file_size );
2899 strlcat(abs_file, configfile, abs_file_size);
2900 configfile = abs_file;
2902 #endif /* defined unix */
2906 clients->next = NULL;
2910 #elif defined(_WIN32)
2914 /* Prepare mutexes if supported and necessary. */
2915 initialize_mutexes();
2917 random_seed = (unsigned int)time(NULL);
2919 srandom(random_seed);
2922 #endif /* ifdef HAVE_RANDOM */
2925 * Unix signal handling
2927 * Catch the abort, interrupt and terminate signals for a graceful exit
2928 * Catch the hangup signal so the errlog can be reopened.
2929 * Ignore the broken pipe signals (FIXME: Why?)
2931 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
2934 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP, 0 };
2935 const int ignored_signals[] = { SIGPIPE, 0 };
2937 for (idx = 0; catched_signals[idx] != 0; idx++)
2939 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
2940 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
2942 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
2943 #endif /* ifdef sun */
2945 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
2949 for (idx = 0; ignored_signals[idx] != 0; idx++)
2951 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
2953 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
2958 #else /* ifdef _WIN32 */
2959 # ifdef _WIN_CONSOLE
2961 * We *are* in a windows console app.
2962 * Print a verbose messages about FAQ's and such
2964 printf("%s", win32_blurb);
2965 # endif /* def _WIN_CONSOLE */
2966 #endif /* def _WIN32 */
2969 /* Initialize the CGI subsystem */
2970 cgi_init_error_messages();
2973 * If runnig on unix and without the --nodaemon
2974 * option, become a daemon. I.e. fork, detach
2975 * from tty and get process group leadership
2988 if ( pid < 0 ) /* error */
2993 else if ( pid != 0 ) /* parent */
2998 * must check for errors
2999 * child died due to missing files aso
3002 wpid = waitpid( pid, &status, WNOHANG );
3011 /* Should be more portable, but not as well tested */
3016 #else /* ndef __FreeBSD__ */
3018 #endif /* ndef __FreeBSD__ */
3019 fd = open("/dev/tty", O_RDONLY);
3022 /* no error check here */
3023 ioctl( fd, TIOCNOTTY,0 );
3027 /* FIXME: should close stderr (fd 2) here too, but the test
3029 * and load config file is done in listen_loop() and puts
3030 * some messages on stderr there.
3037 } /* -END- if (!no_daemon) */
3040 * As soon as we have written the PID file, we can switch
3041 * to the user and group ID indicated by the --user option
3047 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3049 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3055 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3057 if (chroot(pw->pw_dir) < 0)
3059 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3063 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3066 if (setuid(pw->pw_uid))
3068 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3072 char putenv_dummy[64];
3074 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3075 if (putenv(putenv_dummy) != 0)
3077 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3080 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3081 if (putenv(putenv_dummy) != 0)
3083 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3089 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3092 #endif /* defined unix */
3095 /* This will be FALSE unless the command line specified --service
3099 /* Yup, so now we must attempt to establish a connection
3100 * with the service dispatcher. This will only work if this
3101 * process was launched by the service control manager to
3102 * actually run as a service. If this isn't the case, i've
3103 * known it take around 30 seconds or so for the call to return.
3106 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3107 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3109 /* Service has run, and at this point is now being stopped, so just return */
3114 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3116 /* An error occurred. Usually it's because --service was wrongly specified
3117 * and we were unable to connect to the Service Control Dispatcher because
3118 * it wasn't expecting us and is therefore not listening.
3120 * For now, just continue below to call the listen_loop function.
3123 #endif /* def _WIN32 */
3133 /*********************************************************************
3135 * Function : bind_port_helper
3137 * Description : Bind the listen port. Handles logging, and aborts
3141 * 1 : config = Privoxy configuration. Specifies port
3144 * Returns : Port that was opened.
3146 *********************************************************************/
3147 static jb_socket bind_port_helper(struct configuration_spec * config)
3152 if ( (config->haddr != NULL)
3153 && (config->haddr[0] == '1')
3154 && (config->haddr[1] == '2')
3155 && (config->haddr[2] == '7')
3156 && (config->haddr[3] == '.') )
3158 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
3161 else if (config->haddr == NULL)
3163 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3168 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3169 config->hport, config->haddr);
3172 result = bind_port(config->haddr, config->hport, &bfd);
3179 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
3180 "There may be another Privoxy or some other "
3181 "proxy running on port %d",
3182 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
3183 config->hport, config->hport);
3186 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
3187 "The hostname is not resolvable",
3188 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
3191 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
3192 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
3195 /* shouldn't get here */
3196 return JB_INVALID_SOCKET;
3199 config->need_bind = 0;
3206 /* Without this simple workaround we get this compiler warning from _beginthread
3207 * warning C4028: formal parameter 1 different from declaration
3209 void w32_service_listen_loop(void *p)
3213 #endif /* def _WIN32 */
3216 /*********************************************************************
3218 * Function : listen_loop
3220 * Description : bind the listen port and enter a "FOREVER" listening loop.
3226 *********************************************************************/
3227 static void listen_loop(void)
3229 struct client_state *csp = NULL;
3231 struct configuration_spec * config;
3233 config = load_config();
3235 bfd = bind_port_helper(config);
3237 #ifdef FEATURE_GRACEFUL_TERMINATION
3238 while (!g_terminate)
3243 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3244 while (waitpid(-1, NULL, WNOHANG) > 0)
3246 /* zombie children */
3248 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3251 * Free data that was used by died threads
3257 * Re-open the errlog after HUP signal
3259 if (received_hup_signal)
3261 init_error_log(Argv[0], config->logfile, config->debug);
3262 received_hup_signal = 0;
3267 #ifdef FEATURE_COOKIE_JAR
3269 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
3270 * already open. I think unload_configfile() is not being run, which should do
3271 * this work. Until that can get resolved, we'll use this workaround.
3275 if (csp->config->jar)
3277 fclose(csp->config->jar);
3278 csp->config->jar = NULL;
3280 #endif /* FEATURE_COOKIE_JAR */
3281 #endif /* __OS2__ */
3283 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
3285 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
3289 csp->flags |= CSP_FLAG_ACTIVE;
3290 csp->sfd = JB_INVALID_SOCKET;
3292 csp->config = config = load_config();
3294 if ( config->need_bind )
3297 * Since we were listening to the "old port", we will not see
3298 * a "listen" param change until the next IJB request. So, at
3299 * least 1 more request must be made for us to find the new
3300 * setting. I am simply closing the old socket and binding the
3303 * Which-ever is correct, we will serve 1 more page via the
3304 * old settings. This should probably be a "show-proxy-args"
3305 * request. This should not be a so common of an operation
3306 * that this will hurt people's feelings.
3311 bfd = bind_port_helper(config);
3314 log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
3316 if (!accept_connection(csp, bfd))
3318 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3331 log_error(LOG_LEVEL_CONNECT, "accepted connection from %s", csp->ip_addr_str);
3334 #ifdef FEATURE_TOGGLE
3335 if (global_toggle_state)
3337 csp->flags |= CSP_FLAG_TOGGLED_ON;
3339 #endif /* def FEATURE_TOGGLE */
3341 if (run_loader(csp))
3343 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
3344 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3348 if (block_acl(NULL,csp))
3350 log_error(LOG_LEVEL_CONNECT, "Connection from %s dropped due to ACL", csp->ip_addr_str);
3351 close_socket(csp->cfd);
3355 #endif /* def FEATURE_ACL */
3357 /* add it to the list of clients */
3358 csp->next = clients->next;
3359 clients->next = csp;
3361 if (config->multi_threaded)
3365 /* this is a switch () statment in the C preprocessor - ugh */
3366 #undef SELECTED_ONE_OPTION
3368 /* Use Pthreads in preference to native code */
3369 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
3370 #define SELECTED_ONE_OPTION
3372 pthread_t the_thread;
3373 pthread_attr_t attrs;
3375 pthread_attr_init(&attrs);
3376 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
3377 errno = pthread_create(&the_thread, &attrs,
3378 (void * (*)(void *))serve, csp);
3379 child_id = errno ? -1 : 0;
3380 pthread_attr_destroy(&attrs);
3384 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
3385 #define SELECTED_ONE_OPTION
3386 child_id = _beginthread(
3387 (void (*)(void *))serve,
3392 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
3393 #define SELECTED_ONE_OPTION
3394 child_id = _beginthread(
3395 (void(* _Optlink)(void*))serve,
3401 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
3402 #define SELECTED_ONE_OPTION
3404 thread_id tid = spawn_thread
3405 (server_thread, "server", B_NORMAL_PRIORITY, csp);
3407 if ((tid >= 0) && (resume_thread(tid) == B_OK))
3409 child_id = (int) tid;
3418 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
3419 #define SELECTED_ONE_OPTION
3420 csp->cfd = ReleaseSocket(csp->cfd, -1);
3423 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3424 NP_Output, Output(),
3425 NP_CloseOutput, FALSE,
3426 NP_Name, (ULONG)"privoxy child",
3430 child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3431 NP_Output, Output(),
3432 NP_CloseOutput, FALSE,
3433 NP_Name, (ULONG)"privoxy child",
3434 NP_StackSize, 200*1024,
3440 ((struct Task *)child_id)->tc_UserData = csp;
3441 Signal((struct Task *)child_id, SIGF_SINGLE);
3446 #if !defined(SELECTED_ONE_OPTION)
3449 /* This block is only needed when using fork().
3450 * When using threads, the server thread was
3451 * created and run by the call to _beginthread().
3453 if (child_id == 0) /* child */
3456 #ifdef FEATURE_TOGGLE
3457 int inherited_toggle_state = global_toggle_state;
3458 #endif /* def FEATURE_TOGGLE */
3463 * If we've been toggled or we've blocked the request, tell Mom
3466 #ifdef FEATURE_TOGGLE
3467 if (inherited_toggle_state != global_toggle_state)
3469 rc |= RC_FLAG_TOGGLED;
3471 #endif /* def FEATURE_TOGGLE */
3473 #ifdef FEATURE_STATISTICS
3474 if (csp->flags & CSP_FLAG_REJECTED)
3476 rc |= RC_FLAG_BLOCKED;
3478 #endif /* ndef FEATURE_STATISTICS */
3482 else if (child_id > 0) /* parent */
3484 /* in a fork()'d environment, the parent's
3485 * copy of the client socket and the CSP
3489 #if !defined(_WIN32) && !defined(__CYGWIN__)
3491 wait( &child_status );
3494 * Evaluate child's return code: If the child has
3495 * - been toggled, toggle ourselves
3496 * - blocked its request, bump up the stats counter
3499 #ifdef FEATURE_TOGGLE
3500 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
3502 global_toggle_state = !global_toggle_state;
3504 #endif /* def FEATURE_TOGGLE */
3506 #ifdef FEATURE_STATISTICS
3508 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
3512 #endif /* def FEATURE_STATISTICS */
3514 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
3515 close_socket(csp->cfd);
3516 csp->flags &= ~CSP_FLAG_ACTIVE;
3520 #undef SELECTED_ONE_OPTION
3521 /* end of cpp switch () */
3523 if (child_id < 0) /* failed */
3525 char buf[BUFFER_SIZE];
3527 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
3529 snprintf(buf , sizeof(buf), "Privoxy: can't fork: errno = %d", errno);
3531 write_socket(csp->cfd, buf, strlen(buf));
3532 close_socket(csp->cfd);
3533 csp->flags &= ~CSP_FLAG_ACTIVE;
3544 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
3546 /* Clean up. Aim: free all memory (no leaks) */
3547 #ifdef FEATURE_GRACEFUL_TERMINATION
3549 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
3551 unload_current_config_file();
3552 unload_current_actions_file();
3553 unload_current_re_filterfile();
3554 #ifdef FEATURE_TRUST
3555 unload_current_trust_file();
3558 if (config->multi_threaded)
3565 } while ((clients->next != NULL) && (--i > 0));
3569 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
3580 #ifdef FEATURE_COOKIE_JAR
3581 if (NULL != config->jar)
3583 fclose(config->jar);
3587 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
3588 /* Cleanup - remove taskbar icon etc. */
3593 #endif /* FEATURE_GRACEFUL_TERMINATION */