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