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