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