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