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