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