1 const char jcc_rcs[] = "$Id: jcc.c,v 1.97 2006/08/18 15:23:17 david__schmidt 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 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.97 2006/08/18 15:23:17 david__schmidt
37 * Windows service (re-)integration
41 * --install[:service_name]
42 * --uninstall[:service_name]
45 * They work as follows:
46 * --install will create a service for you and then terminate.
47 * By default the service name will be "privoxy" (without the quotes).
48 * However you can run multiple services if you wish, just by adding
49 * a colon and then a name (no spaces).
51 * --uninstall follows the exact same rules a --install.
53 * --service is used when the program is executed by the service
54 * control manager, and in normal circumstances would never be
55 * used as a command line argument.
57 * Revision 1.96 2006/08/15 20:12:36 david__schmidt
58 * Windows service integration
60 * Revision 1.95 2006/08/03 02:46:41 david__schmidt
61 * Incorporate Fabian Keil's patch work:
\rhttp://www.fabiankeil.de/sourcecode/privoxy/
63 * Revision 1.94 2006/07/18 14:48:46 david__schmidt
64 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
65 * with what was really the latest development (the v_3_0_branch branch)
67 * Revision 1.92.2.16 2005/04/03 20:10:50 david__schmidt
68 * Thanks to Jindrich Makovicka for a race condition fix for the log
69 * file. The race condition remains for non-pthread implementations.
70 * Reference patch #1175720.
72 * Revision 1.92.2.15 2004/10/03 12:53:32 david__schmidt
73 * Add the ability to check jpeg images for invalid
74 * lengths of comment blocks. Defensive strategy
75 * against the exploit:
76 * Microsoft Security Bulletin MS04-028
77 * Buffer Overrun in JPEG Processing (GDI+) Could
78 * Allow Code Execution (833987)
79 * Enabled with +inspect-jpegs in actions files.
81 * Revision 1.92.2.14 2003/12/12 12:52:53 oes
82 * - Fixed usage info for non-unix platforms
83 * - Fixed small cmdline parsing bug
85 * Revision 1.92.2.13 2003/11/27 19:20:27 oes
86 * Diagnostics: Now preserve the returncode of pthread_create
87 * in errno. Closes BR #775721. Thanks to Geoffrey Hausheer.
89 * Revision 1.92.2.12 2003/07/11 11:34:19 oes
90 * No longer ignore SIGCHLD. Fixes bug #769381
92 * Revision 1.92.2.11 2003/05/14 12:32:02 oes
93 * Close jarfile on graceful exit, remove stray line
95 * Revision 1.92.2.10 2003/05/08 15:13:46 oes
96 * Cosmetics: Killed a warning, a typo and an allocation left at exit
98 * Revision 1.92.2.9 2003/04/03 15:08:42 oes
99 * No longer rely on non-POSIX.1 extensions of getcwd().
102 * Revision 1.92.2.8 2003/03/31 13:12:32 oes
103 * Replaced setenv() by posix-compliant putenv()
104 * Thanks to Neil McCalden (nmcc AT users.sf.net).
106 * Revision 1.92.2.7 2003/03/17 16:48:59 oes
107 * Added chroot ability, thanks to patch by Sviatoslav Sviridov
109 * Revision 1.92.2.6 2003/03/11 11:55:00 oes
110 * Clean-up and extension of improvements for forked mode:
111 * - Child's return code now consists of flags RC_FLAG_*
112 * - Reporting toggle to parent now properly #ifdef'ed
113 * - Children now report blocking to parent. This enables
114 * statistics in forked mode
116 * Revision 1.92.2.5 2003/03/10 23:45:32 oes
117 * Fixed bug #700381: Non-Threaded version now capable of being toggled.
118 * Children now report having been toggled through _exit(17), parents
119 * watch for that code and toggle themselves if found.
121 * Revision 1.92.2.4 2003/03/07 03:41:04 david__schmidt
122 * Wrapping all *_r functions (the non-_r versions of them) with
123 * mutex semaphores for OSX. Hopefully this will take care of all
124 * of those pesky crash reports.
126 * Revision 1.92.2.3 2003/02/28 12:53:06 oes
127 * Fixed two mostly harmless mem leaks
129 * Revision 1.92.2.2 2002/11/20 14:37:47 oes
130 * Fix: Head of global clients list now initialized to NULL
132 * Revision 1.92.2.1 2002/09/25 14:52:24 oes
133 * Added basic support for OPTIONS and TRACE HTTP methods:
134 * - New interceptor direct_response() added in chat().
135 * - sed() moved to earlier in the process, so that the
136 * Host: header is evaluated before actions and forwarding
139 * Revision 1.92 2002/05/08 16:00:46 oes
140 * Chat's buffer handling:
141 * - Fixed bug with unchecked out-of-mem conditions
142 * while reading client request & server headers
143 * - No longer predict if the buffer limit will be exceeded
144 * in the next read -- check add_to_iob's new
145 * return code. If buffer couldn't be extended
146 * (policy or out-of-mem) while
147 * - reading from client: abort
148 * - reading server headers: send error page
149 * - buffering server body for filter: flush,
150 * and if that fails: send error page
152 * Revision 1.91 2002/04/08 20:35:58 swa
155 * Revision 1.90 2002/04/02 14:57:28 oes
156 * Made sending wafers independent of FEATURE_COOKIE_JAR
158 * Revision 1.89 2002/03/31 17:18:59 jongfoster
159 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
161 * Revision 1.88 2002/03/27 14:32:43 david__schmidt
162 * More compiler warning message maintenance
164 * Revision 1.87 2002/03/26 22:29:54 swa
165 * we have a new homepage!
167 * Revision 1.86 2002/03/25 17:04:55 david__schmidt
168 * Workaround for closing the jarfile before load_config() comes around again
170 * Revision 1.85 2002/03/24 15:23:33 jongfoster
173 * Revision 1.84 2002/03/24 13:25:43 swa
174 * name change related issues
176 * Revision 1.83 2002/03/16 23:54:06 jongfoster
177 * Adding graceful termination feature, to help look for memory leaks.
178 * If you enable this (which, by design, has to be done by hand
179 * editing config.h) and then go to http://i.j.b/die, then the program
180 * will exit cleanly after the *next* request. It should free all the
181 * memory that was used.
183 * Revision 1.82 2002/03/13 00:27:05 jongfoster
186 * Revision 1.81 2002/03/12 01:42:50 oes
187 * Introduced modular filters
189 * Revision 1.80 2002/03/11 22:07:05 david__schmidt
190 * OS/2 port maintenance:
191 * - Fixed EMX build - it had decayed a little
192 * - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
193 * substituted a memset for now.
195 * Revision 1.79 2002/03/09 20:03:52 jongfoster
196 * - Making various functions return int rather than size_t.
197 * (Undoing a recent change). Since size_t is unsigned on
198 * Windows, functions like read_socket that return -1 on
199 * error cannot return a size_t.
201 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
202 * crashes, and also frequently caused JB to jump to 100%
203 * CPU and stay there. (Because it thought it had just
204 * read ((unsigned)-1) == 4Gb of data...)
206 * - The signature of write_socket has changed, it now simply
207 * returns success=0/failure=nonzero.
209 * - Trying to get rid of a few warnings --with-debug on
210 * Windows, I've introduced a new type "jb_socket". This is
211 * used for the socket file descriptors. On Windows, this
212 * is SOCKET (a typedef for unsigned). Everywhere else, it's
213 * an int. The error value can't be -1 any more, so it's
214 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
215 * Windows it maps to the #define INVALID_SOCKET.)
217 * - The signature of bind_port has changed.
219 * Revision 1.78 2002/03/08 21:35:04 oes
220 * Added optional group supplement to --user option. Will now use default group of user if no group given
222 * Revision 1.77 2002/03/07 03:52:06 oes
223 * - Fixed compiler warnings etc
224 * - Improved handling of failed DNS lookups
226 * Revision 1.76 2002/03/06 22:54:35 jongfoster
227 * Automated function-comment nitpicking.
229 * Revision 1.75 2002/03/06 10:02:19 oes
230 * Fixed stupid bug when --user was not given
232 * Revision 1.74 2002/03/06 00:49:31 jongfoster
233 * Fixing warning on Windows
234 * Making #ifdefs that refer to the same variable consistently
235 * use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
237 * Revision 1.73 2002/03/05 23:57:30 hal9
238 * Stray character 's' on line 1618 was breaking build.
240 * Revision 1.72 2002/03/05 21:33:45 david__schmidt
241 * - Re-enable OS/2 building after new parms were added
242 * - Fix false out of memory report when resolving CGI templates when no IP
243 * address is available of failed attempt (a la no such domain)
245 * Revision 1.71 2002/03/05 18:13:56 oes
246 * Added --user option
248 * Revision 1.70 2002/03/05 04:52:42 oes
249 * Deleted non-errlog debugging code
251 * Revision 1.69 2002/03/04 23:50:00 jongfoster
252 * Splitting off bind_port() call into bind_port_helper(), with
255 * Revision 1.68 2002/03/04 20:17:32 oes
258 * Revision 1.67 2002/03/04 18:18:57 oes
259 * - Removed _DEBUG mode
260 * - Cleand up cmdline parsing
261 * - Introduced --no-daemon, --pidfile options
262 * - Cleaned up signal handling:
263 * - Terminate cleanly on INT, TERM and ABRT
264 * - Schedule logfile for re-opening on HUP
265 * - Ignore CHLD and PIPE
266 * - Leave the rest with their default handlers
267 * - Uniform handler registration
268 * - Added usage() function
269 * - Played styleguide police
271 * Revision 1.66 2002/03/03 15:06:55 oes
272 * Re-enabled automatic config reloading
274 * Revision 1.65 2002/03/03 14:49:11 oes
275 * Fixed CLF logging: Now uses client's original HTTP request
277 * Revision 1.64 2002/03/03 09:18:03 joergs
278 * Made jumbjuster work on AmigaOS again.
280 * Revision 1.63 2002/03/02 04:14:50 david__schmidt
281 * Clean up a little CRLF unpleasantness that suddenly appeared
283 * Revision 1.62 2002/02/20 23:17:23 jongfoster
284 * Detecting some out-of memory conditions and exiting with a log message.
286 * Revision 1.61 2002/01/17 21:01:52 jongfoster
287 * Moving all our URL and URL pattern parsing code to urlmatch.c.
289 * Revision 1.60 2001/12/30 14:07:32 steudten
290 * - Add signal handling (unix)
291 * - Add SIGHUP handler (unix)
292 * - Add creation of pidfile (unix)
293 * - Add action 'top' in rc file (RH)
294 * - Add entry 'SIGNALS' to manpage
295 * - Add exit message to logfile (unix)
297 * Revision 1.59 2001/12/13 14:07:18 oes
298 * Fixed Bug: 503 error page now sent OK
300 * Revision 1.58 2001/11/30 23:37:24 jongfoster
301 * Renaming the Win32 config file to config.txt - this is almost the
302 * same as the corresponding UNIX name "config"
304 * Revision 1.57 2001/11/16 00:47:43 jongfoster
305 * Changing the tty-disconnection code to use setsid().
307 * Revision 1.56 2001/11/13 20:20:54 jongfoster
308 * Tabs->spaces, fixing a bug with missing {} around an if()
310 * Revision 1.55 2001/11/13 20:14:53 jongfoster
311 * Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
313 * Revision 1.54 2001/11/07 00:03:14 steudten
314 * Give reliable return value if an error
315 * occurs not just 0 with new daemon mode.
317 * Revision 1.53 2001/11/05 21:41:43 steudten
318 * Add changes to be a real daemon just for unix os.
319 * (change cwd to /, detach from controlling tty, set
320 * process group and session leader to the own process.
322 * Add some fatal-error log message for failed malloc().
323 * Add '-d' if compiled with 'configure --with-debug' to
324 * enable debug output.
326 * Revision 1.52 2001/10/26 20:11:20 jongfoster
327 * Fixing type mismatch
329 * Revision 1.51 2001/10/26 17:38:28 oes
332 * Revision 1.50 2001/10/25 03:40:48 david__schmidt
333 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
334 * threads to call select() simultaneously. So, it's time to do a real, live,
335 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
336 * (native). Both versions will work, but using __OS2__ offers multi-threading.
338 * Revision 1.49 2001/10/23 21:41:35 jongfoster
339 * Added call to initialize the (statically-allocated of course)
340 * "out of memory" CGI response.
342 * Revision 1.48 2001/10/10 19:56:46 jongfoster
343 * Moving some code that wasn't cookie-related out of an #ifdef
346 * Revision 1.47 2001/10/10 16:44:36 oes
347 * Added CONNECT destination port limitation check
349 * Revision 1.46 2001/10/08 15:17:41 oes
350 * Re-enabled SSL forwarding
352 * Revision 1.45 2001/10/07 15:42:11 oes
353 * Replaced 6 boolean members of csp with one bitmap (csp->flags)
355 * Moved downgrading of the HTTP version from parse_http_request to
356 * chat(), since we can't decide if it is necessary before we have
357 * determined the actions for the URL. The HTTP command is now
358 * *always* re-built so the repairs need no longer be special-cased.
360 * filter_popups now gets a csp pointer so it can raise the new
361 * CSP_FLAG_MODIFIED flag.
365 * Added configurable size limit for the IOB. If the IOB grows so
366 * large that the next read would exceed the limit, the header
367 * is generated, and the header & unfiltered buffer are flushed
368 * to the client. Chat then continues in non-buffering,
369 * non-filtering body mode.
371 * Revision 1.44 2001/10/02 18:13:57 oes
374 * Revision 1.43 2001/10/02 15:32:13 oes
375 * Moved generation of hdr
377 * Revision 1.42 2001/09/21 23:02:02 david__schmidt
378 * Cleaning up 2 compiler warnings on OS/2.
380 * Revision 1.41 2001/09/16 17:05:14 jongfoster
381 * Removing unused #include showarg.h
383 * Revision 1.40 2001/09/16 15:41:45 jongfoster
384 * Fixing signed/unsigned comparison warning.
386 * Revision 1.39 2001/09/16 13:21:27 jongfoster
387 * Changes to use new list functions.
389 * Revision 1.38 2001/09/16 13:01:46 jongfoster
390 * Removing redundant function call that zeroed zalloc()'d memory.
392 * Revision 1.37 2001/09/10 11:12:24 oes
393 * Deleted unused variable
395 * Revision 1.36 2001/09/10 10:56:15 oes
396 * Silenced compiler warnings
398 * Revision 1.35 2001/07/31 14:44:22 oes
399 * Deleted unused size parameter from filter_popups()
401 * Revision 1.34 2001/07/30 22:08:36 jongfoster
402 * Tidying up #defines:
403 * - All feature #defines are now of the form FEATURE_xxx
404 * - Permanently turned off WIN_GUI_EDIT
405 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
407 * Revision 1.33 2001/07/29 19:32:00 jongfoster
408 * Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
410 * Revision 1.32 2001/07/29 18:47:05 jongfoster
411 * Adding missing #include "loadcfg.h"
413 * Revision 1.31 2001/07/29 12:17:48 oes
414 * Applied pthread fix by Paul Lieverse
416 * Revision 1.30 2001/07/25 22:57:13 jongfoster
417 * __BEOS__ no longer overrides FEATURE_PTHREAD.
418 * This is because FEATURE_PTHREAD will soon be widely used, so I
419 * want to keep it simple.
421 * Revision 1.29 2001/07/24 12:47:06 oes
422 * Applied BeOS support update by Eugenia
424 * Revision 1.28 2001/07/23 13:26:12 oes
425 * Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
427 * Revision 1.27 2001/07/19 19:09:47 haroon
428 * - Added code to take care of the situation where while processing the first
429 * server response (which includes the server header), after finding the end
430 * of the headers we were not looking past the end of the headers for
431 * content modification. I enabled it for filter_popups.
432 * Someone else should look to see if other similar operations should be
433 * done to the discarded portion of the buffer.
435 * Note 2001/07/20: No, the other content modification mechanisms will process
436 * the whole iob later anyway. --oes
438 * Revision 1.26 2001/07/18 12:31:36 oes
441 * Revision 1.25 2001/07/15 19:43:49 jongfoster
442 * Supports POSIX threads.
443 * Also removed some unused #includes.
445 * Revision 1.24 2001/07/13 14:00:40 oes
446 * - Generic content modification scheme:
447 * Each feature has its own applicability flag that is set
448 * from csp->action->flags.
449 * Replaced the "filtering" int flag , by a function pointer
450 * "content_filter" to the function that will do the content
451 * modification. If it is != NULL, the document will be buffered
452 * and processed through *content_filter, which must set
453 * csp->content_length and return a modified copy of the body
454 * or return NULL (on failiure).
455 * - Changed csp->is_text to the more generic bitmap csp->content_type
456 * which can currently take the valued CT_TEXT or CT_GIF
458 * - Removed all #ifdef PCRS
460 * Revision 1.23 2001/07/02 02:28:25 iwanttokeepanon
461 * Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
462 * the `block_acl' call. This prevents a compilation error when the user
463 * does not wish to use the "ACL" feature.
465 * Revision 1.22 2001/06/29 21:45:41 oes
466 * Indentation, CRLF->LF, Tab-> Space
468 * Revision 1.21 2001/06/29 13:29:36 oes
469 * - Cleaned up, improved comments
470 * - Unified all possible interceptors (CGI,
471 * block, trust, fast_redirect) in one
472 * place, with one (CGI) answer generation
473 * mechansim. Much clearer now.
474 * - Removed the GIF image generation, which
475 * is now done in filters.c:block_url()
476 * - Made error conditions like domain lookup
477 * failiure or (various) problems while talking
478 * to the server use cgi.c:error_response()
479 * instead of generating HTML/HTTP in chat() (yuck!)
480 * - Removed logentry from cancelled commit
482 * Revision 1.20 2001/06/09 10:55:28 jongfoster
483 * Changing BUFSIZ ==> BUFFER_SIZE
485 * Revision 1.19 2001/06/07 23:12:52 jongfoster
486 * Replacing function pointer in struct gateway with a directly
487 * called function forwarded_connect().
488 * Replacing struct gateway with struct forward_spec
490 * Revision 1.18 2001/06/03 19:12:16 oes
491 * introduced new cgi handling
493 * Revision 1.17 2001/06/01 20:07:23 jongfoster
494 * Now uses action +image-blocker{} rather than config->tinygif
496 * Revision 1.16 2001/06/01 18:49:17 jongfoster
497 * Replaced "list_share" with "list" - the tiny memory gain was not
498 * worth the extra complexity.
500 * Revision 1.15 2001/05/31 21:24:47 jongfoster
501 * Changed "permission" to "action" throughout.
502 * Removed DEFAULT_USER_AGENT - it must now be specified manually.
503 * Moved vanilla wafer check into chat(), since we must now
504 * decide whether or not to add it based on the URL.
506 * Revision 1.14 2001/05/29 20:14:01 joergs
507 * AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
510 * Revision 1.13 2001/05/29 09:50:24 jongfoster
511 * Unified blocklist/imagelist/permissionslist.
512 * File format is still under discussion, but the internal changes
515 * Also modified interceptor behaviour:
516 * - We now intercept all URLs beginning with one of the following
517 * prefixes (and *only* these prefixes):
519 * * http://ijbswa.sf.net/config/
520 * * http://ijbswa.sourceforge.net/config/
521 * - New interceptors "home page" - go to http://i.j.b/ to see it.
522 * - Internal changes so that intercepted and fast redirect pages
523 * are not replaced with an image.
524 * - Interceptors now have the option to send a binary page direct
525 * to the client. (i.e. ijb-send-banner uses this)
526 * - Implemented show-url-info interceptor. (Which is why I needed
527 * the above interceptors changes - a typical URL is
528 * "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
529 * The previous mechanism would not have intercepted that, and
530 * if it had been intercepted then it then it would have replaced
533 * Revision 1.12 2001/05/27 22:17:04 oes
535 * - re_process_buffer no longer writes the modified buffer
536 * to the client, which was very ugly. It now returns the
537 * buffer, which it is then written by chat.
539 * - content_length now adjusts the Content-Length: header
540 * for modified documents rather than crunch()ing it.
541 * (Length info in csp->content_length, which is 0 for
542 * unmodified documents)
544 * - For this to work, sed() is called twice when filtering.
546 * Revision 1.11 2001/05/26 17:27:53 jongfoster
547 * Added support for CLF and fixed LOG_LEVEL_LOG.
548 * Also did CRLF->LF fix of my previous patch.
550 * Revision 1.10 2001/05/26 15:26:15 jongfoster
551 * ACL feature now provides more security by immediately dropping
552 * connections from untrusted hosts.
554 * Revision 1.9 2001/05/26 00:28:36 jongfoster
555 * Automatic reloading of config file.
556 * Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
557 * Most of the global variables have been moved to a new
558 * struct configuration_spec, accessed through csp->config->globalname
559 * Most of the globals remaining are used by the Win32 GUI.
561 * Revision 1.8 2001/05/25 22:43:18 jongfoster
562 * Fixing minor memory leak and buffer overflow.
564 * Revision 1.7 2001/05/25 22:34:30 jongfoster
567 * Revision 1.6 2001/05/23 00:13:58 joergs
568 * AmigaOS support fixed.
570 * Revision 1.5 2001/05/22 18:46:04 oes
572 * - Enabled filtering banners by size rather than URL
573 * by adding patterns that replace all standard banner
574 * sizes with the "Junkbuster" gif to the re_filterfile
576 * - Enabled filtering WebBugs by providing a pattern
577 * which kills all 1x1 images
579 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
580 * which is selected by the (nonstandard and therefore
581 * capital) letter 'U' in the option string.
582 * It causes the quantifiers to be ungreedy by default.
583 * Appending a ? turns back to greedy (!).
585 * - Added a new interceptor ijb-send-banner, which
586 * sends back the "Junkbuster" gif. Without imagelist or
587 * MSIE detection support, or if tinygif = 1, or the
588 * URL isn't recognized as an imageurl, a lame HTML
589 * explanation is sent instead.
591 * - Added new feature, which permits blocking remote
592 * script redirects and firing back a local redirect
594 * The feature is conditionally compiled, i.e. it
595 * can be disabled with --disable-fast-redirects,
596 * plus it must be activated by a "fast-redirects"
597 * line in the config file, has its own log level
598 * and of course wants to be displayed by show-proxy-args
599 * Note: Boy, all the #ifdefs in 1001 locations and
600 * all the fumbling with configure.in and acconfig.h
601 * were *way* more work than the feature itself :-(
603 * - Because a generic redirect template was needed for
604 * this, tinygif = 3 now uses the same.
606 * - Moved GIFs, and other static HTTP response templates
611 * - Removed some >400 CRs again (Jon, you really worked
614 * Revision 1.4 2001/05/21 19:34:01 jongfoster
615 * Made failure to bind() a fatal error.
617 * Revision 1.3 2001/05/20 01:21:20 jongfoster
618 * Version 2.9.4 checkin.
619 * - Merged popupfile and cookiefile, and added control over PCRS
620 * filtering, in new "permissionsfile".
621 * - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
622 * file error you now get a message box (in the Win32 GUI) rather
623 * than the program exiting with no explanation.
624 * - Made killpopup use the PCRS MIME-type checking and HTTP-header
626 * - Removed tabs from "config"
627 * - Moved duplicated url parsing code in "loaders.c" to a new funcition.
628 * - Bumped up version number.
630 * Revision 1.2 2001/05/17 22:34:44 oes
631 * - Added hint on GIF char array generation to jcc.c
632 * - Cleaned CRLF's from the sources and related files
633 * - Repaired logging for REF and FRC
635 * Revision 1.1.1.1 2001/05/15 13:58:56 oes
636 * Initial import of version 2.9.3 source tree
639 *********************************************************************/
645 #include <sys/types.h>
652 #ifdef FEATURE_PTHREAD
654 #endif /* def FEATURE_PTHREAD */
657 # ifndef FEATURE_PTHREAD
661 # include <windows.h>
662 # include <process.h>
663 # endif /* ndef FEATURE_PTHREAD */
666 # ifndef _WIN_CONSOLE
668 # endif /* ndef _WIN_CONSOLE */
669 # include "w32svrapi.h"
671 #else /* ifndef _WIN32 */
673 # if !defined (__OS2__)
675 # include <sys/wait.h>
676 # endif /* ndef __OS2__ */
677 # include <sys/time.h>
678 # include <sys/stat.h>
679 # include <sys/ioctl.h>
682 #include <sys/termios.h>
693 # include <socket.h> /* BeOS has select() for sockets only. */
694 # include <OS.h> /* declarations for threads and stuff. */
697 # if defined(__EMX__) || defined(__OS2__)
698 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
703 #define bzero(B,N) memset(B,0x00,n)
718 #include "killpopup.h"
719 #include "miscutil.h"
721 #include "jbsockets.h"
726 #include "urlmatch.h"
728 const char jcc_h_rcs[] = JCC_H_VERSION;
729 const char project_h_rcs[] = PROJECT_H_VERSION;
732 struct client_state clients[1];
733 struct file_list files[1];
735 #ifdef FEATURE_STATISTICS
736 int urls_read = 0; /* total nr of urls read inc rejected */
737 int urls_rejected = 0; /* total nr of urls rejected */
738 #endif /* def FEATURE_STATISTICS */
740 #ifdef FEATURE_GRACEFUL_TERMINATION
744 static void listen_loop(void);
745 static void chat(struct client_state *csp);
747 void serve(struct client_state *csp);
748 #else /* ifndef AMIGA */
749 static void serve(struct client_state *csp);
750 #endif /* def AMIGA */
753 static int32 server_thread(void *data);
754 #endif /* def __BEOS__ */
757 #define sleep(N) Sleep(((N) * 1000))
761 #define sleep(N) DosSleep(((N) * 100))
766 * Hit OSX over the head with a hammer. Protect all *_r functions.
768 pthread_mutex_t gmtime_mutex;
769 pthread_mutex_t localtime_mutex;
770 pthread_mutex_t gethostbyaddr_mutex;
771 pthread_mutex_t gethostbyname_mutex;
772 #endif /* def OSX_DARWIN */
774 #ifdef FEATURE_PTHREAD
775 pthread_mutex_t log_mutex;
776 pthread_mutex_t log_init_mutex;
777 #endif /* FEATURE_PTHREAD */
779 #if defined(unix) || defined(__EMX__)
780 const char *basedir = NULL;
781 const char *pidfile = NULL;
782 int received_hup_signal = 0;
783 #endif /* defined unix */
785 /* The vanilla wafer. */
786 static const char VANILLA_WAFER[] =
787 "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
788 "Do_not_send_me_any_copyrighted_information_other_than_the_"
789 "document_that_I_am_requesting_or_any_of_its_necessary_components._"
790 "In_particular_do_not_send_me_any_cookies_that_"
791 "are_subject_to_a_claim_of_copyright_by_anybody._"
792 "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
793 "(copyright_or_otherwise)_applying_to_any_cookie._";
796 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
797 /*********************************************************************
799 * Function : sig_handler
801 * Description : Signal handler for different signals.
802 * Exit gracefully on ABRT, TERM and INT
803 * or set a flag that will cause the errlog
804 * to be reopened by the main thread on HUP.
807 * 1 : the_signal = the signal cause this function to call
811 *********************************************************************/
812 static void sig_handler(int the_signal)
819 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
827 received_hup_signal = 1;
832 * We shouldn't be here, unless we catch signals
833 * in main() that we can't handle here!
835 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
843 /*********************************************************************
847 * Description : Once a connection to the client has been accepted,
848 * this function is called (via serve()) to handle the
849 * main business of the communication. When this
850 * function returns, the caller must close the client
854 * 1 : csp = Current client state (buffers, headers, etc...)
856 * Returns : On success, the number of bytes written are returned (zero
857 * indicates nothing was written). On error, -1 is returned,
858 * and errno is set appropriately. If count is zero and the
859 * file descriptor refers to a regular file, 0 will be
860 * returned without causing any other effect. For a special
861 * file, the results are not portable.
863 *********************************************************************/
864 static void chat(struct client_state *csp)
867 * This next lines are a little ugly, but they simplifies the if statements
868 * below. Basically if TOGGLE, then we want the if to test if the
869 * CSP_FLAG_TOGGLED_ON flag ist set, else we don't. And if FEATURE_FORCE_LOAD,
870 * then we want the if to test for CSP_FLAG_FORCED , else we don't
872 #ifdef FEATURE_TOGGLE
873 # define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
874 #else /* ifndef FEATURE_TOGGLE */
875 # define IS_TOGGLED_ON_AND
876 #endif /* ndef FEATURE_TOGGLE */
877 #ifdef FEATURE_FORCE_LOAD
878 # define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
879 #else /* ifndef FEATURE_FORCE_LOAD */
880 # define IS_NOT_FORCED_AND
881 #endif /* def FEATURE_FORCE_LOAD */
883 #define IS_ENABLED_AND IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
885 char buf[BUFFER_SIZE];
893 int ms_iis5_hack = 0;
895 unsigned int socks_retries = 0;
896 const struct forward_spec * fwd;
897 struct http_request *http;
898 int len; /* for buffer sizes */
899 #ifdef FEATURE_KILL_POPUPS
900 int block_popups; /* bool, 1==will block popups */
901 int block_popups_now = 0; /* bool, 1==currently blocking popups */
902 #endif /* def FEATURE_KILL_POPUPS */
904 int pcrs_filter; /* bool, 1==will filter through pcrs */
905 int gif_deanimate; /* bool, 1==will deanimate gifs */
906 int jpeg_inspect; /* bool, 1==will inspect jpegs */
908 /* Function that does the content filtering for the current request */
909 char *(*content_filter)() = NULL;
911 /* Skeleton for HTTP response, if we should intercept the request */
912 struct http_response *rsp;
917 * Read the client's request. Note that since we're not using select() we
918 * could get blocked here if a client connected, then didn't say anything!
923 len = read_socket(csp->cfd, buf, sizeof(buf));
925 if (len <= 0) break; /* error! */
928 * If there is no memory left for buffering the
929 * request, there is nothing we can do but hang up
931 if (add_to_iob(csp, buf, len))
936 req = get_header(csp);
940 break; /* no HTTP request! */
945 continue; /* more to come! */
948 #ifdef FEATURE_FORCE_LOAD
949 /* If this request contains the FORCE_PREFIX,
950 * better get rid of it now and set the force flag --oes
953 if (strstr(req, FORCE_PREFIX))
955 strclean(req, FORCE_PREFIX);
956 log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
957 csp->flags |= CSP_FLAG_FORCED;
960 #endif /* def FEATURE_FORCE_LOAD */
962 parse_http_request(req, http, csp);
967 if (http->cmd == NULL)
969 strcpy(buf, CHEADER);
970 write_socket(csp->cfd, buf, strlen(buf));
972 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
974 free_http_request(http);
978 /* decide how to route the HTTP request */
980 if ((fwd = forward_url(http, csp)) == NULL)
982 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
983 /* Never get here - LOG_LEVEL_FATAL causes program exit */
986 /* build the http request to send to the server
987 * we have to do one of the following:
989 * create = use the original HTTP request to create a new
990 * HTTP request that has either the path component
991 * without the http://domainspec (w/path) or the
992 * full orininal URL (w/url)
993 * Note that the path and/or the HTTP version may
994 * have been altered by now.
996 * connect = Open a socket to the host:port of the server
997 * and short-circuit server and client socket.
999 * pass = Pass the request unchanged if forwarding a CONNECT
1000 * request to a parent proxy. Note that we'll be sending
1001 * the CFAIL message ourselves if connecting to the parent
1002 * fails, but we won't send a CSUCCEED message if it works,
1003 * since that would result in a double message (ours and the
1004 * parent's). After sending the request to the parent, we simply
1007 * here's the matrix:
1010 * +--------+--------+
1012 * 0 | create | connect|
1014 * Forwarding +--------+--------+
1016 * 1 | create | pass |
1018 * +--------+--------+
1023 * Determine the actions for this URL
1025 #ifdef FEATURE_TOGGLE
1026 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1028 /* Most compatible set of actions (i.e. none) */
1029 init_current_action(csp->action);
1032 #endif /* ndef FEATURE_TOGGLE */
1034 url_actions(http, csp);
1039 * Check if a CONNECT request is allowable:
1040 * In the absence of a +limit-connect action, allow only port 443.
1041 * If there is an action, allow whatever matches the specificaton.
1045 if( ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
1046 || (csp->action->flags & ACTION_LIMIT_CONNECT
1047 && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
1049 if (csp->action->flags & ACTION_TREAT_FORBIDDEN_CONNECTS_LIKE_BLOCKS)
1051 /* The response will violate the specs, but makes unblocking easier. */
1052 log_error(LOG_LEVEL_ERROR, "Marking suspicious CONNECT request from %s for blocking.",
1054 csp->action->flags |= ACTION_BLOCK;
1059 strcpy(buf, CFORBIDDEN);
1060 write_socket(csp->cfd, buf, strlen(buf));
1061 log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
1062 log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
1070 * Downgrade http version from 1.1 to 1.0 if +downgrade
1073 if ( (http->ssl == 0)
1074 && (!strcmpic(http->ver, "HTTP/1.1"))
1075 && (csp->action->flags & ACTION_DOWNGRADE))
1078 http->ver = strdup("HTTP/1.0");
1080 if (http->ver == NULL)
1082 log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
1087 * Save a copy of the original request for logging
1089 http->ocmd = strdup(http->cmd);
1091 if (http->ocmd == NULL)
1093 log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
1097 * (Re)build the HTTP request for non-SSL requests.
1098 * If forwarding, use the whole URL, else, use only the path.
1104 http->cmd = strdup(http->gpc);
1105 string_append(&http->cmd, " ");
1107 if (fwd->forward_host)
1109 string_append(&http->cmd, http->url);
1113 string_append(&http->cmd, http->path);
1115 string_append(&http->cmd, " ");
1116 string_append(&http->cmd, http->ver);
1118 if (http->cmd == NULL)
1120 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1122 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", http->cmd);
1124 enlist(csp->headers, http->cmd);
1128 * If the user has not supplied any wafers, and the user has not
1129 * told us to suppress the vanilla wafer, then send the vanilla wafer.
1131 if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
1132 && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
1134 enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
1138 #ifdef FEATURE_KILL_POPUPS
1139 block_popups = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1140 #endif /* def FEATURE_KILL_POPUPS */
1142 pcrs_filter = (csp->rlist != NULL) && /* There are expressions to be used */
1143 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1145 gif_deanimate = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1147 jpeg_inspect = ((csp->action->flags & ACTION_JPEG_INSPECT) != 0);
1149 /* grab the rest of the client's headers */
1153 if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
1155 len = read_socket(csp->cfd, buf, sizeof(buf));
1158 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1163 * If there is no memory left for buffering the
1164 * request, there is nothing we can do but hang up
1166 if (add_to_iob(csp, buf, len))
1173 if (p == NULL) break;
1175 enlist(csp->headers, p);
1180 * We have a request. Now, check to see if we need to
1181 * intercept it, i.e. If ..
1185 /* We may not forward the request by rfc2616 sect 14.31 */
1186 (NULL != (rsp = direct_response(csp)))
1188 /* or a CGI call was detected and answered */
1189 || (NULL != (rsp = dispatch_cgi(csp)))
1191 /* or we are enabled and... */
1192 || (IS_ENABLED_AND (
1194 /* ..the request was blocked */
1195 ( NULL != (rsp = block_url(csp)))
1197 /* ..or untrusted */
1198 #ifdef FEATURE_TRUST
1199 || ( NULL != (rsp = trust_url(csp)))
1200 #endif /* def FEATURE_TRUST */
1202 /* ..or a fast redirect kicked in */
1203 #ifdef FEATURE_FAST_REDIRECTS
1204 || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
1205 (NULL != (rsp = redirect_url(csp))))
1206 #endif /* def FEATURE_FAST_REDIRECTS */
1210 /* Write the answer to the client */
1211 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1212 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1214 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1217 #ifdef FEATURE_STATISTICS
1218 /* Count as a rejected request */
1219 csp->flags |= CSP_FLAG_REJECTED;
1220 #endif /* def FEATURE_STATISTICS */
1222 /* Log (FIXME: All intercept reasons appear as "crunch" with Status 200) */
1223 log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
1224 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
1226 /* Clean up and return */
1227 free_http_response(rsp);
1231 hdr = sed(client_patterns, add_client_headers, csp);
1234 /* FIXME Should handle error properly */
1235 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1238 list_remove_all(csp->headers);
1240 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1242 if (fwd->forward_host)
1244 log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1245 fwd->forward_host, fwd->forward_port, http->hostport);
1249 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1252 /* here we connect to the server, gateway, or the forwarder */
1254 while ( (csp->sfd = forwarded_connect(fwd, http, csp))
1255 && (errno == EINVAL) && (socks_retries++ < 3))
1257 log_error(LOG_LEVEL_ERROR, "failed request #%u to connect to %s. Trying again.",
1258 socks_retries, http->hostport);
1261 if (csp->sfd == JB_INVALID_SOCKET)
1263 log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1266 if (errno == EINVAL)
1268 rsp = error_response(csp, "no-such-domain", errno);
1270 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1271 csp->ip_addr_str, http->ocmd);
1275 rsp = error_response(csp, "connect-failed", errno);
1277 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1278 csp->ip_addr_str, http->ocmd);
1282 /* Write the answer to the client */
1285 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1286 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1288 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1292 free_http_response(rsp);
1297 log_error(LOG_LEVEL_CONNECT, "OK");
1299 if (fwd->forward_host || (http->ssl == 0))
1301 /* write the client's (modified) header to the server
1302 * (along with anything else that may be in the buffer)
1305 if (write_socket(csp->sfd, hdr, strlen(hdr))
1306 || (flush_socket(csp->sfd, csp) < 0))
1308 log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1311 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1312 csp->ip_addr_str, http->ocmd);
1314 rsp = error_response(csp, "connect-failed", errno);
1318 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1319 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1321 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1325 free_http_response(rsp);
1333 * We're running an SSL tunnel and we're not forwarding,
1334 * so just send the "connect succeeded" message to the
1335 * client, flush the rest, and get out of the way.
1337 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1338 csp->ip_addr_str, http->ocmd);
1340 if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1348 /* we're finished with the client's header */
1351 maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1353 /* pass data between the client and server
1354 * until one or the other shuts down the connection.
1363 * FD_ZERO here seems to point to an errant macro which crashes.
1364 * So do this by hand for now...
1366 memset(&rfds,0x00,sizeof(fd_set));
1370 FD_SET(csp->cfd, &rfds);
1371 FD_SET(csp->sfd, &rfds);
1373 n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
1377 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1381 /* this is the body of the browser's request
1382 * just read it and write it.
1385 if (FD_ISSET(csp->cfd, &rfds))
1387 len = read_socket(csp->cfd, buf, sizeof(buf));
1391 break; /* "game over, man" */
1394 if (write_socket(csp->sfd, buf, (size_t)len))
1396 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1403 * The server wants to talk. It could be the header or the body.
1404 * If `hdr' is null, then it's the header otherwise it's the body.
1405 * FIXME: Does `hdr' really mean `host'? No.
1409 if (FD_ISSET(csp->sfd, &rfds))
1412 len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1416 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1418 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1419 csp->ip_addr_str, http->ocmd);
1421 rsp = error_response(csp, "connect-failed", errno);
1425 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1426 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1428 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1432 free_http_response(rsp);
1436 /* Add a trailing zero. This lets filter_popups
1437 * use string operations.
1441 #ifdef FEATURE_KILL_POPUPS
1442 /* Filter the popups on this read. */
1443 if (block_popups_now)
1445 filter_popups(buf, csp);
1447 #endif /* def FEATURE_KILL_POPUPS */
1449 /* Normally, this would indicate that we've read
1450 * as much as the server has sent us and we can
1451 * close the client connection. However, Microsoft
1452 * in its wisdom has released IIS/5 with a bug that
1453 * prevents it from sending the trailing \r\n in
1454 * a 302 redirect header (and possibly other headers).
1455 * To work around this if we've haven't parsed
1456 * a full header we'll append a trailing \r\n
1457 * and see if this now generates a valid one.
1459 * This hack shouldn't have any impacts. If we've
1460 * already transmitted the header or if this is a
1461 * SSL connection, then we won't bother with this
1462 * hack. So we only work on partially received
1463 * headers. If we append a \r\n and this still
1464 * doesn't generate a valid header, then we won't
1465 * transmit anything to the client.
1470 if (server_body || http->ssl)
1473 * If we have been buffering up the document,
1474 * now is the time to apply content modification
1475 * and send the result to the client.
1480 * If the content filter fails, use the original
1481 * buffer and length.
1482 * (see p != NULL ? p : csp->iob->cur below)
1484 if (NULL == (p = (*content_filter)(csp)))
1486 csp->content_length = csp->iob->eod - csp->iob->cur;
1489 hdr = sed(server_patterns_light, NULL, csp);
1493 /* FIXME Should handle error properly */
1494 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1497 if (write_socket(csp->cfd, hdr, strlen(hdr))
1498 || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1500 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1510 break; /* "game over, man" */
1514 * This is NOT the body, so
1515 * Let's pretend the server just sent us a blank line.
1517 len = sprintf(buf, "\r\n");
1520 * Now, let the normal header parsing algorithm below do its
1521 * job. If it fails, we'll exit instead of continuing.
1528 * If this is an SSL connection or we're in the body
1529 * of the server document, just write it to the client,
1530 * unless we need to buffer the body for later content-filtering
1533 if (server_body || http->ssl)
1538 * If there is no memory left for buffering the content, or the buffer limit
1539 * has been reached, switch to non-filtering mode, i.e. make & write the
1540 * header, flush the iob and buf, and get out of the way.
1542 if (add_to_iob(csp, buf, len))
1547 log_error(LOG_LEVEL_ERROR, "Flushing header and buffers. Stepping back from filtering.");
1549 hdr = sed(server_patterns, add_server_headers, csp);
1553 * Memory is too tight to even generate the header.
1554 * Send our static "Out-of-memory" page.
1556 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
1557 rsp = cgi_error_memory();
1559 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1560 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1562 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1567 hdrlen = strlen(hdr);
1569 if (write_socket(csp->cfd, hdr, hdrlen)
1570 || ((flushed = flush_socket(csp->cfd, csp)) < 0)
1571 || (write_socket(csp->cfd, buf, (size_t) len)))
1573 log_error(LOG_LEVEL_CONNECT, "Flush header and buffers to client failed: %E");
1579 byte_count += hdrlen + flushed + len;
1581 content_filter = NULL;
1588 if (write_socket(csp->cfd, buf, (size_t)len))
1590 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1599 /* we're still looking for the end of the
1600 * server's header ... (does that make header
1601 * parsing an "out of body experience" ?
1605 * buffer up the data we just read. If that fails,
1606 * there's little we can do but send our static
1607 * out-of-memory page.
1609 if (add_to_iob(csp, buf, len))
1611 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
1612 rsp = cgi_error_memory();
1614 if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1615 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1617 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1622 /* get header lines from the iob */
1624 while ((p = get_header(csp)) != NULL)
1628 /* see following note */
1631 enlist(csp->headers, p);
1635 /* NOTE: there are no "empty" headers so
1636 * if the pointer `p' is not NULL we must
1637 * assume that we reached the end of the
1638 * buffer before we hit the end of the header.
1645 /* Well, we tried our MS IIS/5
1646 * hack and it didn't work.
1647 * The header is incomplete
1648 * and there isn't anything
1649 * we can do about it.
1655 /* Since we have to wait for
1656 * more from the server before
1657 * we can parse the headers
1658 * we just continue here.
1664 /* we have now received the entire header.
1665 * filter it and send the result to the client
1668 hdr = sed(server_patterns, add_server_headers, csp);
1671 /* FIXME Should handle error properly */
1672 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1675 #ifdef FEATURE_KILL_POPUPS
1676 /* Start blocking popups if appropriate. */
1678 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1679 !http->ssl && /* We talk plaintext */
1680 block_popups) /* Policy allows */
1682 block_popups_now = 1;
1684 * Filter the part of the body that came in the same read
1685 * as the last headers:
1687 filter_popups(csp->iob->cur, csp);
1690 #endif /* def FEATURE_KILL_POPUPS */
1692 /* Buffer and pcrs filter this if appropriate. */
1694 if ((csp->content_type & CT_TEXT) && /* It's a text / * MIME-Type */
1695 !http->ssl && /* We talk plaintext */
1696 pcrs_filter) /* Policy allows */
1698 content_filter = pcrs_filter_response;
1701 /* Buffer and gif_deanimate this if appropriate. */
1703 if ((csp->content_type & CT_GIF) && /* It's an image/gif MIME-Type */
1704 !http->ssl && /* We talk plaintext */
1705 gif_deanimate) /* Policy allows */
1707 content_filter = gif_deanimate_response;
1710 /* Buffer and jpg_inspect this if appropriate. */
1712 if ((csp->content_type & CT_JPEG) && /* It's an image/jpeg MIME-Type */
1713 !http->ssl && /* We talk plaintext */
1714 jpeg_inspect) /* Policy allows */
1716 content_filter = jpeg_inspect_response;
1720 * Only write if we're not buffering for content modification
1722 if (!content_filter)
1724 /* write the server's (modified) header to
1725 * the client (along with anything else that
1726 * may be in the buffer)
1729 if (write_socket(csp->cfd, hdr, strlen(hdr))
1730 || ((len = flush_socket(csp->cfd, csp)) < 0))
1732 log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1734 /* the write failed, so don't bother
1735 * mentioning it to the client...
1736 * it probably can't hear us anyway.
1745 /* we're finished with the server's header */
1750 /* If this was a MS IIS/5 hack then it means
1751 * the server has already closed the
1752 * connection. Nothing more to read. Time
1763 return; /* huh? we should never get here */
1766 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1767 csp->ip_addr_str, http->ocmd, byte_count);
1771 /*********************************************************************
1775 * Description : This is little more than chat. We only "serve" to
1776 * to close any socket that chat may have opened.
1779 * 1 : csp = Current client state (buffers, headers, etc...)
1783 *********************************************************************/
1785 void serve(struct client_state *csp)
1786 #else /* ifndef AMIGA */
1787 static void serve(struct client_state *csp)
1788 #endif /* def AMIGA */
1791 close_socket(csp->cfd);
1793 if (csp->sfd != JB_INVALID_SOCKET)
1795 close_socket(csp->sfd);
1798 csp->flags &= ~CSP_FLAG_ACTIVE;
1804 /*********************************************************************
1806 * Function : server_thread
1808 * Description : We only exist to call `serve' in a threaded environment.
1811 * 1 : data = Current client state (buffers, headers, etc...)
1813 * Returns : Always 0.
1815 *********************************************************************/
1816 static int32 server_thread(void *data)
1818 serve((struct client_state *) data);
1825 /*********************************************************************
1829 * Description : Print usage info & exit.
1831 * Parameters : Pointer to argv[0] for identifying ourselves
1835 *********************************************************************/
1836 void usage(const char *myname)
1838 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
1840 "Usage: %s [--help] [--version] [configfile]\n"
1842 "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1844 "Aborting.\n", myname);
1851 /*********************************************************************
1855 * Description : Load the config file and start the listen loop.
1856 * This function is a lot more *sane* with the `load_config'
1857 * and `listen_loop' functions; although it stills does
1858 * a *little* too much for my taste.
1861 * 1 : argc = Number of parameters (including $0).
1862 * 2 : argv = Array of (char *)'s to the parameters.
1864 * Returns : 1 if : can't open config file, unrecognized directive,
1865 * stats requested in multi-thread mode, can't open the
1866 * log file, can't open the jar file, listen port is invalid,
1867 * any load fails, and can't bind port.
1869 * Else main never returns, the process must be signaled
1870 * to terminate execution. Or, on Windows, use the
1871 * "File", "Exit" menu option.
1873 *********************************************************************/
1875 int real_main(int argc, const char *argv[])
1877 int main(int argc, const char *argv[])
1882 struct passwd *pw = NULL;
1883 struct group *grp = NULL;
1892 #if !defined(_WIN32)
1900 * Parse the command line arguments
1902 while (++argc_pos < argc)
1905 /* Check to see if the service must be installed or uninstalled */
1906 if (strncmp(argv[argc_pos], "--install", 9) == 0)
1908 const char *pName = argv[argc_pos] + 9;
1911 exit( (install_service(pName)) ? 0 : 1 );
1913 else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
1915 const char *pName = argv[argc_pos] + 11;
1918 exit((uninstall_service(pName)) ? 0 : 1);
1920 else if (strcmp(argv[argc_pos], "--service" ) == 0)
1922 bRunAsService = TRUE;
1923 w32_set_service_cwd();
1924 atexit(w32_service_exit_notify);
1927 #endif /* defined(_WIN32) */
1930 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1932 if (strcmp(argv[argc_pos], "--help") == 0)
1937 else if(strcmp(argv[argc_pos], "--version") == 0)
1939 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1945 else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1950 else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1952 if (++argc_pos == argc) usage(argv[0]);
1953 pidfile = strdup(argv[argc_pos]);
1956 else if (strcmp(argv[argc_pos], "--user" ) == 0)
1958 if (++argc_pos == argc) usage(argv[argc_pos]);
1960 if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1963 if (NULL == (grp = getgrnam(p)))
1965 log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1969 if (NULL == (pw = getpwnam(argv[argc_pos])))
1971 log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1974 if (p != NULL) *--p = '\0';
1977 else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
1982 #endif /* defined(unix) */
1983 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1985 configfile = argv[argc_pos];
1988 } /* -END- while (more arguments) */
1991 if ( *configfile != '/' )
1993 char *abs_file, cwd[1024];
1995 /* make config-filename absolute here */
1996 if ( !(getcwd(cwd, sizeof(cwd))))
1998 perror("get working dir failed");
2002 if (!(basedir = strdup(cwd))
2003 || (!(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 ))))
2005 perror("malloc failed");
2008 strcpy( abs_file, basedir );
2009 strcat( abs_file, "/" );
2010 strcat( abs_file, configfile );
2011 configfile = abs_file;
2013 #endif /* defined unix */
2017 clients->next = NULL;
2021 #elif defined(_WIN32)
2027 * Prepare global mutex semaphores
2029 pthread_mutex_init(&gmtime_mutex,0);
2030 pthread_mutex_init(&localtime_mutex,0);
2031 pthread_mutex_init(&gethostbyaddr_mutex,0);
2032 pthread_mutex_init(&gethostbyname_mutex,0);
2033 #endif /* def OSX_DARWIN */
2035 #ifdef FEATURE_PTHREAD
2036 pthread_mutex_init(&log_mutex,0);
2037 pthread_mutex_init(&log_init_mutex,0);
2038 #endif /* FEATURE_PTHREAD */
2041 * Unix signal handling
2043 * Catch the abort, interrupt and terminate signals for a graceful exit
2044 * Catch the hangup signal so the errlog can be reopened.
2045 * Ignore the broken pipe signals (FIXME: Why?)
2047 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
2050 const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
2051 const int ignored_signals[] = { SIGPIPE, 0 };
2053 for (idx = 0; catched_signals[idx] != 0; idx++)
2055 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
2057 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
2061 for (idx = 0; ignored_signals[idx] != 0; idx++)
2063 if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
2065 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
2070 #else /* ifdef _WIN32 */
2071 # ifdef _WIN_CONSOLE
2073 * We *are* in a windows console app.
2074 * Print a verbose messages about FAQ's and such
2076 printf(win32_blurb);
2077 # endif /* def _WIN_CONSOLE */
2078 #endif /* def _WIN32 */
2081 /* Initialize the CGI subsystem */
2082 cgi_init_error_messages();
2085 * If runnig on unix and without the --nodaemon
2086 * option, become a daemon. I.e. fork, detach
2087 * from tty and get process group leadership
2100 if ( pid < 0 ) /* error */
2105 else if ( pid != 0 ) /* parent */
2110 * must check for errors
2111 * child died due to missing files aso
2114 wpid = waitpid( pid, &status, WNOHANG );
2123 /* Should be more portable, but not as well tested */
2128 #else /* ndef __FreeBSD__ */
2130 #endif /* ndef __FreeBSD__ */
2131 fd = open("/dev/tty", O_RDONLY);
2134 /* no error check here */
2135 ioctl( fd, TIOCNOTTY,0 );
2139 /* FIXME: should close stderr (fd 2) here too, but the test
2141 * and load config file is done in listen_loop() and puts
2142 * some messages on stderr there.
2149 } /* -END- if (!no_daemon) */
2152 * As soon as we have written the PID file, we can switch
2153 * to the user and group ID indicated by the --user option
2159 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
2161 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
2167 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
2169 if (chroot(pw->pw_dir) < 0)
2171 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
2175 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
2178 if (setuid(pw->pw_uid))
2180 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
2184 char putenv_dummy[64];
2186 strcpy(putenv_dummy, "HOME=/");
2187 if (putenv(putenv_dummy) != 0)
2189 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
2192 snprintf(putenv_dummy, 64, "USER=%s", pw->pw_name);
2193 if (putenv(putenv_dummy) != 0)
2195 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
2201 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
2204 #endif /* defined unix */
2207 /* This will be FALSE unless the command line specified --service
2211 /* Yup, so now we must attempt to establish a connection
2212 * with the service dispatcher. This will only work if this
2213 * process was launched by the service control manager to
2214 * actually run as a service. If this isn't the case, i've
2215 * known it take around 30 seconds or so for the call to return.
2218 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
2219 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
2221 /* Service has run, and at this point is now being stopped, so just return */
2226 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
2228 /* An error occurred. Usually it's because --service was wrongly specified
2229 * and we were unable to connect to the Service Control Dispatcher because
2230 * it wasn't expecting us and is therefore not listening.
2232 * For now, just continue below to call the listen_loop function.
2235 #endif /* def _WIN32 */
2245 /*********************************************************************
2247 * Function : bind_port_helper
2249 * Description : Bind the listen port. Handles logging, and aborts
2253 * 1 : config = Privoxy configuration. Specifies port
2256 * Returns : Port that was opened.
2258 *********************************************************************/
2259 static jb_socket bind_port_helper(struct configuration_spec * config)
2264 if ( (config->haddr != NULL)
2265 && (config->haddr[0] == '1')
2266 && (config->haddr[1] == '2')
2267 && (config->haddr[2] == '7')
2268 && (config->haddr[3] == '.') )
2270 log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
2273 else if (config->haddr == NULL)
2275 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
2280 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
2281 config->hport, config->haddr);
2284 result = bind_port(config->haddr, config->hport, &bfd);
2291 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2292 "There may be another Privoxy or some other "
2293 "proxy running on port %d",
2294 (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
2295 config->hport, config->hport);
2298 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2299 "The hostname is not resolvable",
2300 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2303 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
2304 (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2307 /* shouldn't get here */
2308 return JB_INVALID_SOCKET;
2311 config->need_bind = 0;
2318 /* Without this simple workaround we get this compiler warning from _beginthread
2319 * warning C4028: formal parameter 1 different from declaration
2321 void w32_service_listen_loop(void *p)
2325 #endif /* def _WIN32 */
2328 /*********************************************************************
2330 * Function : listen_loop
2332 * Description : bind the listen port and enter a "FOREVER" listening loop.
2338 *********************************************************************/
2339 static void listen_loop(void)
2341 struct client_state *csp = NULL;
2343 struct configuration_spec * config;
2345 config = load_config();
2347 bfd = bind_port_helper(config);
2349 #ifdef FEATURE_GRACEFUL_TERMINATION
2350 while (!g_terminate)
2355 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
2356 while (waitpid(-1, NULL, WNOHANG) > 0)
2358 /* zombie children */
2360 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
2363 * Free data that was used by died threads
2369 * Re-open the errlog after HUP signal
2371 if (received_hup_signal)
2373 init_error_log(Argv[0], config->logfile, config->debug);
2374 received_hup_signal = 0;
2379 #ifdef FEATURE_COOKIE_JAR
2381 * Need a workaround here: we have to fclose() the jarfile, or we die because it's
2382 * already open. I think unload_configfile() is not being run, which should do
2383 * this work. Until that can get resolved, we'll use this workaround.
2387 if (csp->config->jar)
2389 fclose(csp->config->jar);
2390 csp->config->jar = NULL;
2392 #endif /* FEATURE_COOKIE_JAR */
2393 #endif /* __OS2__ */
2395 if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
2397 log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
2401 csp->flags |= CSP_FLAG_ACTIVE;
2402 csp->sfd = JB_INVALID_SOCKET;
2404 csp->config = config = load_config();
2406 if ( config->need_bind )
2409 * Since we were listening to the "old port", we will not see
2410 * a "listen" param change until the next IJB request. So, at
2411 * least 1 more request must be made for us to find the new
2412 * setting. I am simply closing the old socket and binding the
2415 * Which-ever is correct, we will serve 1 more page via the
2416 * old settings. This should probably be a "show-proxy-args"
2417 * request. This should not be a so common of an operation
2418 * that this will hurt people's feelings.
2423 bfd = bind_port_helper(config);
2426 log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
2428 if (!accept_connection(csp, bfd))
2430 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2443 log_error(LOG_LEVEL_CONNECT, "OK");
2446 #ifdef FEATURE_TOGGLE
2447 if (global_toggle_state)
2449 csp->flags |= CSP_FLAG_TOGGLED_ON;
2451 #endif /* def FEATURE_TOGGLE */
2453 if (run_loader(csp))
2455 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2456 /* Never get here - LOG_LEVEL_FATAL causes program exit */
2460 if (block_acl(NULL,csp))
2462 log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2463 close_socket(csp->cfd);
2467 #endif /* def FEATURE_ACL */
2469 /* add it to the list of clients */
2470 csp->next = clients->next;
2471 clients->next = csp;
2473 if (config->multi_threaded)
2477 /* this is a switch () statment in the C preprocessor - ugh */
2478 #undef SELECTED_ONE_OPTION
2480 /* Use Pthreads in preference to native code */
2481 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2482 #define SELECTED_ONE_OPTION
2484 pthread_t the_thread;
2485 pthread_attr_t attrs;
2487 pthread_attr_init(&attrs);
2488 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2489 errno = pthread_create(&the_thread, &attrs,
2491 child_id = errno ? -1 : 0;
2492 pthread_attr_destroy(&attrs);
2496 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2497 #define SELECTED_ONE_OPTION
2498 child_id = _beginthread(
2499 (void (*)(void *))serve,
2504 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2505 #define SELECTED_ONE_OPTION
2506 child_id = _beginthread(
2507 (void(* _Optlink)(void*))serve,
2513 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2514 #define SELECTED_ONE_OPTION
2516 thread_id tid = spawn_thread
2517 (server_thread, "server", B_NORMAL_PRIORITY, csp);
2519 if ((tid >= 0) && (resume_thread(tid) == B_OK))
2521 child_id = (int) tid;
2530 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2531 #define SELECTED_ONE_OPTION
2532 csp->cfd = ReleaseSocket(csp->cfd, -1);
2534 if((child_id = (int)CreateNewProcTags(
2535 NP_Entry, (ULONG)server_thread,
2536 NP_Output, Output(),
2537 NP_CloseOutput, FALSE,
2538 NP_Name, (ULONG)"privoxy child",
2539 NP_StackSize, 200*1024,
2543 ((struct Task *)child_id)->tc_UserData = csp;
2544 Signal((struct Task *)child_id, SIGF_SINGLE);
2549 #if !defined(SELECTED_ONE_OPTION)
2552 /* This block is only needed when using fork().
2553 * When using threads, the server thread was
2554 * created and run by the call to _beginthread().
2556 if (child_id == 0) /* child */
2559 #ifdef FEATURE_TOGGLE
2560 int inherited_toggle_state = global_toggle_state;
2561 #endif /* def FEATURE_TOGGLE */
2566 * If we've been toggled or we've blocked the request, tell Mom
2569 #ifdef FEATURE_TOGGLE
2570 if (inherited_toggle_state != global_toggle_state)
2572 rc |= RC_FLAG_TOGGLED;
2574 #endif /* def FEATURE_TOGGLE */
2576 #ifdef FEATURE_STATISTICS
2577 if (csp->flags & CSP_FLAG_REJECTED)
2579 rc |= RC_FLAG_BLOCKED;
2581 #endif /* ndef FEATURE_STATISTICS */
2585 else if (child_id > 0) /* parent */
2587 /* in a fork()'d environment, the parent's
2588 * copy of the client socket and the CSP
2592 #if !defined(_WIN32) && !defined(__CYGWIN__)
2594 wait( &child_status );
2597 * Evaluate child's return code: If the child has
2598 * - been toggled, toggle ourselves
2599 * - blocked its request, bump up the stats counter
2602 #ifdef FEATURE_TOGGLE
2603 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
2605 global_toggle_state = !global_toggle_state;
2607 #endif /* def FEATURE_TOGGLE */
2609 #ifdef FEATURE_STATISTICS
2611 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
2615 #endif /* def FEATURE_STATISTICS */
2617 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2618 close_socket(csp->cfd);
2619 csp->flags &= ~CSP_FLAG_ACTIVE;
2623 #undef SELECTED_ONE_OPTION
2624 /* end of cpp switch () */
2626 if (child_id < 0) /* failed */
2628 char buf[BUFFER_SIZE];
2630 log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2632 sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
2634 write_socket(csp->cfd, buf, strlen(buf));
2635 close_socket(csp->cfd);
2636 csp->flags &= ~CSP_FLAG_ACTIVE;
2647 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
2649 /* Clean up. Aim: free all memory (no leaks) */
2650 #ifdef FEATURE_GRACEFUL_TERMINATION
2652 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
2654 unload_current_config_file();
2655 unload_current_actions_file();
2656 unload_current_re_filterfile();
2657 #ifdef FEATURE_TRUST
2658 unload_current_trust_file();
2661 if (config->multi_threaded)
2668 } while ((clients->next != NULL) && (--i > 0));
2672 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
2683 #ifdef FEATURE_COOKIE_JAR
2684 if (NULL != config->jar)
2686 fclose(config->jar);
2690 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
2691 /* Cleanup - remove taskbar icon etc. */
2696 #endif /* FEATURE_GRACEFUL_TERMINATION */