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