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