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