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