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