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