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