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