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