Typo: inspect_jpegs, not inspect-jpegs in form
[privoxy.git] / src / jcc.c
1 const char jcc_rcs[] = "$Id: jcc.c,v 2.7 2003/09/25 01:44:33 david__schmidt Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/src/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 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 2.7  2003/09/25 01:44:33  david__schmidt
37  *    Resyncing HEAD with v_3_0_branch for two OSX fixes:
38  *    Making thread IDs look sane in the logfile for Mach kernels,
39  *    and fixing multithreading crashes due to thread-unsafe
40  *    system calls.
41  *    and
42  *
43  *    Revision 2.6  2003/06/24 12:24:24  oes
44  *    Added a line plus Fix-me as a reminder to fix broken force handling in trunk. Thanks to lionel for the hint
45  *
46  *    Revision 2.5  2003/01/26 20:24:26  david__schmidt
47  *    Updated activity console instrumentation locations
48  *
49  *    Revision 2.4  2002/12/28 03:58:19  david__schmidt
50  *    Initial drop of dashboard instrumentation - enabled with
51  *    --enable-activity-console
52  *
53  *    Revision 2.3  2002/07/18 22:06:12  jongfoster
54  *    Trivial formatting changes
55  *
56  *    Revision 2.2  2002/07/12 04:26:17  agotneja
57  *    Re-factored 'chat()' to become understandable and maintainable as
58  *    a first step in adding Transparent Proxy functionality.
59  *
60  *    Added several new static functions in jcc.c, and moved some data
61  *    parameters up into project.h to allow them to be passed between
62  *    the new functions.
63  *
64  *    Revision 1.91  2002/04/08 20:35:58  swa
65  *    fixed JB spelling
66  *
67  *    Revision 1.90  2002/04/02 14:57:28  oes
68  *    Made sending wafers independent of FEATURE_COOKIE_JAR
69  *
70  *    Revision 1.89  2002/03/31 17:18:59  jongfoster
71  *    Win32 only: Enabling STRICT to fix a VC++ compile warning.
72  *
73  *    Revision 1.88  2002/03/27 14:32:43  david__schmidt
74  *    More compiler warning message maintenance
75  *
76  *    Revision 1.87  2002/03/26 22:29:54  swa
77  *    we have a new homepage!
78  *
79  *    Revision 1.86  2002/03/25 17:04:55  david__schmidt
80  *    Workaround for closing the jarfile before load_config() comes around again
81  *
82  *    Revision 1.85  2002/03/24 15:23:33  jongfoster
83  *    Name changes
84  *
85  *    Revision 1.84  2002/03/24 13:25:43  swa
86  *    name change related issues
87  *
88  *    Revision 1.83  2002/03/16 23:54:06  jongfoster
89  *    Adding graceful termination feature, to help look for memory leaks.
90  *    If you enable this (which, by design, has to be done by hand
91  *    editing config.h) and then go to http://i.j.b/die, then the program
92  *    will exit cleanly after the *next* request.  It should free all the
93  *    memory that was used.
94  *
95  *    Revision 1.82  2002/03/13 00:27:05  jongfoster
96  *    Killing warnings
97  *
98  *    Revision 1.81  2002/03/12 01:42:50  oes
99  *    Introduced modular filters
100  *
101  *    Revision 1.80  2002/03/11 22:07:05  david__schmidt
102  *    OS/2 port maintenance:
103  *    - Fixed EMX build - it had decayed a little
104  *    - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
105  *      substituted a memset for now.
106  *
107  *    Revision 1.79  2002/03/09 20:03:52  jongfoster
108  *    - Making various functions return int rather than size_t.
109  *      (Undoing a recent change).  Since size_t is unsigned on
110  *      Windows, functions like read_socket that return -1 on
111  *      error cannot return a size_t.
112  *
113  *      THIS WAS A MAJOR BUG - it caused frequent, unpredictable
114  *      crashes, and also frequently caused JB to jump to 100%
115  *      CPU and stay there.  (Because it thought it had just
116  *      read ((unsigned)-1) == 4Gb of data...)
117  *
118  *    - The signature of write_socket has changed, it now simply
119  *      returns success=0/failure=nonzero.
120  *
121  *    - Trying to get rid of a few warnings --with-debug on
122  *      Windows, I've introduced a new type "jb_socket".  This is
123  *      used for the socket file descriptors.  On Windows, this
124  *      is SOCKET (a typedef for unsigned).  Everywhere else, it's
125  *      an int.  The error value can't be -1 any more, so it's
126  *      now JB_INVALID_SOCKET (which is -1 on UNIX, and in
127  *      Windows it maps to the #define INVALID_SOCKET.)
128  *
129  *    - The signature of bind_port has changed.
130  *
131  *    Revision 1.78  2002/03/08 21:35:04  oes
132  *    Added optional group supplement to --user option. Will now use default group of user if no group given
133  *
134  *    Revision 1.77  2002/03/07 03:52:06  oes
135  *     - Fixed compiler warnings etc
136  *     - Improved handling of failed DNS lookups
137  *
138  *    Revision 1.76  2002/03/06 22:54:35  jongfoster
139  *    Automated function-comment nitpicking.
140  *
141  *    Revision 1.75  2002/03/06 10:02:19  oes
142  *    Fixed stupid bug when --user was not given
143  *
144  *    Revision 1.74  2002/03/06 00:49:31  jongfoster
145  *    Fixing warning on Windows
146  *    Making #ifdefs that refer to the same variable consistently
147  *    use #ifdef unix rather than mixing #ifdef unix & #ifndef OS2
148  *
149  *    Revision 1.73  2002/03/05 23:57:30  hal9
150  *    Stray character 's' on line 1618 was breaking build.
151  *
152  *    Revision 1.72  2002/03/05 21:33:45  david__schmidt
153  *    - Re-enable OS/2 building after new parms were added
154  *    - Fix false out of memory report when resolving CGI templates when no IP
155  *      address is available of failed attempt (a la no such domain)
156  *
157  *    Revision 1.71  2002/03/05 18:13:56  oes
158  *    Added --user option
159  *
160  *    Revision 1.70  2002/03/05 04:52:42  oes
161  *    Deleted non-errlog debugging code
162  *
163  *    Revision 1.69  2002/03/04 23:50:00  jongfoster
164  *    Splitting off bind_port() call into bind_port_helper(), with
165  *    improved logging.
166  *
167  *    Revision 1.68  2002/03/04 20:17:32  oes
168  *    Fixed usage info
169  *
170  *    Revision 1.67  2002/03/04 18:18:57  oes
171  *    - Removed _DEBUG mode
172  *    - Cleand up cmdline parsing
173  *    - Introduced --no-daemon, --pidfile options
174  *    - Cleaned up signal handling:
175  *      - Terminate cleanly on INT, TERM and ABRT
176  *      - Schedule logfile for re-opening on HUP
177  *      - Ignore CHLD and PIPE
178  *      - Leave the rest with their default handlers
179  *      - Uniform handler registration
180  *    - Added usage() function
181  *    - Played styleguide police
182  *
183  *    Revision 1.66  2002/03/03 15:06:55  oes
184  *    Re-enabled automatic config reloading
185  *
186  *    Revision 1.65  2002/03/03 14:49:11  oes
187  *    Fixed CLF logging: Now uses client's original HTTP request
188  *
189  *    Revision 1.64  2002/03/03 09:18:03  joergs
190  *    Made jumbjuster work on AmigaOS again.
191  *
192  *    Revision 1.63  2002/03/02 04:14:50  david__schmidt
193  *    Clean up a little CRLF unpleasantness that suddenly appeared
194  *
195  *    Revision 1.62  2002/02/20 23:17:23  jongfoster
196  *    Detecting some out-of memory conditions and exiting with a log message.
197  *
198  *    Revision 1.61  2002/01/17 21:01:52  jongfoster
199  *    Moving all our URL and URL pattern parsing code to urlmatch.c.
200  *
201  *    Revision 1.60  2001/12/30 14:07:32  steudten
202  *    - Add signal handling (unix)
203  *    - Add SIGHUP handler (unix)
204  *    - Add creation of pidfile (unix)
205  *    - Add action 'top' in rc file (RH)
206  *    - Add entry 'SIGNALS' to manpage
207  *    - Add exit message to logfile (unix)
208  *
209  *    Revision 1.59  2001/12/13 14:07:18  oes
210  *    Fixed Bug: 503 error page now sent OK
211  *
212  *    Revision 1.58  2001/11/30 23:37:24  jongfoster
213  *    Renaming the Win32 config file to config.txt - this is almost the
214  *    same as the corresponding UNIX name "config"
215  *
216  *    Revision 1.57  2001/11/16 00:47:43  jongfoster
217  *    Changing the tty-disconnection code to use setsid().
218  *
219  *    Revision 1.56  2001/11/13 20:20:54  jongfoster
220  *    Tabs->spaces, fixing a bug with missing {} around an if()
221  *
222  *    Revision 1.55  2001/11/13 20:14:53  jongfoster
223  *    Patch for FreeBSD setpgrp() as suggested by Alexander Lazic
224  *
225  *    Revision 1.54  2001/11/07 00:03:14  steudten
226  *    Give reliable return value if an error
227  *    occurs not just 0 with new daemon mode.
228  *
229  *    Revision 1.53  2001/11/05 21:41:43  steudten
230  *    Add changes to be a real daemon just for unix os.
231  *    (change cwd to /, detach from controlling tty, set
232  *    process group and session leader to the own process.
233  *    Add DBG() Macro.
234  *    Add some fatal-error log message for failed malloc().
235  *    Add '-d' if compiled with 'configure --with-debug' to
236  *    enable debug output.
237  *
238  *    Revision 1.52  2001/10/26 20:11:20  jongfoster
239  *    Fixing type mismatch
240  *
241  *    Revision 1.51  2001/10/26 17:38:28  oes
242  *    Cosmetics
243  *
244  *    Revision 1.50  2001/10/25 03:40:48  david__schmidt
245  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
246  *    threads to call select() simultaneously.  So, it's time to do a real, live,
247  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
248  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
249  *
250  *    Revision 1.49  2001/10/23 21:41:35  jongfoster
251  *    Added call to initialize the (statically-allocated of course)
252  *    "out of memory" CGI response.
253  *
254  *    Revision 1.48  2001/10/10 19:56:46  jongfoster
255  *    Moving some code that wasn't cookie-related out of an #ifdef
256  *    FEATURE_COOKIE_JAR
257  *
258  *    Revision 1.47  2001/10/10 16:44:36  oes
259  *    Added CONNECT destination port limitation check
260  *
261  *    Revision 1.46  2001/10/08 15:17:41  oes
262  *    Re-enabled SSL forwarding
263  *
264  *    Revision 1.45  2001/10/07 15:42:11  oes
265  *    Replaced 6 boolean members of csp with one bitmap (csp->flags)
266  *
267  *    Moved downgrading of the HTTP version from parse_http_request to
268  *      chat(), since we can't decide if it is necessary before we have
269  *      determined the actions for the URL. The HTTP command is now
270  *      *always* re-built so the repairs need no longer be special-cased.
271  *
272  *    filter_popups now gets a csp pointer so it can raise the new
273  *      CSP_FLAG_MODIFIED flag.
274  *
275  *    Bugfix
276  *
277  *    Added configurable size limit for the IOB. If the IOB grows so
278  *      large that the next read would exceed the limit, the header
279  *      is generated, and the header & unfiltered buffer are flushed
280  *      to the client. Chat then continues in non-buffering,
281  *      non-filtering body mode.
282  *
283  *    Revision 1.44  2001/10/02 18:13:57  oes
284  *    Ooops
285  *
286  *    Revision 1.43  2001/10/02 15:32:13  oes
287  *    Moved generation of hdr
288  *
289  *    Revision 1.42  2001/09/21 23:02:02  david__schmidt
290  *    Cleaning up 2 compiler warnings on OS/2.
291  *
292  *    Revision 1.41  2001/09/16 17:05:14  jongfoster
293  *    Removing unused #include showarg.h
294  *
295  *    Revision 1.40  2001/09/16 15:41:45  jongfoster
296  *    Fixing signed/unsigned comparison warning.
297  *
298  *    Revision 1.39  2001/09/16 13:21:27  jongfoster
299  *    Changes to use new list functions.
300  *
301  *    Revision 1.38  2001/09/16 13:01:46  jongfoster
302  *    Removing redundant function call that zeroed zalloc()'d memory.
303  *
304  *    Revision 1.37  2001/09/10 11:12:24  oes
305  *    Deleted unused variable
306  *
307  *    Revision 1.36  2001/09/10 10:56:15  oes
308  *    Silenced compiler warnings
309  *
310  *    Revision 1.35  2001/07/31 14:44:22  oes
311  *    Deleted unused size parameter from filter_popups()
312  *
313  *    Revision 1.34  2001/07/30 22:08:36  jongfoster
314  *    Tidying up #defines:
315  *    - All feature #defines are now of the form FEATURE_xxx
316  *    - Permanently turned off WIN_GUI_EDIT
317  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
318  *
319  *    Revision 1.33  2001/07/29 19:32:00  jongfoster
320  *    Renaming _main() [mingw32 only] to real_main(), for ANSI compliance.
321  *
322  *    Revision 1.32  2001/07/29 18:47:05  jongfoster
323  *    Adding missing #include "loadcfg.h"
324  *
325  *    Revision 1.31  2001/07/29 12:17:48  oes
326  *    Applied pthread fix by Paul Lieverse
327  *
328  *    Revision 1.30  2001/07/25 22:57:13  jongfoster
329  *    __BEOS__ no longer overrides FEATURE_PTHREAD.
330  *    This is because FEATURE_PTHREAD will soon be widely used, so I
331  *    want to keep it simple.
332  *
333  *    Revision 1.29  2001/07/24 12:47:06  oes
334  *    Applied BeOS support update by Eugenia
335  *
336  *    Revision 1.28  2001/07/23 13:26:12  oes
337  *    Fixed bug in popup-killing for the first read that caused binary garbage to be sent between headers and body
338  *
339  *    Revision 1.27  2001/07/19 19:09:47  haroon
340  *    - Added code to take care of the situation where while processing the first
341  *      server response (which includes the server header), after finding the end
342  *      of the headers we were not looking past the end of the headers for
343  *      content modification. I enabled it for filter_popups.
344  *      Someone else should look to see if other similar operations should be
345  *      done to the discarded portion of the buffer.
346  *
347  *      Note 2001/07/20: No, the other content modification mechanisms will process
348  *                       the whole iob later anyway. --oes
349  *
350  *    Revision 1.26  2001/07/18 12:31:36  oes
351  *    cosmetics
352  *
353  *    Revision 1.25  2001/07/15 19:43:49  jongfoster
354  *    Supports POSIX threads.
355  *    Also removed some unused #includes.
356  *
357  *    Revision 1.24  2001/07/13 14:00:40  oes
358  *     - Generic content modification scheme:
359  *       Each feature has its own applicability flag that is set
360  *       from csp->action->flags.
361  *       Replaced the "filtering" int flag , by a function pointer
362  *       "content_filter" to the function that will do the content
363  *       modification. If it is != NULL, the document will be buffered
364  *       and processed through *content_filter, which must set
365  *       csp->content_length and return a modified copy of the body
366  *       or return NULL (on failiure).
367  *     - Changed csp->is_text to the more generic bitmap csp->content_type
368  *       which can currently take the valued CT_TEXT or CT_GIF
369  *     - Reformatting etc
370  *     - Removed all #ifdef PCRS
371  *
372  *    Revision 1.23  2001/07/02 02:28:25  iwanttokeepanon
373  *    Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
374  *    the `block_acl' call.  This prevents a compilation error when the user
375  *    does not wish to use the "ACL" feature.
376  *
377  *    Revision 1.22  2001/06/29 21:45:41  oes
378  *    Indentation, CRLF->LF, Tab-> Space
379  *
380  *    Revision 1.21  2001/06/29 13:29:36  oes
381  *    - Cleaned up, improved comments
382  *    - Unified all possible interceptors (CGI,
383  *      block, trust, fast_redirect) in one
384  *      place, with one (CGI) answer generation
385  *      mechansim. Much clearer now.
386  *    - Removed the GIF image generation, which
387  *      is now done in filters.c:block_url()
388  *    - Made error conditions like domain lookup
389  *      failiure or (various) problems while talking
390  *      to the server use cgi.c:error_response()
391  *      instead of generating HTML/HTTP in chat() (yuck!)
392  *    - Removed logentry from cancelled commit
393  *
394  *    Revision 1.20  2001/06/09 10:55:28  jongfoster
395  *    Changing BUFSIZ ==> BUFFER_SIZE
396  *
397  *    Revision 1.19  2001/06/07 23:12:52  jongfoster
398  *    Replacing function pointer in struct gateway with a directly
399  *    called function forwarded_connect().
400  *    Replacing struct gateway with struct forward_spec
401  *
402  *    Revision 1.18  2001/06/03 19:12:16  oes
403  *    introduced new cgi handling
404  *
405  *    Revision 1.17  2001/06/01 20:07:23  jongfoster
406  *    Now uses action +image-blocker{} rather than config->tinygif
407  *
408  *    Revision 1.16  2001/06/01 18:49:17  jongfoster
409  *    Replaced "list_share" with "list" - the tiny memory gain was not
410  *    worth the extra complexity.
411  *
412  *    Revision 1.15  2001/05/31 21:24:47  jongfoster
413  *    Changed "permission" to "action" throughout.
414  *    Removed DEFAULT_USER_AGENT - it must now be specified manually.
415  *    Moved vanilla wafer check into chat(), since we must now
416  *    decide whether or not to add it based on the URL.
417  *
418  *    Revision 1.14  2001/05/29 20:14:01  joergs
419  *    AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
420  *    increased.
421  *
422  *    Revision 1.13  2001/05/29 09:50:24  jongfoster
423  *    Unified blocklist/imagelist/permissionslist.
424  *    File format is still under discussion, but the internal changes
425  *    are (mostly) done.
426  *
427  *    Also modified interceptor behaviour:
428  *    - We now intercept all URLs beginning with one of the following
429  *      prefixes (and *only* these prefixes):
430  *        * http://i.j.b/
431  *        * http://ijbswa.sf.net/config/
432  *        * http://ijbswa.sourceforge.net/config/
433  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
434  *    - Internal changes so that intercepted and fast redirect pages
435  *      are not replaced with an image.
436  *    - Interceptors now have the option to send a binary page direct
437  *      to the client. (i.e. ijb-send-banner uses this)
438  *    - Implemented show-url-info interceptor.  (Which is why I needed
439  *      the above interceptors changes - a typical URL is
440  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
441  *      The previous mechanism would not have intercepted that, and
442  *      if it had been intercepted then it then it would have replaced
443  *      it with an image.)
444  *
445  *    Revision 1.12  2001/05/27 22:17:04  oes
446  *
447  *    - re_process_buffer no longer writes the modified buffer
448  *      to the client, which was very ugly. It now returns the
449  *      buffer, which it is then written by chat.
450  *
451  *    - content_length now adjusts the Content-Length: header
452  *      for modified documents rather than crunch()ing it.
453  *      (Length info in csp->content_length, which is 0 for
454  *      unmodified documents)
455  *
456  *    - For this to work, sed() is called twice when filtering.
457  *
458  *    Revision 1.11  2001/05/26 17:27:53  jongfoster
459  *    Added support for CLF and fixed LOG_LEVEL_LOG.
460  *    Also did CRLF->LF fix of my previous patch.
461  *
462  *    Revision 1.10  2001/05/26 15:26:15  jongfoster
463  *    ACL feature now provides more security by immediately dropping
464  *    connections from untrusted hosts.
465  *
466  *    Revision 1.9  2001/05/26 00:28:36  jongfoster
467  *    Automatic reloading of config file.
468  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
469  *    Most of the global variables have been moved to a new
470  *    struct configuration_spec, accessed through csp->config->globalname
471  *    Most of the globals remaining are used by the Win32 GUI.
472  *
473  *    Revision 1.8  2001/05/25 22:43:18  jongfoster
474  *    Fixing minor memory leak and buffer overflow.
475  *
476  *    Revision 1.7  2001/05/25 22:34:30  jongfoster
477  *    Hard tabs->Spaces
478  *
479  *    Revision 1.6  2001/05/23 00:13:58  joergs
480  *    AmigaOS support fixed.
481  *
482  *    Revision 1.5  2001/05/22 18:46:04  oes
483  *
484  *    - Enabled filtering banners by size rather than URL
485  *      by adding patterns that replace all standard banner
486  *      sizes with the "Junkbuster" gif to the re_filterfile
487  *
488  *    - Enabled filtering WebBugs by providing a pattern
489  *      which kills all 1x1 images
490  *
491  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
492  *      which is selected by the (nonstandard and therefore
493  *      capital) letter 'U' in the option string.
494  *      It causes the quantifiers to be ungreedy by default.
495  *      Appending a ? turns back to greedy (!).
496  *
497  *    - Added a new interceptor ijb-send-banner, which
498  *      sends back the "Junkbuster" gif. Without imagelist or
499  *      MSIE detection support, or if tinygif = 1, or the
500  *      URL isn't recognized as an imageurl, a lame HTML
501  *      explanation is sent instead.
502  *
503  *    - Added new feature, which permits blocking remote
504  *      script redirects and firing back a local redirect
505  *      to the browser.
506  *      The feature is conditionally compiled, i.e. it
507  *      can be disabled with --disable-fast-redirects,
508  *      plus it must be activated by a "fast-redirects"
509  *      line in the config file, has its own log level
510  *      and of course wants to be displayed by show-proxy-args
511  *      Note: Boy, all the #ifdefs in 1001 locations and
512  *      all the fumbling with configure.in and acconfig.h
513  *      were *way* more work than the feature itself :-(
514  *
515  *    - Because a generic redirect template was needed for
516  *      this, tinygif = 3 now uses the same.
517  *
518  *    - Moved GIFs, and other static HTTP response templates
519  *      to project.h
520  *
521  *    - Some minor fixes
522  *
523  *    - Removed some >400 CRs again (Jon, you really worked
524  *      a lot! ;-)
525  *
526  *    Revision 1.4  2001/05/21 19:34:01  jongfoster
527  *    Made failure to bind() a fatal error.
528  *
529  *    Revision 1.3  2001/05/20 01:21:20  jongfoster
530  *    Version 2.9.4 checkin.
531  *    - Merged popupfile and cookiefile, and added control over PCRS
532  *      filtering, in new "permissionsfile".
533  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
534  *      file error you now get a message box (in the Win32 GUI) rather
535  *      than the program exiting with no explanation.
536  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
537  *      skipping.
538  *    - Removed tabs from "config"
539  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
540  *    - Bumped up version number.
541  *
542  *    Revision 1.2  2001/05/17 22:34:44  oes
543  *     - Added hint on GIF char array generation to jcc.c
544  *     - Cleaned CRLF's from the sources and related files
545  *     - Repaired logging for REF and FRC
546  *
547  *    Revision 1.1.1.1  2001/05/15 13:58:56  oes
548  *    Initial import of version 2.9.3 source tree
549  *
550  *
551  *********************************************************************/
552 \f
553
554 #include "config.h"
555
556 #include <stdio.h>
557 #include <sys/types.h>
558 #include <stdlib.h>
559 #include <string.h>
560 #include <signal.h>
561 #include <fcntl.h>
562 #include <errno.h>
563
564 #ifdef FEATURE_PTHREAD
565 #include <pthread.h>
566 #endif /* def FEATURE_PTHREAD */
567
568 #ifdef _WIN32
569 # ifndef FEATURE_PTHREAD
570 #  ifndef STRICT
571 #   define STRICT
572 #  endif
573 #  include <windows.h>
574 #  include <process.h>
575 # endif /* ndef FEATURE_PTHREAD */
576
577 # include "win32.h"
578 # ifndef _WIN_CONSOLE
579 #  include "w32log.h"
580 # endif /* ndef _WIN_CONSOLE */
581
582 #else /* ifndef _WIN32 */
583
584 # if !defined (__OS2__)
585 # include <unistd.h>
586 # include <sys/wait.h>
587 # endif /* ndef __OS2__ */
588 # include <sys/time.h>
589 # include <sys/stat.h>
590 # include <sys/ioctl.h>
591
592 #ifdef sun
593 #include <sys/termios.h>
594 #endif /* sun */
595
596 #ifdef unix
597 #include <pwd.h>
598 #include <grp.h>
599 #endif
600
601 # include <signal.h>
602
603 # ifdef __BEOS__
604 #  include <socket.h>  /* BeOS has select() for sockets only. */
605 #  include <OS.h>      /* declarations for threads and stuff. */
606 # endif
607
608 # if defined(__EMX__) || defined(__OS2__)
609 #  include <sys/select.h>  /* OS/2/EMX needs a little help with select */
610 # endif
611 # ifdef __OS2__
612 #define INCL_DOS
613 # include <os2.h>
614 #define bzero(B,N) memset(B,0x00,n)
615 # endif
616
617 # ifndef FD_ZERO
618 #  include <select.h>
619 # endif
620
621 #endif
622
623 #include "project.h"
624 #include "list.h"
625 #include "jcc.h"
626 #include "filters.h"
627 #include "loaders.h"
628 #include "parsers.h"
629 #include "killpopup.h"
630 #include "miscutil.h"
631 #include "errlog.h"
632 #include "jbsockets.h"
633 #include "gateway.h"
634 #include "actions.h"
635 #include "cgi.h"
636 #include "loadcfg.h"
637 #include "urlmatch.h"
638 #ifdef FEATURE_ACTIVITY_CONSOLE
639 #include "stats.h"
640 #endif /* def FEATURE_ACTIVITY_CONSOLE */
641
642 const char jcc_h_rcs[] = JCC_H_VERSION;
643 const char project_h_rcs[] = PROJECT_H_VERSION;
644
645 int no_daemon = 0;
646 struct client_state  clients[1];
647 struct file_list     files[1];
648
649 #ifdef FEATURE_STATISTICS
650 int urls_read     = 0;     /* total nr of urls read inc rejected */
651 int urls_rejected = 0;     /* total nr of urls rejected */
652 #endif /* def FEATURE_STATISTICS */
653
654 #ifdef FEATURE_GRACEFUL_TERMINATION
655 int g_terminate = 0;
656 #endif
657
658 static void listen_loop(void);
659 static void chat(struct client_state *csp);
660 static jb_err relay_server_traffic( struct client_state *csp ) ;
661 static jb_err read_client_headers( struct client_state *csp, struct http_request *http ) ;
662 static jb_err process_client_headers( struct client_state *csp, struct http_request *http ) ;
663 static jb_err intercept_page( struct client_state *csp, struct http_request *http );
664 static jb_err open_forwarding_connection( struct client_state *csp );
665 static jb_err send_client_headers_to_server( struct client_state *csp, struct http_request *http,  char* hdr );
666 static jb_err is_connect_request_allowed( struct client_state *csp ) ;
667
668
669 #ifdef AMIGA
670 void serve(struct client_state *csp);
671 #else /* ifndef AMIGA */
672 static void serve(struct client_state *csp);
673 #endif /* def AMIGA */
674
675 #ifdef __BEOS__
676 static int32 server_thread(void *data);
677 #endif /* def __BEOS__ */
678
679 #ifdef _WIN32
680 #define sleep(N)  Sleep(((N) * 1000))
681 #endif
682
683 #ifdef __OS2__
684 #define sleep(N)  DosSleep(((N) * 100))
685 #endif
686
687 #ifdef OSX_DARWIN
688 /*
689  * Hit OSX over the head with a hammer.  Protect all *_r functions.
690  */
691 pthread_mutex_t gmtime_mutex;
692 pthread_mutex_t localtime_mutex;
693 pthread_mutex_t gethostbyaddr_mutex;
694 pthread_mutex_t gethostbyname_mutex;
695 #endif /* def OSX_DARWIN */
696
697 #if defined(unix) || defined(__EMX__)
698 const char *basedir = NULL;
699 const char *pidfile = NULL;
700 int received_hup_signal = 0;
701 #endif /* defined unix */
702
703 /* The vanilla wafer. */
704 static const char VANILLA_WAFER[] =
705    "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
706    "Do_not_send_me_any_copyrighted_information_other_than_the_"
707    "document_that_I_am_requesting_or_any_of_its_necessary_components._"
708    "In_particular_do_not_send_me_any_cookies_that_"
709    "are_subject_to_a_claim_of_copyright_by_anybody._"
710    "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
711    "(copyright_or_otherwise)_applying_to_any_cookie._";
712
713 /**
714  * HTTP header sent when doing HTTPS tunnelling ("CONNECT" method).
715  */
716 static const char CSUCCEED[] =
717    "HTTP/1.0 200 Connection established\n"
718    "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
719
720
721 /**
722  * HTTP reply sent when the browser sends something unintelligible.
723  */
724 static const char CHEADER[] =
725    "HTTP/1.0 400 Invalid header received from browser\r\n\r\n";
726
727
728 /**
729  * HTTP reply sent when the browser tries to tunnel ("CONNECT") to something
730  * other than a HTTPS port (as defined by +limit-connect).
731  */
732 static const char CFORBIDDEN[] =
733    "HTTP/1.0 403 Connection not allowable\r\nX-Hint: If you read this message interactively, then you know why this happens ,-)\r\n\r\n";
734
735 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
736 /*********************************************************************
737  *
738  * Function    :  sig_handler 
739  *
740  * Description :  Signal handler for different signals.
741  *                Exit gracefully on ABRT, TERM and  INT
742  *                or set a flag that will cause the errlog
743  *                to be reopened by the main thread on HUP.
744  *
745  * Parameters  :
746  *          1  :  the_signal = the signal cause this function to call
747  *
748  * Returns     :  - 
749  *
750  *********************************************************************/
751 static void sig_handler(int the_signal)
752 {
753    switch(the_signal)
754    {
755       case SIGABRT:
756       case SIGTERM:
757       case SIGINT:
758          log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
759 #if defined(unix)
760          unlink(pidfile);
761 #endif /* unix */
762          exit(the_signal);
763          break;
764
765       case SIGHUP:
766          received_hup_signal = 1;
767          break;         
768
769       default:
770          /* 
771           * We shouldn't be here, unless we catch signals
772           * in main() that we can't handle here!
773           */
774          log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
775    }
776    return;
777
778 }
779 #endif
780
781
782 /*********************************************************************
783  *
784  * Function    :  chat
785  *
786  * Description :  Once a connection to the client has been accepted,
787  *                this function is called (via serve()) to handle the
788  *                main business of the communication.  When this
789  *                function returns, the caller must close the client
790  *                socket handle.
791  *
792  * Parameters  :
793  *          1  :  csp = Current client state (buffers, headers, etc...)
794  *
795  * Returns     :  void
796  *
797  *********************************************************************/
798 static void chat(struct client_state *csp)
799 {
800
801
802    char buf[BUFFER_SIZE];
803    int len; /* for buffer sizes */
804    char *hdr; 
805    fd_set rfds;
806    int n;
807    jb_socket maxfd;
808    int byte_count = 0;
809    struct http_request *http;
810
811    http = csp->http;
812
813    if (read_client_headers(csp, http ) != JB_ERR_OK )
814       return;
815    
816
817    /* Process the client headers */
818    if (process_client_headers(csp, http) != JB_ERR_OK)
819       return;
820    
821
822    /* Check if this connection request is permitted */
823    if (is_connect_request_allowed(csp) != JB_ERR_OK)
824       return ;
825
826    /*
827     * We have a valid and legit request. Now, check to see if we need to
828     * intercept it.
829     */
830    if (intercept_page(csp, http) != JB_ERR_OK)
831       return;
832   
833    /* 
834     * The page passed the intercept routine, so open a forwarding
835     * connection for conversation
836     */
837    if (open_forwarding_connection(csp) != JB_ERR_OK )
838       return ;
839
840
841
842    hdr = sed(client_patterns, add_client_headers, csp);
843    if (hdr == NULL)
844    {
845       /* FIXME Should handle error properly */
846       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
847    }
848
849    /* FIXME - where should this go, logically ? */
850    list_remove_all(csp->headers);
851
852
853    if (send_client_headers_to_server(csp, http, hdr) != JB_ERR_OK)
854       return ;
855
856
857    /* we're finished with the client's header */
858    freez(hdr);
859
860    maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
861
862    /* pass data between the client and server
863     * until one or the other shuts down the connection.
864     */
865
866    /* Set the flag for reading headers to False */
867    /* This is used in relay_server_traffic */
868    csp->all_headers_read = 0 ;
869
870    for (;;)
871    {
872       jb_err tmp_ret_val = JB_ERR_GENERIC ;
873
874 #ifdef __OS2__
875       /*
876        * FD_ZERO here seems to point to an errant macro which crashes.
877        * So do this by hand for now...
878        */
879       memset(&rfds,0x00,sizeof(fd_set));
880 #else
881       FD_ZERO(&rfds);
882 #endif
883       FD_SET(csp->cfd, &rfds);
884       FD_SET(csp->sfd, &rfds);
885
886       n = select((int)maxfd+1, &rfds, NULL, NULL, NULL);
887
888       if (n < 0)
889       {
890          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
891          return;
892       }
893
894       /*
895        * This is the body of the browser's request.
896        * Just read it and write it.
897        */
898
899       if (FD_ISSET(csp->cfd, &rfds))
900       {
901          len = read_socket(csp->cfd, buf, sizeof(buf));
902
903          if (len <= 0)
904          {
905             log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
906              csp->ip_addr_str, http->ocmd, byte_count);
907             return ;
908          }
909
910          if (write_socket(csp->sfd, buf, (size_t)len))
911          {
912             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
913             return;
914          }
915          continue;
916       }
917
918       /*
919        * Check if the server wants to talk, and if so, converse.
920        */
921
922       if (FD_ISSET(csp->sfd, &rfds))
923          tmp_ret_val = relay_server_traffic(csp) ;
924
925
926       if (tmp_ret_val == JB_ERR_OK)
927          continue ;
928       else
929          return; 
930    }
931    /* We should never get here! */
932    log_error(LOG_LEVEL_FATAL, "chat() : logic error in for() loop" ) ;
933 } /* END chat() */
934
935
936 /*********************************************************************
937  *
938  * Function    :  serve
939  *
940  * Description :  This is little more than chat.  We only "serve" to
941  *                to close any socket that chat may have opened.
942  *
943  * Parameters  :
944  *          1  :  csp = Current client state (buffers, headers, etc...)
945  *
946  * Returns     :  N/A
947  *
948  *********************************************************************/
949 #ifdef AMIGA
950 void serve(struct client_state *csp)
951 #else /* ifndef AMIGA */
952 static void serve(struct client_state *csp)
953 #endif /* def AMIGA */
954 {
955    chat(csp);
956    close_socket(csp->cfd);
957
958    if (csp->sfd != JB_INVALID_SOCKET)
959    {
960       close_socket(csp->sfd);
961    }
962
963    csp->flags &= ~CSP_FLAG_ACTIVE;
964
965 }
966
967
968 #ifdef __BEOS__
969 /*********************************************************************
970  *
971  * Function    :  server_thread
972  *
973  * Description :  We only exist to call `serve' in a threaded environment.
974  *
975  * Parameters  :
976  *          1  :  data = Current client state (buffers, headers, etc...)
977  *
978  * Returns     :  Always 0.
979  *
980  *********************************************************************/
981 static int32 server_thread(void *data)
982 {
983    serve((struct client_state *) data);
984    return 0;
985
986 }
987 #endif
988
989
990 /*********************************************************************
991  *
992  * Function    :  usage
993  *
994  * Description :  Print usage info & exit.
995  *
996  * Parameters  :  Pointer to argv[0] for identifying ourselves
997  *
998  * Returns     :  No. ,-)
999  *
1000  *********************************************************************/
1001 void usage(const char *myname)
1002 {
1003    printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
1004            "Usage: %s [--help] [--version] [--no-daemon] [--pidfile pidfile] [--user user[.group]] [configfile]\n"
1005            "Aborting.\n", myname);
1006  
1007    exit(2);
1008
1009 }
1010
1011
1012 /*********************************************************************
1013  *
1014  * Function    :  main
1015  *
1016  * Description :  Load the config file and start the listen loop.
1017  *                This function is a lot more *sane* with the `load_config'
1018  *                and `listen_loop' functions; although it stills does
1019  *                a *little* too much for my taste.
1020  *
1021  * Parameters  :
1022  *          1  :  argc = Number of parameters (including $0).
1023  *          2  :  argv = Array of (char *)'s to the parameters.
1024  *
1025  * Returns     :  1 if : can't open config file, unrecognized directive,
1026  *                stats requested in multi-thread mode, can't open the
1027  *                log file, can't open the jar file, listen port is invalid,
1028  *                any load fails, and can't bind port.
1029  *
1030  *                Else main never returns, the process must be signaled
1031  *                to terminate execution.  Or, on Windows, use the
1032  *                "File", "Exit" menu option.
1033  *
1034  *********************************************************************/
1035 #ifdef __MINGW32__
1036 int real_main(int argc, const char *argv[])
1037 #else
1038 int main(int argc, const char *argv[])
1039 #endif
1040 {
1041    int argc_pos = 0;
1042 #ifdef unix
1043    struct passwd *pw = NULL;
1044    struct group *grp = NULL;
1045    char *p;
1046 #endif
1047
1048    Argc = argc;
1049    Argv = argv;
1050
1051    configfile =
1052 #if !defined(_WIN32)
1053    "config"
1054 #else
1055    "config.txt"
1056 #endif
1057       ;
1058
1059    /*
1060     * Parse the command line arguments
1061     */
1062    while (++argc_pos < argc)
1063    {
1064 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1065
1066       if (strcmp(argv[argc_pos], "--help") == 0)
1067       {
1068          usage(argv[0]);
1069       }
1070
1071       else if(strcmp(argv[argc_pos], "--version") == 0)
1072       {
1073          printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
1074          exit(0);
1075       }
1076
1077       else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
1078       {
1079          no_daemon = 1;
1080       }
1081 #if defined(unix)
1082       else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
1083       {
1084          if (++argc_pos == argc) usage(argv[0]);
1085          pidfile = strdup(argv[argc_pos]);
1086       }
1087
1088       else if (strcmp(argv[argc_pos], "--user" ) == 0)
1089       {
1090          if (++argc_pos == argc) usage(argv[argc_pos]);
1091
1092          if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
1093          {
1094             *p++ = '\0';
1095             if (NULL == (grp = getgrnam(p)))
1096             {
1097                log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
1098             }
1099          }
1100
1101          if (NULL == (pw = getpwnam(argv[argc_pos])))
1102          {
1103             log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
1104          }
1105
1106          if (p != NULL) *--p = '\0';
1107       }
1108 #endif /* defined(unix) */
1109       else
1110 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1111       {
1112          configfile = argv[argc_pos];
1113       }
1114
1115    } /* -END- while (more arguments) */
1116
1117 #if defined(unix)
1118    if ( *configfile != '/' )
1119    {
1120       char *abs_file;
1121
1122       /* make config-filename absolute here */
1123       if ( !(basedir = getcwd( NULL, 1024 )))
1124       {
1125          perror("get working dir failed");
1126          exit( 1 );
1127       }
1128
1129       if ( !(abs_file = malloc( strlen( basedir ) + strlen( configfile ) + 5 )))
1130       {
1131          perror("malloc failed");
1132          exit( 1 );
1133       }
1134       strcpy( abs_file, basedir );
1135       strcat( abs_file, "/" );
1136       strcat( abs_file, configfile );
1137       configfile = abs_file;
1138    }
1139 #endif /* defined unix */
1140
1141
1142    files->next = NULL;
1143
1144 #ifdef AMIGA
1145    InitAmiga();
1146 #elif defined(_WIN32)
1147    InitWin32();
1148 #endif
1149
1150 #ifdef OSX_DARWIN
1151    /*
1152     * Prepare global mutex semaphores
1153     */
1154    pthread_mutex_init(&gmtime_mutex,0);
1155    pthread_mutex_init(&localtime_mutex,0);
1156    pthread_mutex_init(&gethostbyaddr_mutex,0);
1157    pthread_mutex_init(&gethostbyname_mutex,0);
1158 #endif /* def OSX_DARWIN */
1159
1160    /*
1161     * Unix signal handling
1162     *
1163     * Catch the abort, interrupt and terminate signals for a graceful exit
1164     * Catch the hangup signal so the errlog can be reopened.
1165     * Ignore the broken pipe and child signals
1166     *  FIXME: Isn't ignoring the default for SIGCHLD anyway and why ignore SIGPIPE? 
1167     */
1168 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
1169 {
1170    int idx;
1171    const int catched_signals[] = { SIGABRT, SIGTERM, SIGINT, SIGHUP, 0 };
1172    const int ignored_signals[] = { SIGPIPE, SIGCHLD, 0 };
1173
1174    for (idx = 0; catched_signals[idx] != 0; idx++)
1175    {
1176       if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
1177       {
1178          log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
1179       }
1180    }
1181
1182    for (idx = 0; ignored_signals[idx] != 0; idx++)
1183    {
1184       if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
1185       {
1186          log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
1187       }
1188    }
1189
1190 }
1191 #else /* ifdef _WIN32 */
1192 # ifdef _WIN_CONSOLE
1193    /*
1194     * We *are* in a windows console app.
1195     * Print a verbose messages about FAQ's and such
1196     */
1197    printf(win32_blurb);
1198 # endif /* def _WIN_CONSOLE */
1199 #endif /* def _WIN32 */
1200
1201
1202    /* Initialize the CGI subsystem */
1203    cgi_init_error_messages();
1204
1205    /*
1206     * If runnig on unix and without the --nodaemon
1207     * option, become a daemon. I.e. fork, detach
1208     * from tty and get process group leadership
1209     */
1210 #if defined(unix)
1211    {
1212       pid_t pid = 0;
1213 #if 0
1214       int   fd;
1215 #endif
1216
1217       if (!no_daemon)
1218       {
1219          pid  = fork();
1220
1221          if ( pid < 0 ) /* error */
1222          {
1223             perror("fork");
1224             exit( 3 );
1225          }
1226          else if ( pid != 0 ) /* parent */
1227          {
1228             int status;
1229             pid_t wpid;
1230             /*
1231              * must check for errors
1232              * child died due to missing files aso
1233              */
1234             sleep( 1 );
1235             wpid = waitpid( pid, &status, WNOHANG );
1236             if ( wpid != 0 )
1237             {
1238                exit( 1 );
1239             }
1240             exit( 0 );
1241          }
1242          /* child */
1243 #if 1
1244          /* Should be more portable, but not as well tested */
1245          setsid();
1246 #else /* !1 */
1247 #ifdef __FreeBSD__
1248          setpgrp(0,0);
1249 #else /* ndef __FreeBSD__ */
1250          setpgrp();
1251 #endif /* ndef __FreeBSD__ */
1252          fd = open("/dev/tty", O_RDONLY);
1253          if ( fd )
1254          {
1255             /* no error check here */
1256             ioctl( fd, TIOCNOTTY,0 );
1257             close ( fd );
1258          }
1259 #endif /* 1 */
1260          /* FIXME: should close stderr (fd 2) here too, but the test
1261           * for existence
1262           * and load config file is done in listen_loop() and puts
1263           * some messages on stderr there.
1264           */
1265
1266          close( 0 );
1267          close( 1 );
1268          chdir("/");
1269
1270       } /* -END- if (!no_daemon) */
1271
1272       /*
1273        * As soon as we have written the PID file, we can switch
1274        * to the user and group ID indicated by the --user option
1275        */
1276       write_pid_file();
1277    
1278       if (NULL != pw)
1279       {
1280          if (((NULL != grp) && setgid(grp->gr_gid)) || (setgid(pw->pw_gid)))
1281          {
1282             log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
1283          }
1284          if (setuid(pw->pw_uid))
1285          {
1286             log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
1287          }
1288       }
1289    }
1290 #endif /* defined unix */
1291
1292    listen_loop();
1293
1294    /* NOTREACHED */
1295    return(-1);
1296
1297 }
1298
1299
1300 /*********************************************************************
1301  *
1302  * Function    :  bind_port_helper
1303  *
1304  * Description :  Bind the listen port.  Handles logging, and aborts
1305  *                on failure.
1306  *
1307  * Parameters  :
1308  *          1  :  config = Privoxy configuration.  Specifies port
1309  *                         to bind to.
1310  *
1311  * Returns     :  Port that was opened.
1312  *
1313  *********************************************************************/
1314 static jb_socket bind_port_helper(struct configuration_spec * config)
1315 {
1316    int result;
1317    jb_socket bfd;
1318
1319    if ( (config->haddr != NULL)
1320      && (config->haddr[0] == '1')
1321      && (config->haddr[1] == '2')
1322      && (config->haddr[2] == '7')
1323      && (config->haddr[3] == '.') )
1324    {
1325       log_error(LOG_LEVEL_INFO, "Listening on port %d for local connections only",
1326                 config->hport);
1327    }
1328    else if (config->haddr == NULL)
1329    {
1330       log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
1331                 config->hport);
1332    }
1333    else
1334    {
1335       log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
1336                 config->hport, config->haddr);
1337    }
1338
1339    result = bind_port(config->haddr, config->hport, &bfd);
1340
1341    if (result < 0)
1342    {
1343       switch(result)
1344       {
1345          case -3 :
1346             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
1347                "There may be another Privoxy or some other "
1348                "proxy running on port %d",
1349                (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
1350                       config->hport, config->hport);
1351
1352          case -2 :
1353             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: " 
1354                "The hostname is not resolvable",
1355                (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1356
1357          default :
1358             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: because %E",
1359                (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
1360       }
1361
1362       /* shouldn't get here */
1363       return JB_INVALID_SOCKET;
1364    }
1365
1366    config->need_bind = 0;
1367
1368    return bfd;
1369 }
1370
1371
1372 /*********************************************************************
1373  *
1374  * Function    :  listen_loop
1375  *
1376  * Description :  bind the listen port and enter a "FOREVER" listening loop.
1377  *
1378  * Parameters  :  N/A
1379  *
1380  * Returns     :  Never.
1381  *
1382  *********************************************************************/
1383 static void listen_loop(void)
1384 {
1385    struct client_state *csp = NULL;
1386    jb_socket bfd;
1387    struct configuration_spec * config;
1388
1389    config = load_config();
1390
1391    bfd = bind_port_helper(config);
1392
1393 #ifdef FEATURE_ACTIVITY_CONSOLE
1394    init_stats_config(config);
1395 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1396
1397 #ifdef FEATURE_GRACEFUL_TERMINATION
1398    while (!g_terminate)
1399 #else
1400    for (;;)
1401 #endif
1402    {
1403 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
1404       while (waitpid(-1, NULL, WNOHANG) > 0)
1405       {
1406          /* zombie children */
1407       }
1408 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1409
1410       /*
1411        * Free data that was used by died threads
1412        */
1413       sweep();
1414
1415 #if defined(unix)
1416       /*
1417        * Re-open the errlog after HUP signal
1418        */
1419       if (received_hup_signal)
1420       {
1421          init_error_log(Argv[0], config->logfile, config->debug);
1422          received_hup_signal = 0;
1423       }
1424 #endif
1425
1426 #ifdef __OS2__
1427 #ifdef FEATURE_COOKIE_JAR
1428       /*
1429        * Need a workaround here: we have to fclose() the jarfile, or we die because it's
1430        * already open.  I think unload_configfile() is not being run, which should do
1431        * this work.  Until that can get resolved, we'll use this workaround.
1432        *
1433        * [Note from Jon: We don't unload_configfile() until all existing threads have
1434        * exited - they're likely to hang aroung transferring data to the browser.]
1435        */
1436        if (csp)
1437          if(csp->config)
1438            if (csp->config->jar)
1439            {
1440              fclose(csp->config->jar);
1441              csp->config->jar = NULL;
1442            }
1443 #endif /* FEATURE_COOKIE_JAR */
1444 #endif /* __OS2__ */
1445
1446       if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1447       {
1448          log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1449          continue;
1450       }
1451
1452       csp->flags |= CSP_FLAG_ACTIVE;
1453       csp->sfd    = JB_INVALID_SOCKET;
1454
1455       csp->config = config = load_config();
1456
1457       if ( config->need_bind )
1458       {
1459          /*
1460           * Since we were listening to the "old port", we will not see
1461           * a "listen" param change until the next IJB request.  So, at
1462           * least 1 more request must be made for us to find the new
1463           * setting.  I am simply closing the old socket and binding the
1464           * new one.
1465           *
1466           * Which-ever is correct, we will serve 1 more page via the
1467           * old settings.  This should probably be a "show-proxy-args"
1468           * request.  This should not be a so common of an operation
1469           * that this will hurt people's feelings.
1470           */
1471
1472          close_socket(bfd);
1473
1474          bfd = bind_port_helper(config);
1475       }
1476
1477       log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1478
1479       if (!accept_connection(csp, bfd))
1480       {
1481          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1482
1483 #ifdef AMIGA
1484          if(!childs)
1485          {
1486             exit(1);
1487          }
1488 #endif
1489          freez(csp);
1490          continue;
1491       }
1492       else
1493       {
1494          log_error(LOG_LEVEL_CONNECT, "OK");
1495       }
1496
1497 #ifdef FEATURE_TOGGLE
1498       if (g_bToggleIJB)
1499       {
1500          csp->flags |= CSP_FLAG_TOGGLED_ON;
1501       }
1502 #endif /* def FEATURE_TOGGLE */
1503
1504 #ifdef FEATURE_ACTIVITY_CONSOLE
1505       update_stats_config(config);
1506 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1507
1508       if (run_loader(csp))
1509       {
1510          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1511          /* Never get here - LOG_LEVEL_FATAL causes program exit */
1512       }
1513
1514 #ifdef FEATURE_ACL
1515       if (block_acl(NULL,csp))
1516       {
1517 #ifdef FEATURE_ACTIVITY_CONSOLE
1518          accumulate_stats(STATS_ACL_RESTRICT,1);
1519 #endif /* def FEATURE_ACTIVITY_CONSOLE */
1520          log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1521          close_socket(csp->cfd);
1522          freez(csp);
1523          continue;
1524       }
1525 #endif /* def FEATURE_ACL */
1526
1527       /* add it to the list of clients */
1528       csp->next = clients->next;
1529       clients->next = csp;
1530
1531       if (config->multi_threaded)
1532       {
1533          int child_id;
1534
1535 /* this is a switch () statment in the C preprocessor - ugh */
1536 #undef SELECTED_ONE_OPTION
1537
1538 /* Use Pthreads in preference to native code */
1539 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1540 #define SELECTED_ONE_OPTION
1541          {
1542             pthread_t the_thread;
1543             pthread_attr_t attrs;
1544
1545             pthread_attr_init(&attrs);
1546             pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
1547             child_id = (pthread_create(&the_thread, &attrs,
1548                (void*)serve, csp) ? -1 : 0);
1549             pthread_attr_destroy(&attrs);
1550          }
1551 #endif
1552
1553 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1554 #define SELECTED_ONE_OPTION
1555          child_id = _beginthread(
1556             (void (*)(void *))serve,
1557             64 * 1024,
1558             csp);
1559 #endif
1560
1561 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
1562 #define SELECTED_ONE_OPTION
1563          child_id = _beginthread(
1564             (void(* _Optlink)(void*))serve,
1565             NULL,
1566             64 * 1024,
1567             csp);
1568 #endif
1569
1570 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1571 #define SELECTED_ONE_OPTION
1572          {
1573             thread_id tid = spawn_thread
1574                (server_thread, "server", B_NORMAL_PRIORITY, csp);
1575
1576             if ((tid >= 0) && (resume_thread(tid) == B_OK))
1577             {
1578                child_id = (int) tid;
1579             }
1580             else
1581             {
1582                child_id = -1;
1583             }
1584          }
1585 #endif
1586
1587 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1588 #define SELECTED_ONE_OPTION
1589          csp->cfd = ReleaseSocket(csp->cfd, -1);
1590          if((child_id = (int)CreateNewProcTags(
1591             NP_Entry, (ULONG)server_thread,
1592             NP_Output, Output(),
1593             NP_CloseOutput, FALSE,
1594             NP_Name, (ULONG)"privoxy child",
1595             NP_StackSize, 200*1024,
1596             TAG_DONE)))
1597          {
1598             childs++;
1599             ((struct Task *)child_id)->tc_UserData = csp;
1600             Signal((struct Task *)child_id, SIGF_SINGLE);
1601             Wait(SIGF_SINGLE);
1602          }
1603 #endif
1604
1605 #if !defined(SELECTED_ONE_OPTION)
1606          child_id = fork();
1607
1608          /* This block is only needed when using fork().
1609           * When using threads, the server thread was
1610           * created and run by the call to _beginthread().
1611           */
1612          if (child_id == 0)   /* child */
1613          {
1614             serve(csp);
1615             _exit(0);
1616
1617          }
1618          else if (child_id > 0) /* parent */
1619          {
1620             /* in a fork()'d environment, the parent's
1621              * copy of the client socket and the CSP
1622              * are not used.
1623              */
1624
1625 #if !defined(_WIN32) && defined(__CYGWIN__)
1626             wait( NULL );
1627 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1628             close_socket(csp->cfd);
1629             csp->flags &= ~CSP_FLAG_ACTIVE;
1630          }
1631 #endif
1632
1633 #undef SELECTED_ONE_OPTION
1634 /* end of cpp switch () */
1635
1636          if (child_id < 0) /* failed */
1637          {
1638             char buf[BUFFER_SIZE];
1639
1640             log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1641
1642             sprintf(buf , "Privoxy: can't fork: errno = %d", errno);
1643
1644             write_socket(csp->cfd, buf, strlen(buf));
1645             close_socket(csp->cfd);
1646             csp->flags &= ~CSP_FLAG_ACTIVE;
1647             sleep(5);
1648             continue;
1649          }
1650       }
1651       else
1652       {
1653          serve(csp);
1654       }
1655    }
1656
1657    /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
1658
1659    /* Clean up.  Aim: free all memory (no leaks) */
1660 #ifdef FEATURE_GRACEFUL_TERMINATION
1661
1662    log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
1663
1664    unload_current_config_file();
1665    unload_current_actions_file();
1666    unload_current_re_filterfile();
1667 #ifdef FEATURE_TRUST
1668    unload_current_trust_file();
1669 #endif
1670
1671    if (config->multi_threaded)
1672    {
1673       int i = 60;
1674       do
1675       {
1676          sleep(1);
1677          sweep();
1678       } while ((clients->next != NULL) && (--i > 0));
1679
1680       if (i <= 0)
1681       {
1682          log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
1683       }
1684    }
1685    sweep();
1686    sweep();
1687
1688 #if defined(unix)
1689    free(basedir);
1690 #endif
1691 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
1692    /* Cleanup - remove taskbar icon etc. */
1693    TermLogWindow();
1694 #endif
1695
1696    exit(0);
1697 #endif /* FEATURE_GRACEFUL_TERMINATION */
1698
1699 }
1700
1701 /*********************************************************************
1702  *
1703  * Function    :  relay_server_traffic
1704  *
1705  * Description :  receive traffic from the server and relay it
1706  *                to the client, with some processing
1707  *
1708  * Parameters  :
1709  *          1  :  client_state structure
1710  *                         
1711  *
1712  * Returns     :  JB_ERR_OK if there may be more work
1713  *             :  other values for errors
1714  *
1715  **********************************************************************/
1716
1717 static jb_err relay_server_traffic( struct client_state *csp )
1718 {
1719 #ifdef FEATURE_KILL_POPUPS
1720    int block_popups;         /* bool, 1==will block popups */
1721    int block_popups_now = 0; /* bool, 1==currently blocking popups */
1722 #endif /* def FEATURE_KILL_POPUPS */
1723    
1724    char buf[BUFFER_SIZE];
1725    int len; /* for buffer sizes */
1726    int ms_iis5_hack = 0;
1727    int byte_count = 0;
1728    char *hdr;
1729    char *p;
1730
1731    /* Skeleton for HTTP response, if we should intercept the request */
1732    struct http_response *rsp;
1733
1734    int pcrs_filter;        /* bool, 1==will filter through pcrs */
1735    int gif_deanimate;      /* bool, 1==will deanimate gifs */
1736    int jpeg_inspect;       /* bool, 1==will inspect jpegs */
1737
1738 #ifdef FEATURE_KILL_POPUPS
1739    block_popups               = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
1740 #endif /* def FEATURE_KILL_POPUPS */
1741
1742    pcrs_filter                = (csp->rlist != NULL) &&  /* There are expressions to be used */
1743                                 (!list_is_empty(csp->action->multi[ACTION_MULTI_FILTER]));
1744
1745    gif_deanimate              = ((csp->action->flags & ACTION_DEANIMATE) != 0);
1746
1747    jpeg_inspect               = ((csp->action->flags & ACTION_JPEG_INSPECT) != 0);
1748
1749    fflush (0);
1750    len = read_socket (csp->sfd, buf, sizeof (buf) - 1);
1751
1752    if (len < 0)
1753    {
1754       log_error (LOG_LEVEL_ERROR, "read from: %s failed: %E", csp->http->host);
1755
1756       log_error (LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
1757          csp->ip_addr_str, csp->http->ocmd);
1758
1759       rsp = error_response (csp, "connect-failed", errno);
1760
1761       if (rsp)
1762       {
1763          if (write_socket (csp->cfd, rsp->head, rsp->head_length)
1764             || write_socket (csp->cfd, rsp->body, rsp->content_length))
1765          {
1766             log_error (LOG_LEVEL_ERROR, "write to: %s failed: %E",
1767                        csp->http->host);
1768          }
1769       }
1770
1771       free_http_response (rsp);
1772       return JB_ERR_GENERIC;
1773    }
1774
1775    /* Add a trailing zero.  This lets filter_popups
1776     * use string operations.
1777     */
1778    buf[len] = '\0';
1779
1780 #ifdef FEATURE_KILL_POPUPS
1781    /* Filter the popups on this read. */
1782    if (block_popups_now)
1783    {
1784       filter_popups (buf, csp);
1785    }
1786 #endif /* def FEATURE_KILL_POPUPS */
1787
1788
1789    /* Normally, this would indicate that we've read
1790     * as much as the server has sent us and we can
1791     * close the client connection.  However, Microsoft
1792     * in its wisdom has released IIS/5 with a bug that
1793     * prevents it from sending the trailing \r\n in
1794     * a 302 redirect header (and possibly other headers).
1795     * To work around this if we've haven't parsed
1796     * a full header we'll append a trailing \r\n
1797     * and see if this now generates a valid one.
1798     *
1799     * This hack shouldn't have any impacts.  If we've
1800     * already transmitted the header or if this is a
1801     * SSL connection, then we won't bother with this
1802     * hack.  So we only work on partially received
1803     * headers.  If we append a \r\n and this still
1804     * doesn't generate a valid header, then we won't
1805     * transmit anything to the client.
1806     */
1807    if (len == 0)
1808    {
1809
1810       if (csp->all_headers_read || csp->http->ssl)
1811       {
1812          /*
1813           * If we have been buffering up the document,
1814           * now is the time to apply content modification
1815           * and send the result to the client.
1816           */
1817          if (csp->content_filter)
1818          {
1819             /*
1820              * If the content filter fails, use the original
1821              * buffer and length.
1822              * (see p != NULL ? p : csp->iob->cur below)
1823              */
1824             if (NULL == (p = (*csp->content_filter) (csp)))
1825             {
1826                csp->content_length = csp->iob->eod - csp->iob->cur;
1827             }
1828
1829             hdr = sed (server_patterns, add_server_headers, csp);
1830             if (hdr == NULL)
1831             {
1832                /* FIXME Should handle error properly */
1833                log_error (LOG_LEVEL_FATAL,
1834                   "Out of memory parsing server header");
1835
1836             }
1837
1838             if (write_socket (csp->cfd, hdr, strlen (hdr))
1839                || write_socket (csp->cfd, p != NULL ? p : csp->iob->cur,
1840                           csp->content_length))
1841             {
1842                log_error (LOG_LEVEL_ERROR,
1843                   "write modified content to client failed: %E");
1844                return JB_ERR_GENERIC;
1845             }
1846
1847             freez (hdr);
1848             if (NULL != p)
1849             {
1850                freez (p);
1851             }
1852          }
1853          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1854             csp->ip_addr_str, csp->http->ocmd, byte_count);
1855          return JB_ERR_GENERIC;
1856       }
1857
1858       /*
1859        * This is NOT the body, so
1860        * Let's pretend the server just sent us a blank line.
1861        */
1862       len = sprintf (buf, "\r\n");
1863
1864       /*
1865        * Now, let the normal header parsing algorithm below do its
1866        * job.  If it fails, we'll exit instead of continuing.
1867        */
1868
1869       ms_iis5_hack = 1;
1870    }
1871
1872    /*
1873     * If this is an SSL connection or we're in the body
1874     * of the server document, just write it to the client,
1875     * unless we need to buffer the body for later content-filtering
1876     */
1877
1878    if (csp->all_headers_read || csp->http->ssl)
1879    {
1880       if (csp->content_filter)
1881       {
1882          add_to_iob (csp, buf, len);
1883
1884          /*
1885           * If the buffer limit will be reached on the next read,
1886           * switch to non-filtering mode, i.e. make & write the
1887           * header, flush the socket and get out of the way.
1888           */
1889          if (((size_t) (csp->iob->eod - csp->iob->buf)) +
1890               (size_t) BUFFER_SIZE > csp->config->buffer_limit)
1891          {
1892             size_t hdrlen;
1893
1894             log_error (LOG_LEVEL_ERROR,
1895                         "Buffer size limit reached! Flushing and stepping back.");
1896
1897             hdr = sed (server_patterns, add_server_headers, csp);
1898             if (hdr == NULL)
1899             {
1900                /* FIXME Should handle error properly */
1901                log_error (LOG_LEVEL_FATAL,
1902                   "Out of memory parsing server header");
1903             }
1904
1905             hdrlen = strlen (hdr);
1906             byte_count += hdrlen;
1907
1908             if (write_socket (csp->cfd, hdr, hdrlen)
1909                || ((len = flush_socket (csp->cfd, csp)) < 0))
1910             {
1911                log_error (LOG_LEVEL_CONNECT,
1912                   "write header to client failed: %E");
1913
1914                freez (hdr);
1915                return JB_ERR_GENERIC;
1916             }
1917
1918             freez (hdr);
1919             byte_count += len;
1920
1921             csp->content_filter = NULL;
1922             csp->all_headers_read = 1;
1923
1924          }
1925       }
1926       else
1927       {
1928          if (write_socket (csp->cfd, buf, (size_t) len))
1929          {
1930             log_error (LOG_LEVEL_ERROR, "write to client failed: %E");
1931             return JB_ERR_GENERIC;
1932          }
1933       }
1934       byte_count += len;
1935       return JB_ERR_OK ;
1936    }
1937    else
1938    {
1939       /*
1940        * we're still looking for the end of the
1941        * server's header ... (does that make header
1942        * parsing an "out of body experience" ?
1943        */
1944
1945       /* buffer up the data we just read */
1946       add_to_iob (csp, buf, len);
1947
1948       /* get header lines from the iob */
1949
1950       while ((p = get_header (csp)) != NULL)
1951       {
1952          if (*p == '\0')
1953          {
1954             /* see following note */
1955             log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d",
1956                csp->ip_addr_str, csp->http->ocmd, byte_count);
1957             return JB_ERR_GENERIC;
1958          }
1959          enlist (csp->headers, p);
1960          freez (p);
1961       }
1962
1963       /* NOTE: there are no "empty" headers so
1964        * if the pointer `p' is not NULL we must
1965        * assume that we reached the end of the
1966        * buffer before we hit the end of the header.
1967        */
1968
1969       if (p)
1970       {
1971          if (ms_iis5_hack)
1972          {
1973             /* Well, we tried our MS IIS/5
1974              * hack and it didn't work.
1975              * The header is incomplete
1976              * and there isn't anything
1977              * we can do about it.
1978              */
1979             log_error(LOG_LEVEL_CLF, "Incomplete Server Header: %s - - [%T] \"%s\" 200 %d",
1980                 csp->ip_addr_str, csp->http->ocmd, byte_count);
1981             return JB_ERR_GENERIC;
1982          }
1983          else
1984          {
1985             /* Since we have to wait for
1986              * more from the server before
1987              * we can parse the headers
1988              * we just continue here.
1989              */
1990             return JB_ERR_OK;
1991          }
1992       }      
1993       
1994       /* we have now received the entire header.
1995        * filter it and send the result to the client
1996        */
1997
1998       hdr = sed (server_patterns, add_server_headers, csp);
1999       if (hdr == NULL)
2000       {
2001          /* FIXME Should handle error properly */
2002          log_error (LOG_LEVEL_FATAL, "Out of memory parsing server header");
2003       }
2004
2005   
2006
2007 #ifdef FEATURE_KILL_POPUPS
2008       /* Start blocking popups if appropriate. */
2009
2010       if ((csp->content_type & CT_TEXT) &&   /* It's a text / * MIME-Type */
2011           !csp->http->ssl &&                 /* We talk plaintext */
2012           block_popups)                      /* Policy allows */
2013       {
2014          block_popups_now = 1;
2015          /*
2016           * Filter the part of the body that came in the same read
2017           * as the last headers:
2018           */
2019          filter_popups (csp->iob->cur, csp);
2020       }
2021
2022 #endif /* def FEATURE_KILL_POPUPS */
2023
2024         /* Buffer and pcrs filter this if appropriate. */
2025
2026       if ((csp->content_type & CT_TEXT) &&       /* It's a text / * MIME-Type */
2027           !csp->http->ssl &&                     /* We talk plaintext */
2028           pcrs_filter)                           /* Policy allows */
2029       {
2030          csp->content_filter = pcrs_filter_response;
2031       }
2032
2033       /* Buffer and gif_deanimate this if appropriate. */
2034
2035       if ((csp->content_type & CT_GIF) &&        /* It's a image/gif MIME-Type */
2036           !csp->http->ssl &&                     /* We talk plaintext */
2037           gif_deanimate)                         /* Policy allows */
2038       {
2039          csp->content_filter = gif_deanimate_response;
2040       }
2041
2042       /* Buffer and jpg_inspect this if appropriate. */
2043
2044       if ((csp->content_type & CT_JPEG)  &&      /* It's an image/jpeg MIME-Type */
2045           !csp->http->ssl &&                     /* We talk plaintext */
2046           jpeg_inspect)                          /* Policy allows */
2047       {
2048          csp->content_filter = jpeg_inspect_response;
2049       }
2050
2051       /*
2052        * Only write if we're not buffering for content modification
2053        */
2054       if (!csp->content_filter)
2055       {
2056          /* write the server's (modified) header to
2057           * the client (along with anything else that
2058           * may be in the buffer)
2059           */
2060          if (write_socket (csp->cfd, hdr, strlen (hdr))
2061              || ((len = flush_socket (csp->cfd, csp)) < 0))
2062          {
2063             log_error (LOG_LEVEL_CONNECT,
2064                "write header to client failed: %E");
2065
2066             /* the write failed, so don't bother
2067              * mentioning it to the client...
2068              * it probably can't hear us anyway.
2069              */
2070             freez (hdr);
2071             return JB_ERR_GENERIC;
2072          }
2073
2074          byte_count += len;
2075       }
2076
2077       /* we're finished with the server's header */
2078
2079       freez (hdr);
2080       csp->all_headers_read = 1;
2081
2082       /* If this was a MS IIS/5 hack then it means
2083        * the server has already closed the
2084        * connection.  Nothing more to read.  Time
2085        * to bail.
2086        */
2087       if (ms_iis5_hack)
2088       {
2089          return JB_ERR_GENERIC ;
2090       }
2091    }
2092    return JB_ERR_OK ;
2093 } /* END relay_server_traffic() */
2094
2095
2096 /*********************************************************************
2097  *
2098  * Function    :  read_client_headers
2099  *
2100  * Description :  read all the client headers, and fill in the
2101  *                http* structure
2102  *
2103  * Parameters  :
2104  *          1  :  client_state structure
2105  *          2  :  http_request structure
2106  *                         
2107  *
2108  * Returns     :  JB_ERR_OK  - headers read and parsed ok
2109  *             :  other values - an error occurred.
2110  *********************************************************************/
2111
2112 static jb_err read_client_headers( struct client_state *csp, struct http_request *http )
2113 {
2114
2115    char *p;
2116    char *req;
2117    char buf[BUFFER_SIZE];
2118    int len; /* for buffer sizes */
2119
2120    /*
2121     * Read the client's request.  Note that since we're not using select() we
2122     * could get blocked here if a client connected, then didn't say anything!
2123     *
2124     * This will read all the client headers.
2125     */
2126
2127    req = NULL ;
2128    for (;;)
2129    {
2130       len = read_socket(csp->cfd, buf, sizeof(buf));
2131
2132       if (len <= 0) break;      /* error! */
2133
2134       add_to_iob(csp, buf, len);
2135
2136       req = get_header(csp);
2137
2138       if (req == NULL)
2139       {
2140          break;    /* no HTTP request! */
2141       }
2142
2143       if (*req == '\0')
2144       {
2145          continue;   /* more to come! */
2146       }
2147
2148       /* When we get here we have read one header which is enough */
2149       /* to check whether the connection is allowed */
2150       break; 
2151    }
2152
2153
2154    for(;;) 
2155    {
2156
2157      if ( ( ( p = get_header(csp) ) != NULL) && ( *p == '\0' ) )
2158       {
2159          len = read_socket(csp->cfd, buf, sizeof(buf));
2160          if (len <= 0)
2161          {
2162             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
2163             return JB_ERR_GENERIC;
2164          }
2165          add_to_iob(csp, buf, len);
2166          continue;
2167       }
2168
2169       if (p == NULL) break;
2170
2171       enlist(csp->headers, p);
2172       freez(p);
2173
2174    }
2175
2176    parse_http_request(req, http, csp);
2177    freez(req);
2178
2179    if (http->cmd == NULL)
2180    {
2181       strcpy(buf, CHEADER);
2182       write_socket(csp->cfd, buf, strlen(buf));
2183
2184       log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
2185
2186       return JB_ERR_GENERIC;
2187    }
2188
2189    return JB_ERR_OK ;
2190
2191
2192 } /* END read_client_headers */
2193
2194
2195 /*********************************************************************
2196  *
2197  * Function    :  process_client_headers
2198  *
2199  * Description :  Process client headers
2200  * FIXME: Add description of what we do here!
2201  *
2202  * Parameters  :
2203  *          1  :  client_state structure
2204  *          2  :  http_request structure
2205  *                         
2206  *
2207  * Returns     :  JB_ERR_OK  - headers processed ok
2208  *             :  other values - an error occurred.
2209  *********************************************************************/
2210
2211 static jb_err process_client_headers( struct client_state *csp, struct http_request *http )
2212 {
2213
2214
2215 #ifdef FEATURE_FORCE_LOAD
2216       /* If this request contains the FORCE_PREFIX,
2217        * better get rid of it now and set the force flag --oes
2218        * Changed to use the http structure rather than the req field --jaa
2219        * FIXME: This isn't enough -- there is the path and referrer etc! *
2220        */
2221
2222       if (strstr(http->url, FORCE_PREFIX))
2223       {
2224          strclean(http->url, FORCE_PREFIX);
2225          strclean(http->path, FORCE_PREFIX);
2226          log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", http->url);
2227          csp->flags |= CSP_FLAG_FORCED;
2228       }
2229
2230 #endif /* def FEATURE_FORCE_LOAD */
2231
2232
2233    /* decide how to route the HTTP request */
2234
2235    if ((http->fwd = forward_url(http, csp)) == NULL)
2236    {
2237       log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!?  This can't happen!");
2238       /* Never get here - LOG_LEVEL_FATAL causes program exit */
2239    }
2240
2241    /* build the http request to send to the server
2242     * we have to do one of the following:
2243     *
2244     * create = use the original HTTP request to create a new
2245     *          HTTP request that has either the path component
2246     *          without the http://domainspec (w/path) or the
2247     *          full orininal URL (w/url)
2248     *          Note that the path and/or the HTTP version may
2249     *          have been altered by now.
2250     *
2251     * connect = Open a socket to the host:port of the server
2252     *           and short-circuit server and client socket.
2253     *
2254     * pass =  Pass the request unchanged if forwarding a CONNECT
2255     *         request to a parent proxy. Note that we'll be sending
2256     *         the CFAIL message ourselves if connecting to the parent
2257     *         fails, but we won't send a CSUCCEED message if it works,
2258     *         since that would result in a double message (ours and the
2259     *         parent's). After sending the request to the parent, we simply
2260     *         tunnel.
2261     *
2262     * here's the matrix:
2263     *                        SSL
2264     *                    0        1
2265     *                +--------+--------+
2266     *                |        |        |
2267     *             0  | create | connect|
2268     *                | w/path |        |
2269     *  Forwarding    +--------+--------+
2270     *                |        |        |
2271     *             1  | create | pass   |
2272     *                | w/url  |        |
2273     *                +--------+--------+
2274     *
2275     */
2276
2277    /*
2278     * Determine the actions for this URL
2279     */
2280 #ifdef FEATURE_TOGGLE
2281    if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
2282    {
2283       /* Most compatible set of actions (i.e. none) */
2284       init_current_action(csp->action);
2285    }
2286    else
2287 #endif /* ndef FEATURE_TOGGLE */
2288    {
2289       url_actions(http, csp);
2290    }
2291
2292
2293
2294
2295
2296    /*
2297     * Downgrade http version from 1.1 to 1.0 if +downgrade
2298     * action applies
2299     */
2300    if ( (http->ssl == 0)
2301      && (!strcmpic(http->ver, "HTTP/1.1"))
2302      && (csp->action->flags & ACTION_DOWNGRADE))
2303    {
2304       freez(http->ver);
2305       http->ver = strdup("HTTP/1.0");
2306
2307       if (http->ver == NULL)
2308       {
2309          log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
2310       }
2311    }
2312
2313    /* 
2314     * Save a copy of the original request for logging
2315     */
2316    http->ocmd = strdup(http->cmd);
2317
2318    if (http->ocmd == NULL)
2319    {
2320       log_error(LOG_LEVEL_FATAL, "Out of memory copying HTTP request line");
2321    }
2322
2323    /*
2324     * (Re)build the HTTP request for non-SSL requests.
2325     * If forwarding, use the whole URL, else, use only the path.
2326     */
2327    if (http->ssl == 0)
2328    {
2329       freez(http->cmd);
2330
2331       http->cmd = strdup(http->gpc);
2332       string_append(&http->cmd, " ");
2333
2334       if (http->fwd->forward_host)
2335       {
2336          string_append(&http->cmd, http->url);
2337       }
2338       else
2339       {
2340          string_append(&http->cmd, http->path);
2341       }
2342
2343       string_append(&http->cmd, " ");
2344       string_append(&http->cmd, http->ver);
2345
2346       if (http->cmd == NULL)
2347       {
2348          log_error(LOG_LEVEL_FATAL, "Out of memory rewiting SSL command");
2349       }
2350    }
2351    enlist_first(csp->headers, http->cmd);
2352
2353
2354    /*
2355     * If the user has not supplied any wafers, and the user has not
2356     * told us to suppress the vanilla wafer, then send the vanilla wafer.
2357     */
2358    if (list_is_empty(csp->action->multi[ACTION_MULTI_WAFER])
2359        && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
2360    {
2361       enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
2362    }
2363
2364    return JB_ERR_OK ;
2365 } /* process_client_headers */
2366
2367 /*********************************************************************
2368  *
2369  * Function    :  intercept_page
2370  *
2371  * Description :  Check whether to intercept page
2372  *
2373  * Parameters  :
2374  *          1  :  client_state structure
2375  *          2  :  http_request structure
2376  *                         
2377  *
2378  * Returns     :  JB_ERR_OK  - Do NOT intercept this page
2379  *             :  JB_ERR_INTERCEPT - intercept this page
2380  *             :  all other values - an error occurred.  
2381  *********************************************************************/
2382 static jb_err intercept_page( struct client_state *csp, struct http_request *http )
2383 {
2384
2385    /* Skeleton for HTTP response, if we should intercept the request */
2386    struct http_response *rsp;
2387
2388
2389 /*
2390  * These next lines are a little ugly, but they simplifies the if statements
2391  * below.  Basically if TOGGLE, then we want the if to test if the
2392  * CSP_FLAG_TOGGLED_ON flag ist set, else we don't.  And if FEATURE_FORCE_LOAD,
2393  * then we want the if to test for CSP_FLAG_FORCED , else we don't
2394  */
2395 #ifdef FEATURE_TOGGLE
2396 #   define IS_TOGGLED_ON_AND (csp->flags & CSP_FLAG_TOGGLED_ON) &&
2397 #else /* ifndef FEATURE_TOGGLE */
2398 #   define IS_TOGGLED_ON_AND
2399 #endif /* ndef FEATURE_TOGGLE */
2400 #ifdef FEATURE_FORCE_LOAD
2401 #   define IS_NOT_FORCED_AND !(csp->flags & CSP_FLAG_FORCED) &&
2402 #else /* ifndef FEATURE_FORCE_LOAD */
2403 #   define IS_NOT_FORCED_AND
2404 #endif /* def FEATURE_FORCE_LOAD */
2405
2406 #define IS_ENABLED_AND   IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
2407
2408    if (
2409        /* a CGI call was detected and answered */
2410        (NULL != (rsp = dispatch_cgi(csp)))
2411
2412        /* or we are enabled and... */
2413        || (IS_ENABLED_AND (
2414
2415             /* ..the request was blocked */
2416           ( NULL != (rsp = block_url(csp)))
2417
2418           /* ..or untrusted */
2419 #ifdef FEATURE_TRUST
2420           || ( NULL != (rsp = trust_url(csp)))
2421 #endif /* def FEATURE_TRUST */
2422
2423           /* ..or a fast redirect kicked in */
2424 #ifdef FEATURE_FAST_REDIRECTS
2425           || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) &&
2426                 (NULL != (rsp = redirect_url(csp))))
2427 #endif /* def FEATURE_FAST_REDIRECTS */
2428           ))
2429       )
2430    {
2431       /* Write the answer to the client */
2432       if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2433        || write_socket(csp->cfd, rsp->body, rsp->content_length))
2434       {
2435          log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2436       }
2437
2438 #ifdef FEATURE_STATISTICS
2439       /* Count as a rejected request */
2440       csp->flags |= CSP_FLAG_REJECTED;
2441 #endif /* def FEATURE_STATISTICS */
2442
2443       /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
2444       log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
2445       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->ocmd);
2446
2447       /* Clean up and return */
2448       free_http_response(rsp);
2449       return JB_ERR_INTERCEPT;
2450    }
2451
2452    /* When we get here the request doesn't need to be intercepted */
2453    return JB_ERR_OK ;
2454 }
2455
2456 /*********************************************************************
2457  *
2458  * Function    :  open_forwarding_connection
2459  *
2460  * Description :  Check whether to intercept page
2461  *
2462  * Parameters  :
2463  *          1  :  client_state structure
2464  *          2  :  http_request structure
2465  *                         
2466  * Returns     :  JB_ERR_OK  - Connection opened ok
2467  *             :  all other values - an error occurred.  
2468  *********************************************************************/
2469 static jb_err open_forwarding_connection(struct client_state *csp )
2470 {
2471    struct http_response *rsp;
2472    
2473 #ifdef FEATURE_ACTIVITY_CONSOLE
2474    accumulate_stats(STATS_REQUEST, 1);
2475 #endif /* def FEATURE_ACTIVITY_CONSOLE */
2476    log_error(LOG_LEVEL_GPC, "%s%s", csp->http->hostport, csp->http->path);
2477
2478    if (csp->http->fwd->forward_host)
2479    {
2480       log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
2481                csp->http->fwd->forward_host, csp->http->fwd->forward_port, 
2482                csp->http->hostport);
2483    }
2484    else
2485    {
2486       log_error(LOG_LEVEL_CONNECT, "to %s", csp->http->hostport);
2487    }
2488
2489    /* here we connect to the server, gateway, or the forwarder */
2490
2491    csp->sfd = forwarded_connect(csp->http->fwd, csp->http, csp);
2492
2493    if (csp->sfd == JB_INVALID_SOCKET)
2494    {
2495       log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
2496                 csp->http->hostport);
2497
2498       if (errno == EINVAL)
2499       {
2500          rsp = error_response(csp, "no-such-domain", errno);
2501
2502          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0",
2503                    csp->ip_addr_str, csp->http->ocmd);
2504       }
2505       else
2506       {
2507          rsp = error_response(csp, "connect-failed", errno);
2508
2509          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
2510                    csp->ip_addr_str, csp->http->ocmd);
2511       }
2512
2513
2514       /* Write the answer to the client */
2515       if(rsp)
2516       {
2517          if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2518           || write_socket(csp->cfd, rsp->body, rsp->content_length))
2519          {
2520             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", csp->http->host);
2521          }
2522       }
2523
2524       free_http_response(rsp);
2525       return JB_ERR_GENERIC;
2526    }
2527
2528    log_error(LOG_LEVEL_CONNECT, "OK");
2529    return JB_ERR_OK ;
2530
2531 } /* END open_forwarding_connection() */
2532
2533
2534 /*********************************************************************
2535  *
2536  * Function    :  send_client_headers_to_server
2537  *
2538  * Description :  send the client headers (possibly modified) to the server
2539  *
2540  * Parameters  :
2541  *          1  :  client_state structure
2542  *          2  :  http_request structure
2543  *                         
2544  *
2545  * Returns     :  JB_ERR_OK  - headers sent ok
2546  *             :  other values - an error occurred.
2547  *********************************************************************/
2548
2549 static jb_err send_client_headers_to_server( struct client_state *csp, struct http_request *http, char *hdr )
2550 {
2551
2552    struct http_response *rsp;
2553
2554    if (http->fwd->forward_host || (http->ssl == 0))
2555    {
2556       /* write the client's (modified) header to the server
2557        * (along with anything else that may be in the buffer)
2558        */
2559
2560       if (write_socket(csp->sfd, hdr, strlen(hdr))
2561        || (flush_socket(csp->sfd, csp) <  0))
2562       {
2563          log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
2564                     http->hostport);
2565
2566          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0",
2567                    csp->ip_addr_str, http->ocmd);
2568
2569          rsp = error_response(csp, "connect-failed", errno);
2570
2571          if(rsp)
2572          {
2573             if (write_socket(csp->cfd, rsp->head, rsp->head_length)
2574              || write_socket(csp->cfd, rsp->body, rsp->content_length))
2575             {
2576                log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2577             }
2578          }
2579
2580          free_http_response(rsp);
2581          return JB_ERR_GENERIC;
2582       }
2583    }
2584    else
2585    {
2586       /*
2587        * We're running an SSL tunnel and we're not forwarding,
2588        * so just send the "connect succeeded" message to the
2589        * client, flush the rest, and get out of the way.
2590        */
2591       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n",
2592                 csp->ip_addr_str, http->ocmd);
2593
2594       if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1))
2595       {
2596          return JB_ERR_OK;
2597       }
2598       IOB_RESET(csp);
2599    }
2600
2601    return JB_ERR_OK ;
2602 } /* END send_client_headers_to_server */
2603
2604
2605 /*********************************************************************
2606  *
2607  * Function    :  is_connect_request_allowed
2608  *
2609  * Description :  send the client headers (possibly modified) to the server
2610  *
2611  * Parameters  :
2612  *          1  :  client_state structure
2613  *
2614  *                         
2615  *
2616  * Returns     :  JB_ERR_OK  - connect request allowed
2617  *             :  other values - connect request not allowed
2618  *********************************************************************/
2619 static jb_err is_connect_request_allowed( struct client_state *csp )
2620 {
2621    /*
2622     * Check if a CONNECT request is allowable:
2623     * In the absence of a +limit-connect action, allow only port 443.
2624     * If there is an action, allow whatever matches the specificaton.
2625     */
2626
2627    if(csp->http->ssl)
2628    {
2629       if(  ( !(csp->action->flags & ACTION_LIMIT_CONNECT) && csp->http->port != 443)
2630            || (csp->action->flags & ACTION_LIMIT_CONNECT
2631               && !match_portlist(csp->action->string[ACTION_STRING_LIMIT_CONNECT], csp->http->port)) )
2632       {
2633          char buf[BUFFER_SIZE];
2634          strcpy(buf, CFORBIDDEN);
2635          write_socket(csp->cfd, buf, strlen(buf));
2636
2637          log_error(LOG_LEVEL_CONNECT, "Denying suspicious CONNECT request from %s", csp->ip_addr_str);
2638          log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 403 0", csp->ip_addr_str);
2639
2640          return JB_ERR_GENERIC;
2641       }
2642    }
2643
2644    return JB_ERR_OK ;
2645 } /* END is_connect_request_allowed */
2646
2647 /*
2648   Local Variables:
2649   tab-width: 3
2650   end:
2651 */