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