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