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