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