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