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