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