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