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