911c50590ef3fd3e667802216e041bb12afb0125
[privoxy.git] / jcc.c
1 const char jcc_rcs[] = "$Id: jcc.c,v 1.107 2006/11/13 19:05:51 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/jcc.c,v $
5  *
6  * Purpose     :  Main file.  Contains main() method, main loop, and
7  *                the main connection-handling function.
8  *
9  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
10  *                Privoxy team. http://www.privoxy.org/
11  *
12  *                Based on the Internet Junkbuster originally written
13  *                by and Copyright (C) 1997 Anonymous Coders and
14  *                Junkbusters Corporation.  http://www.junkbusters.com
15  *
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.
21  *
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.
27  *
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.
33  *
34  * Revisions   :
35  *    $Log: jcc.c,v $
36  *    Revision 1.107  2006/11/13 19:05:51  fabiankeil
37  *    Make pthread mutex locking more generic. Instead of
38  *    checking for OSX and OpenBSD, check for FEATURE_PTHREAD
39  *    and use mutex locking unless there is an _r function
40  *    available. Better safe than sorry.
41  *
42  *    Fixes "./configure --disable-pthread" and should result
43  *    in less threading-related problems on pthread-using platforms,
44  *    but it still doesn't fix BR#1122404.
45  *
46  *    Revision 1.106  2006/11/06 19:58:23  fabiankeil
47  *    Move pthread.h inclusion from jcc.c to jcc.h.
48  *    Fixes build on x86-freebsd1 (FreeBSD 5.4-RELEASE).
49  *
50  *    Revision 1.105  2006/11/06 14:26:02  fabiankeil
51  *    Don't exit after receiving the second SIGHUP on Solaris.
52  *
53  *    Fixes BR 1052235, but the same problem may exist on other
54  *    systems. Once 3.0.6 is out we should use sigset()
55  *    where available and see if it breaks anything.
56  *
57  *    Revision 1.104  2006/09/23 13:26:38  roro
58  *    Replace TABs by spaces in source code.
59  *
60  *    Revision 1.103  2006/09/21 12:54:43  fabiankeil
61  *    Fix +redirect{}. Didn't work with -fast-redirects.
62  *
63  *    Revision 1.102  2006/09/06 13:03:04  fabiankeil
64  *    Respond with 400 and a short text message
65  *    if the client tries to use Privoxy as FTP proxy.
66  *
67  *    Revision 1.101  2006/09/06 09:23:37  fabiankeil
68  *    Make number of retries in case of forwarded-connect problems
69  *    a config file option (forwarded-connect-retries) and use 0 as
70  *    default.
71  *
72  *    Revision 1.100  2006/09/03 19:42:59  fabiankeil
73  *    Set random(3) seed.
74  *
75  *    Revision 1.99  2006/09/02 15:36:42  fabiankeil
76  *    Follow the OpenBSD port's lead and protect the resolve
77  *    functions on OpenBSD as well.
78  *
79  *    Revision 1.98  2006/08/24 11:01:34  fabiankeil
80  *    --user fix. Only use the user as group if no group is specified.
81  *    Solves BR 1492612. Thanks to Spinor S. and David Laight.
82  *
83  *    Revision 1.97  2006/08/18 15:23:17  david__schmidt
84  *    Windows service (re-)integration
85  *
86  *    The new args are:
87  *
88  *    --install[:service_name]
89  *    --uninstall[:service_name]
90  *    --service
91  *
92  *    They work as follows:
93  *    --install will create a service for you and then terminate.
94  *    By default the service name will be "privoxy" (without the quotes).
95  *    However you can run multiple services if you wish, just by adding
96  *    a colon and then a name (no spaces).
97  *
98  *    --uninstall follows the exact same rules a --install.
99  *
100  *    --service is used when the program is executed by the service
101  *    control manager, and in normal circumstances would never be
102  *    used as a command line argument.
103  *
104  *    Revision 1.96  2006/08/15 20:12:36  david__schmidt
105  *    Windows service integration
106  *
107  *    Revision 1.95  2006/08/03 02:46:41  david__schmidt
108  *    Incorporate Fabian Keil's patch work:\rhttp://www.fabiankeil.de/sourcecode/privoxy/
109  *
110  *    Revision 1.94  2006/07/18 14:48:46  david__schmidt
111  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
112  *    with what was really the latest development (the v_3_0_branch branch)
113  *
114  *    Revision 1.92.2.16  2005/04/03 20:10:50  david__schmidt
115  *    Thanks to Jindrich Makovicka for a race condition fix for the log
116  *    file.  The race condition remains for non-pthread implementations.
117  *    Reference patch #1175720.
118  *
119  *    Revision 1.92.2.15  2004/10/03 12:53:32  david__schmidt
120  *    Add the ability to check jpeg images for invalid
121  *    lengths of comment blocks.  Defensive strategy
122  *    against the exploit:
123  *       Microsoft Security Bulletin MS04-028
124  *       Buffer Overrun in JPEG Processing (GDI+) Could
125  *       Allow Code Execution (833987)
126  *    Enabled with +inspect-jpegs in actions files.
127  *
128  *    Revision 1.92.2.14  2003/12/12 12:52:53  oes
129  *    - Fixed usage info for non-unix platforms
130  *    - Fixed small cmdline parsing bug
131  *
132  *    Revision 1.92.2.13  2003/11/27 19:20:27  oes
133  *    Diagnostics: Now preserve the returncode of pthread_create
134  *    in errno. Closes BR #775721. Thanks to Geoffrey Hausheer.
135  *
136  *    Revision 1.92.2.12  2003/07/11 11:34:19  oes
137  *    No longer ignore SIGCHLD. Fixes bug #769381
138  *
139  *    Revision 1.92.2.11  2003/05/14 12:32:02  oes
140  *    Close jarfile on graceful exit, remove stray line
141  *
142  *    Revision 1.92.2.10  2003/05/08 15:13:46  oes
143  *    Cosmetics: Killed a warning, a typo and an allocation left at exit
144  *
145  *    Revision 1.92.2.9  2003/04/03 15:08:42  oes
146  *    No longer rely on non-POSIX.1 extensions of getcwd().
147  *    Fixes bug #711001
148  *
149  *    Revision 1.92.2.8  2003/03/31 13:12:32  oes
150  *    Replaced setenv() by posix-compliant putenv()
151  *    Thanks to Neil McCalden (nmcc AT users.sf.net).
152  *
153  *    Revision 1.92.2.7  2003/03/17 16:48:59  oes
154  *    Added chroot ability, thanks to patch by Sviatoslav Sviridov
155  *
156  *    Revision 1.92.2.6  2003/03/11 11:55:00  oes
157  *    Clean-up and extension of improvements for forked mode:
158  *     - Child's return code now consists of flags RC_FLAG_*
159  *     - Reporting toggle to parent now properly #ifdef'ed
160  *     - Children now report blocking to parent. This enables
161  *       statistics in forked mode
162  *
163  *    Revision 1.92.2.5  2003/03/10 23:45:32  oes
164  *    Fixed bug #700381: Non-Threaded version now capable of being toggled.
165  *    Children now report having been toggled through _exit(17), parents
166  *    watch for that code and toggle themselves if found.
167  *
168  *    Revision 1.92.2.4  2003/03/07 03:41:04  david__schmidt
169  *    Wrapping all *_r functions (the non-_r versions of them) with 
170  *    mutex semaphores for OSX.  Hopefully this will take care of all 
171  *    of those pesky crash reports.
172  *
173  *    Revision 1.92.2.3  2003/02/28 12:53:06  oes
174  *    Fixed two mostly harmless mem leaks
175  *
176  *    Revision 1.92.2.2  2002/11/20 14:37:47  oes
177  *    Fix: Head of global clients list now initialized to NULL
178  *
179  *    Revision 1.92.2.1  2002/09/25 14:52:24  oes
180  *    Added basic support for OPTIONS and TRACE HTTP methods:
181  *     - New interceptor direct_response() added in chat().
182  *     - sed() moved to earlier in the process, so that the
183  *       Host: header is evaluated before actions and forwarding
184  *       are decided on.
185  *
186  *    Revision 1.92  2002/05/08 16:00:46  oes
187  *    Chat's buffer handling:
188  *     - Fixed bug with unchecked out-of-mem conditions
189  *       while reading client request & server headers
190  *     - No longer predict if the buffer limit will be exceeded
191  *       in the next read -- check add_to_iob's new
192  *       return code. If buffer couldn't be extended
193  *       (policy or out-of-mem) while
194  *       - reading from client: abort
195  *       - reading server headers: send error page
196  *       - buffering server body for filter: flush,
197  *         and if that fails: send error page
198  *
199  *    Revision 1.91  2002/04/08 20:35:58  swa
200  *    fixed JB spelling
201  *
202  *    Revision 1.90  2002/04/02 14:57:28  oes
203  *    Made sending wafers independent of FEATURE_COOKIE_JAR
204  *
205  *    Revision 1.89  2002/03/31 17:18:59  jongfoster
206  *    Win32 only: Enabling STRICT to fix a VC++ compile warning.
207  *
208  *    Revision 1.88  2002/03/27 14:32:43  david__schmidt
209  *    More compiler warning message maintenance
210  *
211  *    Revision 1.87  2002/03/26 22:29:54  swa
212  *    we have a new homepage!
213  *
214  *    Revision 1.86  2002/03/25 17:04:55  david__schmidt
215  *    Workaround for closing the jarfile before load_config() comes around again
216  *
217  *    Revision 1.85  2002/03/24 15:23:33  jongfoster
218  *    Name changes
219  *
220  *    Revision 1.84  2002/03/24 13:25:43  swa
221  *    name change related issues
222  *
223  *    Revision 1.83  2002/03/16 23:54:06  jongfoster
224  *    Adding graceful termination feature, to help look for memory leaks.
225  *    If you enable this (which, by design, has to be done by hand
226  *    editing config.h) and then go to http://i.j.b/die, then the program
227  *    will exit cleanly after the *next* request.  It should free all the
228  *    memory that was used.
229  *
230  *    Revision 1.82  2002/03/13 00:27:05  jongfoster
231  *    Killing warnings
232  *
233  *    Revision 1.81  2002/03/12 01:42:50  oes
234  *    Introduced modular filters
235  *
236  *    Revision 1.80  2002/03/11 22:07:05  david__schmidt
237  *    OS/2 port maintenance:
238  *    - Fixed EMX build - it had decayed a little
239  *    - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
240  *      substituted a memset for now.
241  *
242  *    Revision 1.79  2002/03/09 20:03:52  jongfoster
243  *    - Making various functions return int rather than size_t.
244  *      (Undoing a recent change).  Since size_t is unsigned on
245  *      Windows, functions like read_socket that return -1 on
246  *      error cannot return a size_t.
247  *
248  *      THIS WAS A MAJOR BUG - it caused frequent, unpredictable
249  *      crashes, and also frequently caused JB to jump to 100%
250  *      CPU and stay there.  (Because it thought it had just
251  *      read ((unsigned)-1) == 4Gb of data...)
252  *
253  *    - The signature of write_socket has changed, it now simply
254  *      returns success=0/failure=nonzero.
255  *
256  *    - Trying to get rid of a few warnings --with-debug on
257  *      Windows, I've introduced a new type "jb_socket".  This is
258  *      used for the socket file descriptors.  On Windows, this
259  *      is SOCKET (a typedef for unsigned).  Everywhere else, it's
260  *      an int.  The error value can't be -1 any more, so it's
261  *      now JB_INVALID_SOCKET (which is -1 on UNIX, and in
262  *      Windows it maps to the #define INVALID_SOCKET.)
263  *
264  *    - The signature of bind_port has changed.
265  *
266  *    Revision 1.78  2002/03/08 21:35:04  oes
267  *    Added optional group supplement to --user option. Will now use default group of user if no group given
268  *
269  *    Revision 1.77  2002/03/07 03:52:06  oes
270  *     - Fixed compiler warnings etc
271  *     - Improved handling of failed DNS lookups
272  *
273  *    Revision 1.76  2002/03/06 22:54:35  jongfoster
274  *    Automated function-comment nitpicking.
275  *
276  *    Revision 1.75  2002/03/06 10:02:19  oes
277  *    Fixed stupid bug when --user was not given
278  *
279  *    Revision 1.74  2002/03/06 00:49:31  jongfoster
280  *    Fixing warning on Windows
281  *    Making #ifdefs that refer to the same variable consistently
282  *    use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
283  *
284  *    Revision 1.73  2002/03/05 23:57:30  hal9
285  *    Stray character 's' on line 1618 was breaking build.
286  *
287  *    Revision 1.72  2002/03/05 21:33:45  david__schmidt
288  *    - Re-enable OS/2 building after new parms were added
289  *    - Fix false out of memory report when resolving CGI templates when no IP
290  *      address is available of failed attempt (a la no such domain)
291  *
292  *    Revision 1.71  2002/03/05 18:13:56  oes
293  *    Added --user option
294  *
295  *    Revision 1.70  2002/03/05 04:52:42  oes
296  *    Deleted non-errlog debugging code
297  *
298  *    Revision 1.69  2002/03/04 23:50:00  jongfoster
299  *    Splitting off bind_port() call into bind_port_helper(), with
300  *    improved logging.
301  *
302  *    Revision 1.68  2002/03/04 20:17:32  oes
303  *    Fixed usage info
304  *
305  *    Revision 1.67  2002/03/04 18:18:57  oes
306  *    - Removed _DEBUG mode
307  *    - Cleand up cmdline parsing
308  *    - Introduced --no-daemon, --pidfile options
309  *    - Cleaned up signal handling:
310  *      - Terminate cleanly on INT, TERM and ABRT
311  *      - Schedule logfile for re-opening on HUP
312  *      - Ignore CHLD and PIPE
313  *      - Leave the rest with their default handlers
314  *      - Uniform handler registration
315  *    - Added usage() function
316  *    - Played styleguide police
317  *
318  *    Revision 1.66  2002/03/03 15:06:55  oes
319  *    Re-enabled automatic config reloading
320  *
321  *    Revision 1.65  2002/03/03 14:49:11  oes
322  *    Fixed CLF logging: Now uses client's original HTTP request
323  *
324  *    Revision 1.64  2002/03/03 09:18:03  joergs
325  *    Made jumbjuster work on AmigaOS again.
326  *
327  *    Revision 1.63  2002/03/02 04:14:50  david__schmidt
328  *    Clean up a little CRLF unpleasantness that suddenly appeared
329  *
330  *    Revision 1.62  2002/02/20 23:17:23  jongfoster
331  *    Detecting some out-of memory conditions and exiting with a log message.
332  *
333  *    Revision 1.61  2002/01/17 21:01:52  jongfoster
334  *    Moving all our URL and URL pattern parsing code to urlmatch.c.
335  *
336  *    Revision 1.60  2001/12/30 14:07:32  steudten
337  *    - Add signal handling (unix)
338  *    - Add SIGHUP handler (unix)
339  *    - Add creation of pidfile (unix)
340  *    - Add action 'top' in rc file (RH)
341  *    - Add entry 'SIGNALS' to manpage
342  *    - Add exit message to logfile (unix)
343  *
344  *    Revision 1.59  2001/12/13 14:07:18  oes
345  *    Fixed Bug: 503 error page now sent OK
346  *
347  *    Revision 1.58  2001/11/30 23:37:24  jongfoster
348  *    Renaming the Win32 config file to config.txt - this is almost the
349  *    same as the corresponding UNIX name "config"
350  *
351  *    Revision 1.57  2001/11/16 00:47:43  jongfoster
352  *    Changing the tty-disconnection code to use setsid().
353  *
354  *    Revision 1.56  2001/11/13 20:20:54  jongfoster
355  *    Tabs->spaces, fixing a bug with missing {} around an if()
356  *
357  *    Revision 1.55  2001/11/13 20:14:53  jongfoster
358  *    Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
359  *
360  *    Revision 1.54  2001/11/07 00:03:14  steudten
361  *    Give reliable return value if an error
362  *    occurs not just 0 with new daemon mode.
363  *
364  *    Revision 1.53  2001/11/05 21:41:43  steudten
365  *    Add changes to be a real daemon just for unix os.
366  *    (change cwd to /, detach from controlling tty, set
367  *    process group and session leader to the own process.
368  *    Add DBG() Macro.
369  *    Add some fatal-error log message for failed malloc().
370  *    Add '-d' if compiled with 'configure --with-debug' to
371  *    enable debug output.
372  *
373  *    Revision 1.52  2001/10/26 20:11:20  jongfoster
374  *    Fixing type mismatch
375  *
376  *    Revision 1.51  2001/10/26 17:38:28  oes
377  *    Cosmetics
378  *
379  *    Revision 1.50  2001/10/25 03:40:48  david__schmidt
380  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
381  *    threads to call select() simultaneously.  So, it's time to do a real, live,
382  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
383  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
384  *
385  *    Revision 1.49  2001/10/23 21:41:35  jongfoster
386  *    Added call to initialize the (statically-allocated of course)
387  *    "out of memory" CGI response.
388  *
389  *    Revision 1.48  2001/10/10 19:56:46  jongfoster
390  *    Moving some code that wasn't cookie-related out of an #ifdef
391  *    FEATURE_COOKIE_JAR
392  *
393  *    Revision 1.47  2001/10/10 16:44:36  oes
394  *    Added CONNECT destination port limitation check
395  *
396  *    Revision 1.46  2001/10/08 15:17:41  oes
397  *    Re-enabled SSL forwarding
398  *
399  *    Revision 1.45  2001/10/07 15:42:11  oes
400  *    Replaced 6 boolean members of csp with one bitmap (csp->flags)
401  *
402  *    Moved downgrading of the HTTP version from parse_http_request to
403  *      chat(), since we can't decide if it is necessary before we have
404  *      determined the actions for the URL. The HTTP command is now
405  *      *always* re-built so the repairs need no longer be special-cased.
406  *
407  *    filter_popups now gets a csp pointer so it can raise the new
408  *      CSP_FLAG_MODIFIED flag.
409  *
410  *    Bugfix
411  *
412  *    Added configurable size limit for the IOB. If the IOB grows so
413  *      large that the next read would exceed the limit, the header
414  *      is generated, and the header & unfiltered buffer are flushed
415  *      to the client. Chat then continues in non-buffering,
416  *      non-filtering body mode.
417  *
418  *    Revision 1.44  2001/10/02 18:13:57  oes
419  *    Ooops
420  *
421  *    Revision 1.43  2001/10/02 15:32:13  oes
422  *    Moved generation of hdr
423  *
424  *    Revision 1.42  2001/09/21 23:02:02  david__schmidt
425  *    Cleaning up 2 compiler warnings on OS/2.
426  *
427  *    Revision 1.41  2001/09/16 17:05:14  jongfoster
428  *    Removing unused #include showarg.h
429  *
430  *    Revision 1.40  2001/09/16 15:41:45  jongfoster
431  *    Fixing signed/unsigned comparison warning.
432  *
433  *    Revision 1.39  2001/09/16 13:21:27  jongfoster
434  *    Changes to use new list functions.
435  *
436  *    Revision 1.38  2001/09/16 13:01:46  jongfoster
437  *    Removing redundant function call that zeroed zalloc()'d memory.
438  *
439  *    Revision 1.37  2001/09/10 11:12:24  oes
440  *    Deleted unused variable
441  *
442  *    Revision 1.36  2001/09/10 10:56:15  oes
443  *    Silenced compiler warnings
444  *
445  *    Revision 1.35  2001/07/31 14:44:22  oes
446  *    Deleted unused size parameter from filter_popups()
447  *
448  *    Revision 1.34  2001/07/30 22:08:36  jongfoster
449  *    Tidying up #defines:
450  *    - All feature #defines are now of the form FEATURE_xxx
451  *    - Permanently turned off WIN_GUI_EDIT
452  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
453  *
454  *    Revision 1.33  2001/07/29 19:32:00  jongfoster
455  *    Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
456  *
457  *    Revision 1.32  2001/07/29 18:47:05  jongfoster
458  *    Adding missing #include "loadcfg.h"
459  *
460  *    Revision 1.31  2001/07/29 12:17:48  oes
461  *    Applied pthread fix by Paul Lieverse
462  *
463  *    Revision 1.30  2001/07/25 22:57:13  jongfoster
464  *    __BEOS__ no longer overrides FEATURE_PTHREAD.
465  *    This is because FEATURE_PTHREAD will soon be widely used, so I
466  *    want to keep it simple.
467  *
468  *    Revision 1.29  2001/07/24 12:47:06  oes
469  *    Applied BeOS support update by Eugenia
470  *
471  *    Revision 1.28  2001/07/23 13:26:12  oes
472  *    Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
473  *
474  *    Revision 1.27  2001/07/19 19:09:47  haroon
475  *    - Added code to take care of the situation where while processing the first
476  *      server response (which includes the server header), after finding the end
477  *      of the headers we were not looking past the end of the headers for
478  *      content modification. I enabled it for filter_popups.
479  *      Someone else should look to see if other similar operations should be
480  *      done to the discarded portion of the buffer.
481  *
482  *      Note 2001/07/20: No, the other content modification mechanisms will process
483  *                       the whole iob later anyway. --oes
484  *
485  *    Revision 1.26  2001/07/18 12:31:36  oes
486  *    cosmetics
487  *
488  *    Revision 1.25  2001/07/15 19:43:49  jongfoster
489  *    Supports POSIX threads.
490  *    Also removed some unused #includes.
491  *
492  *    Revision 1.24  2001/07/13 14:00:40  oes
493  *     - Generic content modification scheme:
494  *       Each feature has its own applicability flag that is set
495  *       from csp->action->flags.
496  *       Replaced the "filtering" int flag , by a function pointer
497  *       "content_filter" to the function that will do the content
498  *       modification. If it is != NULL, the document will be buffered
499  *       and processed through *content_filter, which must set
500  *       csp->content_length and return a modified copy of the body
501  *       or return NULL (on failiure).
502  *     - Changed csp->is_text to the more generic bitmap csp->content_type
503  *       which can currently take the valued CT_TEXT or CT_GIF
504  *     - Reformatting etc
505  *     - Removed all #ifdef PCRS
506  *
507  *    Revision 1.23  2001/07/02 02:28:25  iwanttokeepanon
508  *    Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
509  *    the `block_acl' call.  This prevents a compilation error when the user
510  *    does not wish to use the "ACL" feature.
511  *
512  *    Revision 1.22  2001/06/29 21:45:41  oes
513  *    Indentation, CRLF->LF, Tab-> Space
514  *
515  *    Revision 1.21  2001/06/29 13:29:36  oes
516  *    - Cleaned up, improved comments
517  *    - Unified all possible interceptors (CGI,
518  *      block, trust, fast_redirect) in one
519  *      place, with one (CGI) answer generation
520  *      mechansim. Much clearer now.
521  *    - Removed the GIF image generation, which
522  *      is now done in filters.c:block_url()
523  *    - Made error conditions like domain lookup
524  *      failiure or (various) problems while talking
525  *      to the server use cgi.c:error_response()
526  *      instead of generating HTML/HTTP in chat() (yuck!)
527  *    - Removed logentry from cancelled commit
528  *
529  *    Revision 1.20  2001/06/09 10:55:28  jongfoster
530  *    Changing BUFSIZ ==> BUFFER_SIZE
531  *
532  *    Revision 1.19  2001/06/07 23:12:52  jongfoster
533  *    Replacing function pointer in struct gateway with a directly
534  *    called function forwarded_connect().
535  *    Replacing struct gateway with struct forward_spec
536  *
537  *    Revision 1.18  2001/06/03 19:12:16  oes
538  *    introduced new cgi handling
539  *
540  *    Revision 1.17  2001/06/01 20:07:23  jongfoster
541  *    Now uses action +image-blocker{} rather than config->tinygif
542  *
543  *    Revision 1.16  2001/06/01 18:49:17  jongfoster
544  *    Replaced "list_share" with "list" - the tiny memory gain was not
545  *    worth the extra complexity.
546  *
547  *    Revision 1.15  2001/05/31 21:24:47  jongfoster
548  *    Changed "permission" to "action" throughout.
549  *    Removed DEFAULT_USER_AGENT - it must now be specified manually.
550  *    Moved vanilla wafer check into chat(), since we must now
551  *    decide whether or not to add it based on the URL.
552  *
553  *    Revision 1.14  2001/05/29 20:14:01  joergs
554  *    AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
555  *    increased.
556  *
557  *    Revision 1.13  2001/05/29 09:50:24  jongfoster
558  *    Unified blocklist/imagelist/permissionslist.
559  *    File format is still under discussion, but the internal changes
560  *    are (mostly) done.
561  *
562  *    Also modified interceptor behaviour:
563  *    - We now intercept all URLs beginning with one of the following
564  *      prefixes (and *only* these prefixes):
565  *        * http://i.j.b/
566  *        * http://ijbswa.sf.net/config/
567  *        * http://ijbswa.sourceforge.net/config/
568  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
569  *    - Internal changes so that intercepted and fast redirect pages
570  *      are not replaced with an image.
571  *    - Interceptors now have the option to send a binary page direct
572  *      to the client. (i.e. ijb-send-banner uses this)
573  *    - Implemented show-url-info interceptor.  (Which is why I needed
574  *      the above interceptors changes - a typical URL is
575  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
576  *      The previous mechanism would not have intercepted that, and
577  *      if it had been intercepted then it then it would have replaced
578  *      it with an image.)
579  *
580  *    Revision 1.12  2001/05/27 22:17:04  oes
581  *
582  *    - re_process_buffer no longer writes the modified buffer
583  *      to the client, which was very ugly. It now returns the
584  *      buffer, which it is then written by chat.
585  *
586  *    - content_length now adjusts the Content-Length: header
587  *      for modified documents rather than crunch()ing it.
588  *      (Length info in csp->content_length, which is 0 for
589  *      unmodified documents)
590  *
591  *    - For this to work, sed() is called twice when filtering.
592  *
593  *    Revision 1.11  2001/05/26 17:27:53  jongfoster
594  *    Added support for CLF and fixed LOG_LEVEL_LOG.
595  *    Also did CRLF->LF fix of my previous patch.
596  *
597  *    Revision 1.10  2001/05/26 15:26:15  jongfoster
598  *    ACL feature now provides more security by immediately dropping
599  *    connections from untrusted hosts.
600  *
601  *    Revision 1.9  2001/05/26 00:28:36  jongfoster
602  *    Automatic reloading of config file.
603  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
604  *    Most of the global variables have been moved to a new
605  *    struct configuration_spec, accessed through csp->config->globalname
606  *    Most of the globals remaining are used by the Win32 GUI.
607  *
608  *    Revision 1.8  2001/05/25 22:43:18  jongfoster
609  *    Fixing minor memory leak and buffer overflow.
610  *
611  *    Revision 1.7  2001/05/25 22:34:30  jongfoster
612  *    Hard tabs->Spaces
613  *
614  *    Revision 1.6  2001/05/23 00:13:58  joergs
615  *    AmigaOS support fixed.
616  *
617  *    Revision 1.5  2001/05/22 18:46:04  oes
618  *
619  *    - Enabled filtering banners by size rather than URL
620  *      by adding patterns that replace all standard banner
621  *      sizes with the "Junkbuster" gif to the re_filterfile
622  *
623  *    - Enabled filtering WebBugs by providing a pattern
624  *      which kills all 1x1 images
625  *
626  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
627  *      which is selected by the (nonstandard and therefore
628  *      capital) letter 'U' in the option string.
629  *      It causes the quantifiers to be ungreedy by default.
630  *      Appending a ? turns back to greedy (!).
631  *
632  *    - Added a new interceptor ijb-send-banner, which
633  *      sends back the "Junkbuster" gif. Without imagelist or
634  *      MSIE detection support, or if tinygif = 1, or the
635  *      URL isn't recognized as an imageurl, a lame HTML
636  *      explanation is sent instead.
637  *
638  *    - Added new feature, which permits blocking remote
639  *      script redirects and firing back a local redirect
640  *      to the browser.
641  *      The feature is conditionally compiled, i.e. it
642  *      can be disabled with --disable-fast-redirects,
643  *      plus it must be activated by a "fast-redirects"
644  *      line in the config file, has its own log level
645  *      and of course wants to be displayed by show-proxy-args
646  *      Note: Boy, all the #ifdefs in 1001 locations and
647  *      all the fumbling with configure.in and acconfig.h
648  *      were *way* more work than the feature itself :-(
649  *
650  *    - Because a generic redirect template was needed for
651  *      this, tinygif = 3 now uses the same.
652  *
653  *    - Moved GIFs, and other static HTTP response templates
654  *      to project.h
655  *
656  *    - Some minor fixes
657  *
658  *    - Removed some >400 CRs again (Jon, you really worked
659  *      a lot! ;-)
660  *
661  *    Revision 1.4  2001/05/21 19:34:01  jongfoster
662  *    Made failure to bind() a fatal error.
663  *
664  *    Revision 1.3  2001/05/20 01:21:20  jongfoster
665  *    Version 2.9.4 checkin.
666  *    - Merged popupfile and cookiefile, and added control over PCRS
667  *      filtering, in new "permissionsfile".
668  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
669  *      file error you now get a message box (in the Win32 GUI) rather
670  *      than the program exiting with no explanation.
671  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
672  *      skipping.
673  *    - Removed tabs from "config"
674  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
675  *    - Bumped up version number.
676  *
677  *    Revision 1.2  2001/05/17 22:34:44  oes
678  *     - Added hint on GIF char array generation to jcc.c
679  *     - Cleaned CRLF's from the sources and related files
680  *     - Repaired logging for REF and FRC
681  *
682  *    Revision 1.1.1.1  2001/05/15 13:58:56  oes
683  *    Initial import of version 2.9.3 source tree
684  *
685  *
686  *********************************************************************/
687 \f
688
689 #include "config.h"
690
691 #include <stdio.h>
692 #include <sys/types.h>
693 #include <stdlib.h>
694 #include <string.h>
695 #include <signal.h>
696 #include <fcntl.h>
697 #include <errno.h>
698
699 #ifdef _WIN32
700 # ifndef FEATURE_PTHREAD
701 #  ifndef STRICT
702 #   define STRICT
703 #  endif
704 #  include <windows.h>
705 #  include <process.h>
706 # endif /* ndef FEATURE_PTHREAD */
707
708 # include "win32.h"
709 # ifndef _WIN_CONSOLE
710 #  include "w32log.h"
711 # endif /* ndef _WIN_CONSOLE */
712 # include "w32svrapi.h"
713
714 #else /* ifndef _WIN32 */
715
716 # if !defined (__OS2__)
717 # include <unistd.h>
718 # include <sys/wait.h>
719 # endif /* ndef __OS2__ */
720 # include <sys/time.h>
721 # include <sys/stat.h>
722 # include <sys/ioctl.h>
723
724 #ifdef sun
725 #include <sys/termios.h>
726 #endif /* sun */
727
728 #ifdef unix
729 #include <pwd.h>
730 #include <grp.h>
731 #endif
732
733 # include <signal.h>
734
735 # ifdef __BEOS__
736 #  include <socket.h>  /* BeOS has select() for sockets only. */
737 #  include <OS.h>      /* declarations for threads and stuff. */
738 # endif
739
740 # if defined(__EMX__) || defined(__OS2__)
741 #  include <sys/select.h>  /* OS/2/EMX needs a little help with select */
742 # endif
743 # ifdef __OS2__
744 #define INCL_DOS
745 # include <os2.h>
746 #define bzero(B,N) memset(B,0x00,n)
747 # endif
748
749 # ifndef FD_ZERO
750 #  include <select.h>
751 # endif
752
753 #endif
754
755 #include "project.h"
756 #include "list.h"
757 #include "jcc.h"
758 #include "filters.h"
759 #include "loaders.h"
760 #include "parsers.h"
761 #include "killpopup.h"
762 #include "miscutil.h"
763 #include "errlog.h"
764 #include "jbsockets.h"
765 #include "gateway.h"
766 #include "actions.h"
767 #include "cgi.h"
768 #include "loadcfg.h"
769 #include "urlmatch.h"
770
771 const char jcc_h_rcs[] = JCC_H_VERSION;
772 const char project_h_rcs[] = PROJECT_H_VERSION;
773
774 int no_daemon = 0;
775 struct client_state  clients[1];
776 struct file_list     files[1];
777
778 #ifdef FEATURE_STATISTICS
779 int urls_read     = 0;     /* total nr of urls read inc rejected */
780 int urls_rejected = 0;     /* total nr of urls rejected */
781 #endif /* def FEATURE_STATISTICS */
782
783 #ifdef FEATURE_GRACEFUL_TERMINATION
784 int g_terminate = 0;
785 #endif
786
787 static void listen_loop(void);
788 static void chat(struct client_state *csp);
789 #ifdef AMIGA
790 void serve(struct client_state *csp);
791 #else /* ifndef AMIGA */
792 static void serve(struct client_state *csp);
793 #endif /* def AMIGA */
794
795 #ifdef __BEOS__
796 static int32 server_thread(void *data);
797 #endif /* def __BEOS__ */
798
799 #ifdef _WIN32
800 #define sleep(N)  Sleep(((N) * 1000))
801 #endif
802
803 #ifdef __OS2__
804 #define sleep(N)  DosSleep(((N) * 100))
805 #endif
806
807 #ifdef FEATURE_PTHREAD
808 pthread_mutex_t log_mutex;
809 pthread_mutex_t log_init_mutex;
810
811 #ifndef HAVE_GMTIME_R
812 pthread_mutex_t gmtime_mutex;
813 #endif /* ndef HAVE_GMTIME_R */
814
815 #ifndef HAVE_LOCALTIME_R
816 pthread_mutex_t localtime_mutex;
817 #endif /* ndef HAVE_GMTIME_R */
818
819 #ifndef HAVE_GETHOSTBYADDR_R
820 pthread_mutex_t gethostbyaddr_mutex;
821 #endif /* ndef HAVE_GETHOSTBYADDR_R */
822
823 #ifndef HAVE_GETHOSTBYNAME_R
824 pthread_mutex_t gethostbyname_mutex;
825 #endif /* ndef HAVE_GETHOSTBYNAME_R */
826 #endif /* FEATURE_PTHREAD */
827
828 #if defined(unix) || defined(__EMX__)
829 const char *basedir = NULL;
830 const char *pidfile = NULL;
831 int received_hup_signal = 0;
832 #endif /* defined unix */
833
834 /* The vanilla wafer. */
835 static const char VANILLA_WAFER[] =
836    "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
837    "Do_not_send_me_any_copyrighted_information_other_than_the_"
838    "document_that_I_am_requesting_or_any_of_its_necessary_components._"
839    "In_particular_do_not_send_me_any_cookies_that_"
840    "are_subject_to_a_claim_of_copyright_by_anybody._"
841    "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
842    "(copyright_or_otherwise)_applying_to_any_cookie._";
843
844
845 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
846 /*********************************************************************
847  *
848  * Function    :  sig_handler 
849  *
850  * Description :  Signal handler for different signals.
851  *                Exit gracefully on ABRT, TERM and  INT
852  *                or set a flag that will cause the errlog
853  *                to be reopened by the main thread on HUP.
854  *
855  * Parameters  :
856  *          1  :  the_signal = the signal cause this function to call
857  *
858  * Returns     :  - 
859  *
860  *********************************************************************/
861 static void sig_handler(int the_signal)
862 {
863    switch(the_signal)
864    {
865       case SIGABRT:
866       case SIGTERM:
867       case SIGINT:
868          log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
869 #if defined(unix)
870          if(pidfile)
871          {
872             unlink(pidfile);
873          }
874 #endif /* unix */
875          exit(the_signal);
876          break;
877
878       case SIGHUP:
879          received_hup_signal = 1;
880          break;         
881
882       default:
883          /* 
884           * We shouldn't be here, unless we catch signals
885           * in main() that we can't handle here!
886           */
887          log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
888    }
889    return;
890
891 }
892 #endif
893
894
895 /*********************************************************************
896  *
897  * Function    :  chat
898  *
899  * Description :  Once a connection to the client has been accepted,
900  *                this function is called (via serve()) to handle the
901  *                main business of the communication.  When this
902  *                function returns, the caller must close the client
903  *                socket handle.
904  *
905  * Parameters  :
906  *          1  :  csp = Current client state (buffers, headers, etc...)
907  *
908  * Returns     :  On success, the number of bytes written are returned (zero
909  *                indicates nothing was written).  On error, -1 is returned,
910  *                and errno is set appropriately.  If count is zero and the
911  *                file descriptor refers to a regular file, 0 will be
912  *                returned without causing any other effect.  For a special
913  *                file, the results are not portable.
914  *
915  *********************************************************************/
916 static void chat(struct client_state *csp)
917 {
918 /*
919  * This next lines are a little ugly, but they simplifies the if statements
920  * below.  Basically if TOGGLE, then we want the if to test if the
921  * CSP_FLAG_TOGGLED_ON flag ist set, else we don't.  And if FEATURE_FORCE_LOAD,
922  * then we want the if to test for CSP_FLAG_FORCED , else we don't
923  */
924 #ifdef FEATURE_TOGGLE
925 #   define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
926 #else /* ifndef FEATURE_TOGGLE */
927 #   define IS_TOGGLED_ON_AND
928 #endif /* ndef FEATURE_TOGGLE */
929 #ifdef FEATURE_FORCE_LOAD
930 #   define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
931 #else /* ifndef FEATURE_FORCE_LOAD */
932 #   define IS_NOT_FORCED_AND
933 #endif /* def FEATURE_FORCE_LOAD */
934
935 #define IS_ENABLED_AND   IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
936
937    char buf[BUFFER_SIZE];
938    char *hdr;
939    char *p;
940    char *req;
941    fd_set rfds;
942    int n;
943    jb_socket maxfd;
944    int server_body;
945    int ms_iis5_hack = 0;
946    int byte_count = 0;
947    unsigned int forwarded_connect_retries = 0;
948    unsigned int max_forwarded_connect_retries = csp->config->forwarded_connect_retries;
949    const struct forward_spec * fwd;
950    struct http_request *http;
951    int len; /* for buffer sizes */
952 #ifdef FEATURE_KILL_POPUPS
953    int block_popups;         /* bool, 1==will block popups */
954    int block_popups_now = 0; /* bool, 1==currently blocking popups */
955 #endif /* def FEATURE_KILL_POPUPS */
956
957    int pcrs_filter;        /* bool, 1==will filter through pcrs */
958    int gif_deanimate;      /* bool, 1==will deanimate gifs */
959    int jpeg_inspect;       /* bool, 1==will inspect jpegs */
960
961    /* Function that does the content filtering for the current request */
962    char *(*content_filter)() = NULL;
963
964    /* Skeleton for HTTP response, if we should intercept the request */
965    struct http_response *rsp;
966
967    http = csp->http;
968
969    /*
970     * Read the client's request.  Note that since we're not using select() we
971     * could get blocked here if a client connected, then didn't say anything!
972     */
973
974    for (;;)
975    {
976       len = read_socket(csp->cfd, buf, sizeof(buf));
977
978       if (len <= 0) break;      /* error! */
979       
980       /*
981        * If there is no memory left for buffering the
982        * request, there is nothing we can do but hang up
983        */
984       if (add_to_iob(csp, buf, len))
985       {
986          return;
987       }
988
989       req = get_header(csp);
990
991       if (req == NULL)
992       {
993          break;    /* no HTTP request! */
994       }
995
996       if (*req == '\0')
997       {
998          continue;   /* more to come! */
999       }
1000
1001 #ifdef FEATURE_FORCE_LOAD
1002       /* If this request contains the FORCE_PREFIX,
1003        * better get rid of it now and set the force flag --oes
1004        */
1005
1006       if (strstr(req, FORCE_PREFIX))
1007       {
1008          strclean(req, FORCE_PREFIX);
1009          log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
1010          csp->flags |= CSP_FLAG_FORCED;
1011       }
1012
1013 #endif /* def FEATURE_FORCE_LOAD */
1014
1015       parse_http_request(req, http, csp);
1016       freez(req);
1017       break;
1018    }
1019
1020    if (http->cmd == NULL)
1021    {
1022       strcpy(buf, CHEADER);
1023       write_socket(csp->cfd, buf, strlen(buf));
1024
1025       log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
1026
1027       free_http_request(http);
1028       return;
1029    }
1030
1031    if (!strncmpic(http->cmd, "GET ftp://", 10))
1032    {
1033       strcpy(buf, FTP_RESPONSE);
1034       write_socket(csp->cfd, buf, strlen(buf));
1035
1036       log_error(LOG_LEVEL_ERROR, "%s tried to use Privoxy as FTP proxy: %s",
1037          csp->ip_addr_str, http->cmd);
1038
1039       free_http_request(http);
1040       return;
1041    }
1042
1043    /* decide how to route the HTTP request */
1044
1045    if ((fwd = forward_url(http, csp)) == NULL)
1046    {
1047       log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!?  This can't happen!");
1048       /* Never get here - LOG_LEVEL_FATAL causes program exit */
1049    }
1050
1051    /* build the http request to send to the server
1052     * we have to do one of the following:
1053     *
1054     * create = use the original HTTP request to create a new
1055     *          HTTP request that has either the path component
1056     *          without the http://domainspec (w/path) or the
1057     *          full orininal URL (w/url)
1058     *          Note that the path and/or the HTTP version may
1059     *          have been altered by now.
1060     *
1061     * connect = Open a socket to the host:port of the server
1062     *           and short-circuit server and client socket.
1063     *
1064     * pass =  Pass the request unchanged if forwarding a CONNECT
1065     *         request to a parent proxy. Note that we'll be sending
1066     *         the CFAIL message ourselves if connecting to the parent
1067     *         fails, but we won't send a CSUCCEED message if it works,
1068     *         since that would result in a double message (ours and the
1069     *         parent's). After sending the request to the parent, we simply
1070     *         tunnel.
1071     *
1072     * here's the matrix:
1073     *                        SSL
1074     *                    0        1
1075     *                +--------+--------+
1076     *                |        |        |
1077     *             0  | create | connect|
1078     *                | w/path |        |
1079     *  Forwarding    +--------+--------+
1080     *                |        |        |
1081     *             1  | create | pass   |
1082     *                | w/url  |        |
1083     *                +--------+--------+
1084     *
1085     */
1086
1087    /*
1088     * Determine the actions for this URL
1089     */
1090 #ifdef FEATURE_TOGGLE
1091    if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1092    {
1093       /* Most compatible set of actions (i.e. none) */
1094       init_current_action(csp->action);
1095    }
1096    else
1097 #endif /* ndef FEATURE_TOGGLE */
1098    {
1099       url_actions(http, csp);
1100    }
1101
1102
1103    /*
1104     * Check if a CONNECT request is allowable:
1105     * In the absence of a +limit-connect action, allow only port 443.
1106     * If there is an action, allow whatever matches the specificaton.
1107     */
1108    if(http->ssl)
1109    {
1110       if(  ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
1111            || (csp->action->flags & ACTION_LIMIT_CONNECT
1112               && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
1113       {
1114          if (csp->action->flags & ACTION_TREAT_FORBIDDEN_CONNECTS_LIKE_BLOCKS)
1115          {
1116             /* The response will violate the specs, but makes unblocking easier. */
1117             log_error(LOG_LEVEL_ERROR, "Marking suspicious CONNECT request from %s for blocking.",
1118                csp->ip_addr_str);
1119             csp->action->flags |= ACTION_BLOCK;
1120             http->ssl = 0;
1121          }
1122          else
1123          {
1124             strcpy(buf, CFORBIDDEN);
1125             write_socket(csp->cfd, buf, strlen(buf));
1126             log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
1127             log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
1128             return;
1129          }
1130       }
1131    }
1132
1133
1134    /*
1135     * Downgrade http version from 1.1 to 1.0 if +downgrade
1136     * action applies
1137     */
1138    if ( (http->ssl == 0)
1139      && (!strcmpic(http->ver, "HTTP/1.1"))
1140      && (csp->action->flags & ACTION_DOWNGRADE))
1141    {
1142       freez(http->ver);
1143       http->ver = strdup("HTTP/1.0");
1144
1145       if (http->ver == NULL)
1146       {
1147          log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
1148       }
1149    }
1150
1151    /* 
1152     * Save a copy of the original request for logging
1153     */
1154    http->ocmd = strdup(http->cmd);
1155
1156    if (http->ocmd == NULL)
1157    {
1158       log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
1159    }
1160
1161    /*
1162     * (Re)build the HTTP request for non-SSL requests.
1163     * If forwarding, use the whole URL, else, use only the path.
1164     */
1165    if (http->ssl == 0)
1166    {
1167       freez(http->cmd);
1168
1169       http->cmd = strdup(http->gpc);
1170       string_append(&http->cmd, " ");
1171
1172       if (fwd->forward_host)
1173       {
1174          string_append(&http->cmd, http->url);
1175       }
1176       else
1177       {
1178          string_append(&http->cmd, http->path);
1179       }
1180       string_append(&http->cmd, " ");
1181       string_append(&http->cmd, http->ver);
1182
1183       if (http->cmd == NULL)
1184       {
1185          log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1186       }
1187       log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", http->cmd);
1188    }
1189    enlist(csp->headers, http->cmd);
1190
1191
1192    /*
1193     * If the user has not supplied any wafers, and the user has not
1194     * told us to suppress the vanilla wafer, then send the vanilla wafer.
1195     */
1196    if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
1197        && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
1198    {
1199       enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
1200    }
1201
1202
1203 #ifdef FEATURE_KILL_POPUPS
1204    block_popups               = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1205 #endif /* def FEATURE_KILL_POPUPS */
1206
1207    pcrs_filter                = (csp->rlist != NULL) &&  /* There are expressions to be used */
1208                                 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1209
1210    gif_deanimate              = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1211
1212    jpeg_inspect               = ((csp->action->flags & ACTION_JPEG_INSPECT) != 0);
1213
1214    /* grab the rest of the client's headers */
1215
1216    for (;;)
1217    {
1218       if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
1219       {
1220          len = read_socket(csp->cfd, buf, sizeof(buf));
1221          if (len <= 0)
1222          {
1223             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1224             return;
1225          }
1226          
1227          /*
1228           * If there is no memory left for buffering the
1229           * request, there is nothing we can do but hang up
1230           */
1231          if (add_to_iob(csp, buf, len))
1232          {
1233             return;
1234          }
1235          continue;
1236       }
1237
1238       if (p == NULL) break;
1239
1240       enlist(csp->headers, p);
1241       freez(p);
1242    }
1243
1244    /*
1245     * We have a request. Now, check to see if we need to
1246     * intercept it, i.e. If ..
1247     */
1248
1249    if (
1250        /* We may not forward the request by rfc2616 sect 14.31 */
1251        (NULL != (rsp = direct_response(csp)))
1252
1253        /* or we are enabled and... */
1254        || (IS_ENABLED_AND (
1255
1256             /* ..the request was blocked */
1257           ( NULL != (rsp = block_url(csp)))
1258
1259           /* ..or untrusted */
1260 #ifdef FEATURE_TRUST
1261           || ( NULL != (rsp = trust_url(csp)))
1262 #endif /* def FEATURE_TRUST */
1263
1264           /* ..or a redirect kicked in */
1265           || ( NULL != (rsp = redirect_url(csp)))
1266           ))
1267
1268        /*
1269         * .. or a CGI call was detected and answered.
1270         *
1271         * This check comes last to give the user the power
1272         * to deny acces to some (or all) of the cgi pages.
1273         */
1274        || (NULL != (rsp = dispatch_cgi(csp)))
1275
1276                  )
1277    {
1278       /* Write the answer to the client */
1279       if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1280        || write_socket(csp->cfd, rsp->body, rsp->content_length))
1281       {
1282          log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1283       }
1284
1285 #ifdef FEATURE_STATISTICS
1286       /* Count as a rejected request */
1287       csp->flags |= CSP_FLAG_REJECTED;
1288 #endif /* def FEATURE_STATISTICS */
1289
1290       /* Log (FIXME: All intercept reasons appear as "crunch" with Status 200) */
1291       log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
1292       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
1293
1294       /* Clean up and return */
1295       free_http_response(rsp);
1296       return;
1297    }
1298
1299    hdr = sed(client_patterns, add_client_headers, csp);
1300    if (hdr == NULL)
1301    {
1302       /* FIXME Should handle error properly */
1303       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1304    }
1305
1306    list_remove_all(csp->headers);
1307
1308    log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1309
1310    if (fwd->forward_host)
1311    {
1312       log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
1313                fwd->forward_host, fwd->forward_port, http->hostport);
1314    }
1315    else
1316    {
1317       log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1318    }
1319
1320    /* here we connect to the server, gateway, or the forwarder */
1321
1322    while ( (csp->sfd = forwarded_connect(fwd, http, csp))
1323          && (errno == EINVAL) && (forwarded_connect_retries++ < max_forwarded_connect_retries))
1324    {
1325       log_error(LOG_LEVEL_ERROR, "failed request #%u to connect to %s. Trying again.",
1326                 forwarded_connect_retries, http->hostport);
1327    }
1328
1329    if (csp->sfd == JB_INVALID_SOCKET)
1330    {
1331       log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1332                 http->hostport);
1333
1334       if (errno == EINVAL)
1335       {
1336          rsp = error_response(csp, "no-such-domain", errno);
1337
1338          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
1339                    csp->ip_addr_str, http->ocmd);
1340       }
1341       else
1342       {
1343          rsp = error_response(csp, "connect-failed", errno);
1344
1345          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1346                    csp->ip_addr_str, http->ocmd);
1347       }
1348
1349
1350       /* Write the answer to the client */
1351       if(rsp)
1352       {
1353          if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1354           || write_socket(csp->cfd, rsp->body, rsp->content_length))
1355          {
1356             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1357          }
1358       }
1359
1360       free_http_response(rsp);
1361       freez(hdr);
1362       return;
1363    }
1364
1365    log_error(LOG_LEVEL_CONNECT, "OK");
1366
1367    if (fwd->forward_host || (http->ssl == 0))
1368    {
1369       /* write the client's (modified) header to the server
1370        * (along with anything else that may be in the buffer)
1371        */
1372
1373       if (write_socket(csp->sfd, hdr, strlen(hdr))
1374        || (flush_socket(csp->sfd, csp) <  0))
1375       {
1376          log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
1377                     http->hostport);
1378
1379          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1380                    csp->ip_addr_str, http->ocmd);
1381
1382          rsp = error_response(csp, "connect-failed", errno);
1383
1384          if(rsp)
1385          {
1386             if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1387              || write_socket(csp->cfd, rsp->body, rsp->content_length))
1388             {
1389                log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1390             }
1391          }
1392
1393          free_http_response(rsp);
1394          freez(hdr);
1395          return;
1396       }
1397    }
1398    else
1399    {
1400       /*
1401        * We're running an SSL tunnel and we're not forwarding,
1402        * so just send the "connect succeeded" message to the
1403        * client, flush the rest, and get out of the way.
1404        */
1405       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
1406                 csp->ip_addr_str, http->ocmd);
1407
1408       if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
1409       {
1410          freez(hdr);
1411          return;
1412       }
1413       IOB_RESET(csp);
1414    }
1415
1416    /* we're finished with the client's header */
1417    freez(hdr);
1418
1419    maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
1420
1421    /* pass data between the client and server
1422     * until one or the other shuts down the connection.
1423     */
1424
1425    server_body = 0;
1426
1427    for (;;)
1428    {
1429 #ifdef __OS2__
1430       /*
1431        * FD_ZERO here seems to point to an errant macro which crashes.
1432        * So do this by hand for now...
1433        */
1434       memset(&rfds,0x00,sizeof(fd_set));
1435 #else
1436       FD_ZERO(&rfds);
1437 #endif
1438       FD_SET(csp->cfd, &rfds);
1439       FD_SET(csp->sfd, &rfds);
1440
1441       n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
1442
1443       if (n < 0)
1444       {
1445          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1446          return;
1447       }
1448
1449       /* this is the body of the browser's request
1450        * just read it and write it.
1451        */
1452
1453       if (FD_ISSET(csp->cfd, &rfds))
1454       {
1455          len = read_socket(csp->cfd, buf, sizeof(buf));
1456
1457          if (len <= 0)
1458          {
1459             break; /* "game over, man" */
1460          }
1461
1462          if (write_socket(csp->sfd, buf, (size_t)len))
1463          {
1464             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1465             return;
1466          }
1467          continue;
1468       }
1469
1470       /*
1471        * The server wants to talk.  It could be the header or the body.
1472        * If `hdr' is null, then it's the header otherwise it's the body.
1473        * FIXME: Does `hdr' really mean `host'? No.
1474        */
1475
1476
1477       if (FD_ISSET(csp->sfd, &rfds))
1478       {
1479          fflush( 0 );
1480          len = read_socket(csp->sfd, buf, sizeof(buf) - 1);
1481
1482          if (len < 0)
1483          {
1484             log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1485
1486             log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1487                       csp->ip_addr_str, http->ocmd);
1488
1489             rsp = error_response(csp, "connect-failed", errno);
1490
1491             if(rsp)
1492             {
1493                if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1494                 || write_socket(csp->cfd, rsp->body, rsp->content_length))
1495                {
1496                   log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1497                }
1498             }
1499
1500             free_http_response(rsp);
1501             return;
1502          }
1503
1504          /* Add a trailing zero.  This lets filter_popups
1505           * use string operations.
1506           */
1507          buf[len] = '\0';
1508
1509 #ifdef FEATURE_KILL_POPUPS
1510          /* Filter the popups on this read. */
1511          if (block_popups_now)
1512          {
1513             filter_popups(buf, csp);
1514          }
1515 #endif /* def FEATURE_KILL_POPUPS */
1516
1517          /* Normally, this would indicate that we've read
1518           * as much as the server has sent us and we can
1519           * close the client connection.  However, Microsoft
1520           * in its wisdom has released IIS/5 with a bug that
1521           * prevents it from sending the trailing \r\n in
1522           * a 302 redirect header (and possibly other headers).
1523           * To work around this if we've haven't parsed
1524           * a full header we'll append a trailing \r\n
1525           * and see if this now generates a valid one.
1526           *
1527           * This hack shouldn't have any impacts.  If we've
1528           * already transmitted the header or if this is a
1529           * SSL connection, then we won't bother with this
1530           * hack.  So we only work on partially received
1531           * headers.  If we append a \r\n and this still
1532           * doesn't generate a valid header, then we won't
1533           * transmit anything to the client.
1534           */
1535          if (len == 0)
1536          {
1537
1538             if (server_body || http->ssl)
1539             {
1540                /*
1541                 * If we have been buffering up the document,
1542                 * now is the time to apply content modification
1543                 * and send the result to the client.
1544                 */
1545                if (content_filter)
1546                {
1547                   /*
1548                    * If the content filter fails, use the original
1549                    * buffer and length.
1550                    * (see p != NULL ? p : csp->iob->cur below)
1551                    */
1552                   if (NULL == (p = (*content_filter)(csp)))
1553                   {
1554                      csp->content_length = csp->iob->eod - csp->iob->cur;
1555                   }
1556
1557                   hdr = sed(server_patterns_light, NULL, csp);
1558
1559                   if (hdr == NULL)
1560                   {
1561                      /* FIXME Should handle error properly */
1562                      log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1563                   }
1564
1565                   if (write_socket(csp->cfd, hdr, strlen(hdr))
1566                    || write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length))
1567                   {
1568                      log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
1569                      freez(hdr);
1570                      freez(p);
1571                      return;
1572                   }
1573
1574                   freez(hdr);
1575                   freez(p);
1576                }
1577
1578                break; /* "game over, man" */
1579             }
1580
1581             /*
1582              * This is NOT the body, so
1583              * Let's pretend the server just sent us a blank line.
1584              */
1585             len = sprintf(buf, "\r\n");
1586
1587             /*
1588              * Now, let the normal header parsing algorithm below do its
1589              * job.  If it fails, we'll exit instead of continuing.
1590              */
1591
1592             ms_iis5_hack = 1;
1593          }
1594
1595          /*
1596           * If this is an SSL connection or we're in the body
1597           * of the server document, just write it to the client,
1598           * unless we need to buffer the body for later content-filtering
1599           */
1600
1601          if (server_body || http->ssl)
1602          {
1603             if (content_filter)
1604             {
1605                /*
1606                 * If there is no memory left for buffering the content, or the buffer limit
1607                 * has been reached, switch to non-filtering mode, i.e. make & write the
1608                 * header, flush the iob and buf, and get out of the way.
1609                 */
1610                if (add_to_iob(csp, buf, len))
1611                {
1612                   size_t hdrlen;
1613                   int flushed;
1614
1615                   log_error(LOG_LEVEL_ERROR, "Flushing header and buffers. Stepping back from filtering.");
1616
1617                   hdr = sed(server_patterns, add_server_headers, csp);
1618                   if (hdr == NULL)
1619                   {
1620                      /* 
1621                       * Memory is too tight to even generate the header.
1622                       * Send our static "Out-of-memory" page.
1623                       */
1624                      log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
1625                      rsp = cgi_error_memory();
1626
1627                      if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1628                          || write_socket(csp->cfd, rsp->body, rsp->content_length))
1629                      {
1630                         log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1631                      }
1632                      return;
1633                   }
1634
1635                   hdrlen = strlen(hdr);
1636
1637                   if (write_socket(csp->cfd, hdr, hdrlen)
1638                    || ((flushed = flush_socket(csp->cfd, csp)) < 0)
1639                    || (write_socket(csp->cfd, buf, (size_t) len)))
1640                   {
1641                      log_error(LOG_LEVEL_CONNECT, "Flush header and buffers to client failed: %E");
1642
1643                      freez(hdr);
1644                      return;
1645                   }
1646
1647                   byte_count += hdrlen + flushed + len;
1648                   freez(hdr);
1649                   content_filter = NULL;
1650                   server_body = 1;
1651
1652                }
1653             }
1654             else
1655             {
1656                if (write_socket(csp->cfd, buf, (size_t)len))
1657                {
1658                   log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
1659                   return;
1660                }
1661             }
1662             byte_count += len;
1663             continue;
1664          }
1665          else
1666          {
1667             /* we're still looking for the end of the
1668              * server's header ... (does that make header
1669              * parsing an "out of body experience" ?
1670              */
1671
1672             /* 
1673              * buffer up the data we just read.  If that fails, 
1674              * there's little we can do but send our static
1675              * out-of-memory page.
1676              */
1677             if (add_to_iob(csp, buf, len))
1678             {
1679                log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
1680                rsp = cgi_error_memory();
1681                
1682                if (write_socket(csp->cfd, rsp->head, rsp->head_length)
1683                    || write_socket(csp->cfd, rsp->body, rsp->content_length))
1684                {
1685                   log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1686                }
1687                return;
1688             }
1689
1690             /* get header lines from the iob */
1691
1692             while ((p = get_header(csp)) != NULL)
1693             {
1694                if (*p == '\0')
1695                {
1696                   /* see following note */
1697                   break;
1698                }
1699                enlist(csp->headers, p);
1700                freez(p);
1701             }
1702
1703             /* NOTE: there are no "empty" headers so
1704              * if the pointer `p' is not NULL we must
1705              * assume that we reached the end of the
1706              * buffer before we hit the end of the header.
1707              */
1708
1709             if (p)
1710             {
1711                if (ms_iis5_hack)
1712                {
1713                   /* Well, we tried our MS IIS/5
1714                    * hack and it didn't work.
1715                    * The header is incomplete
1716                    * and there isn't anything
1717                    * we can do about it.
1718                    */
1719                   break;
1720                }
1721                else
1722                {
1723                   /* Since we have to wait for
1724                    * more from the server before
1725                    * we can parse the headers
1726                    * we just continue here.
1727                    */
1728                   continue;
1729                }
1730             }
1731
1732             /* we have now received the entire header.
1733              * filter it and send the result to the client
1734              */
1735
1736             hdr = sed(server_patterns, add_server_headers, csp);
1737             if (hdr == NULL)
1738             {
1739                /* FIXME Should handle error properly */
1740                log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
1741             }
1742
1743 #ifdef FEATURE_KILL_POPUPS
1744             /* Start blocking popups if appropriate. */
1745
1746             if ((csp->content_type & CT_TEXT) &&  /* It's a text / * MIME-Type */
1747                 !http->ssl    &&                  /* We talk plaintext */
1748                 block_popups)                     /* Policy allows */
1749             {
1750                block_popups_now = 1;
1751                /*
1752                 * Filter the part of the body that came in the same read
1753                 * as the last headers:
1754                 */
1755                filter_popups(csp->iob->cur, csp);
1756             }
1757
1758 #endif /* def FEATURE_KILL_POPUPS */
1759
1760             /* Buffer and pcrs filter this if appropriate. */
1761
1762             if ((csp->content_type & CT_TEXT) &&  /* It's a text / * MIME-Type */
1763                 !http->ssl    &&                  /* We talk plaintext */
1764                 pcrs_filter)                      /* Policy allows */
1765             {
1766                content_filter = pcrs_filter_response;
1767             }
1768
1769             /* Buffer and gif_deanimate this if appropriate. */
1770
1771             if ((csp->content_type & CT_GIF)  &&  /* It's an image/gif MIME-Type */
1772                 !http->ssl    &&                  /* We talk plaintext */
1773                 gif_deanimate)                    /* Policy allows */
1774             {
1775                content_filter = gif_deanimate_response;
1776             }
1777
1778             /* Buffer and jpg_inspect this if appropriate. */
1779
1780             if ((csp->content_type & CT_JPEG)  &&  /* It's an image/jpeg MIME-Type */
1781                 !http->ssl    &&                   /* We talk plaintext */
1782                 jpeg_inspect)                      /* Policy allows */
1783             {
1784                content_filter = jpeg_inspect_response;
1785             }
1786
1787             /*
1788              * Only write if we're not buffering for content modification
1789              */
1790             if (!content_filter)
1791             {
1792                /* write the server's (modified) header to
1793                 * the client (along with anything else that
1794                 * may be in the buffer)
1795                 */
1796
1797                if (write_socket(csp->cfd, hdr, strlen(hdr))
1798                 || ((len = flush_socket(csp->cfd, csp)) < 0))
1799                {
1800                   log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1801
1802                   /* the write failed, so don't bother
1803                    * mentioning it to the client...
1804                    * it probably can't hear us anyway.
1805                    */
1806                   freez(hdr);
1807                   return;
1808                }
1809
1810                byte_count += len;
1811             }
1812
1813             /* we're finished with the server's header */
1814
1815             freez(hdr);
1816             server_body = 1;
1817
1818             /* If this was a MS IIS/5 hack then it means
1819              * the server has already closed the
1820              * connection.  Nothing more to read.  Time
1821              * to bail.
1822              */
1823             if (ms_iis5_hack)
1824             {
1825                break;
1826             }
1827          }
1828          continue;
1829       }
1830
1831       return; /* huh? we should never get here */
1832    }
1833
1834    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1835              csp->ip_addr_str, http->ocmd, byte_count);
1836 }
1837
1838
1839 /*********************************************************************
1840  *
1841  * Function    :  serve
1842  *
1843  * Description :  This is little more than chat.  We only "serve" to
1844  *                to close any socket that chat may have opened.
1845  *
1846  * Parameters  :
1847  *          1  :  csp = Current client state (buffers, headers, etc...)
1848  *
1849  * Returns     :  N/A
1850  *
1851  *********************************************************************/
1852 #ifdef AMIGA
1853 void serve(struct client_state *csp)
1854 #else /* ifndef AMIGA */
1855 static void serve(struct client_state *csp)
1856 #endif /* def AMIGA */
1857 {
1858    chat(csp);
1859    close_socket(csp->cfd);
1860
1861    if (csp->sfd != JB_INVALID_SOCKET)
1862    {
1863       close_socket(csp->sfd);
1864    }
1865
1866    csp->flags &= ~CSP_FLAG_ACTIVE;
1867
1868 }
1869
1870
1871 #ifdef __BEOS__
1872 /*********************************************************************
1873  *
1874  * Function    :  server_thread
1875  *
1876  * Description :  We only exist to call `serve' in a threaded environment.
1877  *
1878  * Parameters  :
1879  *          1  :  data = Current client state (buffers, headers, etc...)
1880  *
1881  * Returns     :  Always 0.
1882  *
1883  *********************************************************************/
1884 static int32 server_thread(void *data)
1885 {
1886    serve((struct client_state *) data);
1887    return 0;
1888
1889 }
1890 #endif
1891
1892
1893 /*********************************************************************
1894  *
1895  * Function    :  usage
1896  *
1897  * Description :  Print usage info & exit.
1898  *
1899  * Parameters  :  Pointer to argv[0] for identifying ourselves
1900  *
1901  * Returns     :  No. ,-)
1902  *
1903  *********************************************************************/
1904 void usage(const char *myname)
1905 {
1906    printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
1907 #if !defined(unix)
1908            "Usage: %s [--help] [--version] [configfile]\n"
1909 #else
1910            "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1911 #endif
1912            "Aborting.\n", myname);
1913  
1914    exit(2);
1915
1916 }
1917
1918
1919 /*********************************************************************
1920  *
1921  * Function    :  main
1922  *
1923  * Description :  Load the config file and start the listen loop.
1924  *                This function is a lot more *sane* with the `load_config'
1925  *                and `listen_loop' functions; although it stills does
1926  *                a *little* too much for my taste.
1927  *
1928  * Parameters  :
1929  *          1  :  argc = Number of parameters (including $0).
1930  *          2  :  argv = Array of (char *)'s to the parameters.
1931  *
1932  * Returns     :  1 if : can't open config file, unrecognized directive,
1933  *                stats requested in multi-thread mode, can't open the
1934  *                log file, can't open the jar file, listen port is invalid,
1935  *                any load fails, and can't bind port.
1936  *
1937  *                Else main never returns, the process must be signaled
1938  *                to terminate execution.  Or, on Windows, use the
1939  *                "File", "Exit" menu option.
1940  *
1941  *********************************************************************/
1942 #ifdef __MINGW32__
1943 int real_main(int argc, const char *argv[])
1944 #else
1945 int main(int argc, const char *argv[])
1946 #endif
1947 {
1948    int argc_pos = 0;
1949 #ifdef HAVE_RANDOM
1950    unsigned int random_seed;
1951 #endif /* ifdef HAVE_RANDOM */
1952 #ifdef unix
1953    struct passwd *pw = NULL;
1954    struct group *grp = NULL;
1955    char *p;
1956    int do_chroot = 0;
1957 #endif
1958
1959    Argc = argc;
1960    Argv = argv;
1961
1962    configfile =
1963 #if !defined(_WIN32)
1964    "config"
1965 #else
1966    "config.txt"
1967 #endif
1968       ;
1969
1970    /*
1971     * Parse the command line arguments
1972     */
1973    while (++argc_pos < argc)
1974    {
1975 #ifdef _WIN32
1976       /* Check to see if the service must be installed or uninstalled */
1977       if (strncmp(argv[argc_pos], "--install", 9) == 0)
1978       {
1979          const char *pName = argv[argc_pos] + 9;
1980          if (*pName == ':')
1981             pName++;
1982          exit( (install_service(pName)) ? 0 : 1 );
1983       }
1984       else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
1985       {
1986          const char *pName = argv[argc_pos] + 11;
1987          if (*pName == ':')
1988             pName++;
1989          exit((uninstall_service(pName)) ? 0 : 1);
1990       }
1991       else if (strcmp(argv[argc_pos], "--service" ) == 0)
1992       {
1993          bRunAsService = TRUE;
1994          w32_set_service_cwd();
1995          atexit(w32_service_exit_notify);
1996       }
1997       else
1998 #endif /* defined(_WIN32) */
1999
2000
2001 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2002
2003       if (strcmp(argv[argc_pos], "--help") == 0)
2004       {
2005          usage(argv[0]);
2006       }
2007
2008       else if(strcmp(argv[argc_pos], "--version") == 0)
2009       {
2010          printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
2011          exit(0);
2012       }
2013
2014 #if defined(unix)
2015
2016      else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
2017       {
2018          no_daemon = 1;
2019       }
2020
2021       else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
2022       {
2023          if (++argc_pos == argc) usage(argv[0]);
2024          pidfile = strdup(argv[argc_pos]);
2025       }
2026
2027       else if (strcmp(argv[argc_pos], "--user" ) == 0)
2028       {
2029          if (++argc_pos == argc) usage(argv[argc_pos]);
2030
2031          if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
2032          {
2033             *p++ = '\0';
2034             if (NULL == (grp = getgrnam(p)))
2035             {
2036                log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
2037             }
2038          }
2039
2040          if (NULL == (pw = getpwnam(argv[argc_pos])))
2041          {
2042             log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
2043          }
2044
2045          if (p != NULL) *--p = '\0';
2046       }
2047
2048       else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
2049       {
2050          do_chroot = 1;
2051       }
2052
2053 #endif /* defined(unix) */
2054 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
2055       {
2056          configfile = argv[argc_pos];
2057       }
2058
2059    } /* -END- while (more arguments) */
2060
2061 #if defined(unix)
2062    if ( *configfile != '/' )
2063    {
2064       char *abs_file, cwd[1024];
2065
2066       /* make config-filename absolute here */
2067       if ( !(getcwd(cwd, sizeof(cwd))))
2068       {
2069          perror("get working dir failed");
2070          exit( 1 );
2071       }
2072
2073       if (!(basedir = strdup(cwd))
2074       || (!(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 ))))
2075       {
2076          perror("malloc failed");
2077          exit( 1 );
2078       }
2079       strcpy( abs_file, basedir );
2080       strcat( abs_file, "/" );
2081       strcat( abs_file, configfile );
2082       configfile = abs_file;
2083    }
2084 #endif /* defined unix */
2085
2086
2087    files->next = NULL;
2088    clients->next = NULL;
2089
2090 #ifdef AMIGA
2091    InitAmiga();
2092 #elif defined(_WIN32)
2093    InitWin32();
2094 #endif
2095
2096 #ifdef FEATURE_PTHREAD
2097    /*
2098     * Prepare global mutex semaphores
2099     */
2100    pthread_mutex_init(&log_mutex,0);
2101    pthread_mutex_init(&log_init_mutex,0);
2102
2103 #ifndef HAVE_GMTIME_R
2104    pthread_mutex_init(&gmtime_mutex,0);
2105 #endif /* ndef HAVE_GMTIME_R */
2106
2107 #ifndef HAVE_LOCALTIME_R
2108    pthread_mutex_init(&localtime_mutex,0);
2109 #endif /* ndef HAVE_GMTIME_R */
2110
2111 #ifndef HAVE_GETHOSTBYADDR_R
2112    pthread_mutex_init(&gethostbyaddr_mutex,0);
2113 #endif /* ndef HAVE_GETHOSTBYADDR_R */
2114
2115 #ifndef HAVE_GETHOSTBYNAME_R
2116    pthread_mutex_init(&gethostbyname_mutex,0);
2117 #endif /* ndef HAVE_GETHOSTBYNAME_R */
2118 #endif /* FEATURE_PTHREAD */
2119
2120 #ifdef HAVE_RANDOM
2121    random_seed = (unsigned int)time(NULL);
2122    srandom(random_seed);
2123 #endif /* ifdef HAVE_RANDOM */
2124
2125    /*
2126     * Unix signal handling
2127     *
2128     * Catch the abort, interrupt and terminate signals for a graceful exit
2129     * Catch the hangup signal so the errlog can be reopened.
2130     * Ignore the broken pipe signals (FIXME: Why?)
2131     */
2132 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
2133 {
2134    int idx;
2135    const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
2136    const int ignored_signals[] = { SIGPIPE, 0 };
2137
2138    for (idx = 0; catched_signals[idx] != 0; idx++)
2139    {
2140 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */ 
2141       if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
2142 #else
2143       if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
2144 #endif /* ifdef sun */
2145       {
2146          log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
2147       }
2148    }
2149
2150    for (idx = 0; ignored_signals[idx] != 0; idx++)
2151    {
2152       if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
2153       {
2154          log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
2155       }
2156    }
2157
2158 }
2159 #else /* ifdef _WIN32 */
2160 # ifdef _WIN_CONSOLE
2161    /*
2162     * We *are* in a windows console app.
2163     * Print a verbose messages about FAQ's and such
2164     */
2165    printf(win32_blurb);
2166 # endif /* def _WIN_CONSOLE */
2167 #endif /* def _WIN32 */
2168
2169
2170    /* Initialize the CGI subsystem */
2171    cgi_init_error_messages();
2172
2173    /*
2174     * If runnig on unix and without the --nodaemon
2175     * option, become a daemon. I.e. fork, detach
2176     * from tty and get process group leadership
2177     */
2178 #if defined(unix)
2179 {
2180    pid_t pid = 0;
2181 #if 0
2182    int   fd;
2183 #endif
2184
2185    if (!no_daemon)
2186    {
2187       pid  = fork();
2188
2189       if ( pid < 0 ) /* error */
2190       {
2191          perror("fork");
2192          exit( 3 );
2193       }
2194       else if ( pid != 0 ) /* parent */
2195       {
2196          int status;
2197          pid_t wpid;
2198          /*
2199           * must check for errors
2200           * child died due to missing files aso
2201           */
2202          sleep( 1 );
2203          wpid = waitpid( pid, &status, WNOHANG );
2204          if ( wpid != 0 )
2205          {
2206             exit( 1 );
2207          }
2208          exit( 0 );
2209       }
2210       /* child */
2211 #if 1
2212       /* Should be more portable, but not as well tested */
2213       setsid();
2214 #else /* !1 */
2215 #ifdef __FreeBSD__
2216       setpgrp(0,0);
2217 #else /* ndef __FreeBSD__ */
2218       setpgrp();
2219 #endif /* ndef __FreeBSD__ */
2220       fd = open("/dev/tty", O_RDONLY);
2221       if ( fd )
2222       {
2223          /* no error check here */
2224          ioctl( fd, TIOCNOTTY,0 );
2225          close ( fd );
2226       }
2227 #endif /* 1 */
2228       /* FIXME: should close stderr (fd 2) here too, but the test
2229        * for existence
2230        * and load config file is done in listen_loop() and puts
2231        * some messages on stderr there.
2232        */
2233
2234       close( 0 );
2235       close( 1 );
2236       chdir("/");
2237
2238    } /* -END- if (!no_daemon) */
2239
2240    /*
2241     * As soon as we have written the PID file, we can switch
2242     * to the user and group ID indicated by the --user option
2243     */
2244    write_pid_file();
2245    
2246    if (NULL != pw)
2247    {
2248       if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
2249       {
2250          log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
2251       }
2252       if (do_chroot)
2253       {
2254          if (!pw->pw_dir)
2255          {
2256             log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
2257          }
2258          if (chroot(pw->pw_dir) < 0)
2259          {
2260             log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
2261          }
2262          if (chdir ("/"))
2263          {
2264             log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
2265          }
2266       }
2267       if (setuid(pw->pw_uid))
2268       {
2269          log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
2270       }
2271       if (do_chroot)
2272       {
2273          char putenv_dummy[64];
2274
2275          strcpy(putenv_dummy, "HOME=/");
2276          if (putenv(putenv_dummy) != 0)
2277          {
2278             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
2279          }                
2280
2281          snprintf(putenv_dummy, 64, "USER=%s", pw->pw_name);
2282          if (putenv(putenv_dummy) != 0)
2283          {
2284             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
2285          }
2286       }
2287    }
2288    else if (do_chroot)
2289    {
2290       log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
2291    }
2292 }
2293 #endif /* defined unix */
2294
2295 #ifdef _WIN32
2296    /* This will be FALSE unless the command line specified --service
2297     */
2298    if (bRunAsService)
2299    {
2300       /* Yup, so now we must attempt to establish a connection 
2301        * with the service dispatcher. This will only work if this
2302        * process was launched by the service control manager to
2303        * actually run as a service. If this isn't the case, i've
2304        * known it take around 30 seconds or so for the call to return.
2305        */
2306
2307       /* The StartServiceCtrlDispatcher won't return until the service is stopping */
2308       if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
2309       {
2310          /* Service has run, and at this point is now being stopped, so just return */
2311          return 0;
2312       }
2313
2314 #ifdef _WIN_CONSOLE
2315       printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
2316 #endif
2317       /* An error occurred. Usually it's because --service was wrongly specified
2318        * and we were unable to connect to the Service Control Dispatcher because
2319        * it wasn't expecting us and is therefore not listening.
2320        *
2321        * For now, just continue below to call the listen_loop function.
2322        */
2323    }
2324 #endif /* def _WIN32 */
2325
2326    listen_loop();
2327
2328    /* NOTREACHED */
2329    return(-1);
2330
2331 }
2332
2333
2334 /*********************************************************************
2335  *
2336  * Function    :  bind_port_helper
2337  *
2338  * Description :  Bind the listen port.  Handles logging, and aborts
2339  *                on failure.
2340  *
2341  * Parameters  :
2342  *          1  :  config = Privoxy configuration.  Specifies port
2343  *                         to bind to.
2344  *
2345  * Returns     :  Port that was opened.
2346  *
2347  *********************************************************************/
2348 static jb_socket bind_port_helper(struct configuration_spec * config)
2349 {
2350    int result;
2351    jb_socket bfd;
2352
2353    if ( (config->haddr != NULL)
2354      && (config->haddr[0] == '1')
2355      && (config->haddr[1] == '2')
2356      && (config->haddr[2] == '7')
2357      && (config->haddr[3] == '.') )
2358    {
2359       log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
2360                 config->hport);
2361    }
2362    else if (config->haddr == NULL)
2363    {
2364       log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
2365                 config->hport);
2366    }
2367    else
2368    {
2369       log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
2370                 config->hport, config->haddr);
2371    }
2372
2373    result = bind_port(config->haddr, config->hport, &bfd);
2374
2375    if (result < 0)
2376    {
2377       switch(result)
2378       {
2379          case -3 :
2380             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
2381                "There may be another Privoxy or some other "
2382                "proxy running on port %d",
2383                (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
2384                       config->hport, config->hport);
2385
2386          case -2 :
2387             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: " 
2388                "The hostname is not resolvable",
2389                (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2390
2391          default :
2392             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
2393                (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
2394       }
2395
2396       /* shouldn't get here */
2397       return JB_INVALID_SOCKET;
2398    }
2399
2400    config->need_bind = 0;
2401
2402    return bfd;
2403 }
2404
2405
2406 #ifdef _WIN32
2407 /* Without this simple workaround we get this compiler warning from _beginthread
2408  *     warning C4028: formal parameter 1 different from declaration
2409  */
2410 void w32_service_listen_loop(void *p)
2411 {
2412    listen_loop();
2413 }
2414 #endif /* def _WIN32 */
2415
2416
2417 /*********************************************************************
2418  *
2419  * Function    :  listen_loop
2420  *
2421  * Description :  bind the listen port and enter a "FOREVER" listening loop.
2422  *
2423  * Parameters  :  N/A
2424  *
2425  * Returns     :  Never.
2426  *
2427  *********************************************************************/
2428 static void listen_loop(void)
2429 {
2430    struct client_state *csp = NULL;
2431    jb_socket bfd;
2432    struct configuration_spec * config;
2433
2434    config = load_config();
2435
2436    bfd = bind_port_helper(config);
2437
2438 #ifdef FEATURE_GRACEFUL_TERMINATION
2439    while (!g_terminate)
2440 #else
2441    for (;;)
2442 #endif
2443    {
2444 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
2445       while (waitpid(-1, NULL, WNOHANG) > 0)
2446       {
2447          /* zombie children */
2448       }
2449 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
2450
2451       /*
2452        * Free data that was used by died threads
2453        */
2454       sweep();
2455
2456 #if defined(unix)
2457       /*
2458        * Re-open the errlog after HUP signal
2459        */
2460       if (received_hup_signal)
2461       {
2462          init_error_log(Argv[0], config->logfile, config->debug);
2463          received_hup_signal = 0;
2464       }
2465 #endif
2466
2467 #ifdef __OS2__
2468 #ifdef FEATURE_COOKIE_JAR
2469       /*
2470        * Need a workaround here: we have to fclose() the jarfile, or we die because it's
2471        * already open.  I think unload_configfile() is not being run, which should do
2472        * this work.  Until that can get resolved, we'll use this workaround.
2473        */
2474        if (csp)
2475          if(csp->config)
2476            if (csp->config->jar)
2477            {
2478              fclose(csp->config->jar);
2479              csp->config->jar = NULL;
2480            }
2481 #endif /* FEATURE_COOKIE_JAR */
2482 #endif /* __OS2__ */
2483
2484       if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
2485       {
2486          log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
2487          continue;
2488       }
2489
2490       csp->flags |= CSP_FLAG_ACTIVE;
2491       csp->sfd    = JB_INVALID_SOCKET;
2492
2493       csp->config = config = load_config();
2494
2495       if ( config->need_bind )
2496       {
2497          /*
2498           * Since we were listening to the "old port", we will not see
2499           * a "listen" param change until the next IJB request.  So, at
2500           * least 1 more request must be made for us to find the new
2501           * setting.  I am simply closing the old socket and binding the
2502           * new one.
2503           *
2504           * Which-ever is correct, we will serve 1 more page via the
2505           * old settings.  This should probably be a "show-proxy-args"
2506           * request.  This should not be a so common of an operation
2507           * that this will hurt people's feelings.
2508           */
2509
2510          close_socket(bfd);
2511
2512          bfd = bind_port_helper(config);
2513       }
2514
2515       log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
2516
2517       if (!accept_connection(csp, bfd))
2518       {
2519          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
2520
2521 #ifdef AMIGA
2522          if(!childs)
2523          {
2524             exit(1);
2525          }
2526 #endif
2527          freez(csp);
2528          continue;
2529       }
2530       else
2531       {
2532          log_error(LOG_LEVEL_CONNECT, "OK");
2533       }
2534
2535 #ifdef FEATURE_TOGGLE
2536       if (global_toggle_state)
2537       {
2538          csp->flags |= CSP_FLAG_TOGGLED_ON;
2539       }
2540 #endif /* def FEATURE_TOGGLE */
2541
2542       if (run_loader(csp))
2543       {
2544          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
2545          /* Never get here - LOG_LEVEL_FATAL causes program exit */
2546       }
2547
2548 #ifdef FEATURE_ACL
2549       if (block_acl(NULL,csp))
2550       {
2551          log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
2552          close_socket(csp->cfd);
2553          freez(csp);
2554          continue;
2555       }
2556 #endif /* def FEATURE_ACL */
2557
2558       /* add it to the list of clients */
2559       csp->next = clients->next;
2560       clients->next = csp;
2561
2562       if (config->multi_threaded)
2563       {
2564          int child_id;
2565
2566 /* this is a switch () statment in the C preprocessor - ugh */
2567 #undef SELECTED_ONE_OPTION
2568
2569 /* Use Pthreads in preference to native code */
2570 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
2571 #define SELECTED_ONE_OPTION
2572          {
2573             pthread_t the_thread;
2574             pthread_attr_t attrs;
2575
2576             pthread_attr_init(&attrs);
2577             pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
2578             errno = pthread_create(&the_thread, &attrs,
2579                (void*)serve, csp);
2580             child_id = errno ? -1 : 0;
2581             pthread_attr_destroy(&attrs);
2582          }
2583 #endif
2584
2585 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
2586 #define SELECTED_ONE_OPTION
2587          child_id = _beginthread(
2588             (void (*)(void *))serve,
2589             64 * 1024,
2590             csp);
2591 #endif
2592
2593 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
2594 #define SELECTED_ONE_OPTION
2595          child_id = _beginthread(
2596             (void(* _Optlink)(void*))serve,
2597             NULL,
2598             64 * 1024,
2599             csp);
2600 #endif
2601
2602 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
2603 #define SELECTED_ONE_OPTION
2604          {
2605             thread_id tid = spawn_thread
2606                (server_thread, "server", B_NORMAL_PRIORITY, csp);
2607
2608             if ((tid >= 0) && (resume_thread(tid) == B_OK))
2609             {
2610                child_id = (int) tid;
2611             }
2612             else
2613             {
2614                child_id = -1;
2615             }
2616          }
2617 #endif
2618
2619 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
2620 #define SELECTED_ONE_OPTION
2621          csp->cfd = ReleaseSocket(csp->cfd, -1);
2622          
2623          if((child_id = (int)CreateNewProcTags(
2624             NP_Entry, (ULONG)server_thread,
2625             NP_Output, Output(),
2626             NP_CloseOutput, FALSE,
2627             NP_Name, (ULONG)"privoxy child",
2628             NP_StackSize, 200*1024,
2629             TAG_DONE)))
2630          {
2631             childs++;
2632             ((struct Task *)child_id)->tc_UserData = csp;
2633             Signal((struct Task *)child_id, SIGF_SINGLE);
2634             Wait(SIGF_SINGLE);
2635          }
2636 #endif
2637
2638 #if !defined(SELECTED_ONE_OPTION)
2639          child_id = fork();
2640
2641          /* This block is only needed when using fork().
2642           * When using threads, the server thread was
2643           * created and run by the call to _beginthread().
2644           */
2645          if (child_id == 0)   /* child */
2646          {
2647             int rc = 0;
2648 #ifdef FEATURE_TOGGLE
2649             int inherited_toggle_state = global_toggle_state;
2650 #endif /* def FEATURE_TOGGLE */
2651
2652             serve(csp);
2653
2654             /* 
2655              * If we've been toggled or we've blocked the request, tell Mom
2656              */
2657
2658 #ifdef FEATURE_TOGGLE
2659             if (inherited_toggle_state != global_toggle_state)
2660             {
2661                rc |= RC_FLAG_TOGGLED;
2662             }
2663 #endif /* def FEATURE_TOGGLE */
2664
2665 #ifdef FEATURE_STATISTICS  
2666             if (csp->flags & CSP_FLAG_REJECTED)
2667             {
2668                rc |= RC_FLAG_BLOCKED;
2669             }
2670 #endif /* ndef FEATURE_STATISTICS */
2671
2672             _exit(rc);
2673          }
2674          else if (child_id > 0) /* parent */
2675          {
2676             /* in a fork()'d environment, the parent's
2677              * copy of the client socket and the CSP
2678              * are not used.
2679              */
2680             int child_status;
2681 #if !defined(_WIN32) && !defined(__CYGWIN__)
2682
2683             wait( &child_status );
2684
2685             /* 
2686              * Evaluate child's return code: If the child has
2687              *  - been toggled, toggle ourselves
2688              *  - blocked its request, bump up the stats counter
2689              */
2690
2691 #ifdef FEATURE_TOGGLE
2692             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
2693             {
2694                global_toggle_state = !global_toggle_state;
2695             }
2696 #endif /* def FEATURE_TOGGLE */
2697
2698 #ifdef FEATURE_STATISTICS
2699             urls_read++;
2700             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
2701             {
2702                urls_rejected++;
2703             }
2704 #endif /* def FEATURE_STATISTICS */ 
2705
2706 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
2707             close_socket(csp->cfd);
2708             csp->flags &= ~CSP_FLAG_ACTIVE;
2709          }
2710 #endif
2711
2712 #undef SELECTED_ONE_OPTION
2713 /* end of cpp switch () */
2714
2715          if (child_id < 0) /* failed */
2716          {
2717             char buf[BUFFER_SIZE];
2718
2719             log_error(LOG_LEVEL_ERROR, "can't fork: %E");
2720
2721             sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
2722
2723             write_socket(csp->cfd, buf, strlen(buf));
2724             close_socket(csp->cfd);
2725             csp->flags &= ~CSP_FLAG_ACTIVE;
2726             sleep(5);
2727             continue;
2728          }
2729       }
2730       else
2731       {
2732          serve(csp);
2733       }
2734    }
2735
2736    /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
2737
2738    /* Clean up.  Aim: free all memory (no leaks) */
2739 #ifdef FEATURE_GRACEFUL_TERMINATION
2740
2741    log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
2742
2743    unload_current_config_file();
2744    unload_current_actions_file();
2745    unload_current_re_filterfile();
2746 #ifdef FEATURE_TRUST
2747    unload_current_trust_file();
2748 #endif
2749
2750    if (config->multi_threaded)
2751    {
2752       int i = 60;
2753       do
2754       {
2755          sleep(1);
2756          sweep();
2757       } while ((clients->next != NULL) && (--i > 0));
2758
2759       if (i <= 0)
2760       {
2761          log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
2762       }
2763    }
2764    sweep();
2765    sweep();
2766
2767 #if defined(unix)
2768    freez(basedir);
2769 #endif
2770    freez(configfile);
2771
2772 #ifdef FEATURE_COOKIE_JAR
2773    if (NULL != config->jar)
2774    {
2775       fclose(config->jar);
2776    }
2777 #endif
2778
2779 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
2780    /* Cleanup - remove taskbar icon etc. */
2781    TermLogWindow();
2782 #endif
2783
2784    exit(0);
2785 #endif /* FEATURE_GRACEFUL_TERMINATION */
2786
2787 }
2788
2789
2790 /*
2791   Local Variables:
2792   tab-width: 3
2793   end:
2794 */