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