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