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