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