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