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