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