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