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