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