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