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