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