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