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