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