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