Fixed a typo
[privoxy.git] / jcc.c
1 const char jcc_rcs[] = "$Id: jcc.c,v 1.25 2001/07/15 19:43:49 jongfoster 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  *                IJBSWA team.  http://ijbswa.sourceforge.net
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.25  2001/07/15 19:43:49  jongfoster
37  *    Supports POSIX threads.
38  *    Also removed some unused #includes.
39  *
40  *    Revision 1.24  2001/07/13 14:00:40  oes
41  *     - Generic content modification scheme:
42  *       Each feature has its own applicability flag that is set
43  *       from csp->action->flags.
44  *       Replaced the "filtering" int flag , by a function pointer
45  *       "content_filter" to the function that will do the content
46  *       modification. If it is != NULL, the document will be buffered
47  *       and processed through *content_filter, which must set
48  *       csp->content_length and return a modified copy of the body
49  *       or return NULL (on failiure).
50  *     - Changed csp->is_text to the more generic bitmap csp->content_type
51  *       which can currently take the valued CT_TEXT or CT_GIF
52  *     - Reformatting etc
53  *     - Removed all #ifdef PCRS
54  *
55  *    Revision 1.23  2001/07/02 02:28:25  iwanttokeepanon
56  *    Added "#ifdef ACL_FILES" conditional compilation to line 1291 to exclude
57  *    the `block_acl' call.  This prevents a compilation error when the user
58  *    does not wish to use the "ACL" feature.
59  *
60  *    Revision 1.22  2001/06/29 21:45:41  oes
61  *    Indentation, CRLF->LF, Tab-> Space
62  *
63  *    Revision 1.21  2001/06/29 13:29:36  oes
64  *    - Cleaned up, improved comments
65  *    - Unified all possible interceptors (CGI,
66  *      block, trust, fast_redirect) in one
67  *      place, with one (CGI) answer generation
68  *      mechansim. Much clearer now.
69  *    - Removed the GIF image generation, which
70  *      is now done in filters.c:block_url()
71  *    - Made error conditions like domain lookup
72  *      failiure or (various) problems while talking
73  *      to the server use cgi.c:error_response()
74  *      instead of generating HTML/HTTP in chat() (yuck!)
75  *    - Removed logentry from cancelled commit
76  *
77  *    Revision 1.20  2001/06/09 10:55:28  jongfoster
78  *    Changing BUFSIZ ==> BUFFER_SIZE
79  *
80  *    Revision 1.19  2001/06/07 23:12:52  jongfoster
81  *    Replacing function pointer in struct gateway with a directly
82  *    called function forwarded_connect().
83  *    Replacing struct gateway with struct forward_spec
84  *
85  *    Revision 1.18  2001/06/03 19:12:16  oes
86  *    introduced new cgi handling
87  *
88  *    Revision 1.17  2001/06/01 20:07:23  jongfoster
89  *    Now uses action +image-blocker{} rather than config->tinygif
90  *
91  *    Revision 1.16  2001/06/01 18:49:17  jongfoster
92  *    Replaced "list_share" with "list" - the tiny memory gain was not
93  *    worth the extra complexity.
94  *
95  *    Revision 1.15  2001/05/31 21:24:47  jongfoster
96  *    Changed "permission" to "action" throughout.
97  *    Removed DEFAULT_USER_AGENT - it must now be specified manually.
98  *    Moved vanilla wafer check into chat(), since we must now
99  *    decide whether or not to add it based on the URL.
100  *
101  *    Revision 1.14  2001/05/29 20:14:01  joergs
102  *    AmigaOS bugfix: PCRS needs a lot of stack, stacksize for child threads
103  *    increased.
104  *
105  *    Revision 1.13  2001/05/29 09:50:24  jongfoster
106  *    Unified blocklist/imagelist/permissionslist.
107  *    File format is still under discussion, but the internal changes
108  *    are (mostly) done.
109  *
110  *    Also modified interceptor behaviour:
111  *    - We now intercept all URLs beginning with one of the following
112  *      prefixes (and *only* these prefixes):
113  *        * http://i.j.b/
114  *        * http://ijbswa.sf.net/config/
115  *        * http://ijbswa.sourceforge.net/config/
116  *    - New interceptors "home page" - go to http://i.j.b/ to see it.
117  *    - Internal changes so that intercepted and fast redirect pages
118  *      are not replaced with an image.
119  *    - Interceptors now have the option to send a binary page direct
120  *      to the client. (i.e. ijb-send-banner uses this)
121  *    - Implemented show-url-info interceptor.  (Which is why I needed
122  *      the above interceptors changes - a typical URL is
123  *      "http://i.j.b/show-url-info?url=www.somesite.com/banner.gif".
124  *      The previous mechanism would not have intercepted that, and
125  *      if it had been intercepted then it then it would have replaced
126  *      it with an image.)
127  *
128  *    Revision 1.12  2001/05/27 22:17:04  oes
129  *
130  *    - re_process_buffer no longer writes the modified buffer
131  *      to the client, which was very ugly. It now returns the
132  *      buffer, which it is then written by chat.
133  *
134  *    - content_length now adjusts the Content-Length: header
135  *      for modified documents rather than crunch()ing it.
136  *      (Length info in csp->content_length, which is 0 for
137  *      unmodified documents)
138  *
139  *    - For this to work, sed() is called twice when filtering.
140  *
141  *    Revision 1.11  2001/05/26 17:27:53  jongfoster
142  *    Added support for CLF and fixed LOG_LEVEL_LOG.
143  *    Also did CRLF->LF fix of my previous patch.
144  *
145  *    Revision 1.10  2001/05/26 15:26:15  jongfoster
146  *    ACL feature now provides more security by immediately dropping
147  *    connections from untrusted hosts.
148  *
149  *    Revision 1.9  2001/05/26 00:28:36  jongfoster
150  *    Automatic reloading of config file.
151  *    Removed obsolete SIGHUP support (Unix) and Reload menu option (Win32).
152  *    Most of the global variables have been moved to a new
153  *    struct configuration_spec, accessed through csp->config->globalname
154  *    Most of the globals remaining are used by the Win32 GUI.
155  *
156  *    Revision 1.8  2001/05/25 22:43:18  jongfoster
157  *    Fixing minor memory leak and buffer overflow.
158  *
159  *    Revision 1.7  2001/05/25 22:34:30  jongfoster
160  *    Hard tabs->Spaces
161  *
162  *    Revision 1.6  2001/05/23 00:13:58  joergs
163  *    AmigaOS support fixed.
164  *
165  *    Revision 1.5  2001/05/22 18:46:04  oes
166  *
167  *    - Enabled filtering banners by size rather than URL
168  *      by adding patterns that replace all standard banner
169  *      sizes with the "Junkbuster" gif to the re_filterfile
170  *
171  *    - Enabled filtering WebBugs by providing a pattern
172  *      which kills all 1x1 images
173  *
174  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
175  *      which is selected by the (nonstandard and therefore
176  *      capital) letter 'U' in the option string.
177  *      It causes the quantifiers to be ungreedy by default.
178  *      Appending a ? turns back to greedy (!).
179  *
180  *    - Added a new interceptor ijb-send-banner, which
181  *      sends back the "Junkbuster" gif. Without imagelist or
182  *      MSIE detection support, or if tinygif = 1, or the
183  *      URL isn't recognized as an imageurl, a lame HTML
184  *      explanation is sent instead.
185  *
186  *    - Added new feature, which permits blocking remote
187  *      script redirects and firing back a local redirect
188  *      to the browser.
189  *      The feature is conditionally compiled, i.e. it
190  *      can be disabled with --disable-fast-redirects,
191  *      plus it must be activated by a "fast-redirects"
192  *      line in the config file, has its own log level
193  *      and of course wants to be displayed by show-proxy-args
194  *      Note: Boy, all the #ifdefs in 1001 locations and
195  *      all the fumbling with configure.in and acconfig.h
196  *      were *way* more work than the feature itself :-(
197  *
198  *    - Because a generic redirect template was needed for
199  *      this, tinygif = 3 now uses the same.
200  *
201  *    - Moved GIFs, and other static HTTP response templates
202  *      to project.h
203  *
204  *    - Some minor fixes
205  *
206  *    - Removed some >400 CRs again (Jon, you really worked
207  *      a lot! ;-)
208  *
209  *    Revision 1.4  2001/05/21 19:34:01  jongfoster
210  *    Made failure to bind() a fatal error.
211  *
212  *    Revision 1.3  2001/05/20 01:21:20  jongfoster
213  *    Version 2.9.4 checkin.
214  *    - Merged popupfile and cookiefile, and added control over PCRS
215  *      filtering, in new "permissionsfile".
216  *    - Implemented LOG_LEVEL_FATAL, so that if there is a configuration
217  *      file error you now get a message box (in the Win32 GUI) rather
218  *      than the program exiting with no explanation.
219  *    - Made killpopup use the PCRS MIME-type checking and HTTP-header
220  *      skipping.
221  *    - Removed tabs from "config"
222  *    - Moved duplicated url parsing code in "loaders.c" to a new funcition.
223  *    - Bumped up version number.
224  *
225  *    Revision 1.2  2001/05/17 22:34:44  oes
226  *     - Added hint on GIF char array generation to jcc.c
227  *     - Cleaned CRLF's from the sources and related files
228  *     - Repaired logging for REF and FRC
229  *
230  *    Revision 1.1.1.1  2001/05/15 13:58:56  oes
231  *    Initial import of version 2.9.3 source tree
232  *
233  *
234  *********************************************************************/
235 \f
236
237 #include "config.h"
238
239 #include <stdio.h>
240 #include <sys/types.h>
241 #include <stdlib.h>
242 #include <string.h>
243 #include <signal.h>
244 #include <fcntl.h>
245 #include <errno.h>
246
247 #ifdef FEATURE_PTHREAD
248 #include <pthread.h>
249 #endif /* def FEATURE_PTHREAD */
250
251 #ifdef _WIN32
252 # ifndef FEATURE_PTHREAD
253 #  include <windows.h>
254 #  include <process.h>
255 # endif /* ndef FEATURE_PTHREAD */
256
257 # include "win32.h"
258 # ifndef _WIN_CONSOLE
259 #  include "w32log.h"
260 # endif /* ndef _WIN_CONSOLE */
261
262 #else /* ifndef _WIN32 */
263
264 # include <unistd.h>
265 # include <sys/time.h>
266 # include <sys/wait.h>
267 # include <sys/stat.h>
268 # include <signal.h>
269
270 # ifdef __BEOS__
271 #  include <socket.h>  /* BeOS has select() for sockets only. */
272 #  include <OS.h>      /* declarations for threads and stuff. */
273 # endif
274
275 # ifndef FD_ZERO
276 #  include <select.h>
277 # endif
278
279 #endif
280
281 #include "project.h"
282 #include "list.h"
283 #include "jcc.h"
284 #include "filters.h"
285 #include "loaders.h"
286 #include "showargs.h"
287 #include "parsers.h"
288 #include "killpopup.h"
289 #include "miscutil.h"
290 #include "errlog.h"
291 #include "jbsockets.h"
292 #include "gateway.h"
293 #include "actions.h"
294 #include "cgi.h"
295
296 const char jcc_h_rcs[] = JCC_H_VERSION;
297 const char project_h_rcs[] = PROJECT_H_VERSION;
298
299 struct client_state  clients[1];
300 struct file_list     files[1];
301
302 #ifdef STATISTICS
303 int urls_read     = 0;     /* total nr of urls read inc rejected */
304 int urls_rejected = 0;     /* total nr of urls rejected */
305 #endif /* def STATISTICS */
306
307
308 static void listen_loop(void);
309 static void chat(struct client_state *csp);
310 #ifdef AMIGA
311 void serve(struct client_state *csp);
312 #else /* ifndef AMIGA */
313 static void serve(struct client_state *csp);
314 #endif /* def AMIGA */
315
316 #ifdef __BEOS__
317 static int32 server_thread(void *data);
318 #endif /* def __BEOS__ */
319
320 #ifdef _WIN32
321 #define sleep(N)  Sleep(((N) * 1000))
322 #endif
323
324
325 /* The vanilla wafer. */
326 static const char VANILLA_WAFER[] =
327    "NOTICE=TO_WHOM_IT_MAY_CONCERN_"
328    "Do_not_send_me_any_copyrighted_information_other_than_the_"
329    "document_that_I_am_requesting_or_any_of_its_necessary_components._"
330    "In_particular_do_not_send_me_any_cookies_that_"
331    "are_subject_to_a_claim_of_copyright_by_anybody._"
332    "Take_notice_that_I_refuse_to_be_bound_by_any_license_condition_"
333    "(copyright_or_otherwise)_applying_to_any_cookie._";
334
335
336 /*********************************************************************
337  *
338  * Function    :  chat
339  *
340  * Description :  Once a connection to the client has been accepted,
341  *                this function is called (via serve()) to handle the
342  *                main business of the communication.  When this 
343  *                function returns, the caller must close the client
344  *                socket handle.
345  *
346  * Parameters  :
347  *          1  :  csp = Current client state (buffers, headers, etc...)
348  *
349  * Returns     :  On success, the number of bytes written are returned (zero
350  *                indicates nothing was written).  On error, -1 is returned,
351  *                and errno is set appropriately.  If count is zero and the
352  *                file descriptor refers to a regular file, 0 will be
353  *                returned without causing any other effect.  For a special
354  *                file, the results are not portable.
355  *
356  *********************************************************************/
357 static void chat(struct client_state *csp)
358 {
359 /*
360  * This next lines are a little ugly, but they simplifies the if statements below.
361  * Basically if TOGGLE, then we want the if to test "csp->toggled_on", else we don't
362  * And if FORCE_LOAD, then we want the if to test "csp->toggled_on", else we don't
363  */
364 #ifdef TOGGLE
365 #   define IS_TOGGLED_ON_AND (csp->toggled_on) &&
366 #else /* ifndef TOGGLE */
367 #   define IS_TOGGLED_ON_AND
368 #endif /* ndef TOGGLE */
369 #ifdef FORCE_LOAD
370 #   define IS_NOT_FORCED_AND (!csp->force) && 
371 #else /* ifndef FORCE_LOAD */
372 #   define IS_NOT_FORCED_AND
373 #endif /* def FORCE_LOAD */
374
375 #define IS_ENABLED_AND   IS_TOGGLED_ON_AND IS_NOT_FORCED_AND
376
377    char buf[BUFFER_SIZE];
378    char *hdr, *p, *req;
379    char *err = NULL;
380    fd_set rfds;
381    int n, maxfd, server_body;
382    int ms_iis5_hack = 0;
383    int byte_count = 0;
384    const struct forward_spec * fwd;
385    struct http_request *http;
386 #ifdef KILLPOPUPS
387    int block_popups;         /* bool, 1==will block popups */
388    int block_popups_now = 0; /* bool, 1==currently blocking popups */
389 #endif /* def KILLPOPUPS */
390
391    int pcrs_filter;        /* bool, 1==will filter through pcrs */
392    int gif_deanimate;      /* bool, 1==will deanimate gifs */
393
394    /* Function that does the content filtering for the current request */
395    char *(*content_filter)() = NULL; 
396
397    /* Skeleton for HTTP response, if we should intercept the request */
398    struct http_response *rsp;
399
400    http = csp->http;
401
402    /*
403     * Read the client's request.  Note that since we're not using select() we
404     * could get blocked here if a client connected, then didn't say anything!
405     */
406
407    while (FOREVER)
408    {
409       n = read_socket(csp->cfd, buf, sizeof(buf));
410
411       if (n <= 0) break;      /* error! */
412
413       add_to_iob(csp, buf, n);
414
415       req = get_header(csp);
416
417       if (req == NULL)
418       {
419          break;    /* no HTTP request! */
420       }
421
422       if (*req == '\0')
423       {
424          continue;   /* more to come! */
425       }
426  
427 #ifdef FORCE_LOAD
428       /* If this request contains the FORCE_PREFIX,
429        * better get rid of it now and set the force flag --oes
430        */
431
432       if (strstr(req, FORCE_PREFIX))
433       {
434          strclean(req, FORCE_PREFIX);
435          log_error(LOG_LEVEL_FORCE, "Enforcing request \"%s\".\n", req);
436          csp->force = 1;
437       } 
438       else
439       {
440          csp->force = 0;
441       }
442 #endif /* def FORCE_LOAD */
443   
444       parse_http_request(req, http, csp);
445       freez(req);
446       break;
447    }
448
449    if (http->cmd == NULL)
450    {
451       strcpy(buf, CHEADER);
452       write_socket(csp->cfd, buf, strlen(buf));
453
454       log_error(LOG_LEVEL_CLF, "%s - - [%T] \" \" 400 0", csp->ip_addr_str);
455
456       return;
457    }
458
459    /* decide how to route the HTTP request */
460
461    if ((fwd = forward_url(http, csp)) == NULL)
462    {
463       log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!?  This can't happen!");
464       /* Never get here - LOG_LEVEL_FATAL causes program exit */
465    }
466
467    /* build the http request to send to the server
468     * we have to do one of the following:
469     *
470     * create = use the original HTTP request to create a new
471     *          HTTP request that has only the path component
472     *          without the http://domainspec
473     * pass   = pass the original HTTP request unchanged
474     *
475     * drop   = drop the HTTP request
476     *
477     * here's the matrix:
478     *                        SSL
479     *                    0        1
480     *                +--------+--------+
481     *                |        |        |
482     *             0  | create | drop   |
483     *                |        |        |
484     *  Forwarding    +--------+--------+
485     *                |        |        |
486     *             1  | pass   | pass   |
487     *                |        |        |
488     *                +--------+--------+
489     *
490     */
491
492    if (fwd->forward_host)
493    {
494       /* if forwarding, just pass the request as is */
495       enlist(csp->headers, http->cmd);
496    }
497    else
498    {
499       if (http->ssl == 0)
500       {
501          /* otherwise elide the host information from the url */
502          p = NULL;
503          p = strsav(p, http->gpc);
504          p = strsav(p, " ");
505          p = strsav(p, http->path);
506          p = strsav(p, " ");
507          p = strsav(p, http->ver);
508          enlist(csp->headers, p);
509          freez(p);
510       }
511    }
512
513    /* decide what we're to do with cookies */
514
515 #ifdef TOGGLE
516    if (!csp->toggled_on)
517    {
518       /* Most compatible set of actions (i.e. none) */
519       init_current_action(csp->action);
520    }
521    else
522 #endif /* ndef TOGGLE */
523    {
524       url_actions(http, csp);
525    }
526
527 #ifdef JAR_FILES
528    /*
529     * If we're logging cookies in a cookie jar, and the user has not
530     * supplied any wafers, and the user has not told us to suppress the
531     * vanilla wafer, then send the vanilla wafer.
532     */
533    if ((csp->config->jarfile != NULL)
534        && (csp->action->multi[ACTION_MULTI_WAFER]->next == NULL)
535        && ((csp->action->flags & ACTION_VANILLA_WAFER) != 0))
536    {
537       enlist(csp->action->multi[ACTION_MULTI_WAFER], VANILLA_WAFER);
538    }
539 #endif /* def JAR_FILES */
540
541 #ifdef KILLPOPUPS
542    block_popups               = ((csp->action->flags & ACTION_NO_POPUPS) != 0);
543 #endif /* def KILLPOPUPS */
544
545    pcrs_filter                = (csp->rlist != NULL) &&  /* There are expressions to be used */
546                                 ((csp->action->flags & ACTION_FILTER) != 0);
547
548    gif_deanimate              = ((csp->action->flags & ACTION_DEANIMATE) != 0);
549
550    /* grab the rest of the client's headers */
551
552    while (FOREVER)
553    {
554       if ( ( p = get_header(csp) ) && ( *p == '\0' ) )
555       {
556          n = read_socket(csp->cfd, buf, sizeof(buf));
557          if (n <= 0)
558          {
559             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
560             return;
561          }
562          add_to_iob(csp, buf, n);
563          continue;
564       }
565
566       if (p == NULL) break;
567
568       enlist(csp->headers, p);
569       freez(p);
570    }
571
572    /* We have a request. */
573
574    hdr = sed(client_patterns, add_client_headers, csp);
575    destroy_list(csp->headers);
576
577    /* 
578     * Now, check to see if we need to intercept it, i.e.
579     * If
580     */
581  
582    if (
583        /* a CGI call was detected and answered */
584          (NULL != (rsp = dispatch_cgi(csp))) 
585
586        /* or we are enabled and... */
587        || (IS_ENABLED_AND (
588
589             /* ..the request was blocked */
590             ( NULL != (rsp = block_url(csp)))
591
592           /* ..or untrusted */
593 #ifdef TRUST_FILES
594           || ( NULL != (rsp = trust_url(csp)))
595 #endif 
596
597           /* ..or a fast redirect kicked in */
598 #ifdef FAST_REDIRECTS
599           || (((csp->action->flags & ACTION_FAST_REDIRECTS) != 0) && 
600                      (NULL != (rsp = redirect_url(csp))))
601 #endif /* def FAST_REDIRECTS */
602                  ))
603         )
604    {
605       /* Write the answer to the client */
606       if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
607              || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
608       { 
609          log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
610       }
611
612 #ifdef STATISTICS
613       /* Count as a rejected request */
614       csp->rejected = 1;
615 #endif /* def STATISTICS */
616
617       /* Log (FIXME: All intercept reasons apprear as "crunch" with Status 200) */
618       log_error(LOG_LEVEL_GPC, "%s%s crunch!", http->hostport, http->path);
619       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 3", csp->ip_addr_str, http->cmd); 
620
621       /* Clean up and return */
622       free_http_response(rsp);
623       freez(hdr);
624       return;
625    }
626
627    log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
628
629    if (fwd->forward_host)
630    {
631       log_error(LOG_LEVEL_CONNECT, "via %s:%d to: %s",
632                fwd->forward_host, fwd->forward_port, http->hostport);
633    }
634    else
635    {
636       log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
637    }
638
639    /* here we connect to the server, gateway, or the forwarder */
640
641    csp->sfd = forwarded_connect(fwd, http, csp);
642
643    if (csp->sfd < 0)
644    {
645       log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
646                 http->hostport);
647
648       if (errno == EINVAL)
649       {
650            rsp = error_response(csp, "no-such-domain", errno);
651
652          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 404 0", 
653                    csp->ip_addr_str, http->cmd);
654       }
655       else
656       {
657            rsp = error_response(csp, "connect-failed", errno);
658
659          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0", 
660                    csp->ip_addr_str, http->cmd);
661       }
662
663       /* Write the answer to the client */
664       if(rsp)
665         {
666          if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
667                 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
668          { 
669             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
670          }
671       }
672
673       free_http_response(rsp);
674       freez(hdr);
675       return;
676    }
677
678    log_error(LOG_LEVEL_CONNECT, "OK");
679
680    if (fwd->forward_host || (http->ssl == 0))
681    {
682       /* write the client's (modified) header to the server
683        * (along with anything else that may be in the buffer)
684        */
685
686       n = strlen(hdr);
687
688       if ((write_socket(csp->sfd, hdr, n) != n)
689           || (flush_socket(csp->sfd, csp   ) <  0))
690       {
691          log_error(LOG_LEVEL_CONNECT, "write header to: %s failed: %E",
692                     http->hostport);
693
694          log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0", 
695                    csp->ip_addr_str, http->cmd); 
696
697          rsp = error_response(csp, "connect-failed", errno);
698
699          if(rsp)
700          {
701             if ((write_socket(csp->cfd, rsp->head, n) != n)
702                 || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
703             { 
704                log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
705             }
706          }
707
708          free_http_response(rsp);
709          freez(hdr);
710          return;
711       }
712    }
713    else
714    {
715       /*
716        * We're running an SSL tunnel and we're not forwarding,
717        * so just send the "connect succeeded" message to the
718        * client, flush the rest, and get out of the way.
719        */
720       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 2\n", 
721                 csp->ip_addr_str, http->cmd); 
722
723       if (write_socket(csp->cfd, CSUCCEED, sizeof(CSUCCEED)-1) < 0)
724       {
725          freez(hdr);
726          return;
727       }
728       IOB_RESET(csp);
729    }
730
731    /* we're finished with the client's header */
732    freez(hdr);
733
734    maxfd = ( csp->cfd > csp->sfd ) ? csp->cfd : csp->sfd;
735
736    /* pass data between the client and server
737     * until one or the other shuts down the connection.
738     */
739
740    server_body = 0;
741
742    while (FOREVER)
743    {
744       FD_ZERO(&rfds);
745
746       FD_SET(csp->cfd, &rfds);
747       FD_SET(csp->sfd, &rfds);
748
749       n = select(maxfd+1, &rfds, NULL, NULL, NULL);
750
751       if (n < 0)
752       {
753          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
754          return;
755       }
756
757       /* this is the body of the browser's request
758        * just read it and write it.
759        */
760
761       if (FD_ISSET(csp->cfd, &rfds))
762       {
763          n = read_socket(csp->cfd, buf, sizeof(buf));
764
765          if (n <= 0)
766          {
767             break; /* "game over, man" */
768          }
769
770          if (write_socket(csp->sfd, buf, n) != n)
771          {
772             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
773             return;
774          }
775          continue;
776       }
777
778       /*
779        * The server wants to talk.  It could be the header or the body.
780        * If `hdr' is null, then it's the header otherwise it's the body.
781        * FIXME: Does `hdr' really mean `host'? No.
782        */
783
784
785       if (FD_ISSET(csp->sfd, &rfds))
786       {
787          fflush( 0 );
788          n = read_socket(csp->sfd, buf, sizeof(buf) - 1);
789
790          if (n < 0)
791          {
792             log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
793
794             log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 503 0", 
795                       csp->ip_addr_str, http->cmd); 
796
797             rsp = error_response(csp, "connect-failed", errno);
798
799             if(rsp)
800             {
801                if ((write_socket(csp->cfd, rsp->head, rsp->head_length) != rsp->head_length)
802                     || (write_socket(csp->cfd, rsp->body, rsp->content_length) != rsp->content_length))
803                { 
804                   log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
805                            }
806                         }
807
808             free_http_response(rsp);
809             return;
810          }
811
812          /* Add a trailing zero.  This lets filter_popups
813           * use string operations.
814           */
815          buf[n] = '\0';
816
817 #ifdef KILLPOPUPS
818          /* Filter the popups on this read. */
819          if (block_popups_now)
820          {
821             filter_popups(buf, n);
822          }
823 #endif /* def KILLPOPUPS */
824
825          /* Normally, this would indicate that we've read
826           * as much as the server has sent us and we can
827           * close the client connection.  However, Microsoft
828           * in its wisdom has released IIS/5 with a bug that
829           * prevents it from sending the trailing \r\n in
830           * a 302 redirect header (and possibly other headers).
831           * To work around this if we've haven't parsed
832           * a full header we'll append a trailing \r\n
833           * and see if this now generates a valid one.
834           *
835           * This hack shouldn't have any impacts.  If we've
836           * already transmitted the header or if this is a
837           * SSL connection, then we won't bother with this
838           * hack.  So we only work on partially received
839           * headers.  If we append a \r\n and this still
840           * doesn't generate a valid header, then we won't
841           * transmit anything to the client.
842           */
843          if (n == 0)
844          {
845             
846             if (server_body || http->ssl)
847             {
848                /*
849                 * If we have been buffering up the document,
850                 * now is the time to apply content modification
851                 * and send the result to the client.
852                 */
853                if (content_filter)
854                {
855                   /*
856                    * If the content filter fails, use the original
857                    * buffer and length.
858                    * (see p != NULL ? p : csp->iob->cur below)
859                    */
860                   if (NULL == (p = (*content_filter)(csp)))
861                   {
862                      csp->content_length = csp->iob->eod - csp->iob->cur;
863                   }
864
865                   hdr = sed(server_patterns, add_server_headers, csp);
866                   n = strlen(hdr);
867
868                   if ((write_socket(csp->cfd, hdr, n) != n)
869                       || (write_socket(csp->cfd, p != NULL ? p : csp->iob->cur, csp->content_length) != csp->content_length))
870                   {
871                      log_error(LOG_LEVEL_CONNECT, "write modified content to client failed: %E");
872                      return;
873                   }
874
875                   freez(hdr);
876                   freez(p);
877                }
878
879                break; /* "game over, man" */
880             }
881
882             /*
883              * This is NOT the body, so 
884              * Let's pretend the server just sent us a blank line.
885              */
886             n = sprintf(buf, "\r\n");
887
888             /*
889              * Now, let the normal header parsing algorithm below do its
890              * job.  If it fails, we'll exit instead of continuing.
891              */
892
893             ms_iis5_hack = 1;
894          }
895
896          /*
897           * If this is an SSL connection or we're in the body
898           * of the server document, just write it to the client,
899           * unless we need to buffer the body for later content-filtering
900           */
901
902          if (server_body || http->ssl)
903          {
904             if (content_filter)
905             {
906                add_to_iob(csp, buf, n); 
907             }
908             else
909             {
910                if (write_socket(csp->cfd, buf, n) != n)
911                {
912                   log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
913                   return;
914                }
915             }
916             byte_count += n;
917             continue;
918          }
919          else
920          {
921             /* we're still looking for the end of the
922              * server's header ... (does that make header
923              * parsing an "out of body experience" ?
924              */
925
926             /* buffer up the data we just read */
927             add_to_iob(csp, buf, n);
928
929             /* get header lines from the iob */
930
931             while ((p = get_header(csp)))
932             {
933                if (*p == '\0')
934                {
935                   /* see following note */
936                   break;
937                }
938                enlist(csp->headers, p);
939                freez(p);
940             }
941
942             /* NOTE: there are no "empty" headers so
943              * if the pointer `p' is not NULL we must
944              * assume that we reached the end of the
945              * buffer before we hit the end of the header.
946              */
947
948             if (p)
949             {
950                if (ms_iis5_hack)
951                {
952                   /* Well, we tried our MS IIS/5
953                    * hack and it didn't work.
954                    * The header is incomplete
955                    * and there isn't anything
956                    * we can do about it.
957                    */
958                   break;
959                }
960                else
961                {
962                   /* Since we have to wait for
963                    * more from the server before
964                    * we can parse the headers
965                    * we just continue here.
966                    */
967                   continue;
968                }
969             }
970
971             /* we have now received the entire header.
972              * filter it and send the result to the client
973              */
974
975             hdr = sed(server_patterns, add_server_headers, csp);
976             n   = strlen(hdr);
977
978             /* write the server's (modified) header to
979              * the client (along with anything else that
980              * may be in the buffer)
981              */
982
983 #ifdef KILLPOPUPS
984             /* Start blocking popups if appropriate. */
985
986             if ((csp->content_type & CT_TEXT) &&  /* It's a text / * MIME-Type */
987                 !http->ssl    &&                  /* We talk plaintext */
988                 block_popups)                     /* Policy allows */
989             {
990                block_popups_now = 1;
991             }
992
993 #endif /* def KILLPOPUPS */
994
995             /* Buffer and pcrs filter this if appropriate. */
996
997             if ((csp->content_type & CT_TEXT) &&  /* It's a text / * MIME-Type */
998                 !http->ssl    &&                  /* We talk plaintext */
999                 pcrs_filter)                      /* Policy allows */
1000             {
1001                content_filter = pcrs_filter_response;
1002             }
1003
1004             /* Buffer and gif_deanimate this if appropriate. */
1005
1006             if ((csp->content_type & CT_GIF)  &&  /* It's a image/gif MIME-Type */
1007                 !http->ssl    &&                  /* We talk plaintext */
1008                 gif_deanimate)                    /* Policy allows */
1009             {
1010                content_filter = gif_deanimate_response;
1011             }
1012
1013
1014             /*
1015              * Only write if we're not buffering for content modification
1016              */
1017             if (!content_filter && ((write_socket(csp->cfd, hdr, n) != n)
1018                 || (n = flush_socket(csp->cfd, csp) < 0)))
1019             {
1020                log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
1021
1022                /* the write failed, so don't bother
1023                 * mentioning it to the client...
1024                 * it probably can't hear us anyway.
1025                 */
1026                freez(hdr);
1027                return;
1028             }
1029
1030             !content_filter && (byte_count += n);
1031
1032             /* we're finished with the server's header */
1033
1034             freez(hdr);
1035             server_body = 1;
1036
1037             /* If this was a MS IIS/5 hack then it means
1038              * the server has already closed the
1039              * connection.  Nothing more to read.  Time
1040              * to bail.
1041              */
1042             if (ms_iis5_hack)
1043             {
1044                break;
1045             }
1046          }
1047          continue;
1048       }
1049
1050       return; /* huh? we should never get here */
1051    }
1052
1053    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %d", 
1054              csp->ip_addr_str, http->cmd, byte_count); 
1055 }
1056
1057
1058 /*********************************************************************
1059  *
1060  * Function    :  serve
1061  *
1062  * Description :  This is little more than chat.  We only "serve" to
1063  *                to close any socket that chat may have opened.
1064  *
1065  * Parameters  :
1066  *          1  :  csp = Current client state (buffers, headers, etc...)
1067  *
1068  * Returns     :  N/A
1069  *
1070  *********************************************************************/
1071 #ifdef AMIGA
1072 void serve(struct client_state *csp)
1073 #else /* ifndef AMIGA */
1074 static void serve(struct client_state *csp)
1075 #endif /* def AMIGA */
1076 {
1077    chat(csp);
1078    close_socket(csp->cfd);
1079
1080    if (csp->sfd >= 0)
1081    {
1082       close_socket(csp->sfd);
1083    }
1084
1085    csp->active = 0;
1086
1087 }
1088
1089
1090 #ifdef __BEOS__
1091 /*********************************************************************
1092  *
1093  * Function    :  server_thread
1094  *
1095  * Description :  We only exist to call `serve' in a threaded environment.
1096  *
1097  * Parameters  :
1098  *          1  :  data = Current client state (buffers, headers, etc...)
1099  *
1100  * Returns     :  Always 0.
1101  *
1102  *********************************************************************/
1103 static int32 server_thread(void *data)
1104 {
1105    serve((struct client_state *) data);
1106    return 0;
1107
1108 }
1109 #endif
1110
1111
1112 /*********************************************************************
1113  *
1114  * Function    :  main
1115  *
1116  * Description :  Load the config file and start the listen loop.
1117  *                This function is a lot more *sane* with the `load_config'
1118  *                and `listen_loop' functions; although it stills does
1119  *                a *little* too much for my taste.
1120  *
1121  * Parameters  :
1122  *          1  :  argc = Number of parameters (including $0).
1123  *          2  :  argv = Array of (char *)'s to the parameters.
1124  *
1125  * Returns     :  1 if : can't open config file, unrecognized directive,
1126  *                stats requested in multi-thread mode, can't open the
1127  *                log file, can't open the jar file, listen port is invalid,
1128  *                any load fails, and can't bind port.
1129  *
1130  *                Else main never returns, the process must be signaled
1131  *                to terminate execution.  Or, on Windows, use the 
1132  *                "File", "Exit" menu option.
1133  *
1134  *********************************************************************/
1135 #ifdef __MINGW32__
1136 int _main(int argc, const char *argv[])
1137 #else
1138 int main(int argc, const char *argv[])
1139 #endif
1140 {
1141    configfile =
1142 #ifdef AMIGA
1143    "AmiTCP:db/junkbuster/config"
1144 #elif !defined(_WIN32)
1145    "config"
1146 #else
1147    "junkbstr.txt"
1148 #endif
1149       ;
1150
1151 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
1152    if ((argc >= 2) && (strcmp(argv[1], "--help")==0))
1153    {
1154       printf("JunkBuster proxy version " VERSION ".\n\n"
1155          "Usage: %s [configfile]\n\n"
1156          "See " HOME_PAGE_URL " for details.\n"
1157          "This program is distributed under the GNU GPL, version 2 or later.\n",
1158          argv[0]);
1159       exit(2);
1160    }
1161    if ((argc >= 2) && (strcmp(argv[1], "--version")==0))
1162    {
1163       printf(VERSION "\n");
1164       exit(2);
1165    }
1166 #endif /* !defined(_WIN32) || defined(_WIN_CONSOLE) */
1167
1168    Argc = argc;
1169    Argv = argv;
1170
1171    if (argc > 1)
1172    {
1173       configfile = argv[1];
1174    }
1175
1176    files->next = NULL;
1177
1178 #ifdef AMIGA
1179    InitAmiga();
1180 #elif defined(_WIN32)
1181    InitWin32();
1182 #endif
1183
1184
1185 #ifndef _WIN32
1186    signal(SIGPIPE, SIG_IGN);
1187    signal(SIGCHLD, SIG_IGN);
1188
1189 #else /* ifdef _WIN32 */
1190 # ifdef _WIN_CONSOLE
1191    /*
1192     * We *are* in a windows console app.
1193     * Print a verbose messages about FAQ's and such
1194     */
1195    printf(win32_blurb);
1196 # endif /* def _WIN_CONSOLE */
1197 #endif /* def _WIN32 */
1198
1199
1200    listen_loop();
1201
1202    /* NOTREACHED */
1203    return(-1);
1204
1205 }
1206
1207
1208 /*********************************************************************
1209  *
1210  * Function    :  listen_loop
1211  *
1212  * Description :  bind the listen port and enter a "FOREVER" listening loop.
1213  *
1214  * Parameters  :  N/A
1215  *
1216  * Returns     :  Never.
1217  *
1218  *********************************************************************/
1219 static void listen_loop(void)
1220 {
1221    struct client_state *csp = NULL;
1222    int bfd;
1223    struct configuration_spec * config;
1224
1225    config = load_config();
1226
1227    log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1228              config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1229
1230    bfd = bind_port(config->haddr, config->hport);
1231
1232    if (bfd < 0)
1233    {
1234       log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1235          "- There may be another junkbuster or some other "
1236          "proxy running on port %d", 
1237          (NULL != config->haddr) ? config->haddr : "INADDR_ANY", 
1238          config->hport, config->hport
1239       );
1240       /* shouldn't get here */
1241       return;
1242    }
1243
1244    config->need_bind = 0;
1245
1246
1247    while (FOREVER)
1248    {
1249 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
1250       while (waitpid(-1, NULL, WNOHANG) > 0)
1251       {
1252          /* zombie children */
1253       }
1254 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
1255       sweep();
1256
1257       if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
1258       {
1259          log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
1260          continue;
1261       }
1262
1263       memset(csp, '\0', sizeof(*csp));
1264
1265       csp->active = 1;
1266       csp->sfd    = -1;
1267
1268       csp->config = config = load_config();
1269
1270       if ( config->need_bind )
1271       {
1272          /*
1273           * Since we were listening to the "old port", we will not see
1274           * a "listen" param change until the next IJB request.  So, at
1275           * least 1 more request must be made for us to find the new
1276           * setting.  I am simply closing the old socket and binding the
1277           * new one.
1278           *
1279           * Which-ever is correct, we will serve 1 more page via the
1280           * old settings.  This should probably be a "show-proxy-args"
1281           * request.  This should not be a so common of an operation
1282           * that this will hurt people's feelings.
1283           */
1284
1285          close_socket(bfd);
1286
1287          log_error(LOG_LEVEL_CONNECT, "bind (%s, %d)",
1288                    config->haddr ? config->haddr : "INADDR_ANY", config->hport);
1289          bfd = bind_port(config->haddr, config->hport);
1290
1291          if (bfd < 0)
1292          {
1293             log_error(LOG_LEVEL_FATAL, "can't bind %s:%d: %E "
1294                "- There may be another junkbuster or some other "
1295                "proxy running on port %d", 
1296                (NULL != config->haddr) ? config->haddr : "INADDR_ANY", 
1297                config->hport, config->hport
1298             );
1299             /* shouldn't get here */
1300             return;
1301          }
1302
1303          config->need_bind = 0;
1304       }
1305
1306       log_error(LOG_LEVEL_CONNECT, "accept connection ... ");
1307
1308       if (!accept_connection(csp, bfd))
1309       {
1310          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
1311
1312 #ifdef AMIGA
1313          if(!childs)
1314          {
1315             exit(1); 
1316          }
1317 #endif
1318          freez(csp);
1319          continue;
1320       }
1321       else
1322       {
1323          log_error(LOG_LEVEL_CONNECT, "OK");
1324       }
1325
1326 #if defined(TOGGLE)
1327       /* by haroon - most of credit to srt19170 */
1328       csp->toggled_on = g_bToggleIJB;
1329 #endif
1330
1331       if (run_loader(csp))
1332       {
1333          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
1334          /* Never get here - LOG_LEVEL_FATAL causes program exit */
1335       }
1336
1337 #ifdef ACL_FILES
1338       if (block_acl(NULL,csp))
1339       {
1340          log_error(LOG_LEVEL_CONNECT, "Connection dropped due to ACL");
1341          close_socket(csp->cfd);
1342          freez(csp);
1343          continue;
1344       }
1345 #endif /* def ACL_FILES */
1346
1347       /* add it to the list of clients */
1348       csp->next = clients->next;
1349       clients->next = csp;
1350
1351       if (config->multi_threaded)
1352       {
1353          int child_id;
1354
1355 /* this is a switch () statment in the C preprocessor - ugh */
1356 #undef SELECTED_ONE_OPTION
1357
1358 /* Use Pthreads in preference to native code */
1359 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
1360 #define SELECTED_ONE_OPTION
1361          {
1362             pthread_t the_thread;
1363             pthread_attr_t attrs;
1364
1365             pthread_attr_init(&attrs);
1366             child_id = (pthread_create(&the_thread, &attrs,
1367                (void*)serve, csp) ? -1 : 0);
1368             pthread_attr_destroy(&attrs);
1369          }
1370 #endif
1371
1372 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
1373 #define SELECTED_ONE_OPTION
1374          child_id = _beginthread(
1375             (void*)serve,
1376             64 * 1024,
1377             csp);
1378 #endif
1379
1380 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
1381 #define SELECTED_ONE_OPTION
1382          {
1383             thread_id tid = spawn_thread
1384                (server_thread, "server", B_NORMAL_PRIORITY, csp);
1385
1386             if ((tid >= 0) && (resume_thread(tid) == B_OK))
1387             {
1388                child_id = (int) tid;
1389             }
1390             else
1391             {
1392                child_id = -1;
1393             }
1394          }
1395 #endif
1396
1397 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
1398 #define SELECTED_ONE_OPTION
1399          csp->cfd = ReleaseSocket(csp->cfd, -1);
1400          if((child_id = (int)CreateNewProcTags(
1401             NP_Entry, (ULONG)server_thread,
1402             NP_Output, Output(),
1403             NP_CloseOutput, FALSE,
1404             NP_Name, (ULONG)"junkbuster child",
1405             NP_StackSize, 200*1024,
1406             TAG_DONE)))
1407          {
1408             childs++;
1409             ((struct Task *)child_id)->tc_UserData = csp;
1410             Signal((struct Task *)child_id, SIGF_SINGLE);
1411             Wait(SIGF_SINGLE);
1412          }
1413 #endif
1414
1415 #if !defined(SELECTED_ONE_OPTION)
1416          child_id = fork();
1417
1418          /* This block is only needed when using fork().
1419           * When using threads, the server thread was
1420           * created and run by the call to _beginthread().
1421           */
1422          if (child_id == 0)   /* child */
1423          {
1424             serve(csp);
1425             _exit(0);
1426
1427          }
1428          else if (child_id > 0) /* parent */
1429          {
1430             /* in a fork()'d environment, the parent's
1431              * copy of the client socket and the CSP
1432              * are not used.
1433              */
1434
1435 #if !defined(_WIN32) && defined(__CYGWIN__)
1436             wait( NULL );
1437 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
1438             close_socket(csp->cfd);
1439             csp->active = 0;
1440          }
1441 #endif
1442
1443 #undef SELECTED_ONE_OPTION
1444 /* end of cpp switch () */
1445
1446          if (child_id < 0) /* failed */
1447          {
1448             char buf[BUFFER_SIZE];
1449
1450             log_error(LOG_LEVEL_ERROR, "can't fork: %E");
1451
1452             sprintf(buf , "JunkBuster: can't fork: errno = %d", errno);
1453
1454             write_socket(csp->cfd, buf, strlen(buf));
1455             close_socket(csp->cfd);
1456             csp->active = 0;
1457             sleep(5);
1458             continue;
1459          }
1460       }
1461       else
1462       {
1463          serve(csp);
1464       }
1465    }
1466    /* NOTREACHED */
1467
1468 }
1469
1470
1471 /*
1472   Local Variables:
1473   tab-width: 3
1474   end:
1475 */