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