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