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